numr 0.16.0

Numerical computing and tensor library for Rust, in the role of NumPy: n-dimensional arrays, linear algebra, FFT, statistics and autograd on CPU, CUDA and WebGPU
Documentation
//! Build steps of the correctly rounded CUDA kernels: their nvcc flags and the tables
//! header generated from the Rust table source.

/// The kernel file of `CorrectlyRoundedOps`, which compiles with its own flags.
pub const CORRECTLY_ROUNDED_KERNEL: &str = "correctly_rounded.cu";

/// The one source of the correctly rounded tables, shared with the Rust kernels.
const CORRECTLY_ROUNDED_TABLES: &str = "src/algorithm/correctly_rounded/tables_data.rs";

/// nvcc flags for one kernel file, before the `-gencode` list.
///
/// The correctly rounded kernels must reproduce the CPU bits. They compile without
/// `--use_fast_math`, which would allow approximate division and contraction, and with
/// `--fmad=false`, because nvcc contracts `a * b + c` into an FMA by default. They read
/// the generated tables header from `OUT_DIR`. Every other kernel keeps fast math.
pub fn nvcc_flags(kernel_file: &str, out_dir: &std::path::Path) -> Vec<String> {
    let mut flags = vec!["-fatbin".to_string(), "-O3".to_string()];
    if kernel_file == CORRECTLY_ROUNDED_KERNEL {
        flags.push("--fmad=false".to_string());
        flags.push("--ftz=false".to_string());
        flags.push("-I".to_string());
        flags.push(out_dir.display().to_string());
    } else {
        flags.push("--use_fast_math".to_string());
        flags.push("--ftz=false".to_string());
    }
    flags
}

/// Write `correctly_rounded_tables.cuh` into `OUT_DIR` from [`CORRECTLY_ROUNDED_TABLES`].
///
/// The CUDA kernels read the same tables as the Rust kernels, so the two cannot drift.
pub fn write_correctly_rounded_tables(out_dir: &std::path::Path) {
    println!("cargo:rerun-if-changed={CORRECTLY_ROUNDED_TABLES}");
    let source = std::fs::read_to_string(CORRECTLY_ROUNDED_TABLES).unwrap_or_else(|e| {
        panic!(
            "read {CORRECTLY_ROUNDED_TABLES}: {e}. Restore the file, or regenerate it with \
             scripts/correctly_rounded/port_tables.py"
        )
    });
    let header = render_correctly_rounded_tables(&source).unwrap_or_else(|e| {
        panic!(
            "generate correctly_rounded_tables.cuh from {CORRECTLY_ROUNDED_TABLES}: {e}. \
             Each table must read `pub static NAME: [u64; N] = [` followed by N hex \
             literals and `];`. Regenerate the file with \
             scripts/correctly_rounded/port_tables.py"
        )
    });
    let path = out_dir.join("correctly_rounded_tables.cuh");
    std::fs::write(&path, header).unwrap_or_else(|e| {
        panic!(
            "write {}: {e}. Check that OUT_DIR is writable",
            path.display()
        )
    });
}

/// The CUDA header text for the tables in `source`, or the first parse error.
///
/// Each `pub static NAME: [u64; N]` becomes `__device__ const unsigned long long
/// CR_NAME[N]`. The leading comment block, which carries the provenance and the MIT
/// notice, is kept.
fn render_correctly_rounded_tables(source: &str) -> Result<String, String> {
    let mut out = String::from(
        "// Generated by build.rs from src/algorithm/correctly_rounded/tables_data.rs.\n\
         // Do not edit: change the Rust source instead.\n//\n",
    );
    let mut body = String::new();
    // (name, declared length, values, line of the declaration)
    let mut open: Option<(String, usize, Vec<u64>, usize)> = None;
    let mut tables = 0usize;
    let mut in_preamble = true;
    for (index, line) in source.lines().enumerate() {
        let number = index + 1;
        let text = line.trim();
        if let Some((name, len, values, start)) = open.as_mut() {
            if text == "];" {
                if values.len() != *len {
                    return Err(format!(
                        "table {name} at line {start} declares {len} entries and holds {}",
                        values.len()
                    ));
                }
                body.push_str(&format!(
                    "__device__ const unsigned long long CR_{name}[{len}] = {{\n"
                ));
                for chunk in values.chunks(4) {
                    let row: Vec<String> = chunk.iter().map(|v| format!("0x{v:016x}ULL")).collect();
                    body.push_str(&format!("    {},\n", row.join(", ")));
                }
                body.push_str("};\n\n");
                tables += 1;
                open = None;
                continue;
            }
            for token in text.split(',').map(str::trim).filter(|t| !t.is_empty()) {
                let digits = token
                    .strip_prefix("0x")
                    .ok_or_else(|| format!("line {number}: `{token}` is not a hex literal"))?
                    .replace('_', "");
                let value = u64::from_str_radix(&digits, 16)
                    .map_err(|e| format!("line {number}: `{token}`: {e}"))?;
                values.push(value);
            }
            continue;
        }
        if let Some(rest) = text.strip_prefix("pub static ") {
            in_preamble = false;
            let (name, rest) = rest
                .split_once(": [u64; ")
                .ok_or_else(|| format!("line {number}: `{text}` is not a `[u64; N]` table"))?;
            let len = rest
                .strip_suffix("] = [")
                .ok_or_else(|| format!("line {number}: `{text}` must end with `] = [`"))?
                .parse::<usize>()
                .map_err(|e| format!("line {number}: table length: {e}"))?;
            open = Some((name.to_string(), len, Vec::with_capacity(len), number));
        } else if let Some(doc) = text.strip_prefix("///") {
            body.push_str(&format!("//{doc}\n"));
        } else if text.starts_with("//") {
            if in_preamble {
                out.push_str(text);
                out.push('\n');
            }
        } else if !(text.is_empty() || text == "#[rustfmt::skip]") {
            return Err(format!("line {number}: unexpected `{text}`"));
        }
    }
    if let Some((name, _, _, start)) = open {
        return Err(format!(
            "table {name} at line {start} is not closed by `];`"
        ));
    }
    if tables == 0 {
        return Err("no `pub static` table found".to_string());
    }
    out.push_str("\n#ifndef NUMR_CORRECTLY_ROUNDED_TABLES_CUH\n#define NUMR_CORRECTLY_ROUNDED_TABLES_CUH\n\n");
    out.push_str(&body);
    out.push_str("#endif\n");
    Ok(out)
}