distances.cpp 31.1 KB
Newer Older
J
JinHai-CN 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

// -*- c++ -*-

#include <faiss/utils/distances.h>

#include <cstdio>
#include <cassert>
#include <cstring>
#include <cmath>

#include <omp.h>

C
Cai Yudong 已提交
19
#include <faiss/FaissHook.h>
J
JinHai-CN 已提交
20 21
#include <faiss/impl/AuxIndexStructures.h>
#include <faiss/impl/FaissAssert.h>
22
#include <faiss/utils/ConcurrentBitset.h>
J
JinHai-CN 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149


#ifndef FINTEGER
#define FINTEGER long
#endif


extern "C" {

/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */

int sgemm_ (const char *transa, const char *transb, FINTEGER *m, FINTEGER *
            n, FINTEGER *k, const float *alpha, const float *a,
            FINTEGER *lda, const float *b, FINTEGER *
            ldb, float *beta, float *c, FINTEGER *ldc);

/* Lapack functions, see http://www.netlib.org/clapack/old/single/sgeqrf.c */

int sgeqrf_ (FINTEGER *m, FINTEGER *n, float *a, FINTEGER *lda,
                 float *tau, float *work, FINTEGER *lwork, FINTEGER *info);

int sgemv_(const char *trans, FINTEGER *m, FINTEGER *n, float *alpha,
           const float *a, FINTEGER *lda, const float *x, FINTEGER *incx,
           float *beta, float *y, FINTEGER *incy);

}


