-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.cpp
More file actions
64 lines (58 loc) · 1.45 KB
/
graph.cpp
File metadata and controls
64 lines (58 loc) · 1.45 KB
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
#include "graph.h"
Node *Graph::addNode(std::unique_ptr<Node> node) {
Node *raw = node.get();
nodes_.push_back(std::move(node));
auto out = raw->output_names();
for (auto &tensor : out) {
if (!value_map_.emplace(tensor, raw).second) {
throw std::runtime_error("Duplicate producer for value: " + tensor);
}
}
return raw;
}
void Graph::constructEdges() {
for (auto &node : nodes_) {
for (auto &tensor : node->input_names()) {
auto it = value_map_.find(tensor);
if (it != value_map_.end()) {
auto parent = it->second;
node->addParent(parent);
parent->addChild(node.get());
}
}
}
built = true;
}
void Graph::topoSort() {
if (!built) {
constructEdges();
}
std::unordered_map<Node *, int> indeg;
std::queue<Node *> q;
indeg.reserve(nodes_.size());
for (auto &node : nodes_) {
Node *n = node.get();
indeg[n] = n->parents().size();
if (indeg[n] == 0) {
q.push(n);
}
}
sorted_nodes_.clear();
sorted_nodes_.reserve(nodes_.size());
while (!q.empty()) {
Node *n = q.front();
q.pop();
sorted_nodes_.push_back(n);
for (auto m : n->children()) {
if (--indeg[m] == 0) {
q.push(m);
}
}
}
if (sorted_nodes_.size() != nodes_.size()) {
throw std::runtime_error(
"Topological sort failed: graph has a cycle or bad edges.");
}
for (Node *n : sorted_nodes_)
n->pending_dependencies().store(n->parents().size());
}