Skip to content

Commit e235882

Browse files
xiaolil1luotao1
authored andcommitted
Enable MKL-DNN INT8 Concat Kernel. (#16156)
* Enable INT8 Concat Kernel to improve the performance of MobileNet-SSD. test=develop * Optimize UT format. test=develop * Fix UT file address issue. test=develop * Refine the license year. test=develop * Optimize code for new API. test=develop * Restructure INT8 Concat kernel. test=develop
1 parent 171df5b commit e235882

File tree

2 files changed

+223
-21
lines changed

2 files changed

+223
-21
lines changed

paddle/fluid/operators/mkldnn/concat_mkldnn_op.cc

Lines changed: 99 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ limitations under the License. */
1515
#include <memory>
1616
#include "paddle/fluid/operators/concat_op.h"
1717
#include "paddle/fluid/platform/mkldnn_helper.h"
18+
#include "paddle/fluid/platform/mkldnn_reuse.h"
1819

1920
namespace paddle {
2021
namespace operators {
@@ -38,15 +39,20 @@ static void EnforceLayouts(const std::vector<const Tensor*> inputs) {
3839
}
3940

4041
static memory::primitive_desc CreateMemPrimDesc(const Tensor& input,
41-
const mkldnn::engine& engine) {
42-
constexpr auto data_type = mkldnn::memory::f32;
42+
const mkldnn::engine& engine,
43+
const memory::data_type& dt) {
4344
const auto dims = paddle::framework::vectorize2int(input.dims());
4445
const auto format = input.format();
45-
auto description = memory::desc(dims, data_type, format);
46+
auto description = memory::desc(dims, dt, format);
4647
auto mem_prim_desc = memory::primitive_desc(description, engine);
4748
return mem_prim_desc;
4849
}
4950

51+
static mkldnn::memory::format GetDstMemFormat(
52+
const concat::primitive_desc& concat_pd) {
53+
return (memory::format)concat_pd.dst_primitive_desc().desc().data.format;
54+
}
55+
5056
static platform::CPUPlace GetCpuPlace(
5157
const paddle::framework::ExecutionContext& ctx) {
5258
auto place = ctx.GetPlace();
@@ -61,14 +67,30 @@ static const mkldnn::engine& GetMKLDNNEngine(
6167
return dev_ctx.GetEngine();
6268
}
6369

70+
std::string CreateKey(const paddle::framework::ExecutionContext& ctx,
71+
const std::vector<const Tensor*> multi_input,
72+
const int64_t& concat_axis, const memory::data_type& dt) {
73+
std::string key;
74+
key.reserve(platform::MKLDNNHandler::MaxKeyLength);
75+
for (size_t i = 0; i < multi_input.size(); i++) {
76+
platform::MKLDNNHandler::AppendKeyDims(
77+
&key, paddle::framework::vectorize2int(multi_input[i]->dims()));
78+
}
79+
platform::MKLDNNHandler::AppendKey(&key, std::to_string(concat_axis));
80+
platform::MKLDNNHandler::AppendKey(&key, ctx.op().Output("Out"));
81+
platform::MKLDNNHandler::AppendKey(&key, std::to_string(dt));
82+
return key;
83+
}
84+
6485
template <typename T>
6586
class ConcatPrimitiveFactory {
6687
public:
6788
concat::primitive_desc CreateConcatPrimDescriptor(
6889
const std::vector<const Tensor*> multi_input, Tensor* output,
69-
int concat_axis, const mkldnn::engine& mkldnn_engine) {
70-
CreateSourcesDescriptors(multi_input, mkldnn_engine);
71-
auto dst_desc = CreateDstMemDescriptor(output);
90+
int concat_axis, const mkldnn::engine& mkldnn_engine,
91+
const memory::data_type& dt = memory::data_type::f32) {
92+
CreateSourcesDescriptors(multi_input, mkldnn_engine, dt);
93+
auto dst_desc = CreateDstMemDescriptor(output, dt);
7294
return concat::primitive_desc(dst_desc, concat_axis, srcs_pd);
7395
}
7496

@@ -79,23 +101,39 @@ class ConcatPrimitiveFactory {
79101
return concat(concat_pd, inputs, dst_mem.get());
80102
}
81103

104+
void SetSrcDataHandleByIndex(const std::vector<memory>& srcs, const size_t& i,
105+
void* handler) {
106+
srcs[i].set_data_handle(handler);
107+
}
108+
109+
void SetDstDataHandle(const memory& dst_mem, void* handler) {
110+
dst_mem.set_data_handle(handler);
111+
}
112+
113+
std::vector<memory> GetSrcs() { return srcs; }
114+
115+
memory GetDst() { return dst_mem.get(); }
116+
82117
private:
83-
memory::desc CreateDstMemDescriptor(Tensor* output) {
118+
memory::desc CreateDstMemDescriptor(Tensor* output,
119+
const memory::data_type& dt) {
84120
auto dst_dims = paddle::framework::vectorize2int(output->dims());
85-
return memory::desc(dst_dims, platform::MKLDNNGetDataType<T>(),
86-
memory::format::any);
121+
return memory::desc(dst_dims, dt, memory::format::any);
87122
}
88123

89124
mkldnn::memory CreateDstMemory(const concat::primitive_desc& concat_pd,
90-
Tensor* output, platform::CPUPlace place) {
125+
Tensor* output,
126+
const platform::CPUPlace& place) {
91127
return memory(concat_pd.dst_primitive_desc(),
92128
output->mutable_data<T>(place));
93129
}
94130

95131
void CreateSourcesDescriptors(const std::vector<const Tensor*> multi_input,
96-
const mkldnn::engine& mkldnn_engine) {
132+
const mkldnn::engine& mkldnn_engine,
133+
const memory::data_type& dt) {
97134
for (size_t i = 0; i < multi_input.size(); i++) {
98-
auto mem_prim_desc = CreateMemPrimDesc(*multi_input[i], mkldnn_engine);
135+
auto mem_prim_desc =
136+
CreateMemPrimDesc(*multi_input[i], mkldnn_engine, dt);
99137
srcs_pd.push_back(mem_prim_desc);
100138
srcs.push_back(
101139
memory(mem_prim_desc, to_void_cast(multi_input[i]->data<T>())));
@@ -120,21 +158,59 @@ template <typename T>
120158
class ConcatMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
121159
public:
122160
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
123-
auto place = GetCpuPlace(ctx);
124-
const auto& mkldnn_engine = GetMKLDNNEngine(ctx);
125-
126161
auto multi_input = ctx.MultiInput<Tensor>("X");
127162
EnforceLayouts(multi_input);
128163
Tensor* output = ctx.Output<Tensor>("Out");
129164
int64_t concat_axis = static_cast<int64_t>(ctx.Attr<int>("axis"));
165+
auto& dev_ctx =
166+
ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
167+
auto place = GetCpuPlace(ctx);
168+
169+
memory::data_type dt =
170+
paddle::framework::ToMKLDNNDataType(multi_input[0]->type());
130171

131172
ConcatPrimitiveFactory<T> prim_creator;
132-
auto concat_pd = prim_creator.CreateConcatPrimDescriptor(
133-
multi_input, output, static_cast<int>(concat_axis), mkldnn_engine);
134-
auto concat = prim_creator.CreateConcatPrimitive(concat_pd, output, place);
135-
stream(stream::kind::eager).submit({concat}).wait();
173+
std::string key = CreateKey(ctx, multi_input, concat_axis, dt);
174+
const std::string key_prim = key + "@concat_p";
175+
const std::string key_concat_pd = key + "@concat_pd";
176+
const std::string key_srcs = key + "@concat_srcs";
177+
const std::string key_dst = key + "@concat_dst";
178+
179+
std::shared_ptr<concat::primitive_desc> concat_pd;
180+
std::shared_ptr<std::vector<memory>> srcs;
181+
std::shared_ptr<memory> dst_mem;
182+
auto concat_p = std::static_pointer_cast<concat>(dev_ctx.GetBlob(key_prim));
183+
184+
if (concat_p == nullptr) {
185+
const auto& mkldnn_engine = dev_ctx.GetEngine();
186+
concat_pd = std::make_shared<concat::primitive_desc>(
187+
prim_creator.CreateConcatPrimDescriptor(multi_input, output,
188+
static_cast<int>(concat_axis),
189+
mkldnn_engine, dt));
190+
concat_p = std::make_shared<concat>(
191+
prim_creator.CreateConcatPrimitive(*concat_pd, output, place));
192+
srcs = std::make_shared<std::vector<memory>>(prim_creator.GetSrcs());
193+
dst_mem = std::make_shared<memory>(prim_creator.GetDst());
194+
dev_ctx.SetBlob(key_prim, concat_p);
195+
dev_ctx.SetBlob(key_concat_pd, concat_pd);
196+
dev_ctx.SetBlob(key_srcs, srcs);
197+
dev_ctx.SetBlob(key_dst, dst_mem);
198+
} else {
199+
srcs = std::static_pointer_cast<std::vector<memory>>(
200+
dev_ctx.GetBlob(key_srcs));
201+
dst_mem = std::static_pointer_cast<memory>(dev_ctx.GetBlob(key_dst));
202+
concat_pd = std::static_pointer_cast<concat::primitive_desc>(
203+
dev_ctx.GetBlob(key_concat_pd));
204+
for (size_t i = 0; i < multi_input.size(); i++) {
205+
prim_creator.SetSrcDataHandleByIndex(
206+
*srcs, i, to_void_cast<T>(multi_input[i]->data<T>()));
207+
}
208+
prim_creator.SetDstDataHandle(*dst_mem, output->mutable_data<T>(place));
209+
}
210+
211+
stream(stream::kind::eager).submit({*concat_p}).wait();
136212

137-
output->set_mkldnn_prim_desc(concat_pd.dst_primitive_desc());
213+
output->set_mkldnn_prim_desc(concat_pd->dst_primitive_desc());
138214
}
139215
};
140216
} // namespace operators
@@ -143,4 +219,6 @@ class ConcatMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
143219
namespace ops = paddle::operators;
144220

145221
REGISTER_OP_KERNEL(concat, MKLDNN, ::paddle::platform::CPUPlace,
146-
ops::ConcatMKLDNNOpKernel<float>)
222+
ops::ConcatMKLDNNOpKernel<float>,
223+
ops::ConcatMKLDNNOpKernel<int8_t>,
224+
ops::ConcatMKLDNNOpKernel<uint8_t>);
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# Copyright (c) 2019 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+
from __future__ import print_function
16+
17+
import unittest
18+
import numpy as np
19+
from paddle.fluid.tests.unittests.op_test import OpTest
20+
21+
22+
class TestConcatOp(OpTest):
23+
def setUp(self):
24+
self.op_type = "concat"
25+
self.use_mkldnn = True
26+
self._cpu_only = True
27+
self.init_axis()
28+
self.init_shape()
29+
self.init_test_data()
30+
self.inputs = {'X': [('x0', self.x0), ('x1', self.x1), ('x2', self.x2)]}
31+
self.attrs = {'axis': self.axis, 'use_mkldnn': True}
32+
33+
self.output = np.concatenate(
34+
(self.x0, self.x1, self.x2), axis=self.axis).astype('int')
35+
36+
self.outputs = {'Out': self.output}
37+
38+
def test_check_output(self):
39+
self.check_output()
40+
41+
#--------------------test concat s8 in with axis 0--------------------
42+
43+
def init_test_data(self):
44+
self.x0 = (np.random.randint(0, 100, self.x0_shape) - 50).astype('int8')
45+
self.x1 = (np.random.randint(0, 80, self.x1_shape) - 30).astype('int8')
46+
self.x2 = (np.random.randint(0, 110, self.x2_shape) - 80).astype('int8')
47+
48+
def init_axis(self):
49+
self.axis = 0
50+
51+
def init_shape(self):
52+
self.x0_shape = [2, 2, 1, 2]
53+
self.x1_shape = [1, 2, 1, 2]
54+
self.x2_shape = [3, 2, 1, 2]
55+
56+
57+
#--------------------test concat u8 in with axis 0--------------------
58+
59+
60+
class TestConcatOp2(TestConcatOp):
61+
def init_test_data(self):
62+
self.x0 = (np.random.randint(0, 100, self.x0_shape)).astype('uint8')
63+
self.x1 = (np.random.randint(0, 50, self.x1_shape)).astype('uint8')
64+
self.x2 = (np.random.randint(0, 80, self.x2_shape)).astype('uint8')
65+
66+
def init_axis(self):
67+
self.axis = 0
68+
69+
def init_shape(self):
70+
self.x0_shape = [2, 1, 5, 5]
71+
self.x1_shape = [1, 1, 5, 5]
72+
self.x2_shape = [3, 1, 5, 5]
73+
74+
75+
def create_test_int8_class(parent):
76+
77+
#--------------------test concat s8/u8 in with axis 1--------------------
78+
79+
class TestAxis1Case(parent):
80+
def init_axis(self):
81+
self.axis = 1
82+
83+
def init_shape(self):
84+
self.x0_shape = [1, 1, 5, 5]
85+
self.x1_shape = [1, 2, 5, 5]
86+
self.x2_shape = [1, 3, 5, 5]
87+
88+
#--------------------test concat s8/u8 in with axis 2--------------------
89+
90+
class TestAxis2Case(parent):
91+
def init_axis(self):
92+
self.axis = 2
93+
94+
def init_shape(self):
95+
self.x0_shape = [2, 3, 4, 5]
96+
self.x1_shape = [2, 3, 5, 5]
97+
self.x2_shape = [2, 3, 6, 5]
98+
99+
#--------------------test concat s8/u8 in with axis 3--------------------
100+
101+
class TestAxis3Case(parent):
102+
def init_axis(self):
103+
self.axis = 3
104+
105+
def init_shape(self):
106+
self.x0_shape = [2, 3, 5, 5]
107+
self.x1_shape = [2, 3, 5, 6]
108+
self.x2_shape = [2, 3, 5, 7]
109+
110+
cls_name_1 = "{0}_axis_{1}".format(parent.__name__, "1")
111+
cls_name_2 = "{0}_axis_{1}".format(parent.__name__, "2")
112+
cls_name_3 = "{0}_axis_{1}".format(parent.__name__, "3")
113+
TestAxis1Case.__name__ = cls_name_1
114+
TestAxis2Case.__name__ = cls_name_2
115+
TestAxis3Case.__name__ = cls_name_3
116+
globals()[cls_name_1] = TestAxis1Case
117+
globals()[cls_name_2] = TestAxis2Case
118+
globals()[cls_name_3] = TestAxis3Case
119+
120+
create_test_int8_class(TestConcatOp)
121+
create_test_int8_class(TestConcatOp2)
122+
123+
if __name__ == '__main__':
124+
unittest.main()

0 commit comments

Comments
 (0)