namespace faiss {


/***************************************************************************
 * Matrix/vector ops
 ***************************************************************************/



/* Compute the inner product between a vector x and
   a set of ny vectors y.
   These functions are not intended to replace BLAS matrix-matrix, as they
   would be significantly less efficient in this case. */
void fvec_inner_products_ny (float * ip,
                             const float * x,
                             const float * y,
                             size_t d, size_t ny)
{
    // Not sure which one is fastest
#if 0
    {
        FINTEGER di = d;
        FINTEGER nyi = ny;
        float one = 1.0, zero = 0.0;
        FINTEGER onei = 1;
        sgemv_ ("T", &di, &nyi, &one, y, &di, x, &onei, &zero, ip, &onei);
    }
#endif
    for (size_t i = 0; i < ny; i++) {
        ip[i] = fvec_inner_product (x, y, d);
        y += d;
    }
}





/* Compute the L2 norm of a set of nx vectors */
void fvec_norms_L2 (float * __restrict nr,
                    const float * __restrict x,
                    size_t d, size_t nx)
{

#pragma omp parallel for
    for (size_t i = 0; i < nx; i++) {
        nr[i] = sqrtf (fvec_norm_L2sqr (x + i * d, d));
    }
}

void fvec_norms_L2sqr (float * __restrict nr,
                       const float * __restrict x,
                       size_t d, size_t nx)
{
#pragma omp parallel for
    for (size_t i = 0; i < nx; i++)
        nr[i] = fvec_norm_L2sqr (x + i * d, d);
}



void fvec_renorm_L2 (size_t d, size_t nx, float * __restrict x)
{
#pragma omp parallel for
    for (size_t i = 0; i < nx; i++) {
        float * __restrict xi = x + i * d;

        float nr = fvec_norm_L2sqr (xi, d);

        if (nr > 0) {
            size_t j;
            const float inv_nr = 1.0 / sqrtf (nr);
            for (j = 0; j < d; j++)
                xi[j] *= inv_nr;
        }
    }
}












/***************************************************************************
 * KNN functions
 ***************************************************************************/



/* Find the nearest neighbors for nx queries in a set of ny vectors */
static void knn_inner_product_sse (const float * x,
                        const float * y,
                        size_t d, size_t nx, size_t ny,
150 151
                        float_minheap_array_t * res,
                        ConcurrentBitsetPtr bitset = nullptr)
J
JinHai-CN 已提交
152 153 154
{
    size_t k = res->k;

155
    size_t thread_max_num = omp_get_max_threads();
156
    
S
shengjun.li 已提交
157 158 159 160
    size_t thread_heap_size = nx * k;
    size_t all_heap_size = thread_heap_size * thread_max_num;
    float *value = new float[all_heap_size];
    int64_t *labels = new int64_t[all_heap_size];
161

S
shengjun.li 已提交
162 163
    // init heap
    for (size_t i = 0; i < all_heap_size; i++) {
164 165 166
        value[i] = -1.0 / 0.0;
        labels[i] = -1;
    }
J
JinHai-CN 已提交
167 168

#pragma omp parallel for
169 170 171 172 173 174 175 176
    for (size_t j = 0; j < ny; j++) {
        if(!bitset || !bitset->test(j)) {
            size_t thread_no = omp_get_thread_num();
            const float *y_j = y + j * d;
            for (size_t i = 0; i < nx; i++) {
                const float *x_i = x + i * d;
                float ip = fvec_inner_product (x_i, y_j, d);

S
shengjun.li 已提交
177 178
                float * val_ = value + thread_no * thread_heap_size + i * k;
                int64_t * ids_ = labels + thread_no * thread_heap_size + i * k;
179
                if (ip > val_[0]) {
S
shengjun.li 已提交
180
                    minheap_swap_top (k, val_, ids_, ip, j);
181 182
                }
            }
183 184
        }
    }
J
JinHai-CN 已提交
185

186
    for (size_t t = 1; t < thread_max_num; t++) {
S
shengjun.li 已提交
187
        // merge heap
188 189 190
        for (size_t i = 0; i < nx; i++) {
            float * __restrict value_x = value + i * k;
            int64_t * __restrict labels_x = labels + i * k;
S
shengjun.li 已提交
191 192
            float *value_x_t = value_x + t * thread_heap_size;
            int64_t *labels_x_t = labels_x + t * thread_heap_size;
193 194
            for (size_t j = 0; j < k; j++) {
                if (value_x_t[j] > value_x[0]) {
S
shengjun.li 已提交
195
                    minheap_swap_top (k, value_x, labels_x, value_x_t[j], labels_x_t[j]);
196 197 198
                }
            }
        }
199
    }
J
JinHai-CN 已提交
200

201 202 203 204 205 206 207
    for (size_t i = 0; i < nx; i++) {
        float * value_x = value + i * k;
        int64_t * labels_x = labels + i * k;
        minheap_reorder (k, value_x, labels_x);
    }

    // copy result
S
shengjun.li 已提交
208 209
    memcpy(res->val, value, thread_heap_size * sizeof(float));
    memcpy(res->ids, labels, thread_heap_size * sizeof(int64_t));
210 211 212 213 214 215

    delete[] value;
    delete[] labels;

/*
    else {
216 217 218 219 220 221 222 223 224 225 226 227 228
        size_t check_period = InterruptCallback::get_period_hint (ny * d);
        check_period *= thread_max_num;

        for (size_t i0 = 0; i0 < nx; i0 += check_period) {
            size_t i1 = std::min(i0 + check_period, nx);

#pragma omp parallel for
            for (size_t i = i0; i < i1; i++) {
                const float * x_i = x + i * d;
                const float * y_j = y;

                float * __restrict simi = res->get_val(i);
                int64_t * __restrict idxi = res->get_ids (i);
J
JinHai-CN 已提交
229

230 231 232 233 234 235 236 237 238 239
                minheap_heapify (k, simi, idxi);

                for (size_t j = 0; j < ny; j++) {
                    if(!bitset || !bitset->test(j)){
                        float ip = fvec_inner_product (x_i, y_j, d);

                        if (ip > simi[0]) {
                            minheap_pop (k, simi, idxi);
                            minheap_push (k, simi, idxi, ip, j);
                        }
240
                    }
241
                    y_j += d;
J
JinHai-CN 已提交
242
                }
243
                minheap_reorder (k, simi, idxi);
J
JinHai-CN 已提交
244
            }
245
            InterruptCallback::check ();
J
JinHai-CN 已提交
246 247
        }
    }
248
    */
J
JinHai-CN 已提交
249 250 251 252 253 254
}

static void knn_L2sqr_sse (
                const float * x,
                const float * y,
                size_t d, size_t nx, size_t ny,
255 256
                float_maxheap_array_t * res,
                ConcurrentBitsetPtr bitset = nullptr)
J
JinHai-CN 已提交
257 258 259
{
    size_t k = res->k;

260
    size_t thread_max_num = omp_get_max_threads();
J
JinHai-CN 已提交
261

S
shengjun.li 已提交
262 263 264 265
    size_t thread_heap_size = nx * k;
    size_t all_heap_size = thread_heap_size * thread_max_num;
    float *value = new float[all_heap_size];
    int64_t *labels = new int64_t[all_heap_size];
266

S
shengjun.li 已提交
267 268
    // init heap
    for (size_t i = 0; i < all_heap_size; i++) {
269 270 271 272
        value[i] = 1.0 / 0.0;
        labels[i] = -1;
    }

J
JinHai-CN 已提交
273
#pragma omp parallel for
274 275 276 277 278 279 280 281
    for (size_t j = 0; j < ny; j++) {
        if(!bitset || !bitset->test(j)) {
            size_t thread_no = omp_get_thread_num();
            const float *y_j = y + j * d;
            for (size_t i = 0; i < nx; i++) {
                const float *x_i = x + i * d;
                float disij = fvec_L2sqr (x_i, y_j, d);

S
shengjun.li 已提交
282 283
                float * val_ = value + thread_no * thread_heap_size + i * k;
                int64_t * ids_ = labels + thread_no * thread_heap_size + i * k;
284
                if (disij < val_[0]) {
S
shengjun.li 已提交
285
                    maxheap_swap_top (k, val_, ids_, disij, j);
J
JinHai-CN 已提交
286
                }
287
            }
288 289
        }
    }
290

291
    for (size_t t = 1; t < thread_max_num; t++) {
S
shengjun.li 已提交
292
        // merge heap
293 294 295
        for (size_t i = 0; i < nx; i++) {
            float * __restrict value_x = value + i * k;
            int64_t * __restrict labels_x = labels + i * k;
S
shengjun.li 已提交
296 297
            float *value_x_t = value_x + t * thread_heap_size;
            int64_t *labels_x_t = labels_x + t * thread_heap_size;
298 299
            for (size_t j = 0; j < k; j++) {
                if (value_x_t[j] < value_x[0]) {
S
shengjun.li 已提交
300
                    maxheap_swap_top (k, value_x, labels_x, value_x_t[j], labels_x_t[j]);
301
                }
J
JinHai-CN 已提交
302 303
            }
        }
304 305 306 307 308 309 310 311 312
    }

    for (size_t i = 0; i < nx; i++) {
        float * value_x = value + i * k;
        int64_t * labels_x = labels + i * k;
        maxheap_reorder (k, value_x, labels_x);
    }

    // copy result
S
shengjun.li 已提交
313 314
    memcpy(res->val, value, thread_heap_size * sizeof(float));
    memcpy(res->ids, labels, thread_heap_size * sizeof(int64_t));
315 316 317

    delete[] value;
    delete[] labels;
J
JinHai-CN 已提交
318

319 320
    /*
    else {
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
        size_t check_period = InterruptCallback::get_period_hint (ny * d);
        check_period *= thread_max_num;

        for (size_t i0 = 0; i0 < nx; i0 += check_period) {
            size_t i1 = std::min(i0 + check_period, nx);

#pragma omp parallel for
            for (size_t i = i0; i < i1; i++) {
                const float * x_i = x + i * d;
                const float * y_j = y;
                float * simi = res->get_val(i);
                int64_t * idxi = res->get_ids (i);

                maxheap_heapify (k, simi, idxi);

                for (size_t j = 0; j < ny; j++) {
                    if(!bitset || !bitset->test(j)){
                        float disij = fvec_L2sqr (x_i, y_j, d);

                        if (disij < simi[0]) {
                            maxheap_pop (k, simi, idxi);
                            maxheap_push (k, simi, idxi, disij, j);
                        }
                    }
                    y_j += d;
                }
                maxheap_reorder (k, simi, idxi);
            }
            InterruptCallback::check ();
        }
    }
352
    */
J
JinHai-CN 已提交
353 354
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
static void elkan_L2_sse (
        const float * x,
        const float * y,
        size_t d, size_t nx, size_t ny,
        float_maxheap_array_t * res) {

    if (nx == 0 || ny == 0) {
        return;
    }

    const size_t bs_y = 1024;
    float *data = (float *) malloc((bs_y * (bs_y - 1) / 2) * sizeof (float));

    for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
        size_t j1 = j0 + bs_y;
        if (j1 > ny) j1 = ny;

        auto Y = [&](size_t i, size_t j) -> float& {
            assert(i != j);
            i -= j0, j -= j0;
            return (i > j) ? data[j + i * (i - 1) / 2] : data[i + j * (j - 1) / 2];
        };

#pragma omp parallel for
        for (size_t i = j0 + 1; i < j1; i++) {
            const float *y_i = y + i * d;
            for (size_t j = j0; j < i; j++) {
                const float *y_j = y + j * d;
                Y(i, j) = sqrt(fvec_L2sqr(y_i, y_j, d));
            }
        }

#pragma omp parallel for
        for (size_t i = 0; i < nx; i++) {
            const float *x_i = x + i * d;

            int64_t ids_i = j0;
            float val_i = sqrt(fvec_L2sqr(x_i, y + j0 * d, d));
            float val_i_2 = val_i * 2;
            for (size_t j = j0 + 1; j < j1; j++) {
                if (val_i_2 <= Y(ids_i, j)) {
                    continue;
                }
                const float *y_j = y + j * d;
                float disij = sqrt(fvec_L2sqr(x_i, y_j, d));
                if (disij < val_i) {
                    ids_i = j;
                    val_i = disij;
                    val_i_2 = val_i * 2;
                }
            }

            if (j0 == 0 || res->val[i] > val_i) {
                res->val[i] = val_i;
                res->ids[i] = ids_i;
            }
        }
    }

    free(data);
}
J
JinHai-CN 已提交
416 417 418 419 420 421

/** Find the nearest neighbors for nx queries in a set of ny vectors */
static void knn_inner_product_blas (
        const float * x,
        const float * y,
        size_t d, size_t nx, size_t ny,
422 423
        float_minheap_array_t * res,
        ConcurrentBitsetPtr bitset = nullptr)
J
JinHai-CN 已提交
424 425 426 427 428 429
{
    res->heapify ();

    // BLAS does not like empty matrices
    if (nx == 0 || ny == 0) return;

430 431
    size_t k = res->k;

J
JinHai-CN 已提交
432 433 434
    /* block sizes */
    const size_t bs_x = 4096, bs_y = 1024;
    // const size_t bs_x = 16, bs_y = 16;
435 436
    float *ip_block = new float[bs_x * bs_y];
    ScopeDeleter<float> del1(ip_block);;
J
JinHai-CN 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

    for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
        size_t i1 = i0 + bs_x;
        if(i1 > nx) i1 = nx;

        for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
            size_t j1 = j0 + bs_y;
            if (j1 > ny) j1 = ny;
            /* compute the actual dot products */
            {
                float one = 1, zero = 0;
                FINTEGER nyi = j1 - j0, nxi = i1 - i0, di = d;
                sgemm_ ("Transpose", "Not transpose", &nyi, &nxi, &di, &one,
                        y + j0 * d, &di,
                        x + i0 * d, &di, &zero,
452
                        ip_block, &nyi);
J
JinHai-CN 已提交
453 454 455
            }

            /* collect maxima */
456 457 458 459 460 461 462 463 464 465 466
#pragma omp parallel for
            for(size_t i = i0; i < i1; i++){
                float * __restrict simi = res->get_val(i);
                int64_t * __restrict idxi = res->get_ids (i);
                const float *ip_line = ip_block + (i - i0) * (j1 - j0);

                for(size_t j = j0; j < j1; j++){
                    if(!bitset || !bitset->test(j)){
                        float dis = *ip_line;

                        if(dis > simi[0]){
S
shengjun.li 已提交
467
                            minheap_swap_top(k, simi, idxi, dis, j);
468 469 470 471 472
                        }
                    }
                    ip_line++;
                }
            }
J
JinHai-CN 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485
        }
        InterruptCallback::check ();
    }
    res->reorder ();
}

