Home | History | Annotate | Download | only in kernels
      1 /* Copyright 2018 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 #include "tensorflow/compiler/tf2xla/lib/scatter.h"
     17 #include "tensorflow/compiler/tf2xla/xla_helpers.h"
     18 #include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
     19 #include "tensorflow/compiler/tf2xla/xla_op_registry.h"
     20 #include "tensorflow/compiler/xla/client/computation_builder.h"
     21 
     22 namespace tensorflow {
     23 namespace {
     24 
     25 class UnsortedSegmentSum : public XlaOpKernel {
     26  public:
     27   explicit UnsortedSegmentSum(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
     28     OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_));
     29   }
     30 
     31   void Compile(XlaOpKernelContext* ctx) override {
     32     // output = unsorted_segment_sum(data, indices, num_segments)
     33     // Compute a tensor such that:
     34     //    output[i] = sum over {j where indices[j] == i} of data[j]
     35     //    output[i] == 0 if i does not appear in indices
     36     //
     37     // Contrast with segment_sum(), which assumes indices are sorted and that
     38     // max(indices)+1 is the desired size of the output.
     39     //
     40     // The returned output tensor has the same type as data, and the same shape
     41     // as data with the first indices.rank dimensions are replaced
     42     // by a single dimension with size num_segments.
     43     auto data = ctx->Input(0);
     44     TensorShape data_shape = ctx->InputShape(0);
     45 
     46     auto indices = ctx->Input(1);
     47     TensorShape indices_shape = ctx->InputShape(1);
     48 
     49     int64 num_segments;
     50     OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(2, &num_segments));
     51 
     52     OP_REQUIRES(ctx, data_shape.dims() >= indices_shape.dims(),
     53                 errors::InvalidArgument(
     54                     "UnsortedSegmentSum requires that indices' rank be"
     55                     " less than or equal to data's rank."));
     56     // Validate that indices.shape is a prefix of data.shape.
     57     for (int d = 0; d < indices_shape.dims(); ++d) {
     58       OP_REQUIRES(ctx, (data_shape.dim_size(d) == indices_shape.dim_size(d)),
     59                   errors::InvalidArgument(
     60                       "UnsortedSegmentSum requires indices shape to be prefix"
     61                       " of data_shape, but dimension ",
     62                       d, " differs ", data_shape.dim_size(d), " vs. ",
     63                       indices_shape.dim_size(d)));
     64     }
     65     xla::ComputationBuilder* builder = ctx->builder();
     66     TensorShape buffer_shape = data_shape;
     67     buffer_shape.RemoveDimRange(0, indices_shape.dims());
     68     buffer_shape.InsertDim(0, num_segments);
     69     auto buffer = builder->Broadcast(XlaHelpers::Zero(builder, dtype_),
     70                                      buffer_shape.dim_sizes());
     71 
     72     auto combiner =
     73         [](xla::ComputationDataHandle a, xla::ComputationDataHandle b,
     74            xla::ComputationBuilder* builder) { return builder->Add(a, b); };
     75 
     76     auto result = XlaScatter(buffer, /*updates=*/data, indices,
     77                              /*indices_are_vectors=*/false, combiner, builder);
     78     OP_REQUIRES_OK(ctx, result.status());
     79     ctx->SetOutput(0, result.ValueOrDie());
     80   }
     81 
     82  private:
     83   DataType dtype_;
     84 };
     85 
     86 REGISTER_XLA_OP(Name("UnsortedSegmentSum"), UnsortedSegmentSum);
     87 
     88 }  // namespace
     89 }  // namespace tensorflow
     90