|
| 1 | +/* |
| 2 | + * Copyright 2026 Daniel Cederberg and William Zhang |
| 3 | + * |
| 4 | + * This file is part of the DNLP-differentiation-engine project. |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | +#include "elementwise_univariate.h" |
| 19 | +#include <math.h> |
| 20 | + |
| 21 | +#ifndef M_PI |
| 22 | +#define M_PI 3.14159265358979323846 |
| 23 | +#endif |
| 24 | + |
| 25 | +#ifndef M_SQRT2 |
| 26 | +#define M_SQRT2 1.41421356237309504880 |
| 27 | +#endif |
| 28 | + |
| 29 | +static const double INV_SQRT_2PI = 0.3989422804014326779399461; |
| 30 | + |
| 31 | +static void forward(expr *node, const double *u) |
| 32 | +{ |
| 33 | + node->left->forward(node->left, u); |
| 34 | + |
| 35 | + double *x = node->left->value; |
| 36 | + for (int i = 0; i < node->size; i++) |
| 37 | + { |
| 38 | + node->value[i] = 0.5 * (1.0 + erf(x[i] / M_SQRT2)); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +static void local_jacobian(expr *node, double *vals) |
| 43 | +{ |
| 44 | + double *x = node->left->value; |
| 45 | + for (int j = 0; j < node->size; j++) |
| 46 | + { |
| 47 | + vals[j] = INV_SQRT_2PI * exp(-0.5 * x[j] * x[j]); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +static void local_wsum_hess(expr *node, double *out, const double *w) |
| 52 | +{ |
| 53 | + double *x = node->left->value; |
| 54 | + for (int j = 0; j < node->size; j++) |
| 55 | + { |
| 56 | + /* could avoid recomputing this (like in logistic) */ |
| 57 | + double phi = INV_SQRT_2PI * exp(-0.5 * x[j] * x[j]); |
| 58 | + out[j] = w[j] * (-x[j] * phi); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +expr *new_normal_cdf(expr *child) |
| 63 | +{ |
| 64 | + expr *node = new_elementwise(child); |
| 65 | + node->forward = forward; |
| 66 | + node->local_jacobian = local_jacobian; |
| 67 | + node->local_wsum_hess = local_wsum_hess; |
| 68 | + |
| 69 | + return node; |
| 70 | +} |
0 commit comments