/
codegen.cc
399 lines (366 loc) · 14.8 KB
/
codegen.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
* 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 src/relay/backend/contrib/arm_compute_lib/codegen.cc
* \brief Implementation of the Relay -> ACL JSON serializer.
*/
#include <tvm/ir/module.h>
#include <tvm/relay/attrs/nn.h>
#include <tvm/relay/type.h>
#include <memory>
#include <string>
#include <vector>
#include "../../utils.h"
#include "../codegen_json/codegen_json.h"
namespace tvm {
namespace relay {
namespace contrib {
/*!
* \brief Generates an ACLModule from a relay expression. This "compilation"
* does not require ACL since the actual conversion using ACL APIs is
* deferred until creation of the runtime. This step simply serializes the
* relay program into a JSON string.
*/
class ACLJSONSerializer : public backend::contrib::JSONSerializer {
using JSONGraphNode = tvm::runtime::json::JSONGraphNode;
using JSONGraphNodeEntry = tvm::runtime::json::JSONGraphNodeEntry;
public:
ACLJSONSerializer(const std::string& symbol, const Expr& expr) : JSONSerializer(symbol, expr) {}
/*!
* \brief A series of operators that form a composite
* convolution. Supports both nn.conv2d and qnn.conv2d.
*/
struct CompositeConvNode {
const CallNode* pad = nullptr;
const CallNode* conv = nullptr;
const CallNode* bias = nullptr;
const CallNode* activation = nullptr;
const CallNode* requantize = nullptr;
};
/*!
* \brief A series of operators that form a composite
* dense layer. Supports both nn.dense and qnn.dense.
*/
struct CompositeDenseNode {
const CallNode* dense = nullptr;
const CallNode* bias = nullptr;
const CallNode* requantize = nullptr;
};
/*!
* \brief Visit call nodes and generate appropriate JSON node.
*
* \param cn The current call node.
* \return A list of graph entry nodes.
*/
std::vector<JSONGraphNodeEntry> VisitExpr_(const CallNode* cn) override {
if (cn->op.as<OpNode>()) {
return JSONSerializer::VisitExpr_(cn);
}
if (!cn->op.as<FunctionNode>()) {
LOG(FATAL) << "Arm Compute Library JSON runtime does not support calls to "
<< cn->op->GetTypeKey();
}
auto fn = cn->op.as<FunctionNode>();
auto comp = fn->GetAttr<String>(attr::kComposite);
ICHECK(comp.defined()) << "Arm Compute Library JSON runtime only supports composite functions.";
const std::string name = comp.value();
std::shared_ptr<JSONGraphNode> json_node;
if (name == "arm_compute_lib.conv2d" || name == "arm_compute_lib.qnn_conv2d") {
json_node = CreateCompositeConvJSONNode(cn);
} else if (name == "arm_compute_lib.dense" || name == "arm_compute_lib.qnn_dense") {
json_node = CreateCompositeDenseJSONNode(cn);
} else if (name == "arm_compute_lib.avg_pool2d") {
json_node = CreateCompositeAvgPool2DJSONNode(cn);
} else if (name == "arm_compute_lib.l2_pool2d") {
json_node = CreateCompositeL2Pool2DJSONNode(cn);
} else {
LOG(FATAL) << "Unrecognized Arm Compute Library pattern: " << name;
}
return AddNode(json_node, GetRef<Expr>(cn));
}
private:
/*!
* \brief Extract convolution nodes from a composite function.
*
* \param cn The call node of the composite function.
* \return Extracted composite convolution nodes.
*/
static CompositeConvNode UnpackCompositeConvolution(const CallNode* cn) {
CompositeConvNode nodes{};
const auto* fn = cn->op.as<FunctionNode>();
ICHECK(fn);
// Traverse composite convolution function from child to parent
const auto* current_call = fn->body.as<CallNode>();
if (backend::IsOp(current_call, "qnn.requantize")) {
nodes.requantize = current_call;
current_call = current_call->args[0].as<CallNode>();
}
if (backend::IsOp(current_call, "nn.relu")) {
nodes.activation = current_call;
current_call = current_call->args[0].as<CallNode>();
}
if (backend::IsOp(current_call, "nn.bias_add")) {
nodes.bias = current_call;
current_call = current_call->args[0].as<CallNode>();
}
// Enforce a convolution node exists at this point during traversal
if (nodes.requantize) {
ICHECK(backend::IsOp(current_call, "qnn.conv2d"));
} else {
ICHECK(backend::IsOp(current_call, "nn.conv2d"));
}
nodes.conv = current_call;
if (!current_call->args.empty() && current_call->args[0]->IsInstance<CallNode>()) {
current_call = current_call->args[0].as<CallNode>();
if (backend::IsOp(current_call, "nn.pad")) {
nodes.pad = current_call;
}
}
return nodes;
}
/*!
* \brief Create a JSON representation of a composite convolution.
*
* \param cn The call to be represented.
* \return A JSON representation of a specific operator.
*/
std::shared_ptr<JSONGraphNode> CreateCompositeConvJSONNode(const CallNode* cn) {
CompositeConvNode nodes = UnpackCompositeConvolution(cn);
std::string name = "nn.conv2d";
const auto* conv_attr = nodes.conv->attrs.as<Conv2DAttrs>();
ICHECK(conv_attr);
ICHECK(conv_attr->kernel_layout == "OHWI")
<< "Kernel layout must be OHWI, has the module been pre-processed correctly?";
// Inputs must be added in the same order they appear in the relay graph.
std::vector<JSONGraphNodeEntry> inputs;
inputs.push_back(VisitExpr(cn->args[0])[0]);
inputs.push_back(VisitExpr(nodes.conv->args[1])[0]);
if (nodes.requantize) {
name = "qnn.conv2d";
inputs.push_back(VisitExpr(nodes.conv->args[2])[0]); // input zero-point
inputs.push_back(VisitExpr(nodes.conv->args[3])[0]); // kernel zero-point
inputs.push_back(VisitExpr(nodes.conv->args[4])[0]); // input scale
inputs.push_back(VisitExpr(nodes.conv->args[5])[0]); // kernel scale
}
if (nodes.bias) {
inputs.push_back(VisitExpr(nodes.bias->args[1])[0]);
}
if (nodes.requantize) {
inputs.push_back(VisitExpr(nodes.requantize->args[3])[0]); // output scale
inputs.push_back(VisitExpr(nodes.requantize->args[4])[0]); // output zero-point
}
auto json_node = std::make_shared<JSONGraphNode>(name, "kernel", inputs, 1);
SetCallNodeAttribute(json_node, nodes.conv);
// Override attributes
if (nodes.pad) {
const auto* pad_attr = nodes.pad->attrs.as<PadAttrs>();
ICHECK(pad_attr);
auto p = pad_attr->pad_width;
// Convert to TVM layout for now, conversion to ACL layout takes place in runtime.
// Standard convolution pad layout for TVM: top, left, bottom, right.
std::vector<std::string> padding = {std::to_string(p[1][0].as<IntImmNode>()->value),
std::to_string(p[2][0].as<IntImmNode>()->value),
std::to_string(p[1][1].as<IntImmNode>()->value),
std::to_string(p[2][1].as<IntImmNode>()->value)};
std::vector<dmlc::any> padding_attr;
padding_attr.emplace_back(padding);
json_node->SetAttr("padding", padding_attr);
}
if (nodes.activation) {
std::vector<std::string> activation_type = {"relu"};
std::vector<dmlc::any> act_attr;
act_attr.emplace_back(activation_type);
json_node->SetAttr("activation_type", act_attr);
}
return json_node;
}
/*!
* \brief Extract dense nodes from a composite function.
*
* \param cn The call node of the composite function.
* \return Extracted composite convolution nodes.
*/
static CompositeDenseNode UnpackCompositeDense(const CallNode* cn) {
CompositeDenseNode nodes{};
const auto* fn = cn->op.as<FunctionNode>();
ICHECK(fn);
// Traverse composite dense function from child to parent
const auto* current_call = fn->body.as<CallNode>();
if (backend::IsOp(current_call, "qnn.requantize")) {
nodes.requantize = current_call;
current_call = current_call->args[0].as<CallNode>();
}
if (backend::IsOp(current_call, "nn.bias_add")) {
nodes.bias = current_call;
current_call = current_call->args[0].as<CallNode>();
}
// Enforce a dense node exists at this point during traversal
if (nodes.requantize) {
ICHECK(backend::IsOp(current_call, "qnn.dense"));
} else {
ICHECK(backend::IsOp(current_call, "nn.dense"));
}
nodes.dense = current_call;
return nodes;
}
/*!
* \brief Create a JSON representation of a composite dense (fully-connected) operator.
*
* \param cn The call to be represented.
* \return A JSON representation of a specific operator.
*/
std::shared_ptr<JSONGraphNode> CreateCompositeDenseJSONNode(const CallNode* cn) {
CompositeDenseNode nodes = UnpackCompositeDense(cn);
std::string name = "nn.dense";
// Inputs must be added in the same order they appear in the relay graph.
std::vector<JSONGraphNodeEntry> inputs;
inputs.push_back(VisitExpr(cn->args[0])[0]);
inputs.push_back(VisitExpr(nodes.dense->args[1])[0]);
if (nodes.requantize) {
name = "qnn.dense";
inputs.push_back(VisitExpr(nodes.dense->args[2])[0]); // input zero-point
inputs.push_back(VisitExpr(nodes.dense->args[3])[0]); // weight zero-point
inputs.push_back(VisitExpr(nodes.dense->args[4])[0]); // input scale
inputs.push_back(VisitExpr(nodes.dense->args[5])[0]); // weight scale
}
if (nodes.bias) {
inputs.push_back(VisitExpr(nodes.bias->args[1])[0]);
}
if (nodes.requantize) {
inputs.push_back(VisitExpr(nodes.requantize->args[3])[0]); // output scale
inputs.push_back(VisitExpr(nodes.requantize->args[4])[0]); // output zero-point
}
auto json_node = std::make_shared<JSONGraphNode>(name, "kernel", inputs, 1);
SetCallNodeAttribute(json_node, nodes.dense);
return json_node;
}
/*!
* \brief Create a JSON representation of a composite (global) average pooling operator.
*
* A composite function is only created when using the uint8 datatype for these operators.
*
* \param cn The call to be represented.
* \return A JSON representation of a specific operator.
*/
std::shared_ptr<JSONGraphNode> CreateCompositeAvgPool2DJSONNode(const CallNode* cn) {
const auto* fn = cn->op.as<FunctionNode>();
ICHECK(fn);
const auto* cast = fn->body.as<CallNode>();
ICHECK(cast);
const auto* avg_pool = cast->args[0].as<CallNode>();
ICHECK(avg_pool);
const auto* avg_pool_op = avg_pool->op.as<OpNode>();
ICHECK(avg_pool_op);
const std::string name = avg_pool_op->name;
std::vector<JSONGraphNodeEntry> inputs;
inputs.push_back(VisitExpr(cn->args[0])[0]);
auto json_node = std::make_shared<JSONGraphNode>(name, "kernel", inputs, 1);
SetCallNodeAttribute(json_node, avg_pool);
return json_node;
}
/*!
* \brief Create a JSON representation of a composite L2 pooling operator.
*
* \note Relay does not have an operator for L2 pooling, instead we can create
* an equivalent from power(2) + nn.avg_pool2d + sqrt.
*
* \param cn The call to be represented.
* \return A JSON representation of a specific operator.
*/
std::shared_ptr<JSONGraphNode> CreateCompositeL2Pool2DJSONNode(const CallNode* cn) {
const std::string name = "nn.l2_pool2d";
const auto* fn = cn->op.as<FunctionNode>();
ICHECK(fn);
const auto* sqrt = fn->body.as<CallNode>();
ICHECK(sqrt);
const auto* avg_pool = sqrt->args[0].as<CallNode>();
ICHECK(avg_pool);
const auto* pow = avg_pool->args[0].as<CallNode>();
ICHECK(pow);
const auto* exponent = pow->args[1].as<ConstantNode>();
ICHECK(exponent);
ICHECK_EQ(*static_cast<float*>(exponent->data->data), 2) << "Exponent must be 2 for L2 pooling";
std::vector<JSONGraphNodeEntry> inputs;
inputs.push_back(VisitExpr(cn->args[0])[0]);
auto json_node = std::make_shared<JSONGraphNode>(name, "kernel", inputs, 1);
SetCallNodeAttribute(json_node, avg_pool);
return json_node;
}
};
/*!
* \brief Pre-process a module containing functions ready for ACL codegen.
*
* For now we enforce OHWI kernel layout and fold the transforms away.
*
* \param mod The module to be pre-processed.
* \return The processed module.
*/
IRModule PreProcessModule(const IRModule& mod) {
IRModule preprocessed_module;
tvm::Map<String, Array<String>> desired_layouts = {{"nn.conv2d", {"NHWC", "OHWI"}},
{"qnn.conv2d", {"NHWC", "OHWI"}}};
preprocessed_module = transform::ConvertLayout(desired_layouts)(mod);
preprocessed_module = transform::FoldConstant()(preprocessed_module);
return preprocessed_module;
}
TVM_REGISTER_GLOBAL("relay.ext.arm_compute_lib.optimize").set_body_typed(PreProcessModule);
/*!
* \brief Create a runtime module for ACL.
*
* This consists of a series of "serialized functions" which each represent a
* sub-graph to be computed by ACL and will each be executed independently from
* one another. Each function consists of serialized JSON describing the sub-graph
* and serialized constant tensors.
*
* \note The ACL runtime module only supports a single operator per
* sub-graph currently.
*
* \param ref The ext_func Relay expression/module to be executed using extern ops.
* \return A runtime module.
*/
runtime::Module ACLCompiler(const ObjectRef& ref) {
ICHECK(ref->IsInstance<FunctionNode>()) << "The input ref is expected to be a Relay function.";
Function func = Downcast<Function>(ref);
std::string func_name = backend::GetExtSymbol(func);
ACLJSONSerializer serializer(func_name, func);
serializer.serialize();
std::string graph_json = serializer.GetJSON();
auto param_names = serializer.GetParams();
const auto* pf = runtime::Registry::Get("runtime.arm_compute_lib_runtime_create");
ICHECK(pf != nullptr) << "Cannot find JSON runtime module to create";
runtime::Module lib = (*pf)(func_name, graph_json, param_names);
return lib;
}
TVM_REGISTER_GLOBAL("relay.ext.arm_compute_lib").set_body_typed(ACLCompiler);
/*!
* \brief Check whether ACL graph runtime is used.
*
* \return True if ACL graph runtime is enabled, False if not.
*/
inline constexpr bool IsACLRuntimeEnabled() {
#if TVM_GRAPH_RUNTIME_ARM_COMPUTE_LIB
return true;
#else
return false;
#endif
}
TVM_REGISTER_GLOBAL("relay.op.is_arm_compute_runtime_enabled").set_body_typed(IsACLRuntimeEnabled);
} // namespace contrib
} // namespace relay
} // namespace tvm