cross_entropy_op.h 8.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*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. */

#pragma once

#include <functional>
B
baojun 已提交
18
#include <memory>
19
#include <string>
B
baojun 已提交
20
#include <unordered_map>
21 22

#include "ngraph/ngraph.hpp"
23
#include "paddle/fluid/operators/ngraph/ops/op_bridge.h"
24 25 26 27 28
#include "paddle/fluid/platform/ngraph_helper.h"

namespace paddle {
namespace operators {
namespace ngraphs {
29 30 31
std::shared_ptr<ngraph::Node> remove_trailing_one(
    const std::shared_ptr<ngraph::Node>& input) {
  auto shape = input->get_shape();
32
  if (shape.back() == 1 && shape.size() > 1) {
33 34 35 36 37 38
    shape.pop_back();
    return platform::NgReshaper(input, shape);
  } else {
    return input;
  }
}
39

40 41 42 43 44 45 46 47
std::shared_ptr<ngraph::Node> flatten_node(
    const std::shared_ptr<ngraph::Node>& input) {
  auto shape = input->get_shape();
  auto rank = shape.size();
  auto output = input;
  if (rank > 2) {
    auto shape_2d = paddle::platform::FlattenTo2d(shape, rank - 1);
    output = paddle::platform::NgReshaper(input, shape_2d);
48
  }
49 50 51 52 53 54 55 56 57 58
  return output;
}

std::shared_ptr<ngraph::Node> convert_to_node_type(
    const std::shared_ptr<ngraph::Node>& input,
    const std::shared_ptr<ngraph::Node>& ref) {
  auto output = input;
  if (input->get_element_type() != ref->get_element_type()) {
    output =
        std::make_shared<ngraph::op::Convert>(input, ref->get_element_type());
59
  }
60 61
  return output;
}
62

63 64 65 66
std::shared_ptr<ngraph::Node> create_xe(
    const std::shared_ptr<ngraph::Node>& one_hot,
    const std::shared_ptr<ngraph::Node>& x) {
  auto node_log = std::make_shared<ngraph::op::Log>(x);
67

68 69 70 71 72 73 74 75
  auto node_mul = one_hot * node_log;
  auto node_sum = std::make_shared<ngraph::op::Sum>(
      node_mul, ngraph::AxisSet{x->get_shape().size() - 1});

  auto shape = x->get_shape();
  shape.back() = 1;
  return platform::NgReshaper(-node_sum, shape);
}
76

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
std::shared_ptr<ngraph::Node> create_mask(
    const std::shared_ptr<ngraph::Node>& label, int ignore_index) {
  auto ignore_node = paddle::platform::CreateConstant(
      label->get_element_type(), label->get_shape(), {ignore_index});
  auto not_equal_node =
      std::make_shared<ngraph::op::NotEqual>(label, ignore_node);
  return not_equal_node;
}

std::shared_ptr<ngraph::Node> create_one_hot(
    const std::shared_ptr<ngraph::Node>& label,
    const std::shared_ptr<ngraph::Node>& x) {
  auto label_shape = label->get_shape();
  return std::make_shared<ngraph::op::OneHot>(
      remove_trailing_one(label), x->get_shape(), x->get_shape().size() - 1);
}

std::shared_ptr<ngraph::Node> GetCrossEntropy(
    std::shared_ptr<ngraph::Node> x, std::shared_ptr<ngraph::Node> label,
    const bool is_soft_label, int ignore_index) {
  std::shared_ptr<ngraph::Node> node_1_hot = label;
98
  if (!is_soft_label) {
99
    node_1_hot = create_one_hot(label, x);
100
  }
101
  node_1_hot = convert_to_node_type(node_1_hot, x);
102

103
  auto xe = create_xe(node_1_hot, x);
104
  if (!is_soft_label) {
105
    auto mask = convert_to_node_type(create_mask(label, ignore_index), xe);
106 107
    xe = xe * mask;
  }
108
  return xe;
109 110
}

111 112 113 114
std::shared_ptr<ngraph::Node> GetCrossEntropyGrad(
    std::shared_ptr<ngraph::Node> x, std::shared_ptr<ngraph::Node> label,
    std::shared_ptr<ngraph::Node> dy, const bool is_soft_label,
    int ignore_index) {
115 116 117 118 119
  auto x_shape = x->get_shape();
  auto rank = x_shape.size();

  std::shared_ptr<ngraph::Node> mask;
  if (!is_soft_label) {
120 121 122 123
    mask = convert_to_node_type(create_mask(label, ignore_index), x);
    mask = std::make_shared<ngraph::op::Broadcast>(
        remove_trailing_one(mask), x_shape, ngraph::AxisSet{rank - 1});
    label = create_one_hot(label, x);
124 125
  }

126
  auto dy_reshape = remove_trailing_one(dy);
127 128
  auto dy_bcast = std::make_shared<ngraph::op::Broadcast>(
      dy_reshape, x_shape, ngraph::AxisSet{rank - 1});
129 130

  label = convert_to_node_type(label, x);
131 132 133 134 135 136

  auto xe_grad = -label * dy_bcast / x;

  if (!is_soft_label) {
    xe_grad = xe_grad * mask;
  }
137 138
  return xe_grad;
}
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
void BuildCrossEntropyNode(
    const std::shared_ptr<paddle::framework::OperatorBase>& op,
    std::shared_ptr<
        std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
        ngb_node_map) {
  auto x = paddle::platform::GetInputNode(op, "X", ngb_node_map);
  auto label = paddle::platform::GetInputNode(op, "Label", ngb_node_map);
  auto op_attrs = paddle::framework::AttrReader(op->Attrs());
  const bool is_soft_label = op_attrs.Get<bool>("soft_label");
  int ignore_index = op_attrs.Get<int>("ignore_index");
  auto xe = GetCrossEntropy(x, label, is_soft_label, ignore_index);
  paddle::platform::SetOutputNode(op, "Y", xe, ngb_node_map);
}

void BuildCrossEntropyGradNode(
    const std::shared_ptr<paddle::framework::OperatorBase>& op,
    std::shared_ptr<
        std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
        ngb_node_map) {
  auto op_attrs = paddle::framework::AttrReader(op->Attrs());
  const bool is_soft_label = op_attrs.Get<bool>("soft_label");
  int ignore_index = op_attrs.Get<int>("ignore_index");
  auto x = paddle::platform::GetInputNode(op, "X", ngb_node_map);
  auto label = paddle::platform::GetInputNode(op, "Label", ngb_node_map);
  auto dy = paddle::platform::GetInputNode(op, "Y@GRAD", ngb_node_map);
  auto xe_grad = GetCrossEntropyGrad(x, label, dy, is_soft_label, ignore_index);
166 167
  paddle::platform::SetOutputNode(op, "X@GRAD", xe_grad, ngb_node_map);
}
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

void BuildCrossEntropy2Node(
    const std::shared_ptr<paddle::framework::OperatorBase>& op,
    std::shared_ptr<
        std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
        ngb_node_map) {
  auto x = paddle::platform::GetInputNode(op, "X", ngb_node_map);
  auto label = paddle::platform::GetInputNode(op, "Label", ngb_node_map);
  auto op_attrs = paddle::framework::AttrReader(op->Attrs());
  int ignore_index = op_attrs.Get<int>("ignore_index");

  auto rank = x->get_shape().size();

  auto one_hot = convert_to_node_type(create_one_hot(label, x), x);
  auto xe = create_xe(one_hot, x);
  auto mask = convert_to_node_type(create_mask(label, ignore_index), xe);

  xe = xe * mask;

  std::shared_ptr<ngraph::Node> node_sum =
      std::make_shared<ngraph::op::Sum>(one_hot * x, ngraph::AxisSet{rank - 1});
  node_sum = paddle::platform::NgReshaper(node_sum, mask->get_shape());
  auto matchx = mask * node_sum;

  paddle::platform::SetOutputNode(op, "MatchX", matchx, ngb_node_map);
  platform::SetOutputNode(op, "XShape", x, ngb_node_map);
  paddle::platform::SetOutputNode(op, "Y", xe, ngb_node_map);
}

void BuildCrossEntropyGrad2Node(
    const std::shared_ptr<paddle::framework::OperatorBase>& op,
    std::shared_ptr<
        std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
        ngb_node_map) {
  auto op_attrs = paddle::framework::AttrReader(op->Attrs());
  int ignore_index = op_attrs.Get<int>("ignore_index");
  auto matchx = paddle::platform::GetInputNode(op, "MatchX", ngb_node_map);
  auto label = paddle::platform::GetInputNode(op, "Label", ngb_node_map);
  auto x = paddle::platform::GetInputNode(op, "XShape", ngb_node_map);
  auto dy = paddle::platform::GetInputNode(op, framework::GradVarName("Y"),
                                           ngb_node_map);

  matchx = remove_trailing_one(matchx);
  label = remove_trailing_one(label);
  x = remove_trailing_one(x);
  dy = remove_trailing_one(dy);

  auto x_shape = x->get_shape();
  auto rank = x_shape.size();

  auto one_hot = convert_to_node_type(create_one_hot(label, x), x);
  auto mask = convert_to_node_type(create_mask(label, ignore_index), x);

  auto zero = paddle::platform::CreateConstant(matchx->get_element_type(),
                                               matchx->get_shape(), {0});
  auto one = paddle::platform::CreateConstant(matchx->get_element_type(),
                                              matchx->get_shape(), {1});
  auto is_zero = std::make_shared<ngraph::op::Equal>(matchx, zero);
  matchx = std::make_shared<ngraph::op::Select>(is_zero, one, matchx);

  auto dy_bcast = std::make_shared<ngraph::op::Broadcast>(
      mask * dy, x_shape, ngraph::AxisSet{rank - 1});
  auto matchx_bcast = std::make_shared<ngraph::op::Broadcast>(
      matchx, x_shape, ngraph::AxisSet{rank - 1});

  auto xe_grad = -dy_bcast * one_hot / matchx_bcast;
  paddle::platform::SetOutputNode(op, framework::GradVarName("X"), xe_grad,
                                  ngb_node_map);
}
237 238 239
}  // namespace ngraphs
}  // namespace operators
}  // namespace paddle
240 241 242

REGISTER_NG_OP(cross_entropy, BuildCrossEntropyNode);
REGISTER_NG_OP(cross_entropy_grad, BuildCrossEntropyGradNode);
243 244
REGISTER_NG_OP(cross_entropy2, BuildCrossEntropy2Node);
REGISTER_NG_OP(cross_entropy_grad2, BuildCrossEntropyGrad2Node);