ExecutionEngineImpl.cpp 10.2 KB
Newer Older
G
groot 已提交
1 2 3 4 5
/*******************************************************************************
 * Copyright 上海赜睿信息科技有限公司(Zilliz) - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited.
 * Proprietary and confidential.
 ******************************************************************************/
X
xj.lin 已提交
6
#include <stdexcept>
Y
Yu Kun 已提交
7
#include "src/cache/GpuCacheMgr.h"
X
xj.lin 已提交
8

G
groot 已提交
9 10
#include "src/metrics/Metrics.h"
#include "db/Log.h"
J
jinhai 已提交
11
#include "utils/CommonUtil.h"
G
groot 已提交
12

X
xj.lin 已提交
13 14 15
#include "src/cache/CpuCacheMgr.h"
#include "ExecutionEngineImpl.h"
#include "wrapper/knowhere/vec_index.h"
G
groot 已提交
16
#include "wrapper/knowhere/vec_impl.h"
X
xj.lin 已提交
17
#include "knowhere/common/exception.h"
G
groot 已提交
18
#include "db/Exception.h"
X
xj.lin 已提交
19

G
groot 已提交
20 21 22 23 24 25

namespace zilliz {
namespace milvus {
namespace engine {

ExecutionEngineImpl::ExecutionEngineImpl(uint16_t dimension,
X
xj.lin 已提交
26
                                         const std::string &location,
G
groot 已提交
27 28 29 30 31 32 33 34
                                         EngineType index_type,
                                         MetricType metric_type,
                                         int32_t nlist)
    : location_(location),
      dim_(dimension),
      index_type_(index_type),
      metric_type_(metric_type),
      nlist_(nlist) {
X
xj.lin 已提交
35 36 37 38

    index_ = CreatetVecIndex(EngineType::FAISS_IDMAP);
    if (!index_) throw Exception("Create Empty VecIndex");

X
xj.lin 已提交
39 40
    Config build_cfg;
    build_cfg["dim"] = dimension;
G
groot 已提交
41
    build_cfg["metric_type"] = (metric_type_ == MetricType::IP) ? "IP" : "L2";
X
xj.lin 已提交
42 43
    AutoGenParams(index_->GetType(), 0, build_cfg);
    auto ec = std::static_pointer_cast<BFIndex>(index_)->Build(build_cfg);
X
xj.lin 已提交
44
    if (ec != server::KNOWHERE_SUCCESS) { throw Exception("Build index error"); }
G
groot 已提交
45 46
}

X
xj.lin 已提交
47 48
ExecutionEngineImpl::ExecutionEngineImpl(VecIndexPtr index,
                                         const std::string &location,
G
groot 已提交
49 50 51 52 53 54 55 56
                                         EngineType index_type,
                                         MetricType metric_type,
                                         int32_t nlist)
    : index_(std::move(index)),
      location_(location),
      index_type_(index_type),
      metric_type_(metric_type),
      nlist_(nlist) {
X
xj.lin 已提交
57
}
G
groot 已提交
58

X
xj.lin 已提交
59 60 61 62 63
VecIndexPtr ExecutionEngineImpl::CreatetVecIndex(EngineType type) {
    std::shared_ptr<VecIndex> index;
    switch (type) {
        case EngineType::FAISS_IDMAP: {
            index = GetVecIndexFactory(IndexType::FAISS_IDMAP);
G
groot 已提交
64 65
            break;
        }
J
jinhai 已提交
66
        case EngineType::FAISS_IVFFLAT: {
X
xj.lin 已提交
67
            index = GetVecIndexFactory(IndexType::FAISS_IVFFLAT_MIX);
G
groot 已提交
68 69
            break;
        }
J
jinhai 已提交
70 71
        case EngineType::FAISS_IVFSQ8: {
            index = GetVecIndexFactory(IndexType::FAISS_IVFSQ8_MIX);
G
groot 已提交
72 73
            break;
        }
X
xj.lin 已提交
74 75 76 77
        case EngineType::NSG_MIX: {
            index = GetVecIndexFactory(IndexType::NSG_MIX);
            break;
        }
X
xj.lin 已提交
78
        default: {
G
groot 已提交
79 80 81 82
            ENGINE_LOG_ERROR << "Invalid engine type";
            return nullptr;
        }
    }
X
xj.lin 已提交
83
    return index;
G
groot 已提交
84 85 86
}

Status ExecutionEngineImpl::AddWithIds(long n, const float *xdata, const long *xids) {
X
xj.lin 已提交
87
    auto ec = index_->Add(n, xdata, xids);
X
xj.lin 已提交
88 89 90
    if (ec != server::KNOWHERE_SUCCESS) {
        return Status::Error("Add error");
    }
G
groot 已提交
91 92 93 94
    return Status::OK();
}

size_t ExecutionEngineImpl::Count() const {
X
xj.lin 已提交
95
    return index_->Count();
G
groot 已提交
96 97 98
}

size_t ExecutionEngineImpl::Size() const {
X
xj.lin 已提交
99
    return (size_t) (Count() * Dimension()) * sizeof(float);
G
groot 已提交
100 101 102
}

size_t ExecutionEngineImpl::Dimension() const {
X
xj.lin 已提交
103
    return index_->Dimension();
G
groot 已提交
104 105 106
}

size_t ExecutionEngineImpl::PhysicalSize() const {
J
jinhai 已提交
107
    return server::CommonUtil::GetFileSize(location_);
G
groot 已提交
108 109 110
}

Status ExecutionEngineImpl::Serialize() {
X
xj.lin 已提交
111 112 113 114
    auto ec = write_index(index_, location_);
    if (ec != server::KNOWHERE_SUCCESS) {
        return Status::Error("Serialize: write to disk error");
    }
G
groot 已提交
115 116 117
    return Status::OK();
}

J
jinhai 已提交
118
Status ExecutionEngineImpl::Load(bool to_cache) {
X
xj.lin 已提交
119
    index_ = zilliz::milvus::cache::CpuCacheMgr::GetInstance()->GetIndex(location_);
J
jinhai 已提交
120
    bool already_in_cache = (index_ != nullptr);
X
xj.lin 已提交
121 122
    auto start_time = METRICS_NOW_TIME;
    if (!index_) {
X
xj.lin 已提交
123 124 125 126 127 128 129 130 131
        try {
            index_ = read_index(location_);
            ENGINE_LOG_DEBUG << "Disk io from: " << location_;
        } catch (knowhere::KnowhereException &e) {
            ENGINE_LOG_ERROR << e.what();
            return Status::Error(e.what());
        } catch (std::exception &e) {
            return Status::Error(e.what());
        }
X
xj.lin 已提交
132 133
    }

J
jinhai 已提交
134
    if (!already_in_cache && to_cache) {
X
xj.lin 已提交
135 136 137
        Cache();
        auto end_time = METRICS_NOW_TIME;
        auto total_time = METRICS_MICROSECONDS(start_time, end_time);
X
xj.lin 已提交
138

X
xj.lin 已提交
139
        server::Metrics::GetInstance().FaissDiskLoadDurationSecondsHistogramObserve(total_time);
J
jinhai 已提交
140
        double physical_size = PhysicalSize();
X
xj.lin 已提交
141

J
jinhai 已提交
142 143
        server::Metrics::GetInstance().FaissDiskLoadSizeBytesHistogramObserve(physical_size);
        server::Metrics::GetInstance().FaissDiskLoadIOSpeedGaugeSet(physical_size / double(total_time));
X
xj.lin 已提交
144 145
    }
    return Status::OK();
X
xj.lin 已提交
146 147
}

148
Status ExecutionEngineImpl::CopyToGpu(uint64_t device_id) {
Y
Yu Kun 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161
    index_ = zilliz::milvus::cache::GpuCacheMgr::GetInstance(device_id)->GetIndex(location_);
    bool already_in_cache = (index_ != nullptr);
    auto start_time = METRICS_NOW_TIME;
    if (!index_) {
        try {
            index_ = index_->CopyToGpu(device_id);
            ENGINE_LOG_DEBUG << "CPU to GPU" << device_id;
        } catch (knowhere::KnowhereException &e) {
            ENGINE_LOG_ERROR << e.what();
            return Status::Error(e.what());
        } catch (std::exception &e) {
            return Status::Error(e.what());
        }
162
    }
Y
Yu Kun 已提交
163 164 165 166 167 168 169 170 171 172 173

    if (!already_in_cache) {
        GpuCache(device_id);
        auto end_time = METRICS_NOW_TIME;
        auto total_time = METRICS_MICROSECONDS(start_time, end_time);
        double physical_size = PhysicalSize();

        server::Metrics::GetInstance().FaissDiskLoadDurationSecondsHistogramObserve(total_time);
        server::Metrics::GetInstance().FaissDiskLoadIOSpeedGaugeSet(physical_size);
    }

174 175 176 177
    return Status::OK();
}

Status ExecutionEngineImpl::CopyToCpu() {
Y
Yu Kun 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    index_ = zilliz::milvus::cache::CpuCacheMgr::GetInstance()->GetIndex(location_);
    bool already_in_cache = (index_ != nullptr);
    auto start_time = METRICS_NOW_TIME;
    if (!index_) {
        try {
            index_ = index_->CopyToCpu();
            ENGINE_LOG_DEBUG << "GPU to CPU";
        } catch (knowhere::KnowhereException &e) {
            ENGINE_LOG_ERROR << e.what();
            return Status::Error(e.what());
        } catch (std::exception &e) {
            return Status::Error(e.what());
        }
    }

    if(!already_in_cache) {
        Cache();
        auto end_time = METRICS_NOW_TIME;
        auto total_time = METRICS_MICROSECONDS(start_time, end_time);
        double physical_size = PhysicalSize();

        server::Metrics::GetInstance().FaissDiskLoadDurationSecondsHistogramObserve(total_time);
        server::Metrics::GetInstance().FaissDiskLoadIOSpeedGaugeSet(physical_size);
201
    }
Y
Yu Kun 已提交
202

203 204 205
    return Status::OK();
}

X
xj.lin 已提交
206 207 208 209 210
Status ExecutionEngineImpl::Merge(const std::string &location) {
    if (location == location_) {
        return Status::Error("Cannot Merge Self");
    }
    ENGINE_LOG_DEBUG << "Merge index file: " << location << " to: " << location_;
G
groot 已提交
211

X
xj.lin 已提交
212 213
    auto to_merge = zilliz::milvus::cache::CpuCacheMgr::GetInstance()->GetIndex(location);
    if (!to_merge) {
X
xj.lin 已提交
214 215 216 217 218 219 220 221
        try {
            to_merge = read_index(location);
        } catch (knowhere::KnowhereException &e) {
            ENGINE_LOG_ERROR << e.what();
            return Status::Error(e.what());
        } catch (std::exception &e) {
            return Status::Error(e.what());
        }
X
xj.lin 已提交
222 223
    }

X
xj.lin 已提交
224
    if (auto file_index = std::dynamic_pointer_cast<BFIndex>(to_merge)) {
X
xj.lin 已提交
225 226 227 228 229
        auto ec = index_->Add(file_index->Count(), file_index->GetRawVectors(), file_index->GetRawIds());
        if (ec != server::KNOWHERE_SUCCESS) {
            ENGINE_LOG_ERROR << "Merge: Add Error";
            return Status::Error("Merge: Add Error");
        }
X
xj.lin 已提交
230 231 232 233
        return Status::OK();
    } else {
        return Status::Error("file index type is not idmap");
    }
G
groot 已提交
234 235 236
}

ExecutionEnginePtr
X
xj.lin 已提交
237 238 239 240
ExecutionEngineImpl::BuildIndex(const std::string &location) {
    ENGINE_LOG_DEBUG << "Build index file: " << location << " from: " << location_;

    auto from_index = std::dynamic_pointer_cast<BFIndex>(index_);
G
groot 已提交
241
    auto to_index = CreatetVecIndex(index_type_);
X
xj.lin 已提交
242 243 244 245
    if (!to_index) {
        throw Exception("Create Empty VecIndex");
    }

X
xj.lin 已提交
246 247
    Config build_cfg;
    build_cfg["dim"] = Dimension();
G
groot 已提交
248 249
    build_cfg["metric_type"] = (metric_type_ == MetricType::IP) ? "IP" : "L2";
    build_cfg["gpu_id"] = gpu_num_;
X
xj.lin 已提交
250
    build_cfg["nlist"] = nlist_;
X
xj.lin 已提交
251 252
    AutoGenParams(to_index->GetType(), Count(), build_cfg);

X
xj.lin 已提交
253 254 255
    auto ec = to_index->BuildAll(Count(),
                                 from_index->GetRawVectors(),
                                 from_index->GetRawIds(),
X
xj.lin 已提交
256
                                 build_cfg);
X
xj.lin 已提交
257
    if (ec != server::KNOWHERE_SUCCESS) { throw Exception("Build index error"); }
X
xj.lin 已提交
258

G
groot 已提交
259
    return std::make_shared<ExecutionEngineImpl>(to_index, location, index_type_, metric_type_, nlist_);
G
groot 已提交
260 261 262
}

Status ExecutionEngineImpl::Search(long n,
X
xj.lin 已提交
263 264
                                   const float *data,
                                   long k,
Y
Yu Kun 已提交
265
                                   long nprobe,
X
xj.lin 已提交
266 267
                                   float *distances,
                                   long *labels) const {
Y
Yu Kun 已提交
268 269
    ENGINE_LOG_DEBUG << "Search Params: [k]  " << k << " [nprobe] " << nprobe;
    auto ec = index_->Search(n, data, distances, labels, Config::object{{"k", k}, {"nprobe", nprobe}});
X
xj.lin 已提交
270 271 272 273
    if (ec != server::KNOWHERE_SUCCESS) {
        ENGINE_LOG_ERROR << "Search error";
        return Status::Error("Search: Search Error");
    }
G
groot 已提交
274 275 276 277
    return Status::OK();
}

Status ExecutionEngineImpl::Cache() {
X
xj.lin 已提交
278
    zilliz::milvus::cache::CpuCacheMgr::GetInstance()->InsertItem(location_, index_);
G
groot 已提交
279 280 281 282

    return Status::OK();
}

Y
Yu Kun 已提交
283 284 285 286
Status ExecutionEngineImpl::GpuCache(uint64_t gpu_id) {
    zilliz::milvus::cache::GpuCacheMgr::GetInstance(gpu_id)->InsertItem(location_, index_);
}

X
xj.lin 已提交
287
// TODO(linxj): remove.
G
groot 已提交
288
Status ExecutionEngineImpl::Init() {
X
xj.lin 已提交
289 290 291
    using namespace zilliz::milvus::server;
    ServerConfig &config = ServerConfig::GetInstance();
    ConfigNode server_config = config.GetConfig(CONFIG_SERVER);
G
groot 已提交
292
        gpu_num_ = server_config.GetInt32Value("gpu_index", 0);
G
groot 已提交
293 294 295 296 297 298 299 300

    return Status::OK();
}


} // namespace engine
} // namespace milvus
} // namespace zilliz