Caffe2 - C++ API
A deep learning, cross platform ML framework
net_simple_refcount.cc
1 #include "caffe2/core/net_simple_refcount.h"
2 #include "caffe2/core/net.h"
3 
4 #include <iostream>
5 #include <set>
6 #include <unordered_map>
7 #include <unordered_set>
8 
9 #include "caffe2/core/operator.h"
10 #include "caffe2/core/static_tracepoint.h"
11 #include "caffe2/core/timer.h"
12 #include "caffe2/proto/caffe2_pb.h"
13 #include "caffe2/utils/proto_utils.h"
14 
15 namespace caffe2 {
16 
17 SimpleRefCountNet::SimpleRefCountNet(
18  const std::shared_ptr<const NetDef>& net_def,
19  Workspace* ws)
20  : SimpleNet(net_def, ws) {
21  VLOG(1) << "Constructing SimpleRefCountNet " << net_def->name();
22  // Construct the "to delete" list.
23  delete_list_.resize(net_def->op_size());
24 
25  std::map<string, int> last_consumed_at;
26  std::set<string> created_by_me;
27  // For each opeartor
28  for (int idx = 0; idx < net_def->op_size(); ++idx) {
29  const auto& op_def = net_def->op(idx);
30  for (const string& in_name : op_def.input()) {
31  last_consumed_at[in_name] = idx;
32  }
33  for (const string& out_name : op_def.output()) {
34  created_by_me.insert(out_name);
35  }
36  }
37  // We do not delete any operator that is not produced by the net, and
38  // any operator that is marked as external_output. Any blob that is not
39  // consumed won't be in the last_consumed_at map, so we don't need to
40  // do anything special.
41  for (auto& kv : last_consumed_at) {
42  if (!created_by_me.count(kv.first)) {
43  kv.second = -1;
44  }
45  }
46  for (const string& name : net_def->external_output()) {
47  last_consumed_at[name] = -1;
48  }
49  // Set up the delete list.
50  for (auto& kv : last_consumed_at) {
51  if (kv.second > 0) {
52  delete_list_[kv.second].push_back(ws->GetBlob(kv.first));
53  VLOG(1) << "NetSimpleRefCountNet: will delete " << kv.first
54  << " at operator #" << kv.second;
55  }
56  }
57 }
58 
59 bool SimpleRefCountNet::Run() {
60  StartAllObservers();
61  VLOG(1) << "Running net " << name_;
62  for (int op_id = 0; op_id < operators_.size(); ++op_id) {
63  auto& op = operators_[op_id];
64  VLOG(1) << "Running operator " << op->debug_def().name() << "("
65  << op->debug_def().type() << ").";
66  bool res = op->Run();
67  if (!res) {
68  LOG(ERROR) << "Operator failed: " << ProtoDebugString(op->debug_def());
69  return false;
70  }
71  for (Blob* blob : delete_list_[op_id]) {
72  blob->Reset();
73  }
74  }
75  StopAllObservers();
76  return true;
77 }
78 
79 REGISTER_NET(simple_refcount, SimpleRefCountNet);
80 
81 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13