test_ivf.cpp 23.0 KB
Newer Older
J
jinhai 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

X
xj.lin 已提交
18 19 20 21

#include <gtest/gtest.h>

#include <iostream>
22 23 24 25 26
#include <thread>

#include <faiss/AutoTune.h>
#include <faiss/gpu/GpuAutoTune.h>
#include <faiss/gpu/GpuIndexIVFFlat.h>
X
xj.lin 已提交
27

X
xiaojun.lin 已提交
28 29
#include "knowhere/common/Exception.h"
#include "knowhere/common/Timer.h"
X
xiaojun.lin 已提交
30 31 32 33 34 35 36 37
#include "knowhere/adapter/Structure.h"
#include "knowhere/index/vector_index/helpers/Cloner.h"
#include "knowhere/index/vector_index/IndexIVF.h"
#include "knowhere/index/vector_index/IndexGPUIVF.h"
#include "knowhere/index/vector_index/IndexIVFPQ.h"
#include "knowhere/index/vector_index/IndexGPUIVFPQ.h"
#include "knowhere/index/vector_index/IndexIVFSQ.h"
#include "knowhere/index/vector_index/IndexGPUIVFSQ.h"
X
xj.lin 已提交
38 39 40 41

#include "utils.h"

using namespace zilliz::knowhere;
X
xiaojun.lin 已提交
42
using namespace zilliz::knowhere::cloner;
X
xj.lin 已提交
43 44 45 46 47

using ::testing::TestWithParam;
using ::testing::Values;
using ::testing::Combine;

X
xiaojun.lin 已提交
48 49 50 51 52 53
constexpr int device_id = 0;
constexpr int64_t DIM = 128;
constexpr int64_t NB = 1000000/100;
constexpr int64_t NQ = 10;
constexpr int64_t K = 10;

X
xj.lin 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
IVFIndexPtr IndexFactory(const std::string &type) {
    if (type == "IVF") {
        return std::make_shared<IVF>();
    } else if (type == "IVFPQ") {
        return std::make_shared<IVFPQ>();
    } else if (type == "GPUIVF") {
        return std::make_shared<GPUIVF>(device_id);
    } else if (type == "GPUIVFPQ") {
        return std::make_shared<GPUIVFPQ>(device_id);
    } else if (type == "IVFSQ") {
        return std::make_shared<IVFSQ>();
    } else if (type == "GPUIVFSQ") {
        return std::make_shared<GPUIVFSQ>(device_id);
    }
}

X
xiaojun.lin 已提交
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
enum class ParameterType {
    ivf,
    ivfpq,
    ivfsq,
    nsg,
};

class ParamGenerator {
 public:
    static ParamGenerator& GetInstance(){
        static ParamGenerator instance;
        return instance;
    }

    Config Gen(const ParameterType& type){
        if (type == ParameterType::ivf) {
            auto tempconf = std::make_shared<IVFCfg>();
            tempconf->d = DIM;
            tempconf->gpu_id = device_id;
            tempconf->nlist = 100;
            tempconf->nprobe = 16;
            tempconf->k = K;
            tempconf->metric_type = METRICTYPE::L2;
            return tempconf;
        }
        else if (type == ParameterType::ivfpq) {
            auto tempconf = std::make_shared<IVFPQCfg>();
            tempconf->d = DIM;
            tempconf->gpu_id = device_id;
            tempconf->nlist = 100;
            tempconf->nprobe = 16;
            tempconf->k = K;
            tempconf->m = 8;
            tempconf->nbits = 8;
            tempconf->metric_type = METRICTYPE::L2;
            return tempconf;
        }
        else if (type == ParameterType::ivfsq) {
            auto tempconf = std::make_shared<IVFSQCfg>();
            tempconf->d = DIM;
            tempconf->gpu_id = device_id;
            tempconf->nlist = 100;
            tempconf->nprobe = 16;
            tempconf->k = K;
            tempconf->nbits = 8;
            tempconf->metric_type = METRICTYPE::L2;
            return tempconf;
        }
    }
};

