tensor.hpp 12.2 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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

#include <stdio.h>
T
TianXiaogang 已提交
18
#include <unistd.h>
Y
Yan Chunwei 已提交
19 20 21 22 23 24 25 26 27
#include <algorithm>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

28 29 30 31
#include "lite/backends/fpga/KD/dl_engine.hpp"
#include "lite/backends/fpga/KD/float16.hpp"
#include "lite/backends/fpga/KD/llapi/zynqmp_api.h"
#include "lite/backends/fpga/KD/shape.hpp"
Y
Yan Chunwei 已提交
32 33 34 35 36 37 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 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

namespace paddle {
namespace zynqmp {

enum DataType : int {
  FP32 = 0,
  FP16 = 1,
  INT8 = 2,
  INT32 = 3,
};

enum DataSyncStatus : int {
  Synched = 0,
  Device = 1,
  CPU = 2,
};

typedef uint16_t float16;

inline int CellSize(DataType type) {
  switch (type) {
    case FP32:
      return sizeof(float);
    case FP16:
      return sizeof(float16);
    case INT32:
      return sizeof(int32_t);
    case INT8:
      return sizeof(int8_t);
    default:
      return 0;
  }
  return 0;
}

class PlaceHolder {
 public:
  PlaceHolder() {}
  explicit PlaceHolder(size_t size) {
    size_ = size;
    data_ = fpga_malloc(size_);
  }

  void* data() { return data_; }
  void set_data(const void* ptr) { data_ = const_cast<void*>(ptr); }

  size_t memorySize() { return size_; }
  void set_size(size_t new_size) { size_ = new_size; }

  ~PlaceHolder() { fpga_free(data_); }

  float scale_[2];

 private:
  void* data_ = nullptr;
  size_t size_ = 0;
};

class Tensor {
 public:
  Tensor() { DLEngine::get_instance(); }

  int id() { return id_; }

  template <typename Dtype>
  Dtype* data() {
    if (placeHolder_ == nullptr) {
      return nullptr;
    }
    void* ptr = reinterpret_cast<char*>(this->placeHolder_->data()) +
                offset * CellSize(dataType_);
    return reinterpret_cast<Dtype*>(ptr);
  }

C
chonwhite 已提交
106 107 108 109 110
  void releaseData() {
    released = true;
    placeHolder_.reset();
  }

Y
Yan Chunwei 已提交
111 112
  template <typename Dtype>
  Dtype* mutableData(DataType dataType, const Shape& shape) {
C
chonwhite 已提交
113
    this->shape_.reset(new Shape(shape));
Y
Yan Chunwei 已提交
114 115 116 117 118 119
    this->dataType_ = dataType;
    return mutableData<Dtype>();
  }

  template <typename Dtype>
  Dtype* mutableData() {
T
TianXiaogang 已提交
120 121
    size_t memorySize =
        shape_->memorySize(CellSize(dataType_)) * mem_scale_factor_;
Y
Yan Chunwei 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    if (placeHolder_ != nullptr) {
      if (memorySize > placeHolder_->memorySize()) {
        placeHolder_.reset(new PlaceHolder(memorySize));
      }
    } else {
      placeHolder_.reset(new PlaceHolder(memorySize));
    }
    return data<Dtype>();
  }

  size_t memorySize() {
    if (placeHolder_ == nullptr) {
      return 0;
    }
    return placeHolder_->memorySize();
  }

  void setDataType(DataType dataType) { this->dataType_ = dataType; }

  DataType dataType() { return this->dataType_; }

C
chonwhite 已提交
143
  Shape& shape() { return *(shape_.get()); }
Y
Yan Chunwei 已提交
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

  bool aligned() { return this->aligned_; }

  void setAligned(bool aligned) { this->aligned_ = aligned; }

  float* scale() { return placeHolder_->scale_; }

