conv_pe.hpp 9.9 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* 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 <arm_neon.h>
#include <vector>

20 21 22 23 24 25 26
#include "lite/backends/fpga/KD/pe.hpp"
#include "lite/backends/fpga/KD/pe_params.hpp"
#include "lite/backends/fpga/KD/pes/concat_pe.hpp"
#include "lite/backends/fpga/KD/pes/conv_pe.hpp"
#include "lite/backends/fpga/KD/pes/conv_process.hpp"
#include "lite/backends/fpga/KD/pes/elementwise_add_pe.hpp"
#include "lite/backends/fpga/KD/pes/scale_pe.hpp"
Y
Yan Chunwei 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

namespace paddle {
namespace zynqmp {

class ConvPE : public PE {
 public:
  bool init() {
    Tensor* output = param_.output;
    output->setAligned(true);
    output->setDataLocation(Device);
    return true;
  }

  void apply() {
    split_axis = fill_split_arg(param_);

    if (split_axis == 0 && param_.splitParams().size() > 1) {
      ConcatParam& concat_param = concatPE_.param();
      for (auto conv_param : param_.splitParams()) {
        concat_param.inputs.push_back(&conv_param->output);
      }
      concat_param.output = param_.output;
      concatPE_.init();
      concatPE_.apply();
    }
52 53 54 55 56 57 58 59 60 61

    if (DLEngine::get_instance().isZU3() &&
        param_.input->shape().dimSize() == 4 &&
        param_.input->shape().width() == 1 &&
        param_.input->shape().width() >= 2048) {
      use_cpu_ = true;
    }

    if (param_.filter->shape().width() == 1 &&
        param_.filter->shape().height() == 1) {
62
        // use_cpu_ = true;
63 64 65 66
    }
    if (!use_cpu_) {
      // param_.filter->releaseData();
    }
Y
Yan Chunwei 已提交
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 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


  void cpu_conv_hwc() {

    Tensor* input = param_.input;
    Tensor* output = param_.output;
    input->syncToCPU();

    Tensor float_input;
    Tensor float_output;
    float* image_addr = float_input.mutableData<float>(FP32, input->shape());
    float_input.copyFrom(input);
    float_input.syncToCPU();
    float* out = float_output.mutableData<float>(FP32, output->shape());

    int out_width = output->shape().width();
    int out_channel = output->shape().channel();
    int in_channel = input->shape().channel();

    float* filter_data = param_.filter->data<float>();

    int image_height = input->shape().height();
    int image_width = input->shape().width();
    int image_channels = input->shape().channel();
    int image_pad_h = param_.paddings[0];
    int image_pad_w = param_.paddings[1];
    int kernel_height = param_.filter->shape().height();
    int kernel_width = param_.filter->shape().width();
    int kernel_step_h = param_.strides[0];
    int kernel_step_w = param_.strides[1];
    // int out_channel = param_.strides[1];
    int pooled_height_ = output->shape().height();
    int pooled_width_ = out_width;
    int filter_chw = image_channels * kernel_height * kernel_width;

    float max = 0;

    for (int ph = 0; ph < pooled_height_; ph++) {
      for (int pw = 0; pw < pooled_width_; pw++) {
        int hstart = ph * kernel_step_h - image_pad_h;
        int wstart = pw * kernel_step_w - image_pad_w;
        int hend = std::min(hstart + kernel_height, (int) image_height);
        int wend = std::min(wstart + kernel_width, (int) image_width);
        hstart = std::max(hstart, (int) 0);
        wstart = std::max(wstart, (int) 0);
        for (int oc = 0; oc < out_channel; oc++) {
          float sum = 0.0f;
          const int pool_index = (ph * pooled_width_ + pw) * out_channel + oc;
          for (int c = 0; c < image_channels; c++) {
            for (int h = hstart; h < hend; h++) {
              int hi = 0;
              if (ph == 0) {
                  hi = h - hstart + image_pad_h;
              } else{
                  hi = h - hstart;
              }
              for (int w = wstart; w < wend; w++) {
                int wi = 0;
                if (pw == 0) {
                    wi = w - wstart + image_pad_w;
                }else {
                    wi = w - wstart;
                }
                const int index = (h * image_width + w) * image_channels + c;
//                          int weight_index = (hi * kernel_width + wi) * image_channels + c;//TODO
                int weight_index = oc * filter_chw + kernel_width *
                    kernel_height * c + kernel_width * hi + wi;
                float value = image_addr[index] * filter_data[weight_index];
                sum += value;
              }
            }
          }
            // std::cout << " ============================= pool_index:" << pool_index << " sum:" << sum << std::endl;
          
          if (param_.relu.enabled && sum < 0) {
            sum = -sum;
          }
          if (sum > max) {
            max = sum;
          }
          out[pool_index] = sum;
        }
      }
    }
    float_output.flush();
    output->copyFrom(&float_output);
    output->scale()[0] = max / 127;
    output->scale()[1] = 127 / max;
  }




Y
Yan Chunwei 已提交
161 162 163 164 165 166 167 168 169
  void cpu_compute() {
    Tensor* input = param_.input;
    Tensor* output = param_.output;
    input->syncToCPU();

    Tensor float_input;
    Tensor float_output;
    float* image_addr = float_input.mutableData<float>(FP32, input->shape());
    float_input.copyFrom(input);
170 171 172 173 174 175 176 177 178
    float_input.syncToCPU();

    // float_input.saveToFile("input", true);
    // param_.filter->saveToFile("filter", true);
    // param_.bias()->saveToFile("bias", true);

    // exit(-1);

    // float16* data_out = output->data<float16>();
Y
Yan Chunwei 已提交
179 180
    float* out = float_output.mutableData<float>(FP32, output->shape());

181 182 183
    float* bias_data = param_.bias()->data<float>();

    int out_width = output->shape().width();
Y
Yan Chunwei 已提交
184 185 186 187 188
    int out_channel = output->shape().channel();
    int in_channel = input->shape().channel();

    float* filter_data = param_.filter->data<float>();
    float* mi = new float[in_channel];
189
    float max = 0;
Y
Yan Chunwei 已提交
190

191
    int out_index = 0;
Y
Yan Chunwei 已提交
192 193 194 195 196
    for (int i = 0; i < out_channel; i++) {
      float* image = image_addr;
      float* filter_ptr = filter_data + i * in_channel;
      float* out_ptr = mi;

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
      for (int h = 0; h < output->shape().height(); h++) {
        for (int w = 0; w < output->shape().width(); w++) {

          float sum = 0;

          // #pragma omp parallel for
          for (int j = 0; j < in_channel; j++) {
            int image_index = h * out_width * in_channel + w * in_channel + j;
            float value = image_addr[image_index] * filter_ptr[j];
            sum += value;
  
            // mi[j] = value;
          }

          
          // for (int j = 0; j < in_channel; j++) {
          //   sum += mi[j];
          // }

          sum += bias_data[i];

          if (param_.relu.enabled && sum < 0) {
            sum = 0;
          }
          if (sum > max) {
            max = sum;
          }
          out_index = h * out_width * out_channel + w * out_channel + i;
          out[out_index] = sum;
          // out_index++;
        }
Y
Yan Chunwei 已提交
228 229 230 231 232
      }
    }
    delete[] mi;
    float_output.flush();
    output->copyFrom(&float_output);
233 234 235 236 237 238
    output->scale()[0] = max / 127;
    output->scale()[1] = 127 / max;

    // float_output.saveToFile("out", true);

    // exit(-1);
Y
Yan Chunwei 已提交
239 240 241
  }

  bool dispatch() {
242 243 244 245 246 247 248 249 250 251
    if (use_cpu_) {
      cpu_compute();
      return true;
    }

    inplace_.leaky_relu_enable =
        (param_.relu.leaky_relu_factor != 0) ? true : false;
    inplace_.relu_enable =
        inplace_.leaky_relu_enable ? false : param_.relu.enabled;

Y
Yan Chunwei 已提交
252 253
    inplace_.power_enable = false;
    inplace_.normalize_enable = false;
254
    if (inplace_.relu_enable || inplace_.leaky_relu_enable) {
Y
Yan Chunwei 已提交
255
      config_inplace(inplace_);
256 257 258 259 260 261
      if (inplace_.leaky_relu_enable) {
        activeParamterArgs.type = TYPE_LEAK_RELU;
        activeParamterArgs.leaky_relu_factor =
            fp32_2_fp16(param_.relu.leaky_relu_factor);
        config_activation(activeParamterArgs);
      }
Y
Yan Chunwei 已提交
262 263 264 265 266
    }

    std::vector<BasicConvParam*>& params = param_.splitParams();
    int ret = 0;
    for (auto conv_param : params) {
267
      // conv_param->input.printScale();
Y
Yan Chunwei 已提交
268 269 270
      ret |= compute_fpga_conv_basic(conv_param->args);
    }

271
    if (inplace_.relu_enable || inplace_.leaky_relu_enable) {
Y
Yan Chunwei 已提交
272
      inplace_.relu_enable = false;
273
      inplace_.leaky_relu_enable = false;
Y
Yan Chunwei 已提交
274
      config_inplace(inplace_);
275 276 277 278 279 280

      if (inplace_.leaky_relu_enable) {
        activeParamterArgs.type = TYPE_LEAK_RELU;
        activeParamterArgs.leaky_relu_factor = fp32_2_fp16(0);
        config_activation(activeParamterArgs);
      }
Y
Yan Chunwei 已提交
281 282 283 284
    }

    size_t size = params.size();
    if (split_axis == 0 && ret == 0 && size > 1) {
285
      // std::cout << "concat size:" << size << std::endl;
Y
Yan Chunwei 已提交
286 287 288
      concatPE_.dispatch();
    }
    if (split_axis == 1 && ret == 0 && size > 1) {
289
      // for (int n = 0; n < size - 1; n++) {
Y
Yan Chunwei 已提交
290 291 292 293 294 295
      ElementwiseAddParam& add_param = addPE_.param();
      add_param.inputs = {&params[0]->output, &params[1]->output};
      add_param.output = param_.output;
      addPE_.init();
      addPE_.apply();
      addPE_.dispatch();
296 297 298 299 300 301 302 303 304 305

      // param_.output->printScale();

      // params[0]->input.saveToFile("conv_1.txt");
      // params[1]->input.saveToFile("conv_2.txt");

      // params[0]->output.saveToFile("ew_o1.txt");
      // params[1]->output.saveToFile("ew_o2.txt");
      // std::cout << "\n ================== EW ================== \n";
      // }
Y
Yan Chunwei 已提交
306
    }
307 308 309 310 311

    if (param_.input->shape().channel() == 64 && param_.output->shape().channel() == 128) {
      // exit(-1);
    }

Y
Yan Chunwei 已提交
312 313 314 315 316 317
    return ret == 0;
  }

  ConvParam& param() { return param_; }

 private:
318
  bool use_cpu_ = false;
Y
Yan Chunwei 已提交
319 320 321 322 323
  ConvParam param_;
  ConcatPE concatPE_;
  ElementwiseAddPE addPE_;
  int split_axis = 0;
  InplaceArgs inplace_ = {0};
324
  ActiveParamterArgs activeParamterArgs;
Y
Yan Chunwei 已提交
325 326 327 328
};

}  // namespace zynqmp
}  // namespace paddle