X
xj.lin 已提交
121
class IVFTest
X
xiaojun.lin 已提交
122
    : public DataGen, public TestWithParam<::std::tuple<std::string, ParameterType>> {
X
xj.lin 已提交
123 124
 protected:
    void SetUp() override {
X
xiaojun.lin 已提交
125 126
        ParameterType parameter_type;
        std::tie(index_type, parameter_type) = GetParam();
X
xj.lin 已提交
127
        //Init_with_default();
X
xiaojun.lin 已提交
128
        Generate(DIM, NB, NQ);
X
xj.lin 已提交
129
        index_ = IndexFactory(index_type);
X
xiaojun.lin 已提交
130
        conf = ParamGenerator::GetInstance().Gen(parameter_type);
X
xj.lin 已提交
131
        FaissGpuResourceMgr::GetInstance().InitDevice(device_id, 1024*1024*200, 1024*1024*600, 2);
X
xj.lin 已提交
132
    }
133 134 135
    void TearDown() override {
        FaissGpuResourceMgr::GetInstance().Free();
    }
X
xj.lin 已提交
136 137 138

 protected:
    std::string index_type;
X
xiaojun.lin 已提交
139
    Config conf;
X
xj.lin 已提交
140 141 142 143
    IVFIndexPtr index_ = nullptr;
};


X
xiaojun.lin 已提交
144

X
xj.lin 已提交
145 146
INSTANTIATE_TEST_CASE_P(IVFParameters, IVFTest,
                        Values(
X
xiaojun.lin 已提交
147 148 149 150 151 152
                            std::make_tuple("IVF", ParameterType::ivf),
                            std::make_tuple("GPUIVF", ParameterType::ivf),
                            std::make_tuple("IVFPQ", ParameterType::ivfpq),
                            std::make_tuple("GPUIVFPQ", ParameterType::ivfpq),
                            std::make_tuple("IVFSQ", ParameterType::ivfsq),
                            std::make_tuple("GPUIVFSQ", ParameterType::ivfsq)
X
xj.lin 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
                        )
);

void AssertAnns(const DatasetPtr &result,
                const int &nq,
                const int &k) {
    auto ids = result->array()[0];
    for (auto i = 0; i < nq; i++) {
        EXPECT_EQ(i, *(ids->data()->GetValues<int64_t>(1, i * k)));
    }
}

void PrintResult(const DatasetPtr &result,
                 const int &nq,
                 const int &k) {
    auto ids = result->array()[0];
    auto dists = result->array()[1];

    std::stringstream ss_id;
    std::stringstream ss_dist;
    for (auto i = 0; i < 10; i++) {
        for (auto j = 0; j < k; ++j) {
            ss_id << *(ids->data()->GetValues<int64_t>(1, i * k + j)) << " ";
            ss_dist << *(dists->data()->GetValues<float>(1, i * k + j)) << " ";
        }
        ss_id << std::endl;
        ss_dist << std::endl;
    }
    std::cout << "id\n" << ss_id.str() << std::endl;
    std::cout << "dist\n" << ss_dist.str() << std::endl;
}

TEST_P(IVFTest, ivf_basic) {
    assert(!xb.empty());

X
xiaojun.lin 已提交
188
    auto preprocessor = index_->BuildPreprocessor(base_dataset, conf);
X
xj.lin 已提交
189 190
    index_->set_preprocessor(preprocessor);

X
xiaojun.lin 已提交
191
    auto model = index_->Train(base_dataset, conf);
X
xj.lin 已提交
192
    index_->set_index_model(model);
X
xiaojun.lin 已提交
193
    index_->Add(base_dataset, conf);
X
xj.lin 已提交
194 195
    EXPECT_EQ(index_->Count(), nb);
    EXPECT_EQ(index_->Dimension(), dim);
X
xiaojun.lin 已提交
196 197
    auto result = index_->Search(query_dataset, conf);
    AssertAnns(result, nq, conf->k);
X
xj.lin 已提交
198 199 200 201 202 203 204 205 206
    //PrintResult(result, nq, k);
}

