/*
Copyright 2020 The OneFlow 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 "oneflow/core/framework/framework.h"
#include "oneflow/core/framework/op_generated.h"

namespace oneflow {

void CheckIsPerm(const std::vector<int32_t>& perm) {
  std::vector<bool> is_used(perm.size(), false);
  FOR_RANGE(size_t, i, 0, perm.size()) {
    CHECK_GE(perm[i], 0);
    CHECK_LE(perm[i], perm.size());
    CHECK_EQ(is_used[perm[i]], false);
    is_used[perm[i]] = true;
  }
}

/*static*/ Maybe<void> TransposeOp::GetSbp(user_op::SbpContext* ctx) {
  const user_op::TensorDesc& input_tensor = ctx->LogicalTensorDesc4InputArgNameAndIndex("input", 0);
  const auto& perm = ctx->Attr<std::vector<int32_t>>("perm");
  CHECK_EQ_OR_RETURN(perm.size(), input_tensor.shape().NumAxes());
  FOR_RANGE(int32_t, i, 0, perm.size()) {
    int32_t axis = perm.at(i);
    if (axis < 0) { axis += perm.size(); }
    CHECK_GE_OR_RETURN(axis, 0);
    CHECK_LT_OR_RETURN(axis, perm.size());
    ctx->NewBuilder().Split(ctx->inputs(), axis).Split(ctx->outputs(), i).Build();
  }
  ctx->NewBuilder().PartialSum(ctx->inputs()).PartialSum(ctx->outputs()).Build();
  return Maybe<void>::Ok();
}
/*static*/ Maybe<void> TransposeOp::InferLogicalTensorDesc(user_op::InferContext* ctx) {
  const user_op::TensorDesc& in_tensor_desc = ctx->InputTensorDesc("input", 0);
  user_op::TensorDesc* out_tensor_desc = ctx->MutOutputTensorDesc("output", 0);
  const Shape& in_shape = in_tensor_desc.shape();
  Shape out_shape = in_tensor_desc.shape();
  const auto& perm = ctx->Attr<std::vector<int32_t>>("perm");
  CHECK_EQ_OR_RETURN(perm.size(), in_shape.NumAxes());
  CheckIsPerm(perm);
  // if (perm.at(0) != 0) { CHECK_OR_RETURN(!in_tensor_desc->is_dynamic()); }
  out_tensor_desc->set_is_dynamic(in_tensor_desc.is_dynamic());
  FOR_RANGE(size_t, i, 0, perm.size()) { out_shape.Set(i, in_shape.At(perm[i])); }
  out_tensor_desc->set_shape(out_shape);
  return Maybe<void>::Ok();
}
/*static*/ Maybe<void> TransposeOp::InferPhysicalTensorDesc(user_op::InferContext* ctx) {
  return InferLogicalTensorDesc(ctx);
}
/*static*/ Maybe<void> TransposeOp::InferDataType(user_op::InferContext* ctx) {
  ctx->SetOutputDType("output", 0, ctx->InputDType("input", 0));
  return Maybe<void>::Ok();
}

}  // namespace oneflow