// distance correction is an operator that can be applied to transform
// the distances
template<class DistanceCorrection>
static void knn_L2sqr_blas (const float * x,
        const float * y,
        size_t d, size_t nx, size_t ny,
        float_maxheap_array_t * res,
486 487
        const DistanceCorrection &corr,
        ConcurrentBitsetPtr bitset = nullptr)
J
JinHai-CN 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
{
    res->heapify ();

    // BLAS does not like empty matrices
    if (nx == 0 || ny == 0) return;

    size_t k = res->k;

    /* block sizes */
    const size_t bs_x = 4096, bs_y = 1024;
    // const size_t bs_x = 16, bs_y = 16;
    float *ip_block = new float[bs_x * bs_y];
    float *x_norms = new float[nx];
    float *y_norms = new float[ny];
    ScopeDeleter<float> del1(ip_block), del3(x_norms), del2(y_norms);

    fvec_norms_L2sqr (x_norms, x, d, nx);
    fvec_norms_L2sqr (y_norms, y, d, ny);


    for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
        size_t i1 = i0 + bs_x;
        if(i1 > nx) i1 = nx;

        for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
            size_t j1 = j0 + bs_y;
            if (j1 > ny) j1 = ny;
            /* compute the actual dot products */
            {
                float one = 1, zero = 0;
                FINTEGER nyi = j1 - j0, nxi = i1 - i0, di = d;
                sgemm_ ("Transpose", "Not transpose", &nyi, &nxi, &di, &one,
                        y + j0 * d, &di,
                        x + i0 * d, &di, &zero,
                        ip_block, &nyi);
            }

            /* collect minima */
#pragma omp parallel for
            for (size_t i = i0; i < i1; i++) {
                float * __restrict simi = res->get_val(i);
                int64_t * __restrict idxi = res->get_ids (i);
                const float *ip_line = ip_block + (i - i0) * (j1 - j0);

                for (size_t j = j0; j < j1; j++) {
533 534 535
                    if(!bitset || !bitset->test(j)){
                        float ip = *ip_line;
                        float dis = x_norms[i] + y_norms[j] - 2 * ip;
J
JinHai-CN 已提交
536

537 538 539
                        // negative values can occur for identical vectors
                        // due to roundoff errors
                        if (dis < 0) dis = 0;
J
JinHai-CN 已提交
540

541
                        dis = corr (dis, i, j);
J
JinHai-CN 已提交
542

543
                        if (dis < simi[0]) {
S
shengjun.li 已提交
544
                            maxheap_swap_top (k, simi, idxi, dis, j);
545
                        }
J
JinHai-CN 已提交
546
                    }
547
                    ip_line++;
J
JinHai-CN 已提交
548 549 550 551 552 553 554 555 556
                }
            }
        }
        InterruptCallback::check ();
    }
    res->reorder ();

}