  void alignImage(Tensor* dst = nullptr, bool copy = false) {
    if (shape_->shouldAlign()) {
      int cell_size = CellSize(this->dataType_);
      char* dst_data = nullptr;
      size_t mem_size = shape_->memorySize(cell_size);
      if (dst == nullptr) {
        dst_data = reinterpret_cast<char*>(fpga_malloc(mem_size));
      } else {
        dst_data = dst->data<char>();
      }
      int wc = shape_->width() * shape_->channel();
      int wc_aligned = align_image(wc);
      int remainder = wc_aligned - wc;

      char* src_start = data<char>();
      char* dst_start = dst_data;
      for (int n = 0; n < shape_->num(); n++) {
        for (int h = 0; h < shape_->height(); h++) {
          memcpy(dst_start, src_start, wc * cell_size);
          memset(dst_start + wc * cell_size, 0, remainder * cell_size);
          src_start += wc * cell_size;
          dst_start += wc_aligned * cell_size;
        }
      }
      if (dst == nullptr) {
        memcpy(data<void>(), dst_data, mem_size);
        flush();
        fpga_free(dst_data);
      } else {
        dst->flush();
      }
    } else {
      if (copy) {
        dst->copyFrom(this);
      } else {
        // TODO(chonwhite) share data.
      }
    }
    if (dst != nullptr) {
      dst->copyScaleFrom(this);
    }
  }

  inline void copyScaleFrom(Tensor* src) {
    placeHolder_->scale_[0] = src->placeHolder_->scale_[0];
    placeHolder_->scale_[1] = src->placeHolder_->scale_[1];
  }

  void unalignImage(Tensor* dst = nullptr, bool copy = false) {
    Tensor* target = dst == nullptr ? this : dst;
    if (!target->aligned_) {
      if (copy && dst != nullptr) {
        dst->copyFrom(this);
      }
      return;
    }
    target->syncToCPU();
    if (shape_->shouldAlign()) {
      int cell_size = CellSize(this->dataType_);
      char* dst_data = nullptr;
      size_t mem_size = shape_->memorySize(cell_size);
      if (dst == nullptr) {
        dst_data = reinterpret_cast<char*>(fpga_malloc(mem_size));
      } else {
        dst_data = dst->data<char>();
      }
      int wc = shape_->width() * shape_->channel();
      int wc_aligned = align_image(wc);

      char* src_start = data<char>();
      char* dst_start = dst_data;
      for (int n = 0; n < shape_->num(); n++) {
        for (int h = 0; h < shape_->height(); h++) {
          memcpy(dst_start, src_start, wc * cell_size);
          src_start += wc_aligned * cell_size;
          dst_start += wc * cell_size;
        }
      }
      if (dst == nullptr) {
        memcpy(data<void>(), dst_data, mem_size);
        flush();
        fpga_free(dst_data);
      } else {
        dst->flush();
      }
    } else {
      if (copy) {
        dst->copyFrom(this);
      } else {
        // TODO(chonwhite) share data.
      }
    }
  }

T
TianXiaogang 已提交
245 246 247 248
  void setMemScale(float scale_factor) {
    this->mem_scale_factor_ = scale_factor;
  }

Y
Yan Chunwei 已提交
249 250 251 252 253 254 255 256
  void shareDataWith(Tensor* src) { shareDataWith(src, src->shape()); }

  void shareDataWith(Tensor* src, const Shape& shape, int offset = 0) {
    this->placeHolder_ = src->placeHolder_;
    this->dataType_ = src->dataType_;
    this->aligned_ = src->aligned_;
    this->dateLocation_ = src->dateLocation_;
    this->offset = offset;
C
chonwhite 已提交
257
    shape_.reset(new Shape(shape));
Y
Yan Chunwei 已提交
258 259 260 261 262 263 264 265 266 267 268
  }

