test_helper.h 9.4 KB
Newer Older
1 2 3 4 5 6 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
// Copyright (c) 2021 CINN 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 <glog/logging.h>

#include <iomanip>
#include <random>

#include "paddle/cinn/frontend/decomposer/use_decomposer.h"
#include "paddle/cinn/frontend/decomposer_registry.h"
#include "paddle/cinn/frontend/net_builder.h"
#include "paddle/cinn/frontend/optimize.h"
#include "paddle/cinn/frontend/pass/use_program_pass.h"
#include "paddle/cinn/frontend/program_pass.h"
#include "paddle/cinn/hlir/framework/graph.h"
#include "paddle/cinn/hlir/framework/graph_compiler.h"
#include "paddle/cinn/hlir/framework/pass.h"
#include "paddle/cinn/hlir/framework/tensor.h"
#include "paddle/cinn/hlir/op/use_ops.h"
33
#include "paddle/cinn/hlir/pass/use_general_pass.h"
34 35 36 37
#include "paddle/cinn/hlir/pass/use_pass.h"

namespace cinn::frontend {

38 39
using CPUKernelFunc = std::function<void(const std::vector<size_t>& lengths,
                                         const std::vector<void*>& ptrs)>;
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

template <typename T, typename Alloc = std::allocator<T>>
std::ostream& operator<<(std::ostream& os, const std::vector<T, Alloc>& vec) {
  os << "{";
  bool is_first = true;
  for (auto e : vec) {
    if (is_first) {
      is_first = false;
    } else {
      os << ", ";
    }
    os << e;
  }
  os << "}\n";
  return os;
}

template <typename T>
58 59 60 61 62
void InitRandomVector(std::vector<T>* vec,
                      size_t numel,
                      T low = static_cast<T>(0),
                      T high = static_cast<T>(1),
                      float precision = 1e-5) {
63 64 65 66 67 68
  std::random_device seed;
  std::default_random_engine engine(seed());
  std::uniform_real_distribution<double> dist(low, high);

  vec->resize(numel);
  for (size_t i = 0; i < numel; ++i) {
69 70
    T value = static_cast<T>(dist(engine));
    int coeff = static_cast<int>(value / precision);
71 72 73 74 75
    vec->at(i) = precision * static_cast<T>(coeff);
  }
}

template <>
76 77
void InitRandomVector<int>(
    std::vector<int>* vec, size_t numel, int low, int high, float precision);
78 79

template <typename T>
80 81 82
void CopyFromVector(const std::vector<T>& vec,
                    hlir::framework::Tensor tensor,
                    Target target) {
83 84 85 86 87 88 89 90 91
  auto* data = tensor->mutable_data<T>(target);

  size_t numel = tensor->shape().numel();
  CHECK_EQ(vec.size(), numel);

  if (target == common::DefaultNVGPUTarget()) {
#ifdef CINN_WITH_CUDA
    cudaMemcpy(data, vec.data(), numel * sizeof(T), cudaMemcpyHostToDevice);
#else
92 93
    LOG(FATAL)
        << "NVGPU Target only support on flag CINN_WITH_CUDA ON! Please check.";
94 95 96 97 98 99 100
#endif
  } else {
    std::copy(vec.begin(), vec.end(), data);
  }
}

template <>
101 102 103
void CopyFromVector<bool>(const std::vector<bool>& vec,
                          hlir::framework::Tensor tensor,
                          Target target);
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

template <typename T>
void CopyToVector(const hlir::framework::Tensor tensor, std::vector<T>* vec) {
  auto* data = tensor->data<T>();

  size_t numel = tensor->shape().numel();
  vec->resize(numel);

#ifdef CINN_WITH_CUDA
  cudaMemcpy(vec->data(), data, numel * sizeof(T), cudaMemcpyDeviceToHost);
#else
  for (size_t i = 0; i < numel; ++i) {
    vec->at(i) = data[i];
  }
#endif
}

template <>
122 123
void CopyToVector<bool>(const hlir::framework::Tensor tensor,
                        std::vector<bool>* vec);
124 125

template <typename T>
126 127 128 129
void CheckOutput(const std::vector<T>& actual,
                 const std::vector<T>& expect,
                 float atol = 1e-8,
                 float rtol = 1e-5) {
130 131
  CHECK_EQ(actual.size(), expect.size());

132 133 134
  auto allclose = [](T a, T e, float atol, float rtol) {
    return abs(a - e) <= (atol + rtol * abs(e));
  };
135 136

  float max_diff = 0.0f;
137 138
  int offset = 0;
  int num_diffs = 0;
139 140 141 142 143 144 145 146

  size_t numel = actual.size();
  for (size_t i = 0; i < numel; ++i) {
    if (!allclose(actual[i], expect[i], atol, rtol)) {
      float absolute_diff = abs((actual[i] - expect[i]));
      float relative_diff = abs(absolute_diff / expect[i]);
      if (relative_diff > max_diff) {
        max_diff = relative_diff;
147
        offset = i;
148 149
      }
      num_diffs += 1;
150 151 152 153
      VLOG(4) << "- i=" << i << ", " << std::setprecision(8) << actual[i]
              << " (actual) vs " << std::setprecision(8) << expect[i]
              << " (expect), relative_diff=" << relative_diff
              << ", absolute_diff=" << absolute_diff;
154 155
    }
  }
156 157 158 159 160 161
  LOG(INFO) << "- Total " << num_diffs
            << " different results, offset=" << offset << ", " << actual[offset]
            << " (actual) vs " << expect[offset]
            << " (expect), maximum_relative_diff=" << max_diff
            << " (absolute_diff=" << abs((actual[offset] - expect[offset]))
            << ")";
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
  CHECK_EQ(num_diffs, 0);
}

template <typename T>
void ComputeReferenceCpu(const std::vector<std::vector<T>>& input_vecs,
                         const std::vector<std::vector<T>>& output_vecs,
                         std::vector<std::vector<T>>* output_refs,
                         CPUKernelFunc cpu_kernel_func) {
  output_refs->resize(output_vecs.size());
  for (size_t i = 0; i < output_vecs.size(); ++i) {
    output_refs->at(i).resize(output_vecs[i].size());
  }

  // Prepare the arguments for reference.
  // For different operations, the needed parameters maybe different.
  size_t n = input_vecs[0].size();
  std::vector<size_t> lengths;
  lengths.push_back(n);

  std::vector<void*> ptrs(input_vecs.size() + output_refs->size());
  for (size_t i = 0; i < input_vecs.size(); ++i) {
    ptrs[i] = const_cast<void*>(static_cast<const void*>(input_vecs[i].data()));
  }
  for (size_t i = 0; i < output_refs->size(); ++i) {
    ptrs[input_vecs.size() + i] = output_refs->at(i).data();
  }
  cpu_kernel_func(lengths, ptrs);
}

void RunDecomposer(Program* prog,
                   const Target& target,
193
                   const std::vector<std::string>& passes = {"Decomposer"},
194 195 196
                   const std::vector<std::string>& fetch_ids = {});

template <typename T>
197
void RunAndCheckShape(NetBuilder* builder,
198 199 200
                      const std::vector<std::string>& input_names,
                      const std::vector<std::string>& output_names,
                      const std::vector<std::vector<int>>& output_shapes,
201
                      std::vector<std::vector<T>>* input_vecs = nullptr,
202
                      std::vector<std::vector<T>>* output_vecs = nullptr,
203 204 205
                      T low = 0,
                      T high = 1,
                      const std::vector<std::string>& passes = {"Decomposer"}) {
206
  auto prog = builder->Build();
207 208 209 210 211 212 213 214 215
  Target target = common::DefaultTarget();
  RunDecomposer(&prog, target, passes, output_names);
  auto graph = std::make_shared<hlir::framework::Graph>(prog, target);
  hlir::framework::ApplyPasses(graph.get(), DefaultOpFusionPasses());
  auto scope = BuildScope(target, graph);
  hlir::framework::GraphCompiler gc(target, scope, graph);

  auto runtime_program = gc.Build();
  std::vector<std::vector<T>> input_vecs_internal;
216 217
  std::vector<std::vector<T>>* input_vecs_ptr =
      input_vecs ? input_vecs : &input_vecs_internal;
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
  for (size_t i = 0; i < input_names.size(); ++i) {
    scope->Var<hlir::framework::Tensor>(input_names[i]);
    auto tensor = scope->GetTensor(input_names[i]);

    std::vector<T> vec;
    InitRandomVector<T>(&vec, tensor->shape().numel(), low, high);
    CopyFromVector<T>(vec, tensor, target);
    input_vecs_ptr->push_back(vec);
  }
  runtime_program->Execute();

  for (size_t i = 0; i < output_names.size(); ++i) {
    auto tensor = scope->GetTensor(output_names[i]);
    CHECK_EQ(tensor->shape().data() == output_shapes[i], true)
        << "The " << i << "-th shape is expected to be " << output_shapes[i];
    if (output_vecs) {
      std::vector<T> vec;
      CopyToVector<T>(tensor, &vec);
      output_vecs->push_back(vec);
    }
  }
}

template <typename T>
242
void RunAndCheck(NetBuilder* builder,
243 244 245 246
                 const std::vector<std::string>& input_names,
                 const std::vector<std::string>& output_names,
                 const std::vector<std::vector<int>>& output_shapes,
                 CPUKernelFunc cpu_kernel_func,
247 248 249 250
                 T low = 0,
                 T high = 1,
                 float atol = 1e-8,
                 float rtol = 1e-5,
251 252 253
                 const std::vector<std::string>& passes = {"Decomposer"}) {
  std::vector<std::vector<T>> input_vecs;
  std::vector<std::vector<T>> output_vecs;
254 255 256 257 258 259 260 261 262
  RunAndCheckShape<T>(builder,
                      input_names,
                      output_names,
                      output_shapes,
                      &input_vecs,
                      &output_vecs,
                      low,
                      high,
                      passes);
263 264

  std::vector<std::vector<T>> output_refs;
265 266
  ComputeReferenceCpu<T>(
      input_vecs, output_vecs, &output_refs, cpu_kernel_func);
267 268

  for (size_t i = 0; i < output_vecs.size(); ++i) {
269 270
    LOG(INFO) << "Check the " << i << "-th output, name=" << output_names[i]
              << ", shape=" << output_shapes[i];
271 272 273 274 275
    CheckOutput<T>(output_vecs[i], output_refs[i], atol, rtol);
  }
}

}  // namespace cinn::frontend