text
stringlengths
0
2.2M
// point to compute graph's outputs
void insertBailOuts(Block* b) {
for (auto it = b->nodes().begin(); it != b->nodes().end(); ++it) {
if (it->kind() == prim::Guard) {
auto bailout_node = b->owningGraph()->create(prim::BailOut);
bailouts_.push_back(bailout_node);
const auto& live_inputs = liveness_sets_[*it];
// guarded inputs come first
// currently, there's always one guarded input
bailout_node->addInput(it->input());
for (auto li : live_inputs) {
// Guarded inputs have already been added
// Also, skip some inputs that BailOutGraphBuilder can
// materialize into bailout graphs directly
if (!shouldBeCapturedInByBailOut(li->node()) || li == it->input()) {
continue;
}
bailout_node->addInput(li);
}
bailout_node->output()->setType(it->output()->type());
bailout_node->i_(attr::index, bailout_index_++);
// we can't immediately replace nodes since this action will corrupt
// the liveness sets of following BailOut nodes if any of their
// arguments are BailOut nodes themselves
replacements_.insert({it->output(), bailout_node->output()});
} else {
for (auto ib : it->blocks()) {
insertBailOuts(ib);
}
}
}
}
std::shared_ptr<Graph> graph_;
std::map<Node*, Node*> subgraphs;
std::size_t bailout_index_;
std::unordered_map<Node*, std::vector<Value*>> liveness_sets_;
std::vector<Node*> bailouts_;
std::map<Value*, Value*> replacements_;
};
void InsertBailOuts(std::shared_ptr<Graph> graph) {
BailOutInserter ibo(std::move(graph));
ibo.run();
}
// linearly scans through graph's nodes to locate prim::BailOut whose
// index matches the given `index`
static Node* locateBailOutNodeInUnoptimizedGraph(Block* b, int64_t index) {
for (auto n : b->nodes()) {
if ((n->kind() == prim::BailOut || n->kind() == prim::Guard) &&
n->hasAttribute(attr::index) && n->i(attr::index) == index) {
return n;
}
for (auto ib : n->blocks()) {
if (auto bn = locateBailOutNodeInUnoptimizedGraph(ib, index)) {
return bn;
}
}
}
return nullptr;
}
// Removes prim::BailOuts and hooks the guarded input directly
// to its users
static void removeBailouts(Block* b) {
for (auto it = b->nodes().begin(); it != b->nodes().end(); it++) {
if (it->kind() == prim::BailOut || it->kind() == prim::Guard) {
// clear profiling information
it->inputs().at(0)->setType(TensorType::get());
it->output()->replaceAllUsesWith(it->inputs().at(0));
it.destroyCurrent();
} else {
for (auto ib : it->blocks()) {
removeBailouts(ib);
}
}
}
}
// see `bailout_graph.h`
TORCH_API std::shared_ptr<Graph> BuildBailOutGraphFrom(
int64_t bailout_index,
const std::shared_ptr<Graph>& orig,
const std::shared_ptr<Graph>& target) {
auto orig_bailout_node =
locateBailOutNodeInUnoptimizedGraph(orig->block(), bailout_index);
GRAPH_DEBUG("bailout triggered for ", *orig_bailout_node);
GRAPH_DUMP("original bailout graph ", orig);
TORCH_INTERNAL_ASSERT(
orig_bailout_node->inputs().at(0)->type()->cast<FunctionType>() ==
nullptr);
TORCH_INTERNAL_ASSERT(
orig_bailout_node &&
(orig_bailout_node->kind() == prim::BailOut ||