Changeset: 5854cb32f0c8 for MonetDB
URL: https://dev.monetdb.org/hg/MonetDB/rev/5854cb32f0c8
Modified Files:
        monetdb5/modules/kernel/vss.c
        sql/backends/monet5/rel_bin.c
        sql/server/rel_exp.c
        sql/server/rel_exp.h
Branch: nested
Log Message:

add initial bond optimization


diffs (truncated from 762 to 300 lines):

diff --git a/monetdb5/modules/kernel/vss.c b/monetdb5/modules/kernel/vss.c
--- a/monetdb5/modules/kernel/vss.c
+++ b/monetdb5/modules/kernel/vss.c
@@ -11,12 +11,18 @@
 /*
  * BOND: Branch-and-bound ON Decomposed data
  *
- * MAL module providing k-NN search and L2 squared distance computation
- * on decomposed vector columns (one BAT per dimension).
+ * Vector columns are stored decomposed: each dimension is a separate BAT.
+ * BOND exploits this layout by computing partial L2 distances dimension
+ * by dimension, pruning candidates whose partial distance already exceeds
+ * the current k-th best after each batch of dimensions.
+ * Dimension ordering: dimensions are processed in decreasing order of
+ * |query[d] - mean[d]|, so that the most discriminating dimensions come
+ * first and pruning kicks in early.
  */
 
 
 /* monetdb_config.h must be included as the first include file */
+#include "mal_errors.h"
 #include <monetdb_config.h>
 #include <gdk.h>
 
@@ -35,7 +41,268 @@
 #include <stddef.h>
 #include <stdint.h>
 