  void copyFrom(Tensor* src) {
    if (src->dataType_ == dataType_) {
      src->syncToCPU();
      memcpy(data<void>(), src->data<void>(), memorySize());
      copyScaleFrom(src);
      flush();
      return;
    }
    BypassArgs args;
C
chonwhite 已提交
269
    args.input_data_type = src->dataType_ == FP32 ? DATA_TYPE_FP32 : DATA_TYPE_FP16;
Y
Yan Chunwei 已提交
270 271 272
    args.output_data_type = dataType_ == FP32 ? DATA_TYPE_FP32 : DATA_TYPE_FP16;
    args.input_layout_type = LAYOUT_HWC;
    args.output_layout_type = LAYOUT_HWC;
C
chonwhite 已提交
273 274 275 276 277 278 279 280 281
    args.image = {
      .address = src->data<void>(),
      .scale_address = src->scale(),
      .channels = (uint32_t)src->shape().numel(),
      .width = 1,
      .height = 1,
      .pad_width = 0U,
      .pad_height = 0U
    };
T
TianXiaogang 已提交
282 283

    ImageOutputArgs output = {
C
chonwhite 已提交
284 285
      .address = data<void>(),
      .scale_address = scale(),
Y
Yan Chunwei 已提交
286
    };
C
chonwhite 已提交
287

T
TianXiaogang 已提交
288
    args.output = output;
Y
Yan Chunwei 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301
    size_t aligned_remainder = src->shape().numel() % 16;
    if (aligned_remainder > 0) {
      size_t dtype_size =
          src->dataType_ == FP32 ? sizeof(float) : sizeof(float16);
      void* dst = src->data<char>() + src->shape().numel() * dtype_size;
      memset(dst, 0, aligned_remainder * dtype_size);
      fpga_flush(dst, aligned_remainder * dtype_size);
    }
    src->syncToDevice();
    perform_bypass(args);
    this->invalidate();
  }

T
TianXiaogang 已提交
302
  void flush() {
C
chonwhite 已提交
303 304 305
    if (released) {
      return;
    }
306
    size_t memorySize = placeHolder_->memorySize();
T
TianXiaogang 已提交
307 308
    fpga_flush(placeHolder_->data(), memorySize);
  }
Y
Yan Chunwei 已提交
309 310

  void invalidate() {
311
    size_t memorySize = placeHolder_->memorySize();
T
TianXiaogang 已提交
312
    fpga_invalidate(placeHolder_->data(), memorySize);
Y
Yan Chunwei 已提交
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
  }

  void sync() {
    switch (synchedStatus_) {
      case CPU:
        flush();
        break;
      case Device:
        invalidate();
        break;
      default:
        break;
    }
  }

  void syncToCPU() {
    if (dateLocation_ == Device) {
      invalidate();
    }
  }

  void syncToDevice() {
    if (dateLocation_ == CPU) {
      flush();
    }
  }

  DataSyncStatus synchedStatus() { return synchedStatus_; }

  void setSynchedStatus(DataSyncStatus status) { synchedStatus_ = status; }

  void setDataLocation(DataSyncStatus location) { dateLocation_ = location; }

  void print() {}

  void printScale() {
    if (placeHolder_ == nullptr) {
      return;
    }
  }

T
TianXiaogang 已提交
354 355
  void printScale(std::string type) { printScale(); }

Y
Yan Chunwei 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
  std::string dimsFileName() {
    return std::to_string(shape_->num()) + "_" +
           std::to_string(shape_->channel()) + "_" +
           std::to_string(shape_->height()) + "_" +
           std::to_string(shape_->width()) + ".txt";
  }

  void saveToFile() { std::string path = dimsFileName(); }

  void saveToFile(std::string prefix, bool with_shape) {
    std::string path = prefix;
    if (with_shape) {
      path = path + "_" + dimsFileName();
    } else {
      path = path + ".txt";
    }
    saveToFile(path);
  }

  void saveToFile(std::string path) {
    syncToCPU();
T
TianXiaogang 已提交
377
    invalidate();
Y
Yan Chunwei 已提交
378 379 380 381 382 383 384 385
    std::ofstream ofs;
    static int counter = 0;
    std::string npath = std::to_string(counter) + "_" + path;
    counter++;
    save_file_with_name(npath);
  }