//TEST_P(IVFTest, gpu_to_cpu) {
//    if (index_type.find("GPU") == std::string::npos) { return; }
//
//    // else
//    assert(!xb.empty());
//
X
xiaojun.lin 已提交
207
//    auto preprocessor = index_->BuildPreprocessor(base_dataset, conf);
X
xj.lin 已提交
208 209
//    index_->set_preprocessor(preprocessor);
//
X
xiaojun.lin 已提交
210
//    auto model = index_->Train(base_dataset, conf);
X
xj.lin 已提交
211
//    index_->set_index_model(model);
X
xiaojun.lin 已提交
212
//    index_->Add(base_dataset, conf);
X
xj.lin 已提交
213 214
//    EXPECT_EQ(index_->Count(), nb);
//    EXPECT_EQ(index_->Dimension(), dim);
X
xiaojun.lin 已提交
215
//    auto result = index_->Search(query_dataset, conf);
X
xj.lin 已提交
216 217 218 219
//    AssertAnns(result, nq, k);
//
//    if (auto device_index = std::dynamic_pointer_cast<GPUIVF>(index_)) {
//        auto host_index = device_index->Copy_index_gpu_to_cpu();
X
xiaojun.lin 已提交
220
//        auto result = host_index->Search(query_dataset, conf);
X
xj.lin 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
//        AssertAnns(result, nq, k);
//    }
//}

TEST_P(IVFTest, ivf_serialize) {
    auto serialize = [](const std::string &filename, BinaryPtr &bin, uint8_t *ret) {
        FileIOWriter writer(filename);
        writer(static_cast<void *>(bin->data.get()), bin->size);

        FileIOReader reader(filename);
        reader(ret, bin->size);
    };

    {
        // serialize index-model
X
xiaojun.lin 已提交
236
        auto model = index_->Train(base_dataset, conf);
X
xj.lin 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
        auto binaryset = model->Serialize();
        auto bin = binaryset.GetByName("IVF");

        std::string filename = "/tmp/ivf_test_model_serialize.bin";
        auto load_data = new uint8_t[bin->size];
        serialize(filename, bin, load_data);

        binaryset.clear();
        auto data = std::make_shared<uint8_t>();
        data.reset(load_data);
        binaryset.Append("IVF", data, bin->size);

        model->Load(binaryset);

        index_->set_index_model(model);
X
xiaojun.lin 已提交
252 253 254
        index_->Add(base_dataset, conf);
        auto result = index_->Search(query_dataset, conf);
        AssertAnns(result, nq, conf->k);
X
xj.lin 已提交
255 256 257 258
    }

    {
        // serialize index
X
xiaojun.lin 已提交
259
        auto model = index_->Train(base_dataset, conf);
X
xj.lin 已提交
260
        index_->set_index_model(model);
X
xiaojun.lin 已提交
261
        index_->Add(base_dataset, conf);
X
xj.lin 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        auto binaryset = index_->Serialize();
        auto bin = binaryset.GetByName("IVF");

        std::string filename = "/tmp/ivf_test_serialize.bin";
        auto load_data = new uint8_t[bin->size];
        serialize(filename, bin, load_data);

        binaryset.clear();
        auto data = std::make_shared<uint8_t>();
        data.reset(load_data);
        binaryset.Append("IVF", data, bin->size);

        index_->Load(binaryset);
        EXPECT_EQ(index_->Count(), nb);
        EXPECT_EQ(index_->Dimension(), dim);
X
xiaojun.lin 已提交
277 278
        auto result = index_->Search(query_dataset, conf);
        AssertAnns(result, nq, conf->k);
X
xj.lin 已提交
279 280 281 282 283 284
    }
}

