bsf-inl-tensor.h 10.6 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 48
#include <comlog/comlog.h>
#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 已提交
49
    butil::atomic<size_t> index;
W
wangguibao 已提交
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

    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 已提交
75
        index.store(0, butil::memory_order_relaxed); 
W
wangguibao 已提交
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 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 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 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 262 263 264 265 266 267 268 269 270 271
    }
};

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) {
                CFATAL_LOG("Out tensor is empty, when aligned");
                return false;
            }

            if (out.size() != in.size()) {
                CFATAL_LOG("In/Out tensor size not eq: %ld!=%ld",
                        out.size(), in.size());
                return false;
            }

            for (size_t fi = 0, shape0 = 0; fi < out.count(); ++fi) {
                if (!out[fi].valid()) {
                    CFATAL_LOG("Out[%ld] tensor not valid", fi);
                    return false;
                }

                if (out.size() != out[fi].shape0()) {
                    CFATAL_LOG("Shape0 not consistency, %ld!=%ld, %ld",
                            out.size(), out[fi].shape0(), fi);
                    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) {
                CFATAL_LOG("Malloc failed, size: %ld", 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) {
                    CFATAL_LOG("Invalid bytes: %ld + %ld >= %ld",
                            data_byte, acc_byte, tensor_byte);
                    return ;
                }

                const Tensor& tensor = (*(tm.task->get(is_in)))[fi];
                memcpy(data_buf + data_byte, 
                        tensor.data.data() + tm.begin * ins_byte, 
                        acc_byte);
                data_byte += acc_byte;
            }

            if (data_byte != tensor_byte) {
                CFATAL_LOG("Invalid tensor byte: %ld != %ld",
                        data_byte, tensor_byte); 
                return ;
            }

            batch_tensor.data = DataBuf(data_buf, tensor_byte);
            if (is_in) {
                _batch_in.push_back(batch_tensor);
            } else {
                _batch_out.push_back(batch_tensor);
            }
        }

W
wangguibao 已提交
272
        LOG(INFO) << "merge input(" << is_in << ") samples: " 
W
wangguibao 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 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
            << batch_size << " from " << _tasks.size() << " pvs";
    }

    void notify_tasks() {
        if (_batch_out.size() != _batch_in.size()) {
            CFATAL_LOG("batch size not consistency: %ld != %ld",
                    _batch_out.size(), _batch_in.size());
            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());
                    memcpy(ptr + offset_dst, 
                            _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(
                            _batch_out[fi].data.data() + offset_src, add_byte);
                }
            }
        }
        
        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 已提交
330
                butil::return_object(task);
W
wangguibao 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
            }
        }
    }

    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 _rem_size;
    size_t _batch_size;
    bool _batch_align;
};

} // namespace bsf
} // namespace im