bsf.h 22.6 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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
//
//     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.

#pragma once
W
wangguibao 已提交
16 17

#include <errno.h>
W
wangguibao 已提交
18
#include <algorithm>
H
HexToString 已提交
19
#include <list>
W
wangguibao 已提交
20
#include <vector>
W
wangguibao 已提交
21 22 23 24

#ifdef BCLOUD
#include "base/atomicops.h"
#else
W
wangguibao 已提交
25
#include "butil/atomicops.h"
W
wangguibao 已提交
26 27
#endif

G
guru4elephant 已提交
28
#include "core/predictor/common/inner_common.h"
W
wangguibao 已提交
29

W
wangguibao 已提交
30
#include "boost/function.hpp"
W
wangguibao 已提交
31

32 33 34
#include "core/predictor/framework/memory.h"
#include "paddle_inference_api.h"

W
wangguibao 已提交
35 36 37 38 39
namespace im {
namespace bsf {

static const size_t DEFAULT_BATCH_SIZE = 100;

40 41 42 43 44 45 46 47 48 49 50 51
// InItemT is paddle::PaddleTensor
// InVectorT std::vector<paddle::PaddleTensor>
// InVectorT means different feedvar, but not batch.
// Batch is already inside the  paddle::PaddleTensor.

// size_t `rem` records how many batch have not been put in BatchTasks.
// `rem` don`t need to be atomic, cause the operation `put` is synchronous.
// actually, the reason is that lock have been added outside the operation
// `put`.

// size_t `index` records how many batch have been processing completed.
// `index` need to be atomic, cause the operation 'notify' is asynchronous.
W
wangguibao 已提交
52
template <typename InItemT, typename OutItemT>
W
wangguibao 已提交
53
struct Task {
54 55
  typedef std::vector<InItemT> InVectorT;
  typedef std::vector<OutItemT> OutVectorT;
W
wangguibao 已提交
56 57 58
  typedef InItemT InType;
  typedef OutItemT OutType;
  typedef Task<InItemT, OutItemT> TaskT;
59 60
  typedef std::vector<int> ShapeVector;
  typedef std::vector<ShapeVector> VectorOfShapeVector;
W
wangguibao 已提交
61

W
wangguibao 已提交
62 63 64
  int read_fd;
  int write_fd;
  pid_t owner_tid;
65 66
  const InVectorT* inVectorT_ptr;
  OutVectorT* outVectorT_ptr;
W
wangguibao 已提交
67 68 69 70 71 72 73
  size_t rem;
  butil::atomic<size_t> index;

  Task() {
    read_fd = -1;
    write_fd = -1;
    owner_tid = -1;
74 75
    inVectorT_ptr = NULL;
    outVectorT_ptr = NULL;
W
wangguibao 已提交
76 77 78
    rem = -1;
    index.store(0, butil::memory_order_relaxed);
  }
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

  bool check_feedvar_valid(int feedvar_index) {
    if (feedvar_index < 0 || inVectorT_ptr->size() <= feedvar_index) {
      LOG(ERROR) << "feedvar doesnt exsit or feedvar_index error";
      return 0;
    }

    if ((*inVectorT_ptr)[feedvar_index].shape.size() <= 0) {
      LOG(ERROR) << "feedvar[" << feedvar_index << "].shape.size()<=0,error";
      return 0;
    }

    return 1;
  }

  // Now, it simply assume that the first dimension of data is batch.
  // so the batch is PaddleTensor.shape[0]

  // If batch information is added into feedvar.prototxt.
  // we can get the information from the feedvar.prototxt instead of assume.
  size_t feedvar_batch_size(int feedvar_index) {
    if (!check_feedvar_valid(feedvar_index)) {
      return 0;
    }

    return (*inVectorT_ptr)[feedvar_index].shape[0];
  }

