ut_helper.h 7.8 KB
Newer Older
F
flame 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 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

17
#include <gtest/gtest.h>
F
flame 已提交
18
#include <map>
F
flame 已提交
19 20 21 22 23 24
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

25
#include "paddle/fluid/framework/block_desc.h"
F
flame 已提交
26 27 28
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/tensor_util.h"
29
#include "paddle/fluid/inference/anakin/convert/op_converter.h"
F
flame 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include "paddle/fluid/inference/anakin/engine.h"
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/utils/singleton.h"
#include "paddle/fluid/platform/enforce.h"

using anakin::Precision;
using anakin::saber::X86;

namespace paddle {
namespace inference {
namespace anakin {

/*
 * Get a random float value between [low, high]
 */
float random(float low, float high) {
  static std::random_device rd;
  static std::mt19937 mt(rd());
  std::uniform_real_distribution<double> dist(low, high);
  return dist(mt);
}

52 53
void RandomizeTensor(framework::LoDTensor* tensor,
                     const platform::Place& place) {
F
flame 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
  auto dims = tensor->dims();
  size_t num_elements = analysis::AccuDims(dims, dims.size());
  PADDLE_ENFORCE_GT(num_elements, 0);

  platform::CPUPlace cpu_place;
  framework::LoDTensor temp_tensor;
  temp_tensor.Resize(dims);
  auto* temp_data = temp_tensor.mutable_data<float>(cpu_place);

  for (size_t i = 0; i < num_elements; i++) {
    *(temp_data + i) = random(0., 1.);
  }

  TensorCopySync(temp_tensor, place, tensor);
}

/*
 * Help to validate the correctness between Fluid Op and the corresponding
 * anakin
 * layer.
 */
75
template <typename TargetT, ::anakin::Precision PrecisionT>
F
flame 已提交
76
class AnakinConvertValidation {
77
  using AnakinNvEngineT = AnakinEngine<TargetT, PrecisionT>;
F
flame 已提交
78 79 80 81 82

 public:
  AnakinConvertValidation() = delete;

  AnakinConvertValidation(const std::unordered_set<std::string>& parameters,
83 84 85 86 87
                          framework::Scope* scope,
                          const platform::DeviceContext& ctx,
                          bool use_gpu = true)
      : parameters_(parameters), scope_(scope), ctx_(ctx), use_gpu_(use_gpu) {
    engine_.reset(new AnakinEngine<TargetT, PrecisionT>(true));
F
flame 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  }

  // Declare a Variable as input with random initialization.
  void DeclInputVar(const std::string& name,
                    const std::vector<int> tensor_dims) {
    DeclVar(name, tensor_dims);
    // should decalre anakin input here.
  }

  void DeclParamVar(const std::string& name, const std::vector<int> dim_vec) {
    DeclVar(name, dim_vec);
  }

  void DeclOutputVar(const std::string& name, const std::vector<int> dim_vec) {
    DeclVar(name, dim_vec);
    // should declare anakin output here.
  }

  void DeclVar(const std::string& name, const std::vector<int> dim_vec) {
N
nhzlx 已提交
107
    auto* x = scope_->Var(name);
F
flame 已提交
108 109
    auto* x_tensor = x->GetMutable<framework::LoDTensor>();
    x_tensor->Resize(framework::make_ddim(dim_vec));
110
    RandomizeTensor(x_tensor, ctx_.GetPlace());
111 112 113 114 115 116 117 118 119 120 121

    std::vector<int64_t> dim_vec_int64;
    for (auto& ele : dim_vec) {
      dim_vec_int64.push_back(static_cast<int64_t>(ele));
    }

    // Add var_desc to block_desc
    auto* block_desc = program_desc_.MutableBlock(framework::kRootBlockIndex);

    auto* var_desc = block_desc->Var(name);
    var_desc->SetShape(dim_vec_int64);
F
flame 已提交
122 123 124 125 126 127 128
  }

  void SetOp(const framework::proto::OpDesc& desc) {
    op_ = framework::OpRegistry::CreateOp(desc);
    op_desc_.reset(new framework::OpDesc(desc, nullptr));
    // should init anakin engine here.

129
    auto& block_desc = program_desc_.Block(framework::kRootBlockIndex);
130
    Singleton<AnakinOpConverter<TargetT, PrecisionT>>::Global().ConvertOp(
131 132
        desc, block_desc, parameters_, *scope_, engine_.get(),
        true /*test_mode*/);
F
flame 已提交
133
    engine_->Freeze();
134 135

    std::map<std::string, std::vector<int>> temp_max_input_shape;
F
flame 已提交
136 137
    for (const auto& input : op_desc_->InputArgumentNames()) {
      if (parameters_.count(input)) continue;
N
nhzlx 已提交
138
      auto& t = inference::analysis::GetFromScope<framework::LoDTensor>(*scope_,
F
flame 已提交
139 140
                                                                        input);
      auto t_shape = framework::vectorize2int(t.dims());
141 142 143
      while (t_shape.size() < 4) {
        t_shape.push_back(1);
      }
F
flame 已提交
144
      engine_->SetInputShape(input, t_shape);
145
      temp_max_input_shape[input] = t_shape;
F
flame 已提交
146
    }
147
    engine_->SetMaxInputShape(temp_max_input_shape);
F
flame 已提交
148
    engine_->Optimize();
149
    engine_->InitNet();
F
flame 已提交
150 151 152 153 154 155 156 157
  }

