1/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16// XLA implementations of Categorical op.
17
18#include "tensorflow/compiler/tf2xla/shape_util.h"
19#include "tensorflow/compiler/tf2xla/type_util.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/client/lib/arithmetic.h"
24#include "tensorflow/core/framework/op_kernel.h"
25#include "tensorflow/core/framework/tensor.h"
26#include "tensorflow/core/framework/tensor_shape.h"
27
28namespace tensorflow {
29namespace {
30
31class CategoricalOp : public XlaOpKernel {
32 public:
33  explicit CategoricalOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
34
35  void Compile(XlaOpKernelContext* ctx) override {
36    // Get the logits
37    const xla::ComputationDataHandle& logits = ctx->Input(0);
38    TensorShape logits_shape = ctx->InputShape(0);
39    int64 num_samples;
40    OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(1, &num_samples));
41    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(logits_shape),
42                errors::InvalidArgument("logits should be a matrix, got shape ",
43                                        logits_shape.DebugString()));
44    OP_REQUIRES(ctx, num_samples >= 0,
45                errors::InvalidArgument(
46                    "num_samples should be nonnegative, got ", num_samples));
47
48    for (int i = 0; i < 2; i++) {
49      const int64 dim = logits_shape.dim_size(i);
50      OP_REQUIRES(
51          ctx, static_cast<int>(dim) == dim,
52          errors::InvalidArgument("logits.shape = ", logits_shape.DebugString(),
53                                  " too large for int"));
54    }
55
56    const int64 batch_size = logits_shape.dim_size(0);
57    const int64 num_classes = logits_shape.dim_size(1);
58
59    xla::ComputationBuilder* builder = ctx->builder();
60
61    std::array<int64, 3> uniform_shape_array = {
62        {batch_size, num_samples, num_classes}};
63    xla::PrimitiveType uniform_xla_type;
64    OP_REQUIRES_OK(ctx,
65                   DataTypeToPrimitiveType(input_type(0), &uniform_xla_type));
66    xla::Shape uniform_shape =
67        xla::ShapeUtil::MakeShape(uniform_xla_type, uniform_shape_array);
68    auto uniforms = builder->RngUniform(
69        XlaHelpers::Zero(builder, input_type(0)),
70        XlaHelpers::One(builder, input_type(0)), uniform_shape);
71
72    // Use Gumbel softmax trick to generate categorical samples.
73    // See:
74    // https://hips.seas.harvard.edu/blog/2013/04/06/the-gumbel-max-trick-for-discrete-distributions/
75    // TODO(b/68769470): Switch to using a cumulative sum approach.
76    auto softmax_entries =
77        builder->Sub(logits, builder->Log(builder->Neg(builder->Log(uniforms))),
78                     /*broadcast_dimensions=*/{0, 2});
79
80    TensorShape softmax_shape(uniform_shape_array);
81    xla::ComputationDataHandle argmax;
82    OP_REQUIRES_OK(
83        ctx,
84        XlaHelpers::ArgMax(builder, ctx, softmax_entries, softmax_shape,
85                           input_type(0), output_type(0), /*axis=*/2, &argmax));
86
87    ctx->SetOutput(0, argmax);
88  }
89
90 private:
91  TF_DISALLOW_COPY_AND_ASSIGN(CategoricalOp);
92};
93
94// TODO(b/68769717): Rename this sampler to Categorical.
95REGISTER_XLA_OP(Name("Multinomial").CompileTimeConstInput("num_samples"),
96                CategoricalOp);
97
98}  // anonymous namespace
99}  // namespace tensorflow
100