G
groot 已提交
557 558 559 560 561
template<class DistanceCorrection>
static void knn_jaccard_blas (const float * x,
                              const float * y,
                              size_t d, size_t nx, size_t ny,
                              float_maxheap_array_t * res,
562 563
                              const DistanceCorrection &corr,
                              ConcurrentBitsetPtr bitset = nullptr)
G
groot 已提交
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
{
    res->heapify ();

    // BLAS does not like empty matrices
    if (nx == 0 || ny == 0) return;

    size_t k = res->k;

    /* block sizes */
    const size_t bs_x = 4096, bs_y = 1024;
    // const size_t bs_x = 16, bs_y = 16;
    float *ip_block = new float[bs_x * bs_y];
    float *x_norms = new float[nx];
    float *y_norms = new float[ny];
    ScopeDeleter<float> del1(ip_block), del3(x_norms), del2(y_norms);

    fvec_norms_L2sqr (x_norms, x, d, nx);
    fvec_norms_L2sqr (y_norms, y, d, ny);


    for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
        size_t i1 = i0 + bs_x;
        if(i1 > nx) i1 = nx;

        for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
            size_t j1 = j0 + bs_y;
            if (j1 > ny) j1 = ny;
            /* compute the actual dot products */
            {
                float one = 1, zero = 0;
                FINTEGER nyi = j1 - j0, nxi = i1 - i0, di = d;
                sgemm_ ("Transpose", "Not transpose", &nyi, &nxi, &di, &one,
                        y + j0 * d, &di,
                        x + i0 * d, &di, &zero,
                        ip_block, &nyi);
            }

            /* collect minima */
#pragma omp parallel for
            for (size_t i = i0; i < i1; i++) {
                float * __restrict simi = res->get_val(i);
                int64_t * __restrict idxi = res->get_ids (i);
                const float *ip_line = ip_block + (i - i0) * (j1 - j0);

                for (size_t j = j0; j < j1; j++) {
609 610 611
                    if(!bitset || !bitset->test(j)){
                        float ip = *ip_line;
                        float dis = 1.0 - ip / (x_norms[i] + y_norms[j] - ip);
G
groot 已提交
612

613 614 615
                        // negative values can occur for identical vectors
                        // due to roundoff errors
                        if (dis < 0) dis = 0;
G
groot 已提交
616

617
                        dis = corr (dis, i, j);
G
groot 已提交
618

619
                        if (dis < simi[0]) {
S
shengjun.li 已提交
620
                            maxheap_swap_top (k, simi, idxi, dis, j);
621
                        }
G
groot 已提交
622
                    }
623
                    ip_line++;
G
groot 已提交
624 625 626 627 628 629 630
                }
            }
        }
        InterruptCallback::check ();
    }
    res->reorder ();
}
J
JinHai-CN 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646







