Skip to content

Commit edb88b5

Browse files
authored
Update from Facebook (pytorch#8887)
* add opencl + fpga context adds an opencl context inside caffe2/fb which can be used for fpga access * [Caffe2] Force tensor inference checks to be triggered during testing We've started to rely on TensorInference functions more for different analysis. This diff ensures that the TensorInference function's result matches what is expected from the definition of the operator. * Enable building //caffe2:torch with @mode/opt In @mode/opt, python runs out of a PAR, which breaks a lot of assumptions in the code about where templates/ folders live relative to __file__. Rather than introduce hacks with parutil, I simply turn template_path into a parameter for all the relevant functions and thread it through from the top level. * [Caffe2] Fix cost models for DotProduct and Div. Update Tensor Inference for dot product As title. DotProduct states that output is a 1-D tensor (https://caffe2.ai/docs/operators-catalogue.html#dotproduct) though code suggests it is either 0- or 1-D depending on inputs. TensorInference defined to support implementation. * [SG-MoE] Add an option to make the experts NOT as components * [nomnigraph] Rename and fixup convertToNeuralNetOperator API This will make things a bit cleaner * no longer symlink THNN.h and THCUNN.h * forced decoder network (onnx export) Closes pytorch/translate#95 Add networks in ensemble_export.py to create a forced decoding network from PyTorch NMT checkpoints. This network takes an arbitrary numberized (source, target) pair and returns the model score for the translation, including penalties. Vocabulary reduction networks are also supported, but note that target indices which are not in the possible_translation_tokens generated for the source input will be trea * Revert schema change to fix production models Revert schema change to fix production models * MockLogDeviceReader - rebase on FIX # Goal 1), Build a make_mock_log_device_reader using make_mock_reader 2), Replace the real log_device_reader here: https://fburl.com/raihwf1p # Log by D8151734 Real log_device_reader: ``` I0529 20:29:05.373108 954994 tensor.h:839] Tensor print_net/log of type std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >. Dims: (): read_net/ParseOpenTrainingRow:0 I0529 20:29:05.373244 954994 tensor.h:839] Tensor read_net/ParseOpenTrainin * [C2/D2][1/n]: Nonnegative-Constrained Optimization -- log barrier implement log barrier as a regularization method * Add teacher weight screening. Add teacher weight sceening according to teacher labels. If teacher label is zero, we do not use the distill loss in the objective function. * Add NormalizerContext See task for more detail. This implementation is a copy of what exists for RegularizerContext except for how the parameters are defined in the model_definition thrift file. I'll try an alternative implementation which overrides the default arguments of functions instead like for argscopes in tensorflow. https://github.com/pytorch/pytorch/compare/master...MaximeBoucher:update-from-facebook-0939578c068c?expand=1 * Adding cosine similarity option in dot processor Add pairwise cosine similarity option in dot product. Add an option to concate dot product and cosine similarity. Add test cases. * [nomnigraph][redo] Concat elim for sparseNN Same as D7962948, which was reverted because Operator Schema was not defined * [pytorch] Revert pytorch#7918 'Release GIL when copying to shared memory', breaks ASAN Revert this pytorch diff that breaks ASAN when running Filament in dev mode; in opt mode it gives "bad file descriptor" errors. Looks like a race when copying tensors to shared memory in multiple mp.Queue's (which spawn separate threads). https://github.com/pytorch/pytorch/pull/7918/files * [nomnigraph][mobile] Enable nomnigraph by default, use -Oz on nomnigraph related code to reduce code size enables nomnigraph and reduces codesize * [Warmup] Allow both offline incremental training and online training Change plan name on saving side and reading side to support both training type This diff depends on D8128530 and D8168651. * Revert D7802642: [Warmup] Allow both offline incremental training and online training This reverts commit afc213cf9b36cecf75333a788391c4d09f4afccc @bypass-lint An infra SEV is better than not reverting this diff. If you copy this password, see you in SEV Review! @cause_a_sev_many_files * Add legacy grad logic to fix div op on old graphs. Add legacy grad logic to fix div op on old graphs. * Correctly propagate operator failures Propagate errors from operators that throw exceptions and return false * Revert D8374829: [caffe2][nomnigraph][redo] Concat elim for sparseNN This reverts commit 6dda028c463e54bb5c32188bbbe9202107e188a5 @bypass-lint An infra SEV is better than not reverting this diff. If you copy this password, see you in SEV Review! @cause_a_sev_many_files * [Caffe2] Added extra_info to core.DeviceOption(), enforced extra_info to be inherited in scope.DeviceScope extra_info is a newly defined field in DeviceOption proto. This diff added extra_info to the core.DeviceOption(). And, In scope.DeviceScope(), this diff enforce the new scope to inherit the extra_info from old scope. * [opt] hgdirsync wasn't enabled, merge diverged code Here's the damage, P59732616 basically xplat was left behind but had the change from assert to CAFFE_ENFORCE * OMP parallelism over RoIs for RoIAlign op Simpler to parallelize over RoIs. Shouldn't affect other uses as it relies on the number of OMP threads set during startup. PR: pytorch#8562 * Use int64_t for shape in FillOps to avoid overflow of int32 * Implement Rotated RoIAlign op Based on Rotated RPNs as explained in https://arxiv.org/abs/1703.01086. The idea is simple - orientation/angle is added as an RPN anchor parameter and then the angle is further regressed similar to bbox coords. There are some additional changes related to NMS and IoU, but besides that it's a direct extension to Faster-RCNN. Further details in https://fb.quip.com/sZHlA1iMfWPZ. RoIs are represented in [center_x, center_y, width, height, angle] format. `angle` repre * Rotated RoIAlign op CUDA forward implementation CUDA forward impl for D8415490 * RoIAlignRotated op CUDA backward pass implementation TSIA * All remaining fixes to eliminate process_github.sh Most of this diff has already been reviewed separately, except for the parts relating to _thnn/utils.py and _utils._internal.py remove skipIf(True, 'Fbcode') line from process_github.sh replace sed of cpp file with #ifdef to control cudnnDestroy use undo sync-time deletion of .gitattributes, remove process_github.sh switch to using _utils._internal rather than try-import-except This diff also fixes the open-source bug where rebuilds have * Back out "Revert D7802642: [Warmup] Allow both offline incremental training and online training" Original commit changeset: 7707d2efe60e The original diff is backout becuase the online trainer package is backed out. This code would only work with new online trainer package * [easy] improve error log in adagrad op as title * re-allow use of thnn_h_path This fixes cffi usage in OSS * [4/4] [tum] paralyzing layerNorm for GPU full sync as title * add compile=False to pytorch tests, remove hack with pyc * Add shape and type inference for RowWiseArgMax operator See title * Revert D8515341: Back out "Revert D7802642: [Warmup] Allow both offline incremental training and online training" This reverts commit 78167eeef0af16b60f72c82f9dcdda9b41b4dcbd @bypass-lint An infra SEV is better than not reverting this diff. If you copy this password, see you in SEV Review! @cause_a_sev_many_files * [fix-flaky-test] mock_hive_reader_test flaky, because GlobalCounter collects local counts intervally # Problem `MockHiveReader` uses `GlobalCounter` to limit `max_examples`. GlobalCounter on server node collect local counts from worker nodes every 1 sec. This 1 sec delay makes it impossible to limit exactly to the `max_examples`, it will definitely exceed `max_examples`. # Plan Given, ``` Expected num_examples = max_examples + num_examples/sec (Read Speed) x 1 sec (GlobalCounter Sync Int * [Caffe2] Fix FCGradient cost inference. Prevent overflow in cost inference FCGradient missed a factor 2 in the `num_outputs == 3` case. Overflow was occurring with flop calculation for FC. Changed types to `uint64_t` to prevent future problems. * Fix binary ops with empty inputs Fix binary ops with empty inputs * Support the filling of input blob with provided data as title for Biz Integrity case * Back out "Revert D8515341: Back out "Revert D7802642: [Warmup] Allow both offline incremental training and online training"" Original commit changeset: 30c55dd38816 Original diff is reverted due to introducing bad integration test. Fixed the integration test. * [c2][easy] improve pack ops error loggings as desc. * Add ShapeTypeInference for LpNorm operator As desc * Shard test_nn to reduce runtime for each test target Closes pytorch#8793 The current test_nn would time out and be disabled in GreenWarden, and we need to have an option to split it up in order to pass the stress test. Right now GreenWarden roughly allows running 100 test cases in test_nn before timing out, and here we have an option to divide test_nn into 30 shards (with ~40 tests in each shard) to allow for some test suite growth in the future. * Change default caffe2_streams_per_gpu to 1 * Remove IN_SANDCASTLE from common.py and test_nn.py We prefer to disable the failing tests through Sandcastle UI instead. * Add a new class for an updated prof_dag.proto This diff contains: - An updated prof_dag.proto that contains blob profiles. - A class to deserialize this information (serialization is in a follow up diff) - Update to separate profiling information from NeuralNet (and use it as part of the class above). - Unit tests * Lambdarank for SparseNN This diff adds a lambda_rank_layer for SparseNN. changes include 1) Adds support for multi sessions in c2 op 2) Adds support for two different loss functions in c2 op 3) Unit tests for op * Revert D8586950: Back out "Revert D8515341: Back out "Revert D7802642: [Warmup] Allow both offline incremental training and online training"" This reverts commit 012220ed63eccc35659a57b31d16a3625da6317b @bypass-lint An infra SEV is better than not reverting this diff. If you copy this password, see you in SEV Review! @cause_a_sev_many_files * [easy] A few fixups to multithread predictor benchmark (1) support perf on T6 server (2) remove dead code * fix a bug about the map size as title * Fix reduce sum on in-place case. Fix reduce sum on in-place case. * [Warmup] Reland reverted diff Allow both offline incremental training and online training Closes pytorch#8827 fix net transform integration test. Allow offline and online trainer to coexist D7802642. * Add StoreHandlerNotAvailableException Add an exception for a store that is not available or has been deleted. * Use exception handling for fault tolerance, missing KV store Remove status blobs to communication ops so that exceptions propagate on failure. * [C2/D2][2/n]: Nonnegative-Constrained Optimization -- bounded grad proj for simple bounded constrained optimization, incl non-negative box constraints. * [GanH]: Adaptive Weighting with More Estimations With implemented postivity optimization, we now learn adaptive weights with different parameterizations. This improves parameter estimation and training stability. * Revert some changes for landing * Remove AutoNoGIL in StorageSharing * Temporarily disable net_tests * Revert "[Caffe2] Force tensor inference checks to be triggered during testing" This reverts commit 67ef05c22b2f71b4a489695384932f968384a2a4. * Revert "Fix reduce sum on in-place case." This reverts commit 6cb8a8e1b3db7b6d20941b0053e3f3836068eb64. * Revert "Revert "Fix reduce sum on in-place case."" This reverts commit 130a257.
1 parent 055f527 commit edb88b5

File tree

128 files changed

+3819
-757
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

128 files changed

+3819
-757
lines changed

binaries/benchmark_helper.cc

+38-3
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include "observers/observer_config.h"
3232
#include "observers/perf_observer.h"
3333

34+
using std::map;
3435
using std::shared_ptr;
3536
using std::string;
3637
using std::unique_ptr;
@@ -91,6 +92,7 @@ void setOperatorEngine(caffe2::NetDef* net_def, const string& backend) {
9192
void loadInput(
9293
shared_ptr<caffe2::Workspace> workspace,
9394
const bool run_on_gpu,
95+
map<string, caffe2::TensorProtos>& tensor_protos_map,
9496
const string& input,
9597
const string& input_file,
9698
const string& input_dims,
@@ -105,9 +107,11 @@ void loadInput(
105107
input_files.size(),
106108
"Input name and file should have the same number.");
107109
for (int i = 0; i < input_names.size(); ++i) {
108-
caffe2::BlobProto blob_proto;
109-
CAFFE_ENFORCE(caffe2::ReadProtoFromFile(input_files[i], &blob_proto));
110-
workspace->CreateBlob(input_names[i])->Deserialize(blob_proto);
110+
caffe2::TensorProtos tensor_protos;
111+
CAFFE_ENFORCE(
112+
caffe2::ReadProtoFromFile(input_files[i], &tensor_protos));
113+
workspace->CreateBlob(input_names[i]);
114+
tensor_protos_map.insert(std::make_pair(input_names[i], tensor_protos));
111115
}
112116
} else if (input_dims.size() || input_type.size()) {
113117
CAFFE_ENFORCE_GE(
@@ -176,9 +180,38 @@ void loadInput(
176180
}
177181
}
178182

183+
void fillInputBlob(
184+
shared_ptr<caffe2::Workspace> workspace,
185+
map<string, caffe2::TensorProtos>& tensor_protos_map,
186+
int iteration) {
187+
if (tensor_protos_map.empty()) {
188+
return;
189+
}
190+
191+
for (auto& tensor_kv : tensor_protos_map) {
192+
caffe2::Blob* blob = workspace->GetBlob(tensor_kv.first);
193+
if (blob == nullptr) {
194+
blob = workspace->CreateBlob(tensor_kv.first);
195+
}
196+
// todo: support gpu and make this function a tempalte
197+
int protos_size = tensor_kv.second.protos_size();
198+
caffe2::TensorProto* tensor_proto =
199+
tensor_kv.second.mutable_protos(iteration % protos_size);
200+
caffe2::TensorCPU* tensor = blob->GetMutable<caffe2::TensorCPU>();
201+
tensor->Resize(std::vector<caffe2::TIndex>());
202+
if (tensor_proto->data_type() == caffe2::TensorProto::STRING) {
203+
(tensor->mutable_data<std::string>())[0] = tensor_proto->string_data(0);
204+
} else if (tensor_proto->data_type() == caffe2::TensorProto::FLOAT) {
205+
(tensor->mutable_data<float>())[0] = tensor_proto->float_data(0);
206+
}
207+
// todo: for other types
208+
}
209+
}
210+
179211
void runNetwork(
180212
shared_ptr<caffe2::Workspace> workspace,
181213
caffe2::NetDef& net_def,
214+
map<string, caffe2::TensorProtos>& tensor_protos_map,
182215
const bool wipe_cache,
183216
const bool run_individual,
184217
const int warmup,
@@ -194,6 +227,7 @@ void runNetwork(
194227
caffe2::ObserverConfig::initSampleRate(1, 1, 1, run_individual, warmup);
195228
LOG(INFO) << "Running warmup runs.";
196229
for (int i = 0; i < warmup; ++i) {
230+
fillInputBlob(workspace, tensor_protos_map, i);
197231
CAFFE_ENFORCE(net->Run(), "Warmup run ", i, " has failed.");
198232
}
199233

@@ -208,6 +242,7 @@ void runNetwork(
208242
".");
209243
for (int i = 0; i < iter; ++i) {
210244
caffe2::ObserverConfig::initSampleRate(1, 1, 1, 0, warmup);
245+
fillInputBlob(workspace, tensor_protos_map, i);
211246
CAFFE_ENFORCE(net->Run(), "Main run ", i, " has failed.");
212247
if (wipe_cache) {
213248
caffe2::wipe_cache();

binaries/benchmark_helper.h

+7
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#include "caffe2/core/operator.h"
2525
#include "caffe2/utils/string_utils.h"
2626

27+
using std::map;
2728
using std::shared_ptr;
2829
using std::string;
2930
using std::vector;
@@ -73,10 +74,15 @@ void setOperatorEngine(caffe2::NetDef*, const string&);
7374
void loadInput(
7475
shared_ptr<caffe2::Workspace>,
7576
const bool,
77+
map<string, caffe2::TensorProtos>&,
7678
const string&,
7779
const string&,
7880
const string&,
7981
const string&);
82+
void fillInputBlob(
83+
shared_ptr<caffe2::Workspace>,
84+
map<string, caffe2::TensorProtos>&,
85+
int iteration);
8086
void writeOutput(
8187
shared_ptr<caffe2::Workspace>,
8288
const bool,
@@ -86,6 +92,7 @@ void writeOutput(
8692
void runNetwork(
8793
shared_ptr<caffe2::Workspace>,
8894
caffe2::NetDef&,
95+
map<string, caffe2::TensorProtos>&,
8996
const bool,
9097
const bool,
9198
const int,

binaries/caffe2_benchmark.cc

+5
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include "binaries/benchmark_helper.h"
66

77
using std::make_shared;
8+
using std::map;
89
using std::string;
910
using std::vector;
1011

@@ -96,9 +97,12 @@ int main(int argc, char** argv) {
9697
setDeviceType(&net_def, run_dev);
9798
setOperatorEngine(&net_def, caffe2::FLAGS_backend);
9899

100+
map<string, caffe2::TensorProtos> tensor_protos_map;
101+
99102
loadInput(
100103
workspace,
101104
run_on_gpu,
105+
tensor_protos_map,
102106
caffe2::FLAGS_input,
103107
caffe2::FLAGS_input_file,
104108
caffe2::FLAGS_input_dims,
@@ -107,6 +111,7 @@ int main(int argc, char** argv) {
107111
runNetwork(
108112
workspace,
109113
net_def,
114+
tensor_protos_map,
110115
caffe2::FLAGS_wipe_cache,
111116
caffe2::FLAGS_run_individual,
112117
caffe2::FLAGS_warmup,

binaries/tsv_2_proto.cc

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Copyright (c) 2016-present, Facebook, Inc.
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+
17+
#include <sstream>
18+
#include <string>
19+
20+
#include "caffe2/core/blob_serialization.h"
21+
#include "caffe2/core/db.h"
22+
#include "caffe2/core/init.h"
23+
#include "caffe2/core/logging.h"
24+
#include "caffe2/proto/caffe2.pb.h"
25+
#include "caffe2/utils/proto_utils.h"
26+
27+
CAFFE2_DEFINE_string(f_in, "", "The input data file name.");
28+
CAFFE2_DEFINE_string(f_out, "", "The output data file name.");
29+
30+
int main(int argc, char** argv) {
31+
caffe2::GlobalInit(&argc, &argv);
32+
std::ifstream f_in(caffe2::FLAGS_f_in);
33+
std::ofstream f_out(caffe2::FLAGS_f_out);
34+
std::string line;
35+
caffe2::TensorProtos tensor_protos;
36+
while (std::getline(f_in, line)) {
37+
caffe2::TensorProto* data = tensor_protos.add_protos();
38+
data->set_data_type(caffe2::TensorProto::STRING);
39+
data->add_dims(0);
40+
data->add_string_data(line);
41+
data->set_name("text");
42+
}
43+
f_in.close();
44+
std::string output_str;
45+
tensor_protos.SerializeToString(&output_str);
46+
f_out << output_str;
47+
f_out.close();
48+
return 0;
49+
}

caffe2/contrib/opencl/context.cc

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ OpenCLContextSingleton::OpenCLContextSingleton() {
2727
}
2828
device = devices[device_id];
2929

30-
context = cl::Context({device});
30+
context = cl::Context({device});
3131
queue = cl::CommandQueue(context, device);
3232
}
3333

caffe2/contrib/prof/profiling_annotations.h

+66-23
Original file line numberDiff line numberDiff line change
@@ -3,54 +3,97 @@
33
#pragma once
44

55
#include "caffe2/contrib/prof/prof_dag_net.h"
6-
#include "caffe2/core/nomnigraph/include/nomnigraph/Representations/NeuralNet.h"
7-
8-
using nom::repr::Annotation;
96

107
namespace caffe2 {
8+
namespace contrib {
9+
namespace prof {
1110

12-
// Annotations used when profiling a NeuralNetOperator.
13-
class ProfilingOperatorAnnotation : public Annotation {
11+
// Accumulates data points and generates two point summary: mean, stddev.
12+
class TwoNumberStats {
1413
public:
15-
ProfilingOperatorAnnotation()
16-
: Annotation(AnnotationKind::ProfilingOperator) {}
17-
// LLVM-style RTTI implementation.
18-
static bool classof(const Annotation* annotation) {
19-
return annotation->getKind() == AnnotationKind::ProfilingOperator;
14+
TwoNumberStats() : sum_(0), squareSum_(0), count_(0) {}
15+
// To prepopulate state of the TwoNumberStats accumulator.
16+
TwoNumberStats(float mean, float stddev, int count)
17+
: sum_(mean * count),
18+
squareSum_((stddev * stddev + mean * mean) * count),
19+
count_(count) {}
20+
void addPoint(float point) {
21+
sum_ += point;
22+
squareSum_ += point * point;
23+
count_++;
24+
}
25+
float getMean() const {
26+
if (count_ == 0) {
27+
return 0;
28+
}
29+
return sum_ / count_;
2030
}
31+
// Returns population stddev.
32+
float getStddev() const {
33+
if (count_ == 0) {
34+
return 0;
35+
}
36+
return sqrt((count_ * squareSum_ - sum_ * sum_) / (count_ * count_));
37+
}
38+
39+
private:
40+
// Sum of data points.
41+
float sum_;
42+
// Sum of square of data points.
43+
float squareSum_;
44+
// Sample count.
45+
int count_;
46+
};
47+
48+
// Annotations used when profiling a NeuralNetOperator.
49+
class ProfilingOperatorAnnotation {
50+
public:
51+
ProfilingOperatorAnnotation() {}
52+
explicit ProfilingOperatorAnnotation(const ProfDAGProto& stats_proto)
53+
: execution_time_ms_(
54+
stats_proto.execution_time().mean(),
55+
stats_proto.execution_time().stddev(),
56+
stats_proto.execution_time().count()) {}
57+
ProfilingOperatorAnnotation(ProfilingOperatorAnnotation&&) = default;
2158
// Accessors
22-
const Stats& execution_time_ms() const {
59+
const TwoNumberStats& getExecutionTimeMs() const {
2360
return execution_time_ms_;
2461
}
25-
Stats* mutable_execution_time_ms() {
62+
TwoNumberStats* getMutableExecutionTimeMs() {
2663
return &execution_time_ms_;
2764
}
2865

2966
private:
3067
// Statistics for how long this op took to execute.
31-
Stats execution_time_ms_;
68+
TwoNumberStats execution_time_ms_;
3269
};
3370

34-
// Annotations used when profiling a NeuralNetData.
35-
class ProfilingDataAnnotation : public Annotation {
71+
// Annotations used when profiling a NeuralNetData. Data this class
72+
// stores is translatable to/from BlobProfile. Note: translation
73+
// may be lossy due to use of floating point arithmetic.
74+
class ProfilingDataAnnotation {
3675
public:
37-
ProfilingDataAnnotation() : Annotation(AnnotationKind::ProfilingData) {}
38-
// LLVM-style RTTI implementation.
39-
static bool classof(const Annotation* annotation) {
40-
return annotation->getKind() == AnnotationKind::ProfilingData;
41-
}
76+
ProfilingDataAnnotation() {}
77+
explicit ProfilingDataAnnotation(const BlobProfile& profile)
78+
: used_bytes_(
79+
profile.bytes_used().mean(),
80+
profile.bytes_used().stddev(),
81+
profile.bytes_used().count()) {}
82+
ProfilingDataAnnotation(ProfilingDataAnnotation&&) = default;
4283
// Accessors
43-
const Stats& used_bytes() const {
84+
const TwoNumberStats& getUsedBytes() const {
4485
return used_bytes_;
4586
}
46-
Stats* mutable_used_bytes() {
87+
TwoNumberStats* getMutableUsedBytes() {
4788
return &used_bytes_;
4889
}
4990

5091
private:
5192
// Statistics for how much data this tensor/parameter used (per invocation of
5293
// the op that generated the data).
53-
Stats used_bytes_;
94+
TwoNumberStats used_bytes_;
5495
};
5596

97+
} // namespace prof
98+
} // namespace contrib
5699
} // namespace caffe2

caffe2/contrib/prof/profiling_annotations_test.cc

+30-13
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,41 @@
44
#include <gtest/gtest.h>
55

66
namespace caffe2 {
7+
namespace contrib {
8+
namespace prof {
79
namespace {
810

9-
TEST(ProfilingAnnotationsTest, BasicAccess) {
11+
TEST(TwoNumberStatsTest, ComputeAndGetOpStatsSummary) {
12+
// e.g., 2 and 3
13+
TwoNumberStats stats;
14+
stats.addPoint(2);
15+
stats.addPoint(3);
16+
EXPECT_FLOAT_EQ(2.5, stats.getMean());
17+
// Population standard deviation.
18+
EXPECT_FLOAT_EQ(0.5, stats.getStddev());
19+
}
20+
21+
TEST(TwoNumberStatsTest, TestRestore) {
22+
// Expect that restore&recompute is still the same.
23+
// E.g., 2 and 3 (above).
24+
TwoNumberStats stats(2.5, 0.5, 2);
25+
// Expect that restore&recompute is still the same.
26+
EXPECT_FLOAT_EQ(2.5, stats.getMean());
27+
// Population standard deviation.
28+
EXPECT_FLOAT_EQ(0.5, stats.getStddev());
29+
}
30+
31+
TEST(ProfilingAnnotationsTest, BasicAccessToActiveData) {
1032
ProfilingOperatorAnnotation op_annotation;
11-
op_annotation.mutable_execution_time_ms()->sum = 5;
33+
op_annotation.getMutableExecutionTimeMs()->addPoint(5);
34+
EXPECT_EQ(5, op_annotation.getExecutionTimeMs().getMean());
35+
1236
ProfilingDataAnnotation data_annotation;
13-
data_annotation.mutable_used_bytes()->sum = 7;
14-
auto* op_annotation_ptr =
15-
dyn_cast<ProfilingOperatorAnnotation>(&op_annotation);
16-
ASSERT_NE(nullptr, op_annotation_ptr);
17-
EXPECT_EQ(5, op_annotation_ptr->execution_time_ms().sum);
18-
auto* data_annotation_ptr =
19-
dyn_cast<ProfilingDataAnnotation>(&data_annotation);
20-
ASSERT_NE(nullptr, data_annotation_ptr);
21-
EXPECT_EQ(7, data_annotation_ptr->used_bytes().sum);
22-
EXPECT_EQ(nullptr, dyn_cast<ProfilingOperatorAnnotation>(&data_annotation));
23-
EXPECT_EQ(nullptr, dyn_cast<ProfilingDataAnnotation>(&op_annotation));
37+
data_annotation.getMutableUsedBytes()->addPoint(7);
38+
EXPECT_EQ(7, data_annotation.getUsedBytes().getMean());
2439
}
2540

2641
} // namespace
42+
} // namespace prof
43+
} // namespace contrib
2744
} // namespace caffe2

0 commit comments

Comments
 (0)