<commit_before>/* Copyright 2015 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 <functional>
#include <unordered_map>
#include <utility>

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/hash/hash.h"

namespace tensorflow {

typedef Eigen::ThreadPoolDevice CPUDevice;

template <typename T, typename TIndex>
class UniqueOp : public OpKernel {
 public:
  explicit UniqueOp(OpKernelConstruction* context) : OpKernel(context) {}

  void Compute(OpKernelContext* context) override {
    const Tensor& input = context->input(0);
    // TODO(dga):  Make unique polymorphic for returning int32 and int64
    // vectors to support large tensors.
    OP_REQUIRES(context,
                input.NumElements() <= std::numeric_limits<int32>::max(),
                errors::InvalidArgument(
                    "unique does not support input tensors larger than ",
                    std::numeric_limits<int32>::max(), " elements"));

    int64 axis = 0;
    std::vector<int64> new_sizes{1, input.NumElements(), 1};
    if (context->num_inputs() == 1) {
      OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
                  errors::InvalidArgument("unique expects a 1D vector."));
    } else {
      // In case of UniqueV2, the axis is a 1D vector. The purpose is
      // to allow specifying either "no axis" or "axis". The `[]` means
      // "no axis", while `[x]` means `axis = x`.
      const Tensor& axis_tensor = context->input(1);
      OP_REQUIRES(context, TensorShapeUtils::IsVector(axis_tensor.shape()),
                  errors::InvalidArgument("axis expects a 1D vector."));
      OP_REQUIRES(
          context, axis_tensor.NumElements() <= 1,
          errors::InvalidArgument(
              "axis does not support input tensors larger than 1 elements"));
      if (axis_tensor.NumElements() == 0) {
        OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
                    errors::InvalidArgument("unique expects a 1D vector."));
      } else {
        auto axis_vec = axis_tensor.vec<int64>();
        axis = axis_vec(0);
        axis = axis < 0 ? axis + input.dims() : axis;
        OP_REQUIRES(context, 0 <= axis && axis < input.dims(),
                    errors::InvalidArgument("axis has to be between [0, ",
                                            input.dims(), ")"));
        if (axis > 0) {
          for (int64 i = 0; i < axis; i++) {
            new_sizes[0] *= input.dim_size(i);
          }
        }
        new_sizes[1] = input.dim_size(axis);
        if (axis + 1 < input.dims()) {
          for (int64 i = axis + 1; i < input.dims(); i++) {
            new_sizes[2] *= input.dim_size(i);
          }
        }
      }
    }

    auto Tin = input.shaped<T, 3>(new_sizes);

    Tensor* idx = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(
                                1, TensorShape({Tin.dimension(1)}), &idx));
    auto idx_vec = idx->template vec<TIndex>();

    auto hash_fn = [&Tin](const int64& key) -> unsigned long {
      size_t h = 0;
      for (int64 i = 0; i < Tin.dimension(0); i++) {
        for (int64 j = 0; j < Tin.dimension(2); j++) {
          h = Hash64Combine(h, hash<T>{}(Tin(i, key, j)));
        }
      }
      return h;
    };

    auto equal_to_fn = [&Tin](const int64& lhs, const int64& rhs) {
      for (int64 i = 0; i < Tin.dimension(0); i++) {
        for (int64 j = 0; j < Tin.dimension(2); j++) {
          if (Tin(i, lhs, j) != Tin(i, rhs, j)) {
            return false;
          }
        }
      }
      return true;
    };

    std::unordered_map<int64, int64, decltype(hash_fn), decltype(equal_to_fn)>
        uniq(0, hash_fn, equal_to_fn);

    uniq.reserve(2 * Tin.dimension(1));

    for (int64 i = 0, j = 0; i < Tin.dimension(1); ++i) {
      auto it = uniq.insert(std::make_pair(i, j));
      idx_vec(i) = it.first->second;
      if (it.second) {
        ++j;
      }
    }

    int64 uniq_size = static_cast<int64>(uniq.size());
    new_sizes[1] = uniq_size;
    TensorShape output_shape(input.shape());
    output_shape.set_dim(axis, uniq_size);
    Tensor* output = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
    auto Tout = output->shaped<T, 3>(new_sizes);

    for (auto it : uniq) {
      for (int64 i = 0; i < Tin.dimension(0); i++) {
        for (int64 j = 0; j < Tin.dimension(2); j++) {
          Tout(i, it.second, j) = Tin(i, it.first, j);
        }
      }
    }

    if (num_outputs() > 2) {
      OP_REQUIRES_OK(context, context->allocate_output(
                                  2, TensorShape({uniq_size}), &output));
      auto count_output_vec = output->template vec<TIndex>();
      count_output_vec.setZero();
      for (int64 i = 0; i < Tin.dimension(1); ++i) {
        count_output_vec(idx_vec(i))++;
      }
    }
  }
};

#define REGISTER_UNIQUE(type)                                    \
  REGISTER_KERNEL_BUILDER(Name("Unique")                         \<commit_msg>Replace loop iteration with `chip` (#15289)<commit_after>/* Copyright 2015 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 <functional>
#include <unordered_map>
#include <utility>

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/hash/hash.h"

namespace tensorflow {

typedef Eigen::ThreadPoolDevice CPUDevice;

template <typename T, typename TIndex>
class UniqueOp : public OpKernel {
 public:
  explicit UniqueOp(OpKernelConstruction* context) : OpKernel(context) {}

  void Compute(OpKernelContext* context) override {
    const Tensor& input = context->input(0);
    // TODO(dga):  Make unique polymorphic for returning int32 and int64
    // vectors to support large tensors.
    OP_REQUIRES(context,
                input.NumElements() <= std::numeric_limits<int32>::max(),
                errors::InvalidArgument(
                    "unique does not support input tensors larger than ",
                    std::numeric_limits<int32>::max(), " elements"));

    int64 axis = 0;
    std::vector<int64> new_sizes{1, input.NumElements(), 1};
    if (context->num_inputs() == 1) {
      OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
                  errors::InvalidArgument("unique expects a 1D vector."));
    } else {
      // In case of UniqueV2, the axis is a 1D vector. The purpose is
      // to allow specifying either "no axis" or "axis". The `[]` means
      // "no axis", while `[x]` means `axis = x`.
      const Tensor& axis_tensor = context->input(1);
      OP_REQUIRES(context, TensorShapeUtils::IsVector(axis_tensor.shape()),
                  errors::InvalidArgument("axis expects a 1D vector."));
      OP_REQUIRES(
          context, axis_tensor.NumElements() <= 1,
          errors::InvalidArgument(
              "axis does not support input tensors larger than 1 elements"));
      if (axis_tensor.NumElements() == 0) {
        OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
                    errors::InvalidArgument("unique expects a 1D vector."));
      } else {
        auto axis_vec = axis_tensor.vec<int64>();
        axis = axis_vec(0);
        axis = axis < 0 ? axis + input.dims() : axis;
        OP_REQUIRES(context, 0 <= axis && axis < input.dims(),
                    errors::InvalidArgument("axis has to be between [0, ",
                                            input.dims(), ")"));
        if (axis > 0) {
          for (int64 i = 0; i < axis; i++) {
            new_sizes[0] *= input.dim_size(i);
          }
        }
        new_sizes[1] = input.dim_size(axis);
        if (axis + 1 < input.dims()) {
          for (int64 i = axis + 1; i < input.dims(); i++) {
            new_sizes[2] *= input.dim_size(i);
          }
        }
      }
    }

    auto Tin = input.shaped<T, 3>(new_sizes);

    Tensor* idx = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(
                                1, TensorShape({Tin.dimension(1)}), &idx));
    auto idx_vec = idx->template vec<TIndex>();

    auto hash_fn = [&Tin](const int64& key) -> unsigned long {
      size_t h = 0;
      for (int64 i = 0; i < Tin.dimension(0); i++) {
        for (int64 j = 0; j < Tin.dimension(2); j++) {
          h = Hash64Combine(h, hash<T>{}(Tin(i, key, j)));
        }
      }
      return h;
    };

    auto equal_to_fn = [&Tin](const int64& lhs, const int64& rhs) {
      for (int64 i = 0; i < Tin.dimension(0); i++) {
        for (int64 j = 0; j < Tin.dimension(2); j++) {
          if (Tin(i, lhs, j) != Tin(i, rhs, j)) {
            return false;
          }
        }
      }
      return true;
    };

    std::unordered_map<int64, int64, decltype(hash_fn), decltype(equal_to_fn)>
        uniq(0, hash_fn, equal_to_fn);

    uniq.reserve(2 * Tin.dimension(1));

    for (int64 i = 0, j = 0; i < Tin.dimension(1); ++i) {
      auto it = uniq.insert(std::make_pair(i, j));
      idx_vec(i) = it.first->second;
      if (it.second) {
        ++j;
      }
    }

    int64 uniq_size = static_cast<int64>(uniq.size());
    new_sizes[1] = uniq_size;
    TensorShape output_shape(input.shape());
    output_shape.set_dim(axis, uniq_size);
    Tensor* output = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
    auto Tout = output->shaped<T, 3>(new_sizes);

    for (auto it : uniq) {
      Tout.chip(it.second, 1) = Tin.chip(it.first, 1);
    }

    if (num_outputs() > 2) {
      OP_REQUIRES_OK(context, context->allocate_output(
                                  2, TensorShape({uniq_size}), &output));
      auto count_output_vec = output->template vec<TIndex>();
      count_output_vec.setZero();
      for (int64 i = 0; i < Tin.dimension(1); ++i) {
        count_output_vec(idx_vec(i))++;
      }
    }
  }
};

#define REGISTER_UNIQUE(type)                                    \
  REGISTER_KERNEL_BUILDER(Name("Unique")                         \
{'fraction_non_alphanumeric': 0.1476364268335071, 'fraction_numerical': 0.01937782412234967, 'mean_word_length': 2.519571865443425, 'pattern_counts': {'":': 0, '<': 63, '<?xml version=': 0, '>': 59, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6422173', 'n_tokens_mistral': 3753, 'n_tokens_neox': 3540, 'n_words': 931}