bsf-inl-tensor.h 10.1 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

W
wangguibao 已提交
15 16
#pragma once

W
wangguibao 已提交
17
#include <butil/atomicops.h>
W
wangguibao 已提交
18
#include <errno.h>
W
wangguibao 已提交
19
#include <algorithm>
W
wangguibao 已提交
20
#include <deque>
W
wangguibao 已提交
21
#include <vector>
W
wangguibao 已提交
22 23 24
#include "predictor/common/inner_common.h"
#include "predictor/framework/infer_data.h"
#include "predictor/framework/memory.h"
W
wangguibao 已提交
25 26 27 28 29 30

#include <boost/function.hpp>

namespace im {
namespace bsf {

W
wangguibao 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
template <>
struct Task<baidu::paddle_serving::predictor::Tensor,
            baidu::paddle_serving::predictor::Tensor> {
  typedef Task<baidu::paddle_serving::predictor::Tensor,
               baidu::paddle_serving::predictor::Tensor>
      TaskT;
  typedef baidu::paddle_serving::predictor::Tensor Tensor;
  typedef baidu::paddle_serving::predictor::Tensor InType;
  typedef baidu::paddle_serving::predictor::Tensor OutType;
  typedef baidu::paddle_serving::predictor::BatchTensor BatchTensor;
  typedef baidu::paddle_serving::predictor::BatchTensor InArrayT;
  typedef baidu::paddle_serving::predictor::BatchTensor OutArrayT;

  struct Segment {
    Segment(void* p, size_t b, size_t s) : ptr(p), begin(b), size(s) {}
    void* ptr;
    size_t begin;
    size_t size;
  };
W
wangguibao 已提交
50

W
wangguibao 已提交
51 52
  int read_fd;
  int write_fd;
W
wangguibao 已提交
53

W
wangguibao 已提交
54
  pid_t owner_tid;
W
wangguibao 已提交
55

W
wangguibao 已提交
56 57
  const InArrayT* in;
  OutArrayT* out;
W
wangguibao 已提交
58

W
wangguibao 已提交
59 60
  size_t rem;
  size_t size;
W
wangguibao 已提交
61

W
wangguibao 已提交
62
  butil::atomic<size_t> index;
W
wangguibao 已提交
63

W
wangguibao 已提交
64 65 66 67 68 69 70
  const BatchTensor* get(bool is_in) const {
    if (is_in) {
      return in;
    } else {
      return out;
    }
  }
W
wangguibao 已提交
71

W
wangguibao 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  BatchTensor* get(bool is_in) {
    if (is_in) {
      return const_cast<BatchTensor*>(in);
    } else {
      return out;
    }
  }

  Task() {
    read_fd = -1;
    write_fd = -1;
    owner_tid = -1;
    in = NULL;
    out = NULL;
    rem = -1;
    size = -1;
    index.store(0, butil::memory_order_relaxed);
  }
};
W
wangguibao 已提交
91

W
wangguibao 已提交
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 136 137 138 139 140 141 142
template <>
class BatchTasks<Task<baidu::paddle_serving::predictor::Tensor,
                      baidu::paddle_serving::predictor::Tensor>> {
 public:
  typedef baidu::paddle_serving::predictor::Tensor Tensor;
  typedef baidu::paddle_serving::predictor::Tensor InType;
  typedef baidu::paddle_serving::predictor::Tensor OutType;
  typedef baidu::paddle_serving::predictor::DataBuf DataBuf;
  typedef baidu::paddle_serving::predictor::MempoolWrapper MempoolWrapper;

  typedef Task<baidu::paddle_serving::predictor::Tensor,
               baidu::paddle_serving::predictor::Tensor>
      TaskT;
  typedef TaskMeta<TaskT> TaskMetaT;
  typedef TaskT::InArrayT InArrayT;
  typedef TaskT::OutArrayT OutArrayT;

  explicit BatchTasks(size_t batch_size, bool batch_align = false)
      : _batch_size(batch_size),
        _rem_size(batch_size),
        _batch_align(batch_align) {
    _batch_in.clear();
    _batch_out.clear();
    _tasks.clear();
  }

  ~BatchTasks() {
    _batch_in.clear();
    _batch_out.clear();
    _tasks.clear();
  }

  static bool check_valid(const InArrayT& in,
                          OutArrayT& out,  // NOLINT
                          bool align) {    // NOLINT
    if (align) {
      if (out.count() <= 0 || out.size() <= 0) {
        LOG(ERROR) << "Out tensor is empty, when aligned";
        return false;
      }

      if (out.size() != in.size()) {
        LOG(ERROR) << "In/Out tensor size not eq: " << out.size()
                   << "!=" << in.size();
        return false;
      }

      for (size_t fi = 0, shape0 = 0; fi < out.count(); ++fi) {
        if (!out[fi].valid()) {
          LOG(ERROR) << "Out[" << fi << "] tensor not valid";
          return false;
W
wangguibao 已提交
143 144
        }

W
wangguibao 已提交
145 146 147 148
        if (out.size() != out[fi].shape0()) {
          LOG(ERROR) << "Shape0 not consistency, " << out.size()
                     << "!=" << out[fi].shape0() << ", " << fi;
          return false;
W
wangguibao 已提交
149
        }
W
wangguibao 已提交
150
      }
W
wangguibao 已提交
151 152
    }

W
wangguibao 已提交
153 154
    return true;
  }
W
wangguibao 已提交
155

W
wangguibao 已提交
156 157 158 159
  size_t append_task(TaskT* task) {
    size_t add = std::min(task->rem, _rem_size);
    if (!_batch_align) {
      add = task->rem;
W
wangguibao 已提交
160
    }
W
wangguibao 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    TaskMetaT tm(task, task->in->size() - task->rem, add);
    _tasks.push_back(tm);

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

  void merge_tasks() {
    merge_input();
    merge_output();
  }

  void merge_input() {
    if (_tasks.size() <= 0 || _tasks[0].task->in->count() <= 0) {
      return;
W
wangguibao 已提交
177 178
    }

W
wangguibao 已提交
179 180 181 182
    if (_tasks.size() == 1 && !_batch_align) {
      TaskMetaT& tm = _tasks[0];
      _batch_in = *(tm.task->in);
      return;
W
wangguibao 已提交
183 184
    }

W
wangguibao 已提交
185 186
    merge_tensor(true);
  }
W
wangguibao 已提交
187

W
wangguibao 已提交
188 189 190 191 192
  void merge_output() {
    if (_batch_align) {
      if (_tasks.size() <= 0 || _tasks[0].task->out->count() <= 0) {
        return;
      }
W
wangguibao 已提交
193 194
    }

W
wangguibao 已提交
195 196
    if (_tasks.size() <= 0 || _tasks[0].task->out->count() <= 0) {
      return;
W
wangguibao 已提交
197 198
    }

W
wangguibao 已提交
199 200 201 202 203
    TaskMetaT& tm = _tasks[0];
    if (_tasks.size() == 1 && !_batch_align) {
      _batch_out = *(tm.task->out);
      return;
    }
W
wangguibao 已提交
204

W
wangguibao 已提交
205 206 207 208 209
    if (tm.task->out->size() <= 0) {
      // shape is empty
      _batch_out = *(tm.task->out);
      return;
    }
W
wangguibao 已提交
210

W
wangguibao 已提交
211 212 213 214
    if ((*tm.task->out)[0].data.data() == 0 ||
        (*tm.task->out)[0].data.size() == 0) {
      _batch_out = *(tm.task->out);
      return;
W
wangguibao 已提交
215 216
    }

W
wangguibao 已提交
217 218
    merge_tensor(false);
  }
W
wangguibao 已提交
219

W
wangguibao 已提交
220 221 222 223 224 225 226 227
  void merge_tensor(bool is_in) {
    // accumulate batch size from fetched tasks
    size_t batch_size = 0;
    for (size_t ti = 0; ti < _tasks.size(); ++ti) {
      TaskMetaT& tm = _tasks[ti];
      size_t add = tm.end - tm.begin;
      batch_size += add;
    }
W
wangguibao 已提交
228

W
wangguibao 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    // merge all instanses in each tensor data
    size_t tensor_count = _tasks[0].task->get(is_in)->count();
    for (size_t fi = 0; fi < tensor_count; ++fi) {
      const Tensor& head = (*(_tasks[0].task->get(is_in)))[fi];
      Tensor batch_tensor;
      batch_tensor.name = head.name;
      batch_tensor.type = head.type;
      batch_tensor.shape.push_back(batch_size);

      size_t ins_ele_count = 1;
      for (size_t si = 1; si < head.shape.size(); ++si) {
        batch_tensor.shape.push_back(head.shape[si]);
        ins_ele_count *= head.shape[si];
      }

      size_t tensor_ele_count = ins_ele_count * batch_size;
      size_t ins_byte = ins_ele_count * head.ele_byte();

      size_t tensor_byte = tensor_ele_count * head.ele_byte();
      void* data_buf = MempoolWrapper::instance().malloc(tensor_byte);
      if (!data_buf) {
        LOG(ERROR) << "Malloc failed, size: " << tensor_byte;
        return;
      }

      size_t data_byte = 0;
      for (size_t ti = 0; ti < _tasks.size(); ++ti) {
        TaskMetaT& tm = _tasks[ti];
        size_t acc_byte = ins_byte * (tm.end - tm.begin);
        if (data_byte + acc_byte > tensor_byte) {
          LOG(ERROR) << "Invalid bytes: " << data_byte << " + " << acc_byte
                     << " >= " << tensor_byte;
          return;
W
wangguibao 已提交
262 263
        }

W
wangguibao 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        const Tensor& tensor = (*(tm.task->get(is_in)))[fi];
        memcpy(
            reinterpret_cast<char*>(data_buf) + data_byte,
            reinterpret_cast<char*>(tensor.data.data()) + tm.begin * ins_byte,
            acc_byte);
        data_byte += acc_byte;
      }

      if (data_byte != tensor_byte) {
        LOG(ERROR) << "Invalid tensor byte: " << data_byte
                   << " != " << tensor_byte;
        return;
      }

      batch_tensor.data =
          DataBuf(reinterpret_cast<char*>(data_buf), tensor_byte);
      if (is_in) {
        _batch_in.push_back(batch_tensor);
      } else {
        _batch_out.push_back(batch_tensor);
      }
    }
W
wangguibao 已提交
286

W
wangguibao 已提交
287 288 289
    LOG(INFO) << "merge input(" << is_in << ") samples: " << batch_size
              << " from " << _tasks.size() << " pvs";
  }
W
wangguibao 已提交
290

W
wangguibao 已提交
291 292 293 294 295
  void notify_tasks() {
    if (_batch_out.size() != _batch_in.size()) {
      LOG(ERROR) << "batch size not consistency: " << _batch_out.size()
                 << " != " << _batch_in.size();
      return;
W
wangguibao 已提交
296 297
    }

W
wangguibao 已提交
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
    size_t tensor_count = _batch_out.count();
    size_t batch_size = _batch_out.size();
    for (size_t fi = 0; fi < tensor_count; ++fi) {
      const Tensor& tensor = _batch_out[fi];
      size_t ins_byte = tensor.ele_byte();
      for (size_t si = 1; si < tensor.shape.size(); ++si) {
        ins_byte *= tensor.shape[si];
      }

      for (size_t ti = 0, bi = 0, add = 0; ti < _tasks.size();
           ++ti, bi += add) {
        OutArrayT* dst = _tasks[ti].task->out;
        add = _tasks[ti].end - _tasks[ti].begin;
        size_t offset_src = ins_byte * bi;
        size_t add_byte = add * ins_byte;

        if (_batch_align) {  // merge all batchs
          size_t offset_dst = ins_byte * _tasks[ti].begin;
          void* ptr = const_cast<void*>((*dst)[fi].data.data());
          memcpy(
              reinterpret_cast<char*>(ptr) + offset_dst,
              reinterpret_cast<char*>(_batch_out[fi].data.data()) + offset_src,
              add_byte);
        } else {  // overwrite
          if (dst->count() <= 0) {
            dst->push_back(_batch_out[fi]);
          } else {
            (*dst)[fi] = _batch_out[fi];
          }

          (*dst)[fi].shape[0] = add;
          (*dst)[fi].data = DataBuf(
              reinterpret_cast<char*>(_batch_out[fi].data.data()) + offset_src,
              add_byte);
W
wangguibao 已提交
332
        }
W
wangguibao 已提交
333
      }
W
wangguibao 已提交
334 335
    }

W
wangguibao 已提交
336 337 338 339 340
    for (size_t ti = 0; ti < _tasks.size(); ++ti) {
      TaskT* task = _tasks[ti].task;
      size_t begin = _tasks[ti].begin;
      size_t end = _tasks[ti].end;
      size_t add = end - begin;
W
wangguibao 已提交
341

W
wangguibao 已提交
342 343 344 345
      size_t index = task->index.fetch_add(add);
      if ((index + add) >= task->in->size()) {
        char c = 0;
        while (write(task->write_fd, &c, 1) != 1 && errno == EINTR) {
W
wangguibao 已提交
346
        }
W
wangguibao 已提交
347 348
        butil::return_object(task);
      }
W
wangguibao 已提交
349
    }
W
wangguibao 已提交
350
  }
W
wangguibao 已提交
351

W
wangguibao 已提交
352
  const typename TaskT::InArrayT& in() const { return _batch_in; }
W
wangguibao 已提交
353

W
wangguibao 已提交
354
  typename TaskT::OutArrayT& out() { return _batch_out; }
W
wangguibao 已提交
355

W
wangguibao 已提交
356
  size_t task_size() { return _tasks.size(); }
W
wangguibao 已提交
357

W
wangguibao 已提交
358 359 360 361 362 363 364
 private:
  std::vector<TaskMetaT> _tasks;
  InArrayT _batch_in;
  OutArrayT _batch_out;
  size_t _batch_size;
  size_t _rem_size;
  bool _batch_align;
W
wangguibao 已提交
365 366
};

W
wangguibao 已提交
367 368
}  // namespace bsf
}  // namespace im