TEST_P(IVFTest, clone_test) {
    assert(!xb.empty());

X
xiaojun.lin 已提交
285
    auto preprocessor = index_->BuildPreprocessor(base_dataset, conf);
X
xj.lin 已提交
286 287
    index_->set_preprocessor(preprocessor);

X
xiaojun.lin 已提交
288
    auto model = index_->Train(base_dataset, conf);
X
xj.lin 已提交
289
    index_->set_index_model(model);
X
xiaojun.lin 已提交
290
    index_->Add(base_dataset, conf);
X
xj.lin 已提交
291 292
    EXPECT_EQ(index_->Count(), nb);
    EXPECT_EQ(index_->Dimension(), dim);
X
xiaojun.lin 已提交
293 294
    auto result = index_->Search(query_dataset, conf);
    AssertAnns(result, nq, conf->k);
X
xj.lin 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    //PrintResult(result, nq, k);

    auto AssertEqual = [&] (DatasetPtr p1, DatasetPtr p2) {
        auto ids_p1 = p1->array()[0];
        auto ids_p2 = p2->array()[0];

        for (int i = 0; i < nq * k; ++i) {
            EXPECT_EQ(*(ids_p2->data()->GetValues<int64_t>(1, i)),
                      *(ids_p1->data()->GetValues<int64_t>(1, i)));
        }
    };

    {
        // clone in place
        std::vector<std::string> support_idx_vec{"IVF", "GPUIVF", "IVFPQ", "IVFSQ", "GPUIVFSQ"};
        auto finder = std::find(support_idx_vec.cbegin(), support_idx_vec.cend(), index_type);
        if (finder != support_idx_vec.cend()) {
            EXPECT_NO_THROW({
                                auto clone_index = index_->Clone();
X
xiaojun.lin 已提交
314 315
                                auto clone_result = clone_index->Search(query_dataset, conf);
                                //AssertAnns(result, nq, conf->k);
X
xj.lin 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
                                AssertEqual(result, clone_result);
                                std::cout << "inplace clone [" << index_type << "] success" << std::endl;
                            });
        } else {
            EXPECT_THROW({
                             std::cout << "inplace clone [" << index_type << "] failed" << std::endl;
                             auto clone_index = index_->Clone();
                         }, KnowhereException);
        }
    }

    {
        // copy from gpu to cpu
        std::vector<std::string> support_idx_vec{"GPUIVF", "GPUIVFSQ"};
        auto finder = std::find(support_idx_vec.cbegin(), support_idx_vec.cend(), index_type);
        if (finder != support_idx_vec.cend()) {
            EXPECT_NO_THROW({
                                auto clone_index = CopyGpuToCpu(index_, Config());
X
xiaojun.lin 已提交
334
                                auto clone_result = clone_index->Search(query_dataset, conf);
X
xj.lin 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
                                AssertEqual(result, clone_result);
                                std::cout << "clone G <=> C [" << index_type << "] success" << std::endl;
                            });
        } else {
            EXPECT_THROW({
                             std::cout << "clone G <=> C [" << index_type << "] failed" << std::endl;
                             auto clone_index = CopyGpuToCpu(index_, Config());
                         }, KnowhereException);
        }
    }

    {
        // copy to gpu
        std::vector<std::string> support_idx_vec{"IVF", "GPUIVF", "IVFSQ", "GPUIVFSQ"};
        auto finder = std::find(support_idx_vec.cbegin(), support_idx_vec.cend(), index_type);
        if (finder != support_idx_vec.cend()) {
            EXPECT_NO_THROW({
                                auto clone_index = CopyCpuToGpu(index_, device_id, Config());
X
xiaojun.lin 已提交
353
                                auto clone_result = clone_index->Search(query_dataset, conf);
X
xj.lin 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
                                AssertEqual(result, clone_result);
                                std::cout << "clone C <=> G [" << index_type << "] success" << std::endl;
                            });
        } else {
            EXPECT_THROW({
                             std::cout << "clone C <=> G [" << index_type << "] failed" << std::endl;
                             auto clone_index = CopyCpuToGpu(index_, device_id, Config());
                         }, KnowhereException);
        }
    }
}

TEST_P(IVFTest, seal_test) {
    //FaissGpuResourceMgr::GetInstance().InitDevice(device_id);

    std::vector<std::string> support_idx_vec{"GPUIVF", "GPUIVFSQ"};
    auto finder = std::find(support_idx_vec.cbegin(), support_idx_vec.cend(), index_type);
    if (finder == support_idx_vec.cend()) {
        return;
    }

    assert(!xb.empty());

X
xiaojun.lin 已提交
377
    auto preprocessor = index_->BuildPreprocessor(base_dataset, conf);
X
xj.lin 已提交
378 379
    index_->set_preprocessor(preprocessor);

X
xiaojun.lin 已提交
380
    auto model = index_->Train(base_dataset, conf);
X
xj.lin 已提交
381
    index_->set_index_model(model);
X
xiaojun.lin 已提交
382
    index_->Add(base_dataset, conf);
X
xj.lin 已提交
383 384
    EXPECT_EQ(index_->Count(), nb);
    EXPECT_EQ(index_->Dimension(), dim);
X
xiaojun.lin 已提交
385 386
    auto result = index_->Search(query_dataset, conf);
    AssertAnns(result, nq, conf->k);
X
xj.lin 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399

    auto cpu_idx = CopyGpuToCpu(index_, Config());

    TimeRecorder tc("CopyToGpu");
    CopyCpuToGpu(cpu_idx, device_id, Config());
    auto without_seal = tc.RecordSection("Without seal");
    cpu_idx->Seal();
    tc.RecordSection("seal cost");
    CopyCpuToGpu(cpu_idx, device_id, Config());
    auto with_seal = tc.RecordSection("With seal");
    ASSERT_GE(without_seal, with_seal);
}

