1
0

interface.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <torch/extension.h>
  2. // CUDA forward declarations
  3. std::vector<at::Tensor> softmax_xentropy_cuda(
  4. const at::Tensor &input,
  5. const at::Tensor &labels,
  6. const float smoothing,
  7. const int total_classes);
  8. at::Tensor softmax_xentropy_backward_cuda(
  9. const at::Tensor &grad_loss,
  10. at::Tensor &logits,
  11. const at::Tensor &max_log_sum_exp,
  12. const at::Tensor &labels,
  13. const float smoothing,
  14. const bool inplace,
  15. const int total_classes);
  16. // C++ interface
  17. #define CHECK_CUDA(x) AT_ASSERTM(x.is_cuda(), #x " must be a CUDA tensor")
  18. #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous")
  19. #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
  20. std::vector<at::Tensor> softmax_xentropy_forward(
  21. const at::Tensor &input,
  22. const at::Tensor &labels,
  23. const float smoothing,
  24. const int total_classes=-1) {
  25. // For tensor parallel cross entropy with smoothing, we want to pass in the total number
  26. // of classes so that smoothing can be applied correctly. If total_classes=-1, use the
  27. // last dimension of the input tensor.
  28. CHECK_INPUT(input);
  29. CHECK_INPUT(labels);
  30. return softmax_xentropy_cuda(input, labels, smoothing, total_classes);
  31. }
  32. at::Tensor softmax_xentropy_backward(
  33. const at::Tensor &grad_loss,
  34. at::Tensor &logits,
  35. const at::Tensor &max_log_sum_exp,
  36. const at::Tensor &labels,
  37. const float smoothing,
  38. const bool inplace,
  39. const int total_classes=-1) {
  40. CHECK_INPUT(grad_loss);
  41. CHECK_INPUT(logits);
  42. CHECK_INPUT(max_log_sum_exp);
  43. CHECK_INPUT(labels);
  44. return softmax_xentropy_backward_cuda(grad_loss, logits, max_log_sum_exp, labels,
  45. smoothing, inplace, total_classes);
  46. }
  47. PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  48. m.def("forward", &softmax_xentropy_forward, "Softmax cross entropy loss with label smoothing forward (CUDA)", py::arg("input"), py::arg("labels"), py::arg("smoothing"), py::arg("total_classes")=-1);
  49. m.def("backward", &softmax_xentropy_backward, "Softmax cross entropy loss with label smoothing backward (CUDA)", py::arg("grad_loss"), py::arg("logits"), py::arg("max_log_sum_exp"), py::arg("labels"), py::arg("smoothing"), py::arg("inplace"), py::arg("total_classes")=-1);
  50. }