/*******************************************************
 * KNN driver functions
 *******************************************************/

int distance_compute_blas_threshold = 20;

void knn_inner_product (const float * x,
        const float * y,
        size_t d, size_t nx, size_t ny,
647 648
        float_minheap_array_t * res,
        ConcurrentBitsetPtr bitset)
J
JinHai-CN 已提交
649 650
{
    if (d % 4 == 0 && nx < distance_compute_blas_threshold) {
651
        knn_inner_product_sse (x, y, d, nx, ny, res, bitset);
J
JinHai-CN 已提交
652
    } else {
653
        knn_inner_product_blas (x, y, d, nx, ny, res, bitset);
J
JinHai-CN 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667
    }
}



struct NopDistanceCorrection {
  float operator()(float dis, size_t /*qno*/, size_t /*bno*/) const {
    return dis;
    }
};

void knn_L2sqr (const float * x,
                const float * y,
                size_t d, size_t nx, size_t ny,
668 669 670
                float_maxheap_array_t * res,
                ConcurrentBitsetPtr bitset)
{
671 672 673 674 675
    if (bitset == nullptr && res->k == 1 && nx >= ny * 2) {
        // Note: L2 but not L2sqr
        // usually used in IVF::train
        elkan_L2_sse(x, y, d, nx, ny, res);
    } else if (d % 4 == 0 && nx < distance_compute_blas_threshold) {
676 677 678 679 680 681 682 683 684 685 686 687
        knn_L2sqr_sse (x, y, d, nx, ny, res, bitset);
    } else {
        NopDistanceCorrection nop;
        knn_L2sqr_blas (x, y, d, nx, ny, res, nop, bitset);
    }
}

