RangeUtils.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <ATen/AccumulateType.h>
  2. #include <c10/core/Scalar.h>
  3. #include <limits>
  4. namespace at::native {
  5. inline void arange_check_bounds(
  6. const c10::Scalar& start,
  7. const c10::Scalar& end,
  8. const c10::Scalar& step) {
  9. // use double precision for validation to avoid precision issues
  10. double dstart = start.to<double>();
  11. double dend = end.to<double>();
  12. double dstep = step.to<double>();
  13. TORCH_CHECK(dstep > 0 || dstep < 0, "step must be nonzero");
  14. TORCH_CHECK(
  15. std::isfinite(dstart) && std::isfinite(dend),
  16. "unsupported range: ",
  17. dstart,
  18. " -> ",
  19. dend);
  20. TORCH_CHECK(
  21. ((dstep > 0) && (dend >= dstart)) || ((dstep < 0) && (dend <= dstart)),
  22. "upper bound and lower bound inconsistent with step sign");
  23. }
  24. template <typename scalar_t>
  25. int64_t compute_arange_size(const Scalar& start, const Scalar& end, const Scalar& step) {
  26. arange_check_bounds(start, end, step);
  27. // we use double precision for (start - end) / step
  28. // to compute size_d for consistency across devices.
  29. // The problem with using accscalar_t is that accscalar_t might be float32 on gpu for a float32 scalar_t,
  30. // but double on cpu for the same,
  31. // and the effective output size starts differing on CPU vs GPU because of precision issues, which
  32. // we dont want.
  33. // the corner-case we do want to take into account is int64_t, which has higher precision than double
  34. double size_d;
  35. if constexpr (std::is_same_v<scalar_t, int64_t>) {
  36. using accscalar_t = at::acc_type<scalar_t, false>;
  37. auto xstart = start.to<accscalar_t>();
  38. auto xend = end.to<accscalar_t>();
  39. auto xstep = step.to<accscalar_t>();
  40. int64_t sgn = (xstep > 0) - (xstep < 0);
  41. size_d = std::ceil((xend - xstart + xstep - sgn) / xstep);
  42. } else {
  43. size_d = std::ceil(static_cast<double>(end.to<double>() - start.to<double>())
  44. / step.to<double>());
  45. }
  46. TORCH_CHECK(size_d >= 0 && size_d <= static_cast<double>(std::numeric_limits<int64_t>::max()),
  47. "invalid size, possible overflow?");
  48. return static_cast<int64_t>(size_d);
  49. }
  50. } // namespace at::native