Skip to content

Commit 8c71ada

Browse files
pzelazko-intelluotao1
authored andcommitted
MKLDNN conv2d kernel added (#8451)
* MKLDNN conv2 OP kernel added * TODOs added * mkldnn conv2d OP refactor * CanCUDNNBeUsed and CanMKLDNNBeUsed moved
1 parent 049383c commit 8c71ada

File tree

10 files changed

+465
-115
lines changed

10 files changed

+465
-115
lines changed

paddle/fluid/operators/CMakeLists.txt

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
file(GLOB GENERAL_OPS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "*_op.cc")
2+
string(REPLACE "_mkldnn" "" GENERAL_OPS "${GENERAL_OPS}")
23
string(REPLACE ".cc" "" GENERAL_OPS "${GENERAL_OPS}")
4+
list(REMOVE_DUPLICATES GENERAL_OPS)
35
set(DEPS_OPS "")
46
set(pybind_file ${PADDLE_SOURCE_DIR}/paddle/fluid/pybind/pybind.h)
57
file(WRITE ${pybind_file} "// Generated by the paddle/operator/CMakeLists.txt. DO NOT EDIT!\n\n")
@@ -13,6 +15,8 @@ function(op_library TARGET)
1315
set(cu_cc_srcs)
1416
set(cudnn_cu_cc_srcs)
1517
set(CUDNN_FILE)
18+
set(mkldnn_cc_srcs)
19+
set(MKLDNN_FILE)
1620
set(op_common_deps operator op_registry math_function)
1721
set(options "")
1822
set(oneValueArgs "")
@@ -36,12 +40,20 @@ function(op_library TARGET)
3640
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${CUDNN_FILE}.cu.cc)
3741
list(APPEND cudnn_cu_cc_srcs ${CUDNN_FILE}.cu.cc)
3842
endif()
43+
if(WITH_MKLDNN)
44+
string(REPLACE "_op" "_mkldnn_op" MKLDNN_FILE "${TARGET}")
45+
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${MKLDNN_FILE}.cc)
46+
list(APPEND mkldnn_cc_srcs ${MKLDNN_FILE}.cc)
47+
endif()
48+
endif()
3949
else()
4050
foreach(src ${op_library_SRCS})
4151
if (${src} MATCHES ".*\\.cu$")
4252
list(APPEND cu_srcs ${src})
4353
elseif(${src} MATCHES ".*_cudnn_op.cu.cc$")
4454
list(APPEND cudnn_cu_cc_srcs ${src})
55+
elseif(WITH_MKLDNN AND ${src} MATCHES ".*_mkldnn_op.cc$")
56+
list(APPEND mkldnn_cc_srcs ${src})
4557
elseif(${src} MATCHES ".*\\.cu.cc$")
4658
list(APPEND cu_cc_srcs ${src})
4759
elseif(${src} MATCHES ".*\\.cc$")
@@ -62,11 +74,11 @@ function(op_library TARGET)
6274
set(DEPS_OPS ${TARGET} ${DEPS_OPS} PARENT_SCOPE)
6375
endif()
6476
if (WITH_GPU)
65-
nv_library(${TARGET} SRCS ${cc_srcs} ${cu_cc_srcs} ${cudnn_cu_cc_srcs} ${cu_srcs} DEPS ${op_library_DEPS}
77+
nv_library(${TARGET} SRCS ${cc_srcs} ${cu_cc_srcs} ${cudnn_cu_cc_srcs} ${mkldnn_cc_srcs} ${cu_srcs} DEPS ${op_library_DEPS}
6678
${op_common_deps})
6779
else()
68-
cc_library(${TARGET} SRCS ${cc_srcs} DEPS ${op_library_DEPS}
69-
${op_common_deps})
80+
cc_library(${TARGET} SRCS ${cc_srcs} ${mkldnn_cc_srcs} DEPS ${op_library_DEPS}
81+
${op_common_deps})
7082
endif()
7183

7284
# Define operators that don't need pybind here.
@@ -101,7 +113,8 @@ function(op_library TARGET)
101113
# pybind USE_CPU_ONLY_OP
102114
list(LENGTH cu_srcs cu_srcs_len)
103115
list(LENGTH cu_cc_srcs cu_cc_srcs_len)
104-
if (${pybind_flag} EQUAL 0 AND ${cu_srcs_len} EQUAL 0 AND ${cu_cc_srcs_len} EQUAL 0)
116+
list(LENGTH mkldnn_cc_srcs mkldnn_cc_srcs_len)
117+
if (${pybind_flag} EQUAL 0 AND ${mkldnn_cc_srcs_len} EQUAL 0 AND ${cu_srcs_len} EQUAL 0 AND ${cu_cc_srcs_len} EQUAL 0)
105118
file(APPEND ${pybind_file} "USE_CPU_ONLY_OP(${TARGET});\n")
106119
set(pybind_flag 1)
107120
endif()
@@ -112,6 +125,11 @@ function(op_library TARGET)
112125
file(APPEND ${pybind_file} "USE_OP_DEVICE_KERNEL(${TARGET}, CUDNN);\n")
113126
endif()
114127

128+
# pybind USE_OP_DEVICE_KERNEL for MKLDNN
129+
if (WITH_MKLDNN AND ${mkldnn_cc_srcs_len} GREATER 0)
130+
file(APPEND ${pybind_file} "USE_OP_DEVICE_KERNEL(${TARGET}, MKLDNN);\n")
131+
endif()
132+
115133
# pybind USE_OP
116134
if (${pybind_flag} EQUAL 0)
117135
file(APPEND ${pybind_file} "USE_OP(${TARGET});\n")
Lines changed: 313 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,313 @@
1+
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License. */
14+
15+
#include "mkldnn.hpp"
16+
#include "paddle/fluid/framework/tensor.h"
17+
#include "paddle/fluid/operators/conv_op.h"
18+
#include "paddle/fluid/platform/mkldnn_helper.h"
19+
20+
namespace paddle {
21+
namespace operators {
22+
23+
using paddle::framework::Tensor;
24+
using paddle::platform::MKLDNNDeviceContext;
25+
using paddle::platform::MKLDNNMemDesc;
26+
27+
using mkldnn::memory; // Note: paddle has also "memory" namespace
28+
using mkldnn::primitive;
29+
using mkldnn::convolution_forward;
30+
using mkldnn::convolution_backward_weights;
31+
using mkldnn::convolution_backward_data;
32+
using mkldnn::convolution_direct;
33+
using mkldnn::prop_kind;
34+
using mkldnn::padding_kind;
35+
using mkldnn::stream;
36+
37+
namespace {
38+
std::unique_ptr<mkldnn::convolution_forward::primitive_desc>
39+
ConvFwdPrimitiveDesc(const memory::desc& src, const memory::desc& weights,
40+
const memory::desc& dst, const std::vector<int>& strides,
41+
const std::vector<int>& paddings,
42+
const mkldnn::engine& engine);
43+
44+
convolution_backward_weights::primitive_desc ConvBwdWeightsPrimitiveDesc(
45+
const memory::desc& src, const memory::desc& diff_weights,
46+
const memory::desc& diff_dst, const std::vector<int>& strides,
47+
const std::vector<int>& paddings,
48+
const convolution_forward::primitive_desc& conv_pd,
49+
const mkldnn::engine& engine);
50+
51+
convolution_backward_data::primitive_desc ConvBwdDataPrimitiveDesc(
52+
const memory::desc& diff_src, const memory::desc& weights,
53+
const memory::desc& diff_dst, const std::vector<int>& strides,
54+
const std::vector<int>& paddings,
55+
const convolution_forward::primitive_desc& conv_pd,
56+
const mkldnn::engine& engine);
57+
} // anonymous namespace
58+
59+
template <typename T>
60+
class ConvOpMkldnnKernel : public paddle::framework::OpKernel<T> {
61+
public:
62+
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
63+
PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
64+
"It must use CPUPlace.");
65+
66+
auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
67+
const auto& mkldnn_engine = dev_ctx.GetEngine();
68+
69+
auto* input = ctx.Input<Tensor>("Input");
70+
auto* filter = ctx.Input<Tensor>("Filter");
71+
auto* output = ctx.Output<Tensor>("Output");
72+
73+
// Get an unique name from "argument" name of "Output" variable
74+
// This name will be used as key when saving info into device context
75+
const std::string key = ctx.op().Output("Output");
76+
const std::string key_conv_pd = key + "@conv_pd";
77+
78+
std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
79+
std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");
80+
std::vector<int> dilations = ctx.Attr<std::vector<int>>("dilations");
81+
int groups = ctx.Attr<int>("groups");
82+
83+
// TODO(pzelazko-intel) add support for group convolution and dilation
84+
PADDLE_ENFORCE(groups == 1, "group convolution is not implemented yet");
85+
PADDLE_ENFORCE(
86+
dilations.size() == 2 && dilations[0] == 1 && dilations[1] == 1,
87+
"dilation in convolution is not implemented yet");
88+
89+
const T* input_data = input->data<T>();
90+
const T* filter_data = filter->data<T>();
91+
// allocate memory for output
92+
T* output_data = output->mutable_data<T>(ctx.GetPlace());
93+
94+
PADDLE_ENFORCE(input->dims().size() == 4,
95+
"Input must be with 4 dimensions, i.e. NCHW");
96+
PADDLE_ENFORCE(filter->dims().size() == 4,
97+
"Filter must be with 4 dimensions, i.e. OIHW");
98+
99+
std::vector<int> src_tz = paddle::framework::vectorize2int(input->dims());
100+
std::vector<int> weights_tz =
101+
paddle::framework::vectorize2int(filter->dims());
102+
std::vector<int> dst_tz = paddle::framework::vectorize2int(output->dims());
103+
104+
// TODO(pzelazko-intel): support more formats
105+
// memory descriptors for convolution src/weight/dst
106+
auto conv_src_md =
107+
MKLDNNMemDesc(src_tz, memory::data_type::f32, memory::format::nchw);
108+
auto conv_weights_md =
109+
MKLDNNMemDesc(weights_tz, memory::data_type::f32, memory::format::oihw);
110+
auto conv_dst_md =
111+
MKLDNNMemDesc(dst_tz, memory::data_type::f32, memory::format::nchw);
112+
113+
// create memory primitives
114+
auto conv_src_memory =
115+
memory({conv_src_md, mkldnn_engine}, (void*)input_data);
116+
auto conv_weights_memory =
117+
memory({conv_weights_md, mkldnn_engine}, (void*)filter_data);
118+
auto conv_dst_memory = memory({conv_dst_md, mkldnn_engine}, output_data);
119+
120+
std::unique_ptr<convolution_forward::primitive_desc> conv_pd =
121+
ConvFwdPrimitiveDesc(conv_src_md, conv_weights_md, conv_dst_md, strides,
122+
paddings, mkldnn_engine);
123+
124+
// save p_conv_pd into dev_ctx to be referred in backward path
125+
auto p_conv_pd = conv_pd.get();
126+
std::shared_ptr<void> conv_pd_value = std::move(conv_pd);
127+
dev_ctx.SetBlob(key_conv_pd, conv_pd_value);
128+
129+
// create convolution op primitive
130+
auto conv_prim = convolution_forward(*p_conv_pd, conv_src_memory,
131+
conv_weights_memory, conv_dst_memory);
132+
133+
// push op to stream and wait MKLDNN until it's executed
134+
std::vector<primitive> pipeline{conv_prim};
135+
stream(stream::kind::eager).submit(pipeline).wait();
136+
}
137+
};
138+
139+
template <typename T>
140+
class ConvGradOpMkldnnKernel : public paddle::framework::OpKernel<T> {
141+
public:
142+
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
143+
PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
144+
"It must use CPUPlace.");
145+
146+
auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
147+
const auto& mkldnn_engine = dev_ctx.GetEngine();
148+
149+
const Tensor* input = ctx.Input<Tensor>("Input");
150+
const Tensor* filter = ctx.Input<Tensor>("Filter");
151+
const Tensor* output = ctx.Input<Tensor>("Output");
152+
const Tensor* output_grad =
153+
ctx.Input<Tensor>(framework::GradVarName("Output"));
154+
Tensor* input_grad = ctx.Output<Tensor>(framework::GradVarName("Input"));
155+
Tensor* filter_grad = ctx.Output<Tensor>(framework::GradVarName("Filter"));
156+
157+
if (!input_grad && !filter_grad) return;
158+
159+
// Get an unique name from "argument" name of "Output" variable
160+
// This name will be used as key when saving info into device context
161+
const std::string key = ctx.op().Input("Output");
162+
const std::string key_conv_pd = key + "@conv_pd";
163+
164+
std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
165+
std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");
166+
167+
const T* input_data = input->data<T>();
168+
const T* filter_data = filter->data<T>();
169+
const T* output_grad_data = output_grad->data<T>();
170+
T* input_grad_data = nullptr;
171+
T* filter_grad_data = nullptr;
172+
173+
// allocate memory for gradient of input/filter
174+
if (input_grad) {
175+
input_grad_data = input_grad->mutable_data<T>(ctx.GetPlace());
176+
}
177+
if (filter_grad) {
178+
filter_grad_data = filter_grad->mutable_data<T>(ctx.GetPlace());
179+
}
180+
181+
std::vector<int> src_tz = paddle::framework::vectorize2int(input->dims());
182+
std::vector<int> weights_tz =
183+
paddle::framework::vectorize2int(filter->dims());
184+
std::vector<int> dst_tz = paddle::framework::vectorize2int(output->dims());
185+
186+
// TODO(pzelazko-intel): support more formats
187+
auto conv_src_md =
188+
MKLDNNMemDesc(src_tz, memory::data_type::f32, memory::format::nchw);
189+
auto conv_diff_src_md =
190+
MKLDNNMemDesc(src_tz, memory::data_type::f32, memory::format::nchw);
191+
auto conv_weights_md =
192+
MKLDNNMemDesc(weights_tz, memory::data_type::f32, memory::format::oihw);
193+
auto conv_diff_weights_md =
194+
MKLDNNMemDesc(weights_tz, memory::data_type::f32, memory::format::oihw);
195+
auto conv_diff_dst_md =
196+
MKLDNNMemDesc(dst_tz, memory::data_type::f32, memory::format::nchw);
197+
198+
// create memory
199+
auto conv_diff_dst_memory =
200+
memory({conv_diff_weights_md, mkldnn_engine}, (void*)output_grad_data);
201+
// Retrieve conv_pd from device context
202+
std::shared_ptr<void> conv_pd;
203+
convolution_forward::primitive_desc* p_conv_pd;
204+
205+
conv_pd = dev_ctx.GetBlob(key_conv_pd);
206+
PADDLE_ENFORCE(conv_pd != nullptr,
207+
"Fail to find conv_pd in device context");
208+
p_conv_pd =
209+
static_cast<convolution_forward::primitive_desc*>(conv_pd.get());
210+
211+
// create backward conv primitive for weights
212+
if (filter_grad) {
213+
// create primitive descriptor
214+
convolution_backward_weights::primitive_desc conv_bwd_weights_pd =
215+
ConvBwdWeightsPrimitiveDesc(conv_src_md, conv_diff_weights_md,
216+
conv_diff_dst_md, strides, paddings,
217+
*p_conv_pd, mkldnn_engine);
218+
219+
// create memory
220+
auto conv_diff_weights_memory = memory(
221+
{conv_diff_weights_md, mkldnn_engine}, (void*)filter_grad_data);
222+
auto conv_src_memory =
223+
memory({conv_src_md, mkldnn_engine}, (void*)input_data);
224+
225+
// create backward conv primitive for weights
226+
auto conv_bwd_weights_prim = convolution_backward_weights(
227+
conv_bwd_weights_pd, conv_src_memory, conv_diff_dst_memory,
228+
conv_diff_weights_memory);
229+
230+
// push primitive and execute it
231+
std::vector<primitive> pipeline{conv_bwd_weights_prim};
232+
stream(stream::kind::eager).submit(pipeline).wait();
233+
}
234+
235+
if (input_grad) {
236+
// create primitive descriptor
237+
convolution_backward_data::primitive_desc conv_bwd_data_pd =
238+
ConvBwdDataPrimitiveDesc(conv_diff_src_md, conv_weights_md,
239+
conv_diff_dst_md, strides, paddings,
240+
*p_conv_pd, mkldnn_engine);
241+
242+
// create memory
243+
auto conv_diff_src_memory =
244+
memory({conv_diff_src_md, mkldnn_engine}, (void*)input_grad_data);
245+
auto conv_weights_memory =
246+
memory({conv_weights_md, mkldnn_engine}, (void*)filter_data);
247+
248+
// create backward conv primitive for data
249+
auto conv_bwd_data_prim =
250+
convolution_backward_data(conv_bwd_data_pd, conv_diff_dst_memory,
251+
conv_weights_memory, conv_diff_src_memory);
252+
253+
// push primitive and execute it
254+
std::vector<primitive> pipeline{conv_bwd_data_prim};
255+
stream(stream::kind::eager).submit(pipeline).wait();
256+
}
257+
} // Compute()
258+
};
259+
260+
namespace {
261+
std::unique_ptr<convolution_forward::primitive_desc> ConvFwdPrimitiveDesc(
262+
const memory::desc& src, const memory::desc& weights,
263+
const memory::desc& dst, const std::vector<int>& strides,
264+
const std::vector<int>& paddings, const mkldnn::engine& engine) {
265+
mkldnn::memory::dims stride_dims = {strides[0], strides[1]};
266+
mkldnn::memory::dims padding_dims = {paddings[0], paddings[1]};
267+
268+
auto conv_desc = mkldnn::convolution_forward::desc(
269+
mkldnn::prop_kind::forward, mkldnn::convolution_direct, src, weights, dst,
270+
stride_dims, padding_dims, padding_dims, mkldnn::padding_kind::zero);
271+
272+
auto p_conv_pd = new convolution_forward::primitive_desc(conv_desc, engine);
273+
274+
return std::unique_ptr<mkldnn::convolution_forward::primitive_desc>(
275+
p_conv_pd);
276+
}
277+
278+
convolution_backward_weights::primitive_desc ConvBwdWeightsPrimitiveDesc(
279+
const memory::desc& src, const memory::desc& diff_weights,
280+
const memory::desc& diff_dst, const std::vector<int>& strides,
281+
const std::vector<int>& paddings,
282+
const convolution_forward::primitive_desc& conv_pd,
283+
const mkldnn::engine& engine) {
284+
auto conv_bwd_weights_desc = convolution_backward_weights::desc(
285+
convolution_direct, src, diff_weights, diff_dst, strides, paddings,
286+
paddings, padding_kind::zero);
287+
return convolution_backward_weights::primitive_desc(conv_bwd_weights_desc,
288+
engine, conv_pd);
289+
}
290+
291+
convolution_backward_data::primitive_desc ConvBwdDataPrimitiveDesc(
292+
const memory::desc& diff_src, const memory::desc& weights,
293+
const memory::desc& diff_dst, const std::vector<int>& strides,
294+
const std::vector<int>& paddings,
295+
const convolution_forward::primitive_desc& conv_pd,
296+
const mkldnn::engine& engine) {
297+
auto conv_bwd_data_desc = convolution_backward_data::desc(
298+
convolution_direct, diff_src, weights, diff_dst, strides, paddings,
299+
paddings, padding_kind::zero);
300+
return convolution_backward_data::primitive_desc(conv_bwd_data_desc, engine,
301+
conv_pd);
302+
}
303+
} // anonymous namespace
304+
} // namespace operators
305+
} // namespace paddle
306+
307+
namespace ops = paddle::operators;
308+
309+
REGISTER_OP_KERNEL(conv2d, MKLDNN, ::paddle::platform::CPUPlace,
310+
ops::ConvOpMkldnnKernel<float>);
311+
312+
REGISTER_OP_KERNEL(conv2d_grad, MKLDNN, ::paddle::platform::CPUPlace,
313+
ops::ConvGradOpMkldnnKernel<float>);

0 commit comments

Comments
 (0)