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 33 34 35 36
// 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"
#include "paddle/cinn/hlir/pass/use_pass.h"

namespace cinn::frontend {

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

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>
57 58 59 60 61
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) {
62 63 64 65 66 67
  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) {
68 69
    T value = static_cast<T>(dist(engine));
    int coeff = static_cast<int>(value / precision);
70 71 72 73 74
    vec->at(i) = precision * static_cast<T>(coeff);
  }
}

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

template <typename T>
79 80 81
void CopyFromVector(const std::vector<T>& vec,
                    hlir::framework::Tensor tensor,
                    Target target) {
82 83 84 85 86 87 88 89 90
  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
91 92
    LOG(FATAL)
        << "NVGPU Target only support on flag CINN_WITH_CUDA ON! Please check.";
93 94 95 96 97 98 99
#endif
  } else {
    std::copy(vec.begin(), vec.end(), data);
  }
}

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

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 <>
121 122
void CopyToVector<bool>(const hlir::framework::Tensor tensor,
                        std::vector<bool>* vec);
123 124

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

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

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

  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;
146
        offset = i;
147 148
      }
      num_diffs += 1;
149 150 151 152
      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;
153 154
    }
  }
155 156 157 158 159 160
  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]))
            << ")";
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
  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,
192
                   const std::vector<std::string>& passes = {"Decomposer"},
193 194 195 196 197 198 199
                   const std::vector<std::string>& fetch_ids = {});

template <typename T>
void RunAndCheckShape(NetBuilder& builder,
                      const std::vector<std::string>& input_names,
                      const std::vector<std::string>& output_names,
                      const std::vector<std::vector<int>>& output_shapes,
200
                      std::vector<std::vector<T>>* input_vecs = nullptr,
201
                      std::vector<std::vector<T>>* output_vecs = nullptr,
202 203 204 205
                      T low = 0,
                      T high = 1,
                      const std::vector<std::string>& passes = {"Decomposer"}) {
  auto prog = builder.Build();
206 207 208 209 210 211 212 213 214
  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;
215 216
  std::vector<std::vector<T>>* input_vecs_ptr =
      input_vecs ? input_vecs : &input_vecs_internal;
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
  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>
void RunAndCheck(NetBuilder& builder,
                 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,
246 247 248 249
                 T low = 0,
                 T high = 1,
                 float atol = 1e-8,
                 float rtol = 1e-5,
250 251 252
                 const std::vector<std::string>& passes = {"Decomposer"}) {
  std::vector<std::vector<T>> input_vecs;
  std::vector<std::vector<T>> output_vecs;
253 254 255 256 257 258 259 260 261
  RunAndCheckShape<T>(builder,
                      input_names,
                      output_names,
                      output_shapes,
                      &input_vecs,
                      &output_vecs,
                      low,
                      high,
                      passes);
262 263

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

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

}  // namespace cinn::frontend