cumprod.cc 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (c) 2022 PaddlePaddle 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. #include "ultra_infer/function/cumprod.h"
  15. namespace ultra_infer {
  16. namespace function {
  17. void GetCumprodDimInfo(const std::vector<int64_t> &dim, int cumprod_dim,
  18. size_t *outer_dim, size_t *mid_dim, size_t *inner_dim) {
  19. int dim_size = dim.size();
  20. FDASSERT(cumprod_dim >= -dim_size,
  21. "The input dim of CumprodOp should be larger than the opposite "
  22. "rank of input x which is %d. But received dim = %d",
  23. -dim_size, cumprod_dim);
  24. FDASSERT(cumprod_dim < dim_size,
  25. "The input dim of CumprodOp should be smaller than the "
  26. "rank of input x which is %d. But received dim = %d",
  27. dim_size, cumprod_dim);
  28. if (cumprod_dim < 0)
  29. cumprod_dim += dim_size;
  30. *outer_dim = 1;
  31. for (int i = 0; i < cumprod_dim; ++i) {
  32. *outer_dim *= dim[i];
  33. }
  34. *mid_dim = dim[cumprod_dim];
  35. *inner_dim = 1;
  36. for (int i = cumprod_dim + 1; i < dim_size; ++i) {
  37. *inner_dim *= dim[i];
  38. }
  39. }
  40. template <typename T>
  41. void CumprodKernel(const FDTensor &x, FDTensor *out, int axis) {
  42. auto *x_data = reinterpret_cast<const T *>(x.Data());
  43. auto shape = x.Shape();
  44. size_t outer_dim = 1;
  45. size_t mid_dim = 1;
  46. size_t inner_dim = 1;
  47. GetCumprodDimInfo(shape, axis, &outer_dim, &mid_dim, &inner_dim);
  48. out->Allocate(x.Shape(), x.Dtype());
  49. auto *out_data = reinterpret_cast<T *>(out->Data());
  50. for (size_t i = 0; i < outer_dim; i++) {
  51. for (size_t j = 0; j < mid_dim; j++) {
  52. for (size_t k = 0; k < inner_dim; k++) {
  53. size_t pos = i * mid_dim * inner_dim + j * inner_dim + k;
  54. if (j == 0) {
  55. out_data[pos] = x_data[pos];
  56. } else {
  57. out_data[pos] = out_data[pos - inner_dim] * x_data[pos];
  58. }
  59. }
  60. }
  61. }
  62. }
  63. void Cumprod(const FDTensor &x, FDTensor *out, int axis) {
  64. FD_VISIT_INT_FLOAT_TYPES(x.dtype, "CumprodKernel",
  65. ([&] { CumprodKernel<data_t>(x, out, axis); }));
  66. }
  67. } // namespace function
  68. } // namespace ultra_infer