SearchTask.cpp 10.9 KB
Newer Older
1
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
J
jinhai 已提交
2
//
3 4
// 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
J
jinhai 已提交
5
//
6 7 8 9 10
// 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.
J
jinhai 已提交
11

Z
update  
Zhiru Zhu 已提交
12 13
#include "scheduler/task/SearchTask.h"

14
#include <fiu/fiu-local.h>
Z
update  
Zhiru Zhu 已提交
15

16
#include <src/index/thirdparty/faiss/IndexFlat.h>
S
starlord 已提交
17
#include <algorithm>
Z
Zhiru Zhu 已提交
18
#include <memory>
S
starlord 已提交
19
#include <string>
20
#include <thread>
21
#include <unordered_map>
S
starlord 已提交
22
#include <utility>
23

24
#include "db/Utils.h"
G
groot 已提交
25
#include "db/engine/ExecutionEngineImpl.h"
S
shengjh 已提交
26
#include "scheduler/SchedInst.h"
Z
Zhiru Zhu 已提交
27 28 29
#include "utils/Log.h"
#include "utils/TimeRecorder.h"

30
namespace milvus {
W
wxyu 已提交
31
namespace scheduler {
32

33 34 35
SearchTask::SearchTask(const server::ContextPtr& context, engine::snapshot::ScopedSnapshotT snapshot,
                       const engine::DBOptions& options, const query::QueryPtr& query_ptr,
                       engine::snapshot::ID_TYPE segment_id, TaskLabelPtr label)
G
groot 已提交
36 37
    : Task(TaskType::SearchTask, std::move(label)),
      context_(context),
38
      snapshot_(snapshot),
G
groot 已提交
39 40 41 42
      options_(options),
      query_ptr_(query_ptr),
      segment_id_(segment_id) {
    CreateExecEngine();
43 44
}

G
groot 已提交
45 46 47
void
SearchTask::CreateExecEngine() {
    if (execution_engine_ == nullptr && query_ptr_ != nullptr) {
48
        execution_engine_ = engine::EngineFactory::Build(snapshot_, options_.meta_.path_, segment_id_);
W
wxyu 已提交
49
    }
W
wxyu 已提交
50 51
}

G
groot 已提交
52 53
Status
SearchTask::OnLoad(LoadType type, uint8_t device_id) {
G
groot 已提交
54
    TimeRecorder rc("SearchTask::OnLoad " + std::to_string(segment_id_));
W
wxyu 已提交
55 56
    Status stat = Status::OK();
    std::string error_msg;
57
    std::string type_str;
58

G
groot 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72
    try {
        if (type == LoadType::DISK2CPU) {
            engine::ExecutionEngineContext context;
            context.query_ptr_ = query_ptr_;
            stat = execution_engine_->Load(context);
            type_str = "DISK2CPU";
        } else if (type == LoadType::CPU2GPU) {
            stat = execution_engine_->CopyToGpu(device_id);
            type_str = "CPU2GPU" + std::to_string(device_id);
        } else if (type == LoadType::GPU2CPU) {
            // stat = engine_->CopyToCpu();
            type_str = "GPU2CPU";
        } else {
            error_msg = "Wrong load type";
W
wxyu 已提交
73
            stat = Status(SERVER_UNEXPECTED_ERROR, error_msg);
W
wxyu 已提交
74
        }
G
groot 已提交
75 76 77
    } catch (std::exception& ex) {
        // typical error: out of disk space or permition denied
        error_msg = "Failed to load index file: " + std::string(ex.what());
G
groot 已提交
78
        LOG_ENGINE_ERROR_ << LogOut("Search task encounter exception: %s", error_msg.c_str());
G
groot 已提交
79
        stat = Status(SERVER_UNEXPECTED_ERROR, error_msg);
W
wxyu 已提交
80 81 82
    }

    if (!stat.ok()) {
83 84
        Status s;
        if (stat.ToString().find("out of memory") != std::string::npos) {
85
            error_msg = "out of memory: " + type_str + " : " + stat.message();
86 87
            s = Status(SERVER_OUT_OF_MEMORY, error_msg);
        } else {
88
            error_msg = "Failed to load index file: " + type_str + " : " + stat.message();
89 90
            s = Status(SERVER_UNEXPECTED_ERROR, error_msg);
        }
91

Y
yukun 已提交
92 93
        job_->status() = s;
        return Status::OK();
94 95
    }

G
groot 已提交
96
    std::string info = "Search task load segment id: " + std::to_string(segment_id_) + " " + type_str + " totally cost";
G
groot 已提交
97
    rc.ElapseFromBegin(info);
G
groot 已提交
98 99

    return Status::OK();
100 101
}

G
groot 已提交
102 103
Status
SearchTask::OnExecute() {
G
groot 已提交
104 105
    milvus::server::ContextFollower tracer(context_, "XSearchTask::Execute " + std::to_string(segment_id_));
    TimeRecorder rc(LogOut("[%s][%ld] DoSearch file id:%ld", "search", 0, segment_id_));
W
wxyu 已提交
106

G
groot 已提交
107 108 109
    if (execution_engine_ == nullptr) {
        return Status(DB_ERROR, "execution engine is null");
    }
G
groot 已提交
110

111 112
    //    auto search_job = std::static_pointer_cast<scheduler::SearchJob>(std::shared_ptr<scheduler::Job>(job_));
    auto search_job = static_cast<scheduler::SearchJob*>(job_);
G
groot 已提交
113 114 115 116 117
    try {
        /* step 2: search */
        engine::ExecutionEngineContext context;
        context.query_ptr_ = query_ptr_;
        context.query_result_ = std::make_shared<engine::QueryResult>();
118
        STATUS_CHECK(execution_engine_->Search(context));
119

G
groot 已提交
120 121 122
        rc.RecordSection("search done");

        /* step 3: pick up topk result */
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        // TODO(yukun): Remove hardcode here
        auto vector_param = context.query_ptr_->vectors.begin()->second;
        auto topk = vector_param->topk;
        auto segment_ptr = snapshot_->GetSegmentCommitBySegmentId(segment_id_);
        auto spec_k = segment_ptr->GetRowCount() < topk ? segment_ptr->GetRowCount() : topk;
        int64_t nq = vector_param->nq;
        if (spec_k == 0) {
            LOG_ENGINE_WARNING_ << LogOut("[%s][%ld] Searching in an empty segment. segment id = %d", "search", 0,
                                          segment_ptr->GetID());
        } else {
            //            std::unique_lock<std::mutex> lock(search_job->mutex());
            if (!search_job->query_result()) {
                search_job->query_result() = std::make_shared<engine::QueryResult>();
                search_job->query_result()->row_num_ = nq;
            }
Y
yukun 已提交
138 139 140
            if (vector_param->metric_type == "IP") {
                ascending_reduce_ = false;
            }
141 142 143 144
            SearchTask::MergeTopkToResultSet(context.query_result_->result_ids_,
                                             context.query_result_->result_distances_, spec_k, nq, topk,
                                             ascending_reduce_, search_job->query_result());
        }
G
groot 已提交
145 146 147 148 149

        rc.RecordSection("reduce topk done");
    } catch (std::exception& ex) {
        LOG_ENGINE_ERROR_ << LogOut("[%s][%ld] SearchTask encounter exception: %s", "search", 0, ex.what());
        return Status(SERVER_UNEXPECTED_ERROR, ex.what());
150 151 152
    }

    rc.ElapseFromBegin("totally cost");
G
groot 已提交
153
    return Status::OK();
Y
yudong.cai 已提交
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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
void
SearchTask::MergeTopkToResultSet(const engine::ResultIds& src_ids, const engine::ResultDistances& src_distances,
                                 size_t src_k, size_t nq, size_t topk, bool ascending, engine::QueryResultPtr& result) {
    if (src_ids.empty()) {
        LOG_ENGINE_DEBUG_ << LogOut("[%s][%d] Search result is empty.", "search", 0);
        return;
    }

    size_t tar_k = result->result_ids_.size() / nq;
    size_t buf_k = std::min(topk, src_k + tar_k);

    engine::ResultIds buf_ids(nq * buf_k, -1);
    engine::ResultDistances buf_distances(nq * buf_k, 0.0);
    for (uint64_t i = 0; i < nq; i++) {
        size_t buf_k_j = 0, src_k_j = 0, tar_k_j = 0;
        size_t buf_idx, src_idx, tar_idx;

        size_t buf_k_multi_i = buf_k * i;
        size_t src_k_multi_i = topk * i;
        size_t tar_k_multi_i = tar_k * i;

        while (buf_k_j < buf_k && src_k_j < src_k && tar_k_j < tar_k) {
            src_idx = src_k_multi_i + src_k_j;
            tar_idx = tar_k_multi_i + tar_k_j;
            buf_idx = buf_k_multi_i + buf_k_j;

            if ((result->result_ids_[tar_idx] == -1) ||  // initialized value
                (ascending && src_distances[src_idx] < result->result_distances_[tar_idx]) ||
                (!ascending && src_distances[src_idx] > result->result_distances_[tar_idx])) {
                buf_ids[buf_idx] = src_ids[src_idx];
                buf_distances[buf_idx] = src_distances[src_idx];
                src_k_j++;
            } else {
                buf_ids[buf_idx] = result->result_ids_[tar_idx];
                buf_distances[buf_idx] = result->result_distances_[tar_idx];
                tar_k_j++;
            }
            buf_k_j++;
        }

        if (buf_k_j < buf_k) {
            if (src_k_j < src_k) {
                while (buf_k_j < buf_k && src_k_j < src_k) {
                    buf_idx = buf_k_multi_i + buf_k_j;
                    src_idx = src_k_multi_i + src_k_j;
                    buf_ids[buf_idx] = src_ids[src_idx];
                    buf_distances[buf_idx] = src_distances[src_idx];
                    src_k_j++;
                    buf_k_j++;
                }
            } else {
                while (buf_k_j < buf_k && tar_k_j < tar_k) {
                    buf_idx = buf_k_multi_i + buf_k_j;
                    tar_idx = tar_k_multi_i + tar_k_j;
                    buf_ids[buf_idx] = result->result_ids_[tar_idx];
                    buf_distances[buf_idx] = result->result_distances_[tar_idx];
                    tar_k_j++;
                    buf_k_j++;
                }
            }
        }
    }
    result->result_ids_.swap(buf_ids);
    result->result_distances_.swap(buf_distances);
}

G
groot 已提交
222 223
int64_t
SearchTask::nq() {
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    if (query_ptr_) {
        auto vector_query = query_ptr_->vectors.begin();
        if (vector_query != query_ptr_->vectors.end()) {
            if (vector_query->second) {
                auto vector_param = vector_query->second;
                auto field_visitor = snapshot_->GetField(vector_query->second->field_name);
                if (field_visitor) {
                    if (field_visitor->GetParams().contains(engine::PARAM_DIMENSION)) {
                        int64_t dim = field_visitor->GetParams()[engine::PARAM_DIMENSION];
                        if (!vector_param->query_vector.float_data.empty()) {
                            return vector_param->query_vector.float_data.size() / dim;
                        } else if (!vector_param->query_vector.binary_data.empty()) {
                            return vector_param->query_vector.binary_data.size() * 8 / dim;
                        }
                    }
                }
            }
        }
    }
G
groot 已提交
243
    return 0;
244 245
}

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
milvus::json
SearchTask::ExtraParam() {
    milvus::json param;
    if (query_ptr_) {
        auto vector_query = query_ptr_->vectors.begin();
        if (vector_query != query_ptr_->vectors.end()) {
            if (vector_query->second) {
                return vector_query->second->extra_params;
            }
        }
    }
    return param;
}

std::string
SearchTask::IndexType() {
    if (!index_type_.empty()) {
        return index_type_;
    }
    auto seg_visitor = engine::SegmentVisitor::Build(snapshot_, segment_id_);
    index_type_ = "FLAT";

    if (seg_visitor) {
        for (const auto& name : query_ptr_->index_fields) {
            auto field_visitor = seg_visitor->GetFieldVisitor(name);
            auto type = field_visitor->GetField()->GetFtype();
            if (!field_visitor) {
                continue;
            }
            if (type == engine::DataType::VECTOR_FLOAT || type == engine::DataType::VECTOR_BINARY) {
                auto fe_visitor = field_visitor->GetElementVisitor(engine::FieldElementType::FET_INDEX);
                if (fe_visitor) {
                    auto element = fe_visitor->GetElement();
                    index_type_ = element->GetTypeName();
                }
                return index_type_;
            }
        }
    }
    return index_type_;
}

S
starlord 已提交
288 289
}  // namespace scheduler
}  // namespace milvus