aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/tf2xla/kernels/xla_broadcast_helper_op.cc
blob: 412afeaaad96842521fbd306f5b666e837e675fd (plain)
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
/* Copyright 2018 The TensorFlow 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 "absl/algorithm/container.h"
#include "absl/strings/str_join.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/core/errors.h"

namespace tensorflow {
namespace {

class XlaBroadcastHelperOp : public XlaOpKernel {
 public:
  explicit XlaBroadcastHelperOp(OpKernelConstruction* context)
      : XlaOpKernel(context) {}

  void Compile(XlaOpKernelContext* context) override {
    xla::XlaOp lhs = context->Input(0);
    xla::XlaOp rhs = context->Input(1);
    const TensorShape lhs_shape = context->InputShape(0);
    const TensorShape rhs_shape = context->InputShape(1);

    const bool broadcast_lhs = lhs_shape.dims() < rhs_shape.dims();
    const TensorShape* min_rank_shape = broadcast_lhs ? &lhs_shape : &rhs_shape;
    const TensorShape* max_rank_shape = broadcast_lhs ? &rhs_shape : &lhs_shape;

    std::vector<int64> broadcast_dims;
    OP_REQUIRES_OK(context, context->ConstantInputAsIntVector("broadcast_dims",
                                                              &broadcast_dims));
    if (broadcast_dims.empty()) {
      OP_REQUIRES(
          context,
          lhs_shape.dims() == rhs_shape.dims() || lhs_shape.dims() == 0 ||
              rhs_shape.dims() == 0,
          errors::InvalidArgument(
              "If broadcast_dims is empty, both "
              "arguments must have equal rank; "
              "argument shapes, or at least one argument must be a scalar: ",
              lhs_shape.DebugString(), " and ", rhs_shape.DebugString()));
      context->SetOutput(0, lhs);
      context->SetOutput(1, rhs);
      return;
    }

    OP_REQUIRES(
        context, broadcast_dims.size() == min_rank_shape->dims(),
        errors::InvalidArgument(
            "broadcast_dims must have size equal to the smaller argument rank; "
            "broadcast_dims: [",
            absl::StrJoin(broadcast_dims, ","), "]; argument shapes: ",
            lhs_shape.DebugString(), " and ", rhs_shape.DebugString()));
    std::vector<int64> sorted_broadcast_dims = broadcast_dims;
    absl::c_sort(sorted_broadcast_dims);
    std::set<int64> dims_set(broadcast_dims.begin(), broadcast_dims.end());
    OP_REQUIRES(context,
                dims_set.size() == broadcast_dims.size() &&
                    broadcast_dims == sorted_broadcast_dims,
                errors::InvalidArgument(
                    "Duplicate or nonmonotonic dimension in broadcast_dims; "
                    "broadcast_dims: [",
                    absl::StrJoin(broadcast_dims, ","), "]"));

    std::vector<int64> broadcast_shape(max_rank_shape->dims(), 1LL);
    for (int i = 0; i < broadcast_dims.size(); ++i) {
      const int dim = broadcast_dims[i];
      OP_REQUIRES(
          context, dim >= 0 && dim < broadcast_shape.size(),
          errors::InvalidArgument(
              "Invalid broadcast dimension (", dim, "); broadcast_dims: [",
              absl::StrJoin(broadcast_dims, ","), "]; argument shapes: ",
              lhs_shape.DebugString(), " and ", rhs_shape.DebugString()));
      broadcast_shape[dim] = min_rank_shape->dim_size(i);
    }
    xla::PrimitiveType type = context->input_xla_type(0);
    xla::Shape broadcast_xla_shape =
        xla::ShapeUtil::MakeShape(type, broadcast_shape);
    if (broadcast_lhs) {
      lhs = xla::BroadcastInDim(lhs, broadcast_xla_shape, broadcast_dims);
    } else {
      rhs = xla::BroadcastInDim(rhs, broadcast_xla_shape, broadcast_dims);
    }
    context->SetOutput(0, lhs);
    context->SetOutput(1, rhs);
  }

 private:
  xla::DotDimensionNumbers dnums_;

  TF_DISALLOW_COPY_AND_ASSIGN(XlaBroadcastHelperOp);
};

REGISTER_XLA_OP(
    Name("XlaBroadcastHelper").CompileTimeConstInput("broadcast_dims"),
    XlaBroadcastHelperOp);

}  // namespace
}  // namespace tensorflow