  size_t feedvar_element_bytesize(int feedvar_index) {
    if (!check_feedvar_valid(feedvar_index)) {
      return 0;
    }
    int dtype = (*inVectorT_ptr)[feedvar_index].dtype;
    if (dtype == paddle::PaddleDType::INT64) {
      return sizeof(int64_t);
    }
    if (dtype == paddle::PaddleDType::FLOAT32) {
      return sizeof(float);
    }
    if (dtype == paddle::PaddleDType::INT32) {
      return sizeof(int32_t);
    }
    if (dtype == paddle::PaddleDType::UINT8) {
      return sizeof(char);
    }
    return 0;
  }

  // Now, the implementation of this function is based on assumption
  // that shape [0] = batch_size.
  size_t feedvar_element_num(int feedvar_index) {
    if (!check_feedvar_valid(feedvar_index)) {
      return 0;
    }
    int element_num = 1;
    if ((*inVectorT_ptr)[feedvar_index].shape.size() == 1) {
      // cause shape[0] is batch_size.
H
HexToString 已提交
136 137
      // [10,1] = [10], so if shape[1] doesn`t exist.
      // should return 1.
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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 188 189 190 191 192 193 194
      return 1;
    }
    // start from shape[1], cause shape[0] = batch_size.
    for (int i = 1; i < (*inVectorT_ptr)[feedvar_index].shape.size(); ++i) {
      element_num *= (*inVectorT_ptr)[feedvar_index].shape[i];
    }
    return element_num;
  }

  size_t feedvar_bytesize(int feedvar_index) {
    return feedvar_element_num(feedvar_index) *
           feedvar_element_bytesize(feedvar_index);
  }

  ShapeVector feedvar_shape_nobatch(int feedvar_index) {
    if (!check_feedvar_valid(feedvar_index)) {
      return ShapeVector();
    }
    return ShapeVector{(*inVectorT_ptr)[feedvar_index].shape.begin() + 1,
                       (*inVectorT_ptr)[feedvar_index].shape.end()};
  }

  VectorOfShapeVector feedvar_shape_nobatch() {
    VectorOfShapeVector vector_of_feedvar_shape_nobatch(inVectorT_ptr->size());
    for (int index = 0; index < inVectorT_ptr->size(); ++index) {
      vector_of_feedvar_shape_nobatch.push_back(feedvar_shape_nobatch(index));
    }
    return vector_of_feedvar_shape_nobatch;
  }

  // At present, it is considered that the batch of all feedvar is consistent.
  // so for each feedvar, PaddleTensor.shape[0] should be the same.
  bool check_batch_align() {
    int batch_size_align = feedvar_batch_size(0);
    for (int feedvar_index = 0; feedvar_index < inVectorT_ptr->size();
         ++feedvar_index) {
      if (feedvar_batch_size(feedvar_index) != batch_size_align) {
        return 0;
      }
    }
    /*
    for(int fetchvar_index = 0; fetchvar_index < outVectorT_ptr->size();
    ++fetchvar_index) {
      if(fetchvar_batch_size(fetchvar_index) != batch_size_align) {
        return 0;
      }
    }
    */
    return 1;
  }

  size_t batch_size() {
    if (check_batch_align()) {
      return feedvar_batch_size(0);
    }
    return 0;
  }
W
wangguibao 已提交
195 196
};

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
// `Several Task` or `part of batch in Task` can be a TaskMeta.
// Task is the original Request from User.
// For example, the batch of Task is 30. There are 4 Requests.
// The batch of BatchTasks is 100, which means we can deal 100 batch 1 time.
// TaskMeta-1:{task-1,0,30} TaskMeta-2:{task-2,0,30} TaskMeta-3:{task-3,0,30}
// but the last Task will be divided to 2 TaskMeta.
// TaskMeta-4:{task-4,0,10} TaskMeta-5:{task-4,10,30}.
// TaskMeta-1 ~ TaskMeta-4 will be inside BatchTasks-1.
// TaskMeta-5 will be inside BatchTasks-2.

// TaskMeta is necessary.
// cause we need know the the corresponding relationship between
// `batch_out`(which is in BatchTasks) and `outVectorT_ptr`(which is in Task).
// especially when 1 Task be divided into several TaskMeta and be put into
// several different BatchTasks.
W
wangguibao 已提交
212
template <typename TaskT>
W
wangguibao 已提交
213
struct TaskMeta {
W
wangguibao 已提交
214 215 216 217 218 219
  TaskMeta(TaskT* ptr, size_t start, size_t add)
      : task(ptr), begin(start), end(start + add) {}