400 401 402 403 404 405 406 407

class GPURESTEST
    : public DataGen, public ::testing::Test {
 protected:
    void SetUp() override {
        Generate(128, 1000000, 1000);
        FaissGpuResourceMgr::GetInstance().InitDevice(device_id, 1024*1024*200, 1024*1024*300, 2);

X
xiaojun.lin 已提交
408
        k = 100;
409 410 411 412 413 414 415 416
        elems = nq * k;
        ids = (int64_t *) malloc(sizeof(int64_t) * elems);
        dis = (float *) malloc(sizeof(float) * elems);
    }

    void TearDown() override {
        delete ids;
        delete dis;
417
        FaissGpuResourceMgr::GetInstance().Free();
418 419 420 421 422 423 424 425 426 427 428
    }

 protected:
    std::string index_type;
    IVFIndexPtr index_ = nullptr;

    int64_t *ids = nullptr;
    float *dis = nullptr;
    int64_t elems = 0;
};

X
xj.lin 已提交
429
const int search_count = 18;
X
xj.lin 已提交
430
const int load_count = 3;
431 432 433 434 435

TEST_F(GPURESTEST, gpu_ivf_resource_test) {
    assert(!xb.empty());

    {
X
xj.lin 已提交
436 437 438 439 440
        index_ =  std::make_shared<GPUIVF>(-1);
        ASSERT_EQ(std::dynamic_pointer_cast<GPUIVF>(index_)->GetGpuDevice(), -1);
        std::dynamic_pointer_cast<GPUIVF>(index_)->SetGpuDevice(device_id);
        ASSERT_EQ(std::dynamic_pointer_cast<GPUIVF>(index_)->GetGpuDevice(), device_id);

X
xiaojun.lin 已提交
441 442 443 444 445 446 447 448 449
        auto conf = std::make_shared<IVFCfg>();
        conf->nlist = 1638;
        conf->d = dim;
        conf->gpu_id = device_id;
        conf->metric_type = METRICTYPE::L2;
        conf->k = k;
        conf->nprobe = 1;

        auto preprocessor = index_->BuildPreprocessor(base_dataset, conf);
450
        index_->set_preprocessor(preprocessor);
X
xiaojun.lin 已提交
451
        auto model = index_->Train(base_dataset, conf);
452
        index_->set_index_model(model);
X
xiaojun.lin 已提交
453
        index_->Add(base_dataset, conf);
454 455 456 457 458
        EXPECT_EQ(index_->Count(), nb);
        EXPECT_EQ(index_->Dimension(), dim);

        TimeRecorder tc("knowere GPUIVF");
        for (int i = 0; i < search_count; ++i) {
X
xiaojun.lin 已提交
459
            index_->Search(query_dataset, conf);
460 461 462
            if (i > search_count - 6 || i < 5)
                tc.RecordSection("search once");
        }
X
xj.lin 已提交
463
        tc.ElapseFromBegin("search all");
464
    }
X
xj.lin 已提交
465
    FaissGpuResourceMgr::GetInstance().Dump();
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481

    {
        // IVF-Search
        faiss::gpu::StandardGpuResources res;
        faiss::gpu::GpuIndexIVFFlatConfig idx_config;
        idx_config.device = device_id;
        faiss::gpu::GpuIndexIVFFlat device_index(&res, dim, 1638, faiss::METRIC_L2, idx_config);
        device_index.train(nb, xb.data());
        device_index.add(nb, xb.data());

        TimeRecorder tc("ori IVF");
        for (int i = 0; i < search_count; ++i) {
            device_index.search(nq, xq.data(), k, dis, ids);
            if (i > search_count - 6 || i < 5)
                tc.RecordSection("search once");
        }
X
xj.lin 已提交
482
        tc.ElapseFromBegin("search all");
483 484 485 486 487 488 489 490 491
    }

}

