This repository was archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathdot.cc
265 lines (238 loc) · 11.8 KB
/
dot.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* \file dot.cc
* \brief CPU Implementation of matrix dot
*/
#include "./dot-inl.h"
#if MXNET_USE_ONEDNN == 1
#include "operator/nn/dnnl/dnnl_batch_dot-inl.h"
#include "operator/nn/dnnl/dnnl_dot-inl.h"
#endif // MXNET_USE_ONEDNN
namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(DotParam);
NNVM_REGISTER_OP(dot)
MXNET_ADD_SPARSE_OP_ALIAS(dot)
.describe(R"doc(Dot product of two arrays.
``dot``'s behavior depends on the input array dimensions:
- 1-D arrays: inner product of vectors
- 2-D arrays: matrix multiplication
- N-D arrays: a sum product over the last axis of the first input and the first
axis of the second input
For example, given 3-D ``x`` with shape `(n,m,k)` and ``y`` with shape `(k,r,s)`, the
result array will have shape `(n,m,r,s)`. It is computed by::
dot(x,y)[i,j,a,b] = sum(x[i,j,:]*y[:,a,b])
Example::
x = reshape([0,1,2,3,4,5,6,7], shape=(2,2,2))
y = reshape([7,6,5,4,3,2,1,0], shape=(2,2,2))
dot(x,y)[0,0,1,1] = 0
sum(x[0,0,:]*y[:,1,1]) = 0
The storage type of ``dot`` output depends on storage types of inputs, transpose option and
forward_stype option for output storage type. Implemented sparse operations include:
- dot(default, default, transpose_a=True/False, transpose_b=True/False) = default
- dot(csr, default, transpose_a=True) = default
- dot(csr, default, transpose_a=True) = row_sparse
- dot(csr, default) = default
- dot(csr, row_sparse) = default
- dot(default, csr) = csr (CPU only)
- dot(default, csr, forward_stype='default') = default
- dot(default, csr, transpose_b=True, forward_stype='default') = default
If the combination of input storage types and forward_stype does not match any of the
above patterns, ``dot`` will fallback and generate output with default storage.
.. Note::
If the storage type of the lhs is "csr", the storage type of gradient w.r.t rhs will be
"row_sparse". Only a subset of optimizers support sparse gradients, including SGD, AdaGrad
and Adam. Note that by default lazy updates is turned on, which may perform differently
from standard updates. For more details, please check the Optimization API at:
https://mxnet.apache.org/versions/master/api/python/docs/api/optimizer/index.html
)doc" ADD_FILELINE)
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr_parser(ParamParser<DotParam>)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"lhs", "rhs"};
})
.set_attr<mxnet::FInferShape>("FInferShape", DotShape)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>)
.set_attr<FInferStorageType>("FInferStorageType", DotForwardInferStorageType)
.set_attr<FResourceRequest>("FResourceRequest",
[](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
.set_attr<THasDeterministicOutput>("THasDeterministicOutput", true)
.set_attr<FCompute>("FCompute<cpu>", DotForward_<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", DotForwardEx<cpu>)
#if MXNET_USE_ONEDNN == 1
.set_attr<bool>("TIsMKLDNN", true)
#endif
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_dot"})
.add_argument("lhs", "NDArray-or-Symbol", "The first input")
.add_argument("rhs", "NDArray-or-Symbol", "The second input")
.add_arguments(DotParam::__FIELDS__());
NNVM_REGISTER_OP(_backward_dot)
.set_num_inputs(3)
.set_num_outputs(2)
.set_attr_parser(ParamParser<DotParam>)
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<FInferStorageType>("FInferStorageType", DotBackwardInferStorageType)
.set_attr<FResourceRequest>("FResourceRequest",
[](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
.set_attr<FCompute>("FCompute<cpu>", DotBackward_<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", DotBackwardEx<cpu>)
.add_arguments(DotParam::__FIELDS__());
#if MXNET_USE_ONEDNN == 1
void DotForwardExDNNL(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
if (SupportDNNLDot(inputs)) {
DNNL_OPCHECK_INIT(false, outputs.size(), inputs, outputs);
DNNLRun(DNNLDotForward<false>, attrs, ctx, inputs, req, outputs);
DNNL_OPCHECK_RUN(DotForward_<cpu>, attrs, ctx, inputs, req, outputs);
} else {
FallBackCompute(DotForward_<cpu>, attrs, ctx, inputs, req, outputs);
}
}
static void BatchDotComputeExCPU(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
if (SupportDNNLBatchDot(inputs)) {
DNNL_OPCHECK_INIT(false, outputs.size(), inputs, outputs);
DNNLRun(DNNLBatchDotForward<false>, attrs, ctx, inputs, req, outputs);
DNNL_OPCHECK_RUN(BatchDotForward_<cpu>, attrs, ctx, inputs, req, outputs);
return;
}
FallBackCompute(BatchDotForward_<cpu>, attrs, ctx, inputs, req, outputs);
}
static bool BatchDotStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 2);
CHECK_EQ(out_attrs->size(), 1);
return DNNLStorageType(attrs, dev_mask, true, dispatch_mode, in_attrs, out_attrs);
}
#endif
NNVM_REGISTER_OP(batch_dot)
.add_alias("_npx_batch_dot")
.describe(R"doc(Batchwise dot product.
``batch_dot`` is used to compute dot product of ``x`` and ``y`` when ``x`` and
``y`` are data in batch, namely N-D (N >= 3) arrays in shape of `(B0, ..., B_i, :, :)`.
For example, given ``x`` with shape `(B_0, ..., B_i, N, M)` and ``y`` with shape
`(B_0, ..., B_i, M, K)`, the result array will have shape `(B_0, ..., B_i, N, K)`,
which is computed by::
batch_dot(x,y)[b_0, ..., b_i, :, :] = dot(x[b_0, ..., b_i, :, :], y[b_0, ..., b_i, :, :])
)doc" ADD_FILELINE)
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr_parser(ParamParser<DotParam>)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"lhs", "rhs"};
})
.set_attr<mxnet::FInferShape>("FInferShape", BatchDotShape<DotParam>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>)
.set_attr<FResourceRequest>("FResourceRequest",
[](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
.set_attr<THasDeterministicOutput>("THasDeterministicOutput", true)
.set_attr<FCompute>("FCompute<cpu>", BatchDotForward_<cpu>)
#if MXNET_USE_ONEDNN == 1
.set_attr<bool>("TIsDNNL", true)
.set_attr<FInferStorageType>("FInferStorageType", BatchDotStorageType)
.set_attr<FComputeEx>("FComputeEx<cpu>", BatchDotComputeExCPU)
#endif
.set_attr<nnvm::FGradient>(
"FGradient",
[](const nnvm::ObjectPtr& n, const std::vector<nnvm::NodeEntry>& ograds) {
const DotParam& param = nnvm::get<DotParam>(n->attrs.parsed);
nnvm::ObjectPtr lhs_grad;
nnvm::ObjectPtr rhs_grad;
std::string lhs_gnode_name = n->attrs.name + "_backward_lhs";
std::string rhs_gnode_name = n->attrs.name + "_backward_rhs";
if (param.transpose_a && param.transpose_b) {
// Gradient of z = dot(x.T, y.T)
// dx = dot(dz, y).T = dot(y.T, dz.T)
// dy = dot(x, dz).T = dot(dz.T, x.T)
lhs_grad = MakeNode(
"batch_dot", lhs_gnode_name, {n->inputs[1], ograds[0]}, &(n->attrs.dict), &n);
rhs_grad = MakeNode(
"batch_dot", rhs_gnode_name, {ograds[0], n->inputs[0]}, &(n->attrs.dict), &n);
} else if (!param.transpose_a && param.transpose_b) {
// Gradient of z = dot(x, y.T)
// dx = dot(dz, y)
// dy = dot(x.T, dz).T = dot(dz.T, x)
auto lhs_attrs_dict = n->attrs.dict;
auto rhs_attrs_dict = n->attrs.dict;
lhs_attrs_dict["transpose_a"] = "false";
lhs_attrs_dict["transpose_b"] = "false";
rhs_attrs_dict["transpose_a"] = "true";
rhs_attrs_dict["transpose_b"] = "false";
lhs_grad = MakeNode(
"batch_dot", lhs_gnode_name, {ograds[0], n->inputs[1]}, &lhs_attrs_dict, &n);
rhs_grad = MakeNode(
"batch_dot", rhs_gnode_name, {ograds[0], n->inputs[0]}, &rhs_attrs_dict, &n);
} else if (param.transpose_a && !param.transpose_b) {
// Gradient of z = dot(x.T, y)
// dx = dot(dz, y.T).T = dot(y, dz.T)
// dy = dot(x, dz)
auto lhs_attrs_dict = n->attrs.dict;
auto rhs_attrs_dict = n->attrs.dict;
lhs_attrs_dict["transpose_a"] = "false";
lhs_attrs_dict["transpose_b"] = "true";
rhs_attrs_dict["transpose_a"] = "false";
rhs_attrs_dict["transpose_b"] = "false";
lhs_grad = MakeNode(
"batch_dot", lhs_gnode_name, {n->inputs[1], ograds[0]}, &lhs_attrs_dict, &n);
rhs_grad = MakeNode(
"batch_dot", rhs_gnode_name, {n->inputs[0], ograds[0]}, &rhs_attrs_dict, &n);
} else {
// Gradient of z = dot(x, y)
// dx = dot(dz, y.T)
// dy = dot(x.T, dz)
auto lhs_attrs_dict = n->attrs.dict;
auto rhs_attrs_dict = n->attrs.dict;
lhs_attrs_dict["transpose_a"] = "false";
lhs_attrs_dict["transpose_b"] = "true";
rhs_attrs_dict["transpose_a"] = "true";
rhs_attrs_dict["transpose_b"] = "false";
lhs_grad = MakeNode(
"batch_dot", lhs_gnode_name, {ograds[0], n->inputs[1]}, &lhs_attrs_dict, &n);
rhs_grad = MakeNode(
"batch_dot", rhs_gnode_name, {n->inputs[0], ograds[0]}, &rhs_attrs_dict, &n);
}
std::vector<nnvm::NodeEntry> ret;
ret.emplace_back(nnvm::NodeEntry{lhs_grad, 0, 0});
ret.emplace_back(nnvm::NodeEntry{rhs_grad, 0, 0});
return ret;
})
.add_argument("lhs", "NDArray-or-Symbol", "The first input")
.add_argument("rhs", "NDArray-or-Symbol", "The second input")
.add_arguments(DotParam::__FIELDS__());
} // namespace op
} // namespace mxnet