  TaskT* task;
  size_t begin;
  size_t end;
W
wangguibao 已提交
220 221
};

222 223 224
// each TaskT is already include batch in itself
// BatchTasks need to combine several `small TaskMeta` into a new `big TaskT`.
// The only difference between the `big TaskT` and `small TaskT` is that
H
HexToString 已提交
225 226
// the TaskT.inVectorT_ptr->[feedvar_index].shape[0]
// which is actually batch_size is different.
W
wangguibao 已提交
227
template <typename TaskT>
W
wangguibao 已提交
228
class BatchTasks {
W
wangguibao 已提交
229 230 231 232 233 234 235 236 237 238
 public:
  typedef typename TaskT::InType InType;
  typedef typename TaskT::OutType OutType;
  typedef TaskMeta<TaskT> TaskMetaT;

  explicit BatchTasks(size_t batch_size, bool batch_align = true)
      : _batch_size(batch_size),
        _rem_size(batch_size),
        _batch_align(batch_align) {
    _batch_in.clear();
239
    _batch_in_offset.clear();
W
wangguibao 已提交
240
    _batch_out.clear();
241 242
    _batch_out_offset.clear();
    _taskmeta_vector.clear();
W
wangguibao 已提交
243 244 245 246
  }

  ~BatchTasks() {
    _batch_in.clear();
247
    _batch_in_offset.clear();
W
wangguibao 已提交
248
    _batch_out.clear();
249 250
    _batch_out_offset.clear();
    _taskmeta_vector.clear();
W
wangguibao 已提交
251 252 253
  }

  // synchronized operation
254
  // because Upper level callers of this function have already locked.
W
wangguibao 已提交
255 256 257 258
  size_t append_task(TaskT* task) {
    size_t add = std::min(task->rem, _rem_size);
    if (!_batch_align) {
      add = task->rem;
W
wangguibao 已提交
259
    }
260 261 262
    int start_index = task->batch_size() - task->rem;
    TaskMetaT tm(task, start_index, add);
    _taskmeta_vector.push_back(tm);
W
wangguibao 已提交
263 264 265 266 267 268

    task->rem -= add;
    _rem_size -= add;
    return _rem_size;
  }

269 270
  static bool check_valid(const typename TaskT::InVectorT& in,
                          const typename TaskT::OutVectorT& out,
W
wangguibao 已提交
271 272 273 274 275 276 277
                          bool align) {
    (void)in;
    (void)out;
    (void)align;
    return true;
  }

278 279 280 281 282 283 284 285 286 287 288
  // this should be modified totally.
  // maybe we don`t need to do this inside the BatchTasks.
  // we can do the copy work outside the BatchTasks.
  // cause maybe next time we don`t need to do the extra copy.
  // directly copy the every Task into the Predictor.

  // lod is not supported.
  // if lod is set, we should not allow to use the bsf task.