-#define DIMENSION_MISMATCH_ERR "Vector dimensions mismatch"
+#define DIMENSION_MISMATCH_ERR "Dimensions mismatch error"
+
+typedef struct bond_collection {
+       BAT **dims;        /* array of dimension BATs (not owned, just 
referenced) */
+       int ndims;         /* number of dimensions */
+       BUN nvecs;         /* number of vectors (rows) */
+       dbl *dim_means;    /* mean value per dimension (for dimension ordering) 
*/
+       dbl *dim_max;           /* max value per dimension */
+       dbl *dim_min;           /* min value per dimension */
+       dbl kth_upper;          /* kth upper bound */
+} bond_collection;
+
+/* Helper: comparison function for sorting dimensions by discriminating power 
*/
+typedef struct {
+       int dim;
+       dbl score;
+} dim_score;
+
+static int
+dim_score_cmp(const void *a, const void *b)
+{
+       dbl sa = ((const dim_score *)a)->score;
+       dbl sb = ((const dim_score *)b)->score;
+       /* descending order */
+       if (sa > sb)
+               return -1;
+       if (sa < sb)
+               return 1;
+       return 0;
+}
+
+/*
+ * bond_dim_order: return an array of dimension indices sorted by
+ * |query[d] - mean[d]| descending (most discriminating first).
+ */
+static int *
+bond_dim_order(allocator *ma, bond_collection *bc, const dbl *query_vals)
+{
+       dim_score *scores = ma_alloc(ma, bc->ndims * sizeof(dim_score));
+       int *order = ma_alloc(ma, bc->ndims * sizeof(int));
+
+       if (!scores || !order) {
+               TRC_ERROR(MAL_SERVER, "bond_dim_order: allocation failed\n");
+               return NULL;
+       }
+
+       for (int d = 0; d < bc->ndims; d++) {
+               scores[d].dim = d;
+               dbl diff = query_vals[d] - bc->dim_means[d];
+               scores[d].score = diff < 0 ? -diff : diff;
+       }
+
+       qsort(scores, bc->ndims, sizeof(dim_score), dim_score_cmp);
+
+       for (int i = 0; i < bc->ndims; i++)
+               order[i] = scores[i].dim;
+
+       return order;
+}
+
+static bond_collection *
+bond_create(allocator *ma, BAT **dim_bats, int ndims)
+{
+       if (dim_bats && ndims > 0) {
+               bond_collection *bc = ma_alloc(ma, sizeof(bond_collection));
+               *bc = (bond_collection) {
+                       .ndims = ndims,
+                       .kth_upper = DBL_MAX,
+               };
+               if (bc) {
+                       bc->dims = ma_alloc(ma, ndims * sizeof(BAT *));
+                       bc->dim_means = ma_alloc(ma, ndims * sizeof(dbl));
+                       bc->dim_max = ma_alloc(ma, ndims * sizeof(dbl));
+                       bc->dim_min = ma_alloc(ma, ndims * sizeof(dbl));
+                       bc->nvecs = BATcount(dim_bats[0]);
+                       for (int d = 0; d < ndims; d++) {
+                               BAT *b = dim_bats[d];
+                               bc->dims[d] = b;
+                               dbl avg;
+                               BUN cnt;
+                               if (BATcalcavg(b, NULL, &avg, &cnt, 0) != 
GDK_SUCCEED)
+                                       return NULL;
+                               bc->dim_means[d] = avg;
+                               bc->dim_max[d] = *(dbl*)BATmax(b, NULL);
+                               bc->dim_min[d] = *(dbl*)BATmin(b, NULL);
+                       }
+                       return bc;
+               }
+       }
+       return NULL;
+}
+
+
+static dbl
+bond_upper_bound(bond_collection *bc, const dbl *query_vals, BUN k, dbl *acc, 
dbl *res)
+{
+       for (int i = 0; i < bc->ndims; i++) {
+               BAT *b = bc->dims[i];
+               size_t cnt = BATcount(b);
+               assert(cnt > k);
+               dbl *d = (dbl*) Tloc(b, 0);
+               dbl q = query_vals[i];
+               for (BUN j=0; j<k && j<cnt; j++) {
+                       dbl diff = q - d[j];
+                       dbl sq = diff * diff;
+                       acc[j] += sq;
+                       if (acc[j] > *res)
+                               *res = acc[j];
+               }
+       }
+       return *res;
+}
+
+
+static char*
+bond_search(bond_collection *bc, const dbl *query_vals,
+                       BUN k, int *dim_order, BAT *cands,
+                       BAT **oid_result, BAT **dist_result)
+{
+       BAT *partial = NULL;
+       BAT *candidates = cands;
+       bool own_candidates = false;
+
+       if (!bc || !query_vals || k == 0 || !oid_result || !dist_result || 
!dim_order)
+               throw(MAL, "vss.bond_search", "invalid arguments");
+
+       *oid_result = NULL;
+       *dist_result = NULL;
+
+       for (int i = 0; i < bc->ndims; i++) {
+               int d = dim_order[i];
+
+               ValRecord qval = {.vtype = TYPE_dbl};
+               qval.val.dval = query_vals[d];
+
+               /* diff = dim[d] - query[d] */
+               BAT *diff = BATcalcsubcst(bc->dims[d], &qval, candidates, 
TYPE_dbl);
+               if (!diff)
+                       goto bailout;
+
+               /* sq = diff * diff */
+               BAT *sq = BATcalcmul(diff, diff, NULL, NULL, TYPE_dbl);
+               BBPreclaim(diff);
+               if (!sq)
+                       goto bailout;
+
+               if (partial) {
+                       BAT *new_partial = BATcalcadd(partial, sq, NULL, NULL, 
TYPE_dbl);
+                       BBPreclaim(partial);
+                       BBPreclaim(sq);
+                       if (!new_partial)
+                               goto bailout;
+                       partial = new_partial;
+               } else {
+                       partial = sq;
+               }
+
+               /* Prune after every m=2 step dimension (except the last) when
+                * there are more than 2*k candidates remaining */
+               int step = 2;
+               if ((i % step == 0) && i > 0 && i < (bc->ndims - 1) && 
BATcount(partial) > k * 2) {
+                       BAT *topn_oids = NULL;
+                       BAT *oids = NULL;
+
+                       if (BATfirstn(&topn_oids, NULL, partial, NULL,
+                                     NULL, k, true, false, false) != 
GDK_SUCCEED)
+                               goto bailout;
+
+                       ///* Find the k-th (worst) distance among top-k */
+                       BATiter pi = bat_iterator(partial);
+                       BATiter ti = bat_iterator(topn_oids);
+                       dbl kth_dist = DBL_MAX;
+                       for (BUN j = 0; j < BATcount(topn_oids); j++) {
+                               oid o = BATtdense(topn_oids)? 
topn_oids->tseqbase + j : ((const oid *)ti.base)[j];
+                               dbl v = ((const dbl *)pi.base)[o - 
partial->hseqbase];
+                               if (v > kth_dist || kth_dist == DBL_MAX)
+                                       kth_dist = v;
+                       }
+                       bat_iterator_end(&ti);
+                       bat_iterator_end(&pi);
+                       BBPreclaim(topn_oids);
+                       dbl theoretical_reminder = 0.0;
+                       for (int j=i+1; j < bc->ndims; j++) {
+                               // calc theoretical upper bound
+                               dbl min_val = bc->dim_min[j];
+                               dbl max_val = bc->dim_max[j];
+                               dbl d1 = query_vals[j] - min_val;
+                               dbl d2 = query_vals[j] - max_val;
+                               dbl sq = fmax(d1*d1, d2*d2);
+                               theoretical_reminder += sq;
+                       }
+
+                       // potentially tighten upper bound
+                       if (kth_dist != DBL_MAX && (bc->kth_upper > (kth_dist + 
theoretical_reminder)))
+                               bc->kth_upper = kth_dist + theoretical_reminder;
+
+                       /* Keep only candidates whose partial distance <= 
kth_dist */
+                       dbl zero = 0.0;
+                       BAT *new_cands = BATselect(partial, NULL,
+                                                  &zero, &bc->kth_upper,
+                                                  true, true, false, false);
+                       if (!new_cands)
+                               goto bailout;
+                       BAT *new_partial = BATproject(new_cands, partial);
+                       if (!new_partial) {
+                               BBPreclaim(new_cands);
+                               goto bailout;
+                       }
+                       BBPreclaim(partial);
+
+                       if (own_candidates) {
+                               oids = BATproject(new_cands, candidates);
+                               BBPreclaim(new_cands);
+                               BBPreclaim(candidates);
+                               candidates = oids;
+                       } else {
+                               candidates = new_cands;
+                       }
+                       partial = new_partial;
+                       own_candidates = true;
+               }
+
+               if (candidates && BATcount(candidates) < 10*k)
+                       break;
+       }
+
+       /* Final top-k selection */
+       {
+               BAT *topn_oids = NULL;
+               BAT *res_oids = NULL;
+
+               if (BATfirstn(&topn_oids, NULL, partial, NULL,
+                             NULL, k, true, false, false) != GDK_SUCCEED)
+                       goto bailout;
+
+               /* Project distances through top-k oids */
+               BAT *result_dists = BATproject(topn_oids, partial);
+               BBPreclaim(partial);
+               if (!result_dists) {
+                       BBPreclaim(topn_oids);
+                       goto bailout;
+               }
+               if (own_candidates) {
+                       res_oids = BATproject(topn_oids, candidates);
+                       BBPreclaim(candidates);
+                       BBPreclaim(topn_oids);
+               } else {
+                       res_oids = topn_oids;
+               }
+
+               *oid_result = res_oids;
+               *dist_result = result_dists;
+       }
+
+       return MAL_SUCCEED;
+
+bailout:
+       BBPreclaim(partial);
+       if (own_candidates)
+               BBPreclaim(candidates);
+       throw(MAL, "vss.bond_search", GDK_EXCEPTION);
+}
 
 /**
  * @brief Generic Macro to generate L1(Manhattan) distance functions.
@@ -208,33 +475,6 @@ DEFINE_SCALAR_HANDLER(l1, f64, dbl, dbl)
 DEFINE_SCALAR_HANDLER(cos, f64, dbl, dbl)
 
 
-//static char*
-//l2sq_distance(Client ctx, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci)
_______________________________________________
checkin-list mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to