From 36a088e39c2c5f59cd02fb3c50a86f5adf11bfb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emre=20=C3=96cel?= Date: Tue, 24 Nov 2026 18:14:00 +0300 Subject: [PATCH] feat(c_api): add conv2d, softmax, layer_norm, gelu, silu, reshape, transpose and a C/CMake example - c_api.rs / oxideon.h: oxideon_tensor_{gelu,silu,softmax,reshape,transpose, layer_norm,conv2d}; weight/bias arguments are optional (NULL). Errors are reported through oxideon_last_error_message like the existing ops. - tests: results checked against hand-computed values, plus null pointers, bad axes/shapes and wrong-rank input returning NULL instead of panicking - examples/c_embed: minimal C project + CMakeLists.txt that builds the `oxideon` cdylib with cargo and links it (conv2d -> layer_norm -> gelu -> softmax) Safetensors loading and CUDA device selection from the issue are left for follow-ups. Refs #5 Co-Authored-By: Claude Sonnet 5.5 --- crates/oxideon-core/src/c_api.rs | 217 +++++++++++++++++++++++++++++++ examples/c_embed/CMakeLists.txt | 52 ++++++++ examples/c_embed/main.c | 64 +++++++++ include/oxideon.h | 45 +++++++ 4 files changed, 378 insertions(+) create mode 100644 examples/c_embed/CMakeLists.txt create mode 100644 examples/c_embed/main.c diff --git a/crates/oxideon-core/src/c_api.rs b/crates/oxideon-core/src/c_api.rs index e0e0dc4..e1969de 100644 --- a/crates/oxideon-core/src/c_api.rs +++ b/crates/oxideon-core/src/c_api.rs @@ -211,10 +211,227 @@ pub unsafe extern "C" fn oxideon_tensor_relu(x: *const OxideonTensor) -> *mut Ox guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.relu() })) } +/// Elementwise GELU (exact, erf-based). +/// +/// # Safety +/// `x` must be a valid `OxideonTensor` pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn oxideon_tensor_gelu(x: *const OxideonTensor) -> *mut OxideonTensor { + if x.is_null() { + set_err("null operand in oxideon_tensor_gelu"); + return ptr::null_mut(); + } + guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.gelu() })) +} + +/// Elementwise SiLU (swish) `x * sigmoid(x)`. +/// +/// # Safety +/// `x` must be a valid `OxideonTensor` pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn oxideon_tensor_silu(x: *const OxideonTensor) -> *mut OxideonTensor { + if x.is_null() { + set_err("null operand in oxideon_tensor_silu"); + return ptr::null_mut(); + } + guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.silu() })) +} + +/// Softmax along `axis` (negative values count from the last dimension). +/// +/// # Safety +/// `x` must be a valid `OxideonTensor` pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn oxideon_tensor_softmax(x: *const OxideonTensor, axis: i64) -> *mut OxideonTensor { + if x.is_null() { + set_err("null operand in oxideon_tensor_softmax"); + return ptr::null_mut(); + } + guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.softmax(axis as isize) })) +} + +/// Reshapes `x` to `shape[ndim]` (the element count must be unchanged). +/// +/// # Safety +/// `x` must be a valid `OxideonTensor` pointer and `shape` must point to `ndim` valid `usize` values. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn oxideon_tensor_reshape( + x: *const OxideonTensor, + shape: *const usize, + ndim: usize, +) -> *mut OxideonTensor { + if x.is_null() || (ndim > 0 && shape.is_null()) { + set_err("null pointer passed to oxideon_tensor_reshape"); + return ptr::null_mut(); + } + let shp = if ndim == 0 { &[][..] } else { unsafe { std::slice::from_raw_parts(shape, ndim) } }; + guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.reshape(shp) })) +} + +/// Swaps dimensions `dim0` and `dim1` (negative values count from the last dimension). +/// +/// # Safety +/// `x` must be a valid `OxideonTensor` pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn oxideon_tensor_transpose(x: *const OxideonTensor, dim0: i64, dim1: i64) -> *mut OxideonTensor { + if x.is_null() { + set_err("null operand in oxideon_tensor_transpose"); + return ptr::null_mut(); + } + guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.transpose(dim0 as isize, dim1 as isize) })) +} + +/// Layer normalization over the trailing `normalized_ndim` dimensions, whose sizes are `normalized_shape[normalized_ndim]`. +/// `weight` and `bias` are optional (pass NULL to skip them). +/// +/// # Safety +/// `x` must be a valid `OxideonTensor` pointer, `normalized_shape` must point to `normalized_ndim` valid `usize` values, +/// and `weight` / `bias` must each be NULL or a valid `OxideonTensor` pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn oxideon_tensor_layer_norm( + x: *const OxideonTensor, + normalized_shape: *const usize, + normalized_ndim: usize, + weight: *const OxideonTensor, + bias: *const OxideonTensor, + eps: f64, +) -> *mut OxideonTensor { + if x.is_null() || normalized_shape.is_null() || normalized_ndim == 0 { + set_err("null pointer or empty normalized_shape passed to oxideon_tensor_layer_norm"); + return ptr::null_mut(); + } + let shp = unsafe { std::slice::from_raw_parts(normalized_shape, normalized_ndim) }; + let (w, b) = unsafe { (weight.as_ref().map(|t| &t.inner), bias.as_ref().map(|t| &t.inner)) }; + guard(ptr::null_mut(), || boxed(crate::nn::functional_ext::layer_norm(unsafe { &(*x).inner }, shp, w, b, eps))) +} + +/// 2D convolution of `input: [N, C_in, H, W]` with `weight: [C_out, C_in, kH, kW]` and an optional `bias: [C_out]` (NULL to skip). +/// +/// # Safety +/// `input` and `weight` must be valid `OxideonTensor` pointers and `bias` must be NULL or a valid `OxideonTensor` pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn oxideon_tensor_conv2d( + input: *const OxideonTensor, + weight: *const OxideonTensor, + bias: *const OxideonTensor, + stride_h: usize, + stride_w: usize, + pad_h: usize, + pad_w: usize, + dilation_h: usize, + dilation_w: usize, +) -> *mut OxideonTensor { + if input.is_null() || weight.is_null() { + set_err("null operand in oxideon_tensor_conv2d"); + return ptr::null_mut(); + } + let b = unsafe { bias.as_ref().map(|t| &t.inner) }; + guard(ptr::null_mut(), || { + boxed(unsafe { + (*input).inner.conv2d(&(*weight).inner, b, (stride_h, stride_w), (pad_h, pad_w), (dilation_h, dilation_w)) + }) + }) +} + #[cfg(test)] mod tests { use super::*; + unsafe fn make(data: &[f32], shape: &[usize]) -> *mut OxideonTensor { + unsafe { oxideon_tensor_from_f32(data.as_ptr(), data.len(), shape.as_ptr(), shape.len()) } + } + + unsafe fn read(t: *const OxideonTensor) -> Vec { + let mut out = vec![0.0f32; unsafe { oxideon_tensor_numel(t) }]; + assert_eq!(unsafe { oxideon_tensor_copy_f32(t, out.as_mut_ptr(), out.len()) }, 0); + out + } + + fn assert_close(a: &[f32], b: &[f32]) { + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(b) { + assert!((x - y).abs() < 1e-5, "{a:?} vs {b:?}"); + } + } + + #[test] + fn c_api_activations_softmax_and_layer_norm() { + unsafe { + let x = make(&[-1.0, 0.0, 1.0, 2.0], &[2, 2]); + let g = oxideon_tensor_gelu(x); + assert_close(&read(g), &[-0.158_655_26, 0.0, 0.841_344_7, 1.954_499_7]); + let s = oxideon_tensor_silu(x); + assert_close(&read(s), &[-0.268_941_4, 0.0, 0.731_058_6, 1.761_594_2]); + let sm = oxideon_tensor_softmax(x, -1); + assert_close(&read(sm), &[0.268_941_4, 0.731_058_6, 0.268_941_4, 0.731_058_6]); + assert!(oxideon_tensor_softmax(x, 5).is_null(), "out-of-range axis is an error"); + + // layer_norm over the last dim: each row [a, b] -> [-1, 1] (eps = 0), then weight 2 / bias 1 -> [-1, 3] + let w = make(&[2.0, 2.0], &[2]); + let b = make(&[1.0, 1.0], &[2]); + let ln = oxideon_tensor_layer_norm(x, [2usize].as_ptr(), 1, std::ptr::null(), std::ptr::null(), 0.0); + assert_close(&read(ln), &[-1.0, 1.0, -1.0, 1.0]); + let lnwb = oxideon_tensor_layer_norm(x, [2usize].as_ptr(), 1, w, b, 0.0); + assert_close(&read(lnwb), &[-1.0, 3.0, -1.0, 3.0]); + assert!(oxideon_tensor_layer_norm(x, [3usize].as_ptr(), 1, w, b, 1e-5).is_null(), "mismatched normalized_shape"); + assert!(oxideon_tensor_layer_norm(x, std::ptr::null(), 1, w, b, 1e-5).is_null()); + + for t in [x, g, s, sm, w, b, ln, lnwb] { + oxideon_tensor_free(t); + } + } + } + + #[test] + fn c_api_reshape_and_transpose() { + unsafe { + let x = make(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]); + let r = oxideon_tensor_reshape(x, [3usize, 2].as_ptr(), 2); + let mut shp = [0usize; 2]; + assert_eq!(oxideon_tensor_shape(r, shp.as_mut_ptr(), 2), 0); + assert_eq!(shp, [3, 2]); + assert_eq!(read(r), [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]); + assert!(oxideon_tensor_reshape(x, [4usize].as_ptr(), 1).is_null(), "element count must match"); + assert!(oxideon_tensor_reshape(x, std::ptr::null(), 2).is_null()); + + let t = oxideon_tensor_transpose(x, 0, 1); + assert_eq!(oxideon_tensor_shape(t, shp.as_mut_ptr(), 2), 0); + assert_eq!(shp, [3, 2]); + assert_eq!(read(t), [1.0, 4.0, 2.0, 5.0, 3.0, 6.0]); + let t_neg = oxideon_tensor_transpose(x, -1, -2); + assert_eq!(read(t_neg), [1.0, 4.0, 2.0, 5.0, 3.0, 6.0]); + assert!(oxideon_tensor_transpose(x, 0, 7).is_null()); + + for p in [x, r, t, t_neg] { + oxideon_tensor_free(p); + } + } + } + + #[test] + fn c_api_conv2d() { + unsafe { + // 1x1x3x3 input, 1x1x2x2 all-ones kernel, bias 0.5: each output is a 2x2 window sum + 0.5 + let x = make(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], &[1, 1, 3, 3]); + let w = make(&[1.0; 4], &[1, 1, 2, 2]); + let b = make(&[0.5], &[1]); + let y = oxideon_tensor_conv2d(x, w, b, 1, 1, 0, 0, 1, 1); + assert_close(&read(y), &[12.5, 16.5, 24.5, 28.5]); + let y_nb = oxideon_tensor_conv2d(x, w, std::ptr::null(), 1, 1, 0, 0, 1, 1); + assert_close(&read(y_nb), &[12.0, 16.0, 24.0, 28.0]); + // padding 1 grows the output to 4x4 + let y_pad = oxideon_tensor_conv2d(x, w, std::ptr::null(), 1, 1, 1, 1, 1, 1); + assert_eq!(oxideon_tensor_numel(y_pad), 16); + // a 3D input is an error, not a crash + let flat = make(&[1.0; 9], &[3, 3, 1]); + assert!(oxideon_tensor_conv2d(flat, w, std::ptr::null(), 1, 1, 0, 0, 1, 1).is_null()); + assert!(oxideon_tensor_conv2d(std::ptr::null(), w, std::ptr::null(), 1, 1, 0, 0, 1, 1).is_null()); + for p in [x, w, b, y, y_nb, y_pad, flat] { + oxideon_tensor_free(p); + } + } + } + #[test] fn c_api_roundtrip_matmul_and_relu() { let a_data = [1.0f32, -2.0, 3.0, 4.0]; diff --git a/examples/c_embed/CMakeLists.txt b/examples/c_embed/CMakeLists.txt new file mode 100644 index 0000000..0c1479c --- /dev/null +++ b/examples/c_embed/CMakeLists.txt @@ -0,0 +1,52 @@ +# Minimal C project that links the Oxideon C API (`include/oxideon.h`). +# +# cmake -S examples/c_embed -B build/c_embed +# cmake --build build/c_embed --config Release +# ./build/c_embed/c_embed (build/c_embed/Release/c_embed.exe on Windows) +# +# The shared library is built with `cargo build --release -p oxideon` (the facade crate is a `cdylib`, and it +# re-exports the `oxideon_*` C symbols from `oxideon-core`), so a Rust toolchain must be on PATH. +cmake_minimum_required(VERSION 3.15) +project(oxideon_c_embed C) + +set(OXIDEON_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../..") +set(OXIDEON_CARGO_TARGET_DIR "${CMAKE_CURRENT_BINARY_DIR}/cargo-target") +set(OXIDEON_LIB_DIR "${OXIDEON_CARGO_TARGET_DIR}/release") + +find_program(CARGO_EXECUTABLE cargo REQUIRED) + +if(WIN32) + set(OXIDEON_LIB_FILE "${OXIDEON_LIB_DIR}/oxideon.dll") + set(OXIDEON_IMPLIB_FILE "${OXIDEON_LIB_DIR}/oxideon.dll.lib") +elseif(APPLE) + set(OXIDEON_LIB_FILE "${OXIDEON_LIB_DIR}/liboxideon.dylib") +else() + set(OXIDEON_LIB_FILE "${OXIDEON_LIB_DIR}/liboxideon.so") +endif() + +add_custom_target(oxideon_rust ALL + COMMAND "${CARGO_EXECUTABLE}" build --release -p oxideon + --manifest-path "${OXIDEON_ROOT}/Cargo.toml" + --target-dir "${OXIDEON_CARGO_TARGET_DIR}" + COMMENT "Building the Oxideon shared library with cargo" + USES_TERMINAL) + +add_library(oxideon SHARED IMPORTED GLOBAL) +set_target_properties(oxideon PROPERTIES + IMPORTED_LOCATION "${OXIDEON_LIB_FILE}" + INTERFACE_INCLUDE_DIRECTORIES "${OXIDEON_ROOT}/include") +if(WIN32) + set_target_properties(oxideon PROPERTIES IMPORTED_IMPLIB "${OXIDEON_IMPLIB_FILE}") +endif() + +add_executable(c_embed main.c) +add_dependencies(c_embed oxideon_rust) +target_link_libraries(c_embed PRIVATE oxideon) + +if(WIN32) + # the DLL must sit next to the executable + add_custom_command(TARGET c_embed POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${OXIDEON_LIB_FILE}" "$") +else() + set_target_properties(c_embed PROPERTIES BUILD_RPATH "${OXIDEON_LIB_DIR}") +endif() diff --git a/examples/c_embed/main.c b/examples/c_embed/main.c new file mode 100644 index 0000000..bffc525 --- /dev/null +++ b/examples/c_embed/main.c @@ -0,0 +1,64 @@ +/* Minimal C program using the Oxideon C API: a tiny "conv -> layer_norm -> GELU -> softmax" forward pass. */ +#include +#include + +#include "oxideon.h" + +static int check(const void* ptr, const char* what) { + if (ptr != NULL) return 1; + const char* msg = oxideon_last_error_message(); + fprintf(stderr, "%s failed: %s\n", what, msg ? msg : "unknown error"); + return 0; +} + +int main(void) { + /* A 1x1x4x4 "image" and a 2x1x3x3 convolution kernel (output channel 0: 3x3 box blur, channel 1: center tap only). */ + float img[16]; + for (int i = 0; i < 16; ++i) img[i] = (float)((i * i) % 7) / 4.0f; + float kernel[18] = {0}; + for (int i = 0; i < 9; ++i) kernel[i] = 1.0f / 9.0f; + kernel[9 + 4] = 1.0f; + + const size_t img_shape[4] = {1, 1, 4, 4}; + const size_t ker_shape[4] = {2, 1, 3, 3}; + OxideonTensor* x = oxideon_tensor_from_f32(img, 16, img_shape, 4); + OxideonTensor* w = oxideon_tensor_from_f32(kernel, 18, ker_shape, 4); + if (!check(x, "tensor_from_f32(img)") || !check(w, "tensor_from_f32(kernel)")) return 1; + + /* conv2d -> [1, 2, 2, 2] (stride 1, no padding, no bias) */ + OxideonTensor* conv = oxideon_tensor_conv2d(x, w, NULL, 1, 1, 0, 0, 1, 1); + if (!check(conv, "conv2d")) return 1; + + /* flatten to [2, 4], normalize each row, then GELU and softmax along the last axis */ + const size_t flat_shape[2] = {2, 4}; + OxideonTensor* flat = oxideon_tensor_reshape(conv, flat_shape, 2); + const size_t norm_shape[1] = {4}; + OxideonTensor* normed = flat ? oxideon_tensor_layer_norm(flat, norm_shape, 1, NULL, NULL, 1e-5) : NULL; + OxideonTensor* act = normed ? oxideon_tensor_gelu(normed) : NULL; + OxideonTensor* probs = act ? oxideon_tensor_softmax(act, -1) : NULL; + if (!check(probs, "reshape/layer_norm/gelu/softmax")) return 1; + + float out[8]; + if (oxideon_tensor_copy_f32(probs, out, 8) != 0) { + fprintf(stderr, "copy failed: %s\n", oxideon_last_error_message()); + return 1; + } + for (int row = 0; row < 2; ++row) { + printf("row %d:", row); + float sum = 0.0f; + for (int col = 0; col < 4; ++col) { + printf(" %.4f", out[row * 4 + col]); + sum += out[row * 4 + col]; + } + printf(" (sum = %.4f)\n", sum); + } + + oxideon_tensor_free(probs); + oxideon_tensor_free(act); + oxideon_tensor_free(normed); + oxideon_tensor_free(flat); + oxideon_tensor_free(conv); + oxideon_tensor_free(w); + oxideon_tensor_free(x); + return 0; +} diff --git a/include/oxideon.h b/include/oxideon.h index 9fe4f7c..4bc8c88 100644 --- a/include/oxideon.h +++ b/include/oxideon.h @@ -49,6 +49,51 @@ OxideonTensor* oxideon_tensor_matmul( OxideonTensor* oxideon_tensor_relu(const OxideonTensor* x); +/* Elementwise activations. */ +OxideonTensor* oxideon_tensor_gelu(const OxideonTensor* x); +OxideonTensor* oxideon_tensor_silu(const OxideonTensor* x); + +/* Softmax along `axis` (negative axes count from the last dimension). */ +OxideonTensor* oxideon_tensor_softmax(const OxideonTensor* x, int64_t axis); + +/* Reshape to shape[ndim]; the element count must not change. */ +OxideonTensor* oxideon_tensor_reshape( + const OxideonTensor* x, + const size_t* shape, + size_t ndim +); + +/* Swap two dimensions (negative dims count from the last dimension). */ +OxideonTensor* oxideon_tensor_transpose( + const OxideonTensor* x, + int64_t dim0, + int64_t dim1 +); + +/* Layer norm over the trailing `normalized_ndim` dims (sizes in normalized_shape). + * `weight` and `bias` may be NULL. */ +OxideonTensor* oxideon_tensor_layer_norm( + const OxideonTensor* x, + const size_t* normalized_shape, + size_t normalized_ndim, + const OxideonTensor* weight, + const OxideonTensor* bias, + double eps +); + +/* 2D convolution: input [N, C_in, H, W], weight [C_out, C_in, kH, kW], optional bias [C_out] (may be NULL). */ +OxideonTensor* oxideon_tensor_conv2d( + const OxideonTensor* input, + const OxideonTensor* weight, + const OxideonTensor* bias, + size_t stride_h, + size_t stride_w, + size_t pad_h, + size_t pad_w, + size_t dilation_h, + size_t dilation_w +); + #ifdef __cplusplus } #endif