void knn_jaccard (const float * x,
                  const float * y,
                  size_t d, size_t nx, size_t ny,
                  float_maxheap_array_t * res,
                  ConcurrentBitsetPtr bitset)
J
JinHai-CN 已提交
688 689
{
    if (d % 4 == 0 && nx < distance_compute_blas_threshold) {
690 691
//        knn_jaccard_sse (x, y, d, nx, ny, res);
        printf("jaccard sse not implemented!\n");
J
JinHai-CN 已提交
692 693
    } else {
        NopDistanceCorrection nop;
694
        knn_jaccard_blas (x, y, d, nx, ny, res, nop, bitset);
J
JinHai-CN 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
    }
}

struct BaseShiftDistanceCorrection {
    const float *base_shift;
    float operator()(float dis, size_t /*qno*/, size_t bno) const {
      return dis - base_shift[bno];
    }
};

void knn_L2sqr_base_shift (
         const float * x,
         const float * y,
         size_t d, size_t nx, size_t ny,
         float_maxheap_array_t * res,
         const float *base_shift)
{
    BaseShiftDistanceCorrection corr = {base_shift};
    knn_L2sqr_blas (x, y, d, nx, ny, res, corr);
}



/***************************************************************************
 * compute a subset of  distances
 ***************************************************************************/

/* compute the inner product between x and a subset y of ny vectors,
   whose indices are given by idy.  */
void fvec_inner_products_by_idx (float * __restrict ip,
                                 const float * x,
                                 const float * y,
                                 const int64_t * __restrict ids, /* for y vecs */
                                 size_t d, size_t nx, size_t ny)
{
#pragma omp parallel for
    for (size_t j = 0; j < nx; j++) {
        const int64_t * __restrict idsj = ids + j * ny;
        const float * xj = x + j * d;
        float * __restrict ipj = ip + j * ny;
        for (size_t i = 0; i < ny; i++) {
            if (idsj[i] < 0)
                continue;
            ipj[i] = fvec_inner_product (xj, y + d * idsj[i], d);
        }
    }
}



/* compute the inner product between x and a subset y of ny vectors,
   whose indices are given by idy.  */
void fvec_L2sqr_by_idx (float * __restrict dis,
                        const float * x,
                        const float * y,
                        const int64_t * __restrict ids, /* ids of y vecs */
                        size_t d, size_t nx, size_t ny)
{
#pragma omp parallel for
    for (size_t j = 0; j < nx; j++) {
        const int64_t * __restrict idsj = ids + j * ny;
        const float * xj = x + j * d;
        float * __restrict disj = dis + j * ny;
        for (size_t i = 0; i < ny; i++) {
            if (idsj[i] < 0)
                continue;
            disj[i] = fvec_L2sqr (xj, y + d * idsj[i], d);
        }
    }
}

