diff --git a/include/atoms/affine.h b/include/atoms/affine.h index cdeb16e2..a128835c 100644 --- a/include/atoms/affine.h +++ b/include/atoms/affine.h @@ -24,6 +24,17 @@ expr *new_add(expr *left, expr *right); expr *new_neg(expr *child); +/* Is the node this atom? */ +bool expr_is_add(const expr *node); +bool expr_is_broadcast(const expr *node); +bool expr_is_hstack(const expr *node); +bool expr_is_index(const expr *node); +bool expr_is_sum(const expr *node); +bool expr_is_scalar_mult(const expr *node); +bool expr_is_vector_mult(const expr *node); +/* A constant leaf: parameter node with param_id == PARAM_FIXED. */ +bool expr_is_fixed_parameter(const expr *node); + expr *new_sum(expr *child, int axis); expr *new_hstack(expr **args, int n_args, int n_vars); expr *new_vstack(expr **args, int n_args, int n_vars); diff --git a/include/expr.h b/include/expr.h index a76487c2..f3a1fa39 100644 --- a/include/expr.h +++ b/include/expr.h @@ -41,6 +41,14 @@ 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); +/* Builds a new node of node's atom, with node's attributes, over other + children; right is NULL for a unary atom. Set by elementwise atoms only. */ +typedef struct expr *(*new_same_atom_fn)(const struct expr *node, struct expr *left, + struct expr *right); +/* Do two nodes of one atom have the same attributes (e.g. the exponent of a + power)? Only atoms that set `new_same_atom` and have attributes need it. */ +typedef bool (*same_attrs_fn)(const struct expr *a, const struct expr *b); + /* AFFINITY_UNKNOWN must be 0 (the workspace is calloc'ed) */ typedef enum { @@ -106,6 +114,9 @@ typedef struct expr /* For nodes with children outside left/right (see expr_set_needs_refresh). Must return whether those children contain an updatable parameter. */ set_needs_refresh_children_fn set_needs_refresh_children; + new_same_atom_fn new_same_atom; /* elementwise atoms; NULL otherwise */ + same_attrs_fn same_attrs; /* NULL: no attributes */ + int pass_id; /* scratch index of a graph pass; else 0 */ Expr_Work *work; bool has_params; /* subtree has an updatable parameter */ bool needs_parameter_refresh; /* cached parameter data is stale */ diff --git a/include/problem.h b/include/problem.h index b7645860..abd5cd6e 100644 --- a/include/problem.h +++ b/include/problem.h @@ -26,6 +26,7 @@ typedef struct { + double time_vectorize; /* re-vectorization pass in new_problem */ double time_init_derivatives; double time_eval_jacobian; double time_eval_gradient; @@ -72,9 +73,12 @@ typedef struct problem bool verbose; } problem; -/* Retains objective and constraints (shared ownership with caller) */ +/* Retains objective and constraints (shared ownership with caller). With + vectorize set, the roots are first re-vectorized (vectorize.h): the problem + then holds the roots the pass returns, which need not be the ones passed + in. */ problem *new_problem(expr *objective, expr **constraints, int n_constraints, - bool verbose); + bool verbose, bool vectorize); void problem_init_jacobian(problem *prob); void problem_init_hessian(problem *prob); void problem_init_derivatives(problem *prob); diff --git a/include/vectorize.h b/include/vectorize.h new file mode 100644 index 00000000..b4ffff97 --- /dev/null +++ b/include/vectorize.h @@ -0,0 +1,66 @@ +/* + * Copyright 2026 Daniel Cederberg and William Zhang + * + * This file is part of the SparseDiffEngine project. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef VECTORIZE_H +#define VECTORIZE_H + +#include "expr.h" + +/* Re-vectorization of expressions built by loops. + * + * A loop in the user's code leaves many small isomorphic expressions (the same + * atoms in the same arrangement, differing only in indices and constants): the + * terms of a chain of adds, the args of an hstack, or a list of constraints. + * The pass replaces k of them by one expression that computes their + * concatenation ("zip"), using that an elementwise atom commutes with + * concatenation: + * + * zip_j f(a_j, b_j) = f(zip_j a_j, zip_j b_j) + * + * At the leaves, entries of one array become a single gather (or the array), + * constants one constant, and k copies of a scalar a broadcast. For example + * + * cos(x[0]) + ... + cos(x[n-1]) -> sum(cos(x)) + * + * Full sums and multiplications by constants have laws of their own; anything + * else is concatenated with an hstack. + * + * An elementwise atom sets `new_same_atom` in its constructor (expr.h), and + * `same_attrs` if it has attributes; atoms built on new_elementwise inherit + * `new_same_atom`. Other atoms need nothing. + * + * The pass must run before jacobian_init / wsum_hess_init. It changes the + * order of summation, so values agree to rounding only. + */ + +/* Smaller groups are left alone, so that hand-vectorized code such as + sum(x**2) + sum(y**2) is not rewritten. */ +#define VECTORIZE_MIN_GROUP 8 + +/* Vectorizes the DAG under roots and replaces each root by its equivalent. + The roots after the first n_separate are a concatenation (a problem's + constraints): runs of isomorphic ones are merged. Returns the new number + of roots. + + The caller must hold a reference to each root it passes in, and keeps it. + Each root returned carries a new reference that belongs to the caller. */ +int vectorize_exprs(expr **roots, int n_roots, int n_separate); + +/* One root: expr *v = vectorize_expr(root); free_expr(root); */ +expr *vectorize_expr(expr *root); + +#endif /* VECTORIZE_H */ diff --git a/src/atoms/affine/add.c b/src/atoms/affine/add.c index af863c56..7b04dd57 100644 --- a/src/atoms/affine/add.c +++ b/src/atoms/affine/add.c @@ -89,6 +89,17 @@ static bool is_affine(const expr *node) return node->left->is_affine(node->left) && node->right->is_affine(node->right); } +bool expr_is_add(const expr *node) +{ + return node->forward_impl == forward; +} + +static expr *new_same_atom(const expr *node, expr *left, expr *right) +{ + (void) node; + return new_add(left, right); +} + expr *new_add(expr *left, expr *right) { assert(left->d1 == right->d1 && left->d2 == right->d2); @@ -100,6 +111,7 @@ expr *new_add(expr *left, expr *right) node->right = right; expr_retain(left); expr_retain(right); + node->new_same_atom = new_same_atom; return node; } diff --git a/src/atoms/affine/broadcast.c b/src/atoms/affine/broadcast.c index 685d697d..519ced5c 100644 --- a/src/atoms/affine/broadcast.c +++ b/src/atoms/affine/broadcast.c @@ -163,6 +163,11 @@ static bool is_affine(const expr *node) return node->left->is_affine(node->left); } +bool expr_is_broadcast(const expr *node) +{ + return node->forward_impl == forward; +} + expr *new_broadcast(expr *child, int d1, int d2) { // --------------------------------------------------------------------------- diff --git a/src/atoms/affine/hstack.c b/src/atoms/affine/hstack.c index fdc9dc0a..bdf1aedb 100644 --- a/src/atoms/affine/hstack.c +++ b/src/atoms/affine/hstack.c @@ -147,6 +147,11 @@ static void free_type_data(expr *node) hnode->args = NULL; } +bool expr_is_hstack(const expr *node) +{ + return node->forward_impl == forward; +} + expr *new_hstack(expr **args, int n_args, int n_vars) { /* compute second dimension */ diff --git a/src/atoms/affine/index.c b/src/atoms/affine/index.c index 18831d35..11d93c5f 100644 --- a/src/atoms/affine/index.c +++ b/src/atoms/affine/index.c @@ -143,6 +143,11 @@ static void free_type_data(expr *node) } } +bool expr_is_index(const expr *node) +{ + return node->forward_impl == forward; +} + expr *new_index(expr *child, int d1, int d2, const int *indices, int n_idxs) { assert(d1 * d2 == n_idxs); diff --git a/src/atoms/affine/neg.c b/src/atoms/affine/neg.c index 33f7bd88..1208b9b7 100644 --- a/src/atoms/affine/neg.c +++ b/src/atoms/affine/neg.c @@ -86,6 +86,13 @@ static bool is_affine(const expr *node) return node->left->is_affine(node->left); } +static expr *new_same_atom(const expr *node, expr *left, expr *right) +{ + (void) node; + (void) right; + return new_neg(left); +} + expr *new_neg(expr *child) { expr *node = (expr *) sp_calloc(1, sizeof(expr)); @@ -94,6 +101,7 @@ expr *new_neg(expr *child) eval_wsum_hess_impl, NULL); node->left = child; expr_retain(child); + node->new_same_atom = new_same_atom; return node; } diff --git a/src/atoms/affine/parameter.c b/src/atoms/affine/parameter.c index 2a1fa456..d5c54128 100644 --- a/src/atoms/affine/parameter.c +++ b/src/atoms/affine/parameter.c @@ -65,6 +65,12 @@ static bool is_affine(const expr *node) return true; } +bool expr_is_fixed_parameter(const expr *node) +{ + return node->forward_impl == forward && + ((const parameter_expr *) node)->param_id == PARAM_FIXED; +} + expr *new_parameter(int d1, int d2, int param_id, int n_vars, const double *values) { parameter_expr *pnode = (parameter_expr *) sp_calloc(1, sizeof(parameter_expr)); diff --git a/src/atoms/affine/scalar_mult.c b/src/atoms/affine/scalar_mult.c index 18f10300..84845ce3 100644 --- a/src/atoms/affine/scalar_mult.c +++ b/src/atoms/affine/scalar_mult.c @@ -126,6 +126,11 @@ static void free_type_data(expr *node) } } +bool expr_is_scalar_mult(const expr *node) +{ + return node->forward_impl == forward; +} + expr *new_scalar_mult(expr *param_node, expr *child) { scalar_mult_expr *mult_node = diff --git a/src/atoms/affine/sum.c b/src/atoms/affine/sum.c index 01b69bb3..d8d6d1d3 100644 --- a/src/atoms/affine/sum.c +++ b/src/atoms/affine/sum.c @@ -163,6 +163,11 @@ static bool is_affine(const expr *node) return node->left->is_affine(node->left); } +bool expr_is_sum(const expr *node) +{ + return node->forward_impl == forward; +} + expr *new_sum(expr *child, int axis) { int d2 = 0; diff --git a/src/atoms/affine/vector_mult.c b/src/atoms/affine/vector_mult.c index 1188a503..cf2e16f5 100644 --- a/src/atoms/affine/vector_mult.c +++ b/src/atoms/affine/vector_mult.c @@ -129,6 +129,11 @@ static bool is_affine(const expr *node) return node->left->is_affine(node->left); } +bool expr_is_vector_mult(const expr *node) +{ + return node->forward_impl == forward; +} + expr *new_vector_mult(expr *param_node, expr *child) { vector_mult_expr *vnode = diff --git a/src/atoms/bivariate_full_dom/multiply.c b/src/atoms/bivariate_full_dom/multiply.c index ac1f1807..24a4890b 100644 --- a/src/atoms/bivariate_full_dom/multiply.c +++ b/src/atoms/bivariate_full_dom/multiply.c @@ -232,6 +232,12 @@ static bool is_affine(const expr *node) return false; } +static expr *new_same_atom(const expr *node, expr *left, expr *right) +{ + (void) node; + return new_elementwise_mult(left, right); +} + expr *new_elementwise_mult(expr *left, expr *right) { elementwise_mult_expr *mul_node = @@ -245,6 +251,7 @@ expr *new_elementwise_mult(expr *left, expr *right) node->right = right; expr_retain(left); expr_retain(right); + node->new_same_atom = new_same_atom; return node; } diff --git a/src/atoms/elementwise_full_dom/common.c b/src/atoms/elementwise_full_dom/common.c index 64b9684a..34b93179 100644 --- a/src/atoms/elementwise_full_dom/common.c +++ b/src/atoms/elementwise_full_dom/common.c @@ -174,6 +174,17 @@ bool is_affine_elementwise(const expr *node) return false; } +/* an attribute-free elementwise atom is its three functions */ +static expr *new_same_atom(const expr *node, expr *left, expr *right) +{ + (void) right; + expr *copy = new_elementwise(left); + copy->forward_impl = node->forward_impl; + copy->local_jacobian = node->local_jacobian; + copy->local_wsum_hess = node->local_wsum_hess; + return copy; +} + void init_elementwise(expr *node, expr *child) { /* Initialize base fields */ @@ -185,6 +196,7 @@ void init_elementwise(expr *node, expr *child) /* Set left child */ node->left = child; expr_retain(child); + node->new_same_atom = new_same_atom; } expr *new_elementwise(expr *child) diff --git a/src/atoms/elementwise_full_dom/power.c b/src/atoms/elementwise_full_dom/power.c index c1ec9251..3fa2456d 100644 --- a/src/atoms/elementwise_full_dom/power.c +++ b/src/atoms/elementwise_full_dom/power.c @@ -99,6 +99,17 @@ static void local_wsum_hess(expr *node, double *out, const double *w) } } +static expr *new_same_atom(const expr *node, expr *left, expr *right) +{ + (void) right; + return new_power(left, ((const power_expr *) node)->p); +} + +static bool same_attrs(const expr *a, const expr *b) +{ + return ((const power_expr *) a)->p == ((const power_expr *) b)->p; +} + expr *new_power(expr *child, double p) { /* Allocate the type-specific struct */ @@ -111,6 +122,8 @@ expr *new_power(expr *child, double p) /* Set type-specific field */ pnode->p = p; + node->new_same_atom = new_same_atom; + node->same_attrs = same_attrs; return node; } diff --git a/src/problem.c b/src/problem.c index 89a39fca..2e294fea 100644 --- a/src/problem.c +++ b/src/problem.c @@ -21,16 +21,58 @@ #include "sparsediff_linalg/matrix_vstack.h" #include "sparsediff_linalg/tracked_alloc.h" #include "subexpr.h" +#include "vectorize.h" #include #include #include #include /* Store the objective and constraints in the problem, which holds one - reference on each. */ + reference on each. With vectorize set they go through the vectorization + pass first (vectorize.h), and the problem stores what the pass returns. + + All of them go through the pass in one call, so a subexpression used by + several is rewritten once and stays shared. The pass may merge constraints: + n scalar constraints built by a loop come back as one constraint of size n, + with row i equal to the old constraint i. */ static void set_objective_and_constraints(problem *prob, expr *objective, - expr **constraints, int n_constraints) + expr **constraints, int n_constraints, + bool vectorize) { + expr **roots = NULL; + if (vectorize) + { + /* timed with the release of what the pass replaced */ + Timer timer; + clock_gettime(CLOCK_MONOTONIC, &timer.start); + int n = 1 + n_constraints; + roots = (expr **) sp_malloc(n * sizeof(expr *)); + roots[0] = objective; + if (n_constraints > 0) + { + memcpy(roots + 1, constraints, n_constraints * sizeof(expr *)); + } + + /* the pass wants a reference held on what it is given, and returns + roots that each carry a reference of ours */ + for (int i = 0; i < n; i++) + { + expr_retain(roots[i]); + } + int n_new = vectorize_exprs(roots, n, 1); + free_expr(objective); + for (int i = 0; i < n_constraints; i++) + { + free_expr(constraints[i]); + } + + objective = roots[0]; + constraints = roots + 1; + n_constraints = n_new - 1; + clock_gettime(CLOCK_MONOTONIC, &timer.end); + prob->stats.time_vectorize = GET_ELAPSED_SECONDS(timer); + } + prob->objective = objective; expr_retain(objective); @@ -46,10 +88,20 @@ static void set_objective_and_constraints(problem *prob, expr *objective, expr_retain(constraints[i]); } } + + if (roots != NULL) + { + /* the problem has its own references now */ + for (int i = 0; i < 1 + n_constraints; i++) + { + free_expr(roots[i]); + } + sp_free(roots); + } } problem *new_problem(expr *objective, expr **constraints, int n_constraints, - bool verbose) + bool verbose, bool vectorize) { #ifdef SP_TRACK_MEMORY /* Start the high-water mark at the current live count: allocations made @@ -61,7 +113,10 @@ problem *new_problem(expr *objective, expr **constraints, int n_constraints, if (!prob) return NULL; prob->n_vars = objective->n_vars; - set_objective_and_constraints(prob, objective, constraints, n_constraints); + + /* objective and constraints, re-vectorized if asked */ + set_objective_and_constraints(prob, objective, constraints, n_constraints, + vectorize); /* allocation */ prob->constraint_values = @@ -236,6 +291,7 @@ static inline void print_end_message(const Diff_engine_stats *stats) #endif printf("\nTiming (seconds):\n"); + printf(" Vectorization pass: %8.3f\n", stats->time_vectorize); printf(" Derivative structure (sparsity): %8.3f\n", stats->time_init_derivatives); printf(" Jacobian evaluation: %8.3f\n", @@ -249,9 +305,10 @@ static inline void print_end_message(const Diff_engine_stats *stats) printf(" Constraints evaluation: %8.3f\n", stats->time_forward_constraints); - double total_time = stats->time_init_derivatives + stats->time_eval_jacobian + - stats->time_eval_gradient + stats->time_eval_hessian + - stats->time_forward_obj + stats->time_forward_constraints; + double total_time = stats->time_vectorize + stats->time_init_derivatives + + stats->time_eval_jacobian + stats->time_eval_gradient + + stats->time_eval_hessian + stats->time_forward_obj + + stats->time_forward_constraints; printf(" ----------------------------------------------\n"); printf(" Total differentiation time: %8.3f\n", total_time); diff --git a/src/vectorize/laws.c b/src/vectorize/laws.c new file mode 100644 index 00000000..db6b5152 --- /dev/null +++ b/src/vectorize/laws.c @@ -0,0 +1,327 @@ +/* + * Copyright 2026 Daniel Cederberg and William Zhang + * + * This file is part of the SparseDiffEngine project. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "subexpr.h" +#include "vectorize.h" +#include "vectorize_internal.h" +#include + +/* The laws: how k nodes of one kind become one node. vec_try_zip, at the + end, picks the law for a group of nodes. A new kind of atom is supported by + adding its law here. */ + +static bool same_op(const expr *a, const expr *b) +{ + return a->forward_impl == b->forward_impl && + a->jacobian_init_impl == b->jacobian_init_impl && + a->local_jacobian == b->local_jacobian && a->d1 == b->d1 && + a->d2 == b->d2 && (a->same_attrs == NULL || a->same_attrs(a, b)); +} + +static bool same_shape(const expr *a, const expr *b) +{ + return a->d1 == b->d1 && a->d2 == b->d2; +} +/* Is z, a zip whose first node is c, the same scalar k times? An atom over + such operands is computed once and repeated (loop invariants). */ +static bool repeats(const expr *z, const expr *c) +{ + if (expr_is_broadcast(z)) + { + return z->left == c; + } + if (!expr_is_fixed_parameter(z) || !expr_is_fixed_parameter(c)) + { + return false; + } + if (c->size != 1) + { + return false; + } + for (int i = 0; i < z->size; i++) + { + if (z->value[i] != c->value[0]) + { + return false; + } + } + return true; +} + +/* zip of the nodes' left children, or of their right children */ +static expr *zip_children(Pass *p, expr **nodes, int k, bool right) +{ + expr **children = (expr **) sp_malloc(k * sizeof(expr *)); + for (int j = 0; j < k; j++) + { + children[j] = nodes[j]->left; + if (right) + { + children[j] = nodes[j]->right; + } + } + expr *z = vec_zip(p, children, k); + sp_free(children); + return z; +} + +/* only elementwise atoms set new_same_atom (expr.h) */ +static bool is_elementwise(const expr *f) +{ + return f->new_same_atom != NULL; +} + +/* The generic law: zip_j f(l_j, r_j) = f(zip_j l_j, zip_j r_j) */ +static expr *zip_elementwise(Pass *p, expr **nodes, int k) +{ + expr *first = nodes[0]; + bool binary = first->right != NULL; + for (int j = 0; j < k; j++) + { + /* the children must have the node's shape (no broadcasting) */ + if (!same_shape(nodes[j]->left, first) || + (binary && !same_shape(nodes[j]->right, first))) + { + return NULL; + } + } + expr *l = zip_children(p, nodes, k, false); + expr *r = NULL; + if (binary) + { + r = zip_children(p, nodes, k, true); + } + if (repeats(l, first->left) && (!binary || repeats(r, first->right)) && + (expr_is_broadcast(l) || (binary && expr_is_broadcast(r)))) + { + return new_broadcast(first, 1, k); /* constants alone stay one constant */ + } + if (binary && (l->var_id == NOT_A_VARIABLE || r->var_id != NOT_A_VARIABLE)) + { + l = shaped(l, r->d1, r->d2); /* a bare variable keeps its shape */ + } + else if (binary) + { + r = shaped(r, l->d1, l->d2); + } + return first->new_same_atom(first, l, r); +} + +/* Entries of one node: a single gather, or the node itself */ +static expr *gather(expr **nodes, int k) +{ + if (k == 1) + { + return nodes[0]; + } + expr *src = nodes[0]->left; + int n = nodes[0]->size, total = k * n; + int *idx = (int *) sp_malloc(total * sizeof(int)); + bool identity = total == src->size; + for (int j = 0; j < k; j++) + { + memcpy(idx + j * n, ((index_expr *) nodes[j])->indices, n * sizeof(int)); + } + for (int i = 0; i < total && identity; i++) + { + identity = idx[i] == i; + } + expr *z = src; + if (!identity) + { + z = new_index(src, nodes[0]->d1, k * nodes[0]->d2, idx, total); + } + sp_free(idx); + return z; +} + +/* Entries of several nodes: one gather for each run of entries of one node. + A gather costs time in the size of the node it reads, so a partial run must + cover an eighth of that node. */ +static expr *zip_index(expr **nodes, int k) +{ + expr **pieces = (expr **) sp_malloc(k * sizeof(expr *)); + int n_pieces = 0; + for (int i = 0, j; i < k; i = j) + { + /* [i, j): the run of nodes that read the same node as nodes[i] */ + j = i + 1; + while (j < k && nodes[j]->left == nodes[i]->left) + { + j++; + } + int run = j - i; + bool covers_enough = 8 * run * nodes[i]->size >= nodes[i]->left->size; + if (run == k || covers_enough) + { + pieces[n_pieces++] = gather(nodes + i, run); + } + else + { + for (int t = i; t < j; t++) + { + pieces[n_pieces++] = nodes[t]; + } + } + } + expr *z = NULL; + if (n_pieces == 1) + { + z = pieces[0]; + } + else if (n_pieces < k) + { + for (int i = 0; i < n_pieces; i++) + { + pieces[i] = + shaped(pieces[i], nodes[0]->d1, pieces[i]->size / nodes[0]->d1); + } + z = new_hstack(pieces, n_pieces, nodes[0]->n_vars); + } + sp_free(pieces); + return z; +} + +/* Constants: one constant. Updatable parameters are not merged. */ +static expr *zip_constants(expr **nodes, int k) +{ + int n = nodes[0]->size; + for (int j = 0; j < k; j++) + { + if (!expr_is_fixed_parameter(nodes[j])) + { + return NULL; + } + } + double *values = (double *) sp_malloc(k * n * sizeof(double)); + for (int j = 0; j < k; j++) + { + memcpy(values + j * n, nodes[j]->value, n * sizeof(double)); + } + expr *z = new_parameter(nodes[0]->d1, k * nodes[0]->d2, PARAM_FIXED, + nodes[0]->n_vars, values); + sp_free(values); + return z; +} + +/* Full sums: the column sums of the children laid out as (child size, k) */ +static expr *zip_sums(Pass *p, expr **nodes, int k) +{ + expr *first_child = nodes[0]->left; + for (int j = 0; j < k; j++) + { + if (((sum_expr *) nodes[j])->axis != -1 || + !same_shape(nodes[j]->left, first_child)) + { + return NULL; + } + } + return new_sum(shaped(zip_children(p, nodes, k, false), first_child->size, k), + 0); +} + +/* Multiplications by constants: one, by the vector of the coefficients */ +static expr *zip_const_mults(Pass *p, expr **nodes, int k) +{ + bool scalar = expr_is_scalar_mult(nodes[0]); + int n = nodes[0]->size; + int param_size = n; + if (scalar) + { + param_size = 1; + } + double *values = (double *) sp_malloc(k * n * sizeof(double)); + for (int j = 0; j < k; j++) + { + /* scalar_mult and vector_mult have the same layout */ + expr *param = ((scalar_mult_expr *) nodes[j])->param_source; + if (!expr_is_fixed_parameter(param) || param->size != param_size) + { + sp_free(values); + return NULL; + } + if (scalar) + { + for (int i = 0; i < n; i++) + { + values[j * n + i] = param->value[0]; + } + } + else + { + for (int i = 0; i < n; i++) + { + values[j * n + i] = param->value[i]; + } + } + } + expr *z = zip_children(p, nodes, k, false); + expr *coef = new_parameter(z->d1, z->d2, PARAM_FIXED, z->n_vars, values); + sp_free(values); + if (expr_is_broadcast(z) && repeats(z, nodes[0]->left) && + repeats(coef, ((scalar_mult_expr *) nodes[0])->param_source)) + { + free_expr(coef); + return new_broadcast(nodes[0], 1, k); + } + return new_vector_mult(coef, z); +} + +/* zip, or NULL when no law does better than an hstack of the nodes */ +expr *vec_try_zip(Pass *p, expr **nodes, int k) +{ + expr *first = nodes[0]; + bool all_one_node = true, all_same_op = true; + for (int j = 1; j < k; j++) + { + all_one_node = all_one_node && nodes[j] == first; + all_same_op = all_same_op && same_op(nodes[j], first); + } + if (all_one_node) + { + if (first->size == 1) + { + return new_broadcast(first, 1, k); + } + return NULL; + } + if (!all_same_op) + { + return NULL; + } + if (is_elementwise(first)) + { + return zip_elementwise(p, nodes, k); + } + if (expr_is_index(first)) + { + return zip_index(nodes, k); + } + if (expr_is_fixed_parameter(first)) + { + return zip_constants(nodes, k); + } + if (expr_is_sum(first)) + { + return zip_sums(p, nodes, k); + } + if (expr_is_scalar_mult(first) || expr_is_vector_mult(first)) + { + return zip_const_mults(p, nodes, k); + } + return NULL; +} diff --git a/src/vectorize/pass.c b/src/vectorize/pass.c new file mode 100644 index 00000000..b961e217 --- /dev/null +++ b/src/vectorize/pass.c @@ -0,0 +1,426 @@ +/* + * Copyright 2026 Daniel Cederberg and William Zhang + * + * This file is part of the SparseDiffEngine project. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "subexpr.h" +#include "vectorize.h" +#include "vectorize_internal.h" +#include + +/* The pass over the graph: which nodes to merge (vectorize_exprs). */ + +/* The children the pass walks: an hstack's args, else left and right */ +static int n_child_slots(const expr *node) +{ + return expr_is_hstack(node) ? ((const hstack_expr *) node)->n_args : 2; +} + +static expr **child_slot(expr *node, int i) +{ + if (expr_is_hstack(node)) + { + return &((hstack_expr *) node)->args[i]; + } + return i == 0 ? &node->left : &node->right; +} + +static uint64_t mix(uint64_t h, uint64_t x) +{ + x *= 0x9E3779B97F4A7C15ull; + x ^= x >> 29; + h ^= x; + h *= 0xBF58476D1CE4E5B9ull; + h ^= h >> 32; + return h; +} + +/* Number the nodes under root, children first, without recursion (a chain + can be 1e5 deep). The signature covers atoms and shapes but no data, so the + iterations of a loop get equal signatures; it is only a hint, zip checks + what it merges. */ +static void number_nodes(Pass *p, expr *root) +{ + expr **stack = NULL; + int n = 0, cap = 0; + PUSH(stack, n, cap, root); + while (n > 0) + { + expr *node = stack[n - 1]; + if (node->pass_id == 0) + { + node->pass_id = -1; /* entered: the children are numbered first */ + for (int i = 0, n_children = n_child_slots(node); i < n_children; i++) + { + expr *child = *child_slot(node, i); + if (child != NULL && child->pass_id == 0) + { + PUSH(stack, n, cap, child); + } + } + continue; + } + n--; + if (node->pass_id > 0) + { + continue; /* numbered through another parent */ + } + + uint64_t sig = mix(0x243F6A8885A308D3ull, (uintptr_t) node->forward_impl); + sig = mix(sig, (uintptr_t) node->jacobian_init_impl); + sig = mix(sig, (uintptr_t) node->local_jacobian); + sig = mix(mix(sig, (uint64_t) node->d1), (uint64_t) node->d2); + uint64_t sources = 0; + for (int i = 0, n_children = n_child_slots(node); i < n_children; i++) + { + expr *child = *child_slot(node, i); + if (child == NULL) + { + continue; + } + sig = mix(sig, p->info[child->pass_id].sig); + sources = mix(sources, p->info[child->pass_id].sources); + p->info[child->pass_id].parents++; + } + if (expr_is_index(node)) + { + sources = (uint64_t) node->left->pass_id; + } + Info *info = add_info(p, node); + info->sig = sig; + info->sources = sources; + expr_retain(node); + } + sp_free(stack); +} + +/* point a child slot at the child's replacement */ +static void rewire(Pass *p, expr **slot) +{ + expr *old = *slot; + if (old == NULL || p->info[old->pass_id].replacement == old) + { + return; + } + *slot = p->info[old->pass_id].replacement; + expr_retain(*slot); + free_expr(old); /* drops the slot's reference; the pass still holds old */ +} + +/* Replace every run of at least VECTORIZE_MIN_GROUP nodes of equal signature + by its zip (when `always` is false, only if a law applies). Returns the new + length. */ +static int zip_runs(Pass *p, expr **nodes, const uint64_t *sig, int n, bool always) +{ + int n_out = 0; + for (int start = 0, end; start < n; start = end) + { + /* [start, end): the run of nodes with the signature of nodes[start] */ + end = start + 1; + while (end < n && sig[end] == sig[start]) + { + end++; + } + int k = end - start; + expr *z = NULL; + if (k >= VECTORIZE_MIN_GROUP && always) + { + z = vec_zip(p, nodes + start, k); + } + else if (k >= VECTORIZE_MIN_GROUP) + { + z = vec_try_zip(p, nodes + start, k); + } + if (z != NULL) + { + nodes[n_out++] = z; + continue; + } + for (int i = start; i < end; i++) + { + nodes[n_out++] = nodes[i]; + } + } + return n_out; +} + +typedef struct +{ + uint64_t sig, sources; + int pos; + expr *node; +} Term; + +static int by_sig_sources_pos(const void *pa, const void *pb) +{ + const Term *a = (const Term *) pa, *b = (const Term *) pb; + if (a->sig != b->sig) + { + return a->sig < b->sig ? -1 : 1; + } + if (a->sources != b->sources) + { + return a->sources < b->sources ? -1 : 1; + } + return a->pos - b->pos; +} + +/* The terms of the chain under head (its children that are not inner adds), + in source order, each rewired to its replacement */ +static Term *chain_terms(Pass *p, expr *head, int *n_terms) +{ + expr ***stack = NULL; + Term *terms = NULL; + int n_stack = 0, cap_stack = 0, n = 0, cap = 0; + PUSH(stack, n_stack, cap_stack, &head->right); + PUSH(stack, n_stack, cap_stack, &head->left); + while (n_stack > 0) + { + expr **slot = stack[--n_stack]; + Info info = p->info[(*slot)->pass_id]; + if (info.in_parent_chain) + { + PUSH(stack, n_stack, cap_stack, &(*slot)->right); + PUSH(stack, n_stack, cap_stack, &(*slot)->left); + continue; + } + rewire(p, slot); + terms = (Term *) grow(terms, n, &cap, sizeof(Term)); + terms[n].sig = info.sig; + terms[n].sources = info.sources; + terms[n].pos = n; + terms[n++].node = *slot; + } + sp_free(stack); + *n_terms = n; + return terms; +} + +/* Sort the terms into groups and set sig to the group: the terms of one + signature that read the same arrays, if there are enough of them, and the + signature's other terms together. A group is named by the position of its + first term, which keeps the order of the sum independent of hash values. */ +static void group_terms(Term *terms, int n) +{ + qsort(terms, n, sizeof(Term), by_sig_sources_pos); + for (int sig_start = 0, sig_end; sig_start < n; sig_start = sig_end) + { + /* [sig_start, sig_end): the terms of one signature */ + sig_end = sig_start + 1; + while (sig_end < n && terms[sig_end].sig == terms[sig_start].sig) + { + sig_end++; + } + int rest_pos = n; /* first position among the small runs */ + for (int src_start = sig_start, src_end; src_start < sig_end; + src_start = src_end) + { + /* [src_start, src_end): those of them that read the same arrays */ + src_end = src_start + 1; + while (src_end < sig_end && + terms[src_end].sources == terms[src_start].sources) + { + src_end++; + } + bool own_group = src_end - src_start >= VECTORIZE_MIN_GROUP; + if (!own_group && terms[src_start].pos < rest_pos) + { + rest_pos = terms[src_start].pos; + } + for (int i = src_start; i < src_end; i++) + { + terms[i].sig = own_group ? terms[src_start].pos : n; + } + } + for (int i = sig_start; i < sig_end; i++) + { + if (terms[i].sig == (uint64_t) n) + { + terms[i].sig = (uint64_t) rest_pos; + } + } + } + qsort(terms, n, sizeof(Term), by_sig_sources_pos); +} + +/* A chain of adds: every large enough group of isomorphic terms becomes the + sum of its zip. Returns head when there is no such group. */ +static expr *rewrite_chain(Pass *p, expr *head) +{ + int n; + Term *terms = chain_terms(p, head, &n); + group_terms(terms, n); + expr **nodes = (expr **) sp_malloc(n * sizeof(expr *)); + uint64_t *sig = (uint64_t *) sp_malloc(n * sizeof(uint64_t)); + for (int i = 0; i < n; i++) + { + nodes[i] = terms[i].node; + sig[i] = terms[i].sig; + } + int n_out = zip_runs(p, nodes, sig, n, true); + expr *sum = head; + for (int i = 0; i < n_out && n_out < n; i++) + { + /* a term has the chain's size; a zip of k terms has k times that */ + expr *z = nodes[i]; + int k = z->size / head->size; + if (k > 1 && head->size == 1) + { + z = new_sum(z, -1); + } + else if (k > 1) + { + /* the sum of the blocks, as a node of the blocks' shape */ + z = new_sum(shaped(z, head->size, k), 1); + z = new_reshape(z, head->d1, head->d2); + } + sum = i > 0 ? new_add(sum, z) : z; + } + sp_free(sig); + sp_free(nodes); + sp_free(terms); + return sum; +} + +/* hstack: zip the runs of isomorphic args */ +static expr *rewrite_hstack(Pass *p, expr *node) +{ + hstack_expr *hs = (hstack_expr *) node; + int n = hs->n_args; + uint64_t *sig = (uint64_t *) sp_malloc(n * sizeof(uint64_t)); + expr **pieces = (expr **) sp_malloc(n * sizeof(expr *)); + for (int i = 0; i < n; i++) + { + sig[i] = p->info[hs->args[i]->pass_id].sig; + rewire(p, &hs->args[i]); + pieces[i] = hs->args[i]; + } + int n_out = zip_runs(p, pieces, sig, n, false); + for (int i = 0; i < n_out && n_out < n; i++) + { + pieces[i] = shaped(pieces[i], node->d1, pieces[i]->size / node->d1); + } + expr *replacement = node; + if (n_out == 1) + { + replacement = pieces[0]; + } + else if (n_out < n) + { + replacement = new_hstack(pieces, n_out, node->n_vars); + } + sp_free(pieces); + sp_free(sig); + return replacement; +} + +int vectorize_exprs(expr **roots, int n_roots, int n_separate) +{ + Pass p = {0}; + for (int i = 0; i < n_roots; i++) + { + number_nodes(&p, roots[i]); + } + int n_original = p.n_info; /* the nodes under the roots */ + for (int i = 0; i < n_roots; i++) + { + p.info[roots[i]->pass_id].parents++; + } + /* an add whose only parent is an add belongs to that parent's chain; a + shared add starts its own chain */ + for (int i = 1; i <= n_original; i++) + { + expr *node = p.info[i].node; + if (expr_is_add(node)) + { + Info *left = &p.info[node->left->pass_id]; + Info *right = &p.info[node->right->pass_id]; + left->in_parent_chain = expr_is_add(left->node) && left->parents == 1; + right->in_parent_chain = expr_is_add(right->node) && right->parents == 1; + } + } + + /* children first: a node's children are final when it is rewritten */ + for (int i = 1; i <= n_original; i++) + { + expr *node = p.info[i].node, *replacement = node; + if (p.info[i].in_parent_chain) + continue; /* rewritten with its chain's head */ + if (expr_is_add(node)) + { + replacement = rewrite_chain(&p, node); + } + else if (expr_is_hstack(node)) + { + replacement = rewrite_hstack(&p, node); + } + else + { + rewire(&p, &node->left); + rewire(&p, &node->right); + } + p.info[i].replacement = replacement; /* after the call: zip moves p.info */ + if (replacement != node) + { + expr_retain(replacement); + } + } + + /* the roots; those after the first n_separate are a concatenation */ + uint64_t *sig = (uint64_t *) sp_malloc((n_roots + 1) * sizeof(uint64_t)); + for (int i = 0; i < n_roots; i++) + { + sig[i] = p.info[roots[i]->pass_id].sig; + roots[i] = p.info[roots[i]->pass_id].replacement; + } + int n_out = n_separate + zip_runs(&p, roots + n_separate, sig + n_separate, + n_roots - n_separate, false); + sp_free(sig); + + /* the caller's references to the new roots; then the pass drops its own, + which frees what was replaced and what it built and did not use */ + for (int i = 0; i < n_out; i++) + { + expr_retain(roots[i]); + } + for (int i = n_original + 1; i <= p.n_info; i++) + { + p.info[i].node->pass_id = 0; + } + for (int i = 0; i < p.n_memo; i++) + { + free_expr(p.memo[i].zip); + sp_free(p.memo[i].nodes); + } + for (int i = 1; i <= n_original; i++) + { + expr *node = p.info[i].node; + node->pass_id = 0; + if (p.info[i].replacement != node) + { + free_expr(p.info[i].replacement); + } + free_expr(node); + } + sp_free(p.memo); + sp_free(p.info); + return n_out; +} + +expr *vectorize_expr(expr *root) +{ + vectorize_exprs(&root, 1, 1); + return root; +} diff --git a/src/vectorize/vectorize_internal.h b/src/vectorize/vectorize_internal.h new file mode 100644 index 00000000..185eafee --- /dev/null +++ b/src/vectorize/vectorize_internal.h @@ -0,0 +1,107 @@ +/* + * Copyright 2026 Daniel Cederberg and William Zhang + * + * This file is part of the SparseDiffEngine project. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef VECTORIZE_INTERNAL_H +#define VECTORIZE_INTERNAL_H + +/* Shared by the two halves of the vectorization pass (see include/vectorize.h + for the design): zip.c and laws.c merge k nodes into one, pass.c decides + which nodes to merge. */ + +#include "atoms/affine.h" +#include "expr.h" +#include "sparsediff_linalg/tracked_alloc.h" +#include +#include +#include + +/* ------------------------------------------------------------------------ + The pass state: info[node->pass_id] for every node under the roots, + numbered children first. The pass holds a reference to these nodes, to + their replacements and to every zip, so nothing is freed while it runs. + ------------------------------------------------------------------------ */ +typedef struct +{ + expr *node; + expr *replacement; /* the node's replacement (itself until it is rewritten) */ + uint64_t sig; /* structure of the subtree: equal for isomorphic nodes */ + uint64_t sources; /* the nodes that the subtree's index nodes read from */ + int parents; /* references from other nodes' children, and from roots */ + int first_memo; /* 1 + index of the last zip built with this node first */ + bool in_parent_chain; /* an add that is part of its only parent's chain */ +} Info; + +typedef struct +{ + expr **nodes; /* a copy of the k nodes */ + int k; + expr *zip; + int next; /* 1 + index of the next zip with the same first node */ +} Memo; + +typedef struct +{ + Info *info; /* 1-based: the nodes under the roots, then nodes of the pass */ + int n_info, cap_info; + Memo *memo; + int n_memo, cap_memo; + int depth; /* of the recursion in zip */ +} Pass; + +/* room for element n of the array v */ +static inline void *grow(void *v, int n, int *cap, size_t size) +{ + if (n < *cap) + { + return v; + } + *cap = 2 * n + 64; + return sp_realloc(v, *cap * size); +} +#define PUSH(v, n, cap, x) ((v) = grow(v, n, &(cap), sizeof *(v)), (v)[(n)++] = (x)) + +/* give node the next number and a fresh Info */ +static inline Info *add_info(Pass *p, expr *node) +{ + p->info = (Info *) grow(p->info, p->n_info + 1, &p->cap_info, sizeof(Info)); + node->pass_id = ++p->n_info; + Info *info = &p->info[p->n_info]; + memset(info, 0, sizeof(Info)); + info->node = info->replacement = node; + return info; +} + +/* z, as a node of shape (d1, d2) */ +static inline expr *shaped(expr *z, int d1, int d2) +{ + return z->d1 == d1 && z->d2 == d2 ? z : new_reshape(z, d1, d2); +} + +/* ------------------------------------------------------------------------ + zip (zip.c): one node whose flat value is the concatenation of k nodes of + equal shape. Only the flat (column-major) layout of the result is defined. + ------------------------------------------------------------------------ */ + +/* Each zip is built once and remembered, so asking again returns the same + node. Falls back to an hstack of the nodes when no law applies. */ +expr *vec_zip(Pass *p, expr **nodes, int k); + +/* zip by one of the laws (laws.c), or NULL when no law does better than an + hstack of the nodes */ +expr *vec_try_zip(Pass *p, expr **nodes, int k); + +#endif /* VECTORIZE_INTERNAL_H */ diff --git a/src/vectorize/zip.c b/src/vectorize/zip.c new file mode 100644 index 00000000..c524dba5 --- /dev/null +++ b/src/vectorize/zip.c @@ -0,0 +1,91 @@ +/* + * Copyright 2026 Daniel Cederberg and William Zhang + * + * This file is part of the SparseDiffEngine project. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "subexpr.h" +#include "vectorize.h" +#include "vectorize_internal.h" +#include + +/* vec_zip: what is the same for every kind of node. Look up a zip built + before, try the laws (laws.c), fall back to an hstack, and remember the + result. */ + +/* zip recurses down the terms; below this depth it concatenates what is left */ +#define MAX_ZIP_DEPTH 1000 + +/* The zip of these k nodes, if it was built before. The zips are remembered + in a list under their first node. */ +static expr *find_zip(Pass *p, expr **nodes, int k) +{ + if (nodes[0]->pass_id == 0) + { + return NULL; /* a node the pass created, not yet in a zip */ + } + int entry = p->info[nodes[0]->pass_id].first_memo; + while (entry > 0) + { + Memo *memo = &p->memo[entry - 1]; + if (memo->k == k && memcmp(memo->nodes, nodes, k * sizeof(expr *)) == 0) + { + return memo->zip; + } + entry = memo->next; + } + return NULL; +} + +/* Remember z as the zip of these k nodes; the pass holds a reference to it */ +static void remember_zip(Pass *p, expr **nodes, int k, expr *z) +{ + if (nodes[0]->pass_id == 0) + { + add_info(p, nodes[0]); + } + Info *first = &p->info[nodes[0]->pass_id]; + Memo memo = {(expr **) sp_malloc(k * sizeof(expr *)), k, z, first->first_memo}; + memcpy(memo.nodes, nodes, k * sizeof(expr *)); + expr_retain(z); + PUSH(p->memo, p->n_memo, p->cap_memo, memo); + first->first_memo = p->n_memo; +} + +/* Each zip is built once, so shared subexpressions stay shared and the work + follows the DAG, not its expansion */ +expr *vec_zip(Pass *p, expr **nodes, int k) +{ + if (k == 1) + { + return nodes[0]; + } + expr *z = find_zip(p, nodes, k); + if (z != NULL) + { + return z; + } + p->depth++; + if (p->depth <= MAX_ZIP_DEPTH) + { + z = vec_try_zip(p, nodes, k); + } + p->depth--; + if (z == NULL) + { + z = new_hstack(nodes, k, nodes[0]->n_vars); + } + remember_zip(p, nodes, k, z); + return z; +} diff --git a/tests/all_tests.c b/tests/all_tests.c index 32b15cd7..2a4572a9 100644 --- a/tests/all_tests.c +++ b/tests/all_tests.c @@ -63,6 +63,7 @@ #include "problem/test_param_prob.h" #include "problem/test_param_source_refresh.h" #include "problem/test_problem.h" +#include "vectorize/test_vectorize.h" #include "wsum_hess/affine/test_broadcast.h" #include "wsum_hess/affine/test_convolve.h" #include "wsum_hess/affine/test_diag_mat.h" @@ -452,6 +453,37 @@ int main(void) mu_run_test(test_const_hstack_left_matmul, tests_run); mu_run_test(test_param_hstack_left_matmul, tests_run); mu_run_test(test_param_scalar_mult_convolve, tests_run); + printf("\n--- Vectorize Tests ---\n"); + mu_run_test(test_vectorize_sum_cos, tests_run); + mu_run_test(test_vectorize_least_squares, tests_run); + mu_run_test(test_vectorize_weighted_exp, tests_run); + mu_run_test(test_vectorize_dot_two_variables, tests_run); + mu_run_test(test_vectorize_separate_variables, tests_run); + mu_run_test(test_vectorize_shared_scalar, tests_run); + mu_run_test(test_vectorize_chain_under_exp, tests_run); + mu_run_test(test_vectorize_power_mismatch_fallback, tests_run); + mu_run_test(test_vectorize_nonstackable_fallback, tests_run); + mu_run_test(test_vectorize_updatable_params_preserved, tests_run); + mu_run_test(test_vectorize_hstack_args, tests_run); + mu_run_test(test_vectorize_nested_double_loop, tests_run); + mu_run_test(test_vectorize_inner_products, tests_run); + mu_run_test(test_vectorize_scalar_variables, tests_run); + mu_run_test(test_vectorize_doubling_dag, tests_run); + mu_run_test(test_vectorize_shared_chain_two_roots, tests_run); + mu_run_test(test_vectorize_problem_constraints, tests_run); + mu_run_test(test_vectorize_many_small_arrays, tests_run); + mu_run_test(test_vectorize_loop_invariant, tests_run); + mu_run_test(test_vectorize_shared_subexpression, tests_run); + mu_run_test(test_vectorize_coupled_recurrence, tests_run); + mu_run_test(test_vectorize_deep_terms, tests_run); + mu_run_test(test_vectorize_partial_sums, tests_run); + mu_run_test(test_vectorize_roots_under_a_replaced_node, tests_run); + mu_run_test(test_vectorize_two_zips_one_leader, tests_run); + mu_run_test(test_vectorize_duplicate_roots, tests_run); + mu_run_test(test_vectorize_min_group, tests_run); + mu_run_test(test_vectorize_vector_terms, tests_run); + mu_run_test(test_vectorize_few_entries_of_large_arrays, tests_run); + mu_run_test(test_vectorize_off, tests_run); #endif /* PROFILE_ONLY */ #ifdef PROFILE_ONLY diff --git a/tests/problem/test_param_broadcast.h b/tests/problem/test_param_broadcast.h index bd318425..9a1cb765 100644 --- a/tests/problem/test_param_broadcast.h +++ b/tests/problem/test_param_broadcast.h @@ -25,7 +25,7 @@ const char *test_constant_broadcast_vector_mult(void) expr *c_bcast = new_broadcast(c, 2, 3); expr *constraint = new_vector_mult(c_bcast, x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); problem_init_derivatives(prob); /* point for evaluating */ @@ -57,7 +57,7 @@ const char *test_constant_promote_vector_mult(void) expr *c_bcast = new_promote(c, 2, 3); expr *constraint = new_vector_mult(c_bcast, x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); problem_init_derivatives(prob); @@ -90,7 +90,7 @@ const char *test_param_broadcast_vector_mult(void) expr *c_bcast = new_broadcast(c, 2, 3); expr *constraint = new_vector_mult(c_bcast, x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); expr *param_nodes[1] = {c}; problem_register_params(prob, param_nodes, 1); @@ -139,7 +139,7 @@ const char *test_param_promote_vector_mult(void) expr *c_bcast = new_promote(c, 2, 3); expr *constraint = new_vector_mult(c_bcast, x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); expr *param_nodes[1] = {c}; problem_register_params(prob, param_nodes, 1); @@ -188,7 +188,7 @@ const char *test_const_sum_scalar_mult(void) expr *c_sum = new_sum(c, -1); expr *constraint = new_scalar_mult(c_sum, x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); problem_init_derivatives(prob); @@ -219,7 +219,7 @@ const char *test_param_sum_scalar_mult(void) expr *c_sum = new_sum(c, -1); expr *constraint = new_scalar_mult(c_sum, x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); expr *param_nodes[1] = {c}; problem_register_params(prob, param_nodes, 1); @@ -268,7 +268,7 @@ const char *test_const_hstack_left_matmul(void) expr *param_nodes[2] = {p1, p2}; expr *p_hstack = new_hstack(param_nodes, 2, 2 * n); expr *objective = new_left_matmul_dense(p_hstack, x, 1, 2 * n, NULL); - problem *prob = new_problem(objective, NULL, 0, false); + problem *prob = new_problem(objective, NULL, 0, false, true); problem_init_derivatives(prob); @@ -301,7 +301,7 @@ const char *test_param_hstack_left_matmul(void) expr *param_nodes[2] = {p1, p2}; expr *p_hstack = new_hstack(param_nodes, 2, 2 * n); expr *objective = new_left_matmul_dense(p_hstack, x, 1, 2 * n, NULL); - problem *prob = new_problem(objective, NULL, 0, false); + problem *prob = new_problem(objective, NULL, 0, false, true); problem_register_params(prob, param_nodes, 2); problem_init_derivatives(prob); @@ -354,7 +354,7 @@ const char *test_param_scalar_mult_convolve(void) expr *constraint = new_convolve(scaled_kernel, x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); expr *param_nodes[1] = {s}; problem_register_params(prob, param_nodes, 1); diff --git a/tests/problem/test_param_prob.h b/tests/problem/test_param_prob.h index 3bbf3f15..1c3b8a21 100644 --- a/tests/problem/test_param_prob.h +++ b/tests/problem/test_param_prob.h @@ -25,7 +25,7 @@ const char *test_param_scalar_mult_problem(void) expr *a_param = new_parameter(1, 1, 0, n, theta); expr *scaled = new_scalar_mult(a_param, log_x); expr *objective = new_sum(scaled, -1); - problem *prob = new_problem(objective, NULL, 0, false); + problem *prob = new_problem(objective, NULL, 0, false, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {a_param}; @@ -72,7 +72,7 @@ const char *test_param_scalar_mult_problem_with_constant(void) expr *c = new_parameter(1, 1, PARAM_FIXED, n, &c_val); expr *scaled = new_scalar_mult(a_param, new_add(new_sum(log_x, -1), c)); expr *objective = new_sum(scaled, -1); - problem *prob = new_problem(objective, NULL, 0, false); + problem *prob = new_problem(objective, NULL, 0, false, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {a_param}; @@ -117,7 +117,7 @@ const char *test_param_vector_mult_problem(void) expr *p_param = new_parameter(2, 1, 0, n, theta); expr *constraint = new_vector_mult(p_param, x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {p_param}; @@ -173,7 +173,7 @@ const char *test_param_left_matmul_problem(void) expr *constraint = new_left_matmul_dense(A_param, x, 2, 2, NULL); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); /* register parameters and fill sparsity patterns*/ expr *param_nodes[1] = {A_param}; @@ -233,7 +233,7 @@ const char *test_param_right_matmul_problem(void) expr *constraint = new_right_matmul_dense(A_param, x, 2, 2, NULL); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {A_param}; @@ -298,7 +298,7 @@ const char *test_param_fixed_skip_in_update(void) expr *sum_b_x = new_sum(b_x, -1); expr *objective = new_add(sum_a_log, sum_b_x); - problem *prob = new_problem(objective, NULL, 0, false); + problem *prob = new_problem(objective, NULL, 0, false, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {b_param}; @@ -349,7 +349,7 @@ const char *test_param_left_matmul_rectangular(void) expr *constraint = new_left_matmul_dense(A_param, x, 3, 2, NULL); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {A_param}; @@ -414,7 +414,7 @@ const char *test_param_right_matmul_rectangular(void) expr *constraint = new_right_matmul_dense(A_param, x, 2, 3, NULL); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {A_param}; @@ -480,7 +480,7 @@ const char *test_param_shared_left_matmul_problem(void) expr *constraints[2]; constraints[0] = new_left_matmul_dense(A_param, x, 2, 2, NULL); constraints[1] = new_left_matmul_dense(A_param, y, 2, 2, NULL); - problem *prob = new_problem(objective, constraints, 2, false); + problem *prob = new_problem(objective, constraints, 2, false, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {A_param}; @@ -549,7 +549,7 @@ const char *test_param_convolve_problem(void) expr *a_param = new_parameter(3, 1, 0, n, theta); expr *constraint = new_convolve(a_param, exp_x); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, true); + problem *prob = new_problem(objective, constraints, 1, true, true); /* register parameters and fill sparsity patterns */ expr *param_nodes[1] = {a_param}; @@ -639,7 +639,7 @@ const char *test_problem_jacobian_memcpy_skip(void) expr *exp_c = new_exp(x); expr *constraints[2] = {scaled, exp_c}; - problem *prob = new_problem(objective, constraints, 2, false); + problem *prob = new_problem(objective, constraints, 2, false, true); expr *param_nodes[1] = {a_param}; problem_register_params(prob, param_nodes, 1); problem_init_derivatives(prob); diff --git a/tests/problem/test_param_source_refresh.h b/tests/problem/test_param_source_refresh.h index 07f52f70..154edbde 100644 --- a/tests/problem/test_param_source_refresh.h +++ b/tests/problem/test_param_source_refresh.h @@ -47,7 +47,7 @@ const char *test_composite_source_left_matmul(void) expr *constraint = new_left_matmul_dense(coeff, x, 2, 2, NULL); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); expr *param_nodes[1] = {p}; problem_register_params(prob, param_nodes, 1); @@ -120,7 +120,7 @@ const char *test_composite_source_quad_form(void) expr *Q_src = new_vector_mult(new_promote(g, 2, 2), S_const); expr *objective = new_quad_form_dense(x, 2, NULL, Q_src); - problem *prob = new_problem(objective, NULL, 0, false); + problem *prob = new_problem(objective, NULL, 0, false, true); expr *param_nodes[1] = {g}; problem_register_params(prob, param_nodes, 1); @@ -185,7 +185,7 @@ const char *test_composite_source_nested_gates(void) expr *constraint = new_left_matmul_dense(coeff, x, 2, 2, NULL); expr *constraints[1] = {constraint}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); expr *param_nodes[1] = {p}; problem_register_params(prob, param_nodes, 1); @@ -256,7 +256,7 @@ const char *test_composite_source_kron(void) expr *Z = new_left_kron(coeff, X, 2, 2, 2, 2, active, 4); expr *objective = new_sum(Z, -1); - problem *prob = new_problem(objective, NULL, 0, false); + problem *prob = new_problem(objective, NULL, 0, false, true); expr *param_nodes[1] = {p}; problem_register_params(prob, param_nodes, 1); diff --git a/tests/problem/test_problem.h b/tests/problem/test_problem.h index 3b2c59c5..de5d803d 100644 --- a/tests/problem/test_problem.h +++ b/tests/problem/test_problem.h @@ -31,7 +31,7 @@ const char *test_problem_new_free(void) expr *constraints[1] = {x_constraint}; /* Create problem */ - problem *prob = new_problem(objective, constraints, 1, true); + problem *prob = new_problem(objective, constraints, 1, true, true); mu_assert("new_problem failed", prob != NULL); mu_assert("n_vars wrong", prob->n_vars == 3); @@ -57,7 +57,7 @@ const char *test_problem_objective_forward(void) expr *x_constraint = new_variable(3, 1, 0, 3); expr *constraints[1] = {x_constraint}; - problem *prob = new_problem(objective, constraints, 1, true); + problem *prob = new_problem(objective, constraints, 1, true, true); double u[3] = {1.0, 2.0, 3.0}; problem_init_derivatives(prob); @@ -105,7 +105,7 @@ const char *test_problem_constraint_forward(void) expr *constraints[2] = {log_c1, exp_c2}; - problem *prob = new_problem(objective, constraints, 2, true); + problem *prob = new_problem(objective, constraints, 2, true, true); double u[2] = {2.0, 4.0}; problem_init_derivatives(prob); @@ -131,7 +131,7 @@ const char *test_problem_gradient(void) expr *log_x = new_log(x); expr *objective = new_sum(log_x, -1); - problem *prob = new_problem(objective, NULL, 0, true); + problem *prob = new_problem(objective, NULL, 0, true, true); double u[3] = {1.0, 2.0, 4.0}; problem_init_derivatives(prob); @@ -167,7 +167,7 @@ const char *test_problem_jacobian(void) expr *constraints[1] = {log_c1}; - problem *prob = new_problem(objective, constraints, 1, true); + problem *prob = new_problem(objective, constraints, 1, true, true); double u[2] = {2.0, 4.0}; problem_init_derivatives(prob); @@ -231,7 +231,7 @@ const char *test_problem_jacobian_multi(void) expr *constraints[2] = {log_c1, exp_c2}; - problem *prob = new_problem(objective, constraints, 2, true); + problem *prob = new_problem(objective, constraints, 2, true, true); double u[2] = {2.0, 4.0}; problem_init_derivatives(prob); @@ -308,7 +308,7 @@ const char *test_problem_hessian(void) expr *constraints[2] = {exp_c1, sin_c2}; - problem *prob = new_problem(objective, constraints, 2, true); + problem *prob = new_problem(objective, constraints, 2, true, true); double u[3] = {1.0, 2.0, 3.0}; problem_init_derivatives(prob); @@ -363,7 +363,7 @@ const char *test_problem_hessian_shared_subexpr(void) expr *exp_log_x = new_exp(log_x); expr *constraints[2] = {log_x, exp_log_x}; - problem *prob = new_problem(objective, constraints, 2, false); + problem *prob = new_problem(objective, constraints, 2, false, true); problem_init_derivatives(prob); double u[3] = {1.0, 2.0, 3.0}; @@ -405,7 +405,7 @@ const char *test_problem_hessian_sum_exp_left_matmul_dense_transpose(void) expr *exp_AX = new_exp(AX); expr *objective = new_sum(exp_AX, -1); - problem *prob = new_problem(objective, NULL, 0, false); + problem *prob = new_problem(objective, NULL, 0, false, true); problem_init_derivatives(prob); problem_objective_forward(prob, u_vals); @@ -474,7 +474,7 @@ const char *test_problem_jacobian_spd_constraint_interleaved(void) expr *T = new_transpose(L); expr *constraints[1] = {T}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); problem_init_jacobian(prob); double u[6] = {0.1, 0.2, 0.3, -0.1, -0.2, -0.3}; @@ -525,7 +525,7 @@ const char *test_problem_jacobian_spd_sum_constraint(void) expr *S = new_sum(L, 1); expr *constraints[1] = {S}; - problem *prob = new_problem(objective, constraints, 1, false); + problem *prob = new_problem(objective, constraints, 1, false, true); problem_init_jacobian(prob); double u[6] = {0.1, 0.2, 0.3, -0.1, -0.2, -0.3}; diff --git a/tests/profiling/profile_lasso.h b/tests/profiling/profile_lasso.h index 8cd74ad9..bb336ffd 100644 --- a/tests/profiling/profile_lasso.h +++ b/tests/profiling/profile_lasso.h @@ -62,7 +62,7 @@ const char *profile_lasso(void) expr *c2 = new_add(new_neg(x), new_neg(t)); expr *constraints[2] = {c1, c2}; - problem *prob = new_problem(objective, constraints, 2, false); + problem *prob = new_problem(objective, constraints, 2, false, true); expr *param_nodes[1] = {lam}; problem_register_params(prob, param_nodes, 1); diff --git a/tests/profiling/profile_memory.h b/tests/profiling/profile_memory.h index fd9946bc..18f4ebe5 100644 --- a/tests/profiling/profile_memory.h +++ b/tests/profiling/profile_memory.h @@ -43,7 +43,7 @@ const char *profile_memory(void) expr *e = new_exp(AX); expr *cost = new_sum(e, -1); - problem *prob = new_problem(cost, NULL, 0, /*verbose=*/true); + problem *prob = new_problem(cost, NULL, 0, /*verbose=*/true, true); problem_init_derivatives(prob); problem_objective_forward(prob, u); diff --git a/tests/vectorize/test_vectorize.h b/tests/vectorize/test_vectorize.h new file mode 100644 index 00000000..8c088aea --- /dev/null +++ b/tests/vectorize/test_vectorize.h @@ -0,0 +1,1009 @@ +#ifndef TEST_VECTORIZE_H +#define TEST_VECTORIZE_H + +#include "atoms/affine.h" +#include "atoms/bivariate_full_dom.h" +#include "atoms/elementwise_full_dom.h" +#include "atoms/elementwise_restricted_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" +#include "vectorize.h" +#include +#include + +/* Tests of the re-vectorization pass (vectorize.h). The unrolled trees are + built the way the Python frontend emits them: x[i] is a scalar index node, + a Python float is a (1,1) fixed parameter, a - b is add(a, neg(b)) and a + Python sum is a left-deep chain of binary adds. */ + +static expr *vt_idx(expr *x, int i) +{ + return new_index(x, 1, 1, &i, 1); +} + +static expr *vt_cst(double v, int n_vars) +{ + return new_parameter(1, 1, PARAM_FIXED, n_vars, &v); +} + +static expr *vt_chain(expr **terms, int n) +{ + expr *acc = terms[0]; + for (int i = 1; i < n; i++) + { + acc = new_add(acc, terms[i]); + } + return acc; +} + +static void vt_fill_u(double *u, int n) +{ + for (int i = 0; i < n; i++) + { + u[i] = 0.3 + 0.17 * i - 0.05 * i * i / (double) n; + } +} + +/* Vectorize root, check that the result computes the same values as root at u + and that its analytic Jacobian and Hessian match finite differences. Frees + root; returns the vectorized tree (caller frees) or NULL on failure. */ +/* the pass on a root that nobody holds yet; the result is ours to free */ +static expr *vt_vectorize(expr *root) +{ + expr_retain(root); + expr *v = vectorize_expr(root); + free_expr(root); + return v; +} + +static expr *vt_check(expr *root, const double *u, int *ok) +{ + *ok = 1; + root->forward(root, u); + int size = root->size; + double *expected = (double *) malloc(size * sizeof(double)); + memcpy(expected, root->value, size * sizeof(double)); + + expr *v = vt_vectorize(root); + + v->forward(v, u); + if (v->size != size || !cmp_double_array(v->value, expected, size)) + { + *ok = 0; + } + free(expected); + if (!*ok) + { + return v; + } + + double *w = (double *) malloc(size * sizeof(double)); + for (int i = 0; i < size; i++) + { + w[i] = 1.0 + 0.1 * i; + } + if (!check_jacobian_num(v, u, NUMERICAL_DIFF_DEFAULT_H)) + { + *ok = 0; + } + if (!check_wsum_hess(v, u, w, NUMERICAL_DIFF_DEFAULT_H)) + { + *ok = 0; + } + free(w); + return v; +} + +/* sum_i cos(x_i) -> sum(cos(x)) with the bare variable restored */ +const char *test_vectorize_sum_cos(void) +{ + int n = 9, ok; + double u[9]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + terms[i] = new_cos(vt_idx(x, i)); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("sum cos numeric", ok); + mu_assert("root should be replaced", expr_is_sum(v)); + mu_assert("result is scalar", v->size == 1); + mu_assert("result is a sum over an n-vector", + v->left != NULL && v->left->size == n); + mu_assert("cos over the bare variable", v->left->left == x); + mu_assert("x kept alive by the new tree only", x->refcount == 1); + free_expr(v); + return 0; +} + +/* sum_i (x_i - b_i)^2: constants merge, shapes (n,1) vs (1,n) are aligned */ +const char *test_vectorize_least_squares(void) +{ + int n = 9, ok; + double u[9]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + expr *diff = new_add(vt_idx(x, i), new_neg(vt_cst(0.5 * i, n))); + terms[i] = new_power(diff, 2.0); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("least squares numeric", ok); + mu_assert("power over a length-n vector", v->left->size == n); + mu_assert("add over the bare variable", v->left->left->left == x); + free_expr(v); + return 0; +} + +/* sum_i a_i exp(x_i): scalar mults by constants become one vector mult */ +const char *test_vectorize_weighted_exp(void) +{ + int n = 9, ok; + double u[9]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + terms[i] = new_scalar_mult(vt_cst(1.0 + i, n), new_exp(vt_idx(x, i))); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("weighted exp numeric", ok); + mu_assert("one vector mult over exp(x)", + v->left->size == n && v->left->left->left == x); + free_expr(v); + return 0; +} + +/* sum_i x_i y_i -> multiply(x, y) on the bare-variable path */ +const char *test_vectorize_dot_two_variables(void) +{ + int n = 8, ok; + double u[16]; + vt_fill_u(u, 2 * n); + expr *x = new_variable(n, 1, 0, 2 * n); + expr *y = new_variable(n, 1, n, 2 * n); + expr *terms[8]; + for (int i = 0; i < n; i++) + { + terms[i] = new_elementwise_mult(vt_idx(x, i), vt_idx(y, i)); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("dot numeric", ok); + mu_assert("multiply(x, y)", v->left->left == x && v->left->right == y); + free_expr(v); + return 0; +} + +/* interleaved sum cos(x_i) + sum cos(y_i), x and y of one length: terms that + read different arrays are separate groups when each has enough terms */ +const char *test_vectorize_separate_variables(void) +{ + int n = 9, m = 9, ok; + double u[18]; + vt_fill_u(u, n + m); + expr *x = new_variable(n, 1, 0, n + m); + expr *y = new_variable(m, 1, n, n + m); + expr *terms[18]; + int t = 0; + for (int i = 0; i < m; i++) + { + if (i < n) + { + terms[t++] = new_cos(vt_idx(x, i)); + } + terms[t++] = new_cos(vt_idx(y, i)); + } + expr *v = vt_check(vt_chain(terms, t), u, &ok); + mu_assert("separate variables numeric", ok); + mu_assert("add of two sums", + expr_is_add(v) && v->left->size == 1 && v->right->size == 1); + mu_assert("cos(x) first, then cos(y)", + v->left->left->left == x && v->right->left->left == y); + free_expr(v); + return 0; +} + +/* variance sum_i (x_i - s)^2 with s = sum_i x_i shared by every term */ +const char *test_vectorize_shared_scalar(void) +{ + int n = 9, ok; + double u[9]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *xs[9]; + for (int i = 0; i < n; i++) + { + xs[i] = vt_idx(x, i); + } + expr *s = vt_chain(xs, n); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + terms[i] = new_power(new_add(vt_idx(x, i), new_neg(s)), 2.0); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("shared scalar numeric", ok); + free_expr(v); + return 0; +} + +/* a chain under a unary op: exp(sum_i exp(x_i)); the root is kept, rewired */ +const char *test_vectorize_chain_under_exp(void) +{ + int n = 9, ok; + double u[9]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + terms[i] = new_exp(vt_idx(x, i)); + } + expr *root = new_exp(vt_chain(terms, n)); + expr *v = vt_check(root, u, &ok); + mu_assert("chain under exp numeric", ok); + mu_assert("root kept", v == root); + mu_assert("chain replaced by sum(exp(x))", v->left->size == 1 && + v->left->left->size == n && + v->left->left->left == x); + free_expr(v); + return 0; +} + +/* mixed exponents are one group, but powers with different exponents are not + the same op: the group falls back to an hstack */ +const char *test_vectorize_power_mismatch_fallback(void) +{ + int n = 10, ok; + double u[10]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[10]; + for (int i = 0; i < n; i++) + terms[i] = new_power(vt_idx(x, i), i % 2 ? 3.0 : 2.0); + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("power mismatch numeric", ok); + mu_assert("sum over an hstack of the n powers", + v->size == 1 && expr_is_hstack(v->left) && + ((hstack_expr *) v->left)->n_args == n); + free_expr(v); + return 0; +} + +/* a non-stackable op inside the loop: cos(quad_form(x[i:i+2])) */ +const char *test_vectorize_nonstackable_fallback(void) +{ + int n = 10, ok; + double u[10]; + vt_fill_u(u, n); + double Q[4] = {2.0, 0.5, 0.5, 1.0}; + expr *x = new_variable(n, 1, 0, n); + expr *terms[9]; + for (int i = 0; i < n - 1; i++) + { + int idx[2] = {i, i + 1}; + expr *pair = new_index(x, 2, 1, idx, 2); + terms[i] = new_cos(new_quad_form_dense(pair, 2, Q, NULL)); + } + expr *v = vt_check(vt_chain(terms, n - 1), u, &ok); + mu_assert("nonstackable numeric", ok); + mu_assert("cos over an hstack of quad forms", + v->left->size == n - 1 && expr_is_hstack(v->left->left)); + free_expr(v); + return 0; +} + +/* sum_i theta_i x_i with updatable parameters: the parameter nodes survive and + problem_update_params keeps driving the gradient */ +const char *test_vectorize_updatable_params_preserved(void) +{ + int n = 8; + double theta[8] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; + expr *x = new_variable(n, 1, 0, n); + expr *params[8], *terms[8]; + for (int i = 0; i < n; i++) + { + params[i] = new_parameter(1, 1, i, n, &theta[i]); + terms[i] = new_scalar_mult(params[i], vt_idx(x, i)); + } + expr *root = vt_chain(terms, n); + problem *prob = new_problem(root, NULL, 0, false, true); + mu_assert("objective rewritten", prob->objective != root); + problem_register_params(prob, params, n); + problem_init_derivatives(prob); + + double u[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}; + problem_objective_forward(prob, u); + problem_gradient(prob); + mu_assert("gradient = theta", cmp_double_array(prob->gradient_values, theta, n)); + + double theta2[8] = {-1.0, 0.5, 2.5, 7.0, 0.0, 3.0, -2.0, 1.5}; + problem_update_params(prob, theta2); + problem_objective_forward(prob, u); + problem_gradient(prob); + mu_assert("gradient = updated theta", + cmp_double_array(prob->gradient_values, theta2, n)); + free_problem(prob); + return 0; +} + +/* hstack of scalar index nodes collapses; partial runs are zipped in place */ +const char *test_vectorize_hstack_args(void) +{ + int n = 8, ok; + double u[16]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *args[8]; + for (int i = 0; i < n; i++) + { + args[i] = vt_idx(x, i); + } + expr *v = vt_check(new_hstack(args, n, n), u, &ok); + mu_assert("full hstack numeric", ok); + mu_assert("collapsed to a reshape of x", v->size == n && v->left == x); + free_expr(v); /* frees x too */ + + vt_fill_u(u, 2 * n); + x = new_variable(2 * n, 1, 0, 2 * n); + expr *mixed[17]; + for (int i = 0; i < n; i++) + { + mixed[i] = new_sin(vt_idx(x, i)); + mixed[n + 1 + i] = new_sin(vt_idx(x, n + i)); + } + mixed[n] = vt_cst(3.0, 2 * n); + v = vt_check(new_hstack(mixed, 2 * n + 1, 2 * n), u, &ok); + mu_assert("partial hstack numeric", ok); + mu_assert("three pieces in order", expr_is_hstack(v) && + ((hstack_expr *) v)->n_args == 3 && + ((hstack_expr *) v)->args[1]->size == 1 && + ((hstack_expr *) v)->args[0]->size == n); + free_expr(v); + return 0; +} + +/* nested loops sum_i sum_j exp(x_i + y_j) flatten into one gather per variable */ +const char *test_vectorize_nested_double_loop(void) +{ + int m = 3, ok; + double u[6]; + vt_fill_u(u, 2 * m); + expr *x = new_variable(m, 1, 0, 2 * m); + expr *y = new_variable(m, 1, m, 2 * m); + expr *outer[3]; + for (int i = 0; i < m; i++) + { + expr *inner[3]; + for (int j = 0; j < m; j++) + { + inner[j] = new_exp(new_add(vt_idx(x, i), vt_idx(y, j))); + } + outer[i] = vt_chain(inner, m); + } + expr *v = vt_check(vt_chain(outer, m), u, &ok); + mu_assert("double loop numeric", ok); + mu_assert("one exp over m*m entries", v->size == 1 && v->left->size == m * m); + free_expr(v); + return 0; +} + +/* sum over inner products: sum_i (sum_j A_ij x_j - b_i)^2 zips the inner sums */ +const char *test_vectorize_inner_products(void) +{ + int n = 8, m = 8, ok; + double u[8]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *outer[8]; + for (int i = 0; i < m; i++) + { + expr *inner[8]; + for (int j = 0; j < n; j++) + { + inner[j] = + new_scalar_mult(vt_cst(0.1 * (i + 1) * (j + 2), n), vt_idx(x, j)); + } + expr *dot = new_add(vt_chain(inner, n), new_neg(vt_cst(0.3 * i, n))); + outer[i] = new_power(dot, 2.0); + } + expr *v = vt_check(vt_chain(outer, m), u, &ok); + mu_assert("inner products numeric", ok); + mu_assert("power over an m-vector", v->left->size == m); + free_expr(v); + return 0; +} + +/* a loop over n separate scalar variables (CVXPY style): the skeleton ignores + var_id, so the terms bucket and the variables are stacked */ +const char *test_vectorize_scalar_variables(void) +{ + int n = 9, ok; + double u[9]; + vt_fill_u(u, n); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + terms[i] = new_cos(new_variable(1, 1, i, n)); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("scalar variables numeric", ok); + mu_assert("sum(cos(hstack(v_i)))", + v->size == 1 && v->left->size == n && expr_is_hstack(v->left->left) && + ((hstack_expr *) v->left->left)->n_args == n); + free_expr(v); + return 0; +} + +/* s = cos(x0); s = s + s repeated: a 21-node DAG whose naive flattening has 2^20 + operands. Shared adds are operands, so the result stays O(depth). */ +const char *test_vectorize_doubling_dag(void) +{ + int depth = 20, ok; + double u[2] = {0.4, 0.7}; + expr *x = new_variable(2, 1, 0, 2); + expr *s = new_cos(vt_idx(x, 0)); + for (int j = 0; j < depth; j++) + { + s = new_add(s, s); + } + expr *v = vt_check(s, u, &ok); + mu_assert("doubling numeric", ok); + mu_assert("value is 2^20 cos(x0)", + fabs(v->value[0] - 1048576.0 * cos(u[0])) < 1e-6 * 1048576.0); + mu_assert("no blow-up", v->size == 1 && v->left != NULL && v->left->size <= 2); + free_expr(v); + return 0; +} + +/* a chain shared by two roots (objective and constraint) is vectorized once and + both roots point at the same sum node */ +const char *test_vectorize_shared_chain_two_roots(void) +{ + int n = 9; + double u[10]; + vt_fill_u(u, n + 1); + expr *x = new_variable(n, 1, 0, n + 1); + expr *y = new_variable(1, 1, n, n + 1); + expr *xs[9]; + for (int i = 0; i < n; i++) + { + xs[i] = vt_idx(x, i); + } + expr *s = vt_chain(xs, n); + expr *roots[2] = {new_add(s, new_cos(y)), new_neg(s)}; + expr *out[2] = {roots[0], roots[1]}; + expr_retain(roots[0]); + expr_retain(roots[1]); + mu_assert("two roots", vectorize_exprs(out, 2, 2) == 2); + free_expr(out[0]); /* the roots are unchanged: one reference is enough */ + free_expr(out[1]); + mu_assert("objective kept, rewired", out[0] == roots[0]); + mu_assert("constraint kept, rewired", out[1] == roots[1]); + expr *sum_node = roots[1]->left; + mu_assert("constraint sees sum(x)", + sum_node->size == 1 && sum_node != s && sum_node->left == x); + mu_assert("objective sees the same sum node", roots[0]->left == sum_node); + /* s was owned by the two roots only; releasing both references freed it */ + roots[0]->forward(roots[0], u); + roots[1]->forward(roots[1], u); + double sx = 0.0; + for (int i = 0; i < n; i++) + { + sx += u[i]; + } + mu_assert("values", fabs(roots[0]->value[0] - (sx + cos(u[n]))) < 1e-12 && + fabs(roots[1]->value[0] + sx) < 1e-12); + mu_assert("jacobians", + check_jacobian_num(roots[0], u, NUMERICAL_DIFF_DEFAULT_H) && + check_jacobian_num(roots[1], u, NUMERICAL_DIFF_DEFAULT_H)); + free_expr(roots[0]); + free_expr(roots[1]); + return 0; +} + +/* problem level: a loop of scalar constraints becomes one vector constraint + with the same Jacobian as the hand-written version */ +const char *test_vectorize_problem_constraints(void) +{ + int n = 9; + double u[9]; + vt_fill_u(u, n); + + /* unrolled: cos(x_i) - x_{i+1} == 0 */ + expr *x = new_variable(n, 1, 0, n); + expr *obj = new_sum(new_exp(x), -1); + expr_retain(obj); /* shared by three problems below */ + expr *cons[8]; + for (int i = 0; i < n - 1; i++) + { + cons[i] = new_add(new_cos(vt_idx(x, i)), new_neg(vt_idx(x, i + 1))); + } + problem *prob = new_problem(obj, cons, n - 1, false, true); + mu_assert("one vector constraint", + prob->n_constraints == 1 && prob->constraints[0]->size == n - 1); + mu_assert("total size unchanged", prob->total_constraint_size == n - 1); + problem_init_derivatives(prob); + problem_constraint_forward(prob, u); + problem_jacobian(prob); + + /* hand-written */ + int lo[8], hi[8]; + for (int i = 0; i < n - 1; i++) + { + lo[i] = i; + hi[i] = i + 1; + } + expr *hand = new_add(new_cos(new_index(x, n - 1, 1, lo, n - 1)), + new_neg(new_index(x, n - 1, 1, hi, n - 1))); + expr *hand_cons[1] = {hand}; + problem *ref = new_problem(obj, hand_cons, 1, false, true); + problem_init_derivatives(ref); + problem_constraint_forward(ref, u); + problem_jacobian(ref); + + mu_assert("constraint values", cmp_double_array(prob->constraint_values, + ref->constraint_values, n - 1)); + mu_assert("jacobian nnz", prob->jacobian->nnz == ref->jacobian->nnz); + mu_assert("jacobian rows", + cmp_int_array(prob->jacobian->p, ref->jacobian->p, n)); + mu_assert("jacobian cols", cmp_int_array(prob->jacobian->i, ref->jacobian->i, + ref->jacobian->nnz)); + mu_assert("jacobian vals", cmp_double_array(prob->jacobian->x, ref->jacobian->x, + ref->jacobian->nnz)); + free_problem(prob); + free_problem(ref); + + /* mixed list: a vector constraint, the isomorphic rows, then a different + row; the order and the other constraints' shapes are kept */ + expr *mixed[10]; + double expected[18]; + mixed[0] = new_sin(x); + for (int i = 0; i < n; i++) + { + expected[i] = sin(u[i]); + } + for (int i = 0; i < n - 1; i++) + { + mixed[1 + i] = new_add(new_cos(vt_idx(x, i)), new_neg(vt_idx(x, i + 1))); + expected[n + i] = cos(u[i]) - u[i + 1]; + } + mixed[n] = new_exp(vt_idx(x, 0)); + expected[2 * n - 1] = exp(u[0]); + problem *pm = new_problem(obj, mixed, n + 1, false, true); + mu_assert("three constraints", pm->n_constraints == 3 && + pm->constraints[0] == mixed[0] && + pm->constraints[1]->size == n - 1 && + pm->constraints[2]->size == 1); + problem_init_derivatives(pm); + problem_constraint_forward(pm, u); + mu_assert("mixed values in order", + cmp_double_array(pm->constraint_values, expected, 2 * n)); + free_problem(pm); + free_expr(obj); /* last owner of obj, and through it of x */ + return 0; +} + +/* sum of squares of the entries of ten 3-vectors: too few entries per array + for a group each, so they are one group over the concatenated arrays */ +const char *test_vectorize_many_small_arrays(void) +{ + int n_arrays = 10, len = 3, n = 30, ok; + double u[30]; + vt_fill_u(u, n); + expr *terms[30]; + for (int k = 0; k < n_arrays; k++) + { + expr *x = new_variable(len, 1, k * len, n); + for (int i = 0; i < len; i++) + { + terms[k * len + i] = new_power(vt_idx(x, i), 2.0); + } + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("many small arrays numeric", ok); + mu_assert("one sum of one power", expr_is_sum(v) && v->left->size == n); + mu_assert("over the ten arrays", + expr_is_hstack(v->left->left) && + ((hstack_expr *) v->left->left)->n_args == n_arrays); + free_expr(v); + return 0; +} + +/* x_i * exp(0.5 * a * b + 1), with the factor that does not depend on i built + again in every iteration: it is computed once and repeated */ +const char *test_vectorize_loop_invariant(void) +{ + int n = 9, ok; + double u[11]; + vt_fill_u(u, n + 2); + expr *x = new_variable(n, 1, 0, n + 2); + expr *a = new_variable(1, 1, n, n + 2); + expr *b = new_variable(1, 1, n + 1, n + 2); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + expr *ab = new_scalar_mult(vt_cst(0.5, n + 2), new_elementwise_mult(a, b)); + expr *factor = new_exp(new_add(ab, vt_cst(1.0, n + 2))); + terms[i] = new_elementwise_mult(vt_idx(x, i), factor); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("loop invariant numeric", ok); + expr *factor = v->left->right; + if (!expr_is_broadcast(factor)) + { + factor = factor->left; /* a reshape */ + } + mu_assert("x times a repeated scalar", v->left->size == n && + expr_is_broadcast(factor) && + factor->left->size == 1); + free_expr(v); + return 0; +} + +/* e_i * sin(e_i) with e_i = exp(x_i): the two uses of e_i stay one node, so + exp is evaluated once */ +const char *test_vectorize_shared_subexpression(void) +{ + int n = 9, ok; + double u[9]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + expr *e = new_exp(vt_idx(x, i)); + terms[i] = new_elementwise_mult(e, new_sin(e)); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("shared subexpression numeric", ok); + mu_assert("exp(x) * sin(exp(x)) over one exp(x)", + v->left->left == v->left->right->left && v->left->left->left == x); + free_expr(v); + return 0; +} + +/* n rollouts of m = p * q, p <- cos(m), q <- sin(m): each step uses both + states, so the expansion of a term has 2^steps nodes. The pass has to follow + the DAG, not the expansion. */ +const char *test_vectorize_coupled_recurrence(void) +{ + int n = 8, steps = 200, ok; + double u[16]; + vt_fill_u(u, 2 * n); + expr *x = new_variable(n, 1, 0, 2 * n); + expr *y = new_variable(n, 1, n, 2 * n); + expr *terms[8]; + for (int i = 0; i < n; i++) + { + expr *p = vt_idx(x, i), *q = vt_idx(y, i); + for (int t = 0; t < steps; t++) + { + expr *m = new_elementwise_mult(p, q); + p = new_cos(m); + q = new_sin(m); + } + terms[i] = new_elementwise_mult(p, q); + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("coupled recurrence numeric", ok); + mu_assert("coupled recurrence is one sum", v->left->size == n); + free_expr(v); + return 0; +} + +/* terms nested deeper than zip recurses (MAX_ZIP_DEPTH in zip.c, 1000): + the top of each term is vectorized and the rest is concatenated. Not much + deeper, since the engine's own recursion needs about 4 kB of stack per level + under AddressSanitizer. */ +const char *test_vectorize_deep_terms(void) +{ + int n = 8, depth = 1200, ok; + double u[8]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[8]; + for (int i = 0; i < n; i++) + { + terms[i] = vt_idx(x, i); + for (int t = 0; t < depth; t++) + { + terms[i] = new_sin(terms[i]); + } + } + expr *v = vt_check(vt_chain(terms, n), u, &ok); + mu_assert("deep terms numeric", ok); + mu_assert("deep terms are one sum", v->left->size == n); + free_expr(v); + return 0; +} + +/* partial sums s_i = s_{i-1} + x_i that are all used (as constraints): every + s_i is shared, so none is expanded into its own sum of i terms */ +const char *test_vectorize_partial_sums(void) +{ + int n = 12; + double u[12]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *cons[12]; + expr *s = vt_idx(x, 0); + for (int i = 1; i < n; i++) + { + s = new_add(s, vt_idx(x, i)); + cons[i - 1] = new_exp(s); + } + expr *obj = new_sum(x, -1); + problem *prob = new_problem(obj, cons, n - 1, false, true); + mu_assert("rows kept", prob->total_constraint_size == n - 1); + problem_init_derivatives(prob); + problem_constraint_forward(prob, u); + problem_jacobian(prob); + double acc = u[0]; + for (int i = 1; i < n; i++) + { + acc += u[i]; + mu_assert("partial sum values", + fabs(prob->constraint_values[i - 1] - exp(acc)) < 1e-12); + } + mu_assert("lower triangular jacobian", + prob->jacobian->nnz == n * (n + 1) / 2 - 1); + free_problem(prob); + return 0; +} + +/* constraints S_j = sum_i cos(x[8j+i]) that are also the terms of the + objective 0.5 * (S_0 + ... + S_7): every S_j is replaced, and so is the + objective's chain that was rewired to the replacements. The new constraints + must survive the release of the old chain. */ +const char *test_vectorize_roots_under_a_replaced_node(void) +{ + int m = 8, n = 64; + double u[64]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *S[8], *cons[9], *terms[8]; + for (int j = 0; j < m; j++) + { + for (int i = 0; i < m; i++) + { + terms[i] = new_cos(vt_idx(x, m * j + i)); + } + S[j] = vt_chain(terms, m); + } + for (int j = 0; j < 4; j++) + { + cons[j] = S[j]; + } + cons[4] = new_exp(vt_idx(x, 0)); /* keeps the S_j from merging */ + for (int j = 4; j < m; j++) + { + cons[j + 1] = S[j]; + } + expr *obj = new_scalar_mult(vt_cst(0.5, n), vt_chain(S, m)); + problem *prob = new_problem(obj, cons, m + 1, false, true); + mu_assert("nine constraints", prob->n_constraints == m + 1); + problem_init_derivatives(prob); + problem_constraint_forward(prob, u); + double total = 0.0; + for (int j = 0; j < m; j++) + { + double sj = 0.0; + for (int i = 0; i < m; i++) + { + sj += cos(u[m * j + i]); + } + mu_assert("constraint value", + fabs(prob->constraint_values[j < 4 ? j : j + 1] - sj) < 1e-12); + total += sj; + } + mu_assert("objective value", + fabs(problem_objective_forward(prob, u) - 0.5 * total) < 1e-12); + free_problem(prob); + return 0; +} + +/* two chains that both start with d_0 and continue with different d_i, where + d_i = f(f(...f(x_i))) and f(c) = exp(c + c): zips of two different lists + start with the same node at every level, and both have to be remembered */ +const char *test_vectorize_two_zips_one_leader(void) +{ + int n = 15, depth = 60; + expr *x = new_variable(n, 1, 0, n); + expr *d[15], *first[8], *second[8]; + for (int i = 0; i < n; i++) + { + d[i] = vt_idx(x, i); + for (int t = 0; t < depth; t++) + { + d[i] = new_exp(new_scalar_mult(vt_cst(0.01, n), new_add(d[i], d[i]))); + } + } + first[0] = second[0] = d[0]; + for (int i = 1; i < 8; i++) + { + first[i] = d[i]; + second[i] = d[7 + i]; + } + expr *roots[2] = {new_exp(vt_chain(first, 8)), new_exp(vt_chain(second, 8))}; + expr *out[2] = {roots[0], roots[1]}; + expr_retain(roots[0]); + expr_retain(roots[1]); + mu_assert("two roots", vectorize_exprs(out, 2, 2) == 2); + mu_assert("both vectorized", + expr_is_sum(out[0]->left) && expr_is_sum(out[1]->left)); + free_expr(roots[0]); + free_expr(roots[1]); + free_expr(out[0]); + free_expr(out[1]); + return 0; +} + +/* the same floating constraint passed twice, and replaced by the pass */ +const char *test_vectorize_duplicate_roots(void) +{ + int n = 9; + double u[9]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[9]; + for (int i = 0; i < n; i++) + { + terms[i] = new_cos(vt_idx(x, i)); + } + expr *c = vt_chain(terms, n); + expr *cons[2] = {c, c}; + expr *obj = new_sum(x, -1); + problem *prob = new_problem(obj, cons, 2, false, true); + mu_assert("two rows", prob->total_constraint_size == 2); + problem_init_derivatives(prob); + problem_constraint_forward(prob, u); + double expected = 0.0; + for (int i = 0; i < n; i++) + { + expected += cos(u[i]); + } + mu_assert("both rows", fabs(prob->constraint_values[0] - expected) < 1e-12 && + fabs(prob->constraint_values[1] - expected) < 1e-12); + free_problem(prob); + return 0; +} + +/* groups below VECTORIZE_MIN_GROUP are left alone; at the threshold they stack */ +const char *test_vectorize_min_group(void) +{ + int k = VECTORIZE_MIN_GROUP, ok; + int n = k; /* one variable entry per term of the long chain */ + + /* k - 1 like terms: untouched */ + expr *x = new_variable(n, 1, 0, n); + expr **terms = (expr **) malloc(k * sizeof(expr *)); + for (int i = 0; i < k - 1; i++) + { + terms[i] = new_cos(vt_idx(x, i)); + } + expr *root = vt_chain(terms, k - 1); + expr *v = vt_vectorize(root); + mu_assert("k - 1 terms are not stacked", v == root); + free_expr(root); + + /* k like terms: stacked, same values and derivatives */ + double *u = (double *) malloc(n * sizeof(double)); + vt_fill_u(u, n); + x = new_variable(n, 1, 0, n); + for (int i = 0; i < k; i++) + { + terms[i] = new_cos(vt_idx(x, i)); + } + v = vt_check(vt_chain(terms, k), u, &ok); + mu_assert("k terms are stacked", expr_is_sum(v)); + mu_assert("k terms numeric", ok); + free_expr(v); + free(u); + free(terms); + + /* hand-vectorized y**2 + z**2: the tree is left exactly as written */ + expr *y = new_variable(5, 1, 0, 10), *z = new_variable(5, 1, 5, 10); + expr *py = new_power(y, 2.0), *pz = new_power(z, 2.0); + root = new_add(py, pz); + v = vt_vectorize(root); + mu_assert("pair of vector terms: root kept", v == root); + mu_assert("pair of vector terms: operands kept", + root->left == py && root->right == pz && py->left == y && + pz->left == z); + free_expr(root); + return 0; +} + +/* a chain of vectors: sum_i cos(x[3i:3i+3]) is the row sums of one cos */ +const char *test_vectorize_vector_terms(void) +{ + int k = 9, m = 3, n = 27, ok; + double u[27]; + vt_fill_u(u, n); + expr *x = new_variable(n, 1, 0, n); + expr *terms[9]; + for (int i = 0; i < k; i++) + { + int idx[3] = {3 * i, 3 * i + 1, 3 * i + 2}; + terms[i] = new_cos(new_index(x, m, 1, idx, m)); + } + expr *v = vt_check(vt_chain(terms, k), u, &ok); + mu_assert("vector terms numeric", ok); + mu_assert("vector terms keep their shape", v->d1 == m && v->d2 == 1); + mu_assert("vector terms are merged", !expr_is_add(v)); + free_expr(v); + return 0; +} + +/* a few entries of each of two large arrays: neither array is gathered for + them (a gather costs time in the array's size), so the entries are + concatenated as they are */ +const char *test_vectorize_few_entries_of_large_arrays(void) +{ + int n = 200, ok; + double u[200]; + vt_fill_u(u, n); + expr *x = new_variable(100, 1, 0, n), *y = new_variable(100, 1, 100, n); + expr *terms[8]; + for (int i = 0; i < 4; i++) + { + terms[i] = new_cos(vt_idx(x, i)); + terms[4 + i] = new_cos(vt_idx(y, i)); + } + expr *v = vt_check(vt_chain(terms, 8), u, &ok); + mu_assert("few entries numeric", ok); + mu_assert("few entries: one cos over the eight entries", + expr_is_sum(v) && expr_is_hstack(v->left->left) && + ((hstack_expr *) v->left->left)->n_args == 8); + free_expr(v); + return 0; +} + +/* new_problem with vectorize off keeps the roots it is given */ +const char *test_vectorize_off(void) +{ + int n = 2 * VECTORIZE_MIN_GROUP; + expr *x = new_variable(n, 1, 0, n); + expr **terms = (expr **) malloc(n * sizeof(expr *)); + expr **cons = (expr **) malloc(n * sizeof(expr *)); + for (int i = 0; i < n; i++) + { + terms[i] = new_cos(vt_idx(x, i)); + cons[i] = new_exp(vt_idx(x, i)); + } + expr *obj = vt_chain(terms, n); + + problem *off = new_problem(obj, cons, n, false, false); + mu_assert("off: objective kept", off->objective == obj); + mu_assert("off: no pass time", off->stats.time_vectorize == 0.0); + mu_assert("off: constraints kept", off->n_constraints == n); + for (int i = 0; i < n; i++) + { + mu_assert("off: constraint kept", off->constraints[i] == cons[i]); + } + + problem *on = new_problem(obj, cons, n, false, true); + mu_assert("on: objective rewritten", on->objective != obj); + mu_assert("on: pass time", on->stats.time_vectorize > 0.0); + mu_assert("on: one vector constraint", + on->n_constraints == 1 && on->total_constraint_size == n); + + free_problem(off); + free_problem(on); + free(terms); + free(cons); + return 0; +} + +#endif /* TEST_VECTORIZE_H */ diff --git a/tests/wsum_hess/composite/test_shared_dag.h b/tests/wsum_hess/composite/test_shared_dag.h index 72e8555c..75b954ec 100644 --- a/tests/wsum_hess/composite/test_shared_dag.h +++ b/tests/wsum_hess/composite/test_shared_dag.h @@ -121,7 +121,8 @@ static problem *build_root_problem(bool shared) 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 *prob = + new_problem(new_sum(new_sin(g_obj), -1), constraints, 2, false, true); problem_init_derivatives(prob); return prob; }