fusion_rnn_mkldnn.h 8.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2021 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. */

L
Leo Chen 已提交
15 16
#pragma once

17 18 19 20 21
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace operators {

22
using phi::funcs::CreateKey;
23
using phi::funcs::OneDNNGetDataType;
24
using phi::funcs::RNNReorderType;
25 26

template <typename T, typename T_alg, typename T_out = T>
27
class RNNMKLDNNHandler : public phi::funcs::OneDNNHandlerT<T, T_alg> {
28 29
 public:
  RNNMKLDNNHandler(const paddle::framework::ExecutionContext& ctx,
30
                   const phi::OneDNNContext& dev_ctx,
31 32
                   const dnnl::engine mkldnn_engine,
                   platform::Place cpu_place,
33
                   const phi::DenseTensor* input,
34 35
                   const phi::DenseTensor* weight_h,
                   const phi::DenseTensor* h0,
36 37 38 39 40 41 42
                   const bool is_reverse,
                   const int64_t N,
                   const int64_t Ti,
                   const int64_t IC,
                   const int64_t OC,
                   const int64_t G,
                   const std::string& unique_name)
43
      : phi::funcs::OneDNNHandlerT<T, T_alg>(
44 45 46
            dev_ctx,
            dev_ctx.GetEngine(),
            cpu_place,
47
            CreateKey(dev_ctx, unique_name, OneDNNGetDataType<T>(), Ti)),
48 49 50 51 52 53 54
        N(N),
        Ti(Ti),
        IC(IC),
        OC(OC),
        G(G) {
    // Create memory key without Ti because weights, bias and h0 memories
    // do not depend on Ti size but primitive and input/output memory do
55
    memory_key_ = phi::funcs::ExtendKeyWithThreadInfoIfNeeded(
56
        dev_ctx, CreateKey(dev_ctx, unique_name, OneDNNGetDataType<T>()));
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

    // Is it int8 kernel
    const bool is_INT8 = std::is_same<T, uint8_t>::value;

    if (is_INT8) {
      // Int8 attributes
      const float scale_data = ctx.Attr<float>("Scale_data");
      const float shift_data = ctx.Attr<float>("Shift_data");
      const auto scale_weights = ctx.Attr<std::vector<float>>("Scale_weights");

      const int weights_scale_mask =
          0 +
          (1 << 3)  // bit, indicating the unique scales for `g` dim in `ldigo`
          +
          (1 << 4);  // bit, indicating the unique scales for `o` dim in `ldigo`

      attr_.set_rnn_data_qparams(scale_data, shift_data);
      attr_.set_rnn_weights_qparams(weights_scale_mask, scale_weights);
    }
  }

78 79 80 81 82 83
  bool is_NTC() { return this->is_NTC(this->fwd_pd_->dst_desc()); }

  bool is_NTC(const dnnl::memory::desc& md) {
    auto ntc_md = dnnl::memory::desc(
        md.dims(), md.data_type(), dnnl::memory::format_tag::ntc);
    return md == ntc_md;
84 85
  }

86 87 88 89
  void reorderRNNdata(void* input_data,
                      void* output_data,
                      std::vector<size_t> lod,
                      const bool is_reverse,
90
                      RNNReorderType reorder_type) {
91 92
    switch (reorder_type) {
      // Reorder input memory [WORDS, C] + LoD -> [N, T, C]
93
      case RNNReorderType::PP_NTC: {
94 95 96 97 98
        auto* input_data_iter = reinterpret_cast<T*>(input_data);
        auto* output_data_iter = reinterpret_cast<T*>(output_data);
        for (int n = 0; n < N; ++n) {
          const auto num_elements = (lod[n + 1] - lod[n]) * IC;
          const auto offset = is_reverse ? (Ti * IC - num_elements) : 0;
99 100
          memcpy(output_data_iter + n * Ti * IC + offset,
                 input_data_iter,
101 102 103 104 105
                 sizeof(T) * num_elements);
          input_data_iter += num_elements;
        }
      } break;
      // Reorder input memory [WORDS, C] + LoD -> [T, N, C]
106
      case RNNReorderType::PP_TNC: {
107 108 109 110 111 112 113
        auto* input_data_iter = reinterpret_cast<T*>(input_data);
        auto* output_data_iter = reinterpret_cast<T*>(output_data);
        for (int n = 0; n < N; ++n) {
          const auto num_elements = (lod[n + 1] - lod[n]);
          const auto offset = is_reverse ? (Ti - num_elements) : 0;
          for (size_t t = 0; t < num_elements; ++t) {
            memcpy(output_data_iter + (t + offset) * N * IC + n * IC,
114 115
                   input_data_iter,
                   sizeof(T) * IC);
116 117 118 119 120
            input_data_iter += IC;
          }
        }
      } break;
      // Reorder output values to PP format [N, T, C] -> [WORDS, C]
121
      case RNNReorderType::NTC_PP: {
122 123 124 125 126
        auto* input_data_iter = reinterpret_cast<T_out*>(input_data);
        auto* output_data_iter = reinterpret_cast<T_out*>(output_data);
        for (int n = 0; n < N; ++n) {
          const auto num_elements = (lod[n + 1] - lod[n]) * OC;
          const auto offset = is_reverse ? (Ti * OC - num_elements) : 0;
127 128
          memcpy(output_data_iter,
                 input_data_iter + n * Ti * OC + offset,
129 130 131 132 133
                 sizeof(T_out) * num_elements);
          output_data_iter += num_elements;
        }
      } break;
      // Reorder output values to PP format [T, N, C] -> [WORDS, C]
134
      case RNNReorderType::TNC_PP: {
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        auto* input_data_iter = reinterpret_cast<T_out*>(input_data);
        auto* output_data_iter = reinterpret_cast<T_out*>(output_data);
        for (int n = 0; n < N; ++n) {
          const auto num_elements = lod[n + 1] - lod[n];
          const auto offset = is_reverse ? (Ti - num_elements) : 0;
          for (size_t t = 0; t < num_elements; ++t) {
            memcpy(output_data_iter,
                   input_data_iter + (t + offset) * N * OC + n * OC,
                   sizeof(T_out) * OC);
            output_data_iter += OC;
          }
        }
      } break;
    }
  }

  std::shared_ptr<dnnl::memory> AcquireInputMemoryWithReorder(
152
      const phi::DenseTensor* input, const bool is_reverse) {
153 154 155 156 157 158 159 160 161 162 163
    const auto name = this->key_ + "@input_mem";
    auto memory_p =
        std::static_pointer_cast<dnnl::memory>(this->dev_ctx_.GetBlob(name));

    if (!memory_p) {
      memory_p = std::make_shared<dnnl::memory>(this->fwd_pd_->src_desc(),
                                                this->engine_);
      this->dev_ctx_.SetBlob(name, memory_p);
    }

    const auto& input_lod = input->lod()[0];
164
    auto* x_data = phi::funcs::to_void_cast(input->data<T>());
165 166 167 168

    auto* x_onednn_data = memory_p->get_data_handle();
    memset(x_onednn_data, 0, sizeof(T) * N * Ti * IC);

169
    if (is_NTC(this->fwd_pd_->src_desc())) {
170 171
      reorderRNNdata(
          x_data, x_onednn_data, input_lod, is_reverse, RNNReorderType::PP_NTC);
172
    } else {
173 174
      reorderRNNdata(
          x_data, x_onednn_data, input_lod, is_reverse, RNNReorderType::PP_TNC);
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    }
    return memory_p;
  }

  std::shared_ptr<dnnl::memory> AcquireOutputMemory() {
    const auto name = this->key_ + "@output_mem";
    auto memory_p =
        std::static_pointer_cast<dnnl::memory>(this->dev_ctx_.GetBlob(name));

    if (!memory_p) {
      memory_p = std::make_shared<dnnl::memory>(this->fwd_pd_->dst_desc(),
                                                this->engine_);
      this->dev_ctx_.SetBlob(name, memory_p);
    }
    return memory_p;
  }

  // TODO(grygielski) H0 is for now persistable
  // TODO(jczaja) H0 should be updated each iter and of T type (Fusion pass does
  // not support in yet)
195
  template <typename U>
196
  std::shared_ptr<dnnl::memory> AcquireH0Memory(const phi::DenseTensor* h0) {
197 198 199 200 201 202 203
    const std::string h0_key = memory_key_ + "@h0";
    auto memory_p =
        std::static_pointer_cast<dnnl::memory>(this->dev_ctx_.GetBlob(h0_key));

    if (!memory_p) {
      auto user_h0_memory = dnnl::memory();
      if (h0) {
204
        user_h0_memory = dnnl::memory(
205
            {{1, 1, N, OC}, OneDNNGetDataType<U>(), OneDNNMemoryFormat::ldnc},
206
            this->engine_,
207
            phi::funcs::to_void_cast(h0->data<U>()));
208
      } else {
209
        user_h0_memory = dnnl::memory(
210
            {{1, 1, N, OC}, OneDNNGetDataType<U>(), OneDNNMemoryFormat::ldnc},
211 212
            this->engine_);
        memset(user_h0_memory.get_data_handle(), 0, sizeof(U) * N * OC);
213 214 215 216
      }
      memory_p = std::make_shared<dnnl::memory>(this->fwd_pd_->src_iter_desc(),
                                                this->engine_);

217
      auto& astream = phi::OneDNNContext::tls().get_stream();
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
      dnnl::reorder(user_h0_memory, *memory_p, attr_)
          .execute(astream, user_h0_memory, *memory_p);

      this->dev_ctx_.SetBlob(h0_key, memory_p);
    }
    return memory_p;
  }

 protected:
  // RNN dimensions
  // N - Batch Size
  // Ti - Max sentence length
  // IC - Input Channels
  // OC - Output Channels
  // G  - Number of gates
  const int64_t N, Ti, IC, OC, G;

  // Memory size of weights, bias and h0 does not depend
  // on Ti size, thus we need another key to cache them
  std::string memory_key_;
  dnnl::primitive_attr attr_;
};
}  // namespace operators
}  // namespace paddle