docs/cpp/source/api/library/registration.md
The library API provides macros and classes for registering custom operators with PyTorch's dispatcher.
Example:
TORCH_LIBRARY(myops, m) {
m.def("add(Tensor self, Tensor other) -> Tensor", &add_impl);
m.def("mul(Tensor self, Tensor other) -> Tensor");
m.impl("mul", torch::kCPU, &mul_cpu_impl);
m.impl("mul", torch::kCUDA, &mul_cuda_impl);
}
Example:
TORCH_LIBRARY_IMPL(myops, XLA, m) {
m.impl("mul", &mul_xla_impl);
}
Example:
// In file1.cpp
TORCH_LIBRARY(myops, m) {
m.def("add(Tensor self, Tensor other) -> Tensor", &add_impl);
}
// In file2.cpp
TORCH_LIBRARY_FRAGMENT(myops, m) {
m.def("mul(Tensor self, Tensor other) -> Tensor", &mul_impl);
}
Example:
TORCH_LIBRARY(myops, m) {
// Define with implementation
m.def("add(Tensor self, Tensor other) -> Tensor", &add_impl);
// Define schema only
m.def("mul(Tensor self, Tensor other) -> Tensor");
// Provide backend-specific implementations
m.impl("mul", torch::kCPU, &mul_cpu_impl);
m.impl("mul", torch::kCUDA, &mul_cuda_impl);
}
:members:
:no-link:
:members:
:undoc-members:
The library API provides builder methods on the Library class for registering
operators. See the Library class documentation above for the full API including
def(), impl(), and fallback() methods.
Common dispatch keys used with torch::dispatch():
torch::kCPU - CPU backendtorch::kCUDA - CUDA backendtorch::kAutograd - Autograd backendtorch::kMeta - Meta tensor backend