void pairwise_indexed_L2sqr (
        size_t d, size_t n,
        const float * x, const int64_t *ix,
        const float * y, const int64_t *iy,
        float *dis)
{
#pragma omp parallel for
    for (size_t j = 0; j < n; j++) {
        if (ix[j] >= 0 && iy[j] >= 0) {
            dis[j] = fvec_L2sqr (x + d * ix[j], y + d * iy[j], d);
        }
    }
}

void pairwise_indexed_inner_product (
        size_t d, size_t n,
        const float * x, const int64_t *ix,
        const float * y, const int64_t *iy,
        float *dis)
{
#pragma omp parallel for
    for (size_t j = 0; j < n; j++) {
        if (ix[j] >= 0 && iy[j] >= 0) {
            dis[j] = fvec_inner_product (x + d * ix[j], y + d * iy[j], d);
        }
    }
}


/* Find the nearest neighbors for nx queries in a set of ny vectors
   indexed by ids. May be useful for re-ranking a pre-selected vector list */
void knn_inner_products_by_idx (const float * x,
                                const float * y,
                                const int64_t * ids,
                                size_t d, size_t nx, size_t ny,
                                float_minheap_array_t * res)
{
    size_t k = res->k;

#pragma omp parallel for
    for (size_t i = 0; i < nx; i++) {
        const float * x_ = x + i * d;
        const int64_t * idsi = ids + i * ny;
        size_t j;
        float * __restrict simi = res->get_val(i);
        int64_t * __restrict idxi = res->get_ids (i);
        minheap_heapify (k, simi, idxi);

        for (j = 0; j < ny; j++) {
            if (idsi[j] < 0) break;
            float ip = fvec_inner_product (x_, y + d * idsi[j], d);

            if (ip > simi[0]) {
S
shengjun.li 已提交
819
                minheap_swap_top (k, simi, idxi, ip, idsi[j]);
J
JinHai-CN 已提交
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
            }
        }
        minheap_reorder (k, simi, idxi);
    }

}

void knn_L2sqr_by_idx (const float * x,
                       const float * y,
                       const int64_t * __restrict ids,
                       size_t d, size_t nx, size_t ny,
                       float_maxheap_array_t * res)
{
    size_t k = res->k;

#pragma omp parallel for
    for (size_t i = 0; i < nx; i++) {
        const float * x_ = x + i * d;
        const int64_t * __restrict idsi = ids + i * ny;
        float * __restrict simi = res->get_val(i);
        int64_t * __restrict idxi = res->get_ids (i);
        maxheap_heapify (res->k, simi, idxi);
        for (size_t j = 0; j < ny; j++) {
            float disij = fvec_L2sqr (x_, y + d * idsi[j], d);

            if (disij < simi[0]) {
S
shengjun.li 已提交
846
                maxheap_swap_top (k, simi, idxi, disij, idsi[j]);
J
JinHai-CN 已提交
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
            }
        }
        maxheap_reorder (res->k, simi, idxi);
    }

}





/***************************************************************************
 * Range search
 ***************************************************************************/

/** Find the nearest neighbors for nx queries in a set of ny vectors
 * compute_l2 = compute pairwise squared L2 distance rather than inner prod
 */
template <bool compute_l2>
static void range_search_blas (
        const float * x,
        const float * y,
        size_t d, size_t nx, size_t ny,
        float radius,
        RangeSearchResult *result)
{

    // BLAS does not like empty matrices
    if (nx == 0 || ny == 0) return;

    /* block sizes */
    const size_t bs_x = 4096, bs_y = 1024;
    // const size_t bs_x = 16, bs_y = 16;
    float *ip_block = new float[bs_x * bs_y];
    ScopeDeleter<float> del0(ip_block);

    float *x_norms = nullptr, *y_norms = nullptr;
    ScopeDeleter<float> del1, del2;
    if (compute_l2) {
        x_norms = new float[nx];
        del1.set (x_norms);
        fvec_norms_L2sqr (x_norms, x, d, nx);

        y_norms = new float[ny];
        del2.set (y_norms);
        fvec_norms_L2sqr (y_norms, y, d, ny);
    }

    std::vector <RangeSearchPartialResult *> partial_results;

    for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
        size_t j1 = j0 + bs_y;
        if (j1 > ny) j1 = ny;
        RangeSearchPartialResult * pres = new RangeSearchPartialResult (result);
        partial_results.push_back (pres);

        for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
            size_t i1 = i0 + bs_x;
            if(i1 > nx) i1 = nx;

            /* compute the actual dot products */
            {
                float one = 1, zero = 0;
                FINTEGER nyi = j1 - j0, nxi = i1 - i0, di = d;
                sgemm_ ("Transpose", "Not transpose", &nyi, &nxi, &di, &one,
                        y + j0 * d, &di,
                        x + i0 * d, &di, &zero,
                        ip_block, &nyi);
            }


            for (size_t i = i0; i < i1; i++) {
                const float *ip_line = ip_block + (i - i0) * (j1 - j0);

                RangeQueryResult & qres = pres->new_result (i);

                for (size_t j = j0; j < j1; j++) {
                    float ip = *ip_line++;
                    if (compute_l2) {
                        float dis =  x_norms[i] + y_norms[j] - 2 * ip;
                        if (dis < radius) {
                            qres.add (dis, j);
                        }
                    } else {
                        if (ip > radius) {
                            qres.add (ip, j);
                        }
                    }
                }
            }
        }
        InterruptCallback::check ();
    }

    RangeSearchPartialResult::merge (partial_results);
}


