build_cinn_pass.cc 14.4 KB
Newer Older
J
jiangcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2021 PaddlePaddle 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. */

#include "paddle/fluid/framework/paddle2cinn/build_cinn_pass.h"

17 18
#include <algorithm>
#include <iterator>
J
jiangcheng 已提交
19 20 21 22
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
23
#include <utility>
J
jiangcheng 已提交
24 25
#include <vector>

26 27
#include "cinn/frontend/op_mapper_registry.h"
#include "cinn/frontend/op_mappers/use_op_mappers.h"
J
jiangcheng 已提交
28
#include "paddle/fluid/framework/ir/graph.h"
29
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
J
jiangcheng 已提交
30 31
#include "paddle/fluid/framework/ir/node.h"
#include "paddle/fluid/framework/ir/subgraph_detector.h"
32
#include "paddle/fluid/framework/op_proto_maker.h"
33
#include "paddle/fluid/framework/paddle2cinn/cinn_compiler.h"
34 35
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/errors.h"
J
jiangcheng 已提交
36 37 38 39 40 41 42 43 44 45 46

namespace paddle {
namespace framework {
namespace paddle2cinn {

using framework::ir::Graph;
using framework::ir::Node;

using GraphNodeVec = std::vector<Node*>;
using GraphNodeSet = std::unordered_set<Node*>;

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
namespace {
int ExtractOpRole(const GraphNodeSet& cluster) {
  std::unordered_set<int> op_roles;
  std::string attr_name = OpProtoAndCheckerMaker::OpRoleAttrName();
  for (auto* n : cluster) {
    if (n->Op() && n->Op()->HasAttr(attr_name)) {
      op_roles.insert(BOOST_GET_CONST(int, n->Op()->GetAttr(attr_name)));
    }
  }
  if (op_roles.size() == 1U) {
    return *(op_roles.begin());
  } else {
    return static_cast<int>(OpRole::kNotSpecified);
  }
}

63 64 65 66 67
// Deal with subgraph's feed input var node:
// create a new input var node and it's feed op node
void AddFeedOpAndVar(const std::unordered_set<Node*>& feed_vars,
                     const GraphNodeSet& cluster,
                     const std::unordered_map<Node*, Node*>& old_op2new_op,
68
                     const std::unordered_map<Node*, Node*>& old_var2new_var,
69 70 71 72 73 74 75 76
                     Graph* graph) {
  for (auto* old_var : feed_vars) {
    // create feed op
    OpDesc desc;
    desc.SetType("feed");
    desc.SetOutput("Out", {old_var->Name()});
    auto op = graph->CreateOpNode(&desc);

77 78
    // get new feed var node
    auto* var = old_var2new_var.at(old_var);
79 80

    // link feed op and feed var
81
    IR_NODE_LINK_TO(op, var);
82 83 84 85

    // link feed var to cluster op
    for (auto* old_op : old_var->outputs) {
      if (cluster.count(old_op)) {
86
        IR_NODE_LINK_TO(var, old_op2new_op.at(old_op));
87 88
      }
      // Do not need relink old op or old var here, they will be
89
      // fixed in RemoveSubGraphFromGraph, here we just deal with
90 91 92 93 94 95 96 97 98 99 100
      // new subgraph's node.
    }
  }
}

// Deal with subgraph's parameter var node:
// create a new input var node, it's data will get by scope,
// so it don't need feed op
void AddParamVar(const std::unordered_set<Node*>& param_vars,
                 const GraphNodeSet& cluster,
                 const std::unordered_map<Node*, Node*>& old_op2new_op,
101
                 const std::unordered_map<Node*, Node*>& old_var2new_var,
102 103
                 Graph* graph) {
  for (auto* old_var : param_vars) {
104
    auto* var = old_var2new_var.at(old_var);
105 106 107

    for (auto* old_op : old_var->outputs) {
      if (cluster.count(old_op)) {
108
        IR_NODE_LINK_TO(var, old_op2new_op.at(old_op));
109 110 111 112 113 114 115 116 117 118
      }
    }
  }
}

// Deal with subgraph's outputs var node:
// create a new output var node and it's fetch op
void AddOutputVar(const std::unordered_set<Node*>& output_vars,
                  const GraphNodeSet& cluster,
                  const std::unordered_map<Node*, Node*>& old_op2new_op,
119
                  const std::unordered_map<Node*, Node*>& old_var2new_var,
120 121
                  Graph* graph) {
  for (auto* old_var : output_vars) {
122
    auto* var = old_var2new_var.at(old_var);
123 124 125

    for (auto* old_op : old_var->inputs) {
      if (cluster.count(old_op)) {
126
        IR_NODE_LINK_TO(old_op2new_op.at(old_op), var);
127 128 129 130 131
      }
    }
  }
}

J
jiangcheng 已提交
132 133
// Create new subgraph with and op nodes are cluster nodes, and all
// var node are from internal nodes
134 135
std::unique_ptr<Graph> CreateNewSubGraph(const GraphNodeSet& cluster,
                                         const GraphNodeSet& cluster_internals,
136 137
                                         const GraphNodeSet& cluster_inputs,
                                         const GraphNodeSet& cluster_outputs) {
J
jiangcheng 已提交
138 139
  // Graph's constructor must has one parameter, and in our code,
  // the ProgramDesc is useless, so here we pass a temporary object.
140
  auto subgraph = std::make_unique<Graph>(framework::ProgramDesc());
J
jiangcheng 已提交
141 142 143

  std::unordered_map<Node*, Node*> old_op2new_op;
  for (auto* op : cluster) {
144
    auto sub_node = subgraph->CreateOpNode(op->Op());
J
jiangcheng 已提交
145 146 147 148 149
    old_op2new_op[op] = sub_node;
  }

  std::unordered_map<Node*, Node*> old_var2new_var;
  for (auto* var : cluster_internals) {
150 151 152 153 154
    PADDLE_ENFORCE_NOT_NULL(var->Var(),
                            platform::errors::PreconditionNotMet(
                                "The var desc of the node in cluster_internals "
                                "shouldn't be null."));
    auto* sub_node = subgraph->CreateVarNode(var->Var());
J
jiangcheng 已提交
155 156
    old_var2new_var[var] = sub_node;
  }
157 158 159 160 161 162 163 164 165 166 167 168
  for (auto* var : cluster_inputs) {
    if (var->Var()) {
      auto* sub_node = subgraph->CreateVarNode(var->Var());
      old_var2new_var[var] = sub_node;
    }
  }
  for (auto* var : cluster_outputs) {
    if (var->Var()) {
      auto* sub_node = subgraph->CreateVarNode(var->Var());
      old_var2new_var[var] = sub_node;
    }
  }
J
jiangcheng 已提交
169

170 171
  std::unordered_set<Node*> need_feed_vars;
  std::unordered_set<Node *> param_vars, output_vars;
J
jiangcheng 已提交
172 173 174 175 176
  // the subgraph is independently, so here we only need link
  // to the node in new subgraph, and discard the link to
  // out-graph.
  for (auto* op : cluster) {
    for (auto* var : op->inputs) {
177 178 179 180
      // one output var maybe an input of the cluster
      if (cluster_internals.count(var) ||
          (cluster_outputs.count(var) && old_var2new_var.count(var))) {
        IR_NODE_LINK_TO(old_var2new_var.at(var), old_op2new_op.at(op));
181
      } else if (cluster_inputs.count(var) && var->Var() != nullptr) {
182 183 184 185 186 187 188 189 190 191 192
        if (var->Var()->IsParameter()) {
          // Parameters have been preserved in scope, compared to feed var,
          // param just need add new var and don't need add feed op.
          // The var is used for check whether we need preserve the tensor
          // when transform paddle scope to CINN scope.
          param_vars.insert(var);
        } else {
          // When the var is subgraph input and the var is not parameter,
          // we need add a new feed op to feed the var.
          need_feed_vars.insert(var);
        }
J
jiangcheng 已提交
193 194 195 196
      }
    }
    for (auto* var : op->outputs) {
      if (cluster_internals.count(var)) {
197
        IR_NODE_LINK_TO(old_op2new_op.at(op), old_var2new_var.at(var));
198
      } else if (cluster_outputs.count(var) && var->Var() != nullptr) {
199 200 201 202
        // Create new output var node to guarantee the independency of
        // subgraph. In other words, the subgraph has no connection with
        // other graph, even the input graph.
        output_vars.insert(var);
J
jiangcheng 已提交
203 204 205 206
      }
    }
  }

207 208 209 210 211 212
  AddFeedOpAndVar(need_feed_vars, cluster, old_op2new_op, old_var2new_var,
                  subgraph.get());
  AddParamVar(param_vars, cluster, old_op2new_op, old_var2new_var,
              subgraph.get());
  AddOutputVar(output_vars, cluster, old_op2new_op, old_var2new_var,
               subgraph.get());
J
jiangcheng 已提交
213

214
  return subgraph;
J
jiangcheng 已提交
215 216 217 218
}

// This interface is used to classify all variables involved in a cluster into
// three types: inputs, outputs, and internals.
219 220 221
// The input node is some subgraph op's input but not any subgraph op's output.
// The output node is some subgraph op's output and some out-graph op's input.
// Specially, the internal node is a node that only used by subgraph, and
J
jiangcheng 已提交
222
// out-graph should not using this node at all.
223 224
// cluster_inputs & cluster_outputs & cluster_internals == NULL
// cluster_outputs | cluster_internals == all graph op's outputs node
J
jiangcheng 已提交
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
void AnalyseClusterVariables(const GraphNodeSet& cluster,
                             GraphNodeSet* cluster_inputs,
                             GraphNodeSet* cluster_outputs,
                             GraphNodeSet* cluster_internals) {
  // collecting all input and output of op
  for (auto* op_node : cluster) {
    for (auto* input_var_node : op_node->inputs) {
      cluster_inputs->insert(input_var_node);
    }
    for (auto* output_var_node : op_node->outputs) {
      cluster_outputs->insert(output_var_node);
    }
  }
  // remove output node from cluster_inputs,
  // and add cluster_internals node
  for (auto* var_node : *cluster_outputs) {
    if (cluster_inputs->count(var_node) > 0) {
      // if a input node also exists in output list, remove
      cluster_inputs->erase(var_node);

      // the internal node is must an output node of sub-graph,
      // but not any input node of out-graph.
      bool is_only_used_internal = true;
      for (auto* next_op_node : var_node->outputs) {
        is_only_used_internal &= (cluster.count(next_op_node) > 0);
      }
      if (is_only_used_internal) {
        cluster_internals->insert(var_node);
      }
    }
  }

  // if a output node also exists in internal list, remove.
  for (auto* var_node : *cluster_internals) {
    cluster_outputs->erase(var_node);
  }
}

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
void AddLinkToCinnOp(const GraphNodeSet& cluster_inputs,
                     const GraphNodeSet& cluster_outputs, Node* cinn_op_node) {
  // add new link from cluster_inputs to cinn_op_node
  for (auto* var_node : cluster_inputs) {
    IR_NODE_LINK_TO(var_node, cinn_op_node);
  }

  // add new link from cinn_op_node to cluster_outputs
  for (auto* var_node : cluster_outputs) {
    IR_NODE_LINK_TO(cinn_op_node, var_node);
  }
}

void AddCinnOpToGraph(const GraphNodeSet& cluster,
                      const GraphNodeSet& cluster_inputs,
                      const GraphNodeSet& cluster_outputs,
                      const std::string& compilation_key, Graph* graph) {
  // Add the cinn launch op
  framework::OpDesc cinn_op_desc;
  cinn_op_desc.SetType(kCinnLaunchOp);
283
  std::vector<std::string> input_names;
284 285 286 287 288 289
  std::for_each(cluster_inputs.begin(), cluster_inputs.end(),
                [&input_names](Node* n) {
                  if (n->Var() != nullptr) {
                    input_names.emplace_back(n->Name());
                  }
                });
290
  cinn_op_desc.SetInput("X", input_names);
291
  std::vector<std::string> output_names;
292 293 294 295 296 297
  std::for_each(cluster_outputs.begin(), cluster_outputs.end(),
                [&output_names](Node* n) {
                  if (n->Var() != nullptr) {
                    output_names.emplace_back(n->Name());
                  }
                });
298 299 300 301 302 303 304 305
  cinn_op_desc.SetOutput("Out", output_names);
  cinn_op_desc.SetAttr(kCompilationKey, compilation_key);
  cinn_op_desc.SetAttr(OpProtoAndCheckerMaker::OpRoleAttrName(),
                       ExtractOpRole(cluster));
  cinn_op_desc.Flush();
  auto* cinn_op_node = graph->CreateOpNode(&cinn_op_desc);
  // Add new links from or to the the cinn launch op node
  AddLinkToCinnOp(cluster_inputs, cluster_outputs, cinn_op_node);
J
jiangcheng 已提交
306 307 308 309 310 311
}

// Removing cluster node and internals node from Graph
void RemoveSubGraphFromGraph(const GraphNodeSet& cluster,
                             const GraphNodeSet& cluster_internals,
                             Graph* graph) {
312 313 314 315 316 317
  const std::unordered_set<const Node*> const_cluster{cluster.cbegin(),
                                                      cluster.cend()};
  const std::unordered_set<const Node*> const_internals{
      cluster_internals.cbegin(), cluster_internals.cend()};
  ir::GraphSafeRemoveNodes(graph, const_cluster);
  ir::GraphSafeRemoveNodes(graph, const_internals);
J
jiangcheng 已提交
318 319
}

320
// Replacing Cinn subgraph to a cinn op node, whose op_type is
J
jiangcheng 已提交
321 322
// kCinnLaunchOp, and inputs ares cluster_inputs and outputs are
// cluster_outputs.
323 324 325 326 327 328 329 330 331 332 333
// Meanwhile, move all links of cluster to the cinn op.
void ReplaceSubGraphWithCinnOpNode(const GraphNodeSet& cluster,
                                   const GraphNodeSet& cluster_inputs,
                                   const GraphNodeSet& cluster_outputs,
                                   const GraphNodeSet& cluster_internals,
                                   const std::string& compilation_key,
                                   Graph* graph) {
  // Add the cinn op node whose name is "kCinnLaunchOp" into graph
  AddCinnOpToGraph(cluster, cluster_inputs, cluster_outputs, compilation_key,
                   graph);
  // Remove the cinn subgraph from graph
J
jiangcheng 已提交
334 335 336 337 338 339 340
  RemoveSubGraphFromGraph(cluster, cluster_internals, graph);
}

// Search all subgraphs which all op node supported by CINN,
// Here we using SubgraphDetector to detecte the subgraph that
// all of op node supported by CINN. We using OpMapperRegistry
// to check whether the op node supported by CINN.
341
void SearchAllSubgraphs(Graph* graph) {
J
jiangcheng 已提交
342 343 344 345 346 347 348
  auto teller = [](const Node* node) {
    return ::cinn::frontend::OpMapperRegistry::Global()->Find(node->Name()) !=
           nullptr;
  };
  std::vector<GraphNodeVec> clusters =
      framework::ir::SubgraphDetector(graph, teller)();

349
  auto* cinn_compiler = CinnCompiler::GetInstance();
J
jiangcheng 已提交
350
  for (const auto& node_vec : clusters) {
351
    // Classify var node to inputs, outputs, and internals.
J
jiangcheng 已提交
352 353 354 355 356
    GraphNodeSet cluster_set(node_vec.begin(), node_vec.end());

    GraphNodeSet cluster_inputs, cluster_outputs, cluster_internals;
    AnalyseClusterVariables(cluster_set, &cluster_inputs, &cluster_outputs,
                            &cluster_internals);
357 358
    // Create a new subgraph according to the found cluster and
    // save it in CinnCompiler
359 360
    std::string compilation_key = cinn_compiler->AddGraph(CreateNewSubGraph(
        cluster_set, cluster_internals, cluster_inputs, cluster_outputs));
361 362 363
    // Replace the found cluster to a new cinn op node
    ReplaceSubGraphWithCinnOpNode(cluster_set, cluster_inputs, cluster_outputs,
                                  cluster_internals, compilation_key, graph);
J
jiangcheng 已提交
364 365
  }
}
366
}  // namespace
J
jiangcheng 已提交
367

368
void BuildCinnPass::ApplyImpl(Graph* graph) const { SearchAllSubgraphs(graph); }
J
jiangcheng 已提交
369 370 371 372 373 374

}  // namespace paddle2cinn
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(build_cinn_pass, paddle::framework::paddle2cinn::BuildCinnPass);