  // batch.merge_tasks() is thread-safe function
  // cause batch is a local variable and Task is just read, not written.
W
wangguibao 已提交
289
  void merge_tasks() {
290 291 292 293 294 295 296 297 298 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
    if (_taskmeta_vector.size() <= 0) {
      return;
    }

    // Temporarily, the batch of each feedvar is consistent
    // If not consistent, use feedvar_batch_size instead of task->batch_size().
    int temp_batch = 0;
    for (size_t ti = 0; ti < _taskmeta_vector.size(); ++ti) {
      TaskMetaT& tm = _taskmeta_vector[ti];
      temp_batch += tm.task->batch_size();
    }
    if (temp_batch > _batch_size) {
      LOG(ERROR) << "_realNumber_batch_in >_batch_size, error.";
      return;
    }

    int feedvar_num = _taskmeta_vector[0].task->inVectorT_ptr->size();
    if (_batch_in_offset.size() == 0) {
      _batch_in_offset.resize(feedvar_num, 0);
      _realNumber_batch_in.resize(feedvar_num, temp_batch);
    }

    for (size_t ti = 0; ti < _taskmeta_vector.size(); ++ti) {
      TaskMetaT& tm = _taskmeta_vector[ti];

      for (int index = 0; index < feedvar_num; ++index) {
        const paddle::PaddleTensor& feedVarTensor =
            (*tm.task->inVectorT_ptr)[index];
        int feedvar_bytesize = tm.task->feedvar_bytesize(index);

        if (ti == 0) {
          if (feedVarTensor.lod.size() > 0 && feedVarTensor.lod[0].size() > 0) {
            LOG(ERROR) << "lod Tensor is not supported now.";
            return;
          }
          // for now, we assume that every task feedvar_bytesize is the same.
          // which means we dont support auto embedding.
          // but for different feedvar, it is different.
          paddle::PaddleTensor paddleTensor;
          paddleTensor.dtype = feedVarTensor.dtype;
          paddleTensor.name = feedVarTensor.name;
          paddleTensor.lod = feedVarTensor.lod;
          paddleTensor.shape = feedVarTensor.shape;
          paddleTensor.shape[0] = _realNumber_batch_in[index];
          paddleTensor.data.Resize(feedvar_bytesize *
                                   _realNumber_batch_in[index]);
          _batch_in.push_back(paddleTensor);
        }

        void* dst_ptr = _batch_in[index].data.data() +
                        feedvar_bytesize * _batch_in_offset[index];
        void* source_ptr =
            feedVarTensor.data.data() + feedvar_bytesize * tm.begin;
        int length = feedvar_bytesize * (tm.end - tm.begin);
        memcpy(dst_ptr, source_ptr, length);
        _batch_in_offset[index] += length;
W
wangguibao 已提交
346
      }
W
wangguibao 已提交
347
    }
W
wangguibao 已提交
348
  }
W
wangguibao 已提交
349

350 351 352 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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  bool check_fetchvar_valid(int fetchvar_index) {
    if (fetchvar_index < 0 || _batch_out.size() <= fetchvar_index) {
      LOG(ERROR) << "fetchvar doesnt exsit or fetchvar_index error";
      return 0;
    }

    if (_batch_out[fetchvar_index].shape.size() <= 0) {
      LOG(ERROR) << "fetchvar[" << fetchvar_index << "].shape.size()<=0,error";
      return 0;
    }

    return 1;
  }

  size_t fetchvar_batch_size(int fetchvar_index) {
    if (!check_fetchvar_valid(fetchvar_index)) {
      return 0;
    }

    return _batch_out[fetchvar_index].shape[0];
  }

  size_t fetchvar_element_bytesize(int fetchvar_index) {
    if (!check_fetchvar_valid(fetchvar_index)) {
      return 0;
    }
    int dtype = _batch_out[fetchvar_index].dtype;
    if (dtype == paddle::PaddleDType::INT64) {
      return sizeof(int64_t);
    }
    if (dtype == paddle::PaddleDType::FLOAT32) {
      return sizeof(float);
    }
    if (dtype == paddle::PaddleDType::INT32) {
      return sizeof(int32_t);
    }
    if (dtype == paddle::PaddleDType::UINT8) {
      return sizeof(char);
    }
    return 0;
  }

  // Now, the implementation of this function is based on assumption
  // that shape [0] = batch_size.
  size_t fetchvar_element_num(int fetchvar_index) {
    if (!check_fetchvar_valid(fetchvar_index)) {
      return 0;
    }
    int element_num = 1;
    if (_batch_out[fetchvar_index].shape.size() == 1) {
      // cause shape[0] is batch_size.
      return 1;
    }
    // start from shape[1], cause shape[0] = batch_size.
    for (int i = 1; i < _batch_out[fetchvar_index].shape.size(); ++i) {
      element_num *= _batch_out[fetchvar_index].shape[i];
    }
    return element_num;
  }

  size_t fetchvar_bytesize(int fetchvar_index) {
    return fetchvar_element_num(fetchvar_index) *
           fetchvar_element_bytesize(fetchvar_index);
  }

