This commit is contained in:
Kevin Darby committed 2019-01-02 17:04:10 -05:00
1 parent eb1b42a5e8
commit 458eb2aef1
1283 files changed
+323373

No files matched your search

@@ -0,0 +1,97 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Build a tree structure based on the TensorFlow model's python code stacks.
// Stats are aggregated from descendants to ancestors.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_CODE_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_CODE_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/profiler/internal/tfprof_node.h"
#include "tensorflow/core/profiler/internal/tfprof_show_multi.h"
#include "tensorflow/core/profiler/internal/tfprof_timeline.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/profile.pb.h"
#include "tensorflow/core/profiler/tfprof_log.pb.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
class PprofProfile {
public:
virtual ~PprofProfile() {}
virtual uint64 AddLocation(const CodeNode* callee,
const CodeNode* caller) = 0;
virtual void AddSample(const CodeNode* leaf,
std::vector<uint64>* call_ids) = 0;
virtual Status WritePprofProfile(const string& filename) = 0;
};
class TFCode : public TFMultiShow {
public:
TFCode() {}
~TFCode() override {}
// Add nodes to the code view. Called before Build()
void AddNode(TFGraphNode* node) override;
// Build the code view structure. Called after all nodes
// are added via AddNode().
void Build() override;
private:
const ShowMultiNode* ShowInternal(const Options& opts,
Timeline* timeline) override;
std::vector<CodeNode*> SearchRoot(std::vector<CodeNode*> roots,
const std::vector<string>& regexes);
std::vector<CodeNode*> PrintScope(const std::vector<CodeNode*> roots,
const Options& opts, int depth,
int last_ident);
std::vector<CodeNode*> Account(const std::vector<CodeNode*>& roots,
const Options& opts);
void Format(const CodeNode* root, const std::vector<CodeNode*>& nodes,
const Options& opts, string* display_str,
MultiGraphNodeProto* proto, std::vector<uint64>* call_ids);
string FormatNode(CodeNode* node, const Options& opts, int64 indent) const;
string FormatNodeMemory(CodeNode* node, int64 bytes, int64 total_bytes) const;
std::unique_ptr<CodeNode> root_;
std::unique_ptr<TFMultiGraphNode> graph_root_;
std::unique_ptr<PprofProfile> pprof_profile_;
std::map<string, std::vector<TFGraphNode*>> grad_nodes_;
std::map<string, TFGraphNode*> forward_nodes_;
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_CODE_H_
@@ -0,0 +1,37 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_CONSTANTS_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_CONSTANTS_H_
namespace tensorflow {
namespace tfprof {
// Op name of root of everything. Aggregates all stats.
static const char* const kTFProfRoot = "_TFProfRoot";
// Op type for nodes that doesn't represent a physical node in the
// TensorFlow model. Only exist as a placehold to aggregate children.
// For example, kTFProfRoot belongs to this type.
static const char* const kTFGraphParent = "_TFGraphParent";
static const char* const kTFScopeParent = "_kTFScopeParent";
// Op type for tf.trainable_variables().
static const char* const kTrainableVarType = "_trainable_variables";
// Op type for tensors in the checkpoint file.
static const char* const kCkptVarType = "_checkpoint_variables";
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_CONSTANTS_H_
@@ -0,0 +1,89 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Build a graph structure based on op inputs/outputs. The graph is a directed
// acyclic graph pointing *from outputs to inputs*.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_GRAPH_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_GRAPH_H_
#include <deque>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/profiler/internal/tfprof_node.h"
#include "tensorflow/core/profiler/internal/tfprof_show.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
// Organize tensorflow ops in a graph structure, pointing from output ops
// to input ops.
class TFGraph : public TFShow {
public:
explicit TFGraph(checkpoint::CheckpointReader* ckpt_reader)
: TFShow(ckpt_reader), root_(nullptr) {}
~TFGraph() override {}
void AddNode(TFGraphNode* node) override;
void Build() override;
private:
const ShowNode* ShowInternal(const Options& opts,
Timeline* timeline) override;
bool ShouldShowIfExtra(const ShowNode* node, const Options& opts,
int depth) const override {
return true;
}
GraphNode* CreateParentNode(const string& name);
std::vector<GraphNode*> SearchRoot(const std::vector<GraphNode*>& roots,
const std::vector<string>& regexes,
std::set<string>* visited);
std::vector<GraphNode*> PrintGraph(const std::vector<GraphNode*> roots,
const Options& opts, int depth,
int last_ident, std::set<string>* visits);
std::vector<GraphNode*> Account(const std::vector<GraphNode*>& roots,
const Options& opts,
std::set<string>* visits);
void Format(const std::vector<GraphNode*> roots, string* display_str,
GraphNodeProto* proto);
MemoryTracker memory_tracker_;
GraphNode* root_;
std::vector<std::unique_ptr<NodeDef>> node_defs_;
std::map<string, std::unique_ptr<TFGraphNode>> parent_nodes_;
std::map<string, std::unique_ptr<GraphNode>> nodes_map_;
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_GRAPH_H_
@@ -0,0 +1,918 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_NODE_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_NODE_H_
#include <map>
#include <set>
#include <string>
#include <vector>
#include "tensorflow/core/framework/allocation_description.pb.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/framework/tensor_description.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/regexp.h"
#include "tensorflow/core/profiler/tfprof_log.pb.h"
#include "tensorflow/core/profiler/tfprof_options.h"
namespace tensorflow {
namespace tfprof {
std::vector<int64> ShapeProtoToVec(const TensorShapeProto& shape_pb);
TensorShapeProto VecToShapeProto(const std::vector<int64>& shape_vec);
class TFGraphNode;
class CallStack {
public:
class Trace {
public:
Trace(const CodeDef::Trace* trace,
const std::map<int64, string>* id_to_string)
: trace_(trace), id_to_string_(id_to_string) {}
const int32 lineno() const { return trace_->lineno(); }
string file() const {
// Backward compatible with old proto files.
if (!trace_->file().empty()) return trace_->file();
return id_to_string_->at(trace_->file_id());
}
string function() const {
// Backward compatible with old proto files.
if (!trace_->function().empty()) return trace_->function();
return id_to_string_->at(trace_->function_id());
}
int32 func_start_line() const { return trace_->func_start_line(); }
private:
const CodeDef::Trace* trace_;
const std::map<int64, string>* id_to_string_;
};
CallStack(const CodeDef& def, const std::map<int64, string>* id_to_string)
: def_(def) {
traces_.reserve(def.traces_size());
for (const auto& t : def_.traces()) {
traces_.emplace_back(&t, id_to_string);
}
}
const CodeDef& code_def() const { return def_; }
const std::vector<Trace>& traces() const { return traces_; }
private:
std::vector<Trace> traces_;
CodeDef def_;
};
class ExecStep {
public:
ExecStep() {}
void AddTimeStats(const string& dev, const NodeExecStats& step_stat);
void AddMemoryStats(const string& dev, const NodeExecStats& step_stat);
int64 run_count() const { return exec_.run_count(); }
// The execution time of an op. If it runs on accelerator, then it's
// accelerator_exec_micros(). Otherwise, it's CPU time.
int64 exec_micros() const;
// The accelerator execution time of an op. 0 if not run on accelerator.
int64 accelerator_exec_micros() const;
// The cpu execution time of an op.
int64 cpu_exec_micros() const;
const std::map<string, std::vector<std::pair<int64, int64>>>& op_execs()
const {
return op_execs_;
}
const std::map<string, std::vector<std::pair<int64, int64>>>& cpu_execs()
const {
return cpu_execs_;
}
int64 all_start_micros() const { return exec_.all_start_micros(); }
int64 latest_end_micros() const { return exec_.latest_end_micros(); }
int64 lastest_schedule_end_micros() const {
int64 ret = 0;
for (const auto& exec : cpu_execs_) {
for (const auto& pair : exec.second) {
ret = std::max(ret, pair.first + pair.second);
}
}
return ret;
}
int64 requested_bytes() const {
int64 requested_bytes = 0;
for (const ExecMemory& exec : memory_execs_) {
requested_bytes += exec.requested_bytes();
}
return requested_bytes;
}
int64 peak_bytes() const {
int64 peak_bytes = 0;
for (const ExecMemory& exec : memory_execs_) {
peak_bytes += exec.peak_bytes();
}
return peak_bytes;
}
int64 residual_bytes() const {
int64 residual_bytes = 0;
for (const ExecMemory& exec : memory_execs_) {
residual_bytes += exec.residual_bytes();
}
return residual_bytes;
}
int64 output_bytes() const {
int64 output_bytes = 0;
for (const ExecMemory& exec : memory_execs_) {
output_bytes += exec.output_bytes();
}
return output_bytes;
}
int64 accelerator_temp_bytes() const {
int64 accelerator_temp_bytes = 0;
for (const ExecMemory& exec : memory_execs_) {
accelerator_temp_bytes += exec.accelerator_temp_bytes();
}
return accelerator_temp_bytes;
}
int64 host_temp_bytes() const {
int64 host_temp_bytes = 0;
for (const ExecMemory& exec : memory_execs_) {
host_temp_bytes += exec.host_temp_bytes();
}
return host_temp_bytes;
}
int64 accelerator_persistent_bytes() const {
int64 accelerator_persistent_bytes = 0;
for (const ExecMemory& exec : memory_execs_) {
accelerator_persistent_bytes += exec.accelerator_persistent_bytes();
}
return accelerator_persistent_bytes;
}
int64 host_persistent_bytes() const {
int64 host_persistent_bytes = 0;
for (const ExecMemory& exec : memory_execs_) {
host_persistent_bytes += exec.host_persistent_bytes();
}
return host_persistent_bytes;
}
std::map<int64, int64> allocator_bytes_in_use() const {
std::map<int64, int64> bytes_in_use;
for (const ExecMemory& exec : memory_execs_) {
bytes_in_use[exec.memory_micros()] = exec.allocator_bytes_in_use();
}
return bytes_in_use;
}
const std::vector<AllocationRecord>& allocations() const {
return allocations_;
}
const ExecProfile& ToProto() {
exec_.mutable_accelerator_execs()->clear();
for (const auto& e : accelerator_execs_) {
auto& exec_time = (*exec_.mutable_accelerator_execs())[e.first];
for (const auto& p : e.second) {
auto* t = exec_time.mutable_times()->Add();
t->add_int64_values(p.first);
t->add_int64_values(p.second);
}
}
exec_.mutable_cpu_execs()->clear();
for (const auto& e : cpu_execs_) {
auto& exec_time = (*exec_.mutable_cpu_execs())[e.first];
for (const auto& p : e.second) {
auto* t = exec_time.mutable_times()->Add();
t->add_int64_values(p.first);
t->add_int64_values(p.second);
}
}
exec_.mutable_devices()->Clear();
exec_.mutable_devices()->Reserve(devices_.size());
for (const string& d : devices_) {
exec_.add_devices(d);
}
exec_.mutable_allocations()->Clear();
for (const auto& r : allocations_) {
exec_.add_allocations()->MergeFrom(r);
}
exec_.mutable_memory_execs()->Clear();
for (const auto& m : memory_execs_) {
exec_.add_memory_execs()->MergeFrom(m);
}
return exec_;
}
void FromProto(const ExecProfile& exec) {
exec_.Clear();
exec_.MergeFrom(exec);
devices_.clear();
devices_.insert(exec.devices().begin(), exec.devices().end());
accelerator_execs_.clear();
cpu_execs_.clear();
op_execs_.clear();
allocations_.clear();
memory_execs_.clear();
for (const auto& exec_time : exec_.accelerator_execs()) {
auto& exec = accelerator_execs_[exec_time.first];
auto& op_exec = op_execs_[exec_time.first];
for (const auto& p : exec_time.second.times()) {
exec.push_back(std::make_pair(p.int64_values(0), p.int64_values(1)));
op_exec.push_back(std::make_pair(p.int64_values(0), p.int64_values(1)));
}
}
for (const auto& exec_time : exec_.cpu_execs()) {
auto& exec = cpu_execs_[exec_time.first];
auto& op_exec = op_execs_[exec_time.first];
for (const auto& p : exec_time.second.times()) {
exec.push_back(std::make_pair(p.int64_values(0), p.int64_values(1)));
op_exec.push_back(std::make_pair(p.int64_values(0), p.int64_values(1)));
}
}
for (const auto& r : exec_.allocations()) {
allocations_.push_back(r);
}
for (const auto& m : exec_.memory_execs()) {
memory_execs_.push_back(m);
}
}
private:
ExecProfile exec_;
// device -> vector of {op_start_micros, op_exec_micros} pairs.
// accelerator_execs: gpu:id/stream:all -> {op_start_micros, op_exec_micros}
// For accelerator, vector size can be larger than 1, multiple kernel fires
// or in tf.while_loop.
std::map<string, std::vector<std::pair<int64, int64>>> accelerator_execs_;
// cpu_execs: cpu/gpu:id -> {op_start_micros, op_exec_micros}
// For cpu, vector size can be larger than 1 if in tf.while_loop.
std::map<string, std::vector<std::pair<int64, int64>>> cpu_execs_;
// combines accelerator_execs_ and cpu_execs_.
std::map<string, std::vector<std::pair<int64, int64>>> op_execs_;
// Each ExecMemory corresponds to one scheduling of the op. Normally,
// there are multiple schedulings in while_loop.
std::vector<ExecMemory> memory_execs_;
// All devices the op is associated with (e.g. gpu:0 (scheduling),
// gpu:0:stream:xx (kernel exec), cpu:0 host)
std::set<string> devices_;
// The history of accelerator allocations and deallocations of this step.
std::vector<AllocationRecord> allocations_;
};
#define GRAPH_NODE_BYTES(type) \
do { \
if (execs_.empty()) { \
return 0; \
} \
if (step >= 0) { \
auto exec = execs_.find(step); \
if (exec == execs_.end()) return 0; \
return exec->second.type##_bytes(); \
} \
\
int64 bytes = 0; \
for (const auto& exec : execs_) { \
bytes += exec.second.type##_bytes(); \
} \
return bytes / execs_.size(); \
} while (0)
class TFGraphNode {
public:
TFGraphNode(const ProfileNode& node, const ProfileProto& profile,
const std::map<int64, string>* id_to_string,
const std::map<string, std::unique_ptr<TFGraphNode>>* nodes_map) {
nodes_map_ = nodes_map;
FromProto(node, profile, id_to_string);
}
TFGraphNode(const NodeDef* node, int64 id,
const std::map<string, std::unique_ptr<TFGraphNode>>* nodes_map) {
nodes_map_ = nodes_map;
node_.set_id(id);
node_.set_name(node->name());
node_.set_op(node->op());
node_.set_float_ops(0);
for (const auto& attr : node->attr()) {
(*node_.mutable_attrs())[attr.first].MergeFrom(attr.second);
if (attr.first == "shape" && attr.second.has_shape()) {
if (!shape_.empty()) {
fprintf(stderr, "Found duplicated shapes!\n");
continue;
}
shape_ = ShapeProtoToVec(attr.second.shape());
} else if (attr.first == "_output_shapes" && attr.second.has_list()) {
if (!output_shapes_.empty()) {
fprintf(stderr, "Found duplicated output shapes!\n");
continue;
}
for (int i = 0; i < attr.second.list().shape_size(); ++i) {
output_shapes_[i] = ShapeProtoToVec(attr.second.list().shape(i));
}
}
}
op_types_.insert(node->op());
}
void AddInput(const string& input, int64 output_index, int input_idx) {
inputs_[input_idx] = input;
src_output_idx_[input] = output_index;
}
void AddOpType(const string& op_type) { op_types_.insert(op_type); }
void AddStepStat(int64 step, const string& device,
const NodeExecStats& step_stat);
void AddFloatOps(int64 float_ops) { node_.set_float_ops(float_ops); }
// TODO(xpan): This could take a lot of memory.
void AddCode(const CodeDef& code,
const std::map<int64, string>* id_to_string) {
if (!call_stack_) {
call_stack_.reset(new CallStack(code, id_to_string));
}
}
const string& name() const { return node_.name(); }
int64 id() const { return node_.id(); }
const string& op() const { return node_.op(); }
const ProfileNode& node() { return node_; }
bool trackable(int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) return false;
if (exec->second.all_start_micros() == 0) return false;
if (node_.canonical_device().empty() || node_.host_device().empty()) {
return false;
}
return true;
}
const ProfileNode& ToProto(
const std::map<string, std::unique_ptr<TFGraphNode>>& nodes_map) {
node_.clear_shape();
node_.mutable_shape()->Reserve(shape().size());
for (int64 s : shape()) {
node_.add_shape(s);
}
node_.clear_op_types();
node_.mutable_op_types()->Reserve(op_types().size());
for (const string& t : op_types()) {
node_.add_op_types(t);
}
node_.clear_execs();
for (auto& exec : execs_) {
auto& exec_pb = (*node_.mutable_execs())[exec.first];
exec_pb.MergeFrom(exec.second.ToProto());
}
node_.clear_inputs();
for (const auto& inp : inputs_) {
(*node_.mutable_inputs())[inp.first] = nodes_map.at(inp.second)->id();
}
node_.clear_input_shapes();
for (const auto& s : input_shapes_) {
auto& shape = (*node_.mutable_input_shapes())[s.first];
for (int64 d : s.second) {
shape.add_int64_values(d);
}
}
node_.clear_output_shapes();
for (const auto& s : output_shapes_) {
auto& shape = (*node_.mutable_output_shapes())[s.first];
for (int64 d : s.second) {
shape.add_int64_values(d);
}
}
node_.clear_src_output_index();
for (const auto& s : src_output_idx_) {
int64 id = nodes_map.at(s.first)->id();
(*node_.mutable_src_output_index())[id] = s.second;
}
if (call_stack_) {
node_.clear_trace();
node_.mutable_trace()->MergeFrom(call_stack_->code_def());
}
return node_;
}
void FromProto(const ProfileNode& node, const ProfileProto& profile,
const std::map<int64, string>* id_to_string) {
node_.Clear();
node_.MergeFrom(node);
call_stack_.reset(new CallStack(node.trace(), id_to_string));
op_types_.clear();
op_types_.insert(node_.op_types().begin(), node_.op_types().end());
shape_.clear();
for (int64 s : node_.shape()) {
shape_.push_back(s);
}
execs_.clear();
for (const auto& exec_pb : node.execs()) {
auto& exec = execs_[exec_pb.first];
exec.FromProto(exec_pb.second);
}
inputs_.clear();
for (const auto& inp : node.inputs()) {
inputs_[inp.first] = profile.nodes().at(inp.second).name();
}
input_shapes_.clear();
for (const auto& s : node.input_shapes()) {
auto& shape = input_shapes_[s.first];
for (const int64 d : s.second.int64_values()) {
shape.push_back(d);
}
}
output_shapes_.clear();
for (const auto& s : node.output_shapes()) {
auto& shape = output_shapes_[s.first];
for (const int64 d : s.second.int64_values()) {
shape.push_back(d);
}
}
src_output_idx_.clear();
for (const auto& s : node.src_output_index()) {
src_output_idx_[profile.nodes().at(s.first).name()] = s.second;
}
}
const std::map<int32, string>& inputs() const { return inputs_; }
// Number of times the graph node is executed. When step < 0, the
// average number of times executed across all steps.
int64 run_count(int64 step) const {
if (execs_.empty()) {
return 0;
}
if (step >= 0) {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.run_count();
}
int64 total_run_count = 0;
for (const auto& exec : execs_) {
total_run_count += exec.second.run_count();
}
return total_run_count / execs_.size();
}
// This is overall computation time, including both cpu and accelerator.
// Note, cpu and accelerator might or might not run in parallel.
int64 exec_micros(int64 step) const {
// Empty when no RunMetadata is provided.
if (execs_.empty()) {
return 0;
}
if (step >= 0) {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.exec_micros();
}
int64 total_micros = 0;
for (const auto& exec : execs_) {
total_micros += exec.second.exec_micros();
}
return total_micros / execs_.size();
}
// This is accelerator computation time of a step, or average of
// multiple step, when step < 0.
int64 accelerator_exec_micros(int64 step) const {
// Empty when no RunMetadata is provided.
if (execs_.empty()) {
return 0;
}
if (step >= 0) {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.accelerator_exec_micros();
}
int64 total_micros = 0;
for (const auto& exec : execs_) {
total_micros += exec.second.accelerator_exec_micros();
}
return total_micros / execs_.size();
}
// This is cpu computation time of a step, or average of
// multiple step, when step < 0.
int64 cpu_exec_micros(int64 step) const {
// Empty when no RunMetadata is provided.
if (execs_.empty()) {
return 0;
}
if (step >= 0) {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.cpu_exec_micros();
}
int64 total_micros = 0;
for (const auto& exec : execs_) {
total_micros += exec.second.cpu_exec_micros();
}
return total_micros / execs_.size();
}
int64 requested_bytes(int64 step) const { GRAPH_NODE_BYTES(requested); }
int64 peak_bytes(int64 step) const { GRAPH_NODE_BYTES(peak); }
int64 residual_bytes(int64 step) const { GRAPH_NODE_BYTES(residual); }
int64 output_bytes(int64 step) const { GRAPH_NODE_BYTES(output); }
int64 all_start_micros(int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.all_start_micros();
}
int64 latest_end_micros(int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.latest_end_micros();
}
int64 lastest_schedule_end_micros(int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.lastest_schedule_end_micros();
}
const std::map<string, std::vector<std::pair<int64, int64>>>& op_execs(
int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return empty_execs_;
}
return exec->second.op_execs();
}
const std::map<string, std::vector<std::pair<int64, int64>>>& cpu_execs(
int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return empty_execs_;
}
return exec->second.cpu_execs();
}
const std::map<int64, ExecStep>& all_op_execs() const { return execs_; }
int64 accelerator_temp_bytes(int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.accelerator_temp_bytes();
}
int64 host_temp_bytes(int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return 0;
}
return exec->second.host_temp_bytes();
}
int64 accelerator_persistent_bytes() const {
int64 persistent_bytes = 0;
for (const auto& exec : execs_) {
persistent_bytes = std::max(persistent_bytes,
exec.second.accelerator_persistent_bytes());
}
return persistent_bytes;
}
const std::map<int64, int64> allocator_bytes_in_use(int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return empty_bytes_in_use_;
}
return exec->second.allocator_bytes_in_use();
}
const std::vector<AllocationRecord>& allocations(int64 step) const {
auto exec = execs_.find(step);
if (exec == execs_.end()) {
return empty_allocations_;
}
return exec->second.allocations();
}
int64 parameters() const {
if (!shape().empty()) {
int64 params = 1;
bool complete_shape = true;
for (int64 d : shape()) {
// Sometimes parameters could be <0 when a dim is unknown.
if (d < 0) {
complete_shape = false;
break;
}
params *= d;
}
if (complete_shape) {
return params;
} else {
fprintf(stderr, "Incomplete shape.\n");
}
}
return 0;
}
int64 float_ops(int64 step) const {
// If not run, return static analysis.
if (execs_.empty()) {
return node_.float_ops();
}
// Otherwise, return dynamic float_ops.
return node_.float_ops() * run_count(step);
}
const CallStack* call_stack() { return call_stack_.get(); }
string canonical_device() const { return node_.canonical_device(); }
string host_device() const { return node_.host_device(); }
const std::set<string>& op_types() const { return op_types_; }
const AttrValue* op_attrs(const string& name) const {
const auto it = node_.attrs().find(name);
if (it == node_.attrs().end()) {
return nullptr;
}
return &it->second;
}
const std::vector<int64>& shape() const { return shape_; }
const std::map<int, std::vector<int64>>& output_shapes() const {
return output_shapes_;
}
const std::map<int, std::vector<int64>> input_shapes() const {
std::map<int, std::vector<int64>> input_shapes;
for (const auto& inp : inputs_) {
// Always create an empty vec even if the shape info might be missing.
std::vector<int64>& shape_vec = input_shapes[inp.first];
if (!nodes_map_) continue;
auto input_it = nodes_map_->find(inp.second);
if (input_it == nodes_map_->end()) continue;
auto output_it = src_output_idx_.find(inp.second);
if (output_it == src_output_idx_.end()) continue;
const TFGraphNode* input_node = input_it->second.get();
if (!input_node) continue;
const auto& output_shapes = input_node->output_shapes();
const auto& output_shape = output_shapes.find(output_it->second);
if (output_shape == output_shapes.end()) continue;
if (output_shape != input_node->output_shapes().end()) {
shape_vec.assign(output_shape->second.begin(),
output_shape->second.end());
}
}
return input_shapes;
}
private:
// maps graph node name to TFGraphNode. Not owned.
const std::map<string, std::unique_ptr<TFGraphNode>>* nodes_map_;
// inputs to the node. input index -> input node name.
std::map<int, string> inputs_;
// The output index of the source node.
std::map<string, int32> src_output_idx_;
// proto for serialize/deserialized representation of the node.
ProfileNode node_;
// Python call stack that creates the name.
std::unique_ptr<CallStack> call_stack_;
// Shape of the node (e.g. Variable) if available.
std::vector<int64> shape_;
// Won't missing input_idx. But some shapes might be empty (unknown).
std::map<int, std::vector<int64>> input_shapes_;
// Could miss output_idx if no _output_shapes attr. some shapes can also
// be empty.
std::map<int, std::vector<int64>> output_shapes_;
std::set<string> op_types_;
std::map<int64, ExecStep> execs_;
// Placeholder for empty cases.
std::map<int64, int64> empty_bytes_in_use_;
std::map<string, std::vector<std::pair<int64, int64>>> empty_execs_;
std::vector<AllocationRecord> empty_allocations_;
};
class TFMultiGraphNode {
public:
TFMultiGraphNode(const string& name)
: name_(name),
step_(-1),
run_count_(0),
exec_micros_(0),
accelerator_exec_micros_(0),
cpu_exec_micros_(0),
requested_bytes_(0),
peak_bytes_(0),
residual_bytes_(0),
output_bytes_(0),
float_ops_(0),
parameters_(0) {}
bool SnapshotNodes(int64 step, const std::vector<string>& type_regexes) {
run_count_ = 0;
exec_micros_ = 0;
accelerator_exec_micros_ = 0;
cpu_exec_micros_ = 0;
requested_bytes_ = 0;
peak_bytes_ = 0;
residual_bytes_ = 0;
output_bytes_ = 0;
float_ops_ = 0;
parameters_ = 0;
op_types_.clear();
shapes_.clear();
devices_.clear();
snapshot_nodes_.clear();
step_ = step;
std::vector<const TFGraphNode*> nodes = pick_nodes(type_regexes);
if (nodes.empty()) {
return (type_regexes.size() == 1 && type_regexes[0] == ".*");
}
for (const TFGraphNode* node : nodes) {
op_types_.insert(node->op_types().begin(), node->op_types().end());
run_count_ += node->run_count(step);
exec_micros_ += node->exec_micros(step);
accelerator_exec_micros_ += node->accelerator_exec_micros(step);
cpu_exec_micros_ += node->cpu_exec_micros(step);
requested_bytes_ += node->requested_bytes(step);
peak_bytes_ += node->peak_bytes(step);
residual_bytes_ += node->residual_bytes(step);
output_bytes_ += node->output_bytes(step);
float_ops_ += node->float_ops(step);
parameters_ += node->parameters();
if (node->shape().size() > 0) {
shapes_.push_back(node->shape());
}
devices_.insert(node->canonical_device());
snapshot_nodes_[node->name()] = node;
}
return true;
}
int64 step() const { return step_; }
void AddGraphNode(const TFGraphNode* node) {
if (nodes_.find(node->name()) != nodes_.end()) {
return;
}
nodes_[node->name()] = node;
}
const std::map<string, const TFGraphNode*>& graph_nodes() const {
return snapshot_nodes_;
}
const string& name() const { return name_; }
int64 run_count() const { return run_count_; }
int64 exec_micros() const { return exec_micros_; }
int64 accelerator_exec_micros() const { return accelerator_exec_micros_; }
int64 cpu_exec_micros() const { return cpu_exec_micros_; }
int64 requested_bytes() const { return requested_bytes_; }
int64 peak_bytes() const { return peak_bytes_; }
int64 residual_bytes() const { return residual_bytes_; }
int64 output_bytes() const { return output_bytes_; }
int64 float_ops() const { return float_ops_; }
int64 parameters() const { return parameters_; }
const std::set<string>& devices() const { return devices_; }
const std::set<string>& op_types() const { return op_types_; }
const std::vector<std::vector<int64>>& shapes() const { return shapes_; }
private:
std::vector<const TFGraphNode*> pick_nodes(
const std::vector<string>& type_regexes) {
if (type_regexes.empty()) {
return {};
}
std::vector<const TFGraphNode*> ret;
if (type_regexes.size() == 1 && type_regexes[0] == ".*") {
for (const auto& n : nodes_) {
ret.push_back(n.second);
}
return ret;
}
for (const string& regex : type_regexes) {
for (const auto& n : nodes_) {
for (const string& type : n.second->op_types()) {
if (RE2::FullMatch(type, regex)) {
ret.push_back(n.second);
break;
}
}
}
}
return ret;
}
const string name_;
int64 step_;
// Snapshot based on type_regexes
std::set<string> op_types_;
int64 run_count_;
int64 exec_micros_;
int64 accelerator_exec_micros_;
int64 cpu_exec_micros_;
int64 requested_bytes_;
int64 peak_bytes_;
int64 residual_bytes_;
int64 output_bytes_;
int64 float_ops_;
int64 parameters_;
std::set<string> devices_;
std::vector<std::vector<int64>> shapes_;
std::map<string, const TFGraphNode*> snapshot_nodes_;
// Overall data held by the TFMultiGraphNode.
std::map<string, const TFGraphNode*> nodes_;
};
bool IsPlacedOnCPU(const string& device);
bool IsPlacedOnAccelerator(const string& device);
bool CountAsAcceleratorTime(const string& device);
bool CountAsCPUTime(const string& device);
bool IsCanonicalDevice(const string& device);
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_NODE_H_
@@ -0,0 +1,159 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Node classes used for different views. They are wrappers with "show"
// methods.
//
// ScopeNode is for scope view. GraphNode is for graph view, CodeNode
// is for code view and OpNode for op view.
// ScopeNode and GraphNode each maps to one TFGraphNode.
// CodeNode and OpNode each maps to one TFMultiGraphNode.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_NODE_SHOW_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_NODE_SHOW_H_
#include <algorithm>
#include <string>
#include <vector>
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/profiler/internal/tfprof_constants.h"
#include "tensorflow/core/profiler/internal/tfprof_node.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
class ShowNode {
public:
explicit ShowNode(const TFGraphNode* node);
virtual ~ShowNode() {}
const string& name() const { return node->name(); }
GraphNodeProto* mutable_proto();
const GraphNodeProto& proto() const;
void ReInit(int64 step);
void AggregateTotalStats(ShowNode* node);
void AddSelfToTotalStats();
void ResetTotalStats();
const TFGraphNode* node;
bool account;
string formatted_str;
protected:
GraphNodeProto proto_;
};
class GraphNode : public ShowNode {
public:
explicit GraphNode(TFGraphNode* node) : ShowNode(node) {}
bool Trackable(int64 step) const { return node->trackable(step); }
std::vector<GraphNode*> children;
std::vector<GraphNode*> show_children;
};
class ScopeNode : public ShowNode {
public:
explicit ScopeNode(const TFGraphNode* node) : ShowNode(node) {}
~ScopeNode() override {}
std::vector<ScopeNode*> children;
std::vector<ScopeNode*> show_children;
};
class ShowMultiNode {
public:
explicit ShowMultiNode(TFMultiGraphNode* node);
virtual ~ShowMultiNode() {}
bool ReInit(int64 step, const std::vector<string>& type_regexes);
const string& name() const { return node->name(); }
MultiGraphNodeProto* mutable_proto();
const MultiGraphNodeProto& proto() const;
void AggregateTotalStats(ShowMultiNode* node);
void AddSelfToTotalStats();
void ResetTotalStats();
TFMultiGraphNode* node;
bool account;
bool show;
string formatted_str;
protected:
MultiGraphNodeProto proto_;
};
class CodeNode : public ShowMultiNode {
public:
CodeNode(TFMultiGraphNode* node, const CallStack::Trace* trace,
const string& suffix)
: ShowMultiNode(node), trace_(trace), suffix_(suffix) {}
~CodeNode() override {}
CodeNode* AddChildren(const string& name, const CallStack::Trace* trace,
const string suffix) {
auto it = children_.find(name);
if (it != children_.end()) {
return it->second.get();
}
graph_children_.push_back(
std::unique_ptr<TFMultiGraphNode>(new TFMultiGraphNode(name)));
auto child = &children_[name];
child->reset(new CodeNode(graph_children_.back().get(), trace, suffix));
children.push_back(child->get());
return child->get();
}
bool has_trace() const { return trace_ != nullptr; }
const int32 lineno() const { return trace_->lineno(); }
string file() const { return trace_->file(); }
string function() const { return trace_->function() + suffix_; }
int32 func_start_line() const { return trace_->func_start_line(); }
std::vector<CodeNode*> children;
std::vector<CodeNode*> show_children;
private:
const CallStack::Trace* trace_;
string suffix_;
std::vector<std::unique_ptr<TFMultiGraphNode>> graph_children_;
std::map<string, std::unique_ptr<CodeNode>> children_;
};
class OpNode : public ShowMultiNode {
public:
explicit OpNode(TFMultiGraphNode* node) : ShowMultiNode(node) {}
~OpNode() override {}
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_NODE_SHOW_H_
@@ -0,0 +1,78 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Build a flat structure of ops.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_OP_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_OP_H_
#include <deque>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/profiler/internal/tfprof_node.h"
#include "tensorflow/core/profiler/internal/tfprof_show_multi.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
// Organize tensorflow ops in a graph structure, pointing from output ops
// to input ops.
class TFOp : public TFMultiShow {
public:
explicit TFOp() : TFMultiShow() {}
~TFOp() override {}
void AddNode(TFGraphNode* node) override;
void Build() override;
private:
const ShowMultiNode* ShowInternal(const Options& opts,
Timeline* timeline) override;
int64 SearchRoot(const std::vector<OpNode*> nodes,
const std::vector<string>& regexes);
bool ShouldShowIfExtra(const ShowMultiNode* node, const Options& opts,
int depth) const override {
if (opts.min_occurrence > node->node->graph_nodes().size()) {
return false;
}
return true;
}
string FormatNode(OpNode* node, OpNode* root, const Options& opts) const;
string FormatMemoryNode(int64 node_total_bytes, int64 root_total_bytes,
int64 node_bytes) const;
std::unique_ptr<OpNode> root_;
std::map<string, std::unique_ptr<OpNode>> cnodes_map_;
std::map<string, std::unique_ptr<TFMultiGraphNode>> tfcnodes_map_;
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_OP_H_
@@ -0,0 +1,77 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Build a tree structure based on the TensorFlow op names.
// For example, 'name1/name2' is a child of 'name1'.
// Stats are aggregated from descendants to ancestors.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SCOPE_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SCOPE_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/profiler/internal/tfprof_node.h"
#include "tensorflow/core/profiler/internal/tfprof_show.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
class TFScope : public TFShow {
public:
explicit TFScope(checkpoint::CheckpointReader* ckpt_reader)
: TFShow(ckpt_reader), root_(nullptr) {}
~TFScope() override {}
void AddNode(TFGraphNode* node) override;
void Build() override;
private:
const ShowNode* ShowInternal(const Options& opts,
Timeline* timeline) override;
ScopeNode* CreateParentNode(const string& name);
std::vector<ScopeNode*> SearchRoot(std::vector<ScopeNode*> roots,
const std::vector<string>& regexes);
std::vector<ScopeNode*> PrintScope(const std::vector<ScopeNode*> roots,
const Options& opts, int depth,
int last_ident);
std::vector<ScopeNode*> Account(const std::vector<ScopeNode*>& roots,
const Options& opts);
void Format(const std::vector<ScopeNode*> roots, string* display_str,
GraphNodeProto* proto);
ScopeNode* root_;
std::vector<std::unique_ptr<NodeDef>> node_defs_;
std::map<string, std::unique_ptr<TFGraphNode>> parent_nodes_;
std::map<string, std::unique_ptr<ScopeNode>> nodes_map_;
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SCOPE_H_
@@ -0,0 +1,157 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Parent class and utilities for tfprof_graph and tfprof_scope.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SHOW_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SHOW_H_
#include <algorithm>
#include <string>
#include <vector>
#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/profiler/internal/tfprof_constants.h"
#include "tensorflow/core/profiler/internal/tfprof_node.h"
#include "tensorflow/core/profiler/internal/tfprof_node_show.h"
#include "tensorflow/core/profiler/internal/tfprof_tensor.h"
#include "tensorflow/core/profiler/internal/tfprof_timeline.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
class TFShow {
public:
explicit TFShow(checkpoint::CheckpointReader* ckpt_reader)
: ckpt_reader_(ckpt_reader) {}
virtual ~TFShow() {}
virtual void AddNode(TFGraphNode* node) = 0;
virtual void Build() = 0;
virtual const GraphNodeProto& Show(const string& prefix,
const Options& opts) final;
protected:
virtual const ShowNode* ShowInternal(const Options& opts,
Timeline* timeline) = 0;
bool LookUpCheckPoint(const string& name,
std::unique_ptr<TFProfTensor>* tensor);
// Overridden by subclass if extra requirements need to be met.
virtual bool ShouldShowIfExtra(const ShowNode* node, const Options& opts,
int depth) const {
return true;
}
bool ShouldShow(const ShowNode* node, const Options& opts, int depth) const;
bool ShouldTrim(const ShowNode* node,
const std::vector<string>& regexes) const;
bool ReAccount(ShowNode* node, const Options& opts);
string FormatNode(ShowNode* node, const Options& opts) const;
string FormatNodeMemory(ShowNode* node, int64 bytes, int64 total_bytes) const;
string FormatLegend(const Options& opts) const;
template <typename T>
std::vector<T*> SortNodes(const std::vector<T*>& nodes, const Options& opts) {
if (opts.order_by.empty() || nodes.empty()) {
return nodes;
}
std::vector<T*> sorted_nodes = nodes;
std::sort(sorted_nodes.begin(), sorted_nodes.end(),
[&opts](const T* n1, const T* n2) {
if (n1->name() == kTFProfRoot) return true;
if (n2->name() == kTFProfRoot) return false;
bool name_cmp = n1->name() < n2->name();
if (opts.order_by == kOrderBy[0]) {
return name_cmp;
} else if (opts.order_by == kOrderBy[1]) {
return n1->proto().total_requested_bytes() >
n2->proto().total_requested_bytes();
} else if (opts.order_by == kOrderBy[2]) {
return n1->proto().total_peak_bytes() >
n2->proto().total_peak_bytes();
} else if (opts.order_by == kOrderBy[3]) {
return n1->proto().total_residual_bytes() >
n2->proto().total_residual_bytes();
} else if (opts.order_by == kOrderBy[4]) {
return n1->proto().total_output_bytes() >
n2->proto().total_output_bytes();
} else if (opts.order_by == kOrderBy[5]) {
return n1->proto().total_exec_micros() >
n2->proto().total_exec_micros();
} else if (opts.order_by == kOrderBy[6]) {
return n1->proto().total_accelerator_exec_micros() >
n2->proto().total_accelerator_exec_micros();
} else if (opts.order_by == kOrderBy[7]) {
return n1->proto().total_cpu_exec_micros() >
n2->proto().total_cpu_exec_micros();
} else if (opts.order_by == kOrderBy[8]) {
return n1->proto().total_parameters() >
n2->proto().total_parameters();
} else if (opts.order_by == kOrderBy[9]) {
return n1->proto().total_float_ops() >
n2->proto().total_float_ops();
}
return name_cmp;
});
return sorted_nodes;
}
checkpoint::CheckpointReader* ckpt_reader_;
};
template <typename T>
string FormatTotalExecTime(const T* node, const Options& opts) {
string time = FormatTime(node->proto().total_exec_micros());
if (node->account) {
time = FormatTime(node->proto().exec_micros()) + "/" + time;
} else {
time = "--/" + time;
}
return time;
}
template <typename T>
string FormatCPUExecTime(const T* node, const Options& opts) {
string time = FormatTime(node->proto().total_cpu_exec_micros());
if (node->account) {
time = FormatTime(node->proto().cpu_exec_micros()) + "/" + time;
} else {
time = "--/" + time;
}
return time;
}
template <typename T>
string FormatAcceleratorExecTime(const T* node, const Options& opts) {
string time = FormatTime(node->proto().total_accelerator_exec_micros());
if (node->account) {
time = FormatTime(node->proto().accelerator_exec_micros()) + "/" + time;
} else {
time = "--/" + time;
}
return time;
}
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SHOW_H_
@@ -0,0 +1,130 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Parent class and utilities for tfprof_code.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SHOW_MULTI_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SHOW_MULTI_H_
#include <algorithm>
#include <string>
#include <vector>
#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/profiler/internal/tfprof_constants.h"
#include "tensorflow/core/profiler/internal/tfprof_node.h"
#include "tensorflow/core/profiler/internal/tfprof_node_show.h"
#include "tensorflow/core/profiler/internal/tfprof_show.h"
#include "tensorflow/core/profiler/internal/tfprof_tensor.h"
#include "tensorflow/core/profiler/internal/tfprof_timeline.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
class TFMultiShow {
public:
explicit TFMultiShow() {}
virtual ~TFMultiShow() {}
virtual void AddNode(TFGraphNode* node) = 0;
virtual void Build() = 0;
virtual const MultiGraphNodeProto& Show(const string& prefix,
const Options& opts) final;
protected:
virtual const ShowMultiNode* ShowInternal(const Options& opts,
Timeline* timeline) = 0;
bool LookUpCheckPoint(const string& name,
std::unique_ptr<TFProfTensor>* tensor);
// Overridden by subclass if extra requirements need to be met.
virtual bool ShouldShowIfExtra(const ShowMultiNode* node, const Options& opts,
int depth) const {
return true;
}
bool ShouldShow(const ShowMultiNode* node, const Options& opts,
int depth) const;
bool ShouldTrim(const ShowMultiNode* node,
const std::vector<string>& regexes) const;
bool ReAccount(ShowMultiNode* node, const Options& opts);
string FormatLegend(const Options& opts) const;
string FormatInputShapes(const MultiGraphNodeProto& proto) const;
std::vector<string> FormatTimes(const ShowMultiNode* node,
const Options& opts) const;
template <typename T>
std::vector<T*> SortNodes(const std::vector<T*>& nodes, const Options& opts) {
if (opts.order_by.empty() || nodes.empty()) {
return nodes;
}
std::vector<T*> sorted_nodes = nodes;
std::sort(sorted_nodes.begin(), sorted_nodes.end(),
[&opts](const T* n1, const T* n2) {
if (n1->name() == kTFProfRoot) return true;
if (n2->name() == kTFProfRoot) return false;
bool name_cmp = n1->name() < n2->name();
if (opts.order_by == kOrderBy[0]) {
return name_cmp;
} else if (opts.order_by == kOrderBy[1]) {
return n1->proto().total_requested_bytes() >
n2->proto().total_requested_bytes();
} else if (opts.order_by == kOrderBy[2]) {
return n1->proto().total_peak_bytes() >
n2->proto().total_peak_bytes();
} else if (opts.order_by == kOrderBy[3]) {
return n1->proto().total_residual_bytes() >
n2->proto().total_residual_bytes();
} else if (opts.order_by == kOrderBy[4]) {
return n1->proto().total_output_bytes() >
n2->proto().total_output_bytes();
} else if (opts.order_by == kOrderBy[5]) {
return n1->proto().total_exec_micros() >
n2->proto().total_exec_micros();
} else if (opts.order_by == kOrderBy[6]) {
return n1->proto().total_accelerator_exec_micros() >
n2->proto().total_accelerator_exec_micros();
} else if (opts.order_by == kOrderBy[7]) {
return n1->proto().total_cpu_exec_micros() >
n2->proto().total_cpu_exec_micros();
} else if (opts.order_by == kOrderBy[8]) {
return n1->proto().total_parameters() >
n2->proto().total_parameters();
} else if (opts.order_by == kOrderBy[9]) {
return n1->proto().total_float_ops() >
n2->proto().total_float_ops();
} else if (opts.order_by == kOrderBy[10]) {
return n1->node->graph_nodes().size() >
n2->node->graph_nodes().size();
}
return name_cmp;
});
return sorted_nodes;
}
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_SHOW_MULTI_H_
@@ -0,0 +1,128 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Core API of tfprof.
// 1. Load protos generated from a tensorflow model.
// 2. Build in-memory representations of the tensorflow model, annotate the
// representation with various stats, such as params,times,memory,etc.
// 3. Accept command and options to selectively aggregate stats for analysis
// and print out the results.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_STATS_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_STATS_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include "tensorflow/c/checkpoint_reader.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/profiler/internal/tfprof_code.h"
#include "tensorflow/core/profiler/internal/tfprof_graph.h"
#include "tensorflow/core/profiler/internal/tfprof_node.h"
#include "tensorflow/core/profiler/internal/tfprof_op.h"
#include "tensorflow/core/profiler/internal/tfprof_scope.h"
#include "tensorflow/core/profiler/internal/tfprof_show.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/tfprof_log.pb.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
#include "tensorflow/core/protobuf/config.pb.h"
namespace tensorflow {
namespace tfprof {
class TFStats {
public:
TFStats(std::unique_ptr<GraphDef> graph,
std::unique_ptr<RunMetadata> run_meta,
std::unique_ptr<OpLogProto> op_log,
std::unique_ptr<checkpoint::CheckpointReader> ckpt_reader);
TFStats(const string& filename,
std::unique_ptr<checkpoint::CheckpointReader> ckpt_reader);
~TFStats() {}
const std::map<string, std::unique_ptr<TFGraphNode>>& nodes() const {
return nodes_map_;
}
const std::set<int64>& steps() const { return steps_; }
bool has_code_traces() const { return has_code_traces_; }
double run_coverage() const {
return covered_nodes_.size() / (nodes_map_.size() + 1e-10);
}
void BuildView(const string& cmd);
void BuildAllViews();
// Note: Must first BuildView(view_foo) before ShowXXX(view_foo) methods.
//
// Organize the TensorFlow model as different types of views, and generate
// outputs for profiling.
// TODO(xpan): Should it return reference here?
const GraphNodeProto& ShowGraphNode(const string& cmd,
const Options& opts) const;
const MultiGraphNodeProto& ShowMultiGraphNode(const string& cmd,
const Options& opts) const;
// Add a (partial) graph to existing graph.
void AddGraph(std::unique_ptr<GraphDef> graph);
// Add a step of run time meta data.
void AddRunMeta(int64 step, std::unique_ptr<RunMetadata> run_meta);
// Add tfprof operation meta data, such as customized op type, float_ops,
// and code traces.
void AddOpLogProto(std::unique_ptr<OpLogProto> op_log);
void SerializeToString(string* content);
void WriteProfile(const string& filename);
// For test purpose only.
void AddNodeForTest(int64 step, std::unique_ptr<TFGraphNode> node);
private:
bool Validate(const Options& opts) const;
string MaybeReportMissingTrace() const;
std::set<int64> steps_;
bool has_code_traces_;
bool miss_accelerator_stream_;
std::unique_ptr<TFScope> scope_view_;
std::unique_ptr<TFGraph> graph_view_;
std::unique_ptr<TFCode> code_view_;
std::unique_ptr<TFOp> op_view_;
std::unique_ptr<checkpoint::CheckpointReader> ckpt_reader_;
// TODO(xpan): Store TFGraphNode instead of TFGraphNode* to avoid large
// number of dynamic alloc.
// Maps from graph node name to TFGraphNode.
std::map<string, std::unique_ptr<TFGraphNode>> nodes_map_;
GraphNodeProto empty_graph_node_;
MultiGraphNodeProto empty_multi_graph_node_;
std::map<int64, string> id_to_string_;
// Graph nodes covered by RunMetadata, that is traced with run time stats.
std::set<int64> covered_nodes_;
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_STATS_H_
@@ -0,0 +1,176 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// TFProf representation of a Tensor's value.
// 1. Multi-dimension tensor is flattened in row major, and stored in proto.
// 2. integer are up-casted to int64. floats are up-casted to double. string
// is not supported by TensorFlow CheckPointReader library, though it is
// supported in current code.
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_TENSOR_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_TENSOR_H_
#include <typeinfo>
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
class TFProfTensor {
public:
explicit TFProfTensor(std::unique_ptr<Tensor> tensor)
: tensor_(std::move(tensor)) {
Build();
}
// If pointers are provided, they are filled by the method.
void Display(string* formatted_str, TFProfTensorProto* tfprof_tensor_pb);
private:
// Max length of tensor value displayed to CLI.
const int64 kTFProfTenosrMaxDisplayLen = 10000;
// Max length after which a latency warning will be printed.
const int64 kTFProfTensorMaxWarnLen = 100000;
void Build();
template <typename T>
bool AddValue(const T& value, TFProfTensorProto* dim) {
std::ostringstream sstream;
sstream << value;
if (typeid(value) == typeid(double)) {
double double_val;
CHECK(strings::safe_strtod(sstream.str().c_str(), &double_val));
dim->add_value_double(double_val);
formatted_str_ += strings::Printf(
"%.2f ", dim->value_double(dim->value_double_size() - 1));
} else if (typeid(value) == typeid(int64)) {
int64 int64_val;
CHECK(strings::safe_strto64(sstream.str().c_str(), &int64_val));
dim->add_value_int64(int64_val);
formatted_str_ += strings::Printf(
"%lld ",
static_cast<int64>(dim->value_int64(dim->value_int64_size() - 1)));
} else if (typeid(value) == typeid(string)) {
dim->add_value_str(sstream.str());
formatted_str_ =
strings::StrCat(formatted_str_, "'",
dim->value_str(dim->value_str_size() - 1) + "' ");
} else {
CHECK(false) << "Unsupported type: " << typeid(value).name();
}
}
// It assumes the flatten values are stored in row-major, which is mentioned
// indirectly at various places:
// TODO(xpan): Further verifying it.
template <typename T>
int64 BuildOutput(int64 start, int depth, const std::vector<T>& values,
TFProfTensorProto* dim) {
formatted_str_ += "[";
int64 nstart = start;
if (tensor_->dims() == 0 && values.size() == 1) {
std::ostringstream sstream;
sstream << values[nstart];
if (typeid(values[nstart]) == typeid(double)) {
double double_val;
CHECK(strings::safe_strtod(sstream.str().c_str(), &double_val));
dim->add_value_double(double_val);
formatted_str_ += strings::Printf(
"%.2f ", dim->value_double(dim->value_double_size() - 1));
} else if (typeid(values[nstart]) == typeid(int64)) {
int64 int64_val;
CHECK(strings::safe_strto64(sstream.str().c_str(), &int64_val));
dim->add_value_int64(int64_val);
formatted_str_ += strings::Printf(
"%lld ",
static_cast<int64>(dim->value_int64(dim->value_int64_size() - 1)));
} else if (typeid(values[nstart]) == typeid(string)) {
dim->add_value_str(sstream.str());
formatted_str_ =
strings::StrCat(formatted_str_, "'",
dim->value_str(dim->value_str_size() - 1) + "' ");
} else {
CHECK(false) << "Unsupported type: " << typeid(values[nstart]).name();
}
} else {
for (int i = 0; i < tensor_->dim_size(depth); i++) {
// Last dimension, pull the values.
if (depth == tensor_->dims() - 1) {
std::ostringstream sstream;
sstream << values[nstart];
if (typeid(values[nstart]) == typeid(double)) {
double double_val;
CHECK(strings::safe_strtod(sstream.str().c_str(), &double_val));
dim->add_value_double(double_val);
formatted_str_ += strings::Printf(
"%.2f ", dim->value_double(dim->value_double_size() - 1));
} else if (typeid(values[nstart]) == typeid(int64)) {
int64 int64_val;
CHECK(strings::safe_strto64(sstream.str().c_str(), &int64_val));
dim->add_value_int64(int64_val);
formatted_str_ += strings::Printf(
"%lld ", static_cast<int64>(
dim->value_int64(dim->value_int64_size() - 1)));
} else if (typeid(values[nstart]) == typeid(string)) {
dim->add_value_str(sstream.str());
formatted_str_ = strings::StrCat(
formatted_str_, "'",
dim->value_str(dim->value_str_size() - 1) + "' ");
} else {
CHECK(false) << "Unsupported type: "
<< typeid(values[nstart]).name();
}
++nstart;
} else {
// Not-last dimension. Drill deeper.
nstart = BuildOutput<T>(nstart, depth + 1, values, dim);
}
}
}
if (formatted_str_.length() > kTFProfTenosrMaxDisplayLen) {
formatted_str_ = formatted_str_.substr(0, kTFProfTenosrMaxDisplayLen);
}
formatted_str_ += "],\n";
return nstart;
}
template <typename T, typename U>
void GetValueVec(std::vector<U>* value_vec) {
// TODO(xpan): Address the huge tensor problem.
if (tensor_->NumElements() > kTFProfTensorMaxWarnLen) {
fprintf(stderr, "Showing huge tensor, the tool might halt...\n");
}
auto values = tensor_->flat<T>();
for (int64 i = 0; i < tensor_->NumElements(); i++) {
value_vec->push_back(static_cast<U>(values(i)));
}
}
TFProfTensorProto tfprof_tensor_pb_;
std::unique_ptr<Tensor> tensor_;
string formatted_str_;
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_TENSOR_H_
@@ -0,0 +1,193 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_TIMELINE_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_TIMELINE_H_
#include "include/json/json.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/profiler/internal/tfprof_node_show.h"
#include "tensorflow/core/protobuf/config.pb.h"
namespace tensorflow {
namespace tfprof {
typedef std::map<string, string> Event;
// Class for generating timeline json output.
class ChromeTraceFormatter {
public:
ChromeTraceFormatter() {}
// The following methods creates timeline nodes. See chrome tracing format
// document for details.
Json::Value CreateEvent(const string& ph, const string& category,
const string& name, int64 pid, int64 tid, int64 ts);
void EmitPID(const string& name, int64 pid);
void EmitRegion(int64 ts, int64 duration, int64 pid, int64 tid,
const string& category, const string& name, Json::Value args);
void EmitFlowStart(const string& name, int64 ts, int64 pid, int64 tid,
int64 flow_id);
void EmitFlowEnd(const string& name, int64 ts, int64 pid, int64 tid,
int64 flow_id);
void EmitCounter(const string& category, const string& name, int64 pid,
int64 ts, const string& device, int64 bytes,
const std::map<int64, std::vector<string>>& tensor_mem);
string Format();
private:
// A event is a visualization unit in timeline.
std::vector<Json::Value> events_;
std::vector<Json::Value> metadata_;
};
// A process (time series of events) in the timeline.
class Process {
public:
Process(const string& device, int64 pid) : device(device), pid(pid) {}
// Each lane is a map from start_time to end_time.
std::vector<std::map<int64, int64>> lanes;
// device for the time series.
string device;
// unique id for the time series.
int64 pid;
};
class TimeNode {
public:
TimeNode(Process* process, GraphNode* node, int64 start_micros,
int64 exec_micros)
: process(process),
node(node),
start_micros(start_micros),
exec_micros(exec_micros),
tid(-1) {}
virtual ~TimeNode() {}
const string& name() { return node->name(); }
Process* process;
GraphNode* node;
int64 start_micros;
int64 exec_micros;
int64 tid;
std::vector<TimeNode*> next_tnodes;
};
// Tracking the memory based on the op input/output, temporary bytes and
// persistent bytes.
// Currently, we calculate a "predicted" memory, but do not use it for display.
// The displayed memory timeline is directly from the TensorFlow allocator,
// which is the groundtruth.
class MemoryTracker {
public:
class Device {
public:
// map from tensor name to a pair of <alloc time, bytes_in_use>.
std::map<string, std::map<int64, int64>> tensor_allocs;
// ground truth memory stats. time->bytes.
std::map<int64, int64> allocations;
// tracked allocations, might miss some bytes.
std::map<int64, int64> tracked_allocations;
};
void TrackNode(int64 step, const GraphNode* node);
const std::map<string, Device>& devices() const { return devices_; }
private:
std::map<string, Device> devices_;
};
class Timeline {
public:
Timeline(int64 step, const string& outfile)
: step_(step), outfile_(outfile) {}
~Timeline() {}
int64 step() const { return step_; }
void SetStep(int64 step) { step_ = step; }
void GenerateGraphTimeline(const std::vector<GraphNode*>& gnodes);
void GenerateScopeTimeline(const ScopeNode* node);
void GenerateCodeTimeline(const CodeNode* node);
private:
void TrackNode(const GraphNode* node) { mem_tracker_.TrackNode(step_, node); }
void OutputTimeline();
template <typename Node>
void EmitTreeNode(const Node* node, int64 start_time, int64 duration,
int64 depth, std::set<int64>* visited_depth) {
if (visited_depth->find(depth) == visited_depth->end()) {
chrome_formatter_.EmitPID(strings::StrCat("Scope:", depth), depth);
visited_depth->insert(depth);
}
Json::Value args(Json::objectValue);
args["name"] = Json::Value(node->name());
args["op"] = Json::Value(node->name());
chrome_formatter_.EmitRegion(start_time, duration, depth, 0, "Op",
node->name(), args);
int64 total_micros = 0;
int64 c_start_time = start_time;
for (const Node* child : node->show_children) {
int64 total_exec_micros = child->proto().total_exec_micros();
if (total_exec_micros <= 0) {
continue;
}
EmitTreeNode(child, c_start_time, total_exec_micros, depth + 1,
visited_depth);
c_start_time += total_exec_micros;
total_micros += total_exec_micros;
}
CHECK(total_micros <= duration) << node->name() << " parent:" << duration
<< " children:" << total_micros;
}
void AllocateTimeNodes(GraphNode* gnode);
void AllocateLanes();
int64 AllocatePID();
int64 step_;
const string outfile_;
int64 next_pid_ = 0;
MemoryTracker mem_tracker_;
ChromeTraceFormatter chrome_formatter_;
std::map<string, int64> device_pids_;
std::map<string, std::unique_ptr<Process>> process_;
std::map<int64, std::map<int64, std::map<int64, TimeNode*>>> alloc_nodes_;
std::map<string, std::map<int64, std::unique_ptr<TimeNode>>> tnodes_;
};
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_TIMELINE_H_
@@ -0,0 +1,75 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_UTILS_H_
#define TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_UTILS_H_
#include <string>
#include <vector>
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/protobuf/config.pb.h"
namespace tensorflow {
namespace tfprof {
string FormatNumber(int64 n);
string FormatTime(int64 micros);
string FormatMemory(int64 bytes);
string FormatShapes(const std::vector<int64>& shapes);
tensorflow::Status ParseCmdLine(const string& line, string* cmd,
tensorflow::tfprof::Options* opts);
string StringReplace(const string& str, const string& oldsub,
const string& newsub);
template <typename T>
Status ReadProtoFile(Env* env, const string& fname, T* proto,
bool binary_first) {
string out;
Status s = ReadFileToString(env, fname, &out);
if (!s.ok()) return s;
if (binary_first) {
if (ReadBinaryProto(tensorflow::Env::Default(), fname, proto).ok()) {
return Status();
} else if (protobuf::TextFormat::ParseFromString(out, proto)) {
return Status();
}
} else {
if (protobuf::TextFormat::ParseFromString(out, proto)) {
return Status();
} else if (ReadBinaryProto(tensorflow::Env::Default(), fname, proto).ok()) {
return Status();
}
}
return errors::InvalidArgument("Cannot parse proto file.");
}
void PrintHelp();
// Generate helper message based on the command and options.
string QueryDoc(const string& cmd, const Options& opts);
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_INTERNAL_TFPROF_UTILS_H_
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,186 @@
/* Copyright 2016 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PROFILER_TFPROF_OPTIONS_H_
#define TENSORFLOW_CORE_PROFILER_TFPROF_OPTIONS_H_
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
namespace tfprof {
static const char* const kOptions[] = {
"-max_depth",
"-min_bytes",
"-min_peak_bytes",
"-min_residual_bytes",
"-min_output_bytes",
"-min_micros",
"-min_accelerator_micros",
"-min_cpu_micros",
"-min_params",
"-min_float_ops",
"-min_occurrence",
"-step",
"-order_by",
"-account_type_regexes",
"-start_name_regexes",
"-trim_name_regexes",
"-show_name_regexes",
"-hide_name_regexes",
"-account_displayed_op_only",
"-select",
"-output",
};
static const char* const kOrderBy[] = {
"name", "bytes", "peak_bytes", "residual_bytes",
"output_bytes", "micros", "accelerator_micros", "cpu_micros",
"params", "float_ops", "occurrence",
};
// Append Only.
// TODO(xpan): As we are adding more fields to be selected, we
// need to have a way to tell users what fields are available in which view.
static const char* const kShown[] = {"bytes", "micros",
"params", "float_ops",
"tensor_value", "device",
"op_types", "occurrence",
"input_shapes", "accelerator_micros",
"cpu_micros", "peak_bytes",
"residual_bytes", "output_bytes"};
static const char* const kCmds[] = {
"scope", "graph", "code", "op", "advise", "set", "help",
};
static const char* const kOutput[] = {"timeline", "stdout", "file", "pprof",
"none"};
static const char* const kTimelineOpts[] = {
"outfile",
};
static const char* const kTimelineRequiredOpts[] = {"outfile"};
static const char* const kFileOpts[] = {
"outfile",
};
static const char* const kFileRequiredOpts[] = {
"outfile",
};
static const char* const kPprofOpts[] = {
"outfile",
};
static const char* const kPprofRequiredOpts[] = {
"outfile",
};
struct Options {
public:
static tensorflow::Status FromProtoStr(const string& opts_proto_str,
Options* opts);
virtual ~Options() {}
Options()
: Options(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "", {}, {}, {}, {}, {},
false, {}, "", {}) {}
Options(int max_depth, tensorflow::int64 min_bytes,
tensorflow::int64 min_peak_bytes,
tensorflow::int64 min_residual_bytes,
tensorflow::int64 min_output_bytes, tensorflow::int64 min_micros,
tensorflow::int64 min_accelerator_micros,
tensorflow::int64 min_cpu_micros, tensorflow::int64 min_params,
tensorflow::int64 min_float_ops, tensorflow::int64 min_occurrence,
tensorflow::int64 step, const string& order_by,
const std::vector<string>& account_type_regexes,
const std::vector<string>& start_name_regexes,
const std::vector<string>& trim_name_regexes,
const std::vector<string>& show_name_regexes,
const std::vector<string>& hide_name_regexes,
bool account_displayed_op_only, const std::vector<string>& select,
const string& output_type,
const std::map<string, string>& output_options)
: max_depth(max_depth),
min_bytes(min_bytes),
min_peak_bytes(min_peak_bytes),
min_residual_bytes(min_residual_bytes),
min_output_bytes(min_output_bytes),
min_micros(min_micros),
min_accelerator_micros(min_accelerator_micros),
min_cpu_micros(min_cpu_micros),
min_params(min_params),
min_float_ops(min_float_ops),
min_occurrence(min_occurrence),
step(step),
order_by(order_by),
account_type_regexes(account_type_regexes),
start_name_regexes(start_name_regexes),
trim_name_regexes(trim_name_regexes),
show_name_regexes(show_name_regexes),
hide_name_regexes(hide_name_regexes),
account_displayed_op_only(account_displayed_op_only),
select(select.begin(), select.end()),
output_type(output_type),
output_options(output_options) {}
string ToString() const;
int max_depth;
tensorflow::int64 min_bytes;
tensorflow::int64 min_peak_bytes;
tensorflow::int64 min_residual_bytes;
tensorflow::int64 min_output_bytes;
tensorflow::int64 min_micros;
tensorflow::int64 min_accelerator_micros;
tensorflow::int64 min_cpu_micros;
tensorflow::int64 min_params;
tensorflow::int64 min_float_ops;
tensorflow::int64 min_occurrence;
tensorflow::int64 step;
string order_by;
std::vector<string> account_type_regexes;
std::vector<string> start_name_regexes;
std::vector<string> trim_name_regexes;
std::vector<string> show_name_regexes;
std::vector<string> hide_name_regexes;
bool account_displayed_op_only;
std::set<string> select;
string output_type;
std::map<string, string> output_options;
};
// Parse the -output option.
// 'output_opt': User input string with format: output_type:key=value,key=value.
// 'output_type' and 'output_options' are extracted from 'output_opt'.
tensorflow::Status ParseOutput(const string& output_opt, string* output_type,
std::map<string, string>* output_options);
} // namespace tfprof
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PROFILER_TFPROF_OPTIONS_H_
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff