1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/core/profiler/utils/cost_utils.h"
17
18 #include <string>
19 #include <vector>
20
21 #include "absl/container/flat_hash_set.h"
22 #include "absl/strings/numbers.h"
23 #include "absl/strings/str_join.h"
24 #include "absl/strings/str_split.h"
25 #include "absl/strings/string_view.h"
26 #include "absl/strings/strip.h"
27 #include "absl/types/optional.h"
28 #include "tensorflow/core/framework/tensor_shape.pb.h"
29 #include "tensorflow/core/framework/types.h"
30 #include "tensorflow/core/framework/types.pb.h"
31 #include "tensorflow/core/grappler/costs/cost_estimator.h"
32 #include "tensorflow/core/grappler/costs/op_context.h"
33 #include "tensorflow/core/grappler/costs/op_performance_data.pb.h"
34 #include "tensorflow/core/platform/logging.h"
35 #include "tensorflow/core/platform/types.h"
36 #include "tensorflow/core/profiler/utils/tf_op_utils.h"
37 #include "tensorflow/core/profiler/utils/xplane_schema.h"
38 #include "tensorflow/core/profiler/utils/xplane_visitor.h"
39
40 namespace tensorflow {
41 namespace profiler {
42
43 namespace {
44
45 // Decode the string that encodes tensor shape and type information and convert
46 // to TensorProperties.
47 // Returns an empty TensorProperties if error or input is "".
48 // See OpKernel::TraceString() to see when the shape is encoded as "".
49 // Input format is <DTYPE>[<dim1>, <dim2>,...]
GetTensorProperties(absl::string_view info)50 static OpInfo::TensorProperties GetTensorProperties(absl::string_view info) {
51 OpInfo::TensorProperties tensor_prop;
52 std::vector<absl::string_view> parts = absl::StrSplit(info, '[');
53 if (parts.size() != 2) return tensor_prop;
54 DataType data_type = DT_INVALID;
55 if (!DataTypeFromString(parts[0], &data_type)) return tensor_prop;
56 tensor_prop.set_dtype(data_type);
57 absl::ConsumeSuffix(&parts[1], "]");
58 if (parts[1].empty()) { // Scalar type.
59 tensor_prop.mutable_shape()->add_dim()->set_size(1);
60 return tensor_prop;
61 }
62 std::vector<absl::string_view> dims = absl::StrSplit(parts[1], ',');
63 for (const auto dim : dims) {
64 int size;
65 if (!absl::SimpleAtoi(dim, &size)) return OpInfo::TensorProperties();
66 tensor_prop.mutable_shape()->add_dim()->set_size(size);
67 }
68 return tensor_prop;
69 }
70
71 } // namespace
72
~TfOpRoofLineCostEstimator()73 TfOpRoofLineCostEstimator::~TfOpRoofLineCostEstimator() {
74 if (!unsupported_ops_.empty()) {
75 LOG(ERROR) << "Unsupported Op for Roofline Cost Analysis are:"
76 << absl::StrJoin(unsupported_ops_, ",");
77 }
78 }
79
GetDeviceInfo(const DeviceProperties & device) const80 grappler::DeviceInfo TfOpRoofLineCostEstimator::GetDeviceInfo(
81 const DeviceProperties& device) const {
82 // Hypothetical devices that is used to measure peak flops and memory bytes
83 // accessed.
84 return grappler::DeviceInfo(/*gigaops=*/1, /*gb_per_sec=*/1);
85 }
86
Predict(const XEventVisitor & event)87 TfOpRoofLineCostEstimator::OpRoofLineStats TfOpRoofLineCostEstimator::Predict(
88 const XEventVisitor& event) {
89 TfOp tf_op;
90 absl::string_view tensor_shapes;
91 event.ForEachStat([&](const XStatVisitor& stat) {
92 if (!stat.Type().has_value()) return;
93 switch (stat.Type().value()) {
94 case StatType::kTfOp:
95 tf_op = ParseTfOpFullname(stat.StrOrRefValue());
96 break;
97 case StatType::kTensorShapes:
98 tensor_shapes = stat.StrOrRefValue();
99 break;
100 }
101 });
102
103 // Return empty OpRoofLineStats if shape is not traced or this is not a tf op.
104 if (tf_op.type.empty() || tensor_shapes.empty()) {
105 return {0ULL, 0ULL, /*inaccurate=*/true};
106 }
107
108 grappler::OpContext op_context;
109 op_context.name = std::string(tf_op.type);
110 op_context.op_info.set_op(op_context.name);
111 for (absl::string_view tensor : ParseTensorShapes(tensor_shapes)) {
112 *op_context.op_info.add_inputs() = GetTensorProperties(tensor);
113 }
114 grappler::Costs costs = PredictCosts(op_context);
115 if (costs.inaccurate) unsupported_ops_.insert(std::string(tf_op.type));
116
117 VLOG(1) << tf_op.type << tensor_shapes
118 << " flops:" << costs.compute_time.count()
119 << " bytes:" << costs.memory_time.count();
120
121 /* The compute_time is measured in nanoseconds, therefore numerically it is
122 * equal to flops because giga ops / second cancel the nanoseconds.
123 * Same for memory_time */
124 return {/*flops=*/static_cast<uint64>(costs.compute_time.count()),
125 /*bytes_accessed=*/static_cast<uint64>(costs.memory_time.count()),
126 /*inaccurate=*/costs.inaccurate};
127 }
128
129 } // namespace profiler
130 } // namespace tensorflow
131