helper.h 9.8 KB
Newer Older
T
tensor-tang 已提交
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

T
tensor-tang 已提交
17
#include <iostream>
18
#include <map>
Y
Yihua Xu 已提交
19
#include <memory>
T
tensor-tang 已提交
20
#include <string>
21 22
#include <unordered_map>
#include <utility>  // for std::move
T
tensor-tang 已提交
23 24 25 26 27 28 29 30 31 32 33
#include <vector>
#include "paddle/fluid/operators/jit/gen_base.h"
#include "paddle/fluid/operators/jit/kernel_base.h"
#include "paddle/fluid/operators/jit/kernel_key.h"
#include "paddle/fluid/operators/jit/kernel_pool.h"
#include "paddle/fluid/platform/place.h"

namespace paddle {
namespace operators {
namespace jit {

34
template <typename KernelTuple, typename PlaceType>
T
tensor-tang 已提交
35
inline typename std::enable_if<
36
    std::is_same<typename KernelTuple::data_type, float>::value &&
T
tensor-tang 已提交
37
        std::is_same<PlaceType, platform::CPUPlace>::value,
38
    const Kernel*>::type
39 40
GetJitCode(const typename KernelTuple::attr_type& attr) {
  using Attr = typename KernelTuple::attr_type;
41
  int64_t key = JitCodeKey<Attr>(attr);
42
  auto& codes = JitCodePool<KernelTuple::kernel_type>::Instance();
T
tensor-tang 已提交
43
  if (codes.Has(key)) {
44
    return codes.AllKernels().at(key).get();
T
tensor-tang 已提交
45 46
  }

T
tensor-tang 已提交
47
  // creator is not related with attr, so can use KernelKey as key
48
  KernelKey kkey(KernelTuple::kernel_type, PlaceType());
T
tensor-tang 已提交
49
  // pool: (KernelKey(type, place), vector<GenCreatorPtr>)
50
  auto& creator_map = JitCodeCreatorPool::Instance().AllCreators();
T
tensor-tang 已提交
51 52 53 54 55
  auto iter = creator_map.find(kkey);
  if (iter != creator_map.end()) {
    auto& creators = iter->second;
    for (auto& cur : creators) {
      auto i = dynamic_cast<const JitCodeCreator<Attr>*>(cur.get());
56
      if (i && i->CanBeUsed(attr)) {
T
tensor-tang 已提交
57 58
        auto p = i->CreateJitCode(attr);
        if (p) {
59
          auto res = p.get();
T
tensor-tang 已提交
60
          codes.Insert(key, std::move(p));
61
          return res;
T
tensor-tang 已提交
62 63 64 65
        }
      }
    }
  }
T
tensor-tang 已提交
66 67 68
  return nullptr;
}

69
template <typename KernelTuple, typename PlaceType>
T
tensor-tang 已提交
70
inline typename std::enable_if<
71
    !std::is_same<typename KernelTuple::data_type, float>::value ||
T
tensor-tang 已提交
72
        !std::is_same<PlaceType, platform::CPUPlace>::value,
73
    const Kernel*>::type
74
GetJitCode(const typename KernelTuple::attr_type& attr) {
T
tensor-tang 已提交
75 76 77
  return nullptr;
}

T
tensor-tang 已提交
78 79
// Refer code do not related with attr, which is just for cast
// Refer is always on CPUPlace
80
template <typename KernelTuple>
81 82
inline const Kernel* GetReferKernel() {
  auto& ref_pool = ReferKernelPool::Instance().AllKernels();
83
  KernelKey kkey(KernelTuple::kernel_type, platform::CPUPlace());
T
tensor-tang 已提交
84 85 86 87 88
  auto ref_iter = ref_pool.find(kkey);
  PADDLE_ENFORCE(ref_iter != ref_pool.end(),
                 "Every Kernel should have reference function.");
  auto& ref_impls = ref_iter->second;
  for (auto& impl : ref_impls) {
89
    auto i = dynamic_cast<const ReferKernel<KernelTuple>*>(impl.get());
T
tensor-tang 已提交
90
    if (i) {
91
      return i;
T
tensor-tang 已提交
92 93 94 95 96
    }
  }
  return nullptr;
}

97 98 99 100 101 102 103 104 105 106 107
template <typename KernelTuple>
inline typename KernelTuple::func_type GetReferFunc() {
  auto ker = GetReferKernel<KernelTuple>();
  auto p = dynamic_cast<const ReferKernel<KernelTuple>*>(ker);
  PADDLE_ENFORCE(p, "The Refer kernel should exsit");
  return p->GetFunc();
}

// Return all Kernels that can be used
template <typename KernelTuple, typename PlaceType>
std::vector<const Kernel*> GetAllCandidateKernels(
108
    const typename KernelTuple::attr_type& attr) {
109 110 111 112 113
  // the search order shoudl be jitcode > more > refer
  std::vector<const Kernel*> res;
  auto jitker = GetJitCode<KernelTuple, PlaceType>(attr);
  if (jitker) {
    res.emplace_back(jitker);
T
tensor-tang 已提交
114
  }
T
tensor-tang 已提交
115

116
  // more kernelpool: (KernelKey(type, place), vector<KernelPtr>)
117
  KernelKey kkey(KernelTuple::kernel_type, PlaceType());
118
  auto& pool = KernelPool::Instance().AllKernels();
T
tensor-tang 已提交
119 120 121 122
  auto iter = pool.find(kkey);
  if (iter != pool.end()) {
    auto& impls = iter->second;
    for (auto& impl : impls) {
123
      auto i = dynamic_cast<const KernelMore<KernelTuple>*>(impl.get());
124 125
      if (i && i->CanBeUsed(attr)) {
        res.emplace_back(i);
T
tensor-tang 已提交
126 127 128 129 130
      }
    }
  }

  // The last implementation should be reference function on CPUPlace.
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 176 177
  auto ref = GetReferKernel<KernelTuple>();
  PADDLE_ENFORCE(ref != nullptr, "Refer Kernel can not be empty.");
  res.emplace_back(ref);
  return res;
}

template <typename KernelTuple, typename PlaceType = platform::CPUPlace>
std::vector<std::pair<std::string, typename KernelTuple::func_type>>
GetAllCandidateFuncsWithTypes(const typename KernelTuple::attr_type& attr) {
  using Func = typename KernelTuple::func_type;
  auto kers = GetAllCandidateKernels<KernelTuple, PlaceType>(attr);
  std::vector<std::pair<std::string, Func>> res;
  for (auto k : kers) {
    std::string name = k->ImplType();
    if (name == "JitCode") {
      auto i = dynamic_cast<const GenBase*>(k);
      PADDLE_ENFORCE(i, "jitcode kernel cast can not fail.");
      res.emplace_back(std::make_pair(name, i->template getCode<Func>()));
    } else {
      auto i = dynamic_cast<const KernelMore<KernelTuple>*>(k);
      PADDLE_ENFORCE(i, "kernel cast can not fail.");
      res.emplace_back(std::make_pair(name, i->GetFunc()));
    }
  }
  return res;
}

template <typename KernelTuple, typename PlaceType = platform::CPUPlace>
std::vector<typename KernelTuple::func_type> GetAllCandidateFuncs(
    const typename KernelTuple::attr_type& attr) {
  auto funcs = GetAllCandidateFuncsWithTypes<KernelTuple, PlaceType>(attr);
  std::vector<typename KernelTuple::func_type> res;
  for (auto& i : funcs) {
    res.emplace_back(i.second);
  }
  return res;
}

template <typename KernelTuple, typename PlaceType = platform::CPUPlace>
typename KernelTuple::func_type GetDefaultBestFunc(
    const typename KernelTuple::attr_type& attr) {
  auto funcs = GetAllCandidateFuncs<KernelTuple, PlaceType>(attr);
  PADDLE_ENFORCE_GE(funcs.size(), 1UL);
  // Here could do some runtime benchmark of this attr and return the best one.
  // But yet just get the first one as the default best one,
  // which is searched in order and tuned by offline.
  return funcs[0];
T
tensor-tang 已提交
178 179
}

180
extern std::map<size_t, std::shared_ptr<void>>& GetFuncCacheMap();
Y
Yihua Xu 已提交
181

182
template <typename KernelTuple, typename PlaceType>
T
tensor-tang 已提交
183
class KernelFuncs {
T
tensor-tang 已提交
184
 public:
T
tensor-tang 已提交
185 186
  KernelFuncs() = default;
  static KernelFuncs& Cache() {
Y
Yihua Xu 已提交
187
    auto& func_cache_map = GetFuncCacheMap();
188
    auto key = typeid(KernelFuncs<KernelTuple, PlaceType>).hash_code();
Y
Yihua Xu 已提交
189 190 191 192 193 194 195 196 197
    auto iter = func_cache_map.find(key);
    if (iter != func_cache_map.end()) {
      return *(KernelFuncs<KernelTuple, PlaceType>*)(iter->second.get());
    } else {
      std::shared_ptr<void> cache =
          std::make_shared<KernelFuncs<KernelTuple, PlaceType>>();
      func_cache_map.emplace(key, cache);
      return *(KernelFuncs<KernelTuple, PlaceType>*)(cache.get());
    }
T
tensor-tang 已提交
198 199
  }

200
  // the exposed interface to use
201 202
  typename KernelTuple::func_type At(
      const typename KernelTuple::attr_type& attr) {
203 204
    // Maybe here is not good enough, not all kernels should have jitcode
    int64_t key = JitCodeKey<typename KernelTuple::attr_type>(attr);
T
tensor-tang 已提交
205 206 207
    if (Has(key)) {
      return funcs_.at(key);
    }
208 209
    // If do not have this attr in cache then get the default best
    auto func = GetDefaultBestFunc<KernelTuple, PlaceType>(attr);
T
tensor-tang 已提交
210 211 212 213
    Insert(key, func);
    return func;
  }

214 215
  typename KernelTuple::func_type operator[](
      const typename KernelTuple::attr_type& attr) {
216 217 218 219 220
    return At(attr);
  }

