linspace.cc 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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/linspace.h"
  15. namespace ultra_infer {
  16. namespace function {
  17. template <typename T>
  18. void LinspaceKernel(double start, double end, int num, FDTensor *out) {
  19. FDASSERT(
  20. num > 0,
  21. "The num of linspace op should be larger than 0, but received num is %d",
  22. num);
  23. out->Allocate({num}, TypeToDataType<T>::dtype);
  24. T *out_data = reinterpret_cast<T *>(out->Data());
  25. if (num > 1) {
  26. // step should be of double type for all types
  27. double step = (static_cast<double>(end - start)) / (num - 1);
  28. int half_num = num / 2;
  29. for (int i = 0; i < num; ++i) {
  30. if (i < half_num) {
  31. out_data[i] = static_cast<T>(start + step * i);
  32. } else {
  33. out_data[i] = static_cast<T>(end - step * (num - i - 1));
  34. }
  35. }
  36. } else {
  37. out_data[0] = static_cast<T>(start);
  38. }
  39. }
  40. void Linspace(double start, double end, int num, FDTensor *out,
  41. FDDataType dtype) {
  42. FD_VISIT_INT_FLOAT_TYPES(dtype, "LinspaceKernel", ([&] {
  43. LinspaceKernel<data_t>(start, end, num, out);
  44. }));
  45. }
  46. } // namespace function
  47. } // namespace ultra_infer