mvnorm.cc 12.7 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
// Copyright 2018 The MACE 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 "mace/ops/opencl/image/mvnorm.h"

#include <memory>
#include <set>
#include <string>
#include <vector>

namespace mace {
namespace ops {
namespace opencl {
namespace image {

namespace {

MaceStatus BuildMVNKernel(OpenCLRuntime *runtime, cl::Kernel *kernel,
                          const char *kernel_name,
                          std::set<std::string> *built_options,
L
luxuhui 已提交
32 33 34 35
                          MeanType mean_type_) {
  std::stringstream macro_name;
  macro_name << "-Dmvnorm=" << kernel_name;
  built_options->emplace(macro_name.str());
36 37
  built_options->emplace("-DDATA_TYPE=" + DtToCLDt(DT_FLOAT));
  built_options->emplace("-DCMD_DATA_TYPE=" + DtToCLCMDDt(DT_FLOAT));
L
luxuhui 已提交
38
  if (mean_type_ == MeanType::ACROSS_CHANNELS) {
39
    built_options->emplace("-DACROSS_CHANNELS");
L
luxuhui 已提交
40 41
  } else if (mean_type_ == MeanType::GROUP_CHANNELS) {
    built_options->emplace("-DGROUP_CHANNELS");
42 43 44 45 46 47 48 49 50
  }
  MACE_RETURN_IF_ERROR(runtime->BuildKernel("mvnorm", kernel_name,
                                            *built_options, kernel));
  return MaceStatus::MACE_SUCCESS;
}

}  // namespace

MVNormKernel::MVNormKernel(bool normalize_variance,
L
luxuhui 已提交
51
                           MeanType mean_type, float eps, int group_num)
52
    : normalize_variance_(normalize_variance),
L
luxuhui 已提交
53 54 55
      mean_type_(mean_type),
      eps_(eps),
      group_num_(group_num) {}
56

L
luxuhui 已提交
57 58
MaceStatus MVNormKernel::Compute(OpContext *context,
                                 const Tensor *input, Tensor *output) {
59 60 61 62 63
  const auto batch = input->dim(0);
  const auto height = input->dim(1);
  const auto width = input->dim(2);
  const auto channels = input->dim(3);

L
luxuhui 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
  index_t group_blocks = 0;
  if (mean_type_ == MeanType::GROUP_CHANNELS) {
    MACE_CHECK(group_num_ > 0, "group num should > 0");
    const index_t group = channels / group_num_;
    MACE_CHECK(group > 0 && group % 4 == 0, group, " can not be divided by 4");
    group_blocks = group / 4;
  }

  return DoCompute(context, input, output, batch,
                   height, width, channels, group_blocks);
}

MaceStatus MVNormKernel::DoCompute(
    OpContext *context, const Tensor *input, Tensor *output,
    const index_t batch, const index_t height, const index_t width,
    const index_t channels, const index_t group_blocks) {
80 81 82 83 84 85
  const index_t channel_blocks = RoundUpDiv4(channels);
  const uint32_t gws[3] = {static_cast<uint32_t>(channel_blocks),
                           static_cast<uint32_t>(width),
                           static_cast<uint32_t>(height * batch)};
  auto runtime = context->device()->gpu_runtime()->opencl_runtime();

L
luxuhui 已提交
86 87
  const std::vector<index_t > mean_shape = {batch, 1, 1, channels};
  std::vector<size_t> mean_image_shape;
88
  OpenCLUtil::CalImage2DShape(mean_shape, OpenCLBufferType::IN_OUT_CHANNEL,
L
luxuhui 已提交
89 90 91 92 93 94 95 96
                              &mean_image_shape);
  ScratchImageManager *scratch_manager =
      context->device()->gpu_runtime()->scratch_image_manager();
  ScratchImage scratch_mean_image(scratch_manager);
  auto mace_mean_image = scratch_mean_image.Scratch(
      context->device()->allocator(), mean_image_shape, input->dtype());
  cl::Image *mean_image = static_cast<cl::Image *>(mace_mean_image->buffer());

97
  if (normalize_variance_) {
L
luxuhui 已提交
98 99 100 101 102 103 104 105 106 107
    ScratchImage scratch_mean_image_sqr(scratch_manager);
    auto mace_mean_image_sqr = scratch_mean_image_sqr.Scratch(
        context->device()->allocator(), mean_image_shape, input->dtype());
    cl::Image *mean_image_sqr =
        static_cast<cl::Image *>(mace_mean_image_sqr->buffer());
    // compute the EX
    MACE_RETURN_IF_ERROR(ExecuteMeanValueKernel(
        context, runtime, batch, height, width, channel_blocks, group_blocks,
        input->opencl_image(), mean_image));
    // compute (X - EX)^2 to output
108
    MACE_RETURN_IF_ERROR(ExecuteVarianceNormStep1Kernel(
L
luxuhui 已提交
109 110 111 112 113 114
        context, runtime, gws, height, group_blocks, input->opencl_image(),
        mean_image, output->opencl_image()));
    // compute E((X - EX)^2) to mean_image_sqr_
    MACE_RETURN_IF_ERROR(ExecuteMeanValueKernel(
        context, runtime, batch, height, width, channel_blocks, group_blocks,
        output->opencl_image(), mean_image_sqr));
115 116
    // compute the compute (X - EX) / (E((X - EX)^2)^0.5 + eps_)
    MACE_RETURN_IF_ERROR(ExecuteVarianceNormStep2Kernel(
L
luxuhui 已提交
117 118
        context, runtime, gws, height, group_blocks, input->opencl_image(),
        mean_image, mean_image_sqr, output->opencl_image()));
119
  } else {
L
luxuhui 已提交
120 121 122 123 124
    // compute the EX
    MACE_RETURN_IF_ERROR(ExecuteMeanValueKernel(
        context, runtime, batch, height, width, channel_blocks, group_blocks,
        input->opencl_image(), mean_image));
    // compute the (X - EX)
125
    MACE_RETURN_IF_ERROR(ExecuteMeanNormKernel(
L
luxuhui 已提交
126 127
        context, runtime, gws, height, group_blocks, input->opencl_image(),
        mean_image, output->opencl_image()));
128 129
  }

L
luxuhui 已提交
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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
  return MaceStatus::MACE_SUCCESS;
}

MaceStatus MVNormKernel::ExecuteMeanValueKernel(OpContext *context,
                                                OpenCLRuntime *runtime,
                                                const index_t batch,
                                                const index_t height,
                                                const index_t width,
                                                const index_t channel_blocks,
                                                const index_t group_blocks,
                                                const cl::Image *input_image,
                                                cl::Image *output_image) {
  MACE_OUT_OF_RANGE_DEFINITION;
  if (kernel_mean_.get() == nullptr) {
    std::set<std::string> built_options;
    MACE_OUT_OF_RANGE_CONFIG;
    MACE_NON_UNIFORM_WG_CONFIG;
    MACE_RETURN_IF_ERROR(
        BuildMVNKernel(runtime, &kernel_mean_, "mvnorm_compute_mean_value",
                       &built_options, mean_type_));
    kwg_size_mean_ = static_cast<uint32_t>(
        runtime->GetKernelMaxWorkGroupSize(kernel_mean_));
  }

  const uint32_t gws[2] = {static_cast<uint32_t>(channel_blocks),
                           static_cast<uint32_t>(batch)};
  const std::vector<uint32_t> lws = {static_cast<uint32_t>(kwg_size_mean_) / 8,
                                     8, 0};
  MACE_OUT_OF_RANGE_INIT(kernel_mean_);
  uint32_t idx = 0;
  MACE_OUT_OF_RANGE_SET_ARGS(kernel_mean_);
  MACE_SET_2D_GWS_ARGS(kernel_mean_, gws);
  kernel_mean_.setArg(idx++, *input_image);
  kernel_mean_.setArg(idx++, static_cast<int>(height));
  kernel_mean_.setArg(idx++, static_cast<int>(width));
  kernel_mean_.setArg(idx++, static_cast<int>(group_blocks));
  kernel_mean_.setArg(idx++, *output_image);

  std::string tuning_key = Concat(
      "mvnorm_compute_mean_opencl_kernel", gws[0],
      gws[1], normalize_variance_, mean_type_);

  MACE_RETURN_IF_ERROR(TuningOrRun2DKernel(runtime, kernel_mean_, tuning_key,
                                           gws, lws, context->future()));
  MACE_OUT_OF_RANGE_VALIDATION;
  return MaceStatus::MACE_SUCCESS;
176 177 178 179 180
}

MaceStatus MVNormKernel::ExecuteMeanNormKernel(OpContext *context,
                                               OpenCLRuntime *runtime,
                                               const uint32_t (&gws)[3],
L
luxuhui 已提交
181 182 183 184 185
                                               const index_t height,
                                               const index_t group_blocks,
                                               const cl::Image *input,
                                               const cl::Image *mean_image,
                                               cl::Image *output) {
186 187 188 189 190 191
  MACE_OUT_OF_RANGE_DEFINITION;
  if (kernel_step1_.get() == nullptr) {
    std::set<std::string> built_options;
    MACE_OUT_OF_RANGE_CONFIG;
    MACE_NON_UNIFORM_WG_CONFIG;
    MACE_RETURN_IF_ERROR(BuildMVNKernel(runtime, &kernel_step1_, "mvnorm_mean",
L
luxuhui 已提交
192
                                        &built_options, mean_type_));
193 194 195 196 197 198 199 200
    kwg_size_step1_ = static_cast<uint32_t>(
        runtime->GetKernelMaxWorkGroupSize(kernel_step1_));
  }

  MACE_OUT_OF_RANGE_INIT(kernel_step1_);
  uint32_t idx = 0;
  MACE_OUT_OF_RANGE_SET_ARGS(kernel_step1_);
  MACE_SET_3D_GWS_ARGS(kernel_step1_, gws);
L
luxuhui 已提交
201 202
  kernel_step1_.setArg(idx++, *input);
  kernel_step1_.setArg(idx++, *mean_image);
203
  kernel_step1_.setArg(idx++, static_cast<int>(height));
L
luxuhui 已提交
204 205
  kernel_step1_.setArg(idx++, static_cast<int>(group_blocks));
  kernel_step1_.setArg(idx++, *output);
206 207

  std::vector<uint32_t> lws = Default3DLocalWS(runtime, gws, kwg_size_step1_);
L
luxuhui 已提交
208 209 210
  std::string tuning_key = Concat("mvnorm_mean_opencl_kernel", gws[0], gws[1],
                                  gws[2], normalize_variance_,
                                  mean_type_, group_blocks);
211 212 213 214 215 216 217

  MACE_RETURN_IF_ERROR(TuningOrRun3DKernel(runtime, kernel_step1_, tuning_key,
                                           gws, lws, context->future()));
  MACE_OUT_OF_RANGE_VALIDATION;
  return MaceStatus::MACE_SUCCESS;
}

L
luxuhui 已提交
218
// compute the (X - EX)^2
219 220
MaceStatus MVNormKernel::ExecuteVarianceNormStep1Kernel(
    OpContext *context, OpenCLRuntime *runtime,
L
luxuhui 已提交
221 222
    const uint32_t (&gws)[3], const index_t height, const index_t group_blocks,
    const cl::Image *input, const cl::Image *mean_image, cl::Image *output) {
223 224 225 226 227 228 229
  MACE_OUT_OF_RANGE_DEFINITION;
  if (kernel_step1_.get() == nullptr) {
    std::set<std::string> built_options;
    MACE_OUT_OF_RANGE_CONFIG;
    MACE_NON_UNIFORM_WG_CONFIG;
    MACE_RETURN_IF_ERROR(BuildMVNKernel(runtime, &kernel_step1_,
                                        "mvnorm_vn_step1",
L
luxuhui 已提交
230
                                        &built_options, mean_type_));
231 232 233 234 235 236 237 238
    kwg_size_step1_ = static_cast<uint32_t>(
        runtime->GetKernelMaxWorkGroupSize(kernel_step1_));
  }

  MACE_OUT_OF_RANGE_INIT(kernel_step1_);
  uint32_t idx = 0;
  MACE_OUT_OF_RANGE_SET_ARGS(kernel_step1_);
  MACE_SET_3D_GWS_ARGS(kernel_step1_, gws);
L
luxuhui 已提交
239
  kernel_step1_.setArg(idx++, *input);
240
  kernel_step1_.setArg(idx++, *mean_image);
L
luxuhui 已提交
241
  kernel_step1_.setArg(idx++, *output);
242
  kernel_step1_.setArg(idx++, static_cast<int>(height));
L
luxuhui 已提交
243
  kernel_step1_.setArg(idx++, static_cast<int>(group_blocks));
244 245 246 247 248

  std::vector<uint32_t> lws = Default3DLocalWS(runtime, gws, kwg_size_step1_);
  std::string
      tuning_key = Concat("mvnorm_v_step1_opencl_kernel", gws[0], gws[1],
                          gws[2], normalize_variance_,
L
luxuhui 已提交
249
                          mean_type_);
250 251 252 253 254 255 256

  MACE_RETURN_IF_ERROR(TuningOrRun3DKernel(runtime, kernel_step1_, tuning_key,
                                           gws, lws, context->future()));
  MACE_OUT_OF_RANGE_VALIDATION;
  return MaceStatus::MACE_SUCCESS;
}

L
luxuhui 已提交
257
// compute (X - EX) / (E((X - EX)^2)^0.5 + eps_)
258 259
MaceStatus MVNormKernel::ExecuteVarianceNormStep2Kernel(
    OpContext *context, OpenCLRuntime *runtime, const uint32_t (&gws)[3],
L
luxuhui 已提交
260 261 262
    const index_t height, const index_t group_blocks,
    const cl::Image *input, const cl::Image *mean_image,
    const cl::Image *mean_image_sqr, cl::Image *output) {
263 264 265 266 267 268 269
  MACE_OUT_OF_RANGE_DEFINITION;
  if (kernel_step2_.get() == nullptr) {
    std::set<std::string> built_options;
    MACE_OUT_OF_RANGE_CONFIG;
    MACE_NON_UNIFORM_WG_CONFIG;
    MACE_RETURN_IF_ERROR(BuildMVNKernel(runtime, &kernel_step2_,
                                        "mvnorm_vn_step2",
L
luxuhui 已提交
270
                                        &built_options, mean_type_));
271 272 273 274 275 276 277 278
    kwg_size_step2_ = static_cast<uint32_t>(
        runtime->GetKernelMaxWorkGroupSize(kernel_step2_));
  }

  MACE_OUT_OF_RANGE_INIT(kernel_step2_);
  uint32_t idx = 0;
  MACE_OUT_OF_RANGE_SET_ARGS(kernel_step2_);
  MACE_SET_3D_GWS_ARGS(kernel_step2_, gws);
L
luxuhui 已提交
279
  kernel_step2_.setArg(idx++, *input);
280
  kernel_step2_.setArg(idx++, *mean_image);
L
luxuhui 已提交
281
  kernel_step2_.setArg(idx++, *mean_image_sqr);
282
  kernel_step2_.setArg(idx++, static_cast<int>(height));
L
luxuhui 已提交
283
  kernel_step2_.setArg(idx++, static_cast<int>(group_blocks));
284
  kernel_step2_.setArg(idx++, static_cast<float>(eps_));
L
luxuhui 已提交
285
  kernel_step2_.setArg(idx++, *output);
286 287 288 289 290

  std::vector<uint32_t> lws = Default3DLocalWS(runtime, gws, kwg_size_step2_);
  std::string
      tuning_key = Concat("mvnorm_v_step2_opencl_kernel", gws[0], gws[1],
                          gws[2], normalize_variance_,
L
luxuhui 已提交
291
                          mean_type_);
292 293 294 295 296 297 298 299 300 301 302

  MACE_RETURN_IF_ERROR(TuningOrRun3DKernel(runtime, kernel_step2_, tuning_key,
                                           gws, lws, context->future()));
  MACE_OUT_OF_RANGE_VALIDATION;
  return MaceStatus::MACE_SUCCESS;
}

}  // namespace image
}  // namespace opencl
}  // namespace ops
}  // namespace mace