This tutorial introduces an API for binding C++ classes into PyTorch.
The API is very similar to
pybind11, and most of the concepts will transfer
over if you’re familiar with that system.
Implementing and Binding the Class in C++
For this tutorial, we are going to define a simple C++ class that maintains persistent
state in a member variable.
// This header is all you need to do the C++ portions of this// tutorial#include<torch/script.h>// This header is what defines the custom class registration// behavior specifically. script.h already includes this, but// we include it here so you know it exists in case you want// to look at the API or implementation.#include<torch/custom_class.h>#include<string>#include<vector>template<classT>structMyStackClass:torch::CustomClassHolder{std::vector<T>stack_;MyStackClass(std::vector<T>init):stack_(init.begin(),init.end()){}voidpush(Tx){stack_.push_back(x);}Tpop(){autoval=stack_.back();stack_.pop_back();returnval;}c10::intrusive_ptr<MyStackClass>clone()const{returnc10::make_intrusive<MyStackClass>(stack_);}voidmerge(constc10::intrusive_ptr<MyStackClass>&c){for(auto&elem:c->stack_){push(elem);}}};
There are several things to note:
torch/custom_class.h is the header you need to include to extend PyTorch
with your custom class.
Notice that whenever we are working with instances of the custom
class, we do it via instances of c10::intrusive_ptr<>. Think of intrusive_ptr
as a smart pointer like std::shared_ptr, but the reference count is stored
directly in the object, as opposed to a separate metadata block (as is done in
std::shared_ptr. torch::Tensor internally uses the same pointer type;
and custom classes have to also use this pointer type so that we can
consistently manage different object types.
The second thing to notice is that the user-defined class must inherit from
torch::CustomClassHolder. This ensures that the custom class has space to
store the reference count.
Now let’s take a look at how we will make this class visible to PyTorch, a process called
binding the class:
// Notice a few things:// - We pass the class to be registered as a template parameter to// `torch::class_`. In this instance, we've passed the// specialization of the MyStackClass class ``MyStackClass<std::string>``.// In general, you cannot register a non-specialized template// class. For non-templated classes, you can just pass the// class name directly as the template parameter.// - The arguments passed to the constructor make up the "qualified name"// of the class. In this case, the registered class will appear in// Python and C++ as `torch.classes.my_classes.MyStackClass`. We call// the first argument the "namespace" and the second argument the// actual class name.TORCH_LIBRARY(my_classes,m){m.class_<MyStackClass<std::string>>("MyStackClass")// The following line registers the contructor of our MyStackClass// class that takes a single `std::vector<std::string>` argument,// i.e. it exposes the C++ method `MyStackClass(std::vector<T> init)`.// Currently, we do not support registering overloaded// constructors, so for now you can only `def()` one instance of// `torch::init`..def(torch::init<std::vector<std::string>>())// The next line registers a stateless (i.e. no captures) C++ lambda// function as a method. Note that a lambda function must take a// `c10::intrusive_ptr<YourClass>` (or some const/ref version of that)// as the first argument. Other arguments can be whatever you want..def("top",[](constc10::intrusive_ptr<MyStackClass<std::string>>&self){returnself->stack_.back();})// The following four lines expose methods of the MyStackClass<std::string>// class as-is. `torch::class_` will automatically examine the// argument and return types of the passed-in method pointers and// expose these to Python and TorchScript accordingly. Finally, notice// that we must take the *address* of the fully-qualified method name,// i.e. use the unary `&` operator, due to C++ typing rules..def("push",&MyStackClass<std::string>::push).def("pop",&MyStackClass<std::string>::pop).def("clone",&MyStackClass<std::string>::clone).def("merge",&MyStackClass<std::string>::merge);}
Building the Example as a C++ Project With CMake
Now, we’re going to build the above C++ code with the CMake build system. First, take all the C++ code
we’ve covered so far and place it in a file called class.cpp.
Then, write a simple CMakeLists.txt file and place it in the
same directory. Here is what CMakeLists.txt should look like:
cmake_minimum_required(VERSION3.1FATAL_ERROR)project(custom_class)find_package(TorchREQUIRED)# Define our library targetadd_library(custom_classSHAREDclass.cpp)set(CMAKE_CXX_STANDARD14)# Link against LibTorchtarget_link_libraries(custom_class"${TORCH_LIBRARIES}")
Also, create a build directory. Your file tree should look like this:
What you’ll find is there is now (among other things) a dynamic library
file present in the build directory. On Linux, this is probably named
libcustom_class.so. So the file tree should look like:
Now that we have our class and its registration compiled into an .so file,
we can load that .so into Python and try it out. Here’s a script that
demonstrates that:
importtorch# `torch.classes.load_library()` allows you to pass the path to your .so file# to load it in and make the custom C++ classes available to both Python and# TorchScripttorch.classes.load_library("build/libcustom_class.so")# You can query the loaded libraries like this:print(torch.classes.loaded_libraries)# prints {'/custom_class_project/build/libcustom_class.so'}# We can find and instantiate our custom C++ class in python by using the# `torch.classes` namespace:## This instantiation will invoke the MyStackClass(std::vector<T> init)# constructor we registered earliers=torch.classes.my_classes.MyStackClass(["foo","bar"])# We can call methods in Pythons.push("pushed")asserts.pop()=="pushed"# Test custom operators.push("pushed")torch.ops.my_classes.manipulate_instance(s)# acting as s.pop()asserts.top()=="bar"# Returning and passing instances of custom classes works as you'd expects2=s.clone()s.merge(s2)forexpectedin["bar","foo","bar","foo"]:asserts.pop()==expected# We can also use the class in TorchScript# For now, we need to assign the class's type to a local in order to# annotate the type on the TorchScript function. This may change# in the future.MyStackClass=torch.classes.my_classes.MyStackClass@torch.jit.scriptdefdo_stacks(s:MyStackClass):# We can pass a custom class instance# We can instantiate the classs2=torch.classes.my_classes.MyStackClass(["hi","mom"])s2.merge(s)# We can call a method on the class# We can also return instances of the class# from TorchScript function/methodsreturns2.clone(),s2.top()stack,top=do_stacks(torch.classes.my_classes.MyStackClass(["wow"]))asserttop=="wow"forexpectedin["wow","mom","hi"]:assertstack.pop()==expected
Defining Serialization/Deserialization Methods for Custom C++ Classes
If you try to save a ScriptModule with a custom-bound C++ class as
an attribute, you’ll get the following error:
This is because PyTorch cannot automatically figure out what information
save from your C++ class. You must specify that manually. The way to do that
is to define __getstate__ and __setstate__ methods on the class using
the special def_pickle method on class_.
Here is an example of the def_pickle call we can add to the registration of
MyStackClass to include serialization methods:
// class_<>::def_pickle allows you to define the serialization// and deserialization methods for your C++ class.// Currently, we only support passing stateless lambda functions// as arguments to def_pickle.def_pickle(// __getstate__// This function defines what data structure should be produced// when we serialize an instance of this class. The function// must take a single `self` argument, which is an intrusive_ptr// to the instance of the object. The function can return// any type that is supported as a return value of the TorchScript// custom operator API. In this instance, we've chosen to return// a std::vector<std::string> as the salient data to preserve// from the class.[](
Once we have defined the (de)serialization behavior in this way, our script can
now run successfully:
$ python ../export_attr.py
testing
Defining Custom Operators that Take or Return Bound C++ Classes
Once you’ve defined a custom C++ class, you can also use that class
as an argument or return from a custom operator (i.e. free functions). Suppose
you have the following free function:
This tutorial walked you through how to expose a C++ class to PyTorch, how to
register its methods, how to use that class from Python, and how to save and
load code using the class and run that code in a standalone C++ process. You
are now ready to extend your PyTorch models with C++ classes that interface
with third party C++ libraries or implement any other use case that requires
the lines between Python and C++ to blend smoothly.