 protected:
  bool Has(int64_t key) const { return funcs_.find(key) != funcs_.end(); }
221
  void Insert(int64_t key, typename KernelTuple::func_type func) {
222 223 224
    funcs_.emplace(key, func);
  }

T
tensor-tang 已提交
225
 private:
226
  std::unordered_map<int64_t, typename KernelTuple::func_type> funcs_;
T
tensor-tang 已提交
227
  DISABLE_COPY_AND_ASSIGN(KernelFuncs);
T
tensor-tang 已提交
228 229
};

230
const char* to_string(KernelType kt);
231
const char* to_string(SeqPoolType kt);
232

T
tensor-tang 已提交
233 234
KernelType to_kerneltype(const std::string& act);

T
tensor-tang 已提交
235 236 237 238 239 240 241
inline std::ostream& operator<<(std::ostream& os, const lstm_attr_t& attr) {
  os << "dim_size[" << attr.d << "],act_gate[" << to_string(attr.act_gate)
     << "],act_cand[" << to_string(attr.act_cand) << "],act_cell["
     << to_string(attr.act_cell) << "],use_peephole["
     << (attr.use_peephole ? "True" : "False") << "]";
  return os;
}
242

T
tensor-tang 已提交
243 244 245 246 247
inline std::ostream& operator<<(std::ostream& os, const gru_attr_t& attr) {
  os << "dim_size[" << attr.d << "],act_gate[" << to_string(attr.act_gate)
     << "],act_cand[" << to_string(attr.act_cand) << "]";
  return os;
}
248

249 250 251 252 253
inline std::ostream& operator<<(std::ostream& os, const seq_pool_attr_t& attr) {
  os << "height_size[" << attr.h << "],width_size[" << attr.w << "],pool_type["
     << to_string(attr.type) << "]";
  return os;
}
T
tensor-tang 已提交
254

255 256 257 258 259 260 261 262 263
inline std::ostream& operator<<(std::ostream& os,
                                const emb_seq_pool_attr_t& attr) {
  os << "table_height[" << attr.table_height << "],table_width["
     << attr.table_width << "],index_height[" << attr.index_height
     << "],index_width[" << attr.index_width << "],output_width["
     << attr.out_width << "],pool_type[" << to_string(attr.pool_type) << "]";
  return os;
}

264 265 266 267 268 269 270 271
inline std::ostream& operator<<(std::ostream& os, const sgd_attr_t& attr) {
  os << "param_height[" << attr.param_height << "],param_width["
     << attr.param_width << "],grad_height[" << attr.grad_height
     << "],grad_width[" << attr.grad_width << "],selected_rows_size["
     << attr.selected_rows_size << "]";
  return os;
}

272 273 274 275 276 277 278 279 280
inline std::ostream& operator<<(std::ostream& os, const matmul_attr_t& attr) {
  os << "M[" << attr.m << "],N[" << attr.n << "],K[" << attr.k << "]";
  return os;
}

// expose the method to pack matmul weight
template <typename T>
void pack_weights(const T* src, T* dst, int n, int k);

T
tensor-tang 已提交
281 282 283
}  // namespace jit
}  // namespace operators
}  // namespace paddle