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

#include <gtest/gtest.h>
#include <random>
17
#include "lite/backends/opencl/target_wrapper.h"
Y
Yan Chunwei 已提交
18 19
#include "lite/core/op_registry.h"
#include "lite/core/tensor.h"
20 21 22
#include "lite/kernels/opencl/test_helper.h"

#define FP16_MAX_DIFF (1e-2)
Y
Yan Chunwei 已提交
23 24 25 26 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

namespace paddle {
namespace lite {

#define A(i, j) a[i * lda + j]
#define B(i, j) b[i * ldb + j]
#define C(i, j) c[i * ldc + j]

template <typename T>
void gemm_bias(const T* a,
               const int M,
               const int K,
               const T* b,
               const int K_,
               const int N,
               T* biases,
               T* c) {
  EXPECT_TRUE(K_ == K && M > 0 && N > 0 && K > 0);
  EXPECT_TRUE(a && b && c);
  const int lda = K;
  const int ldb = N;
  const int ldc = N;
  for (int m = 0; m < M; ++m) {
    for (int n = 0; n < N; ++n) {
      C(m, n) = 0.0f;
      for (int k = 0; k < K; ++k) {
        C(m, n) += A(m, k) * B(k, n);
      }
    }
  }
  if (biases) {
    for (int m = 0; m < M; ++m) {
      for (int n = 0; n < N; ++n) {
        C(m, n) += biases[n];
      }
    }
  }
}

void PrintData(std::string name, float* a, const int rows, const int cols) {
  std::cout << "==== " << name << " ====" << std::endl;
  for (int r = 0; r < rows; ++r) {
    for (int c = 0; c < cols; ++c) {
      std::cout << " " << a[r * cols + c];
    }
    std::cout << std::endl;
  }
}

// #define PRINT_RESULT
73
// #define LOOP_TEST
Y
Yan Chunwei 已提交
74 75 76 77 78
TEST(fc, compute) {
  std::unique_ptr<KernelContext> context(new KernelContext);
  context->As<OpenCLContext>().InitOnce();

#ifdef LOOP_TEST
79 80 81
  for (int m = 1; m < 4; m += 1) {
    for (int k = 1; k < 4; k += 1) {
      for (int n = 1; n < 4; n += 1) {
Y
Yan Chunwei 已提交
82 83 84 85 86 87
#else
#if 0
  const int m = 1;
  const int k = 1024;
  const int n = 1000;
#else
88 89 90 91 92 93 94
  // m,k,n:2,3,1
  //       1,2,3
  //       2,1,3
  //       1,2,3
  const int m = 1;
  const int k = 2;
  const int n = 3;
Y
Yan Chunwei 已提交
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
#endif
#endif
        LOG(INFO) << "m=" << m << " n=" << n << " k=" << k;

        auto kernels = KernelRegistry::Global().Create(
            "fc", TARGET(kOpenCL), PRECISION(kFloat), DATALAYOUT(kNCHW));
        ASSERT_FALSE(kernels.empty());
        auto kernel = std::move(kernels.front());

        lite::Tensor x, w, bias, out, out_ref;
        operators::FcParam param;
        param.input = &x;
        param.w = &w;
        param.bias = &bias;
        param.output = &out;
        param.in_num_col_dims = 1;

        kernel->SetParam(param);
        std::unique_ptr<KernelContext> fc_context(new KernelContext);
        context->As<OpenCLContext>().CopySharedTo(
            &(fc_context->As<OpenCLContext>()));
        kernel->SetContext(std::move(fc_context));

        const DDim x_dim = DDim(std::vector<DDim::value_type>{m, k});
        const DDim w_dim = DDim(std::vector<DDim::value_type>{k, n});
        const DDim bias_dim = DDim(std::vector<DDim::value_type>{n});
        const DDim out_dim = DDim(std::vector<DDim::value_type>{m, n});

        x.Resize(x_dim);
        w.Resize(w_dim);
        bias.Resize(bias_dim);
        out.Resize(out_dim);
        out_ref.Resize(out_dim);

        auto* x_data = x.mutable_data<float, cl::Buffer>(TARGET(kOpenCL));
        auto* w_data = w.mutable_data<float, cl::Buffer>(TARGET(kOpenCL));
        auto* bias_data = bias.mutable_data<float, cl::Buffer>(TARGET(kOpenCL));
132
        auto* out_data = out.mutable_data<float, cl::Buffer>(TARGET(kOpenCL));
Y
Yan Chunwei 已提交
133 134 135

        std::default_random_engine engine;
        std::uniform_real_distribution<float> dist(-5, 5);
136 137 138 139 140 141 142 143 144 145 146 147

        std::vector<float> x_source(x_dim.production());
        std::vector<float> w_source(w_dim.production());
        std::vector<float> bias_source(bias_dim.production());

        size_t x_size = x_dim.production() * sizeof(float);
        size_t w_size = w_dim.production() * sizeof(float);
        size_t bias_size = bias_dim.production() * sizeof(float);
        size_t out_size = out_dim.production() * sizeof(float);

        for (size_t i = 0; i < x_dim.production(); ++i) {
          x_source[i] = static_cast<int>(dist(engine));
Y
Yan Chunwei 已提交
148
        }
149 150
        for (size_t i = 0; i < w_dim.production(); ++i) {
          w_source[i] = static_cast<int>(dist(engine));
Y
Yan Chunwei 已提交
151
        }
152 153
        for (size_t i = 0; i < bias_dim.production(); ++i) {
          bias_source[i] = 10;  // static_cast<int>(dist(engine));
Y
Yan Chunwei 已提交
154 155
        }

156 157 158 159 160 161 162
        TargetWrapperCL::MemcpySync(
            x_data, x_source.data(), x_size, IoDirection::HtoD);
        TargetWrapperCL::MemcpySync(
            w_data, w_source.data(), w_size, IoDirection::HtoD);
        TargetWrapperCL::MemcpySync(
            bias_data, bias_source.data(), bias_size, IoDirection::HtoD);

Y
Yan Chunwei 已提交
163 164
        // run opencl kernel
        kernel->Launch();
165
        CLRuntime::Global()->command_queue().finish();
X
xiebaiyuan 已提交
166

167 168 169 170 171 172 173 174
#if 0  // NOTE(ysh329): note event
        auto* wait_list = context->As<OpenCLContext>().cl_wait_list();
        auto* out_ptr = param.output->data<float, cl::Buffer>();
        auto it = wait_list->find(out_ptr);
        if (it != wait_list->end()) {
          VLOG(4) << "--- Find the sync event for the target cl tensor. ---";
          auto& event = *(it->second);
          event.wait();
X
xiebaiyuan 已提交
175
        CLRuntime::Global()->command_queue().finish();
Y
Yan Chunwei 已提交
176 177 178 179 180 181
          double start_nanos =
              event.getProfilingInfo<CL_PROFILING_COMMAND_START>();
          double stop_nanos =
              event.getProfilingInfo<CL_PROFILING_COMMAND_END>();
          double elapsed_micros = (stop_nanos - start_nanos) / 1000.0;
          LOG(INFO) << "Kernel Run Cost Time: " << elapsed_micros << " us.";
182 183 184 185
        } else {
          LOG(FATAL)
              << "Could not find the sync event for the target cl tensor.";
        }
186
#endif
Y
Yan Chunwei 已提交
187

188 189 190 191
        std::vector<float> out_data_from_gpu(out_dim.production());
        TargetWrapperCL::MemcpySync(
            out_data_from_gpu.data(), out_data, bias_size, IoDirection::DtoH);

Y
Yan Chunwei 已提交
192 193
        // run cpu ref
        auto* out_ref_data = out_ref.mutable_data<float>(TARGET(kARM));
194 195 196 197 198 199 200 201
        gemm_bias<float>(x_source.data(),
                         m,
                         k,
                         w_source.data(),
                         k,
                         n,
                         bias_source.data(),
                         out_ref_data);
Y
Yan Chunwei 已提交
202
#ifdef PRINT_RESULT
203 204 205
        PrintData("x", static_cast<float*>(x_source.data()), m, k);
        PrintData("w", static_cast<float*>(w_source.data()), k, n);
        PrintData("bias", static_cast<float*>(bias_source.data()), 1, n);
Y
Yan Chunwei 已提交
206
        PrintData("out_ref_data", static_cast<float*>(out_ref_data), m, n);
207 208
        PrintData(
            "gpu_out", static_cast<float*>(out_data_from_gpu.data()), m, n);
Y
Yan Chunwei 已提交
209 210
#endif

211 212 213 214 215
        for (int eidx = 0; eidx < out_dim.production(); ++eidx) {
          auto abs_diff = COMPUTE_ABS_DIFF(out_ref_data[eidx],
                                           out_data_from_gpu.data()[eidx]);
          auto relative_diff = COMPUTE_RELATIVE_DIFF(
              out_ref_data[eidx], out_data_from_gpu.data()[eidx]);
216 217 218
          EXPECT_EQ(
              (relative_diff <= FP16_MAX_DIFF) || (abs_diff <= FP16_MAX_DIFF),
              true);
219
          if ((relative_diff > FP16_MAX_DIFF) && (abs_diff > FP16_MAX_DIFF)) {
220
            LOG(FATAL) << "error idx:" << eidx << ", out_ref_data[" << eidx
221 222 223 224 225 226 227
                       << "]:" << out_ref_data[eidx]
                       << ", out_data_from_gpu.data()[" << eidx
                       << "]:" << out_data_from_gpu.data()[eidx]
                       << " abs_diff:" << abs_diff
                       << " relative_diff:" << relative_diff
                       << " FP16_MAX_DIFF:" << FP16_MAX_DIFF;
          }
Y
Yan Chunwei 已提交
228 229 230 231 232 233 234 235 236 237 238 239
        }

#ifdef LOOP_TEST
      }  // n
    }    // k
  }      // m
#endif
}

}  // namespace lite
}  // namespace paddle

240
USE_LITE_KERNEL(fc, kOpenCL, kFloat, kNCHW, def);