From 14ca33896e7be5bbf5685e725c10bd4f08c7a1d3 Mon Sep 17 00:00:00 2001 From: dance858 Date: Thu, 26 Nov 2026 11:48:37 -0800 Subject: [PATCH 1/6] Evaluate shared DAG nodes once per pass A node with several parents was re-evaluated once per path from the root in the forward, Jacobian and Hessian passes and in is_affine, which is exponential for deep compositions with reused nodes. - forward: per-pass epoch; atoms recurse through expr_forward - Jacobian: the jacobian_evaluated latch applies to every node and is cleared when a forward pass re-evaluates a non-affine node - Hessian: wsum_hess_init counts in-edges; a shared node sums the weights of its in-edges and runs its impl once. neg, scalar_mult and quad_form fold their factor into the child's weights - is_affine: memoized Co-Authored-By: Claude Fable 5.2 --- include/expr.h | 66 +++++-- include/subexpr.h | 3 +- src/atoms/affine/add.c | 4 +- src/atoms/affine/broadcast.c | 2 +- src/atoms/affine/convolve.c | 4 +- src/atoms/affine/diag_vec.c | 2 +- src/atoms/affine/hstack.c | 2 +- src/atoms/affine/index.c | 2 +- src/atoms/affine/kron.c | 4 +- src/atoms/affine/left_matmul.c | 4 +- src/atoms/affine/neg.c | 18 +- src/atoms/affine/promote.c | 2 +- src/atoms/affine/reshape.c | 2 +- src/atoms/affine/scalar_mult.c | 19 +- src/atoms/affine/sum.c | 2 +- src/atoms/affine/trace.c | 2 +- src/atoms/affine/transpose.c | 2 +- src/atoms/affine/vector_mult.c | 4 +- src/atoms/bivariate_full_dom/matmul.c | 4 +- src/atoms/bivariate_full_dom/multiply.c | 4 +- src/atoms/bivariate_restricted_dom/atan2.c | 4 +- .../bivariate_restricted_dom/quad_over_lin.c | 4 +- src/atoms/bivariate_restricted_dom/rel_entr.c | 4 +- .../rel_entr_scalar_vector.c | 4 +- .../rel_entr_vector_scalar.c | 4 +- src/atoms/elementwise_full_dom/exp.c | 4 +- src/atoms/elementwise_full_dom/hyperbolic.c | 12 +- src/atoms/elementwise_full_dom/logistic.c | 4 +- src/atoms/elementwise_full_dom/normal_cdf.c | 4 +- src/atoms/elementwise_full_dom/power.c | 4 +- src/atoms/elementwise_full_dom/trig.c | 12 +- src/atoms/elementwise_full_dom/xexp.c | 4 +- src/atoms/elementwise_restricted_dom/atanh.c | 4 +- src/atoms/elementwise_restricted_dom/entr.c | 4 +- src/atoms/elementwise_restricted_dom/log.c | 4 +- src/atoms/elementwise_restricted_dom/tan.c | 4 +- src/atoms/other/prod.c | 2 +- src/atoms/other/prod_axis_one.c | 2 +- src/atoms/other/prod_axis_zero.c | 2 +- src/atoms/other/quad_form.c | 18 +- src/expr.c | 93 +++++++--- tests/all_tests.c | 5 + tests/jacobian_tests/test_values_version.h | 12 +- tests/numerical_diff.c | 2 +- tests/wsum_hess/composite/test_shared_dag.h | 168 ++++++++++++++++++ 45 files changed, 413 insertions(+), 123 deletions(-) create mode 100644 tests/wsum_hess/composite/test_shared_dag.h diff --git a/include/expr.h b/include/expr.h index 1ffa8309..d1fb3666 100644 --- a/include/expr.h +++ b/include/expr.h @@ -48,15 +48,26 @@ typedef struct double *dwork; int *iwork; - /* node->is_affine(node), computed once by jacobian_init (affinity is - structural, and the recursive is_affine is too costly per eval). */ - bool is_affine_cached; - - /* True once eval_jacobian has run this parameter epoch; cleared by - expr_set_needs_refresh. Only consulted for affine nodes, where it - lets the eval_jacobian wrapper skip the values_version bump (same - role the old jacobian_csc_filled latch played). */ + /* Memoized node->is_affine(node): 0 unknown, 1 affine, -1 not affine + (affinity is structural). */ + signed char affine_state; + + /* True while the Jacobian values are valid, which lets eval_jacobian + skip the node (and its whole subtree). Set by eval_jacobian; cleared by + expr_set_needs_refresh and, for a non-affine node, by a new forward + pass. */ bool jacobian_evaluated; + + /* expr_fwd_epoch of the last forward pass that evaluated this node */ + uint64_t fwd_epoch; + + /* Shared-node bookkeeping of eval_wsum_hess: the number of wsum_hess_init + calls received (in-edges), the eval_wsum_hess calls received so far in + the current pass, and the weights accumulated over them (allocated iff + hess_n_in > 1). */ + int hess_n_in; + int hess_visits; + double *hess_w; double *local_jac_diag; /* cached f'(g(x)) diagonal */ matrix *hess_term1; /* Jg^T D Jg workspace */ matrix *hess_term2; /* child wsum_hess workspace */ @@ -78,7 +89,8 @@ typedef struct expr double *value; matrix *jacobian; matrix *wsum_hess; - forward_fn forward; + forward_fn forward; /* starts a forward pass: expr_forward_root */ + forward_fn forward_impl; /* the atom's rule; recurses with expr_forward */ jacobian_init_fn jacobian_init_impl; wsum_hess_init_fn wsum_hess_init_impl; eval_jacobian_fn eval_jacobian_impl; @@ -87,7 +99,8 @@ typedef struct expr // ------------------------------------------------------------------------ // other things // ------------------------------------------------------------------------ - is_affine_fn is_affine; + is_affine_fn is_affine; /* memoizing wrapper */ + is_affine_fn is_affine_impl; /* the atom's (recursive) rule */ local_jacobian_fn local_jacobian; /* used by elementwise univariate atoms*/ local_wsum_hess_fn local_wsum_hess; /* used by elementwise univariate atoms*/ free_type_data_fn free_type_data; /* Cleanup for type-specific fields */ @@ -129,14 +142,41 @@ void init_expr(expr *node, int d1, int d2, int n_vars, forward_fn forward, void free_expr(expr *node); -/* Guarded init: skips if already initialized (safe for DAGs - * where a node may be visited through multiple parents). */ +/* Forward pass on a DAG. node->forward(node, u) starts a pass: it bumps + * expr_fwd_epoch and evaluates the node. Atoms recurse into their children + * with expr_forward, which evaluates a node at most once per pass. A new value + * invalidates a non-affine node's Jacobian. (The epoch is a global, so forward + * passes are not thread-safe.) */ +extern uint64_t expr_fwd_epoch; +void expr_forward_root(struct expr *node, const double *u); +static inline void expr_forward(struct expr *node, const double *u) +{ + if (node->work->fwd_epoch == expr_fwd_epoch) return; + node->work->fwd_epoch = expr_fwd_epoch; + if (!node->is_affine(node)) node->work->jacobian_evaluated = false; + node->forward_impl(node, u); +} + +/* Guarded init: the impl runs once per node, however many parents it has. + * + * Every wsum_hess_init(node) call counts as one in-edge of the node and must + * be matched by exactly one eval_wsum_hess(node, w) call per Hessian pass + * (an atom does this for each child; problem does it for its roots). */ void jacobian_init(expr *node); void wsum_hess_init(expr *node); /* Eval wrappers: run the atom's eval_*_impl and bump the output matrix's * values_version so version-guarded caches (CSC mirrors, spd CSR views) - * refresh. Always call these instead of the impl slots. */ + * refresh. Always call these instead of the impl slots. + * + * eval_jacobian skips a node whose Jacobian is still valid. + * + * eval_wsum_hess runs the impl of a node with several in-edges only once per + * pass: the Hessian is linear in the weights, so it accumulates the weights of + * all in-edges and evaluates on the last one. Earlier callers read zeros. This + * requires that an atom only ever adds a child's Hessian to its own (a scaling + * goes into the weights passed to the child). An affine node is skipped; its + * Hessian is zero. */ void eval_jacobian(expr *node); void eval_wsum_hess(expr *node, const double *w); diff --git a/include/subexpr.h b/include/subexpr.h index fedf180d..39b93923 100644 --- a/include/subexpr.h +++ b/include/subexpr.h @@ -67,7 +67,8 @@ typedef struct quad_form_expr /* Q f(x) as an n x 1 permuted_dense: the transposed operand that forms the composition Jacobian 2 (Q f(x))^T J_f through the matrix dispatchers. */ matrix *Qx; - int n; /* quadratic dimension = left->size */ + int n; /* quadratic dimension = left->size */ + double *hess_w; /* weights 2w Q f(x) passed to the child's hessian */ /* parametric dense path: param_source feeds Q each solve (NULL otherwise) */ expr *param_source; diff --git a/src/atoms/affine/add.c b/src/atoms/affine/add.c index adef70e7..af863c56 100644 --- a/src/atoms/affine/add.c +++ b/src/atoms/affine/add.c @@ -26,8 +26,8 @@ static void forward(expr *node, const double *u) { /* children's forward passes */ - node->left->forward(node->left, u); - node->right->forward(node->right, u); + expr_forward(node->left, u); + expr_forward(node->right, u); /* add left and right values */ for (int i = 0; i < node->size; i++) diff --git a/src/atoms/affine/broadcast.c b/src/atoms/affine/broadcast.c index cb6bcb1d..685d697d 100644 --- a/src/atoms/affine/broadcast.c +++ b/src/atoms/affine/broadcast.c @@ -35,7 +35,7 @@ static void forward(expr *node, const double *u) expr *x = node->left; broadcast_expr *bcast = (broadcast_expr *) node; - x->forward(x, u); + expr_forward(x, u); if (bcast->type == BROADCAST_ROW) { diff --git a/src/atoms/affine/convolve.c b/src/atoms/affine/convolve.c index 6bbfe034..f578b9d7 100644 --- a/src/atoms/affine/convolve.c +++ b/src/atoms/affine/convolve.c @@ -71,7 +71,7 @@ static void forward(expr *node, const double *u) if (cnode->base.needs_parameter_refresh) { - cnode->param_source->forward(cnode->param_source, NULL); + expr_forward(cnode->param_source, NULL); /* refresh the convolution matrix values if it exists (necessary to check for null in case someone calls forward before initializing the jacobian, which might happen when we expose Python bindings to SparseDiffEngine) */ @@ -84,7 +84,7 @@ static void forward(expr *node, const double *u) cnode->base.needs_parameter_refresh = false; } - child->forward(child, u); + expr_forward(child, u); const double *a = cnode->param_source->value; const double *x = child->value; diff --git a/src/atoms/affine/diag_vec.c b/src/atoms/affine/diag_vec.c index 80a687c3..7bf7ba39 100644 --- a/src/atoms/affine/diag_vec.c +++ b/src/atoms/affine/diag_vec.c @@ -33,7 +33,7 @@ static void forward(expr *node, const double *u) int n = x->size; /* child's forward pass */ - x->forward(x, u); + expr_forward(x, u); /* zero-initialize output, TODO: do we need to do this? */ memset(node->value, 0, node->size * sizeof(double)); diff --git a/src/atoms/affine/hstack.c b/src/atoms/affine/hstack.c index c93a6a61..fdc9dc0a 100644 --- a/src/atoms/affine/hstack.c +++ b/src/atoms/affine/hstack.c @@ -33,7 +33,7 @@ static void forward(expr *node, const double *u) /* children's forward passes */ for (int i = 0; i < hnode->n_args; i++) { - hnode->args[i]->forward(hnode->args[i], u); + expr_forward(hnode->args[i], u); } /* concatenate values horizontally */ diff --git a/src/atoms/affine/index.c b/src/atoms/affine/index.c index b04c6234..8bcb64c9 100644 --- a/src/atoms/affine/index.c +++ b/src/atoms/affine/index.c @@ -49,7 +49,7 @@ static void forward(expr *node, const double *u) index_expr *idx = (index_expr *) node; /* child's forward pass */ - x->forward(x, u); + expr_forward(x, u); /* gather selected elements */ for (int i = 0; i < idx->n_idxs; i++) diff --git a/src/atoms/affine/kron.c b/src/atoms/affine/kron.c index 180f6b7c..68d505ee 100644 --- a/src/atoms/affine/kron.c +++ b/src/atoms/affine/kron.c @@ -44,7 +44,7 @@ static void refresh_param_values(kron_expr *knode) return; } - knode->param_source->forward(knode->param_source, NULL); + expr_forward(knode->param_source, NULL); knode->base.needs_parameter_refresh = false; } @@ -54,7 +54,7 @@ static void forward(expr *node, const double *u) kron_expr *knode = (kron_expr *) node; refresh_param_values(knode); - child->forward(child, u); + expr_forward(child, u); const double *a = knode->param_source->value; const double *x = child->value; diff --git a/src/atoms/affine/left_matmul.c b/src/atoms/affine/left_matmul.c index d760af7e..5e13b606 100644 --- a/src/atoms/affine/left_matmul.c +++ b/src/atoms/affine/left_matmul.c @@ -68,7 +68,7 @@ static void forward(expr *node, const double *u) /* call forward on param_source if it exists and needs refresh */ if (lnode->param_source != NULL && lnode->base.needs_parameter_refresh) { - lnode->param_source->forward(lnode->param_source, NULL); + expr_forward(lnode->param_source, NULL); } refresh_param_values(lnode); @@ -76,7 +76,7 @@ static void forward(expr *node, const double *u) expr *x = node->left; /* child's forward pass */ - node->left->forward(node->left, u); + expr_forward(node->left, u); /* y = A_kron @ vec(f(x)) */ matrix *A = lnode->A; diff --git a/src/atoms/affine/neg.c b/src/atoms/affine/neg.c index a3e2c75a..ffde875c 100644 --- a/src/atoms/affine/neg.c +++ b/src/atoms/affine/neg.c @@ -24,7 +24,7 @@ static void forward(expr *node, const double *u) { /* child's forward pass */ - node->left->forward(node->left, u); + expr_forward(node->left, u); /* negate values */ for (int i = 0; i < node->size; i++) @@ -62,20 +62,24 @@ static void wsum_hess_init_impl(expr *node) /* initialize child's wsum_hess */ wsum_hess_init(x); + /* weights passed to the child */ + node->work->dwork = (double *) sp_malloc(node->size * sizeof(double)); + /* same sparsity pattern as child (polymorphic copy) */ node->wsum_hess = copy_sparsity_matrices_alloc(x->wsum_hess); } static void eval_wsum_hess_impl(expr *node, const double *w) { - /* For f(x) = -g(x): d²f/dx² = -d²g/dx² */ - eval_wsum_hess(node->left, w); - - /* negate values (sparsity pattern set in wsum_hess_init_impl) */ - for (int k = 0; k < node->left->wsum_hess->nnz; k++) + /* For f(x) = -g(x): sum_i w_i Hf_i = sum_i (-w_i) Hg_i. The sign goes into + the child's weights, never onto its Hessian (see eval_wsum_hess). */ + for (int i = 0; i < node->size; i++) { - node->wsum_hess->x[k] = -node->left->wsum_hess->x[k]; + node->work->dwork[i] = -w[i]; } + eval_wsum_hess(node->left, node->work->dwork); + memcpy(node->wsum_hess->x, node->left->wsum_hess->x, + node->wsum_hess->nnz * sizeof(double)); } static bool is_affine(const expr *node) diff --git a/src/atoms/affine/promote.c b/src/atoms/affine/promote.c index 1d70a445..c8de35c3 100644 --- a/src/atoms/affine/promote.c +++ b/src/atoms/affine/promote.c @@ -26,7 +26,7 @@ static void forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); /* broadcast scalar value to all output elements */ for (int i = 0; i < node->size; i++) diff --git a/src/atoms/affine/reshape.c b/src/atoms/affine/reshape.c index c89f2957..24192195 100644 --- a/src/atoms/affine/reshape.c +++ b/src/atoms/affine/reshape.c @@ -28,7 +28,7 @@ static void forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); memcpy(node->value, node->left->value, node->size * sizeof(double)); } diff --git a/src/atoms/affine/scalar_mult.c b/src/atoms/affine/scalar_mult.c index 617c7d54..12b4dcdb 100644 --- a/src/atoms/affine/scalar_mult.c +++ b/src/atoms/affine/scalar_mult.c @@ -35,14 +35,14 @@ static void forward(expr *node, const double *u) its values) */ if (snode->base.needs_parameter_refresh) { - snode->param_source->forward(snode->param_source, NULL); + expr_forward(snode->param_source, NULL); snode->base.needs_parameter_refresh = false; } double a = snode->param_source->value[0]; /* child's forward pass */ - child->forward(child, u); + expr_forward(child, u); /* local forward pass: multiply each element by scalar a */ for (int i = 0; i < node->size; i++) @@ -84,6 +84,9 @@ static void wsum_hess_init_impl(expr *node) /* initialize child's weighted Hessian */ wsum_hess_init(x); + /* weights passed to the child */ + node->work->dwork = (double *) sp_malloc(node->size * sizeof(double)); + /* same sparsity as child */ node->wsum_hess = copy_sparsity_matrices_alloc(x->wsum_hess); } @@ -91,13 +94,17 @@ static void wsum_hess_init_impl(expr *node) static void eval_wsum_hess_impl(expr *node, const double *w) { expr *x = node->left; - eval_wsum_hess(x, w); - double a = ((scalar_mult_expr *) node)->param_source->value[0]; - for (int j = 0; j < x->wsum_hess->nnz; j++) + + /* the scaling goes into the child's weights, never onto its Hessian (see + eval_wsum_hess) */ + for (int i = 0; i < node->size; i++) { - node->wsum_hess->x[j] = a * x->wsum_hess->x[j]; + node->work->dwork[i] = a * w[i]; } + eval_wsum_hess(x, node->work->dwork); + memcpy(node->wsum_hess->x, x->wsum_hess->x, + node->wsum_hess->nnz * sizeof(double)); } static bool is_affine(const expr *node) diff --git a/src/atoms/affine/sum.c b/src/atoms/affine/sum.c index df4a8adc..01b69bb3 100644 --- a/src/atoms/affine/sum.c +++ b/src/atoms/affine/sum.c @@ -31,7 +31,7 @@ static void forward(expr *node, const double *u) int axis = snode->axis; /* child's forward pass */ - x->forward(x, u); + expr_forward(x, u); if (axis == -1) { diff --git a/src/atoms/affine/trace.c b/src/atoms/affine/trace.c index 175e1569..6d5d260d 100644 --- a/src/atoms/affine/trace.c +++ b/src/atoms/affine/trace.c @@ -27,7 +27,7 @@ static void forward(expr *node, const double *u) expr *x = node->left; /* child's forward pass */ - x->forward(x, u); + expr_forward(x, u); /* local forward pass */ double sum = 0.0; diff --git a/src/atoms/affine/transpose.c b/src/atoms/affine/transpose.c index 9d6b2698..9f3fa24c 100644 --- a/src/atoms/affine/transpose.c +++ b/src/atoms/affine/transpose.c @@ -25,7 +25,7 @@ static void forward(expr *node, const double *u) { /* forward pass for child */ - node->left->forward(node->left, u); + expr_forward(node->left, u); /* local forward pass */ int d1 = node->d1; diff --git a/src/atoms/affine/vector_mult.c b/src/atoms/affine/vector_mult.c index f68500ad..1188a503 100644 --- a/src/atoms/affine/vector_mult.c +++ b/src/atoms/affine/vector_mult.c @@ -36,14 +36,14 @@ static void forward(expr *node, const double *u) its values) */ if (vnode->base.needs_parameter_refresh) { - vnode->param_source->forward(vnode->param_source, NULL); + expr_forward(vnode->param_source, NULL); vnode->base.needs_parameter_refresh = false; } const double *a = vnode->param_source->value; /* child's forward pass */ - child->forward(child, u); + expr_forward(child, u); /* local forward pass: elementwise multiply by a */ for (int i = 0; i < node->size; i++) diff --git a/src/atoms/bivariate_full_dom/matmul.c b/src/atoms/bivariate_full_dom/matmul.c index b70f304f..3d0d2a45 100644 --- a/src/atoms/bivariate_full_dom/matmul.c +++ b/src/atoms/bivariate_full_dom/matmul.c @@ -92,8 +92,8 @@ static void forward(expr *node, const double *u) expr *y = node->right; /* children's forward passes */ - x->forward(x, u); - y->forward(y, u); + expr_forward(x, u); + expr_forward(y, u); /* local forward pass */ int m = x->d1, k = x->d2, n = y->d2; diff --git a/src/atoms/bivariate_full_dom/multiply.c b/src/atoms/bivariate_full_dom/multiply.c index 8067a15b..ac1f1807 100644 --- a/src/atoms/bivariate_full_dom/multiply.c +++ b/src/atoms/bivariate_full_dom/multiply.c @@ -36,8 +36,8 @@ static void forward(expr *node, const double *u) expr *y = node->right; /* children's forward passes */ - x->forward(x, u); - y->forward(y, u); + expr_forward(x, u); + expr_forward(y, u); /* local forward pass */ for (int i = 0; i < node->size; i++) diff --git a/src/atoms/bivariate_restricted_dom/atan2.c b/src/atoms/bivariate_restricted_dom/atan2.c index ab959f59..142fe405 100644 --- a/src/atoms/bivariate_restricted_dom/atan2.c +++ b/src/atoms/bivariate_restricted_dom/atan2.c @@ -38,8 +38,8 @@ static void forward(expr *node, const double *u) expr *x = node->right; /* children's forward passes */ - y->forward(y, u); - x->forward(x, u); + expr_forward(y, u); + expr_forward(x, u); /* local forward pass */ for (int i = 0; i < node->size; i++) diff --git a/src/atoms/bivariate_restricted_dom/quad_over_lin.c b/src/atoms/bivariate_restricted_dom/quad_over_lin.c index 5d721554..ceabde8b 100644 --- a/src/atoms/bivariate_restricted_dom/quad_over_lin.c +++ b/src/atoms/bivariate_restricted_dom/quad_over_lin.c @@ -38,8 +38,8 @@ static void forward(expr *node, const double *u) expr *y = node->right; /* children's forward passes */ - x->forward(x, u); - y->forward(y, u); + expr_forward(x, u); + expr_forward(y, u); /* local forward pass */ node->value[0] = 0.0; diff --git a/src/atoms/bivariate_restricted_dom/rel_entr.c b/src/atoms/bivariate_restricted_dom/rel_entr.c index 5f47347c..2142a3ef 100644 --- a/src/atoms/bivariate_restricted_dom/rel_entr.c +++ b/src/atoms/bivariate_restricted_dom/rel_entr.c @@ -34,8 +34,8 @@ static void forward_vector_args(expr *node, const double *u) expr *y = node->right; /* children's forward passes */ - x->forward(x, u); - y->forward(y, u); + expr_forward(x, u); + expr_forward(y, u); /* local forward pass */ for (int i = 0; i < node->size; i++) diff --git a/src/atoms/bivariate_restricted_dom/rel_entr_scalar_vector.c b/src/atoms/bivariate_restricted_dom/rel_entr_scalar_vector.c index 9e4226ea..8defba08 100644 --- a/src/atoms/bivariate_restricted_dom/rel_entr_scalar_vector.c +++ b/src/atoms/bivariate_restricted_dom/rel_entr_scalar_vector.c @@ -33,8 +33,8 @@ static void forward_scalar_vector(expr *node, const double *u) expr *y = node->right; /* children's forward passes */ - x->forward(x, u); - y->forward(y, u); + expr_forward(x, u); + expr_forward(y, u); /* local forward pass */ for (int i = 0; i < node->size; i++) diff --git a/src/atoms/bivariate_restricted_dom/rel_entr_vector_scalar.c b/src/atoms/bivariate_restricted_dom/rel_entr_vector_scalar.c index 7c432f74..28765a80 100644 --- a/src/atoms/bivariate_restricted_dom/rel_entr_vector_scalar.c +++ b/src/atoms/bivariate_restricted_dom/rel_entr_vector_scalar.c @@ -33,8 +33,8 @@ static void forward_vector_scalar(expr *node, const double *u) expr *y = node->right; /* children's forward passes */ - x->forward(x, u); - y->forward(y, u); + expr_forward(x, u); + expr_forward(y, u); /* local forward pass */ for (int i = 0; i < node->size; i++) diff --git a/src/atoms/elementwise_full_dom/exp.c b/src/atoms/elementwise_full_dom/exp.c index 6b2527c6..6413a984 100644 --- a/src/atoms/elementwise_full_dom/exp.c +++ b/src/atoms/elementwise_full_dom/exp.c @@ -22,7 +22,7 @@ static void forward(expr *node, const double *u) { /* child's forward pass */ - node->left->forward(node->left, u); + expr_forward(node->left, u); /* local forward pass */ for (int i = 0; i < node->size; i++) @@ -47,7 +47,7 @@ static void local_wsum_hess(expr *node, double *out, const double *w) expr *new_exp(expr *child) { expr *node = new_elementwise(child); - node->forward = forward; + node->forward_impl = forward; node->local_jacobian = local_jacobian; node->local_wsum_hess = local_wsum_hess; diff --git a/src/atoms/elementwise_full_dom/hyperbolic.c b/src/atoms/elementwise_full_dom/hyperbolic.c index b586bbdc..7ff19eca 100644 --- a/src/atoms/elementwise_full_dom/hyperbolic.c +++ b/src/atoms/elementwise_full_dom/hyperbolic.c @@ -22,7 +22,7 @@ /* ----------------------- sinh ----------------------- */ static void sinh_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { node->value[i] = sinh(node->left->value[i]); @@ -49,7 +49,7 @@ static void sinh_local_wsum_hess(expr *node, double *out, const double *w) expr *new_sinh(expr *child) { expr *node = new_elementwise(child); - node->forward = sinh_forward; + node->forward_impl = sinh_forward; node->local_jacobian = sinh_local_jacobian; node->local_wsum_hess = sinh_local_wsum_hess; return node; @@ -58,7 +58,7 @@ expr *new_sinh(expr *child) /* ----------------------- tanh ----------------------- */ static void tanh_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { node->value[i] = tanh(node->left->value[i]); @@ -88,7 +88,7 @@ static void tanh_local_wsum_hess(expr *node, double *out, const double *w) expr *new_tanh(expr *child) { expr *node = new_elementwise(child); - node->forward = tanh_forward; + node->forward_impl = tanh_forward; node->local_jacobian = tanh_local_jacobian; node->local_wsum_hess = tanh_local_wsum_hess; return node; @@ -97,7 +97,7 @@ expr *new_tanh(expr *child) /* ----------------------- asinh ----------------------- */ static void asinh_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { node->value[i] = asinh(node->left->value[i]); @@ -126,7 +126,7 @@ static void asinh_local_wsum_hess(expr *node, double *out, const double *w) expr *new_asinh(expr *child) { expr *node = new_elementwise(child); - node->forward = asinh_forward; + node->forward_impl = asinh_forward; node->local_jacobian = asinh_local_jacobian; node->local_wsum_hess = asinh_local_wsum_hess; return node; diff --git a/src/atoms/elementwise_full_dom/logistic.c b/src/atoms/elementwise_full_dom/logistic.c index df231e45..7485f37b 100644 --- a/src/atoms/elementwise_full_dom/logistic.c +++ b/src/atoms/elementwise_full_dom/logistic.c @@ -22,7 +22,7 @@ static void forward(expr *node, const double *u) { /* child's forward pass */ - node->left->forward(node->left, u); + expr_forward(node->left, u); double *x = node->left->value; @@ -80,7 +80,7 @@ static void local_wsum_hess(expr *node, double *out, const double *w) expr *new_logistic(expr *child) { expr *node = new_elementwise(child); - node->forward = forward; + node->forward_impl = forward; node->local_jacobian = local_jacobian; node->local_wsum_hess = local_wsum_hess; return node; diff --git a/src/atoms/elementwise_full_dom/normal_cdf.c b/src/atoms/elementwise_full_dom/normal_cdf.c index 612067b8..728df4e0 100644 --- a/src/atoms/elementwise_full_dom/normal_cdf.c +++ b/src/atoms/elementwise_full_dom/normal_cdf.c @@ -30,7 +30,7 @@ static const double INV_SQRT_2PI = 0.3989422804014326779399461; static void forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); double *x = node->left->value; for (int i = 0; i < node->size; i++) @@ -61,7 +61,7 @@ static void local_wsum_hess(expr *node, double *out, const double *w) expr *new_normal_cdf(expr *child) { expr *node = new_elementwise(child); - node->forward = forward; + node->forward_impl = forward; node->local_jacobian = local_jacobian; node->local_wsum_hess = local_wsum_hess; diff --git a/src/atoms/elementwise_full_dom/power.c b/src/atoms/elementwise_full_dom/power.c index 756e54bd..a69ba2e1 100644 --- a/src/atoms/elementwise_full_dom/power.c +++ b/src/atoms/elementwise_full_dom/power.c @@ -59,7 +59,7 @@ static void forward(expr *node, const double *u) { /* child's forward pass */ - node->left->forward(node->left, u); + expr_forward(node->left, u); /* local forward pass */ double *x = node->left->value; @@ -93,7 +93,7 @@ expr *new_power(expr *child, double p) power_expr *pnode = (power_expr *) sp_calloc(1, sizeof(power_expr)); expr *node = &pnode->base; init_elementwise(node, child); - node->forward = forward; + node->forward_impl = forward; node->local_jacobian = local_jacobian; node->local_wsum_hess = local_wsum_hess; diff --git a/src/atoms/elementwise_full_dom/trig.c b/src/atoms/elementwise_full_dom/trig.c index eea98db8..7ce2017b 100644 --- a/src/atoms/elementwise_full_dom/trig.c +++ b/src/atoms/elementwise_full_dom/trig.c @@ -21,7 +21,7 @@ /* ----------------------- sin ----------------------- */ static void sin_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { node->value[i] = sin(node->left->value[i]); @@ -48,7 +48,7 @@ static void sin_local_wsum_hess(expr *node, double *out, const double *w) expr *new_sin(expr *child) { expr *node = new_elementwise(child); - node->forward = sin_forward; + node->forward_impl = sin_forward; node->local_jacobian = sin_local_jacobian; node->local_wsum_hess = sin_local_wsum_hess; return node; @@ -57,7 +57,7 @@ expr *new_sin(expr *child) /* ----------------------- cos ----------------------- */ static void cos_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { node->value[i] = cos(node->left->value[i]); @@ -84,7 +84,7 @@ static void cos_local_wsum_hess(expr *node, double *out, const double *w) expr *new_cos(expr *child) { expr *node = new_elementwise(child); - node->forward = cos_forward; + node->forward_impl = cos_forward; node->local_jacobian = cos_local_jacobian; node->local_wsum_hess = cos_local_wsum_hess; return node; @@ -93,7 +93,7 @@ expr *new_cos(expr *child) /* ----------------------- atan ----------------------- */ static void atan_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { node->value[i] = atan(node->left->value[i]); @@ -122,7 +122,7 @@ static void atan_local_wsum_hess(expr *node, double *out, const double *w) expr *new_atan(expr *child) { expr *node = new_elementwise(child); - node->forward = atan_forward; + node->forward_impl = atan_forward; node->local_jacobian = atan_local_jacobian; node->local_wsum_hess = atan_local_wsum_hess; return node; diff --git a/src/atoms/elementwise_full_dom/xexp.c b/src/atoms/elementwise_full_dom/xexp.c index 59580ca3..0a42eaf2 100644 --- a/src/atoms/elementwise_full_dom/xexp.c +++ b/src/atoms/elementwise_full_dom/xexp.c @@ -22,7 +22,7 @@ static void forward(expr *node, const double *u) { /* child's forward pass */ - node->left->forward(node->left, u); + expr_forward(node->left, u); /* local forward pass */ for (int i = 0; i < node->size; i++) @@ -53,7 +53,7 @@ static void local_wsum_hess(expr *node, double *out, const double *w) expr *new_xexp(expr *child) { expr *node = new_elementwise(child); - node->forward = forward; + node->forward_impl = forward; node->local_jacobian = local_jacobian; node->local_wsum_hess = local_wsum_hess; return node; diff --git a/src/atoms/elementwise_restricted_dom/atanh.c b/src/atoms/elementwise_restricted_dom/atanh.c index 0acc5841..40b06620 100644 --- a/src/atoms/elementwise_restricted_dom/atanh.c +++ b/src/atoms/elementwise_restricted_dom/atanh.c @@ -20,7 +20,7 @@ static void atanh_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { node->value[i] = atanh(node->left->value[i]); @@ -52,7 +52,7 @@ expr *new_atanh(expr *child) { expr *node = new_restricted(child); if (!node) return NULL; - node->forward = atanh_forward; + node->forward_impl = atanh_forward; node->eval_jacobian_impl = atanh_eval_jacobian; node->eval_wsum_hess_impl = atanh_eval_wsum_hess; return node; diff --git a/src/atoms/elementwise_restricted_dom/entr.c b/src/atoms/elementwise_restricted_dom/entr.c index 38fbeb00..64690813 100644 --- a/src/atoms/elementwise_restricted_dom/entr.c +++ b/src/atoms/elementwise_restricted_dom/entr.c @@ -21,7 +21,7 @@ static void entr_forward(expr *node, const double *u) { expr *child = node->left; - child->forward(child, u); + expr_forward(child, u); for (int i = 0; i < node->size; i++) { @@ -53,7 +53,7 @@ expr *new_entr(expr *child) { expr *node = new_restricted(child); if (!node) return NULL; - node->forward = entr_forward; + node->forward_impl = entr_forward; node->eval_jacobian_impl = entr_eval_jacobian; node->eval_wsum_hess_impl = entr_eval_wsum_hess; return node; diff --git a/src/atoms/elementwise_restricted_dom/log.c b/src/atoms/elementwise_restricted_dom/log.c index 1c82820c..b88717dc 100644 --- a/src/atoms/elementwise_restricted_dom/log.c +++ b/src/atoms/elementwise_restricted_dom/log.c @@ -20,7 +20,7 @@ static void log_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { @@ -52,7 +52,7 @@ expr *new_log(expr *child) { expr *node = new_restricted(child); if (!node) return NULL; - node->forward = log_forward; + node->forward_impl = log_forward; node->eval_jacobian_impl = log_eval_jacobian; node->eval_wsum_hess_impl = log_eval_wsum_hess; return node; diff --git a/src/atoms/elementwise_restricted_dom/tan.c b/src/atoms/elementwise_restricted_dom/tan.c index 17cf4185..2ea752c6 100644 --- a/src/atoms/elementwise_restricted_dom/tan.c +++ b/src/atoms/elementwise_restricted_dom/tan.c @@ -20,7 +20,7 @@ static void tan_forward(expr *node, const double *u) { - node->left->forward(node->left, u); + expr_forward(node->left, u); for (int i = 0; i < node->size; i++) { node->value[i] = tan(node->left->value[i]); @@ -53,7 +53,7 @@ expr *new_tan(expr *child) { expr *node = new_restricted(child); if (!node) return NULL; - node->forward = tan_forward; + node->forward_impl = tan_forward; node->eval_jacobian_impl = tan_eval_jacobian; node->eval_wsum_hess_impl = tan_eval_wsum_hess; return node; diff --git a/src/atoms/other/prod.c b/src/atoms/other/prod.c index dbb93792..396cf37f 100644 --- a/src/atoms/other/prod.c +++ b/src/atoms/other/prod.c @@ -36,7 +36,7 @@ static void forward(expr *node, const double *u) expr *x = node->left; /* forward pass of child */ - x->forward(x, u); + expr_forward(x, u); /* local forward pass and count zeros */ double prod_nonzero = 1.0; diff --git a/src/atoms/other/prod_axis_one.c b/src/atoms/other/prod_axis_one.c index 252f779e..43ac441f 100644 --- a/src/atoms/other/prod_axis_one.c +++ b/src/atoms/other/prod_axis_one.c @@ -30,7 +30,7 @@ static void forward(expr *node, const double *u) { /* forward pass of child */ expr *x = node->left; - x->forward(x, u); + expr_forward(x, u); prod_axis *pnode = (prod_axis *) node; int d1 = x->d1; diff --git a/src/atoms/other/prod_axis_zero.c b/src/atoms/other/prod_axis_zero.c index 5c314c08..675d76ab 100644 --- a/src/atoms/other/prod_axis_zero.c +++ b/src/atoms/other/prod_axis_zero.c @@ -30,7 +30,7 @@ static void forward(expr *node, const double *u) { /* forward pass of child */ expr *x = node->left; - x->forward(x, u); + expr_forward(x, u); prod_axis *pnode = (prod_axis *) node; int d1 = x->d1; diff --git a/src/atoms/other/quad_form.c b/src/atoms/other/quad_form.c index 1d283a0d..6d06b71e 100644 --- a/src/atoms/other/quad_form.c +++ b/src/atoms/other/quad_form.c @@ -52,12 +52,12 @@ static void forward(expr *node, const double *u) /* refresh Q from the parameter if needed */ if (qnode->param_source != NULL && node->needs_parameter_refresh) { - qnode->param_source->forward(qnode->param_source, NULL); + expr_forward(qnode->param_source, NULL); } refresh_param_values_qf(qnode); /* child's forward pass */ - x->forward(x, u); + expr_forward(x, u); /* dwork = Q @ x; value = x' (Q x) */ matrix *Q = qnode->Q; @@ -169,6 +169,7 @@ static void wsum_hess_init_impl(expr *node) node->work->hess_term1 = BTA_matrices_alloc(x->jacobian, qnode->QJf); wsum_hess_init(x); + qnode->hess_w = (double *) sp_malloc(qnode->n * sizeof(double)); node->work->hess_term2 = copy_sparsity_matrices_alloc(x->wsum_hess); /* hess = term1 + term2 */ @@ -203,10 +204,15 @@ static void eval_wsum_hess_impl(expr *node, const double *w) cblas_dscal(H1->nnz, two_w, H1->x, 1); matrix_values_changed(H1); - /* term2 = 2w sum_i (Q f(x))_i nabla^2 f_i (dwork = Q f(x) from forward) */ - eval_wsum_hess(x, node->work->dwork); + /* term2 = 2w sum_i (Q f(x))_i nabla^2 f_i (dwork = Q f(x) from forward). + The factor 2w goes into the child's weights, never onto its Hessian + (see eval_wsum_hess). */ + for (int i = 0; i < qnode->n; i++) + { + qnode->hess_w[i] = two_w * node->work->dwork[i]; + } + eval_wsum_hess(x, qnode->hess_w); memcpy(H2->x, x->wsum_hess->x, x->wsum_hess->nnz * sizeof(double)); - cblas_dscal(H2->nnz, two_w, H2->x, 1); matrix_values_changed(H2); sum_matrices_fill_values(H1, H2, node->wsum_hess); @@ -228,6 +234,8 @@ static void free_type_data(expr *node) qnode->QJf = NULL; free_matrix(qnode->Qx); qnode->Qx = NULL; + sp_free(qnode->hess_w); + qnode->hess_w = NULL; free_expr(qnode->param_source); qnode->param_source = NULL; } diff --git a/src/expr.c b/src/expr.c index d3221b8c..9f2bbc52 100644 --- a/src/expr.c +++ b/src/expr.c @@ -20,6 +20,26 @@ #include #include +/* Affinity is structural and the atoms' rules recurse into their children: + memoize, or the recursion visits a shared node once per path. */ +static bool expr_is_affine(const expr *node) +{ + Expr_Work *wk = node->work; + if (wk->affine_state == 0) + { + wk->affine_state = node->is_affine_impl(node) ? 1 : -1; + } + return wk->affine_state == 1; +} + +uint64_t expr_fwd_epoch = 0; + +void expr_forward_root(expr *node, const double *u) +{ + expr_fwd_epoch++; + expr_forward(node, u); +} + void init_expr(expr *node, int d1, int d2, int n_vars, forward_fn forward, jacobian_init_fn jacobian_init, eval_jacobian_fn eval_jacobian, is_affine_fn is_affine, wsum_hess_init_fn wsum_hess_init, @@ -32,10 +52,12 @@ void init_expr(expr *node, int d1, int d2, int n_vars, forward_fn forward, node->refcount = 0; node->value = (double *) sp_calloc(d1 * d2, sizeof(double)); node->var_id = NOT_A_VARIABLE; - node->forward = forward; + node->forward = expr_forward_root; + node->forward_impl = forward; node->jacobian_init_impl = jacobian_init; node->eval_jacobian_impl = eval_jacobian; - node->is_affine = is_affine; + node->is_affine = expr_is_affine; + node->is_affine_impl = is_affine; node->wsum_hess_init_impl = wsum_hess_init; node->eval_wsum_hess_impl = eval_wsum_hess; node->free_type_data = free_type_data; @@ -73,6 +95,7 @@ void free_expr(expr *node) sp_free(node->work->dwork); sp_free(node->work->iwork); sp_free(node->work->local_jac_diag); + sp_free(node->work->hess_w); free_matrix(node->work->hess_term1); free_matrix(node->work->hess_term2); sp_free(node->work); @@ -84,42 +107,70 @@ void free_expr(expr *node) void jacobian_init(expr *node) { - if (node == NULL) return; - - /* Affinity is structural; cache it so the eval_jacobian wrapper doesn't - pay the O(subtree) recursive is_affine per eval. Set before the init - guard so nodes that preset their jacobian at construction get it too. */ - node->work->is_affine_cached = node->is_affine(node); - - if (node->jacobian != NULL) return; + if (node == NULL || node->jacobian != NULL) return; node->jacobian_init_impl(node); } void wsum_hess_init(expr *node) { - if (node == NULL || node->wsum_hess != NULL) return; + if (node == NULL) return; + + /* one more in-edge; a shared node needs a buffer to sum their weights */ + if (++node->work->hess_n_in == 2) + { + node->work->hess_w = (double *) sp_malloc(node->size * sizeof(double)); + } + + if (node->wsum_hess != NULL) return; node->wsum_hess_init_impl(node); + + /* eval_wsum_hess never touches an affine node, so its zeros are set here */ + if (node->is_affine(node) && node->wsum_hess->nnz > 0) + { + memset(node->wsum_hess->x, 0, node->wsum_hess->nnz * sizeof(double)); + } } -/* Runs the atom's eval and bumps the Jacobian's values_version — except - for an affine node already evaluated this parameter epoch: its values - are constant, so the impl (and with it the whole subtree walk) is - skipped and consumers correctly see "unchanged". expr_set_needs_refresh - re-arms the eval. */ +/* Runs the atom's eval and bumps the Jacobian's values_version, unless the + values are still valid: the node (and with it the whole subtree walk) is + then skipped and consumers correctly see "unchanged". A forward pass + (non-affine nodes) and expr_set_needs_refresh re-arm the eval. */ void eval_jacobian(expr *node) { - if (node == NULL) return; - if (node->work->is_affine_cached && node->work->jacobian_evaluated) return; + if (node == NULL || node->work->jacobian_evaluated) return; node->eval_jacobian_impl(node); matrix_values_changed(node->jacobian); node->work->jacobian_evaluated = true; } -/* Runs the atom's eval and bumps the Hessian's values_version (no affine - handling — the weights change every call). */ +/* Runs the atom's eval and bumps the Hessian's values_version. */ void eval_wsum_hess(expr *node, const double *w) { - if (node == NULL) return; + if (node == NULL || node->is_affine(node)) return; + Expr_Work *wk = node->work; + + /* A shared node is reached once per in-edge. Sum the weights; all callers + but the last read zeros, and the last one triggers the evaluation. */ + if (wk->hess_n_in > 1) + { + if (wk->hess_visits == 0) + { + memcpy(wk->hess_w, w, node->size * sizeof(double)); + memset(node->wsum_hess->x, 0, node->wsum_hess->nnz * sizeof(double)); + matrix_values_changed(node->wsum_hess); + } + else + { + for (int i = 0; i < node->size; i++) + { + wk->hess_w[i] += w[i]; + } + } + if (++wk->hess_visits < wk->hess_n_in) return; + wk->hess_visits = 0; + w = wk->hess_w; + } + node->eval_wsum_hess_impl(node, w); matrix_values_changed(node->wsum_hess); } diff --git a/tests/all_tests.c b/tests/all_tests.c index 45381b8e..37c48595 100644 --- a/tests/all_tests.c +++ b/tests/all_tests.c @@ -85,6 +85,7 @@ #include "wsum_hess/bivariate_restricted_dom/test_rel_entr_scalar_vector.h" #include "wsum_hess/bivariate_restricted_dom/test_rel_entr_vector_scalar.h" #include "wsum_hess/composite/test_chain_rule_wsum_hess.h" +#include "wsum_hess/composite/test_shared_dag.h" #include "wsum_hess/elementwise_full_dom/test_exp.h" #include "wsum_hess/elementwise_full_dom/test_hyperbolic.h" #include "wsum_hess/elementwise_full_dom/test_logistic.h" @@ -390,6 +391,10 @@ int main(void) mu_run_test(test_wsum_hess_add_shared_subexpr, tests_run); mu_run_test(test_wsum_hess_multiply_shared_subexpr, tests_run); mu_run_test(test_wsum_hess_matmul_shared_subexpr, tests_run); + mu_run_test(test_shared_dag_chain, tests_run); + mu_run_test(test_shared_dag_scaling_atoms, tests_run); + mu_run_test(test_shared_dag_quad_form, tests_run); + mu_run_test(test_shared_dag_root_inside_other_root, tests_run); mu_run_test(test_wsum_hess_matmul_exp_exp, tests_run); mu_run_test(test_wsum_hess_matmul_sin_cos, tests_run); mu_run_test(test_wsum_hess_matmul_Ax_By, tests_run); diff --git a/tests/jacobian_tests/test_values_version.h b/tests/jacobian_tests/test_values_version.h index 2294d1a9..d2320529 100644 --- a/tests/jacobian_tests/test_values_version.h +++ b/tests/jacobian_tests/test_values_version.h @@ -10,8 +10,8 @@ #include "numerical_diff.h" #include "test_helpers.h" -/* Non-affine node: every eval_jacobian call bumps the jacobian's - * values_version. */ +/* Non-affine node: eval_jacobian bumps the jacobian's values_version once per + * forward pass (a re-eval at the same point is skipped). */ const char *test_values_version_non_affine(void) { double u[3] = {0.1, 0.2, 0.3}; @@ -25,7 +25,13 @@ const char *test_values_version_non_affine(void) eval_jacobian(e); mu_assert("first eval must bump", e->jacobian->values_version == v0 + 1); eval_jacobian(e); - mu_assert("second eval must bump", e->jacobian->values_version == v0 + 2); + mu_assert("re-eval at the same point must not bump", + e->jacobian->values_version == v0 + 1); + + e->forward(e, u); + eval_jacobian(e); + mu_assert("eval after a forward pass must bump", + e->jacobian->values_version == v0 + 2); free_expr(e); return 0; diff --git a/tests/numerical_diff.c b/tests/numerical_diff.c index 68ca576c..95126692 100644 --- a/tests/numerical_diff.c +++ b/tests/numerical_diff.c @@ -175,7 +175,7 @@ int check_wsum_hess(expr *node, const double *u, const double *w, double h) double *H_num = numerical_wsum_hess(node, u, w, h); /* Now compute analytical (reuses jacobian from numerical) */ - wsum_hess_init(node); + if (node->wsum_hess == NULL) wsum_hess_init(node); node->forward(node, u); eval_jacobian(node); eval_wsum_hess(node, w); diff --git a/tests/wsum_hess/composite/test_shared_dag.h b/tests/wsum_hess/composite/test_shared_dag.h new file mode 100644 index 00000000..72e8555c --- /dev/null +++ b/tests/wsum_hess/composite/test_shared_dag.h @@ -0,0 +1,168 @@ +#include +#include + +#include "atoms/affine.h" +#include "atoms/bivariate_full_dom.h" +#include "atoms/elementwise_full_dom.h" +#include "atoms/non_elementwise_full_dom.h" +#include "expr.h" +#include "minunit.h" +#include "numerical_diff.h" +#include "problem.h" +#include "subexpr.h" +#include "test_helpers.h" + +/* Tests for DAGs in which a node has several parents: every pass must + evaluate a shared node once (not once per path from the root), and the + Hessian must still be right. */ + +/* Objective x_N^2 with x_{k+1} = x_k + h (x_k - x_k^3) + h u_k. Each x_k has + three parents, so the root is reached by 3^N paths: without per-node guards + this test does not finish. Variables are (x_0, u_0, ..., u_{N-1}). */ +#define SHARED_DAG_N 30 +static expr *build_shared_chain(void) +{ + int n_vars = SHARED_DAG_N + 1; + double h = 0.1; + expr *h_param = new_parameter(1, 1, PARAM_FIXED, n_vars, &h); + expr *u = new_variable(SHARED_DAG_N, 1, 1, n_vars); + expr *x = new_variable(1, 1, 0, n_vars); + + for (int k = 0; k < SHARED_DAG_N; k++) + { + expr *drift = new_add(x, new_neg(new_power(x, 3.0))); + expr *u_k = new_index(u, 1, 1, &k, 1); + x = new_add(new_add(x, new_scalar_mult(h_param, drift)), + new_scalar_mult(h_param, u_k)); + } + return new_power(x, 2.0); +} + +const char *test_shared_dag_chain(void) +{ + double u[SHARED_DAG_N + 1]; + u[0] = 0.5; + for (int k = 0; k < SHARED_DAG_N; k++) + { + u[k + 1] = 0.3 * sin(0.7 * k); + } + double w = 1.5; + + expr *obj = build_shared_chain(); + mu_assert("chain jacobian", + check_jacobian_num(obj, u, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("chain hessian", + check_wsum_hess(obj, u, &w, NUMERICAL_DIFF_DEFAULT_H)); + + /* a second pass at another point and weight */ + u[0] = -0.4; + w = -0.7; + mu_assert("chain hessian, second pass", + check_wsum_hess(obj, u, &w, NUMERICAL_DIFF_DEFAULT_H)); + + free_expr(obj); + return 0; +} + +/* g = exp(x) under the atoms that scale their child's Hessian (neg, + scalar_mult) and as both children of a multiply */ +const char *test_shared_dag_scaling_atoms(void) +{ + double u1[3] = {0.1, -0.2, 0.3}; + double u2[3] = {-0.3, 0.4, 0.2}; + double w1[3] = {1.0, -2.0, 0.5}; + double w2[3] = {-0.5, 1.5, 2.0}; + double a = 2.5; + + expr *x = new_variable(3, 1, 0, 3); + expr *g = new_exp(x); + expr *a_param = new_parameter(1, 1, PARAM_FIXED, 3, &a); + expr *e = new_add(new_add(new_neg(g), new_scalar_mult(a_param, g)), + new_elementwise_mult(g, g)); + + mu_assert("jacobian", check_jacobian_num(e, u1, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("hessian", check_wsum_hess(e, u1, w1, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("hessian, second pass", + check_wsum_hess(e, u2, w2, NUMERICAL_DIFF_DEFAULT_H)); + + free_expr(e); + return 0; +} + +/* g = exp(x) under a quad_form (which scales by 2w) and a second parent */ +const char *test_shared_dag_quad_form(void) +{ + double u1[3] = {0.1, -0.2, 0.3}; + double u2[3] = {-0.3, 0.4, 0.2}; + double w1 = 1.5; + double w2 = -0.7; + double Q[9] = {2.0, 0.5, -1.0, 0.5, 1.0, 0.3, -1.0, 0.3, 3.0}; + + expr *x = new_variable(3, 1, 0, 3); + expr *g = new_exp(x); + expr *e = new_add(new_quad_form_dense(g, 3, Q, NULL), new_sum(new_sin(g), -1)); + + mu_assert("jacobian", check_jacobian_num(e, u1, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("hessian", check_wsum_hess(e, u1, &w1, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("hessian, second pass", + check_wsum_hess(e, u2, &w2, NUMERICAL_DIFF_DEFAULT_H)); + + free_expr(e); + return 0; +} + +/* The constraint g = exp(x) is a root of the problem, appears as a constraint + twice, and also sits inside the objective sum(sin(g)): all its in-edges + are delivered in every problem_hessian call. Compared with the same problem + built without any sharing. */ +static problem *build_root_problem(bool shared) +{ + expr *g = new_exp(new_variable(3, 1, 0, 3)); + expr *g_obj = shared ? g : new_exp(new_variable(3, 1, 0, 3)); + expr *g_dup = shared ? g : new_exp(new_variable(3, 1, 0, 3)); + expr *constraints[2] = {g, g_dup}; + problem *prob = new_problem(new_sum(new_sin(g_obj), -1), constraints, 2, false); + problem_init_derivatives(prob); + return prob; +} + +const char *test_shared_dag_root_inside_other_root(void) +{ + double u[2][3] = {{0.1, -0.2, 0.3}, {-0.3, 0.4, 0.2}}; + double obj_w[2] = {1.5, -0.7}; + double w[2][6] = {{1.0, -2.0, 0.5, 0.3, 0.7, -1.1}, + {-0.5, 1.5, 2.0, 0.9, -0.2, 0.4}}; + + problem *shared = build_root_problem(true); + problem *plain = build_root_problem(false); + problem *probs[2] = {shared, plain}; + double H[2][9]; + + for (int pass = 0; pass < 2; pass++) + { + for (int k = 0; k < 2; k++) + { + problem_objective_forward(probs[k], u[pass]); + problem_constraint_forward(probs[k], u[pass]); + problem_gradient(probs[k]); + problem_jacobian(probs[k]); + problem_hessian(probs[k], obj_w[pass], w[pass]); + memset(H[k], 0, sizeof(H[k])); + CSR_matrix *L = probs[k]->lagrange_hessian; + for (int i = 0; i < 3; i++) + { + for (int jj = L->p[i]; jj < L->p[i + 1]; jj++) + { + H[k][3 * i + L->i[jj]] += L->x[jj]; + } + } + } + mu_assert("lagrange hessian differs from the unshared problem", + cmp_double_array(H[0], H[1], 9)); + mu_assert("lagrange hessian is zero", fabs(H[1][0]) > 1e-3); + } + + free_problem(shared); + free_problem(plain); + return 0; +} From 3b2f14dfc82417cbfbc61c581dd6e888a4cef372 Mon Sep 17 00:00:00 2001 From: dance858 Date: Thu, 26 Nov 2026 12:26:56 -0800 Subject: [PATCH 2/6] Make the forward epoch thread-local Threads can again run forward passes on DAGs that share no nodes, as before the per-pass epoch was introduced. Co-Authored-By: Claude Fable 5.2 --- include/expr.h | 11 ++++++++--- src/expr.c | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/include/expr.h b/include/expr.h index d1fb3666..49799e38 100644 --- a/include/expr.h +++ b/include/expr.h @@ -145,9 +145,14 @@ void free_expr(expr *node); /* Forward pass on a DAG. node->forward(node, u) starts a pass: it bumps * expr_fwd_epoch and evaluates the node. Atoms recurse into their children * with expr_forward, which evaluates a node at most once per pass. A new value - * invalidates a non-affine node's Jacobian. (The epoch is a global, so forward - * passes are not thread-safe.) */ -extern uint64_t expr_fwd_epoch; + * invalidates a non-affine node's Jacobian. The epoch is thread-local, so + * threads may run forward passes on DAGs that share no nodes. */ +#if defined(_MSC_VER) +#define SP_THREAD_LOCAL __declspec(thread) +#else +#define SP_THREAD_LOCAL __thread +#endif +extern SP_THREAD_LOCAL uint64_t expr_fwd_epoch; void expr_forward_root(struct expr *node, const double *u); static inline void expr_forward(struct expr *node, const double *u) { diff --git a/src/expr.c b/src/expr.c index 9f2bbc52..ac0db2b4 100644 --- a/src/expr.c +++ b/src/expr.c @@ -32,7 +32,7 @@ static bool expr_is_affine(const expr *node) return wk->affine_state == 1; } -uint64_t expr_fwd_epoch = 0; +SP_THREAD_LOCAL uint64_t expr_fwd_epoch = 0; void expr_forward_root(expr *node, const double *u) { From 708caced0683ef12b809d24f25ad311f5b930704 Mon Sep 17 00:00:00 2001 From: dance858 Date: Thu, 26 Nov 2026 12:32:47 -0800 Subject: [PATCH 3/6] Address review: affinity enum, cblas_dscal in scalar_mult, shorter comment Co-Authored-By: Claude Fable 5.2 --- include/expr.h | 13 ++++++++++--- src/atoms/affine/scalar_mult.c | 7 +++---- src/atoms/other/quad_form.c | 4 +--- src/expr.c | 6 +++--- 4 files changed, 17 insertions(+), 13 deletions(-) diff --git a/include/expr.h b/include/expr.h index 49799e38..6c21ff58 100644 --- a/include/expr.h +++ b/include/expr.h @@ -42,15 +42,22 @@ typedef bool (*is_affine_fn)(const struct expr *node); typedef void (*free_type_data_fn)(struct expr *node); typedef bool (*set_needs_refresh_children_fn)(struct expr *node); +/* Memoized result of node->is_affine(node). Affinity is structural, so it is + computed once. AFFINITY_UNKNOWN must be 0 (the workspace is calloc'ed). */ +typedef enum +{ + AFFINITY_UNKNOWN = 0, + AFFINE, + NON_AFFINE +} affinity; + /* Workspace for derivative computation */ typedef struct { double *dwork; int *iwork; - /* Memoized node->is_affine(node): 0 unknown, 1 affine, -1 not affine - (affinity is structural). */ - signed char affine_state; + affinity affine_state; /* memoized node->is_affine(node) */ /* True while the Jacobian values are valid, which lets eval_jacobian skip the node (and its whole subtree). Set by eval_jacobian; cleared by diff --git a/src/atoms/affine/scalar_mult.c b/src/atoms/affine/scalar_mult.c index 12b4dcdb..f1825084 100644 --- a/src/atoms/affine/scalar_mult.c +++ b/src/atoms/affine/scalar_mult.c @@ -16,6 +16,7 @@ * limitations under the License. */ #include "atoms/affine.h" +#include "sparsediff_linalg/cblas_wrapper.h" #include "sparsediff_linalg/tracked_alloc.h" #include "subexpr.h" #include @@ -98,10 +99,8 @@ static void eval_wsum_hess_impl(expr *node, const double *w) /* the scaling goes into the child's weights, never onto its Hessian (see eval_wsum_hess) */ - for (int i = 0; i < node->size; i++) - { - node->work->dwork[i] = a * w[i]; - } + memcpy(node->work->dwork, w, node->size * sizeof(double)); + cblas_dscal(node->size, a, node->work->dwork, 1); eval_wsum_hess(x, node->work->dwork); memcpy(node->wsum_hess->x, x->wsum_hess->x, node->wsum_hess->nnz * sizeof(double)); diff --git a/src/atoms/other/quad_form.c b/src/atoms/other/quad_form.c index 6d06b71e..a1447142 100644 --- a/src/atoms/other/quad_form.c +++ b/src/atoms/other/quad_form.c @@ -204,9 +204,7 @@ static void eval_wsum_hess_impl(expr *node, const double *w) cblas_dscal(H1->nnz, two_w, H1->x, 1); matrix_values_changed(H1); - /* term2 = 2w sum_i (Q f(x))_i nabla^2 f_i (dwork = Q f(x) from forward). - The factor 2w goes into the child's weights, never onto its Hessian - (see eval_wsum_hess). */ + /* term2 = 2w sum_i (Q f(x))_i nabla^2 f_i (dwork = Q f(x) from forward) */ for (int i = 0; i < qnode->n; i++) { qnode->hess_w[i] = two_w * node->work->dwork[i]; diff --git a/src/expr.c b/src/expr.c index ac0db2b4..3463d0ab 100644 --- a/src/expr.c +++ b/src/expr.c @@ -25,11 +25,11 @@ static bool expr_is_affine(const expr *node) { Expr_Work *wk = node->work; - if (wk->affine_state == 0) + if (wk->affine_state == AFFINITY_UNKNOWN) { - wk->affine_state = node->is_affine_impl(node) ? 1 : -1; + wk->affine_state = node->is_affine_impl(node) ? AFFINE : NON_AFFINE; } - return wk->affine_state == 1; + return wk->affine_state == AFFINE; } SP_THREAD_LOCAL uint64_t expr_fwd_epoch = 0; From d58f27fd4dbd08620d6c326eefc26d2d6a5792f5 Mon Sep 17 00:00:00 2001 From: dance858 Date: Thu, 26 Nov 2026 12:34:30 -0800 Subject: [PATCH 4/6] quad_form: scale the child's weights with cblas_dscal Co-Authored-By: Claude Fable 5.2 --- src/atoms/other/quad_form.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/atoms/other/quad_form.c b/src/atoms/other/quad_form.c index a1447142..432b412e 100644 --- a/src/atoms/other/quad_form.c +++ b/src/atoms/other/quad_form.c @@ -205,10 +205,8 @@ static void eval_wsum_hess_impl(expr *node, const double *w) matrix_values_changed(H1); /* term2 = 2w sum_i (Q f(x))_i nabla^2 f_i (dwork = Q f(x) from forward) */ - for (int i = 0; i < qnode->n; i++) - { - qnode->hess_w[i] = two_w * node->work->dwork[i]; - } + memcpy(qnode->hess_w, node->work->dwork, qnode->n * sizeof(double)); + cblas_dscal(qnode->n, two_w, qnode->hess_w, 1); eval_wsum_hess(x, qnode->hess_w); memcpy(H2->x, x->wsum_hess->x, x->wsum_hess->nnz * sizeof(double)); matrix_values_changed(H2); From 117e42669382b961543987b59c276371550855cd Mon Sep 17 00:00:00 2001 From: dance858 Date: Thu, 26 Nov 2026 12:39:29 -0800 Subject: [PATCH 5/6] Move expr_forward and the forward epoch into expr.c The epoch and its thread-local macro are now private to expr.c. Co-Authored-By: Claude Fable 5.2 --- include/expr.h | 29 ++++++++--------------------- src/expr.c | 23 ++++++++++++++++++++--- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/include/expr.h b/include/expr.h index 6c21ff58..3559d071 100644 --- a/include/expr.h +++ b/include/expr.h @@ -65,7 +65,7 @@ typedef struct pass. */ bool jacobian_evaluated; - /* expr_fwd_epoch of the last forward pass that evaluated this node */ + /* forward pass that last evaluated this node (see expr_forward) */ uint64_t fwd_epoch; /* Shared-node bookkeeping of eval_wsum_hess: the number of wsum_hess_init @@ -96,7 +96,7 @@ typedef struct expr double *value; matrix *jacobian; matrix *wsum_hess; - forward_fn forward; /* starts a forward pass: expr_forward_root */ + forward_fn forward; /* starts a forward pass */ forward_fn forward_impl; /* the atom's rule; recurses with expr_forward */ jacobian_init_fn jacobian_init_impl; wsum_hess_init_fn wsum_hess_init_impl; @@ -149,25 +149,12 @@ void init_expr(expr *node, int d1, int d2, int n_vars, forward_fn forward, void free_expr(expr *node); -/* Forward pass on a DAG. node->forward(node, u) starts a pass: it bumps - * expr_fwd_epoch and evaluates the node. Atoms recurse into their children - * with expr_forward, which evaluates a node at most once per pass. A new value - * invalidates a non-affine node's Jacobian. The epoch is thread-local, so - * threads may run forward passes on DAGs that share no nodes. */ -#if defined(_MSC_VER) -#define SP_THREAD_LOCAL __declspec(thread) -#else -#define SP_THREAD_LOCAL __thread -#endif -extern SP_THREAD_LOCAL uint64_t expr_fwd_epoch; -void expr_forward_root(struct expr *node, const double *u); -static inline void expr_forward(struct expr *node, const double *u) -{ - if (node->work->fwd_epoch == expr_fwd_epoch) return; - node->work->fwd_epoch = expr_fwd_epoch; - if (!node->is_affine(node)) node->work->jacobian_evaluated = false; - node->forward_impl(node, u); -} +/* Forward pass on a DAG. node->forward(node, u) starts a pass and evaluates + * the node. Atoms recurse into their children with expr_forward, which + * evaluates a node at most once per pass. A new value invalidates a non-affine + * node's Jacobian. Threads may run forward passes on DAGs that share no + * nodes. */ +void expr_forward(expr *node, const double *u); /* Guarded init: the impl runs once per node, however many parents it has. * diff --git a/src/expr.c b/src/expr.c index 3463d0ab..e7a8656d 100644 --- a/src/expr.c +++ b/src/expr.c @@ -32,11 +32,28 @@ static bool expr_is_affine(const expr *node) return wk->affine_state == AFFINE; } -SP_THREAD_LOCAL uint64_t expr_fwd_epoch = 0; +/* Thread-local storage in C99 (compiler extensions; C11 has _Thread_local) */ +#if defined(_MSC_VER) +#define EXPR_THREAD_LOCAL __declspec(thread) +#else +#define EXPR_THREAD_LOCAL __thread +#endif -void expr_forward_root(expr *node, const double *u) +/* Identifies the current forward pass; bumped by every top-level forward. */ +static EXPR_THREAD_LOCAL uint64_t fwd_epoch = 0; + +void expr_forward(expr *node, const double *u) +{ + if (node->work->fwd_epoch == fwd_epoch) return; + node->work->fwd_epoch = fwd_epoch; + if (!node->is_affine(node)) node->work->jacobian_evaluated = false; + node->forward_impl(node, u); +} + +/* node->forward of every node: starts a new pass */ +static void expr_forward_root(expr *node, const double *u) { - expr_fwd_epoch++; + fwd_epoch++; expr_forward(node, u); } From 6a7ea87528217fdeb62274cf9b0e9cbd2d74be23 Mon Sep 17 00:00:00 2001 From: dance858 Date: Thu, 26 Nov 2026 12:42:34 -0800 Subject: [PATCH 6/6] Trim comments Co-Authored-By: Claude Fable 5.2 --- include/expr.h | 31 ++++++++++--------------------- src/atoms/affine/neg.c | 3 +-- src/atoms/affine/scalar_mult.c | 2 -- src/expr.c | 3 ++- 4 files changed, 13 insertions(+), 26 deletions(-) diff --git a/include/expr.h b/include/expr.h index 3559d071..e9225aae 100644 --- a/include/expr.h +++ b/include/expr.h @@ -42,8 +42,7 @@ typedef bool (*is_affine_fn)(const struct expr *node); typedef void (*free_type_data_fn)(struct expr *node); typedef bool (*set_needs_refresh_children_fn)(struct expr *node); -/* Memoized result of node->is_affine(node). Affinity is structural, so it is - computed once. AFFINITY_UNKNOWN must be 0 (the workspace is calloc'ed). */ +/* AFFINITY_UNKNOWN must be 0 (the workspace is calloc'ed) */ typedef enum { AFFINITY_UNKNOWN = 0, @@ -59,22 +58,16 @@ typedef struct affinity affine_state; /* memoized node->is_affine(node) */ - /* True while the Jacobian values are valid, which lets eval_jacobian - skip the node (and its whole subtree). Set by eval_jacobian; cleared by - expr_set_needs_refresh and, for a non-affine node, by a new forward - pass. */ + /* The Jacobian values are valid. Cleared by expr_set_needs_refresh and, + for a non-affine node, by a new forward pass. */ bool jacobian_evaluated; /* forward pass that last evaluated this node (see expr_forward) */ uint64_t fwd_epoch; - /* Shared-node bookkeeping of eval_wsum_hess: the number of wsum_hess_init - calls received (in-edges), the eval_wsum_hess calls received so far in - the current pass, and the weights accumulated over them (allocated iff - hess_n_in > 1). */ - int hess_n_in; - int hess_visits; - double *hess_w; + int hess_n_in; /* number of wsum_hess_init calls (in-edges) */ + int hess_visits; /* eval_wsum_hess calls so far in this pass */ + double *hess_w; /* weights summed over them (iff hess_n_in > 1) */ double *local_jac_diag; /* cached f'(g(x)) diagonal */ matrix *hess_term1; /* Jg^T D Jg workspace */ matrix *hess_term2; /* child wsum_hess workspace */ @@ -152,8 +145,7 @@ void free_expr(expr *node); /* Forward pass on a DAG. node->forward(node, u) starts a pass and evaluates * the node. Atoms recurse into their children with expr_forward, which * evaluates a node at most once per pass. A new value invalidates a non-affine - * node's Jacobian. Threads may run forward passes on DAGs that share no - * nodes. */ + * node's Jacobian. */ void expr_forward(expr *node, const double *u); /* Guarded init: the impl runs once per node, however many parents it has. @@ -170,12 +162,9 @@ void wsum_hess_init(expr *node); * * eval_jacobian skips a node whose Jacobian is still valid. * - * eval_wsum_hess runs the impl of a node with several in-edges only once per - * pass: the Hessian is linear in the weights, so it accumulates the weights of - * all in-edges and evaluates on the last one. Earlier callers read zeros. This - * requires that an atom only ever adds a child's Hessian to its own (a scaling - * goes into the weights passed to the child). An affine node is skipped; its - * Hessian is zero. */ + * eval_wsum_hess evaluates a node with several in-edges once per pass, at the + * sum of their weights. An atom must therefore only add a child's Hessian to + * its own, never rescale it (a scaling goes into the child's weights). */ void eval_jacobian(expr *node); void eval_wsum_hess(expr *node, const double *w); diff --git a/src/atoms/affine/neg.c b/src/atoms/affine/neg.c index ffde875c..33f7bd88 100644 --- a/src/atoms/affine/neg.c +++ b/src/atoms/affine/neg.c @@ -71,8 +71,7 @@ static void wsum_hess_init_impl(expr *node) static void eval_wsum_hess_impl(expr *node, const double *w) { - /* For f(x) = -g(x): sum_i w_i Hf_i = sum_i (-w_i) Hg_i. The sign goes into - the child's weights, never onto its Hessian (see eval_wsum_hess). */ + /* For f(x) = -g(x): sum_i w_i Hf_i = sum_i (-w_i) Hg_i */ for (int i = 0; i < node->size; i++) { node->work->dwork[i] = -w[i]; diff --git a/src/atoms/affine/scalar_mult.c b/src/atoms/affine/scalar_mult.c index f1825084..18f10300 100644 --- a/src/atoms/affine/scalar_mult.c +++ b/src/atoms/affine/scalar_mult.c @@ -97,8 +97,6 @@ static void eval_wsum_hess_impl(expr *node, const double *w) expr *x = node->left; double a = ((scalar_mult_expr *) node)->param_source->value[0]; - /* the scaling goes into the child's weights, never onto its Hessian (see - eval_wsum_hess) */ memcpy(node->work->dwork, w, node->size * sizeof(double)); cblas_dscal(node->size, a, node->work->dwork, 1); eval_wsum_hess(x, node->work->dwork); diff --git a/src/expr.c b/src/expr.c index e7a8656d..3d97e498 100644 --- a/src/expr.c +++ b/src/expr.c @@ -39,7 +39,8 @@ static bool expr_is_affine(const expr *node) #define EXPR_THREAD_LOCAL __thread #endif -/* Identifies the current forward pass; bumped by every top-level forward. */ +/* Identifies the current forward pass; bumped by every top-level forward. + Thread-local, so threads may run passes on DAGs that share no nodes. */ static EXPR_THREAD_LOCAL uint64_t fwd_epoch = 0; void expr_forward(expr *node, const double *u)