  bool check_fetchvar_batch_align() {
    int batch_size_align = fetchvar_batch_size(0);

    for (int fetchvar_index = 0; fetchvar_index < _batch_out.size();
         ++fetchvar_index) {
      if (fetchvar_batch_size(fetchvar_index) != batch_size_align) {
        return 0;
      }
    }

    return 1;
  }

  size_t fetchvar_batch_size() {
    if (check_fetchvar_batch_align()) {
      return fetchvar_batch_size(0);
    }
    return 0;
  }

W
wangguibao 已提交
435
  void notify_tasks() {
436 437 438 439 440 441
    if (_taskmeta_vector.size() <= 0) {
      LOG(ERROR) << "_taskmeta_vector.size() <=0, error.";
      return;
    }
    if (_realNumber_batch_in[0] != fetchvar_batch_size()) {
      LOG(ERROR) << "_batch_out`s batch != _batch_in`s batch, error.";
W
wangguibao 已提交
442
      return;
W
wangguibao 已提交
443 444
    }

445 446 447 448 449 450 451 452 453
    int fetchvar_num = _batch_out.size();
    if (_batch_out_offset.size() == 0) {
      _batch_out_offset.resize(fetchvar_num, 0);
    }

    for (size_t ti = 0; ti < _taskmeta_vector.size(); ++ti) {
      TaskT* task = _taskmeta_vector[ti].task;
      size_t begin = _taskmeta_vector[ti].begin;
      size_t end = _taskmeta_vector[ti].end;
W
wangguibao 已提交
454 455
      size_t add = end - begin;

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
      for (int index = 0; index < fetchvar_num; ++index) {
        // the task->outVectorT_ptr is null before core->run().
        // first time we should copy from _batch_out
        // so we need init.
        int fetchvar_bytesize_index = fetchvar_bytesize(index);
        if (task->outVectorT_ptr->size() <= index) {
          paddle::PaddleTensor tensor_out;
          tensor_out.name = _batch_out[index].name;
          tensor_out.dtype = paddle::PaddleDType(_batch_out[index].dtype);
          tensor_out.shape = _batch_out[index].shape;
          tensor_out.shape[0] = task->batch_size();
          tensor_out.lod = _batch_out[index].lod;
          // resize all batch memory at one time
          size_t databuf_size = task->batch_size() * fetchvar_bytesize_index;
          tensor_out.data.Resize(databuf_size);
          task->outVectorT_ptr->push_back(tensor_out);
        }

        paddle::PaddleTensor& fetchVarTensor = (*task->outVectorT_ptr)[index];

        void* dst_ptr =
            fetchVarTensor.data.data() + fetchvar_bytesize_index * begin;
        int length = fetchvar_bytesize_index * add;
        if (_batch_out_offset[index] + length >
            fetchvar_batch_size() * fetchvar_bytesize(index)) {
          LOG(ERROR) << "_batch_out is less than taskmeta, error.";
W
wangguibao 已提交
482
          return;
W
wangguibao 已提交
483
        }
484 485 486 487 488
        void* source_ptr =
            _batch_out[index].data.data() + _batch_out_offset[index];

        memcpy(dst_ptr, source_ptr, length);
        _batch_out_offset[index] += length;
W
wangguibao 已提交
489
      }
W
wangguibao 已提交
490

W
wangguibao 已提交
491
      size_t index = task->index.fetch_add(add);
492
      if ((index + add) >= task->batch_size()) {
W
wangguibao 已提交
493 494
        char c = 0;
        while (write(task->write_fd, &c, 1) != 1 && errno == EINTR) {
W
wangguibao 已提交
495
        }
W
wangguibao 已提交
496 497
        butil::return_object(task);
      }
W
wangguibao 已提交
498
    }
W
wangguibao 已提交
499
  }
W
wangguibao 已提交
500

501
  const typename TaskT::InVectorT& in() const { return _batch_in; }
W
wangguibao 已提交
502

503
  typename TaskT::OutVectorT& out() { return _batch_out; }
W
wangguibao 已提交
504

505
  size_t task_size() { return _taskmeta_vector.size(); }
W
wangguibao 已提交
506 507