  // We use the set 'neglected_output' here, because some Ops like batch norm,
  // the outputs specified in the op des are only used during training,
  // so we should neglect those output during inference.
  void Execute(int batch_size,
               std::unordered_set<std::string> neglected_output = {}) {
    // Execute Fluid Op
158
    op_->Run(*scope_, ctx_.GetPlace());
F
flame 已提交
159

F
flame 已提交
160 161 162
    std::map<std::string, framework::LoDTensor*> inputs;
    for (const auto& input : op_desc_->InputArgumentNames()) {
      if (parameters_.count(input)) continue;
N
nhzlx 已提交
163
      auto* var = scope_->FindVar(input);
F
flame 已提交
164 165 166 167 168 169
      auto tensor = var->GetMutable<framework::LoDTensor>();
      inputs.insert({input, tensor});
    }

    std::map<std::string, framework::LoDTensor*> outputs;
    std::vector<std::vector<float>> fluid_outputs;
F
flame 已提交
170 171 172
    for (const auto& output : op_desc_->OutputArgumentNames()) {
      if (neglected_output.count(output)) continue;
      std::vector<float> fluid_out;
N
nhzlx 已提交
173
      auto* var = scope_->FindVar(output);
F
flame 已提交
174
      auto tensor = var->GetMutable<framework::LoDTensor>();
175
      framework::TensorToVector(*tensor, ctx_, &fluid_out);
F
flame 已提交
176
      fluid_outputs.push_back(fluid_out);
F
flame 已提交
177

F
flame 已提交
178 179 180
      outputs.insert({output, tensor});
    }

181 182 183 184 185 186 187 188
    if (!use_gpu_) {
      engine_->Execute(inputs, outputs);
    } else {
      cudaStream_t stream;
      PADDLE_ENFORCE_EQ(cudaStreamCreate(&stream), 0);
      engine_->Execute(inputs, outputs, stream);
    }

F
flame 已提交
189 190 191 192
    int i_output = 0;
    for (const auto& output : op_desc_->OutputArgumentNames()) {
      if (neglected_output.count(output)) continue;
      std::vector<float> anakin_out;
N
nhzlx 已提交
193
      auto* var = scope_->FindVar(output);
F
flame 已提交
194
      auto tensor = var->GetMutable<framework::LoDTensor>();
195
      framework::TensorToVector(*tensor, ctx_, &anakin_out);
F
flame 已提交
196 197 198 199

      size_t anakin_out_size = anakin_out.size();
      auto fluid_out = fluid_outputs[i_output++];
      for (size_t i = 0; i < anakin_out_size; i++) {
200
        EXPECT_LT(std::abs(fluid_out[i] - anakin_out[i]), 1e-3);
F
flame 已提交
201 202 203 204 205 206 207 208
      }
    }
  }

 private:
  std::unique_ptr<AnakinNvEngineT> engine_{nullptr};
  std::unique_ptr<framework::OperatorBase> op_;
  std::unique_ptr<framework::OpDesc> op_desc_;
209
  framework::ProgramDesc program_desc_;
F
flame 已提交
210
  const std::unordered_set<std::string>& parameters_;
N
nhzlx 已提交
211
  framework::Scope* scope_;
212 213
  const platform::DeviceContext& ctx_;
  bool use_gpu_{true};
F
flame 已提交
214 215
};

216 217 218 219 220 221 222 223 224
template class AnakinConvertValidation<::anakin::saber::NV,
                                       ::anakin::Precision::FP32>;
template class AnakinConvertValidation<::anakin::saber::X86,
                                       ::anakin::Precision::FP32>;

template class AnakinConvertValidation<::anakin::saber::NV,
                                       ::anakin::Precision::INT8>;
template class AnakinConvertValidation<::anakin::saber::X86,
                                       ::anakin::Precision::INT8>;
F
flame 已提交
225 226 227
}  // namespace anakin
}  // namespace inference
}  // namespace paddle