TEST_F(GPURESTEST, gpuivfsq) {
    {
        // knowhere gpu ivfsq
        index_type = "GPUIVFSQ";
        index_ = IndexFactory(index_type);
X
xiaojun.lin 已提交
492 493 494 495 496 497 498 499 500 501 502

        auto conf = std::make_shared<IVFSQCfg>();
        conf->nlist = 1638;
        conf->d = dim;
        conf->gpu_id = device_id;
        conf->metric_type = METRICTYPE::L2;
        conf->k = k;
        conf->nbits = 8;
        conf->nprobe = 1;

        auto preprocessor = index_->BuildPreprocessor(base_dataset, conf);
503
        index_->set_preprocessor(preprocessor);
X
xiaojun.lin 已提交
504
        auto model = index_->Train(base_dataset, conf);
505
        index_->set_index_model(model);
X
xiaojun.lin 已提交
506 507
        index_->Add(base_dataset, conf);
        auto result = index_->Search(query_dataset, conf);
508 509 510 511 512 513 514 515 516
        AssertAnns(result, nq, k);

        auto cpu_idx = CopyGpuToCpu(index_, Config());
        cpu_idx->Seal();

        TimeRecorder tc("knowhere GPUSQ8");
        auto search_idx = CopyCpuToGpu(cpu_idx, device_id, Config());
        tc.RecordSection("Copy to gpu");
        for (int i = 0; i < search_count; ++i) {
X
xiaojun.lin 已提交
517
            search_idx->Search(query_dataset, conf);
518 519 520
            if (i > search_count - 6 || i < 5)
                tc.RecordSection("search once");
        }
X
xj.lin 已提交
521
        tc.ElapseFromBegin("search all");
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    }

    {
        // Ori gpuivfsq Test
        const char *index_description = "IVF1638,SQ8";
        faiss::Index *ori_index = faiss::index_factory(dim, index_description, faiss::METRIC_L2);

        faiss::gpu::StandardGpuResources res;
        auto device_index = faiss::gpu::index_cpu_to_gpu(&res, device_id, ori_index);
        device_index->train(nb, xb.data());
        device_index->add(nb, xb.data());

        auto cpu_index = faiss::gpu::index_gpu_to_cpu(device_index);
        auto idx = dynamic_cast<faiss::IndexIVF *>(cpu_index);
        if (idx != nullptr) {
            idx->to_readonly();
        }
        delete device_index;
        delete ori_index;

        faiss::gpu::GpuClonerOptions option;
        option.allInGpu = true;

        TimeRecorder tc("ori GPUSQ8");
        faiss::Index *search_idx = faiss::gpu::index_cpu_to_gpu(&res, device_id, cpu_index, &option);
        tc.RecordSection("Copy to gpu");
        for (int i = 0; i < search_count; ++i) {
            search_idx->search(nq, xq.data(), k, dis, ids);
            if (i > search_count - 6 || i < 5)
                tc.RecordSection("search once");
        }
X
xj.lin 已提交
553
        tc.ElapseFromBegin("search all");
554 555 556 557 558 559 560
        delete cpu_index;
        delete search_idx;
    }

}

