data_transform.h 5.9 KB
Newer Older
Q
Qiao Longfei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 <functional>
#include <utility>
#include <vector>

#include "paddle/framework/op_kernel_type.h"
22
#include "paddle/framework/selected_rows.h"
Q
Qiao Longfei 已提交
23 24
#include "paddle/framework/tensor.h"
#include "paddle/framework/variable.h"
D
dzhwinter 已提交
25
#include "paddle/operators/math/math_function.h"
Q
Qiao Longfei 已提交
26 27
#include "paddle/platform/device_context.h"
#include "paddle/platform/macros.h"
D
dzhwinter 已提交
28
#include "paddle/platform/transform.h"
Q
Qiao Longfei 已提交
29 30 31 32 33 34

namespace paddle {
namespace framework {

using KernelTypePair = std::pair<OpKernelType, OpKernelType>;

D
dzhwinter 已提交
35 36 37 38
using DataTransformFn =
    std::function<void(const platform::DeviceContext*, const KernelTypePair&,
                       const Variable&, Variable*)>;

Q
Qiao Longfei 已提交
39
struct KernelTypePairHash {
40 41 42 43 44
  static void HashCombine(const OpKernelType& t, std::size_t* seed) {
    OpKernelType::Hash kernel_type_hasher;
    (*seed) ^= kernel_type_hasher(t) + 0x9e3779b9 + (*seed << 6) + (*seed >> 2);
  }

Q
Qiao Longfei 已提交
45 46
  size_t operator()(const KernelTypePair& kernel_pair) const {
    std::size_t seed = 0;
47 48
    HashCombine(kernel_pair.first, &seed);
    HashCombine(kernel_pair.second, &seed);
Q
Qiao Longfei 已提交
49 50 51 52
    return seed;
  }
};

53 54 55 56 57 58 59
Tensor* DataTransform(const OpKernelType& expected_kernel_type,
                      const OpKernelType& kernel_type_for_var,
                      const Tensor& input_tensor);

void CopyVariableWithTensor(const Variable& in_var, const Tensor& tensor,
                            Variable& out_var);

D
dzhwinter 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
template <typename InType, typename OutType>
struct CastDataTypeFunctor {
  HOSTDEVICE inline OutType operator()(InType in) const {
    return static_cast<OutType>(in);
  }
};

template <typename InType>
struct CastDataType {
  CastDataType(const framework::Tensor& in, framework::Tensor* out,
               const platform::DeviceContext* ctx)
      : in_(in), out_(out), ctx_(ctx) {}
  const framework::Tensor in_;
  framework::Tensor* out_;
  const platform::DeviceContext* ctx_;

  template <typename OutType>
  void operator()() {
    auto place = ctx_->GetPlace();

    auto* in_begin = in_.data<InType>();
    auto numel = in_.numel();
    auto* in_end = in_begin + numel;
    auto* out_begin = out_->mutable_data<OutType>(place);
D
dzhwinter 已提交
84

D
dzhwinter 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97
    if (platform::is_cpu_place(place)) {
      platform::Transform<platform::CPUDeviceContext> trans;
      auto* context = static_cast<const platform::CPUDeviceContext*>(ctx_);
      trans(*context, in_begin, in_end, out_begin,
            CastDataTypeFunctor<InType, OutType>());
    } else {
      // TODO(dzhwinter): enhance CopyFrom CPU<->GPU with different data type?
      PADDLE_THROW("Unsupport CPU <-> GPU!");
    }
  }
};

struct CastDataLayout {
D
dzhwinter 已提交
98 99 100
  CastDataLayout(const platform::DeviceContext* ctx,
                 const std::vector<int>& axis, const framework::Tensor& in,
                 framework::Tensor* out)
D
dzhwinter 已提交
101 102 103 104 105 106 107 108 109
      : in_(in), out_(out), ctx_(ctx), axis_(axis) {}
  const framework::Tensor in_;
  framework::Tensor* out_;
  const platform::DeviceContext* ctx_;
  const std::vector<int> axis_;

  template <typename T>
  void operator()() {
    auto place = ctx_->GetPlace();
D
dzhwinter 已提交
110

D
dzhwinter 已提交
111 112 113 114 115 116 117 118 119 120
    if (platform::is_cpu_place(place)) {
      operators::math::Transpose<platform::CPUDeviceContext, T, 4> trans4;
      auto* context = static_cast<const platform::CPUDeviceContext*>(ctx_);
      trans4(*context, in_, out_, axis_);
    } else {
      PADDLE_THROW("Unsupport CPU <-> GPU!");
    }
  }
};

Q
Qiao Longfei 已提交
121
using DataTransformMap =
Q
QI JUN 已提交
122
    std::unordered_map<KernelTypePair, DataTransformFn, KernelTypePairHash>;
Q
Qiao Longfei 已提交
123 124 125 126 127 128 129 130 131 132

class DataTransformFnMap {
 public:
  static DataTransformFnMap& Instance();

  bool Has(const KernelTypePair& key_pair) const {
    return map_.find(key_pair) != map_.end();
  }

  void Insert(const OpKernelType& left, const OpKernelType& right,
Q
QI JUN 已提交
133
              const DataTransformFn& data_tranform_fn) {
Q
Qiao Longfei 已提交
134 135 136 137
    Insert(std::make_pair(left, right), data_tranform_fn);
  }

  void Insert(const KernelTypePair& kernel_type_pair,
Q
QI JUN 已提交
138
              const DataTransformFn& data_tranform_fn) {
Q
Qiao Longfei 已提交
139 140 141 142 143
    PADDLE_ENFORCE(!Has(kernel_type_pair),
                   "KernelTypePair %s has been registered", "");
    map_.insert({kernel_type_pair, data_tranform_fn});
  }

Q
QI JUN 已提交
144
  const DataTransformFn& Get(const KernelTypePair& key_pair) const {
Q
Qiao Longfei 已提交
145 146
    auto data_transformer = GetNullable(key_pair);
    PADDLE_ENFORCE_NOT_NULL(data_transformer,
Q
QI JUN 已提交
147
                            "DataTransformFn should not be NULL");
Q
Qiao Longfei 已提交
148 149 150
    return *data_transformer;
  }

Q
QI JUN 已提交
151
  const DataTransformFn* GetNullable(const KernelTypePair& key_pair) const {
Q
Qiao Longfei 已提交
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 178 179 180 181
    auto it = map_.find(key_pair);
    if (it == map_.end()) {
      return nullptr;
    } else {
      return &(it->second);
    }
  }

  const DataTransformMap& Map() const { return map_; }

 private:
  DataTransformFnMap() = default;
  DataTransformMap map_;
  DISABLE_COPY_AND_ASSIGN(DataTransformFnMap);
};

// generate unique name with __LINE__
// refs https://stackoverflow.com/questions/1597007
#define TOKENPASTE(x, y) x##y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define REGISTER_DATA_TRANSFORM_FN(from, to, fn)                              \
  static int TOKENPASTE2(fn_, __LINE__)() {                                   \
    ::paddle::framework::DataTransformFnMap::Instance().Insert(from, to, fn); \
    return 0;                                                                 \
  }                                                                           \
  static int TOKENPASTE2(var_, __LINE__) __attribute__((unused)) =            \
      TOKENPASTE2(fn_, __LINE__)()

}  // namespace framework
}  // namespace paddle