  void save_file_with_name(std::string path) {
C
chonwhite 已提交
386 387 388 389
    // std::cout << "saving file: " << path << std::endl;
    void* add = (void*)this;
    // printf("tensor @: %p  data: %p \n", (void *)add, (void*)data<void>());  
    // return;
Y
Yan Chunwei 已提交
390 391
    std::ofstream ofs;
    ofs.open(path);
392
    ofs << scale()[0] << " / " << scale()[1] << std::endl;
T
TianXiaogang 已提交
393

Y
Yan Chunwei 已提交
394 395 396 397
    for (int i = 0; i < shape_->numel(); i++) {
      float value = 0;
      if (dataType_ == FP32) {
        value = data<float>()[i];
C
chonwhite 已提交
398 399
      }
      if (dataType_ == FP16) {
Y
Yan Chunwei 已提交
400
        value = half_to_float(data<float16>()[i]);
C
chonwhite 已提交
401 402 403
      }

      if (dataType_ == INT8) {
T
TianXiaogang 已提交
404
        value = data<int8_t>()[i];
Y
Yan Chunwei 已提交
405
      }
C
chonwhite 已提交
406 407 408
      if (dataType_ == INT32) {
        value = data<int32_t>()[i];
      }
C
chonwhite 已提交
409 410 411 412 413
      
      if (i < 10) {
        std::cout << value << ",";
      }

Y
Yan Chunwei 已提交
414
      ofs << value << std::endl;
C
chonwhite 已提交
415

Y
Yan Chunwei 已提交
416
    }
C
chonwhite 已提交
417
    usleep(30000);
Y
Yan Chunwei 已提交
418 419 420 421 422 423 424 425 426 427 428 429
    ofs.close();
  }

  void readFromFile(std::string path) {
    std::ifstream file_stream;
    file_stream.open(path);
    if (!file_stream) {
      return;
    }
    int num = shape_->numel();
    invalidate();
    float max = 0.0f;
T
TianXiaogang 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    if (dataType_ == FP16) {
      float16* data = mutableData<float16>();
      for (int i = 0; i < num; ++i) {
        float value = 0;
        file_stream >> value;
        max = std::max(std::abs(value), max);
        data[i] = float_to_half(value);
      }
    } else {
      float* data = mutableData<float>();
      for (int i = 0; i < num; ++i) {
        float value = 0;
        file_stream >> value;
        max = std::max(std::abs(value), max);
        data[i] = value;
      }
Y
Yan Chunwei 已提交
446 447 448 449 450 451
    }
    flush();
    placeHolder_->scale_[0] = max / 127.0f;
    placeHolder_->scale_[1] = 127.0f / max;
  }

T
TianXiaogang 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
  friend std::ostream& operator<<(std::ostream& os, Tensor& tensor) {
    os << "tensor:"
       << "\n";
    os << "dims: {";
    for (int i = 0; i < tensor.shape().dimSize(); ++i) {
      os << tensor.shape()[i] << " ";
    }
    os << "}\n";
    for (int i = 0; i < tensor.shape().numel(); i++) {
      float value = 0;
      if (tensor.dataType() == FP32) {
        value = tensor.data<float>()[i];
      } else {
        value = half_to_float(tensor.data<float16>()[i]);
      }
      os << value << " ";
C
chonwhite 已提交
468

T
TianXiaogang 已提交
469 470 471 472 473
    }
    os << "\n";
    return os;
  }

Y
Yan Chunwei 已提交
474
 private:
C
chonwhite 已提交
475
  bool released = false;
Y
Yan Chunwei 已提交
476
  int offset = 0;
T
TianXiaogang 已提交
477
  float mem_scale_factor_ = 1.0f;
Y
Yan Chunwei 已提交
478
  std::shared_ptr<PlaceHolder> placeHolder_;
C
chonwhite 已提交
479
  std::shared_ptr<Shape> shape_;
Y
Yan Chunwei 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
  DataType dataType_ = FP32;
  bool aligned_ = false;
  DataSyncStatus synchedStatus_ = Synched;
  DataSyncStatus dateLocation_ = Device;

  static int generateID() {
    static int sID = 0;
    int id = sID++;
    return id;
  }

  int id_ = generateID();
};

}  // namespace zynqmp
}  // namespace paddle