template <bool compute_l2>
static void range_search_sse (const float * x,
                const float * y,
                size_t d, size_t nx, size_t ny,
                float radius,
                RangeSearchResult *res)
{
    FAISS_THROW_IF_NOT (d % 4 == 0);

#pragma omp parallel
    {
        RangeSearchPartialResult pres (res);

#pragma omp for
        for (size_t i = 0; i < nx; i++) {
            const float * x_ = x + i * d;
            const float * y_ = y;
            size_t j;

            RangeQueryResult & qres = pres.new_result (i);

            for (j = 0; j < ny; j++) {
                if (compute_l2) {
                    float disij = fvec_L2sqr (x_, y_, d);
                    if (disij < radius) {
                        qres.add (disij, j);
                    }
                } else {
                    float ip = fvec_inner_product (x_, y_, d);
                    if (ip > radius) {
                        qres.add (ip, j);
                    }
                }
                y_ += d;
            }

        }
        pres.finalize ();
    }

    // check just at the end because the use case is typically just
    // when the nb of queries is low.
    InterruptCallback::check();
}





void range_search_L2sqr (
        const float * x,
        const float * y,
        size_t d, size_t nx, size_t ny,
        float radius,
        RangeSearchResult *res)
{

    if (d % 4 == 0 && nx < distance_compute_blas_threshold) {
        range_search_sse<true> (x, y, d, nx, ny, radius, res);
    } else {
        range_search_blas<true> (x, y, d, nx, ny, radius, res);
    }
}

void range_search_inner_product (
        const float * x,
        const float * y,
        size_t d, size_t nx, size_t ny,
        float radius,
        RangeSearchResult *res)
{

    if (d % 4 == 0 && nx < distance_compute_blas_threshold) {
        range_search_sse<false> (x, y, d, nx, ny, radius, res);
    } else {
        range_search_blas<false> (x, y, d, nx, ny, radius, res);
    }
}


void pairwise_L2sqr (int64_t d,
                     int64_t nq, const float *xq,
                     int64_t nb, const float *xb,
                     float *dis,
                     int64_t ldq, int64_t ldb, int64_t ldd)
{
    if (nq == 0 || nb == 0) return;
    if (ldq == -1) ldq = d;
    if (ldb == -1) ldb = d;
    if (ldd == -1) ldd = nb;

    // store in beginning of distance matrix to avoid malloc
    float *b_norms = dis;

#pragma omp parallel for
    for (int64_t i = 0; i < nb; i++)
        b_norms [i] = fvec_norm_L2sqr (xb + i * ldb, d);

#pragma omp parallel for
    for (int64_t i = 1; i < nq; i++) {
        float q_norm = fvec_norm_L2sqr (xq + i * ldq, d);
        for (int64_t j = 0; j < nb; j++)
            dis[i * ldd + j] = q_norm + b_norms [j];
    }

    {
        float q_norm = fvec_norm_L2sqr (xq, d);
        for (int64_t j = 0; j < nb; j++)
            dis[j] += q_norm;
    }

    {
        FINTEGER nbi = nb, nqi = nq, di = d, ldqi = ldq, ldbi = ldb, lddi = ldd;
        float one = 1.0, minus_2 = -2.0;

        sgemm_ ("Transposed", "Not transposed",
                &nbi, &nqi, &di,
                &minus_2,
                xb, &ldbi,
                xq, &ldqi,
                &one, dis, &lddi);
    }

}


1071
} // namespace faiss