 private:
508 509 510 511 512 513 514
  std::vector<TaskMetaT> _taskmeta_vector;
  typename TaskT::InVectorT _batch_in;
  std::vector<int> _batch_in_offset;
  std::vector<int> _realNumber_batch_in;
  typename TaskT::OutVectorT _batch_out;
  std::vector<int> _batch_out_offset;
  std::vector<int> _realNumber_batch_out;
W
wangguibao 已提交
515 516 517
  size_t _rem_size;
  size_t _batch_size;
  bool _batch_align;
W
wangguibao 已提交
518 519
};

W
wangguibao 已提交
520
// BSF task handle
H
HexToString 已提交
521 522 523 524 525 526 527
// TaskHandler is the handle of Task.
// `read_fd` is used for receive signal in brpc Thread.
// 'write_fd' is used for write signal in bsf Thread.
// when TaskMeta is done, bsf Thread will write to 'write_fd'.
// brpc Thread is keeping reading 'read_fd' in a while loop.
// brpc Thread will receive signal when TaskMeta is done.
// so `read_fd` and 'write_fd' is used for communicate in different Thread.
W
wangguibao 已提交
528
template <typename TaskT>
W
wangguibao 已提交
529
struct TaskHandler {
W
wangguibao 已提交
530 531
  int read_fd;
  int write_fd;
W
wangguibao 已提交
532

W
wangguibao 已提交
533 534 535
  TaskHandler() : read_fd(-1), write_fd(-1) {
    // do nothing
  }
W
wangguibao 已提交
536

W
wangguibao 已提交
537 538 539 540
  explicit TaskHandler(TaskT const& task)
      : read_fd(task.read_fd), write_fd(task.write_fd) {
    // do nothing
  }
W
wangguibao 已提交
541

W
wangguibao 已提交
542
  inline bool valid() const { return read_fd >= 0 && write_fd >= 0; }
W
wangguibao 已提交
543

W
wangguibao 已提交
544 545 546 547
  static TaskHandler<TaskT>& valid_handle() {
    static TaskHandler<TaskT> vhandle;
    return vhandle;
  }
W
wangguibao 已提交
548 549
};

H
HexToString 已提交
550
// TaskExecutor is a Thread pool.
W
wangguibao 已提交
551
template <typename TaskT>
W
wangguibao 已提交
552 553
class TaskExecutor;

H
HexToString 已提交
554
// ThreadContext is used for start a bsf Thread.
W
wangguibao 已提交
555
template <typename TaskT>
W
wangguibao 已提交
556
struct ThreadContext {
W
wangguibao 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  TaskExecutor<TaskT>* executor;
  void* user_thread_context;
  THREAD_T tid;
  int init_status;

  ThreadContext()
      : executor(NULL), user_thread_context(NULL), tid(-1), init_status(0) {
    // do nothing
  }

