1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
|
#include <ATen/ATen.h>
#include <ATen/Parallel.h>
#include <ATen/core/ivalue.h>
#include <ATen/core/symbol.h>
#include <torch/csrc/jit/ir/ir_views.h>
#include <torch/csrc/jit/jit_log.h>
#include <torch/csrc/jit/passes/dead_code_elimination.h>
#include <torch/csrc/jit/passes/freeze_module.h>
#include <torch/csrc/jit/passes/frozen_graph_optimizations.h>
#include <torch/csrc/jit/passes/inliner.h>
#include <torch/csrc/jit/passes/insert_guards.h>
#include <torch/csrc/jit/passes/remove_mutation.h>
#include <torch/csrc/jit/runtime/graph_executor.h>
#include <torch/csrc/jit/runtime/interpreter.h>
#include <torch/csrc/jit/runtime/jit_trace.h>
#include <torch/csrc/jit/runtime/profiling_record.h>
#include <unordered_map>
namespace torch {
namespace jit {
namespace {
// A helper structure to mantain the mappings
// between values from a scripted graph and
// a traced graph
struct TracingData {
std::unordered_map<Value*, Value*> old_to_new_;
std::shared_ptr<Graph> traced_graph_ = nullptr;
TracingData() {
traced_graph_ = std::make_shared<Graph>();
}
};
// create a node in the traced graph that corresponds to `node`
// in the scripted graph. Similar to how `cloneNode` works
Node* traceNode(Node* node, TracingData& td, Stack& stack) {
GRAPH_DEBUG("Tracing node ", getHeader(node));
auto* block = td.traced_graph_->block();
auto env = [&td](Value* v) { return td.old_to_new_.at(v); };
auto new_node = block->appendNode(td.traced_graph_->createClone(node, env));
for (size_t i = 0; i < node->outputs().size(); ++i) {
auto oo = node->outputs()[i];
auto no = new_node->outputs()[i];
no->copyMetadata(oo);
td.old_to_new_[oo] = no;
GRAPH_DEBUG(
"Mapping ",
oo->debugName(),
" to ",
no->debugName()); // old to new outputs
}
return new_node;
}
void eraseAllOutputs(Node* opt_pn) {
// NOLINTNEXTLINE
for (int i = opt_pn->outputs().size() - 1; i >= 0; i--) {
opt_pn->eraseOutput(i);
}
}
void insertTracingNodes(Block*, ProfilingRecord*, TracingData&);
// The subtlety in `createPropNodeForIfBlock` is that we need to create
// a "propagate" node that will propagate the mapping between the outputs
// of a then/else block and the outputs in the traced graph onto the outputs
// of the if node in the scripted node. Note, if nodes will disappear in the
// the traced graph but they are still used in the scripted graph.
void createPropNodeForIfBlock(
Block* b,
Node* n,
ProfilingRecord* pr,
TracingData& td) {
std::vector<Value*> empty_values{};
auto opt_pn = pr->createProfileIValueNode(empty_values);
eraseAllOutputs(opt_pn);
insertTracingNodes(b, pr, td);
b->appendNode(opt_pn);
std::function<void(Stack&)> optional_profiler =
[pr, n, b, &td](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// frame_id is unused
int64_t frame_id = 0;
pop(stack, frame_id);
for (size_t i = 0; i < b->outputs().size(); i++) {
// propagate a then-block or else-output to an if-output
auto nbo = td.old_to_new_.at(b->outputs()[i]);
td.old_to_new_[n->outputs()[i]] = nbo;
GRAPH_DEBUG(
"Map ",
td.old_to_new_[n->outputs()[i]]->debugName(),
" to ",
nbo->debugName());
}
};
// uncomment for debugging
// opt_pn->i_(Symbol::attr("propagate"), 1);
opt_pn->setCallback(optional_profiler);
}
// loop counter is implicit in the loop body outputs, we need to make
// it explicit so it can used in 2+ iterations
void traceLoopCounter(Node* n, ProfilingRecord* pr, TracingData& td) {
LoopView lv(n);
auto opt_pn = pr->createProfileIValueNode(lv.currentTripCount());
eraseAllOutputs(opt_pn);
lv.bodyBlock()->prependNode(opt_pn);
std::function<void(Stack&)> optional_profiler = [pr, n, &td](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// frame_id is unused
int64_t frame_id = 0;
pop(stack, frame_id);
int64_t loop_counter = 0;
pop(stack, loop_counter);
WithInsertPoint wip(td.traced_graph_->block());
auto lc = td.traced_graph_->insertConstant(loop_counter);
LoopView lv(n);
td.old_to_new_[lv.currentTripCount()] = lc;
};
// uncomment for debugging
// opt_pn->i_(Symbol::attr("loop_counter"), 1);
opt_pn->setCallback(optional_profiler);
}
// Similar to how we propagate the mappings for If nodes, we need to propagate
// the mappings from the loop body to the beginning of the block in case we
// run another iteration and to the outputs of the Loop node, for any logic
// downstream that uses the output values of the loop node
static void traceLoop(Node* n, ProfilingRecord* pr, TracingData& td) {
std::vector<Value*> empty_values{};
// this is a propagation node for block inputs (phi values)
// these come from either `prim::Loop` inputs or loop body outputs
{
auto opt_pn = pr->createProfileIValueNode(empty_values);
eraseAllOutputs(opt_pn);
opt_pn->insertBefore(n);
LoopView lv(n);
std::function<void(Stack&)> optional_profiler = [pr, n, &td](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// frame_id is unused
int64_t frame_id = 0;
pop(stack, frame_id);
LoopView lv(n);
TORCH_INTERNAL_ASSERT(
lv.bodyCarriedInputs().size() == lv.carriedInputs().size());
for (size_t i = 0; i < lv.bodyCarriedInputs().size(); i++) {
auto bno = td.old_to_new_.at(lv.carriedInputs()[i]);
td.old_to_new_[lv.bodyCarriedInputs()[i]] = bno;
GRAPH_DEBUG(
"Map ",
td.old_to_new_[lv.bodyCarriedInputs()[i]]->debugName(),
" to ",
bno->debugName());
}
};
// uncomment for debugging
// opt_pn->i_(Symbol::attr("loop_entry"), 1);
opt_pn->setCallback(optional_profiler);
}
{
insertTracingNodes(LoopView(n).bodyBlock(), pr, td);
traceLoopCounter(n, pr, td);
}
// this is a propagation node for loop outputs
{
auto opt_pn = pr->createProfileIValueNode(empty_values);
eraseAllOutputs(opt_pn);
LoopView(n).bodyBlock()->appendNode(opt_pn);
// opt_pn->i_(Symbol::attr("loop_propagate"), 1);
std::function<void(Stack&)> optional_profiler = [pr, n, &td](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// frame_id is unused
int64_t frame_id = 0;
pop(stack, frame_id);
LoopView lv(n);
TORCH_INTERNAL_ASSERT(
lv.bodyCarriedOutputs().size() == lv.carriedOutputs().size());
for (size_t i = 0; i < lv.bodyCarriedOutputs().size(); i++) {
auto bno = td.old_to_new_.at(lv.bodyCarriedOutputs()[i]);
td.old_to_new_[lv.carriedOutputs()[i]] = bno;
GRAPH_DEBUG(
"Map ",
td.old_to_new_[lv.bodyCarriedOutputs()[i]]->debugName(),
" to ",
bno->debugName());
}
};
// uncomment for debugging
// opt_pn->i_(Symbol::attr("loop_exit"), 1);
opt_pn->setCallback(optional_profiler);
}
}
// walks all the nodes in a block and adds profiled nodes to each node
// see the comment for `optional_profiler` below
void insertTracingNodes(Block* block, ProfilingRecord* pr, TracingData& td) {
for (auto it = block->nodes().begin(); it != block->nodes().end();) {
auto n = *it;
it++;
GRAPH_DEBUG("Inserting trace for ", getHeader(n));
if (n->kind() == prim::If) {
IfView ifv(n);
createPropNodeForIfBlock(ifv.thenBlock(), n, pr, td);
createPropNodeForIfBlock(ifv.elseBlock(), n, pr, td);
continue;
}
if (n->kind() == prim::Loop) {
traceLoop(n, pr, td);
continue;
}
TORCH_INTERNAL_ASSERT(n->blocks().empty());
auto opt_pn = pr->createProfileIValueNode(n->outputs());
eraseAllOutputs(opt_pn);
opt_pn->insertAfter(n);
// we only use the `opt_pn->node()` to trigger the handler
// we still capture the actual scripted node `n` we want to trace
// we look at its inputs, map them to the inputs in the traced graph
// and create a new node with `traceNode`
std::function<void(Stack&)> optional_profiler = [pr, n, &td](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// frame_id is unused
int64_t frame_id = 0;
pop(stack, frame_id);
GRAPH_DEBUG("Tracing ", getHeader(n));
auto tracer = traceNode(n, td, stack);
auto ouputs_size = n->outputs().size();
auto iivs = pop(stack, ouputs_size);
for (size_t j = 0; j < ouputs_size; j++) {
auto& iiv = iivs[j];
if (iiv.isTensor()) {
auto t = iiv.toTensor();
auto type = t.defined() ? tensorTypeInCurrentExecutionContext(t)
: TensorType::get();
tracer->outputs().at(j)->setType(type);
}
}
};
opt_pn->setCallback(optional_profiler);
}
}
} // namespace
// To trace graph we create a profile node for every one
// in a scripted graph. When a profiled node handler runs
// we insert a new traced node in a trace graph
// If the profiled node handler is called in a loop
// we will have multiple nodes.
// We also maintain the mapping between the outputs of traced
// nodes and the outputs of the node in the scripted graph.
// There are a few subtleties with tracing Ifs and Loops
// discussed above
std::shared_ptr<Graph> TraceGraph(std::shared_ptr<Graph> graph, Stack& stack) {
TracingData td;
GRAPH_DUMP("Before Inline:", graph);
Inline(*graph.get());
EliminateDeadCode(graph);
GRAPH_DUMP("After Inline:", graph);
auto pr = ProfilingRecord::instrumentGraph(graph);
for (auto inp : pr->profiled_graph_->inputs()) {
auto ni = td.traced_graph_->addInput();
ni->copyMetadata(inp);
ni->setType(ni->type());
td.old_to_new_[inp] = ni;
}
// Set type of the graph inputs using the inputs from the stack.
// This needs to be done before running the interpreter because the stack
// will only have the outputs after the run.
for (auto i : c10::irange(stack.size())) {
if (stack[i].isTensor()) {
td.traced_graph_->inputs().at(i)->setType(
tensorTypeInCurrentExecutionContext(stack[i].toTensor()));
}
}
ProfilingRecord::removeProfileCounter(pr->profiled_graph_->block());
ProfilingRecord::removeProfilingNodes(pr->profiled_graph_->block());
insertTracingNodes(pr->profiled_graph_->block(), pr.get(), td);
GRAPH_DUMP("Profiling Graph:", pr->profiled_graph_);
Code cd(pr->profiled_graph_, "");
InterpreterState is{cd};
is.run(stack);
for (auto out : pr->profiled_graph_->outputs()) {
td.traced_graph_->block()->registerOutput(td.old_to_new_.at(out));
}
GRAPH_DUMP("Traced graph:", td.traced_graph_);
return td.traced_graph_;
}
} // namespace jit
} // namespace torch
|