bsf-inl-tensor.h 10.5 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5
#pragma once

#include <errno.h>
#include <vector>
#include <deque>
W
wangguibao 已提交
6
#include <butil/atomicops.h>
W
wangguibao 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include "common/inner_common.h"
#include "framework/infer_data.h"
#include "framework/memory.h"

#include <boost/function.hpp>

namespace im {
namespace bsf {

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;
    };

    int read_fd;
    int write_fd;

    pid_t owner_tid;

    const InArrayT* in;
    OutArrayT* out;

    size_t rem;
    size_t size;

W
wangguibao 已提交
48
    butil::atomic<size_t> index;
W
wangguibao 已提交
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

    const BatchTensor* get(bool is_in) const {
        if (is_in) {
            return in;
        } else {
            return out;
        }
    }

    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;
W
wangguibao 已提交
74
        index.store(0, butil::memory_order_relaxed); 
W
wangguibao 已提交
75 76 77 78 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
    }
};

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;

    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, bool align) {
        if (align) {
            if (out.count() <= 0 || out.size() <= 0) {
114
                LOG(ERROR) << "Out tensor is empty, when aligned";
W
wangguibao 已提交
115 116 117 118
                return false;
            }

            if (out.size() != in.size()) {
119
                LOG(ERROR) << "In/Out tensor size not eq: " << out.size() << "!=" << in.size();
W
wangguibao 已提交
120 121 122 123 124
                return false;
            }

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

                if (out.size() != out[fi].shape0()) {
130
                    LOG(ERROR) << "Shape0 not consistency, " << out.size() << "!=" << out[fi].shape0() << ", " << fi;
W
wangguibao 已提交
131 132 133 134 135 136 137 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 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 222 223 224 225 226 227 228 229 230 231 232 233
                    return false;
                }
            }
        }

        return true;
    }

    size_t append_task(TaskT* task) {
        size_t add = std::min(task->rem, _rem_size);
        if (!_batch_align) {
            add = task->rem; 
        }
        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 ;
        }

        if (_tasks.size() == 1 && !_batch_align) {
            TaskMetaT& tm = _tasks[0];
            _batch_in = *(tm.task->in);
            return ;
        }

        merge_tensor(true);
    }

    void merge_output() {
        if (_batch_align) {
            if (_tasks.size() <= 0 || _tasks[0].task->out->count() <= 0) {
                return ;
            }
        } 

        if (_tasks.size() <= 0 || _tasks[0].task->out->count() <= 0) {
            return ;
        }

        TaskMetaT& tm = _tasks[0];
        if (_tasks.size() == 1 && !_batch_align) {
            _batch_out = *(tm.task->out);
            return ;
        }

        if (tm.task->out->size() <= 0) {
            // shape is empty
            _batch_out = *(tm.task->out);
            return ;
        }

        if ((*tm.task->out)[0].data.data() == 0 
                || (*tm.task->out)[0].data.size() == 0) {
            _batch_out = *(tm.task->out);
            return ;
        }

        merge_tensor(false);
    }

    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;
        }

        // 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) {
234
                LOG(ERROR) << "Malloc failed, size: " << tensor_byte;
W
wangguibao 已提交
235 236 237 238 239 240 241 242
                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) {
243
                    LOG(ERROR) << "Invalid bytes: " << data_byte << " + " << acc_byte << " >= " << tensor_byte;
W
wangguibao 已提交
244 245 246 247
                    return ;
                }

                const Tensor& tensor = (*(tm.task->get(is_in)))[fi];
W
wangguibao 已提交
248 249
                memcpy((char *)data_buf + data_byte, 
                        (char *)(tensor.data.data()) + tm.begin * ins_byte, 
W
wangguibao 已提交
250 251 252 253 254
                        acc_byte);
                data_byte += acc_byte;
            }

            if (data_byte != tensor_byte) {
255
                LOG(ERROR) << "Invalid tensor byte: " << data_byte << " != " << tensor_byte; 
W
wangguibao 已提交
256 257 258
                return ;
            }

W
wangguibao 已提交
259
            batch_tensor.data = DataBuf((char *)data_buf, tensor_byte);
W
wangguibao 已提交
260 261 262 263 264 265 266
            if (is_in) {
                _batch_in.push_back(batch_tensor);
            } else {
                _batch_out.push_back(batch_tensor);
            }
        }

W
wangguibao 已提交
267
        LOG(INFO) << "merge input(" << is_in << ") samples: " 
W
wangguibao 已提交
268 269 270 271 272
            << batch_size << " from " << _tasks.size() << " pvs";
    }

    void notify_tasks() {
        if (_batch_out.size() != _batch_in.size()) {
273
            LOG(ERROR) << "batch size not consistency: " << _batch_out.size() << " != " << _batch_in.size();
W
wangguibao 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
            return ;
        }

        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());
W
wangguibao 已提交
296 297
                    memcpy((char *)ptr + offset_dst, 
                            (char *)(_batch_out[fi].data.data()) + offset_src, add_byte);
W
wangguibao 已提交
298 299 300 301 302 303 304 305 306
                } 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(
W
wangguibao 已提交
307
                            (char *)(_batch_out[fi].data.data()) + offset_src, add_byte);
W
wangguibao 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
                }
            }
        }
        
        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;

            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 已提交
324
                butil::return_object(task);
W
wangguibao 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
            }
        }
    }

    const typename TaskT::InArrayT& in() const {
        return _batch_in;
    }

    typename TaskT::OutArrayT& out() {
        return _batch_out;
    }

    size_t task_size() {
        return _tasks.size();
    }

private:
    std::vector<TaskMetaT> _tasks;
    InArrayT _batch_in;
    OutArrayT _batch_out;
    size_t _batch_size;
W
wangguibao 已提交
346
    size_t _rem_size;
W
wangguibao 已提交
347 348 349 350 351
    bool _batch_align;
};

} // namespace bsf
} // namespace im