  ~ThreadContext() {
    tid = -1;
    executor = NULL;
    user_thread_context = NULL;
    init_status = 0;
  }
W
wangguibao 已提交
573 574
};

H
HexToString 已提交
575 576 577 578 579 580 581 582 583
// TaskExecutor is a Thread pool.
// Each Model corresponding to a Model.
// TaskT is actually a Request preprocessed by ReaderOp.
// TaskT will be divided as TaskMeta which will be
// put into _task_queue in brpc-Thread by schedule().
// TaskHander will be returned to brpc-Thread.
// start() function will create `thread_num` bsf Threads.
// every bsf Thread check the _task_queue and take TaskMeta from it.
// when a Task`s all TaskMeta is done, TaskHander will be noticed.
W
wangguibao 已提交
584
template <typename TaskT>
W
wangguibao 已提交
585
class TaskExecutor {
W
wangguibao 已提交
586 587 588
 public:
  typedef typename TaskT::InType InType;
  typedef typename TaskT::OutType OutType;
589 590
  typedef typename TaskT::InVectorT InVectorT;
  typedef typename TaskT::OutVectorT OutVectorT;
W
wangguibao 已提交
591
  typedef std::vector<TaskT> TaskArrayT;
592
  typedef baidu::paddle_serving::predictor::MempoolWrapper MempoolWrapper;
W
wangguibao 已提交
593

W
wangguibao 已提交
594 595 596 597 598 599 600 601 602 603 604 605
  TaskExecutor()
      : _stop(false),
        _thread_init_fn(NULL),
        _thread_reset_fn(NULL),
        _user_thread_contexts(NULL),
        _batch_size(DEFAULT_BATCH_SIZE),
        _batch_align(false),
        _fn(NULL) {
    THREAD_MUTEX_INIT(&_mut, NULL);
    THREAD_COND_INIT(&_cond, NULL);
    _task_queue.clear();
  }
W
wangguibao 已提交
606

W
wangguibao 已提交
607 608 609 610
  ~TaskExecutor() {
    THREAD_MUTEX_DESTROY(&_mut);
    THREAD_COND_DESTROY(&_cond);
  }
W
wangguibao 已提交
611

H
HexToString 已提交
612 613 614 615 616
  // cause vector.resize will use copy or move construct.
  TaskExecutor(TaskExecutor<TaskT>&& other) noexcept {
    if (this != &other) {
      TaskExecutor();
    }
W
wangguibao 已提交
617
  }
W
wangguibao 已提交
618

W
wangguibao 已提交
619
  void set_batch_size(size_t batch_size) { _batch_size = batch_size; }
W
wangguibao 已提交
620

W
wangguibao 已提交
621
  void set_batch_align(size_t batch_align) { _batch_align = batch_align; }
W
wangguibao 已提交
622

W
wangguibao 已提交
623 624 625 626 627
  void set_thread_init_fn(boost::function<int(void*)> init_fn,
                          void** contexts = NULL) {
    _thread_init_fn = init_fn;
    _user_thread_contexts = contexts;
  }
W
wangguibao 已提交
628

W
wangguibao 已提交
629 630 631 632
  void set_thread_reset_fn(boost::function<int(void*)> reset_fn) {
    _thread_reset_fn = reset_fn;
  }

633
  void set_thread_callback_fn(boost::function<void(const void*, void*)> cb) {
W
wangguibao 已提交
634 635
    _fn = cb;
  }
W
wangguibao 已提交
636

W
wangguibao 已提交
637 638
  int start(uint32_t thread_num, uint32_t init_timeout_sec = 0);
  void stop();
W
wangguibao 已提交
639

W
wangguibao 已提交
640
  static void* thread_entry(void* args);
W
wangguibao 已提交
641

W
wangguibao 已提交
642
  int work(ThreadContext<TaskT>* context);
W
wangguibao 已提交
643

644
  TaskHandler<TaskT> schedule(const void*, void*);
W
wangguibao 已提交
645

646
  bool move_task_to_batch(BatchTasks<TaskT>& batch);  // NOLINT
W
wangguibao 已提交
647

H
HexToString 已提交
648 649 650 651 652 653 654 655 656 657
 private:
  TaskExecutor(TaskExecutor<TaskT> const& other) = delete;

  TaskExecutor& operator=(TaskExecutor<TaskT> const& other) = delete;
  /*
  TaskExecutor(TaskExecutor<TaskT> && other) = delete;

  TaskExecutor& operator=(TaskExecutor<TaskT> && other) = delete;
  */

W
wangguibao 已提交
658
  bool _stop;
W
wangguibao 已提交
659

W
wangguibao 已提交
660 661 662
  // can't use boost::mutex, because some stupid macro
  THREAD_MUTEX_T _mut;
  THREAD_COND_T _cond;
W
wangguibao 已提交
663

H
HexToString 已提交
664
  std::list<TaskT*> _task_queue;
W
wangguibao 已提交
665

W
wangguibao 已提交
666 667 668
  boost::function<int(void*)> _thread_init_fn;
  boost::function<int(void*)> _thread_reset_fn;
  void** _user_thread_contexts;
W
wangguibao 已提交
669

W
wangguibao 已提交
670
  std::vector<ThreadContext<TaskT>*> _thread_contexts;
W
wangguibao 已提交
671

W
wangguibao 已提交
672 673
  size_t _batch_size;
  bool _batch_align;
W
wangguibao 已提交
674

675
  boost::function<void(const void*, void*)> _fn;
W
wangguibao 已提交
676 677
};

H
HexToString 已提交
678 679 680
// TaskExecutorVector is a SingleTon class.
// Each Model corresponding to a TaskExecutor.
// So we need several TaskExecutor when there are more than 1 Model.
H
HexToString 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
template <typename TaskT>
class TaskExecutorVector {
 public:
  static TaskExecutorVector<TaskT>& instance() {
    static TaskExecutorVector<TaskT> singleton;
    return singleton;
  }

