From 3bbf58f25ae89e72f088a9270df85ec090a2eacd Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Thu, 3 Dec 2026 07:57:19 -0800 Subject: [PATCH 1/8] Adopt dense-preserving binary matrix sums Migrate all six binary allocator callers, pin sparsediff_linalg to its dense-sum implementation, and add structural/numerical regressions plus a deterministic before/after profiling target. Leave four-way and n-way sums unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CMakeLists.txt | 4 + README.md | 34 +++++++ sparsediff_linalg | 2 +- src/atoms/affine/add.c | 7 +- src/atoms/bivariate_full_dom/matmul.c | 5 +- src/atoms/bivariate_full_dom/multiply.c | 6 +- .../bivariate_restricted_dom/quad_over_lin.c | 4 +- src/atoms/elementwise_full_dom/common.c | 5 +- src/atoms/other/quad_form.c | 6 +- tests/all_tests.c | 3 + tests/issue47_models.h | 99 +++++++++++++++++++ .../test_quad_over_lin.h | 2 + tests/profiling/profile_binary_sums.c | 90 +++++++++++++++++ tests/wsum_hess/composite/test_binary_sums.h | 58 +++++++++++ tests/wsum_hess/other/test_quad_form_dense.h | 2 + 15 files changed, 300 insertions(+), 27 deletions(-) create mode 100644 tests/issue47_models.h create mode 100644 tests/profiling/profile_binary_sums.c create mode 100644 tests/wsum_hess/composite/test_binary_sums.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c736b9b..79c83531 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -128,6 +128,10 @@ if(NOT SKBUILD) if(PROFILE_ONLY) target_compile_definitions(all_tests PRIVATE PROFILE_ONLY) message(STATUS "Building ONLY profiling tests") + add_executable(binary_sum_profile tests/profiling/profile_binary_sums.c) + target_include_directories(binary_sum_profile PRIVATE + ${PROJECT_SOURCE_DIR}/tests) + target_link_libraries(binary_sum_profile dnlp_diff) endif() add_test(NAME AllTests COMMAND all_tests) diff --git a/README.md b/README.md index c0c5e401..dd11ede6 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,37 @@ This repository contains a **C implementation of the differentiation engine used The library provides low-level routines for computing sparse Jacobians and Hessians required by nonlinear programming solvers. The library is intended as a **backend component** and is not meant to be used directly by end users. +## Binary-sum performance regression + +The engine's binary-sum callers require the matching `sparsediff_linalg` +allocator API: `matrix *sum_matrices_alloc(A, B)`. Update the library submodule +and engine callers together. Four-way/n-way sums are unchanged. + +Run the deterministic issue #47 workload independently of the other profiles: + +```bash +cmake -S . -B build/profile -DCMAKE_BUILD_TYPE=Release -DPROFILE_ONLY=ON +cmake --build build/profile --target binary_sum_profile +VECLIB_MAXIMUM_THREADS=1 ./build/profile/binary_sum_profile > binary-sums.csv +``` + +On OpenBLAS, use `OPENBLAS_NUM_THREADS=1` instead. Keep the BLAS backend, thread +settings, compiler, host, and inputs identical for before/after comparisons. +The profile covers dense affine residuals, nonlinear compositions, a variable +intercept, two variable blocks, multinomial logit, and an incomplete sparse +control. Each case reports initialization separately, then the median/min/max +of 21 samples after five warmups. Gradient samples include root forward and +Jacobian evaluation; Hessian samples include those plus Hessian evaluation. +Legitimate affine caching remains enabled. No conversions, reference checks, +or printing are included in those evaluation timings. + +For a baseline, build engine `1efa7c26` with library `a8ee39ff` in an isolated +checkout, copying only `tests/issue47_models.h`, +`tests/profiling/profile_binary_sums.c`, and the profiling CMake target into it. +Do not copy the allocator migration. Compare the output value, gradient/Hessian +sums and norms, and structural counts alongside timings. Kind codes are +0=sparse, 1=permuted-dense, 2=stacked; `focus_h_kind=-1` means that intermediate +Hessian was not allocated. The logit intermediate still has an n-way sparse +Hessian sum, even when its Jacobian and the final Hessian are dense. +Wall-clock results are diagnostic, not CI pass/fail thresholds. + diff --git a/sparsediff_linalg b/sparsediff_linalg index b89ee0e5..39441a13 160000 --- a/sparsediff_linalg +++ b/sparsediff_linalg @@ -1 +1 @@ -Subproject commit b89ee0e5ff97096932a1de4af23b4a8279305610 +Subproject commit 39441a137b0945cb0dc7ba0ead8fe81a8baaffc3 diff --git a/src/atoms/affine/add.c b/src/atoms/affine/add.c index af863c56..58fb7f58 100644 --- a/src/atoms/affine/add.c +++ b/src/atoms/affine/add.c @@ -42,12 +42,7 @@ static void jacobian_init_impl(expr *node) jacobian_init(node->left); jacobian_init(node->right); - /* we never have to store more than the sum of children's nnz */ - int nnz_max = node->left->jacobian->nnz + node->right->jacobian->nnz; - node->jacobian = new_sparse_matrix_alloc(node->size, node->n_vars, nnz_max); - - /* fill sparsity pattern */ - sum_matrices_alloc(node->left->jacobian, node->right->jacobian, node->jacobian); + node->jacobian = sum_matrices_alloc(node->left->jacobian, node->right->jacobian); } static void eval_jacobian_impl(expr *node) diff --git a/src/atoms/bivariate_full_dom/matmul.c b/src/atoms/bivariate_full_dom/matmul.c index 3d0d2a45..6cfacb30 100644 --- a/src/atoms/bivariate_full_dom/matmul.c +++ b/src/atoms/bivariate_full_dom/matmul.c @@ -234,10 +234,7 @@ static void jacobian_init_chain_rule(expr *node) mnode->X = new_permuted_dense_full(m, k, NULL); mnode->term1 = BA_dense_kron_I_matrices_alloc(mnode->YT, m, f->jacobian); mnode->term2 = BA_kron_matrices_alloc(mnode->X, n, g->jacobian); - int max_nnz = mnode->term1->nnz + mnode->term2->nnz; - max_nnz = MIN(max_nnz, sat_mul_int(node->size, node->n_vars)); - node->jacobian = new_sparse_matrix_alloc(node->size, node->n_vars, max_nnz); - sum_matrices_alloc(mnode->term1, mnode->term2, node->jacobian); + node->jacobian = sum_matrices_alloc(mnode->term1, mnode->term2); } static void eval_jacobian_chain_rule(expr *node) diff --git a/src/atoms/bivariate_full_dom/multiply.c b/src/atoms/bivariate_full_dom/multiply.c index ac1f1807..fddad667 100644 --- a/src/atoms/bivariate_full_dom/multiply.c +++ b/src/atoms/bivariate_full_dom/multiply.c @@ -50,11 +50,7 @@ static void jacobian_init_impl(expr *node) { jacobian_init(node->left); jacobian_init(node->right); - int nnz_max = node->left->jacobian->nnz + node->right->jacobian->nnz; - node->jacobian = new_sparse_matrix_alloc(node->size, node->n_vars, nnz_max); - - /* fill sparsity pattern */ - sum_matrices_alloc(node->left->jacobian, node->right->jacobian, node->jacobian); + node->jacobian = sum_matrices_alloc(node->left->jacobian, node->right->jacobian); } static void eval_jacobian_impl(expr *node) diff --git a/src/atoms/bivariate_restricted_dom/quad_over_lin.c b/src/atoms/bivariate_restricted_dom/quad_over_lin.c index ceabde8b..327b4fff 100644 --- a/src/atoms/bivariate_restricted_dom/quad_over_lin.c +++ b/src/atoms/bivariate_restricted_dom/quad_over_lin.c @@ -100,9 +100,7 @@ static void jacobian_init_impl(expr *node) ey->i[0] = y->var_id; qnode->ypart = new_sparse_matrix(ey); - node->jacobian = - new_sparse_matrix_alloc(1, node->n_vars, qnode->xpart->nnz + 1); - sum_matrices_alloc(qnode->xpart, qnode->ypart, node->jacobian); + node->jacobian = sum_matrices_alloc(qnode->xpart, qnode->ypart); } } diff --git a/src/atoms/elementwise_full_dom/common.c b/src/atoms/elementwise_full_dom/common.c index 64b9684a..3fd60cac 100644 --- a/src/atoms/elementwise_full_dom/common.c +++ b/src/atoms/elementwise_full_dom/common.c @@ -116,11 +116,8 @@ void wsum_hess_init_elementwise(expr *node) node->work->hess_term2 = copy_sparsity_matrices_alloc(child->wsum_hess); /* wsum_hess = term1 + term2 */ - int max_nnz = node->work->hess_term1->nnz + node->work->hess_term2->nnz; node->wsum_hess = - new_sparse_matrix_alloc(node->n_vars, node->n_vars, max_nnz); - sum_matrices_alloc(node->work->hess_term1, node->work->hess_term2, - node->wsum_hess); + sum_matrices_alloc(node->work->hess_term1, node->work->hess_term2); } } } diff --git a/src/atoms/other/quad_form.c b/src/atoms/other/quad_form.c index 432b412e..d963b276 100644 --- a/src/atoms/other/quad_form.c +++ b/src/atoms/other/quad_form.c @@ -173,10 +173,8 @@ static void wsum_hess_init_impl(expr *node) node->work->hess_term2 = copy_sparsity_matrices_alloc(x->wsum_hess); /* hess = term1 + term2 */ - int max_nnz = node->work->hess_term1->nnz + node->work->hess_term2->nnz; - node->wsum_hess = new_sparse_matrix_alloc(node->n_vars, node->n_vars, max_nnz); - sum_matrices_alloc(node->work->hess_term1, node->work->hess_term2, - node->wsum_hess); + node->wsum_hess = + sum_matrices_alloc(node->work->hess_term1, node->work->hess_term2); } static void eval_wsum_hess_impl(expr *node, const double *w) diff --git a/tests/all_tests.c b/tests/all_tests.c index 32b15cd7..71590470 100644 --- a/tests/all_tests.c +++ b/tests/all_tests.c @@ -85,6 +85,7 @@ #include "wsum_hess/bivariate_restricted_dom/test_rel_entr.h" #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_binary_sums.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" @@ -119,6 +120,8 @@ int main(void) #ifndef PROFILE_ONLY printf("--- Forward Pass Tests ---\n"); + mu_run_test(test_binary_sum_models, tests_run); + mu_run_test(test_binary_sum_matmul_composition, tests_run); mu_run_test(test_variable, tests_run); mu_run_test(test_constant, tests_run); mu_run_test(test_addition, tests_run); diff --git a/tests/issue47_models.h b/tests/issue47_models.h new file mode 100644 index 00000000..b2957f80 --- /dev/null +++ b/tests/issue47_models.h @@ -0,0 +1,99 @@ +#ifndef ISSUE47_MODELS_H +#define ISSUE47_MODELS_H + +#include "atoms/affine.h" +#include "atoms/bivariate_full_dom.h" +#include "atoms/elementwise_full_dom.h" +#include + +enum +{ + SUM47_SQUARE, + SUM47_RESIDUAL, + SUM47_LOGISTIC, + SUM47_ABS, + SUM47_SMOOTH, + SUM47_RESIDUAL_ABS, + SUM47_RESIDUAL_SMOOTH, + SUM47_INTERCEPT, + SUM47_TWO_BLOCKS, + SUM47_LOGIT, + SUM47_SPARSE +}; + +static expr *sum47_model(int model, int m, int d, int classes, expr **focus, + double **inputs) +{ + int nv = model == SUM47_LOGIT ? d * classes + : model == SUM47_INTERCEPT ? d + 1 + : model == SUM47_TWO_BLOCKS ? 2 * d + : d; + double *a = (double *) malloc((size_t) m * d * sizeof(double)); + *inputs = (double *) malloc((size_t) nv * sizeof(double)); + for (int j = 0; j < nv; j++) (*inputs)[j] = 0.1 + (j % 7) * 0.01; + for (int j = 0; j < m * d; j++) a[j] = 0.02 + (j % 17) * 0.002; + expr *x = new_variable(d, model == SUM47_LOGIT ? classes : 1, 0, nv); + expr *z; + if (model == SUM47_SPARSE) + { + CSR_matrix *s = new_CSR_matrix(m, d, m); + for (int i = 0; i < m; i++) + { + s->p[i] = i; + s->i[i] = i % d; + s->x[i] = 0.5; + } + s->p[m] = m; + z = new_left_matmul(NULL, x, s); + free_CSR_matrix(s); + } + else + { + z = new_left_matmul_dense(NULL, x, m, d, a); + } + if (model == SUM47_LOGIT) + { + expr *e = new_exp(z); + expr *inv = new_power(new_reshape(new_sum(e, 1), m, 1), -1.0); + z = new_elementwise_mult(e, new_broadcast(inv, m, classes)); + *focus = z; + double *y = (double *) calloc((size_t) m * classes, sizeof(double)); + for (int i = 0; i < m; i++) y[(i % classes) * m + i] = 1.0; + z = new_add(z, new_neg(new_parameter(m, classes, -1, nv, y))); + free(y); + } + else + { + if (model == SUM47_INTERCEPT) + z = new_add(z, new_promote(new_variable(1, 1, d, nv), m, 1)); + else if (model == SUM47_TWO_BLOCKS) + z = new_add( + z, new_left_matmul_dense(NULL, new_variable(d, 1, d, nv), m, d, a)); + else if (model == SUM47_RESIDUAL || model == SUM47_LOGISTIC || + model == SUM47_RESIDUAL_ABS || model == SUM47_RESIDUAL_SMOOTH || + model == SUM47_SPARSE) + { + double b = -0.01; + z = new_add(z, new_promote(new_parameter(1, 1, -1, nv, &b), m, 1)); + } + *focus = z; + } + free(a); + if (model == SUM47_LOGISTIC) + z = new_logistic(z); + else + { + z = new_power(z, 2.0); + if (model == SUM47_SMOOTH || model == SUM47_RESIDUAL_SMOOTH) + { + double one = 1.0; + z = new_add(z, new_promote(new_parameter(1, 1, -1, nv, &one), m, 1)); + } + if (model == SUM47_ABS || model == SUM47_SMOOTH || + model == SUM47_RESIDUAL_ABS || model == SUM47_RESIDUAL_SMOOTH) + z = new_power(z, 0.5); + } + return new_sum(z, -1); +} + +#endif diff --git a/tests/jacobian_tests/bivariate_restricted_dom/test_quad_over_lin.h b/tests/jacobian_tests/bivariate_restricted_dom/test_quad_over_lin.h index 998d78e5..1b78056a 100644 --- a/tests/jacobian_tests/bivariate_restricted_dom/test_quad_over_lin.h +++ b/tests/jacobian_tests/bivariate_restricted_dom/test_quad_over_lin.h @@ -122,6 +122,8 @@ const char *test_quad_over_lin4(void) eval_jacobian(node); double expected_vals[4] = {-76.25, 71.0, 94.0, 117.0}; + mu_assert("composed quad_over_lin keeps full row dense", + node->jacobian->kind == MATRIX_PERMUTED_DENSE); int expected_Ap[2] = {0, 4}; int expected_Ai[4] = {2, 5, 6, 7}; diff --git a/tests/profiling/profile_binary_sums.c b/tests/profiling/profile_binary_sums.c new file mode 100644 index 00000000..4e2032a2 --- /dev/null +++ b/tests/profiling/profile_binary_sums.c @@ -0,0 +1,90 @@ +#include "Timer.h" +#include "issue47_models.h" +#include +#include + +static int compare_samples(const void *a, const void *b) +{ + double x = *(const double *) a, y = *(const double *) b; + return (x > y) - (x < y); +} + +int main(void) +{ + const char *names[] = { + "square", "residual", "logistic", "abs", + "smooth", "residual_abs", "residual_smooth", "intercept", + "two_blocks", "logit", "sparse"}; + enum + { + WARMUP = 5, + SAMPLES = 21 + }; + puts("model,m,d,K,init_ms,j_kind,j_nnz,h_kind,gradient_ms,g_min_ms,g_max_ms," + "hessian_ms,h_min_ms,h_max_ms,value,gradient_sum,hessian_sum," + "gradient_norm2,hessian_norm2,focus_h_kind,h_nnz"); + for (int model = SUM47_SQUARE; model <= SUM47_SPARSE; model++) + { + int m = model == SUM47_LOGIT ? 1000 : 2000; + int d = model == SUM47_LOGIT ? 20 : 400; + int k = model == SUM47_LOGIT ? 20 : 1; + double *u; + expr *focus; + expr *root = sum47_model(model, m, d, k, &focus, &u); + Timer timer; + clock_gettime(CLOCK_MONOTONIC, &timer.start); + jacobian_init(root); + wsum_hess_init(root); + clock_gettime(CLOCK_MONOTONIC, &timer.end); + double init_ms = GET_ELAPSED_SECONDS(timer) * 1000.0; + double g[SAMPLES], h[SAMPLES], w = 1.0; + for (int sample = -WARMUP; sample < SAMPLES; sample++) + { + clock_gettime(CLOCK_MONOTONIC, &timer.start); + root->forward(root, u); + eval_jacobian(root); + clock_gettime(CLOCK_MONOTONIC, &timer.end); + if (sample >= 0) g[sample] = GET_ELAPSED_SECONDS(timer) * 1000.0; + + clock_gettime(CLOCK_MONOTONIC, &timer.start); + root->forward(root, u); + eval_jacobian(root); + eval_wsum_hess(root, &w); + clock_gettime(CLOCK_MONOTONIC, &timer.end); + if (sample >= 0) h[sample] = GET_ELAPSED_SECONDS(timer) * 1000.0; + } + double gs = 0.0, hs = 0.0, gn = 0.0, hn = 0.0; + for (int i = 0; i < root->jacobian->nnz; i++) + { + double v = root->jacobian->x[i]; + gs += v; + gn += v * v; + } + for (int i = 0; i < root->wsum_hess->nnz; i++) + { + double v = root->wsum_hess->x[i]; + hs += v; + hn += v * v; + } + if (!isfinite(root->value[0]) || !isfinite(gs) || !isfinite(hs) || + !isfinite(gn) || !isfinite(hn)) + { + fprintf(stderr, "Nonfinite benchmark result: %s\n", names[model]); + return 1; + } + qsort(g, SAMPLES, sizeof(double), compare_samples); + qsort(h, SAMPLES, sizeof(double), compare_samples); + printf("%s,%d,%d,%d,%.6f,%d,%d,%d,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f," + "%.12g,%.12g,%.12g,%.12g,%.12g,%d,%d\n", + names[model], m, d, k, init_ms, focus->jacobian->kind, + focus->jacobian->nnz, root->wsum_hess->kind, g[SAMPLES / 2], g[0], + g[SAMPLES - 1], h[SAMPLES / 2], h[0], h[SAMPLES - 1], root->value[0], + gs, hs, sqrt(gn), sqrt(hn), + focus->wsum_hess ? (int) focus->wsum_hess->kind : -1, + root->wsum_hess->nnz); + fflush(stdout); + free_expr(root); + free(u); + } + return 0; +} diff --git a/tests/wsum_hess/composite/test_binary_sums.h b/tests/wsum_hess/composite/test_binary_sums.h new file mode 100644 index 00000000..33336330 --- /dev/null +++ b/tests/wsum_hess/composite/test_binary_sums.h @@ -0,0 +1,58 @@ +#ifndef TEST_BINARY_SUMS_H +#define TEST_BINARY_SUMS_H + +#include "issue47_models.h" +#include "minunit.h" +#include "numerical_diff.h" + +const char *test_binary_sum_models(void) +{ + for (int model = SUM47_SQUARE; model <= SUM47_SPARSE; model++) + { + double *u, w = 1.0; + expr *focus; + expr *root = sum47_model(model, 5, 3, 3, &focus, &u); + jacobian_init(root); + wsum_hess_init(root); + matrix_kind expected = + model == SUM47_SPARSE ? MATRIX_SPARSE : MATRIX_PERMUTED_DENSE; + mu_assert("binary model Jacobian kind", focus->jacobian->kind == expected); + int nnz = model == SUM47_SPARSE ? 5 : focus->size * root->n_vars; + mu_assert("binary model Jacobian nnz", focus->jacobian->nnz == nnz); + if (model != SUM47_LOGIT && model != SUM47_SPARSE) + mu_assert("binary model Hessian kind", + root->wsum_hess->kind == MATRIX_PERMUTED_DENSE); + for (int round = 0; round < 2; round++) + { + mu_assert("binary model gradient", + check_jacobian_num(root, u, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("binary model Hessian", + check_wsum_hess(root, u, &w, NUMERICAL_DIFF_DEFAULT_H)); + for (int i = 0; i < root->n_vars; i++) u[i] += 0.03; + } + free_expr(root); + free(u); + } + return NULL; +} + +const char *test_binary_sum_matmul_composition(void) +{ + double a[4] = {1, 2, -1, 3}, b[4] = {2, -1, 3, 1}; + double u[2] = {0.2, 0.3}, w = 1; + expr *x = new_variable(2, 1, 0, 2); + expr *left = new_left_matmul_dense(NULL, x, 2, 2, a); + expr *right = new_left_matmul_dense(NULL, x, 2, 2, b); + expr *root = new_matmul(new_transpose(left), right); + mu_assert("composed matmul gradient", + check_jacobian_num(root, u, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("composed matmul binary Jacobian kind", + root->jacobian->kind == MATRIX_PERMUTED_DENSE && + root->jacobian->nnz == 2); + mu_assert("composed matmul Hessian", + check_wsum_hess(root, u, &w, NUMERICAL_DIFF_DEFAULT_H)); + free_expr(root); + return NULL; +} + +#endif diff --git a/tests/wsum_hess/other/test_quad_form_dense.h b/tests/wsum_hess/other/test_quad_form_dense.h index bc44953a..6a2515f7 100644 --- a/tests/wsum_hess/other/test_quad_form_dense.h +++ b/tests/wsum_hess/other/test_quad_form_dense.h @@ -96,6 +96,8 @@ const char *test_wsum_hess_quad_form_dense_exp(void) mu_assert("dense quad_form nonlinear composition wsum_hess failed", check_wsum_hess(node, u_vals, &w, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("quad_form binary Hessian sum remains dense", + node->wsum_hess->kind == MATRIX_PERMUTED_DENSE); free_expr(node); return 0; From 4bc33561c4b6db6a66e6766ec7d8d51f3b893629 Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Thu, 3 Dec 2026 08:17:06 -0800 Subject: [PATCH 2/8] Follow library README cleanup Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sparsediff_linalg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sparsediff_linalg b/sparsediff_linalg index 39441a13..54634669 160000 --- a/sparsediff_linalg +++ b/sparsediff_linalg @@ -1 +1 @@ -Subproject commit 39441a137b0945cb0dc7ba0ead8fe81a8baaffc3 +Subproject commit 546346692981304f8522389cad87d4dc75cb02e3 From 1c61b331381095e664f6f57edece090ac207f89d Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Thu, 3 Dec 2026 08:24:05 -0800 Subject: [PATCH 3/8] Follow binary sum readability cleanup Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sparsediff_linalg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sparsediff_linalg b/sparsediff_linalg index 54634669..dc6b77d0 160000 --- a/sparsediff_linalg +++ b/sparsediff_linalg @@ -1 +1 @@ -Subproject commit 546346692981304f8522389cad87d4dc75cb02e3 +Subproject commit dc6b77d0e4732d373c120badbaea35f24d231caf From dcd4f2bceea9fdbecd24e4d6e7475fd4b3ed0071 Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Thu, 3 Dec 2026 08:34:05 -0800 Subject: [PATCH 4/8] Follow matrix sum function reordering Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sparsediff_linalg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sparsediff_linalg b/sparsediff_linalg index dc6b77d0..0e711676 160000 --- a/sparsediff_linalg +++ b/sparsediff_linalg @@ -1 +1 @@ -Subproject commit dc6b77d0e4732d373c120badbaea35f24d231caf +Subproject commit 0e711676b8a2d827c5a424e3344a441e3998029f From 7a32c602dcd8bbd9fc61223d2257543fbe64e99d Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Thu, 3 Dec 2026 08:40:35 -0800 Subject: [PATCH 5/8] Follow dense-pattern helper extraction Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sparsediff_linalg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sparsediff_linalg b/sparsediff_linalg index 0e711676..a37a3a9a 160000 --- a/sparsediff_linalg +++ b/sparsediff_linalg @@ -1 +1 @@ -Subproject commit 0e711676b8a2d827c5a424e3344a441e3998029f +Subproject commit a37a3a9aa9d33d9b8d1bc0329a8a27a6751598f8 From d3df3b54452ace754633793208d15550971da765 Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Thu, 3 Dec 2026 09:10:13 -0800 Subject: [PATCH 6/8] Track reviewed binary sum test cleanup Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sparsediff_linalg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sparsediff_linalg b/sparsediff_linalg index a37a3a9a..fd7bd06d 160000 --- a/sparsediff_linalg +++ b/sparsediff_linalg @@ -1 +1 @@ -Subproject commit a37a3a9aa9d33d9b8d1bc0329a8a27a6751598f8 +Subproject commit fd7bd06dd3c4bebc74e665cc79b374f7c941982f From f6d0676bb4c36d372b79e506ed7f0d3507fab216 Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Thu, 3 Dec 2026 09:25:45 -0800 Subject: [PATCH 7/8] Track binary sum map helper rename Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sparsediff_linalg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sparsediff_linalg b/sparsediff_linalg index fd7bd06d..0e121596 160000 --- a/sparsediff_linalg +++ b/sparsediff_linalg @@ -1 +1 @@ -Subproject commit fd7bd06dd3c4bebc74e665cc79b374f7c941982f +Subproject commit 0e1215967388595f7d89a12480ed361b7d15a1bd From f7b398b04a3e9743fb71a0b3021e9209b5d07eb3 Mon Sep 17 00:00:00 2001 From: dance858 Date: Thu, 3 Dec 2026 13:03:56 -0800 Subject: [PATCH 8/8] Simplify binary sum tests and pin merged sparsediff_linalg Replace the issue-47 model factory with four small explicit tests, drop the standalone profiling target and the README section, and pin the submodule to the merge commit of sparsediff_linalg#48. Co-Authored-By: Claude Fable 5.2 --- CMakeLists.txt | 4 - README.md | 34 ---- sparsediff_linalg | 2 +- tests/all_tests.c | 6 +- tests/issue47_models.h | 99 ------------ tests/profiling/profile_binary_sums.c | 90 ----------- tests/wsum_hess/composite/test_binary_sums.h | 154 ++++++++++++++----- 7 files changed, 121 insertions(+), 268 deletions(-) delete mode 100644 tests/issue47_models.h delete mode 100644 tests/profiling/profile_binary_sums.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 79c83531..8c736b9b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -128,10 +128,6 @@ if(NOT SKBUILD) if(PROFILE_ONLY) target_compile_definitions(all_tests PRIVATE PROFILE_ONLY) message(STATUS "Building ONLY profiling tests") - add_executable(binary_sum_profile tests/profiling/profile_binary_sums.c) - target_include_directories(binary_sum_profile PRIVATE - ${PROJECT_SOURCE_DIR}/tests) - target_link_libraries(binary_sum_profile dnlp_diff) endif() add_test(NAME AllTests COMMAND all_tests) diff --git a/README.md b/README.md index dd11ede6..c0c5e401 100644 --- a/README.md +++ b/README.md @@ -4,37 +4,3 @@ This repository contains a **C implementation of the differentiation engine used The library provides low-level routines for computing sparse Jacobians and Hessians required by nonlinear programming solvers. The library is intended as a **backend component** and is not meant to be used directly by end users. -## Binary-sum performance regression - -The engine's binary-sum callers require the matching `sparsediff_linalg` -allocator API: `matrix *sum_matrices_alloc(A, B)`. Update the library submodule -and engine callers together. Four-way/n-way sums are unchanged. - -Run the deterministic issue #47 workload independently of the other profiles: - -```bash -cmake -S . -B build/profile -DCMAKE_BUILD_TYPE=Release -DPROFILE_ONLY=ON -cmake --build build/profile --target binary_sum_profile -VECLIB_MAXIMUM_THREADS=1 ./build/profile/binary_sum_profile > binary-sums.csv -``` - -On OpenBLAS, use `OPENBLAS_NUM_THREADS=1` instead. Keep the BLAS backend, thread -settings, compiler, host, and inputs identical for before/after comparisons. -The profile covers dense affine residuals, nonlinear compositions, a variable -intercept, two variable blocks, multinomial logit, and an incomplete sparse -control. Each case reports initialization separately, then the median/min/max -of 21 samples after five warmups. Gradient samples include root forward and -Jacobian evaluation; Hessian samples include those plus Hessian evaluation. -Legitimate affine caching remains enabled. No conversions, reference checks, -or printing are included in those evaluation timings. - -For a baseline, build engine `1efa7c26` with library `a8ee39ff` in an isolated -checkout, copying only `tests/issue47_models.h`, -`tests/profiling/profile_binary_sums.c`, and the profiling CMake target into it. -Do not copy the allocator migration. Compare the output value, gradient/Hessian -sums and norms, and structural counts alongside timings. Kind codes are -0=sparse, 1=permuted-dense, 2=stacked; `focus_h_kind=-1` means that intermediate -Hessian was not allocated. The logit intermediate still has an n-way sparse -Hessian sum, even when its Jacobian and the final Hessian are dense. -Wall-clock results are diagnostic, not CI pass/fail thresholds. - diff --git a/sparsediff_linalg b/sparsediff_linalg index 0e121596..04c108e8 160000 --- a/sparsediff_linalg +++ b/sparsediff_linalg @@ -1 +1 @@ -Subproject commit 0e1215967388595f7d89a12480ed361b7d15a1bd +Subproject commit 04c108e8335c789398a24f30864acdf09a5137d0 diff --git a/tests/all_tests.c b/tests/all_tests.c index 71590470..123da9bb 100644 --- a/tests/all_tests.c +++ b/tests/all_tests.c @@ -120,8 +120,6 @@ int main(void) #ifndef PROFILE_ONLY printf("--- Forward Pass Tests ---\n"); - mu_run_test(test_binary_sum_models, tests_run); - mu_run_test(test_binary_sum_matmul_composition, tests_run); mu_run_test(test_variable, tests_run); mu_run_test(test_constant, tests_run); mu_run_test(test_addition, tests_run); @@ -397,6 +395,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_binary_sum_add_dense, tests_run); + mu_run_test(test_binary_sum_multiply_dense, tests_run); + mu_run_test(test_binary_sum_multiply_sparse, tests_run); + mu_run_test(test_binary_sum_matmul_dense, 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); diff --git a/tests/issue47_models.h b/tests/issue47_models.h deleted file mode 100644 index b2957f80..00000000 --- a/tests/issue47_models.h +++ /dev/null @@ -1,99 +0,0 @@ -#ifndef ISSUE47_MODELS_H -#define ISSUE47_MODELS_H - -#include "atoms/affine.h" -#include "atoms/bivariate_full_dom.h" -#include "atoms/elementwise_full_dom.h" -#include - -enum -{ - SUM47_SQUARE, - SUM47_RESIDUAL, - SUM47_LOGISTIC, - SUM47_ABS, - SUM47_SMOOTH, - SUM47_RESIDUAL_ABS, - SUM47_RESIDUAL_SMOOTH, - SUM47_INTERCEPT, - SUM47_TWO_BLOCKS, - SUM47_LOGIT, - SUM47_SPARSE -}; - -static expr *sum47_model(int model, int m, int d, int classes, expr **focus, - double **inputs) -{ - int nv = model == SUM47_LOGIT ? d * classes - : model == SUM47_INTERCEPT ? d + 1 - : model == SUM47_TWO_BLOCKS ? 2 * d - : d; - double *a = (double *) malloc((size_t) m * d * sizeof(double)); - *inputs = (double *) malloc((size_t) nv * sizeof(double)); - for (int j = 0; j < nv; j++) (*inputs)[j] = 0.1 + (j % 7) * 0.01; - for (int j = 0; j < m * d; j++) a[j] = 0.02 + (j % 17) * 0.002; - expr *x = new_variable(d, model == SUM47_LOGIT ? classes : 1, 0, nv); - expr *z; - if (model == SUM47_SPARSE) - { - CSR_matrix *s = new_CSR_matrix(m, d, m); - for (int i = 0; i < m; i++) - { - s->p[i] = i; - s->i[i] = i % d; - s->x[i] = 0.5; - } - s->p[m] = m; - z = new_left_matmul(NULL, x, s); - free_CSR_matrix(s); - } - else - { - z = new_left_matmul_dense(NULL, x, m, d, a); - } - if (model == SUM47_LOGIT) - { - expr *e = new_exp(z); - expr *inv = new_power(new_reshape(new_sum(e, 1), m, 1), -1.0); - z = new_elementwise_mult(e, new_broadcast(inv, m, classes)); - *focus = z; - double *y = (double *) calloc((size_t) m * classes, sizeof(double)); - for (int i = 0; i < m; i++) y[(i % classes) * m + i] = 1.0; - z = new_add(z, new_neg(new_parameter(m, classes, -1, nv, y))); - free(y); - } - else - { - if (model == SUM47_INTERCEPT) - z = new_add(z, new_promote(new_variable(1, 1, d, nv), m, 1)); - else if (model == SUM47_TWO_BLOCKS) - z = new_add( - z, new_left_matmul_dense(NULL, new_variable(d, 1, d, nv), m, d, a)); - else if (model == SUM47_RESIDUAL || model == SUM47_LOGISTIC || - model == SUM47_RESIDUAL_ABS || model == SUM47_RESIDUAL_SMOOTH || - model == SUM47_SPARSE) - { - double b = -0.01; - z = new_add(z, new_promote(new_parameter(1, 1, -1, nv, &b), m, 1)); - } - *focus = z; - } - free(a); - if (model == SUM47_LOGISTIC) - z = new_logistic(z); - else - { - z = new_power(z, 2.0); - if (model == SUM47_SMOOTH || model == SUM47_RESIDUAL_SMOOTH) - { - double one = 1.0; - z = new_add(z, new_promote(new_parameter(1, 1, -1, nv, &one), m, 1)); - } - if (model == SUM47_ABS || model == SUM47_SMOOTH || - model == SUM47_RESIDUAL_ABS || model == SUM47_RESIDUAL_SMOOTH) - z = new_power(z, 0.5); - } - return new_sum(z, -1); -} - -#endif diff --git a/tests/profiling/profile_binary_sums.c b/tests/profiling/profile_binary_sums.c deleted file mode 100644 index 4e2032a2..00000000 --- a/tests/profiling/profile_binary_sums.c +++ /dev/null @@ -1,90 +0,0 @@ -#include "Timer.h" -#include "issue47_models.h" -#include -#include - -static int compare_samples(const void *a, const void *b) -{ - double x = *(const double *) a, y = *(const double *) b; - return (x > y) - (x < y); -} - -int main(void) -{ - const char *names[] = { - "square", "residual", "logistic", "abs", - "smooth", "residual_abs", "residual_smooth", "intercept", - "two_blocks", "logit", "sparse"}; - enum - { - WARMUP = 5, - SAMPLES = 21 - }; - puts("model,m,d,K,init_ms,j_kind,j_nnz,h_kind,gradient_ms,g_min_ms,g_max_ms," - "hessian_ms,h_min_ms,h_max_ms,value,gradient_sum,hessian_sum," - "gradient_norm2,hessian_norm2,focus_h_kind,h_nnz"); - for (int model = SUM47_SQUARE; model <= SUM47_SPARSE; model++) - { - int m = model == SUM47_LOGIT ? 1000 : 2000; - int d = model == SUM47_LOGIT ? 20 : 400; - int k = model == SUM47_LOGIT ? 20 : 1; - double *u; - expr *focus; - expr *root = sum47_model(model, m, d, k, &focus, &u); - Timer timer; - clock_gettime(CLOCK_MONOTONIC, &timer.start); - jacobian_init(root); - wsum_hess_init(root); - clock_gettime(CLOCK_MONOTONIC, &timer.end); - double init_ms = GET_ELAPSED_SECONDS(timer) * 1000.0; - double g[SAMPLES], h[SAMPLES], w = 1.0; - for (int sample = -WARMUP; sample < SAMPLES; sample++) - { - clock_gettime(CLOCK_MONOTONIC, &timer.start); - root->forward(root, u); - eval_jacobian(root); - clock_gettime(CLOCK_MONOTONIC, &timer.end); - if (sample >= 0) g[sample] = GET_ELAPSED_SECONDS(timer) * 1000.0; - - clock_gettime(CLOCK_MONOTONIC, &timer.start); - root->forward(root, u); - eval_jacobian(root); - eval_wsum_hess(root, &w); - clock_gettime(CLOCK_MONOTONIC, &timer.end); - if (sample >= 0) h[sample] = GET_ELAPSED_SECONDS(timer) * 1000.0; - } - double gs = 0.0, hs = 0.0, gn = 0.0, hn = 0.0; - for (int i = 0; i < root->jacobian->nnz; i++) - { - double v = root->jacobian->x[i]; - gs += v; - gn += v * v; - } - for (int i = 0; i < root->wsum_hess->nnz; i++) - { - double v = root->wsum_hess->x[i]; - hs += v; - hn += v * v; - } - if (!isfinite(root->value[0]) || !isfinite(gs) || !isfinite(hs) || - !isfinite(gn) || !isfinite(hn)) - { - fprintf(stderr, "Nonfinite benchmark result: %s\n", names[model]); - return 1; - } - qsort(g, SAMPLES, sizeof(double), compare_samples); - qsort(h, SAMPLES, sizeof(double), compare_samples); - printf("%s,%d,%d,%d,%.6f,%d,%d,%d,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f," - "%.12g,%.12g,%.12g,%.12g,%.12g,%d,%d\n", - names[model], m, d, k, init_ms, focus->jacobian->kind, - focus->jacobian->nnz, root->wsum_hess->kind, g[SAMPLES / 2], g[0], - g[SAMPLES - 1], h[SAMPLES / 2], h[0], h[SAMPLES - 1], root->value[0], - gs, hs, sqrt(gn), sqrt(hn), - focus->wsum_hess ? (int) focus->wsum_hess->kind : -1, - root->wsum_hess->nnz); - fflush(stdout); - free_expr(root); - free(u); - } - return 0; -} diff --git a/tests/wsum_hess/composite/test_binary_sums.h b/tests/wsum_hess/composite/test_binary_sums.h index 33336330..225c02d7 100644 --- a/tests/wsum_hess/composite/test_binary_sums.h +++ b/tests/wsum_hess/composite/test_binary_sums.h @@ -1,58 +1,136 @@ #ifndef TEST_BINARY_SUMS_H #define TEST_BINARY_SUMS_H -#include "issue47_models.h" +#include "atoms/affine.h" +#include "atoms/bivariate_full_dom.h" +#include "atoms/elementwise_full_dom.h" #include "minunit.h" #include "numerical_diff.h" -const char *test_binary_sum_models(void) +/* A binary sum of two matrices that together fill a dense block must stay + dense instead of falling back to a sparse matrix. */ + +/* sum(sqrt(1 + (A x + A y)^2)): the Jacobian of the add and the Hessian of + the outer power are both binary sums with a dense result. */ +const char *test_binary_sum_add_dense(void) +{ + double A[12] = {1, 2, -1, 3, 2, -1, 3, 1, -2, 1, 1, 2}; + double u[6] = {0.2, 0.3, -0.1, 0.4, 0.1, -0.2}; + double w = 1.0; + double one = 1.0; + + expr *x = new_variable(3, 1, 0, 6); + expr *y = new_variable(3, 1, 3, 6); + expr *Ax = new_left_matmul_dense(NULL, x, 4, 3, A); + expr *Ay = new_left_matmul_dense(NULL, y, 4, 3, A); + expr *z = new_add(Ax, Ay); + expr *shifted = new_add(new_power(z, 2.0), + new_promote(new_parameter(1, 1, -1, 6, &one), 4, 1)); + expr *root = new_sum(new_power(shifted, 0.5), -1); + + mu_assert("add dense jacobian check failed", + check_jacobian_num(root, u, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("add dense wsum_hess check failed", + check_wsum_hess(root, u, &w, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("add jacobian should be dense", + z->jacobian->kind == MATRIX_PERMUTED_DENSE && z->jacobian->nnz == 24); + mu_assert("elementwise wsum_hess should be dense", + root->wsum_hess->kind == MATRIX_PERMUTED_DENSE && + root->wsum_hess->nnz == 36); + + free_expr(root); + return 0; +} + +/* (A x) * (B x) elementwise: the Jacobian is a binary sum of two dense + matrices. */ +const char *test_binary_sum_multiply_dense(void) +{ + double A[12] = {1, 2, -1, 3, 2, -1, 3, 1, -2, 1, 1, 2}; + double B[12] = {2, -1, 3, 1, 1, 2, -1, 2, 1, 3, -2, 1}; + double u[3] = {0.2, 0.3, -0.1}; + double w[4] = {1.0, -0.5, 2.0, 0.3}; + + expr *x = new_variable(3, 1, 0, 3); + expr *Ax = new_left_matmul_dense(NULL, x, 4, 3, A); + expr *Bx = new_left_matmul_dense(NULL, x, 4, 3, B); + expr *root = new_elementwise_mult(Ax, Bx); + + mu_assert("multiply dense jacobian check failed", + check_jacobian_num(root, u, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("multiply dense wsum_hess check failed", + check_wsum_hess(root, u, w, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("multiply jacobian should be dense", + root->jacobian->kind == MATRIX_PERMUTED_DENSE && + root->jacobian->nnz == 12); + + free_expr(root); + return 0; +} + +/* (S x) * (T x) elementwise with one entry per row in S and T: the Jacobian + is a binary sum that does not fill a dense block and must stay sparse. */ +const char *test_binary_sum_multiply_sparse(void) { - for (int model = SUM47_SQUARE; model <= SUM47_SPARSE; model++) + double u[3] = {0.2, 0.3, -0.1}; + double w[4] = {1.0, -0.5, 2.0, 0.3}; + + CSR_matrix *S = new_CSR_matrix(4, 3, 4); + CSR_matrix *T = new_CSR_matrix(4, 3, 4); + for (int i = 0; i < 4; i++) { - double *u, w = 1.0; - expr *focus; - expr *root = sum47_model(model, 5, 3, 3, &focus, &u); - jacobian_init(root); - wsum_hess_init(root); - matrix_kind expected = - model == SUM47_SPARSE ? MATRIX_SPARSE : MATRIX_PERMUTED_DENSE; - mu_assert("binary model Jacobian kind", focus->jacobian->kind == expected); - int nnz = model == SUM47_SPARSE ? 5 : focus->size * root->n_vars; - mu_assert("binary model Jacobian nnz", focus->jacobian->nnz == nnz); - if (model != SUM47_LOGIT && model != SUM47_SPARSE) - mu_assert("binary model Hessian kind", - root->wsum_hess->kind == MATRIX_PERMUTED_DENSE); - for (int round = 0; round < 2; round++) - { - mu_assert("binary model gradient", - check_jacobian_num(root, u, NUMERICAL_DIFF_DEFAULT_H)); - mu_assert("binary model Hessian", - check_wsum_hess(root, u, &w, NUMERICAL_DIFF_DEFAULT_H)); - for (int i = 0; i < root->n_vars; i++) u[i] += 0.03; - } - free_expr(root); - free(u); + S->p[i] = i; + S->i[i] = i % 3; + S->x[i] = 0.5 + i; + T->p[i] = i; + T->i[i] = (i + 1) % 3; + T->x[i] = 2.0 - i; } - return NULL; + S->p[4] = 4; + T->p[4] = 4; + + expr *x = new_variable(3, 1, 0, 3); + expr *Sx = new_left_matmul(NULL, x, S); + expr *Tx = new_left_matmul(NULL, x, T); + expr *root = new_elementwise_mult(Sx, Tx); + free_CSR_matrix(S); + free_CSR_matrix(T); + + mu_assert("multiply sparse jacobian check failed", + check_jacobian_num(root, u, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("multiply sparse wsum_hess check failed", + check_wsum_hess(root, u, w, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("multiply jacobian should stay sparse", + root->jacobian->kind == MATRIX_SPARSE && root->jacobian->nnz == 8); + + free_expr(root); + return 0; } -const char *test_binary_sum_matmul_composition(void) +/* (A x)^T (B x): the chain-rule Jacobian of matmul is a binary sum with a + dense result. */ +const char *test_binary_sum_matmul_dense(void) { - double a[4] = {1, 2, -1, 3}, b[4] = {2, -1, 3, 1}; - double u[2] = {0.2, 0.3}, w = 1; + double A[4] = {1, 2, -1, 3}; + double B[4] = {2, -1, 3, 1}; + double u[2] = {0.2, 0.3}; + double w = 1.0; + expr *x = new_variable(2, 1, 0, 2); - expr *left = new_left_matmul_dense(NULL, x, 2, 2, a); - expr *right = new_left_matmul_dense(NULL, x, 2, 2, b); - expr *root = new_matmul(new_transpose(left), right); - mu_assert("composed matmul gradient", + expr *Ax = new_left_matmul_dense(NULL, x, 2, 2, A); + expr *Bx = new_left_matmul_dense(NULL, x, 2, 2, B); + expr *root = new_matmul(new_transpose(Ax), Bx); + + mu_assert("matmul dense jacobian check failed", check_jacobian_num(root, u, NUMERICAL_DIFF_DEFAULT_H)); - mu_assert("composed matmul binary Jacobian kind", + mu_assert("matmul dense wsum_hess check failed", + check_wsum_hess(root, u, &w, NUMERICAL_DIFF_DEFAULT_H)); + mu_assert("matmul jacobian should be dense", root->jacobian->kind == MATRIX_PERMUTED_DENSE && root->jacobian->nnz == 2); - mu_assert("composed matmul Hessian", - check_wsum_hess(root, u, &w, NUMERICAL_DIFF_DEFAULT_H)); + free_expr(root); - return NULL; + return 0; } #endif