• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 // XLA-specific Ops for broadcasting used in gradient
17 // code.
18 
19 #include "absl/strings/str_join.h"
20 #include "tensorflow/compiler/tf2xla/xla_helpers.h"
21 #include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
22 #include "tensorflow/compiler/tf2xla/xla_op_registry.h"
23 #include "tensorflow/compiler/xla/literal.h"
24 #include "tensorflow/core/platform/macros.h"
25 #include "tensorflow/core/platform/types.h"
26 #include "tensorflow/core/util/bcast.h"
27 
28 namespace tensorflow {
29 namespace {
30 
31 // Given shapes of two tensors, computes the broadcast shape.
32 class BCastArgsOp : public XlaOpKernel {
33  public:
BCastArgsOp(OpKernelConstruction * ctx)34   explicit BCastArgsOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
35     OP_REQUIRES_OK(ctx, ctx->MatchSignature({DT_INT32, DT_INT32}, {DT_INT32}));
36   }
37 
Compile(XlaOpKernelContext * ctx)38   void Compile(XlaOpKernelContext* ctx) override {
39     OP_REQUIRES(
40         ctx, ctx->num_inputs() == 2,
41         errors::Unimplemented("Broadcast for n-ary operations (n > 2)"));
42     absl::InlinedVector<BCast::Vec, 2> shapes;
43     for (int i = 0; i < ctx->num_inputs(); ++i) {
44       const TensorShape in_shape = ctx->InputShape(i);
45       OP_REQUIRES(ctx, TensorShapeUtils::IsVector(in_shape),
46                   errors::InvalidArgument("In[", i, "] must be a vector.",
47                                           in_shape.DebugString()));
48       std::vector<int64> shape;
49       OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(i, &shape));
50       shapes.push_back(BCast::Vec(shape.begin(), shape.end()));
51     }
52     BCast bcast(shapes[0], shapes[1]);
53     OP_REQUIRES(ctx, bcast.IsValid(),
54                 errors::InvalidArgument(
55                     "Incompatible shapes: [", absl::StrJoin(shapes[0], ","),
56                     "] vs. [", absl::StrJoin(shapes[1], ","), "]"));
57 
58     const int64 len = bcast.output_shape().size();
59     Tensor output(DT_INT32, TensorShape({len}));
60     for (int64 i = 0; i < len; ++i) {
61       output.flat<int32>()(i) = static_cast<int32>(bcast.output_shape()[i]);
62     }
63     ctx->SetConstantOutput(0, output);
64   }
65 
66  private:
67   TF_DISALLOW_COPY_AND_ASSIGN(BCastArgsOp);
68 };
69 REGISTER_XLA_OP(Name("BroadcastArgs")
70                     .CompileTimeConstantInput("s0")
71                     .CompileTimeConstantInput("s1"),
72                 BCastArgsOp);
73 
74 // Given shapes of two tensors, computes the reduction indices for the
75 // gradient computation.
76 //
77 // TODO(zhifengc):
78 //   1. Adds support for n-ary (n >= 2).
79 class BCastGradArgsOp : public XlaOpKernel {
80  public:
BCastGradArgsOp(OpKernelConstruction * ctx)81   explicit BCastGradArgsOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
82     OP_REQUIRES_OK(
83         ctx, ctx->MatchSignature({DT_INT32, DT_INT32}, {DT_INT32, DT_INT32}));
84   }
85 
Compile(XlaOpKernelContext * ctx)86   void Compile(XlaOpKernelContext* ctx) override {
87     OP_REQUIRES(
88         ctx, ctx->num_inputs() == 2,
89         errors::Unimplemented("Broadcast for n-ary operations (n > 2)"));
90 
91     absl::InlinedVector<BCast::Vec, 4> shapes;
92     for (int i = 0; i < ctx->num_inputs(); ++i) {
93       const TensorShape in_shape = ctx->InputShape(i);
94       OP_REQUIRES(ctx, TensorShapeUtils::IsVector(in_shape),
95                   errors::InvalidArgument("In[", i, "] must be a vector.",
96                                           in_shape.DebugString()));
97       std::vector<int64> vec;
98       OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(i, &vec));
99 
100       shapes.push_back(BCast::Vec(vec.begin(), vec.end()));
101     }
102     BCast bcast(shapes[0], shapes[1]);
103     OP_REQUIRES(ctx, bcast.IsValid(),
104                 errors::InvalidArgument(
105                     "Incompatible shapes: [", absl::StrJoin(shapes[0], ","),
106                     "] vs. [", absl::StrJoin(shapes[1], ","), "]"));
107     Output(ctx, 0, bcast.grad_x_reduce_idx());
108     Output(ctx, 1, bcast.grad_y_reduce_idx());
109   }
110 
111  private:
Output(XlaOpKernelContext * ctx,int idx,const BCast::Vec & v)112   void Output(XlaOpKernelContext* ctx, int idx, const BCast::Vec& v) {
113     const int64 len = v.size();
114     Tensor constant(DT_INT32, TensorShape({len}));
115     for (int64 i = 0; i < len; ++i) {
116       constant.flat<int32>()(i) = static_cast<int32>(v[i]);
117     }
118     ctx->SetConstantOutput(idx, constant);
119   }
120 
121   TF_DISALLOW_COPY_AND_ASSIGN(BCastGradArgsOp);
122 };
123 
124 REGISTER_XLA_OP(Name("BroadcastGradientArgs")
125                     .CompileTimeConstantInput("s0")
126                     .CompileTimeConstantInput("s1"),
127                 BCastGradArgsOp);
128 
129 }  // namespace
130 }  // namespace tensorflow
131