  void resize(int size) { _vector_executor.resize(size); }

  TaskExecutor<TaskT>& operator[](int index) {
    if (_vector_executor.size() <= index || index <= -1) {
      LOG(ERROR) << "_vector_executor.size() <= index or <= -1";
      throw "_vector_executor.size() <= index or <= -1";
    }
    return _vector_executor[index];
  }

 private:
  TaskExecutorVector() = default;
  TaskExecutorVector(const TaskExecutorVector<TaskT>& other) = delete;
  TaskExecutorVector& operator=(const TaskExecutorVector<TaskT>& other) =
      delete;
  TaskExecutorVector(TaskExecutorVector<TaskT>&& other) = delete;
  TaskExecutorVector& operator=(TaskExecutorVector<TaskT>&& other) = delete;
  std::vector<TaskExecutor<TaskT>> _vector_executor;
};

H
HexToString 已提交
709 710 711 712 713
// TaskManager is actually a wrapper of Request in bsf.
// TaskManager`s schedule() change Request to be TaskT.
// and divided TaskT into several TaskMeta to put into the TaskExecutor`s
// task_queue.
// wait() is a while loop to receive signal when a whole Task is done.
W
wangguibao 已提交
714
template <typename InItemT, typename OutItemT>
W
wangguibao 已提交
715
class TaskManager {
W
wangguibao 已提交
716 717
 public:
  typedef Task<InItemT, OutItemT> TaskT;
718 719
  typedef typename TaskT::InVectorT InVectorT;
  typedef typename TaskT::OutVectorT OutVectorT;
W
wangguibao 已提交
720

H
HexToString 已提交
721 722
  explicit TaskManager(uint32_t index)  // NOLINT
      : _model_index(index) {}
W
wangguibao 已提交
723

W
wangguibao 已提交
724
  ~TaskManager() { wait(); }
W
wangguibao 已提交
725

726
  bool schedule(const void* in, void* out);  // NOLINT
W
wangguibao 已提交
727
  void wait();
W
wangguibao 已提交
728

W
wangguibao 已提交
729
  inline void clear() { wait(); }
W
wangguibao 已提交
730

W
wangguibao 已提交
731 732
 private:
  TaskHandler<TaskT> _task_owned;
H
HexToString 已提交
733
  uint32_t _model_index;
W
wangguibao 已提交
734
};  // class TaskManager
W
wangguibao 已提交
735 736

class AutoMutex {
W
wangguibao 已提交
737 738 739 740
 public:
  explicit AutoMutex(THREAD_MUTEX_T& mut) : _mut(mut) {
    THREAD_MUTEX_LOCK(&_mut);
  }
W
wangguibao 已提交
741

W
wangguibao 已提交
742
  ~AutoMutex() { THREAD_MUTEX_UNLOCK(&_mut); }
W
wangguibao 已提交
743

W
wangguibao 已提交
744 745
 private:
  THREAD_MUTEX_T& _mut;
W
wangguibao 已提交
746 747
};

W
wangguibao 已提交
748 749
}  // namespace bsf
}  // namespace im
W
wangguibao 已提交
750

751
// #include "core/predictor/framework/bsf-inl-tensor.h"
G
guru4elephant 已提交
752
#include "core/predictor/framework/bsf-inl.h"