Skip to content

Commit 7ff068e

Browse files
Merge pull request #12 from emreocell/feat/c-api-ops
Expand C API with conv2d/softmax/layer_norm/gelu/silu/reshape/transpose and add a C/CMake example
2 parents 3bc79e9 + 36a088e commit 7ff068e

4 files changed

Lines changed: 378 additions & 0 deletions

File tree

‎crates/oxideon-core/src/c_api.rs‎

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,10 +211,227 @@ pub unsafe extern "C" fn oxideon_tensor_relu(x: *const OxideonTensor) -> *mut Ox
211211
guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.relu() }))
212212
}
213213

214+
/// Elementwise GELU (exact, erf-based).
215+
///
216+
/// # Safety
217+
/// `x` must be a valid `OxideonTensor` pointer.
218+
#[unsafe(no_mangle)]
219+
pub unsafe extern "C" fn oxideon_tensor_gelu(x: *const OxideonTensor) -> *mut OxideonTensor {
220+
if x.is_null() {
221+
set_err("null operand in oxideon_tensor_gelu");
222+
return ptr::null_mut();
223+
}
224+
guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.gelu() }))
225+
}
226+
227+
/// Elementwise SiLU (swish) `x * sigmoid(x)`.
228+
///
229+
/// # Safety
230+
/// `x` must be a valid `OxideonTensor` pointer.
231+
#[unsafe(no_mangle)]
232+
pub unsafe extern "C" fn oxideon_tensor_silu(x: *const OxideonTensor) -> *mut OxideonTensor {
233+
if x.is_null() {
234+
set_err("null operand in oxideon_tensor_silu");
235+
return ptr::null_mut();
236+
}
237+
guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.silu() }))
238+
}
239+
240+
/// Softmax along `axis` (negative values count from the last dimension).
241+
///
242+
/// # Safety
243+
/// `x` must be a valid `OxideonTensor` pointer.
244+
#[unsafe(no_mangle)]
245+
pub unsafe extern "C" fn oxideon_tensor_softmax(x: *const OxideonTensor, axis: i64) -> *mut OxideonTensor {
246+
if x.is_null() {
247+
set_err("null operand in oxideon_tensor_softmax");
248+
return ptr::null_mut();
249+
}
250+
guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.softmax(axis as isize) }))
251+
}
252+
253+
/// Reshapes `x` to `shape[ndim]` (the element count must be unchanged).
254+
///
255+
/// # Safety
256+
/// `x` must be a valid `OxideonTensor` pointer and `shape` must point to `ndim` valid `usize` values.
257+
#[unsafe(no_mangle)]
258+
pub unsafe extern "C" fn oxideon_tensor_reshape(
259+
x: *const OxideonTensor,
260+
shape: *const usize,
261+
ndim: usize,
262+
) -> *mut OxideonTensor {
263+
if x.is_null() || (ndim > 0 && shape.is_null()) {
264+
set_err("null pointer passed to oxideon_tensor_reshape");
265+
return ptr::null_mut();
266+
}
267+
let shp = if ndim == 0 { &[][..] } else { unsafe { std::slice::from_raw_parts(shape, ndim) } };
268+
guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.reshape(shp) }))
269+
}
270+
271+
/// Swaps dimensions `dim0` and `dim1` (negative values count from the last dimension).
272+
///
273+
/// # Safety
274+
/// `x` must be a valid `OxideonTensor` pointer.
275+
#[unsafe(no_mangle)]
276+
pub unsafe extern "C" fn oxideon_tensor_transpose(x: *const OxideonTensor, dim0: i64, dim1: i64) -> *mut OxideonTensor {
277+
if x.is_null() {
278+
set_err("null operand in oxideon_tensor_transpose");
279+
return ptr::null_mut();
280+
}
281+
guard(ptr::null_mut(), || boxed(unsafe { (*x).inner.transpose(dim0 as isize, dim1 as isize) }))
282+
}
283+
284+
/// Layer normalization over the trailing `normalized_ndim` dimensions, whose sizes are `normalized_shape[normalized_ndim]`.
285+
/// `weight` and `bias` are optional (pass NULL to skip them).
286+
///
287+
/// # Safety
288+
/// `x` must be a valid `OxideonTensor` pointer, `normalized_shape` must point to `normalized_ndim` valid `usize` values,
289+
/// and `weight` / `bias` must each be NULL or a valid `OxideonTensor` pointer.
290+
#[unsafe(no_mangle)]
291+
pub unsafe extern "C" fn oxideon_tensor_layer_norm(
292+
x: *const OxideonTensor,
293+
normalized_shape: *const usize,
294+
normalized_ndim: usize,
295+
weight: *const OxideonTensor,
296+
bias: *const OxideonTensor,
297+
eps: f64,
298+
) -> *mut OxideonTensor {
299+
if x.is_null() || normalized_shape.is_null() || normalized_ndim == 0 {
300+
set_err("null pointer or empty normalized_shape passed to oxideon_tensor_layer_norm");
301+
return ptr::null_mut();
302+
}
303+
let shp = unsafe { std::slice::from_raw_parts(normalized_shape, normalized_ndim) };
304+
let (w, b) = unsafe { (weight.as_ref().map(|t| &t.inner), bias.as_ref().map(|t| &t.inner)) };
305+
guard(ptr::null_mut(), || boxed(crate::nn::functional_ext::layer_norm(unsafe { &(*x).inner }, shp, w, b, eps)))
306+
}
307+
308+
/// 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).
309+
///
310+
/// # Safety
311+
/// `input` and `weight` must be valid `OxideonTensor` pointers and `bias` must be NULL or a valid `OxideonTensor` pointer.
312+
#[unsafe(no_mangle)]
313+
pub unsafe extern "C" fn oxideon_tensor_conv2d(
314+
input: *const OxideonTensor,
315+
weight: *const OxideonTensor,
316+
bias: *const OxideonTensor,
317+
stride_h: usize,
318+
stride_w: usize,
319+
pad_h: usize,
320+
pad_w: usize,
321+
dilation_h: usize,
322+
dilation_w: usize,
323+
) -> *mut OxideonTensor {
324+
if input.is_null() || weight.is_null() {
325+
set_err("null operand in oxideon_tensor_conv2d");
326+
return ptr::null_mut();
327+
}
328+
let b = unsafe { bias.as_ref().map(|t| &t.inner) };
329+
guard(ptr::null_mut(), || {
330+
boxed(unsafe {
331+
(*input).inner.conv2d(&(*weight).inner, b, (stride_h, stride_w), (pad_h, pad_w), (dilation_h, dilation_w))
332+
})
333+
})
334+
}
335+
214336
#[cfg(test)]
215337
mod tests {
216338
use super::*;
217339

340+
unsafe fn make(data: &[f32], shape: &[usize]) -> *mut OxideonTensor {
341+
unsafe { oxideon_tensor_from_f32(data.as_ptr(), data.len(), shape.as_ptr(), shape.len()) }
342+
}
343+
344+
unsafe fn read(t: *const OxideonTensor) -> Vec<f32> {
345+
let mut out = vec![0.0f32; unsafe { oxideon_tensor_numel(t) }];
346+
assert_eq!(unsafe { oxideon_tensor_copy_f32(t, out.as_mut_ptr(), out.len()) }, 0);
347+
out
348+
}
349+
350+
fn assert_close(a: &[f32], b: &[f32]) {
351+
assert_eq!(a.len(), b.len());
352+
for (x, y) in a.iter().zip(b) {
353+
assert!((x - y).abs() < 1e-5, "{a:?} vs {b:?}");
354+
}
355+
}
356+
357+
#[test]
358+
fn c_api_activations_softmax_and_layer_norm() {
359+
unsafe {
360+
let x = make(&[-1.0, 0.0, 1.0, 2.0], &[2, 2]);
361+
let g = oxideon_tensor_gelu(x);
362+
assert_close(&read(g), &[-0.158_655_26, 0.0, 0.841_344_7, 1.954_499_7]);
363+
let s = oxideon_tensor_silu(x);
364+
assert_close(&read(s), &[-0.268_941_4, 0.0, 0.731_058_6, 1.761_594_2]);
365+
let sm = oxideon_tensor_softmax(x, -1);
366+
assert_close(&read(sm), &[0.268_941_4, 0.731_058_6, 0.268_941_4, 0.731_058_6]);
367+
assert!(oxideon_tensor_softmax(x, 5).is_null(), "out-of-range axis is an error");
368+
369+
// layer_norm over the last dim: each row [a, b] -> [-1, 1] (eps = 0), then weight 2 / bias 1 -> [-1, 3]
370+
let w = make(&[2.0, 2.0], &[2]);
371+
let b = make(&[1.0, 1.0], &[2]);
372+
let ln = oxideon_tensor_layer_norm(x, [2usize].as_ptr(), 1, std::ptr::null(), std::ptr::null(), 0.0);
373+
assert_close(&read(ln), &[-1.0, 1.0, -1.0, 1.0]);
374+
let lnwb = oxideon_tensor_layer_norm(x, [2usize].as_ptr(), 1, w, b, 0.0);
375+
assert_close(&read(lnwb), &[-1.0, 3.0, -1.0, 3.0]);
376+
assert!(oxideon_tensor_layer_norm(x, [3usize].as_ptr(), 1, w, b, 1e-5).is_null(), "mismatched normalized_shape");
377+
assert!(oxideon_tensor_layer_norm(x, std::ptr::null(), 1, w, b, 1e-5).is_null());
378+
379+
for t in [x, g, s, sm, w, b, ln, lnwb] {
380+
oxideon_tensor_free(t);
381+
}
382+
}
383+
}
384+
385+
#[test]
386+
fn c_api_reshape_and_transpose() {
387+
unsafe {
388+
let x = make(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
389+
let r = oxideon_tensor_reshape(x, [3usize, 2].as_ptr(), 2);
390+
let mut shp = [0usize; 2];
391+
assert_eq!(oxideon_tensor_shape(r, shp.as_mut_ptr(), 2), 0);
392+
assert_eq!(shp, [3, 2]);
393+
assert_eq!(read(r), [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
394+
assert!(oxideon_tensor_reshape(x, [4usize].as_ptr(), 1).is_null(), "element count must match");
395+
assert!(oxideon_tensor_reshape(x, std::ptr::null(), 2).is_null());
396+
397+
let t = oxideon_tensor_transpose(x, 0, 1);
398+
assert_eq!(oxideon_tensor_shape(t, shp.as_mut_ptr(), 2), 0);
399+
assert_eq!(shp, [3, 2]);
400+
assert_eq!(read(t), [1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
401+
let t_neg = oxideon_tensor_transpose(x, -1, -2);
402+
assert_eq!(read(t_neg), [1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
403+
assert!(oxideon_tensor_transpose(x, 0, 7).is_null());
404+
405+
for p in [x, r, t, t_neg] {
406+
oxideon_tensor_free(p);
407+
}
408+
}
409+
}
410+
411+
#[test]
412+
fn c_api_conv2d() {
413+
unsafe {
414+
// 1x1x3x3 input, 1x1x2x2 all-ones kernel, bias 0.5: each output is a 2x2 window sum + 0.5
415+
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]);
416+
let w = make(&[1.0; 4], &[1, 1, 2, 2]);
417+
let b = make(&[0.5], &[1]);
418+
let y = oxideon_tensor_conv2d(x, w, b, 1, 1, 0, 0, 1, 1);
419+
assert_close(&read(y), &[12.5, 16.5, 24.5, 28.5]);
420+
let y_nb = oxideon_tensor_conv2d(x, w, std::ptr::null(), 1, 1, 0, 0, 1, 1);
421+
assert_close(&read(y_nb), &[12.0, 16.0, 24.0, 28.0]);
422+
// padding 1 grows the output to 4x4
423+
let y_pad = oxideon_tensor_conv2d(x, w, std::ptr::null(), 1, 1, 1, 1, 1, 1);
424+
assert_eq!(oxideon_tensor_numel(y_pad), 16);
425+
// a 3D input is an error, not a crash
426+
let flat = make(&[1.0; 9], &[3, 3, 1]);
427+
assert!(oxideon_tensor_conv2d(flat, w, std::ptr::null(), 1, 1, 0, 0, 1, 1).is_null());
428+
assert!(oxideon_tensor_conv2d(std::ptr::null(), w, std::ptr::null(), 1, 1, 0, 0, 1, 1).is_null());
429+
for p in [x, w, b, y, y_nb, y_pad, flat] {
430+
oxideon_tensor_free(p);
431+
}
432+
}
433+
}
434+
218435
#[test]
219436
fn c_api_roundtrip_matmul_and_relu() {
220437
let a_data = [1.0f32, -2.0, 3.0, 4.0];

‎examples/c_embed/CMakeLists.txt‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Minimal C project that links the Oxideon C API (`include/oxideon.h`).
2+
#
3+
# cmake -S examples/c_embed -B build/c_embed
4+
# cmake --build build/c_embed --config Release
5+
# ./build/c_embed/c_embed (build/c_embed/Release/c_embed.exe on Windows)
6+
#
7+
# The shared library is built with `cargo build --release -p oxideon` (the facade crate is a `cdylib`, and it
8+
# re-exports the `oxideon_*` C symbols from `oxideon-core`), so a Rust toolchain must be on PATH.
9+
cmake_minimum_required(VERSION 3.15)
10+
project(oxideon_c_embed C)
11+
12+
set(OXIDEON_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../..")
13+
set(OXIDEON_CARGO_TARGET_DIR "${CMAKE_CURRENT_BINARY_DIR}/cargo-target")
14+
set(OXIDEON_LIB_DIR "${OXIDEON_CARGO_TARGET_DIR}/release")
15+
16+
find_program(CARGO_EXECUTABLE cargo REQUIRED)
17+
18+
if(WIN32)
19+
set(OXIDEON_LIB_FILE "${OXIDEON_LIB_DIR}/oxideon.dll")
20+
set(OXIDEON_IMPLIB_FILE "${OXIDEON_LIB_DIR}/oxideon.dll.lib")
21+
elseif(APPLE)
22+
set(OXIDEON_LIB_FILE "${OXIDEON_LIB_DIR}/liboxideon.dylib")
23+
else()
24+
set(OXIDEON_LIB_FILE "${OXIDEON_LIB_DIR}/liboxideon.so")
25+
endif()
26+
27+
add_custom_target(oxideon_rust ALL
28+
COMMAND "${CARGO_EXECUTABLE}" build --release -p oxideon
29+
--manifest-path "${OXIDEON_ROOT}/Cargo.toml"
30+
--target-dir "${OXIDEON_CARGO_TARGET_DIR}"
31+
COMMENT "Building the Oxideon shared library with cargo"
32+
USES_TERMINAL)
33+
34+
add_library(oxideon SHARED IMPORTED GLOBAL)
35+
set_target_properties(oxideon PROPERTIES
36+
IMPORTED_LOCATION "${OXIDEON_LIB_FILE}"
37+
INTERFACE_INCLUDE_DIRECTORIES "${OXIDEON_ROOT}/include")
38+
if(WIN32)
39+
set_target_properties(oxideon PROPERTIES IMPORTED_IMPLIB "${OXIDEON_IMPLIB_FILE}")
40+
endif()
41+
42+
add_executable(c_embed main.c)
43+
add_dependencies(c_embed oxideon_rust)
44+
target_link_libraries(c_embed PRIVATE oxideon)
45+
46+
if(WIN32)
47+
# the DLL must sit next to the executable
48+
add_custom_command(TARGET c_embed POST_BUILD
49+
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${OXIDEON_LIB_FILE}" "$<TARGET_FILE_DIR:c_embed>")
50+
else()
51+
set_target_properties(c_embed PROPERTIES BUILD_RPATH "${OXIDEON_LIB_DIR}")
52+
endif()

‎examples/c_embed/main.c‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/* Minimal C program using the Oxideon C API: a tiny "conv -> layer_norm -> GELU -> softmax" forward pass. */
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
5+
#include "oxideon.h"
6+
7+
static int check(const void* ptr, const char* what) {
8+
if (ptr != NULL) return 1;
9+
const char* msg = oxideon_last_error_message();
10+
fprintf(stderr, "%s failed: %s\n", what, msg ? msg : "unknown error");
11+
return 0;
12+
}
13+
14+
int main(void) {
15+
/* A 1x1x4x4 "image" and a 2x1x3x3 convolution kernel (output channel 0: 3x3 box blur, channel 1: center tap only). */
16+
float img[16];
17+
for (int i = 0; i < 16; ++i) img[i] = (float)((i * i) % 7) / 4.0f;
18+
float kernel[18] = {0};
19+
for (int i = 0; i < 9; ++i) kernel[i] = 1.0f / 9.0f;
20+
kernel[9 + 4] = 1.0f;
21+
22+
const size_t img_shape[4] = {1, 1, 4, 4};
23+
const size_t ker_shape[4] = {2, 1, 3, 3};
24+
OxideonTensor* x = oxideon_tensor_from_f32(img, 16, img_shape, 4);
25+
OxideonTensor* w = oxideon_tensor_from_f32(kernel, 18, ker_shape, 4);
26+
if (!check(x, "tensor_from_f32(img)") || !check(w, "tensor_from_f32(kernel)")) return 1;
27+
28+
/* conv2d -> [1, 2, 2, 2] (stride 1, no padding, no bias) */
29+
OxideonTensor* conv = oxideon_tensor_conv2d(x, w, NULL, 1, 1, 0, 0, 1, 1);
30+
if (!check(conv, "conv2d")) return 1;
31+
32+
/* flatten to [2, 4], normalize each row, then GELU and softmax along the last axis */
33+
const size_t flat_shape[2] = {2, 4};
34+
OxideonTensor* flat = oxideon_tensor_reshape(conv, flat_shape, 2);
35+
const size_t norm_shape[1] = {4};
36+
OxideonTensor* normed = flat ? oxideon_tensor_layer_norm(flat, norm_shape, 1, NULL, NULL, 1e-5) : NULL;
37+
OxideonTensor* act = normed ? oxideon_tensor_gelu(normed) : NULL;
38+
OxideonTensor* probs = act ? oxideon_tensor_softmax(act, -1) : NULL;
39+
if (!check(probs, "reshape/layer_norm/gelu/softmax")) return 1;
40+
41+
float out[8];
42+
if (oxideon_tensor_copy_f32(probs, out, 8) != 0) {
43+
fprintf(stderr, "copy failed: %s\n", oxideon_last_error_message());
44+
return 1;
45+
}
46+
for (int row = 0; row < 2; ++row) {
47+
printf("row %d:", row);
48+
float sum = 0.0f;
49+
for (int col = 0; col < 4; ++col) {
50+
printf(" %.4f", out[row * 4 + col]);
51+
sum += out[row * 4 + col];
52+
}
53+
printf(" (sum = %.4f)\n", sum);
54+
}
55+
56+
oxideon_tensor_free(probs);
57+
oxideon_tensor_free(act);
58+
oxideon_tensor_free(normed);
59+
oxideon_tensor_free(flat);
60+
oxideon_tensor_free(conv);
61+
oxideon_tensor_free(w);
62+
oxideon_tensor_free(x);
63+
return 0;
64+
}

‎include/oxideon.h‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,51 @@ OxideonTensor* oxideon_tensor_matmul(
4949

5050
OxideonTensor* oxideon_tensor_relu(const OxideonTensor* x);
5151

52+
/* Elementwise activations. */
53+
OxideonTensor* oxideon_tensor_gelu(const OxideonTensor* x);
54+
OxideonTensor* oxideon_tensor_silu(const OxideonTensor* x);
55+
56+
/* Softmax along `axis` (negative axes count from the last dimension). */
57+
OxideonTensor* oxideon_tensor_softmax(const OxideonTensor* x, int64_t axis);
58+
59+
/* Reshape to shape[ndim]; the element count must not change. */
60+
OxideonTensor* oxideon_tensor_reshape(
61+
const OxideonTensor* x,
62+
const size_t* shape,
63+
size_t ndim
64+
);
65+
66+
/* Swap two dimensions (negative dims count from the last dimension). */
67+
OxideonTensor* oxideon_tensor_transpose(
68+
const OxideonTensor* x,
69+
int64_t dim0,
70+
int64_t dim1
71+
);
72+
73+
/* Layer norm over the trailing `normalized_ndim` dims (sizes in normalized_shape).
74+
* `weight` and `bias` may be NULL. */
75+
OxideonTensor* oxideon_tensor_layer_norm(
76+
const OxideonTensor* x,
77+
const size_t* normalized_shape,
78+
size_t normalized_ndim,
79+
const OxideonTensor* weight,
80+
const OxideonTensor* bias,
81+
double eps
82+
);
83+
84+
/* 2D convolution: input [N, C_in, H, W], weight [C_out, C_in, kH, kW], optional bias [C_out] (may be NULL). */
85+
OxideonTensor* oxideon_tensor_conv2d(
86+
const OxideonTensor* input,
87+
const OxideonTensor* weight,
88+
const OxideonTensor* bias,
89+
size_t stride_h,
90+
size_t stride_w,
91+
size_t pad_h,
92+
size_t pad_w,
93+
size_t dilation_h,
94+
size_t dilation_w
95+
);
96+
5297
#ifdef __cplusplus
5398
}
5499
#endif

0 commit comments

Comments
 (0)