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
|
#include <chrono>
#include <vector>
#include "caffe2/core/operator.h"
#include "caffe2/core/stats.h"
#include "caffe2/core/tensor.h"
namespace caffe2 {
class StatRegistryCreateOp : public Operator<CPUContext> {
public:
StatRegistryCreateOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
*OperatorBase::Output<std::unique_ptr<StatRegistry>>(0) =
std::unique_ptr<StatRegistry>(new StatRegistry);
return true;
}
};
class StatRegistryExportOp : public Operator<CPUContext> {
public:
StatRegistryExportOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws),
reset_(GetSingleArgument<bool>("reset", true)) {}
bool RunOnDevice() override {
auto registry = InputSize() > 0
? OperatorBase::Input<std::unique_ptr<StatRegistry>>(0).get()
: &StatRegistry::get();
auto* keys = Output(0);
auto* values = Output(1);
auto* timestamps = Output(2);
auto data = registry->publish(reset_);
keys->Resize(data.size());
values->Resize(data.size());
timestamps->Resize(data.size());
auto* pkeys = keys->template mutable_data<std::string>();
auto* pvals = values->template mutable_data<int64_t>();
auto* ptimestamps = timestamps->template mutable_data<int64_t>();
int i = 0;
for (const auto& stat : data) {
pkeys[i] = std::move(stat.key);
pvals[i] = stat.value;
ptimestamps[i] =
std::chrono::nanoseconds(stat.ts.time_since_epoch()).count();
++i;
}
return true;
}
private:
bool reset_;
};
class StatRegistryUpdateOp : public Operator<CPUContext> {
public:
StatRegistryUpdateOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
const auto& keys = Input(0);
const auto& values = Input(1);
auto registry = InputSize() == 3
? OperatorBase::Input<std::unique_ptr<StatRegistry>>(2).get()
: &StatRegistry::get();
CAFFE_ENFORCE_EQ(keys.numel(), values.numel());
ExportedStatList data(keys.numel());
auto* pkeys = keys.data<std::string>();
auto* pvals = values.data<int64_t>();
int i = 0;
for (auto& stat : data) {
stat.key = pkeys[i];
stat.value = pvals[i];
++i;
}
registry->update(data);
return true;
}
};
class TimerInstance {
public:
explicit TimerInstance(const std::string& name)
: running_(false), stat_(name) {}
void begin() {
CAFFE_ENFORCE(!running_, "Called TimerBegin on an already running timer.");
running_ = true;
start_ = std::chrono::high_resolution_clock::now();
}
void end() {
CAFFE_ENFORCE(running_, "Called TimerEnd on a stopped timer.");
using namespace std::chrono;
auto duration = high_resolution_clock::now() - start_;
auto nanos = duration_cast<nanoseconds>(duration).count();
CAFFE_EVENT(stat_, time_ns, nanos);
running_ = false;
}
int64_t get_ns() {
CAFFE_ENFORCE(running_, "Called TimerGet on a stopped timer.");
using namespace std::chrono;
auto duration = high_resolution_clock::now() - start_;
auto nanos = duration_cast<nanoseconds>(duration).count();
return nanos;
}
private:
bool running_;
std::chrono::high_resolution_clock::time_point start_;
struct TimerStat {
CAFFE_STAT_CTOR(TimerStat);
CAFFE_AVG_EXPORTED_STAT(time_ns);
} stat_;
};
struct TimerBeginOp : public Operator<CPUContext> {
TimerBeginOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws),
given_name_(GetSingleArgument<std::string>(
"counter_name",
operator_def.output().Get(0))),
timer_([this]() { return given_name_; }()) {}
bool RunOnDevice() override {
*OperatorBase::Output<TimerInstance*>(0) = &timer_;
timer_.begin();
return true;
}
private:
const std::string given_name_;
TimerInstance timer_;
};
struct TimerEndOp : public Operator<CPUContext> {
TimerEndOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
OperatorBase::Input<TimerInstance*>(0)->end();
return true;
}
};
struct TimerGetAndEndOp : public Operator<CPUContext> {
TimerGetAndEndOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
int64_t nanos = OperatorBase::Input<TimerInstance*>(0)->get_ns();
OperatorBase::Input<TimerInstance*>(0)->end();
auto* res = Output(0);
res->Resize(1);
res->template mutable_data<int64_t>()[0] = nanos;
return true;
}
};
struct TimerGetOp : public Operator<CPUContext> {
TimerGetOp(const OperatorDef& operator_def, Workspace* ws)
: Operator(operator_def, ws) {}
bool RunOnDevice() override {
int64_t nanos = OperatorBase::Input<TimerInstance*>(0)->get_ns();
auto* res = Output(0);
res->Resize();
res->template mutable_data<int64_t>()[0] = nanos;
return true;
}
};
REGISTER_CPU_OPERATOR(StatRegistryCreate, StatRegistryCreateOp);
REGISTER_CPU_OPERATOR(StatRegistryUpdate, StatRegistryUpdateOp);
REGISTER_CPU_OPERATOR(StatRegistryExport, StatRegistryExportOp);
REGISTER_CPU_OPERATOR(TimerBegin, TimerBeginOp);
REGISTER_CPU_OPERATOR(TimerEnd, TimerEndOp);
REGISTER_CPU_OPERATOR(TimerGetAndEnd, TimerGetAndEndOp);
REGISTER_CPU_OPERATOR(TimerGet, TimerGetOp);
OPERATOR_SCHEMA(StatRegistryCreate)
.NumInputs(0)
.NumOutputs(1)
.SetDoc(R"DOC(
Create a StatRegistry object that will contain a map of performance counters
keyed by name. A StatRegistry is used to gather and retrieve performance
counts throughout the caffe2 codebase.
)DOC")
.Output(0, "handle", "A Blob pointing to the newly created StatRegistry.");
OPERATOR_SCHEMA(StatRegistryUpdate)
.NumInputs(2, 3)
.NumOutputs(0)
.SetDoc(R"DOC(
Update the given StatRegistry, or the global StatRegistry,
with the values of counters for the given keys.
)DOC")
.Input(0, "keys", "1D string tensor with the key names to update.")
.Input(1, "values", "1D int64 tensor with the values to update.")
.Input(
2,
"handle",
"If provided, update the given StatRegistry. "
"Otherwise, update the global singleton.");
OPERATOR_SCHEMA(StatRegistryExport)
.NumInputs(0, 1)
.NumOutputs(3)
.Input(
0,
"handle",
"If provided, export values from given StatRegistry."
"Otherwise, export values from the global singleton StatRegistry.")
.Output(0, "keys", "1D string tensor with exported key names")
.Output(1, "values", "1D int64 tensor with exported values")
.Output(2, "timestamps", "The unix timestamp at counter retrieval.")
.Arg(
"reset",
"(default true) Whether to atomically reset the counters afterwards.");
OPERATOR_SCHEMA(TimerBegin)
.NumInputs(0)
.NumOutputs(1)
.SetDoc(R"DOC(
Start a wallclock timer, returning a scalar tensor containing a pointer to it. The timer is stopped by calling **TimerEnd**.
Github Links:
- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc
)DOC")
.Arg("counter_name", "(*str*): name of the timer object; if not set use output name")
.Output(0, "timer", "(*Tensor`<ptr>`*): pointer to a timer object");
OPERATOR_SCHEMA(TimerEnd)
.NumInputs(1)
.NumOutputs(0)
.SetDoc(R"DOC(
Stop a timer started with **TimerBegin**. Publishes a CAFFE_EVENT.
Github Links:
- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc
)DOC")
.Input(0, "timer", "(*Tensor`<ptr>`*): pointer to a timer object; obtained from **TimerBegin** op");
OPERATOR_SCHEMA(TimerGetAndEnd)
.NumInputs(1)
.NumOutputs(1)
.SetDoc(R"DOC(
Queries the current time of a timer in nanos, stops the timer publishing a CAFFE_EVENT.
Github Links:
- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc
<details>
<summary> <b>Example</b> </summary>
**Code**
```
workspace.ResetWorkspace()
timerbegin_op = core.CreateOperator(
"TimerBegin",
[],
["timer"]
)
timerget_op = core.CreateOperator(
"TimerGet",
["timer"],
["nanos"]
)
timerend_op = core.CreateOperator(
"TimerEnd",
["timer"],
[]
)
timergetandend_op = core.CreateOperator(
"TimerGetAndEnd",
["timer"],
["nanos"]
)
// Test TimerBegin/TimerGet/TimerEnd
workspace.RunOperatorOnce(timerbegin_op)
print("timer:", workspace.FetchBlob("timer"))
workspace.RunOperatorOnce(timerget_op)
print("nanos:", workspace.FetchBlob("nanos"))
workspace.RunOperatorOnce(timerend_op)
// Test TimerBegin/TimerGetAndEnd
workspace.RunOperatorOnce(timerbegin_op)
print("timer:", workspace.FetchBlob("timer"))
workspace.RunOperatorOnce(timergetandend_op)
print("nanos:", workspace.FetchBlob("nanos"))
```
**Result**
```
timer: b'timer, a C++ native class of type caffe2::TimerInstance*.'
nanos: 361140
timer: b'timer, a C++ native class of type caffe2::TimerInstance*.'
nanos: [252250]
```
</details>
)DOC")
.Input(0, "timer", "(*Tensor`<ptr>`*): pointer to a timer object; obtained from **TimerBegin** op")
.Output(0, "nanos", "(*Tensor`<int64>`*): scalar tensor containing time in nanoseconds");
OPERATOR_SCHEMA(TimerGet)
.NumInputs(1)
.NumOutputs(1)
.SetDoc(R"DOC(
Queries the current time of a timer object in nanoseconds.
Github Links:
- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc
)DOC")
.Input(0, "timer", "(*Tensor`<ptr>`*): pointer to a timer object; obtained from **TimerBegin** op")
.Output(0, "nanos", "(*Tensor`<int64>`*): scalar containing time in nanoseconds");
CAFFE_KNOWN_TYPE(TimerInstance*);
CAFFE_KNOWN_TYPE(std::unique_ptr<caffe2::StatRegistry>);
} // namespace caffe2
|