TEST_F(GPURESTEST, copyandsearch) {
X
xiaojun.lin 已提交
561
    // search and copy at the same time
562 563 564 565
    printf("==================\n");

    index_type = "GPUIVFSQ";
    index_ = IndexFactory(index_type);
X
xiaojun.lin 已提交
566 567 568 569 570 571 572 573 574 575 576

    auto conf = std::make_shared<IVFSQCfg>();
    conf->nlist = 1638;
    conf->d = dim;
    conf->gpu_id = device_id;
    conf->metric_type = METRICTYPE::L2;
    conf->k = k;
    conf->nbits = 8;
    conf->nprobe = 1;

    auto preprocessor = index_->BuildPreprocessor(base_dataset, conf);
577
    index_->set_preprocessor(preprocessor);
X
xiaojun.lin 已提交
578
    auto model = index_->Train(base_dataset, conf);
579
    index_->set_index_model(model);
X
xiaojun.lin 已提交
580 581
    index_->Add(base_dataset, conf);
    auto result = index_->Search(query_dataset, conf);
582 583 584 585 586 587 588 589 590 591
    AssertAnns(result, nq, k);

    auto cpu_idx = CopyGpuToCpu(index_, Config());
    cpu_idx->Seal();

    auto search_idx = CopyCpuToGpu(cpu_idx, device_id, Config());

    auto search_func = [&] {
        //TimeRecorder tc("search&load");
        for (int i = 0; i < search_count; ++i) {
X
xiaojun.lin 已提交
592
            search_idx->Search(query_dataset, conf);
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
            //if (i > search_count - 6 || i == 0)
            //    tc.RecordSection("search once");
        }
        //tc.ElapseFromBegin("search finish");
    };
    auto load_func = [&] {
        //TimeRecorder tc("search&load");
        for (int i = 0; i < load_count; ++i) {
            CopyCpuToGpu(cpu_idx, device_id, Config());
            //if (i > load_count -5 || i < 5)
                //tc.RecordSection("Copy to gpu");
        }
        //tc.ElapseFromBegin("load finish");
    };

    TimeRecorder tc("basic");
    CopyCpuToGpu(cpu_idx, device_id, Config());
    tc.RecordSection("Copy to gpu once");
X
xiaojun.lin 已提交
611
    search_idx->Search(query_dataset, conf);
612 613 614 615 616 617 618 619 620 621 622 623 624
    tc.RecordSection("search once");
    search_func();
    tc.RecordSection("only search total");
    load_func();
    tc.RecordSection("only copy total");

    std::thread search_thread(search_func);
    std::thread load_thread(load_func);
    search_thread.join();
    load_thread.join();
    tc.RecordSection("Copy&search total");
}

625 626 627
TEST_F(GPURESTEST, TrainAndSearch) {
    index_type = "GPUIVFSQ";
    index_ = IndexFactory(index_type);
X
xiaojun.lin 已提交
628 629 630 631 632 633 634 635 636 637 638

    auto conf = std::make_shared<IVFSQCfg>();
    conf->nlist = 1638;
    conf->d = dim;
    conf->gpu_id = device_id;
    conf->metric_type = METRICTYPE::L2;
    conf->k = k;
    conf->nbits = 8;
    conf->nprobe = 1;

    auto preprocessor = index_->BuildPreprocessor(base_dataset, conf);
639
    index_->set_preprocessor(preprocessor);
X
xiaojun.lin 已提交
640
    auto model = index_->Train(base_dataset, conf);
641 642
    auto new_index = IndexFactory(index_type);
    new_index->set_index_model(model);
X
xiaojun.lin 已提交
643
    new_index->Add(base_dataset, conf);
644 645 646 647
    auto cpu_idx = CopyGpuToCpu(new_index, Config());
    cpu_idx->Seal();
    auto search_idx = CopyCpuToGpu(cpu_idx, device_id, Config());

X
xiaojun.lin 已提交
648 649
    constexpr int train_count = 1;
    constexpr int search_count = 5000;
650 651
    auto train_stage = [&] {
        for (int i = 0; i < train_count; ++i) {
X
xiaojun.lin 已提交
652
            auto model = index_->Train(base_dataset, conf);
653 654
            auto test_idx = IndexFactory(index_type);
            test_idx->set_index_model(model);
X
xiaojun.lin 已提交
655
            test_idx->Add(base_dataset, conf);
656 657 658 659
        }
    };
    auto search_stage = [&](VectorIndexPtr& search_idx) {
        for (int i = 0; i < search_count; ++i) {
X
xiaojun.lin 已提交
660
            auto result = search_idx->Search(query_dataset, conf);
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
            AssertAnns(result, nq, k);
        }
    };

    //TimeRecorder tc("record");
    //train_stage();
    //tc.RecordSection("train cost");
    //search_stage(search_idx);
    //tc.RecordSection("search cost");

    {
        // search and build parallel
        std::thread search_thread(search_stage, std::ref(search_idx));
        std::thread train_thread(train_stage);
        train_thread.join();
        search_thread.join();
    }
    {
        // build parallel
        std::thread train_1(train_stage);
        std::thread train_2(train_stage);
        train_1.join();
        train_2.join();
    }
    {
        // search parallel
        auto search_idx_2 = CopyCpuToGpu(cpu_idx, device_id, Config());
        std::thread search_1(search_stage, std::ref(search_idx));
        std::thread search_2(search_stage, std::ref(search_idx_2));
        search_1.join();
        search_2.join();
    }
}

695 696


X
xj.lin 已提交
697
// TODO(linxj): Add exception test