blob: 789bcaedeac534472bbfa7d78d03d24460ee21aa [file] [log] [blame]
Eric Kunzee5e26762020-10-13 16:11:07 -07001
2// Copyright (c) 2020, ARM Limited.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#include "subgraph_traverser.h"
17
18using namespace TosaReference;
19using namespace Eigen;
20using namespace tosa;
21
22SubgraphTraverser::SubgraphTraverser(TosaSerializationBasicBlock* _block, TosaSerializationHandler* _tsh)
23{
24 block = _block;
25 tsh = _tsh;
26
27 tensors.clear();
28 nodes.clear();
29 nextNodeList.clear();
30}
31
32SubgraphTraverser::~SubgraphTraverser()
33{
34 nextNodeList.clear();
35
36 for (GraphNode* n : nodes)
37 {
38 delete n;
39 }
40 nodes.clear();
41
42 for (TosaReference::Tensor* t : tensors)
43 {
44 if (t->is_allocated())
45 {
46 t->deallocate();
47 }
48 delete t;
49 }
50 tensors.clear();
51}
52
53int SubgraphTraverser::getNumInputTensors() const
54{
55 return inputTensors.size();
56}
57
58TosaReference::Tensor* SubgraphTraverser::getInputTensor(const unsigned int idx) const
59{
60 return inputTensors[idx];
61}
62
63TosaReference::Tensor* SubgraphTraverser::getInputTensorByName(const std::string name) const
64{
65 for (auto t : inputTensors)
66 {
67 if (t->getName() == name)
68 {
69 return t;
70 }
71 }
72
73 return nullptr;
74}
75
76int SubgraphTraverser::getNumOutputTensors() const
77{
78 return outputTensors.size();
79}
80
81TosaReference::Tensor* SubgraphTraverser::getOutputTensor(const unsigned int idx) const
82{
83 return outputTensors[idx];
84}
85
86TosaReference::Tensor* SubgraphTraverser::getOutputTensorByName(const std::string name) const
87{
88 for (auto t : outputTensors)
89 {
90 if (t->getName() == name)
91 {
92 return t;
93 }
94 }
95
96 return nullptr;
97}
98
99int SubgraphTraverser::initializeGraph()
100{
101 char tensor_fullname[1000];
102 int idx = 0;
103 for (auto op : block->GetOperators())
104 {
105 // translated TosaSerializationOperator to GraphNode
106 DType in_dtype = DType_UNKNOWN, out_dtype = DType_UNKNOWN, weight_dtype = DType_UNKNOWN;
107 uint32_t in_rank = 0, out_rank = 0, weight_rank = 0;
108 for (auto name : op->GetInputTensorNames())
109 {
110
111 TosaSerializationTensor* ts = block->GetTensorByName(name);
112 ASSERT_MSG(ts, "SubgraphTraverser: fail to get tensor %s from TosaSerializationHandler", name.c_str());
113
114 if (ts->HasUsage(Usage_WEIGHT))
115 {
116 weight_dtype = ts->GetDtype();
117 weight_rank = ts->GetShape().size();
118 }
119 else if (ts->HasUsage(Usage_INDEX))
120 {
121 // do nothing, but this will prevent tensor's dtype/rank being wrongly used as template argument when initializing this op
122 }
123 else if (ts->HasUsage(Usage_ACTIVATION))
124 {
125 if (ts->GetShape().size() >= in_rank)
126 {
127 in_dtype = ts->GetDtype();
128 in_rank = ts->GetShape().size();
129 }
130 }
131 }
132
133 for (auto name : op->GetOutputTensorNames())
134 {
135
136 TosaSerializationTensor* ts = block->GetTensorByName(name);
137 ASSERT_MSG(ts, "SubgraphTraverser: fail to get tensor %s from TosaSerializationHandler", name.c_str());
138
139 out_dtype = ts->GetDtype();
140 out_rank = ts->GetShape().size();
141 }
142
143 DEBUG_INFO(GT, "Creating operator id_%03u, %8s, %lu input tensors, %lu output tensors", idx,
144 EnumNamesOp()[op->GetOp()], op->GetInputTensorNames().size(), op->GetOutputTensorNames().size());
145
146 GraphNode* cn = OpFactory::newOp(tsh, op->GetOp(), op->GetAttribute(), op->GetQInfo(), idx, in_dtype, in_rank,
147 out_dtype, out_rank, weight_dtype, weight_rank);
148 if (!cn)
149 {
150 if (weight_dtype == DType_UNKNOWN && weight_rank == 0)
151 {
152 fprintf(g_func_debug.func_debug_file,
153 "OpFactory could not allocate op %8s input=(%s rank %d) -> (%s rank %d)",
154 EnumNamesOp()[op->GetOp()], EnumNamesDType()[in_dtype], in_rank, EnumNamesDType()[out_dtype],
155 out_rank);
156 }
157 else
158 {
159 fprintf(g_func_debug.func_debug_file,
160 "OpFactory could not allocate op %8s input=(%s rank %d), weight=(%s rank %d) -> (%s rank %d)",
161 EnumNamesOp()[op->GetOp()], EnumNamesDType()[in_dtype], in_rank, EnumNamesDType()[weight_dtype],
162 weight_rank, EnumNamesDType()[out_dtype], out_rank);
163 }
164
165 for (auto ts : op->GetInputTensors())
166 {
167 fprintf(g_func_debug.func_debug_file, "Input: %s\n", ts->GetName().c_str());
168 }
169
170 for (auto ts : op->GetOutputTensors())
171 {
172 fprintf(g_func_debug.func_debug_file, "Output: %s\n", ts->GetName().c_str());
173 }
174 FATAL_ERROR("Unsupported operation type or rank.");
175 }
176
177 for (auto name : op->GetInputTensorNames())
178 {
179 cn->addInputName(name);
180 }
181
182 for (auto name : op->GetOutputTensorNames())
183 {
184 cn->addOutputName(name);
185 }
186
187 addNode(cn);
188
189 // if node doesn't have any inputs (i.e. CONST)
190 // it should be ready for evaluation
191 if (op->GetInputTensorNames().empty() && !cn->getOnNextNodeList())
192 {
193 addToNextNodeList(cn);
194 }
195
196 idx++;
197 }
198
199 for (auto ts : block->GetTensors())
200 {
201
202 bool is_const = false;
203 if (ts->HasUsage(Usage_WEIGHT))
204 {
205 is_const = true;
206 }
207
208 DEBUG_INFO(GT, "Creating tensor %s", ts->GetName().c_str());
209 TosaReference::Tensor* ct =
210 TensorFactory::newTensor(ts->GetName(), ts->GetDtype(), ts->GetUsage(), ts->GetFormat(), ts->GetShape(),
211 is_const, ts->GetShape().size());
212
213 if (ts->GetNpyFilePtr())
214 {
215 if (ct->allocate())
216 {
217 FATAL_ERROR("Fail to allocate Eigen tensor %s", ct->getName().c_str());
218 }
219
220 bzero(tensor_fullname, sizeof(tensor_fullname));
221 snprintf(tensor_fullname, sizeof(tensor_fullname), "%s/%s", g_func_config.subgraph_dir,
222 ts->GetNpyFilePtr()->c_str());
223 if (ct->readFromNpyFile(tensor_fullname))
224 {
225 FATAL_ERROR("Cannot read input data into graph tensor %s from block %s", ct->getName().c_str(),
226 block->GetName().c_str());
227 }
228 }
229
230 // update this->tensors
231 addTensor(ct);
232 }
233
234 DEBUG_INFO(GT, "Enumerating block %s graph inputs", block->GetName().c_str());
235 for (auto& input_name : block->GetInputs())
236 {
237 TosaReference::Tensor* ct = findTensorByName(input_name);
238 DEBUG_INFO(GT, "input tensor name=%s", input_name.c_str());
239 if (ct)
240 {
241 ct->setIsSubgraphInput();
242 inputTensors.push_back(ct);
243 }
244 else
245 {
246 FATAL_ERROR("loadGraphJson: Fail to find input tensor by name %s", input_name.c_str());
247 }
248 }
249
250 DEBUG_INFO(GT, "Enumerating block %s graph outputs", block->GetName().c_str());
251 for (auto& output_name : block->GetOutputs())
252 {
253 TosaReference::Tensor* ct = findTensorByName(output_name);
254 DEBUG_INFO(GT, "output tensor name=%s\n", output_name.c_str());
255 if (ct)
256 {
257 ct->setIsSubgraphOutput();
258 outputTensors.push_back(ct);
259 }
260 else
261 {
262 FATAL_ERROR("loadGraphJson: Fail to find output tensor by name %s", output_name.c_str());
263 }
264 }
265
266 if (DEBUG_ENABLED(DEBUG_VERB_HIGH, GT))
267 {
268 dumpNextNodeList(g_func_debug.func_debug_file);
269 }
270
271 return 0;
272}
273
274int SubgraphTraverser::isFullyEvaluated() const
275{
276 return nextNodeList.empty();
277}
278
279GraphNode* SubgraphTraverser::getNextNode()
280{
281 GraphNode* nextNode = nextNodeList.front();
282 ASSERT_MSG(nextNode, "SubgraphTraverser::getNextNode(): called with empty next node list");
283 ASSERT_MSG(nextNode->getOnNextNodeList(),
284 "SubgraphTraverser::getNextNode(): internal state error: node is not listed as being on next node list");
285
286 nextNodeList.pop_front();
287
288 nextNode->clearOnNextNodeList();
289 return nextNode;
290}
291
292int SubgraphTraverser::addToNextNodeList(GraphNode* nextNode)
293{
294 ASSERT_MSG(nextNode, "SubgraphTraverser::addToNextNodeList(): called with no node");
295 ASSERT_MSG(!nextNode->getOnNextNodeList(),
296 "SubgraphTraverser::addToNextNodeList(): internal state error: node is already on next node list");
297
298 nextNode->setOnNextNodeList();
299 nextNodeList.push_back(nextNode);
300
301 return 0;
302}
303
304int SubgraphTraverser::evaluateNextNode()
305{
306 if (isFullyEvaluated())
307 return 0;
308
309 GraphNode* currNode = getNextNode();
310
311 DEBUG_INFO(GT, "Evaluating node_%03lu, %8s, output tensor=%s", currNode->getID(), EnumNamesOp()[currNode->getOp()],
312 currNode->getOutputNames()[0].c_str());
313
314 // Sanity check for never-ending loops
315 if (currNode->getEvalCount() >= MAX_EVAL_COUNT && (currNode->getEvalCount() % MAX_EVAL_COUNT) == 0)
316 {
317 WARNING("Node %lu has been evaluated %d times. Loop suspected.", currNode->getID(), currNode->getEvalCount());
318 }
319
320 for (auto ct : currNode->getOutputs())
321 {
322 if (!ct->is_allocated())
323 if (ct->allocate())
324 {
325 FATAL_ERROR("Fail to allocate Eigen tensor %s", ct->getName().c_str());
326 }
327 }
328
329 if (currNode->eval())
330 {
331 FATAL_ERROR("Error evaluating node: %lu\n", currNode->getID());
332 }
333
334 // free input tensor if all of its consumers have all of their outputs ready and it's not block's output
335 for (auto ct : currNode->getInputs())
336 {
337 bool in_use = false;
338 for (auto cn : ct->getConsumers())
339 {
340 if (!cn->hasAllOutputsReady())
341 {
342 in_use = true;
343 }
344 }
345 for (auto name : block->GetOutputs())
346 {
347 if (name == ct->getName())
348 {
349 in_use = true;
350 }
351 }
352 if (!in_use)
353 {
354 ct->deallocate();
355 }
356 }
357
358 // Search the output tensors of this node to see if
359 // there are now new ready nodes available from completing this node
360 for (TosaReference::Tensor* tensor : currNode->getOutputs())
361 {
362 for (GraphNode* node : tensor->getConsumers())
363 {
364 if (!node->getOnNextNodeList() && node->hasAllInputsReady())
365 {
366 addToNextNodeList(node);
367 }
368 }
369 }
370
371 if (DEBUG_ENABLED(DEBUG_VERB_HIGH, GT))
372 {
373 dumpNextNodeList(g_func_debug.func_debug_file);
374 }
375
376 if (g_func_config.dump_intermediates)
377 {
378 currNode->dumpNode(g_func_debug.func_debug_file);
379 for (auto outs : currNode->getOutputs())
380 {
381 outs->dumpTensorParams(g_func_debug.func_debug_file);
382 outs->dumpTensor(g_func_debug.func_debug_file);
383 fprintf(g_func_debug.func_debug_file, "\n");
384 }
385 }
386
387 return 0;
388}
389
390int SubgraphTraverser::dumpNextNodeList(FILE* out) const
391{
392
393 // Dump next node list
394 fprintf(out, "Next node list\n");
395
396 if (nextNodeList.empty())
397 {
398 fprintf(out, "<empty>\n");
399 }
400
401 for (auto gn : nextNodeList)
402 {
403 gn->dumpNode(out);
404 }
405
406 fprintf(out, "Done.\n");
407 return 0;
408}
409
410int SubgraphTraverser::clearAllNodeMarkings()
411{
412 for (GraphNode* currNode : nodes)
413 {
414 currNode->clearNodeMarked();
415 }
416
417 return false;
418}
419
420int SubgraphTraverser::addTensor(TosaReference::Tensor* ct)
421{
422 // Enforce no duplicate tensors/tensor names
423 // O(N), but the number of tensors is small
424 for (TosaReference::Tensor* currTensor : tensors)
425 {
426 if (ct == currTensor || currTensor->getName() == ct->getName())
427 {
428 FATAL_ERROR("Error: Duplicate tensor or tensor name being added to graph: %s\n", ct->getName().c_str());
429 return 1;
430 }
431 }
432
433 tensors.push_back(ct);
434
435 if (ct->getIsSubgraphInput())
436 {
437 inputTensors.push_back(ct);
438 }
439
440 if (ct->getIsSubgraphOutput())
441 {
442 outputTensors.push_back(ct);
443 }
444
445 return 0;
446}
447int SubgraphTraverser::addNode(GraphNode* newNode)
448{
449 // Enforce no duplicate nodes
450 for (GraphNode* currNode : nodes)
451 {
452 if (currNode == newNode)
453 {
454 FATAL_ERROR("Error: duplicate node being added to graph");
455 return 1;
456 }
457 }
458
459 nodes.push_back(newNode);
460
461 return 0;
462}
463
464TosaReference::Tensor* SubgraphTraverser::findTensorByName(const std::string& name) const
465{
466 for (TosaReference::Tensor* currTensor : tensors)
467 {
468 if (currTensor->getName() == name)
469 {
470 return currTensor;
471 }
472 }
473
474 WARNING("Unable to find tensor with name: %s\n", name.c_str());
475
476 return nullptr;
477}
478
479int SubgraphTraverser::linkTensorsAndNodes()
480{
481 // Nodes have a list of input/output tensor names
482 // For each node, read this list, link up the tensors with their inputs/outputs
483 for (GraphNode* currNode : nodes)
484 {
485
486 // Link inputs/consuming nodes
487 for (std::string& name : currNode->getInputNames())
488 {
489 TosaReference::Tensor* t = findTensorByName(name);
490 if (!t)
491 {
492 FATAL_ERROR("linkTensorsAndNodes: Cannot find tensor %s in node %lu\n", name.c_str(),
493 currNode->getID());
494 return 1;
495 }
496
497 if (currNode->addInputTensor(t))
498 {
499 FATAL_ERROR("linkTensorsAndNodes: cannot link tensor %s to node %lu\n", name.c_str(),
500 currNode->getID());
501 return 1;
502 }
503
504 if (t->addConsumer(currNode))
505 {
506 FATAL_ERROR("linkTensorsAndNodes: cannot link consumer node %lu to tensor %s\n", currNode->getID(),
507 name.c_str());
508 return 1;
509 }
510 }
511
512 // Link outputs/producing nodes
513 for (std::string& name : currNode->getOutputNames())
514 {
515 TosaReference::Tensor* t = findTensorByName(name);
516 if (!t)
517 {
518 FATAL_ERROR("linkTensorsAndNodes: Cannot find tensor %s in node %lu\n", name.c_str(),
519 currNode->getID());
520 return 1;
521 }
522
523 if (currNode->addOutputTensor(t))
524 {
525 FATAL_ERROR("linkTensorsAndNodes: cannot link tensor %s to node %lu\n", name.c_str(),
526 currNode->getID());
527 return 1;
528 }
529
530 if (t->setProducer(currNode))
531 {
532 FATAL_ERROR("linkTensorsAndNodes: cannot link producer node %lu to tensor tensor %s\n",
533 currNode->getID(), name.c_str());
534 return 1;
535 }
536 }
537 }
538
539 return 0;
540}
541
542int SubgraphTraverser::validateGraph()
543{
544 // Need to make sure that:
545 // - each tensor is actually used
546 // - input and output tesnsors truly are just input and just output
547 // Graph building already determined that each node has found its input/output tensors
548
549 for (TosaReference::Tensor* currTensor : tensors)
550 {
551
552 if (!currTensor->getProducer() && currTensor->getConsumers().empty())
553 {
554 WARNING("Graph inconsistency: TosaReference::Tensor %s has no producers or consumers\n",
555 currTensor->getName().c_str());
556 return 1;
557 }
558
559 if (currTensor->getIsSubgraphInput())
560 {
561 if (currTensor->getProducer() && currTensor->getProducer()->getOp() != Op_PLACEHOLDER)
562 {
563 WARNING("Graph inconsistency: TosaReference::Tensor %s is a subgraph input and has a producer\n",
564 currTensor->getName().c_str());
565 return 1;
566 }
567 }
568
569 // comment this check out as this is possible when graph have multiple output
570 // for example:
571 // %0 = add(%arg0, %arg1)
572 // %1 = mul(%arg0, %0)
573 // yields(%0, %1)
574 //if (currTensor->getIsSubgraphOutput()) {
575 // if (!currTensor->getConsumers().empty()) {
576 // WARNING ("Graph inconsistency: TosaReference::Tensor %s is a subgraph output and has a consumer\n",
577 // currTensor->getName().c_str());
578 // return 1;
579 // }
580 //}
581
582 if (g_func_config.tosa_profile == 0)
583 {
584 DType dtype = currTensor->getDtype();
585
586 // Float-point disallowed
587 if (dtype == DType_FLOAT)
588 {
589 WARNING("TOSA Base Inference profile selected: All floating point disabled, but %s tensor %s found\n",
590 EnumNamesDType()[dtype], currTensor->getName().c_str());
591 return 1;
592 }
593 }
594 else if (g_func_config.tosa_profile == 1 || g_func_config.tosa_profile == 2)
595 {
596 // Do nothing. All FP types allowed
597 // Currently no implementation difference between Main Inference and Main Training modes
598 }
599 else
600 {
601 FATAL_ERROR("TOSA profile not recognized: %d", g_func_config.tosa_profile);
602 }
603 }
604
605 for (GraphNode* currNode : nodes)
606 {
607 if (currNode->checkTensorAttributes())
608 {
609 WARNING("TosaReference::Tensor attribute check failed");
610 return 1;
611 }
612 }
613
614 if (outputTensors.size() <= 0)
615 {
616 DEBUG_MED(GT, "Graph output tensor empty");
617 return 0;
618 }
619
620 return 0;
621}
622
623int SubgraphTraverser::dumpGraph(FILE* out) const
624{
625 int i = 0;
626
627 fprintf(out, "Full graph dump:\n");
628 for (GraphNode* currNode : nodes)
629 {
630 fprintf(out, "Node [%d]: ", i++);
631 currNode->dumpNode(out);
632 }
633
634 return 0;
635}
636
637int SubgraphTraverser::evaluateAll()
638{
639 // evaluation loop
640 while (!isFullyEvaluated())
641 {
642 if (evaluateNextNode())
643 {
644 return 1;
645 }
646 }
647
648 return 0;
649}