diff --git a/include/vec_math.h b/include/vec_math.h new file mode 100644 index 0000000..1eb7258 --- /dev/null +++ b/include/vec_math.h @@ -0,0 +1,48 @@ +/* + * Copyright 2026 Daniel Cederberg and William Zhang + * + * This file is part of the SparseDiffEngine project. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef VEC_MATH_H +#define VEC_MATH_H + +/* Elementwise math on arrays. On macOS these use Accelerate's vForce, which + evaluates the array with SIMD; elsewhere they loop over the libm function. */ + +#include "sparsediff_linalg/cblas_wrapper.h" /* Accelerate on macOS */ +#include + +/* Below this length a vForce call is no faster than the scalar loop. */ +#define VEC_MATH_MIN_SIZE 8 + +/* out[i] = exp(x[i]) for i < n. out may be x itself but must not otherwise + overlap it. vForce agrees with exp to 1 ulp and in the special values (inf, + nan, overflow, underflow). */ +static inline void vec_exp(double *out, const double *x, int n) +{ +#ifdef __APPLE__ + if (n >= VEC_MATH_MIN_SIZE) + { + vvexp(out, x, &n); + return; + } +#endif + for (int i = 0; i < n; i++) + { + out[i] = exp(x[i]); + } +} + +#endif /* VEC_MATH_H */ diff --git a/src/atoms/elementwise_full_dom/exp.c b/src/atoms/elementwise_full_dom/exp.c index 6413a98..16e2f28 100644 --- a/src/atoms/elementwise_full_dom/exp.c +++ b/src/atoms/elementwise_full_dom/exp.c @@ -16,7 +16,7 @@ * limitations under the License. */ #include "atoms/elementwise_full_dom.h" -#include +#include "vec_math.h" #include static void forward(expr *node, const double *u) @@ -25,10 +25,7 @@ static void forward(expr *node, const double *u) expr_forward(node->left, u); /* local forward pass */ - for (int i = 0; i < node->size; i++) - { - node->value[i] = exp(node->left->value[i]); - } + vec_exp(node->value, node->left->value, node->size); } static void local_jacobian(expr *node, double *vals)