Lerp.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #pragma once
  2. #include <ATen/native/DispatchStub.h>
  3. #include <ATen/OpMathType.h>
  4. #include <ATen/TensorIterator.h>
  5. #include <c10/core/Scalar.h>
  6. namespace at::native {
  7. template <typename scalar_t>
  8. C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(scalar_t weight) {
  9. return std::abs(weight) < scalar_t(0.5);
  10. }
  11. template <typename scalar_t>
  12. C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(c10::complex<scalar_t> weight) {
  13. // Avoid the sqrt in abs(weight)
  14. return (weight.real() * weight.real() + weight.imag() * weight.imag()) < scalar_t(0.25);
  15. }
  16. template <typename scalar_t, typename weight_t>
  17. C10_HOST_DEVICE C10_ALWAYS_INLINE scalar_t lerp(scalar_t self_, scalar_t end_, weight_t weight_) {
  18. using opmath_t = at::opmath_type<scalar_t>;
  19. using opmath_weight_t = at::opmath_type<weight_t>;
  20. opmath_t self = self_;
  21. opmath_t end = end_;
  22. opmath_weight_t weight = weight_;
  23. // Conditional for better numeric. This has been discussed in
  24. // https://github.com/pytorch/pytorch/pull/18871
  25. return is_lerp_weight_small(weight)
  26. ? self + weight * (end - self)
  27. : end - (end - self) * (opmath_t(1) - weight);
  28. }
  29. using lerp_fn_scalar = void (*)(
  30. at::TensorIteratorBase& iter,
  31. const Scalar& weight);
  32. using lerp_fn_tensor = void (*)(
  33. at::TensorIteratorBase& iter);
  34. DECLARE_DISPATCH(lerp_fn_scalar, lerp_kernel_scalar_weight)
  35. DECLARE_DISPATCH(lerp_fn_tensor, lerp_kernel_tensor_weight)
  36. } // namespace at::native