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#include "tensorflow/compiler/tf2xla/xla_helpers.h"
17#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
18#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
19#include "tensorflow/compiler/xla/client/computation_builder.h"
20#include "tensorflow/core/framework/op_kernel.h"
21#include "tensorflow/core/framework/types.h"
22#include "tensorflow/core/kernels/no_op.h"
23
24namespace tensorflow {
25namespace {
26
27class L2LossOp : public XlaOpKernel {
28 public:
29  explicit L2LossOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
30
31  void Compile(XlaOpKernelContext* ctx) override {
32    const TensorShape input_shape = ctx->InputShape(0);
33
34    DataType dtype = ctx->input_type(0);
35    xla::ComputationBuilder* b = ctx->builder();
36
37    auto zero = XlaHelpers::Zero(b, dtype);
38    auto two = XlaHelpers::IntegerLiteral(b, dtype, 2);
39    const xla::Computation& add = *ctx->GetOrCreateAdd(dtype);
40
41    std::vector<int64> dims(input_shape.dims());
42    std::iota(dims.begin(), dims.end(), 0);
43
44    //  output = sum(t ** 2) / 2
45    auto x = ctx->Input(0);
46    ctx->SetOutput(0, b->Div(b->Reduce(b->Mul(x, x), zero, add, dims), two));
47  }
48};
49
50REGISTER_XLA_OP(Name("L2Loss"), L2LossOp);
51
52}  // namespace
53}  // namespace tensorflow
54