CPUFallback.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #pragma once
  2. #include <ATen/core/ivalue.h>
  3. #include <ATen/core/stack.h>
  4. #include <ATen/core/boxing/KernelFunction.h>
  5. #include <ATen/core/dispatch/Dispatcher.h>
  6. #include <c10/util/Metaprogramming.h>
  7. #include <torch/library.h>
  8. namespace at { namespace native {
  9. // This function implements a boxed fallback to CPU.
  10. // External backends can add their own custom logging on top if it to customize their own CPU fallbacks.
  11. TORCH_API void cpu_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
  12. // This is a helper function that backends can use to directly call their boxed CPU fallback
  13. // TODO: update and add a usage example after https://github.com/pytorch/pytorch/pull/58092 lands.
  14. template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
  15. struct _call_fallback_fn final {};
  16. template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
  17. struct _call_fallback_fn<fallback_fn, Op, symint, ReturnType(ParameterTypes...)> final {
  18. static ReturnType call(typename c10::maybe_keep_symint<symint, ParameterTypes>::type... args) {
  19. auto op = c10::Dispatcher::singleton()
  20. // TODO: figure out how to make compiler happy without dynamic casts
  21. .findSchemaOrThrow((const char*) Op::name, (const char*) Op::overload_name)
  22. //.findSchemaOrThrow("a", "b")
  23. .typed<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>();
  24. return c10::impl::BoxedKernelWrapper<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>::call(
  25. c10::BoxedKernel::makeFromFunction<fallback_fn>(),
  26. op,
  27. c10::DispatchKeySet(), // we know that the cpu_fallback doesn't use the dispatch keyset.
  28. // TODO: get std::forward<> to work
  29. args...
  30. );
  31. }
  32. };
  33. template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
  34. using call_fallback_fn_symint = _call_fallback_fn<fallback_fn, Op, true, typename Op::schema>;
  35. template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
  36. using call_fallback_fn = _call_fallback_fn<fallback_fn, Op, false, typename Op::schema>;
  37. } // namespace native
  38. } // namespace at