ngraph_helper.h 7.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2018 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. */

#ifdef PADDLE_WITH_NGRAPH
#pragma once

#include <functional>
19
#include <memory>
20
#include <string>
21
#include <unordered_map>
22 23 24 25 26 27
#include <vector>
#include "ngraph/ngraph.hpp"

namespace paddle {
namespace platform {

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
std::shared_ptr<ngraph::Node> Nhwc2Nchw(std::shared_ptr<ngraph::Node> in) {
  auto in_shape = in->get_shape();
  in_shape[0] = in->get_shape()[0];
  in_shape[1] = in->get_shape()[3];
  in_shape[2] = in->get_shape()[1];
  in_shape[3] = in->get_shape()[2];
  ngraph::AxisVector axis_vec = {0, 3, 1, 2};
  return std::make_shared<ngraph::op::Reshape>(in, axis_vec, in_shape);
}

std::shared_ptr<ngraph::Node> Nchw2Nhwc(std::shared_ptr<ngraph::Node> in) {
  auto in_shape = in->get_shape();
  in_shape[0] = in->get_shape()[0];
  in_shape[1] = in->get_shape()[2];
  in_shape[2] = in->get_shape()[3];
  in_shape[3] = in->get_shape()[1];
  ngraph::AxisVector axis_vec = {0, 2, 3, 1};
  return std::make_shared<ngraph::op::Reshape>(in, axis_vec, in_shape);
}

48 49 50 51 52 53 54
ngraph::Shape FlattenTo1d(ngraph::Shape sh, int num) {
  auto x1 = std::accumulate(std::begin(sh), std::end(sh) + num, 1,
                            std::multiplies<size_t>());
  size_t x1_l = (size_t)x1;
  return ngraph::Shape{x1_l};
}

55
ngraph::Shape FlattenTo2d(ngraph::Shape sh, int num) {
56 57 58 59 60 61 62 63 64
  auto x1 = std::accumulate(std::begin(sh), std::begin(sh) + num, 1,
                            std::multiplies<size_t>());
  auto x2 = std::accumulate(std::begin(sh) + num, std::end(sh), 1,
                            std::multiplies<size_t>());
  size_t x1_l = static_cast<size_t>(x1);
  size_t x2_l = static_cast<size_t>(x2);
  return ngraph::Shape{x1_l, x2_l};
}

65 66
std::shared_ptr<ngraph::Node> NgReshaper(std::shared_ptr<ngraph::Node> input,
                                         ngraph::Shape shape) {
67 68 69 70 71 72
  std::vector<size_t> input_order(input->get_shape().size());
  std::iota(std::begin(input_order), std::end(input_order), 0);
  return std::make_shared<ngraph::op::Reshape>(
      input, ngraph::AxisVector(input_order), shape);
}

73
std::shared_ptr<ngraph::Node> GetNode(
74
    const std::shared_ptr<paddle::framework::OperatorBase>& op,
75
    const std::string name, const paddle::framework::VariableNameMap& var_map,
76 77 78
    std::shared_ptr<
        std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
        ngb_node_map) {
79
  auto& var_names = var_map.at(name);
80
  if (var_names.size() == 0) return nullptr;
81 82 83 84 85 86 87
  if (ngb_node_map->find(var_names[0]) != ngb_node_map->end()) {
    return (*ngb_node_map)[var_names[0]];
  } else {
    return nullptr;
  }
}

88
std::shared_ptr<ngraph::Node> GetInputNode(
89
    const std::shared_ptr<paddle::framework::OperatorBase>& op,
90
    const std::string name,
91 92 93
    std::shared_ptr<
        std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
        ngb_node_map) {
94
  return GetNode(op, name, op->Inputs(), ngb_node_map);
95 96
}

97
std::shared_ptr<ngraph::Node> GetOutputNode(
98
    const std::shared_ptr<paddle::framework::OperatorBase>& op,
99
    const std::string name,
100 101 102
    std::shared_ptr<
        std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
        ngb_node_map) {
103
  return GetNode(op, name, op->Outputs(), ngb_node_map);
104 105
}

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
template <typename T>
std::shared_ptr<ngraph::Node> CreateConstant(const ngraph::element::Type& type,
                                             ngraph::Shape shape,
                                             std::initializer_list<T> values) {
  std::shared_ptr<ngraph::Node> result;
  if (values.size() == 1 && shape != ngraph::Shape{} &&  // NOLINT
      shape != ngraph::Shape{1}) {
    result = std::make_shared<ngraph::op::Constant>(type, ngraph::Shape{},
                                                    std::vector<T>{values});
    ngraph::AxisSet axis_set;
    for (size_t i = 0; i < shape.size(); ++i) axis_set.insert(i);
    result = std::make_shared<ngraph::op::Broadcast>(result, shape, axis_set);
  } else {
    result = std::make_shared<ngraph::op::Constant>(type, shape,
                                                    std::vector<T>{values});
  }
  return result;
}

125
void SetOutputNode(
126
    const std::shared_ptr<paddle::framework::OperatorBase>& op,
127
    const std::string name, std::shared_ptr<ngraph::Node> node,
128 129 130
    std::shared_ptr<
        std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
        ngb_node_map) {
131
  auto& var_names = op->Outputs().at(name);
132
  if (var_names.size() == 1) {
133 134 135 136 137 138 139 140 141 142
    /*  */
    auto dummy_out = GetOutputNode(op, name, ngb_node_map);
    if (dummy_out && dummy_out->get_shape() != node->get_shape()) {
      node = NgReshaper(node, dummy_out->get_shape());
    }
    if (dummy_out &&
        dummy_out->get_element_type() != node->get_element_type()) {
      node = std::make_shared<ngraph::op::Convert>(
          node, dummy_out->get_element_type());
    }
143 144 145 146
    (*ngb_node_map)[var_names[0]] = node;
  } else if (var_names.size() == 0) {
    (*ngb_node_map)[""] = node;
  } else {
147
    PADDLE_THROW("name %s has more than 1 var_names.", name);
148 149 150
  }
}

151
bool HasOutput(const std::shared_ptr<paddle::framework::OperatorBase>& op,
152
               const std::string name) {
153
  auto& outputs = op->Outputs();
154 155
  if (outputs.find(name) == outputs.end()) return false;
  return outputs.at(name).size() > 0;
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
inline void GetMidDims(const ngraph::Shape& x_shape,
                       const ngraph::Shape& y_shape, int axis, int* pre, int* n,
                       int* post) {
  *pre = 1;
  *n = 1;
  *post = 1;
  for (int i = 0; i < axis; ++i) {
    (*pre) *= x_shape[i];
  }

  for (size_t i = 0; i < y_shape.size(); ++i) {
    PADDLE_ENFORCE_EQ(x_shape[i + axis], y_shape[i],
                      "Broadcast dimension mismatch.");
    (*n) *= y_shape[i];
  }

  for (size_t i = axis + y_shape.size(); i < x_shape.size(); ++i) {
    (*post) *= x_shape[i];
  }
}

inline void TrimTrailingSingularDims(ngraph::Shape* shape) {
  // Remove trailing dimensions of size 1 for y
  auto actual_shape_size = shape->size();
  for (; actual_shape_size != 0; --actual_shape_size) {
    if ((*shape)[actual_shape_size - 1] != 1) {
      break;
    } else {
      shape->pop_back();
    }
  }
}
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

ngraph::element::Type GetNgType(paddle::framework::proto::VarType::Type dtype) {
  ngraph::element::Type ng_dtype;
  if (dtype == paddle::framework::proto::VarType::FP32) {
    ng_dtype = ngraph::element::f32;
  } else if (dtype == paddle::framework::proto::VarType::FP64) {
    ng_dtype = ngraph::element::f64;
  } else if (dtype == paddle::framework::proto::VarType::INT64) {
    ng_dtype = ngraph::element::i64;
  } else if (dtype == paddle::framework::proto::VarType::INT32) {
    ng_dtype = ngraph::element::i32;
  } else {
    PADDLE_THROW("unsupported data type: %s", dtype);
  }
  return ng_dtype;
}
206 207 208 209
}  // namespace platform
}  // namespace paddle

#endif