SearchTask.cpp 13.5 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.

G
groot 已提交
18 19
#include "scheduler/task/SearchTask.h"
#include "scheduler/job/SearchJob.h"
G
groot 已提交
20 21 22 23
#include "metrics/Metrics.h"
#include "db/engine/EngineFactory.h"
#include "utils/TimeRecorder.h"
#include "utils/Log.h"
24 25

#include <thread>
G
groot 已提交
26 27
#include <utility>
#include <string>
28 29 30

namespace zilliz {
namespace milvus {
W
wxyu 已提交
31
namespace scheduler {
32 33 34 35

static constexpr size_t PARALLEL_REDUCE_THRESHOLD = 10000;
static constexpr size_t PARALLEL_REDUCE_BATCH = 1000;

J
jinhai 已提交
36 37
std::mutex XSearchTask::merge_mutex_;

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
//bool
//NeedParallelReduce(uint64_t nq, uint64_t topk) {
//    server::ServerConfig &config = server::ServerConfig::GetInstance();
//    server::ConfigNode &db_config = config.GetConfig(server::CONFIG_DB);
//    bool need_parallel = db_config.GetBoolValue(server::CONFIG_DB_PARALLEL_REDUCE, false);
//    if (!need_parallel) {
//        return false;
//    }
//
//    return nq * topk >= PARALLEL_REDUCE_THRESHOLD;
//}
//
//void
//ParallelReduce(std::function<void(size_t, size_t)> &reduce_function, size_t max_index) {
//    size_t reduce_batch = PARALLEL_REDUCE_BATCH;
//
//    auto thread_count = std::thread::hardware_concurrency() - 1; //not all core do this work
//    if (thread_count > 0) {
//        reduce_batch = max_index / thread_count + 1;
//    }
//    ENGINE_LOG_DEBUG << "use " << thread_count <<
//                     " thread parallelly do reduce, each thread process " << reduce_batch << " vectors";
//
//    std::vector<std::shared_ptr<std::thread> > thread_array;
//    size_t from_index = 0;
//    while (from_index < max_index) {
//        size_t to_index = from_index + reduce_batch;
//        if (to_index > max_index) {
//            to_index = max_index;
//        }
//
//        auto reduce_thread = std::make_shared<std::thread>(reduce_function, from_index, to_index);
//        thread_array.push_back(reduce_thread);
//
//        from_index = to_index;
//    }
//
//    for (auto &thread_ptr : thread_array) {
//        thread_ptr->join();
//    }
//}
79 80 81 82

void
CollectFileMetrics(int file_type, size_t file_size) {
    switch (file_type) {
W
wxyu 已提交
83 84
        case TableFileSchema::RAW:
        case TableFileSchema::TO_INDEX: {
85 86 87 88 89 90 91 92 93 94 95 96 97 98
            server::Metrics::GetInstance().RawFileSizeHistogramObserve(file_size);
            server::Metrics::GetInstance().RawFileSizeTotalIncrement(file_size);
            server::Metrics::GetInstance().RawFileSizeGaugeSet(file_size);
            break;
        }
        default: {
            server::Metrics::GetInstance().IndexFileSizeHistogramObserve(file_size);
            server::Metrics::GetInstance().IndexFileSizeTotalIncrement(file_size);
            server::Metrics::GetInstance().IndexFileSizeGaugeSet(file_size);
            break;
        }
    }
}

W
wxyu 已提交
99
XSearchTask::XSearchTask(TableFileSchemaPtr file)
W
wxyu 已提交
100
    : Task(TaskType::SearchTask), file_(file) {
W
wxyu 已提交
101 102 103 104 105 106 107
    if (file_) {
        index_engine_ = EngineFactory::Build(file_->dimension_,
                                             file_->location_,
                                             (EngineType) file_->engine_type_,
                                             (MetricType) file_->metric_type_,
                                             file_->nlist_);
    }
W
wxyu 已提交
108 109
}

110 111
void
XSearchTask::Load(LoadType type, uint8_t device_id) {
G
groot 已提交
112
    TimeRecorder rc("");
W
wxyu 已提交
113 114
    Status stat = Status::OK();
    std::string error_msg;
115
    std::string type_str;
116 117

    try {
W
wxyu 已提交
118
        if (type == LoadType::DISK2CPU) {
W
wxyu 已提交
119
            stat = index_engine_->Load();
120
            type_str = "DISK2CPU";
W
wxyu 已提交
121
        } else if (type == LoadType::CPU2GPU) {
W
wxyu 已提交
122
            stat = index_engine_->CopyToGpu(device_id);
123
            type_str = "CPU2GPU";
W
wxyu 已提交
124
        } else if (type == LoadType::GPU2CPU) {
W
wxyu 已提交
125
            stat = index_engine_->CopyToCpu();
126
            type_str = "GPU2CPU";
W
wxyu 已提交
127
        } else {
W
wxyu 已提交
128 129
            error_msg = "Wrong load type";
            stat = Status(SERVER_UNEXPECTED_ERROR, error_msg);
W
wxyu 已提交
130
        }
131 132
    } catch (std::exception &ex) {
        //typical error: out of disk space or permition denied
W
wxyu 已提交
133 134 135 136 137
        error_msg = "Failed to load index file: " + std::string(ex.what());
        stat = Status(SERVER_UNEXPECTED_ERROR, error_msg);
    }

    if (!stat.ok()) {
138 139 140 141 142 143 144 145
        Status s;
        if (stat.ToString().find("out of memory") != std::string::npos) {
            error_msg = "out of memory: " + type_str;
            s = Status(SERVER_OUT_OF_MEMORY, error_msg);
        } else {
            error_msg = "Failed to load index file: " + type_str;
            s = Status(SERVER_UNEXPECTED_ERROR, error_msg);
        }
146

G
groot 已提交
147
        if (auto job = job_.lock()) {
W
wxyu 已提交
148 149 150
            auto search_job = std::static_pointer_cast<scheduler::SearchJob>(job);
            search_job->SearchDone(file_->id_);
            search_job->GetStatus() = s;
151 152 153 154 155
        }

        return;
    }

W
wxyu 已提交
156
    size_t file_size = index_engine_->PhysicalSize();
157 158 159 160

    std::string info = "Load file id:" + std::to_string(file_->id_) + " file type:" + std::to_string(file_->file_type_)
        + " size:" + std::to_string(file_size) + " bytes from location: " + file_->location_ + " totally cost";
    double span = rc.ElapseFromBegin(info);
W
wxyu 已提交
161 162 163
//    for (auto &context : search_contexts_) {
//        context->AccumLoadCost(span);
//    }
164 165 166 167 168 169

    CollectFileMetrics(file_->file_type_, file_size);

    //step 2: return search task for later execution
    index_id_ = file_->id_;
    index_type_ = file_->file_type_;
W
wxyu 已提交
170
//    search_contexts_.swap(search_contexts_);
171 172 173 174 175 176 177 178
}

void
XSearchTask::Execute() {
    if (index_engine_ == nullptr) {
        return;
    }

W
wxyu 已提交
179 180
//    ENGINE_LOG_DEBUG << "Searching in file id:" << index_id_ << " with "
//                     << search_contexts_.size() << " tasks";
181

G
groot 已提交
182
    TimeRecorder rc("DoSearch file id:" + std::to_string(index_id_));
183

Y
Yu Kun 已提交
184
    server::CollectDurationMetrics metrics(index_type_);
185

G
groot 已提交
186
    std::vector<int64_t> output_ids;
J
jinhai 已提交
187
    std::vector<float> output_distance;
W
wxyu 已提交
188 189 190

    if (auto job = job_.lock()) {
        auto search_job = std::static_pointer_cast<scheduler::SearchJob>(job);
191
        //step 1: allocate memory
W
wxyu 已提交
192 193 194
        uint64_t nq = search_job->nq();
        uint64_t topk = search_job->topk();
        uint64_t nprobe = search_job->nprobe();
G
groot 已提交
195
        const float *vectors = search_job->vectors();
Y
yudong.cai 已提交
196 197 198

        output_ids.resize(topk * nq);
        output_distance.resize(topk * nq);
W
wxyu 已提交
199
        std::string hdr = "job " + std::to_string(search_job->id()) +
Y
Yu Kun 已提交
200 201
            " nq " + std::to_string(nq) +
            " topk " + std::to_string(topk);
202 203 204

        try {
            //step 2: search
Y
yudong.cai 已提交
205
            index_engine_->Search(nq, vectors, topk, nprobe, output_distance.data(), output_ids.data());
206

Y
yudong.cai 已提交
207
            double span = rc.RecordSection(hdr + ", do search");
W
wxyu 已提交
208
//            search_job->AccumSearchCost(span);
209

210

211
            //step 3: cluster result
W
wxyu 已提交
212
            scheduler::ResultSet result_set;
Y
yudong.cai 已提交
213 214
            auto spec_k = index_engine_->Count() < topk ? index_engine_->Count() : topk;
            XSearchTask::ClusterResult(output_ids, output_distance, nq, spec_k, result_set);
215

Y
yudong.cai 已提交
216
            span = rc.RecordSection(hdr + ", cluster result");
W
wxyu 已提交
217
//            search_job->AccumReduceCost(span);
218

J
jinhai 已提交
219
            // step 4: pick up topk result
W
wxyu 已提交
220
            XSearchTask::TopkResult(result_set, topk, metric_l2, search_job->GetResult());
221

Y
yudong.cai 已提交
222
            span = rc.RecordSection(hdr + ", reduce topk");
W
wxyu 已提交
223
//            search_job->AccumReduceCost(span);
224 225
        } catch (std::exception &ex) {
            ENGINE_LOG_ERROR << "SearchTask encounter exception: " << ex.what();
W
wxyu 已提交
226
//            search_job->IndexSearchDone(index_id_);//mark as done avoid dead lock, even search failed
227 228 229
        }

        //step 5: notify to send result to client
W
wxyu 已提交
230
        search_job->SearchDone(index_id_);
231 232 233
    }

    rc.ElapseFromBegin("totally cost");
234 235 236

    // release index in resource
    index_engine_ = nullptr;
237 238
}

G
groot 已提交
239 240 241 242 243 244
Status
XSearchTask::ClusterResult(const std::vector<int64_t> &output_ids,
                           const std::vector<float> &output_distance,
                           uint64_t nq,
                           uint64_t topk,
                           scheduler::ResultSet &result_set) {
J
jinhai 已提交
245
    if (output_ids.size() < nq * topk || output_distance.size() < nq * topk) {
246
        std::string msg = "Invalid id array size: " + std::to_string(output_ids.size()) +
J
jinhai 已提交
247
            " distance array size: " + std::to_string(output_distance.size());
248
        ENGINE_LOG_ERROR << msg;
G
groot 已提交
249
        return Status(DB_ERROR, msg);
250 251 252 253 254 255 256
    }

    result_set.clear();
    result_set.resize(nq);

    std::function<void(size_t, size_t)> reduce_worker = [&](size_t from_index, size_t to_index) {
        for (auto i = from_index; i < to_index; i++) {
W
wxyu 已提交
257
            scheduler::Id2DistanceMap id_distance;
258 259 260 261 262 263
            id_distance.reserve(topk);
            for (auto k = 0; k < topk; k++) {
                uint64_t index = i * topk + k;
                if (output_ids[index] < 0) {
                    continue;
                }
J
jinhai 已提交
264
                id_distance.push_back(std::make_pair(output_ids[index], output_distance[index]));
265 266 267 268 269
            }
            result_set[i] = id_distance;
        }
    };

270 271 272
//    if (NeedParallelReduce(nq, topk)) {
//        ParallelReduce(reduce_worker, nq);
//    } else {
W
wxyu 已提交
273
    reduce_worker(0, nq);
274
//    }
275 276 277 278

    return Status::OK();
}

G
groot 已提交
279 280 281 282 283
Status
XSearchTask::MergeResult(scheduler::Id2DistanceMap &distance_src,
                         scheduler::Id2DistanceMap &distance_target,
                         uint64_t topk,
                         bool ascending) {
284 285 286 287 288 289
    //Note: the score_src and score_target are already arranged by score in ascending order
    if (distance_src.empty()) {
        ENGINE_LOG_WARNING << "Empty distance source array";
        return Status::OK();
    }

J
jinhai 已提交
290
    std::unique_lock<std::mutex> lock(merge_mutex_);
291 292 293 294 295 296 297
    if (distance_target.empty()) {
        distance_target.swap(distance_src);
        return Status::OK();
    }

    size_t src_count = distance_src.size();
    size_t target_count = distance_target.size();
W
wxyu 已提交
298
    scheduler::Id2DistanceMap distance_merged;
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 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 352 353
    distance_merged.reserve(topk);
    size_t src_index = 0, target_index = 0;
    while (true) {
        //all score_src items are merged, if score_merged.size() still less than topk
        //move items from score_target to score_merged until score_merged.size() equal topk
        if (src_index >= src_count) {
            for (size_t i = target_index; i < target_count && distance_merged.size() < topk; ++i) {
                distance_merged.push_back(distance_target[i]);
            }
            break;
        }

        //all score_target items are merged, if score_merged.size() still less than topk
        //move items from score_src to score_merged until score_merged.size() equal topk
        if (target_index >= target_count) {
            for (size_t i = src_index; i < src_count && distance_merged.size() < topk; ++i) {
                distance_merged.push_back(distance_src[i]);
            }
            break;
        }

        //compare score,
        // if ascending = true, put smallest score to score_merged one by one
        // else, put largest score to score_merged one by one
        auto &src_pair = distance_src[src_index];
        auto &target_pair = distance_target[target_index];
        if (ascending) {
            if (src_pair.second > target_pair.second) {
                distance_merged.push_back(target_pair);
                target_index++;
            } else {
                distance_merged.push_back(src_pair);
                src_index++;
            }
        } else {
            if (src_pair.second < target_pair.second) {
                distance_merged.push_back(target_pair);
                target_index++;
            } else {
                distance_merged.push_back(src_pair);
                src_index++;
            }
        }

        //score_merged.size() already equal topk
        if (distance_merged.size() >= topk) {
            break;
        }
    }

    distance_target.swap(distance_merged);

    return Status::OK();
}

G
groot 已提交
354 355 356 357 358
Status
XSearchTask::TopkResult(scheduler::ResultSet &result_src,
                        uint64_t topk,
                        bool ascending,
                        scheduler::ResultSet &result_target) {
359 360 361 362 363 364 365 366
    if (result_target.empty()) {
        result_target.swap(result_src);
        return Status::OK();
    }

    if (result_src.size() != result_target.size()) {
        std::string msg = "Invalid result set size";
        ENGINE_LOG_ERROR << msg;
G
groot 已提交
367
        return Status(DB_ERROR, msg);
368 369 370 371
    }

    std::function<void(size_t, size_t)> ReduceWorker = [&](size_t from_index, size_t to_index) {
        for (size_t i = from_index; i < to_index; i++) {
W
wxyu 已提交
372 373
            scheduler::Id2DistanceMap &score_src = result_src[i];
            scheduler::Id2DistanceMap &score_target = result_target[i];
374 375 376 377
            XSearchTask::MergeResult(score_src, score_target, topk, ascending);
        }
    };

378 379 380
//    if (NeedParallelReduce(result_src.size(), topk)) {
//        ParallelReduce(ReduceWorker, result_src.size());
//    } else {
W
wxyu 已提交
381
    ReduceWorker(0, result_src.size());
382
//    }
383 384 385 386

    return Status::OK();
}

G
groot 已提交
387 388 389
} // namespace scheduler
} // namespace milvus
} // namespace zilliz