Title: Custom Classes — PyTorch main documentation
Description: Custom classes in PyTorch C++ — registering C++ classes for use in TorchScript and Python.
Keywords:
Domain: docs.pytorch.org
{
"@context": "https://schema.org",
"@type": "Article",
"name": "Custom Classes",
"headline": "Custom Classes",
"description": "Custom classes in PyTorch C++ \u2014 registering C++ classes for use in TorchScript and Python.",
"url": "/api/library/custom_classes.html",
"articleBody": "Custom Classes# PyTorch allows registering custom C++ classes that can be used from Python and TorchScript. Header: torch/custom_class.h class_ Template# template\u003cclass CurClass\u003eclass class_ : public torch::detail::class_base# Entry point for custom C++ class registration. To register a C++ class in PyTorch, instantiate torch::class_ with the desired class as the template parameter. Typically, this instantiation should be done in the initialization of a global variable, so that the class will be made available on dynamic library loading without any additional API calls needed. For example, to register a class named Foo, you might create a global variable like so: static auto register_foo = torch::class_\u003cFoo\u003e(\"myclasses\", \"Foo\") .def(\"myMethod\", \u0026Foo::myMethod) .def(\"lambdaMethod\", [](const c10::intrusive_ptr\u003cFoo\u003e\u0026 self) { // Do something with `self` }); In addition to registering the class, this registration also chains def() calls to register methods. myMethod() is registered with a pointer to the Foo class\u2019s myMethod() method. lambdaMethod() is registered with a C++ lambda expression. Public Functions inline explicit class_(const std::string \u0026namespaceName, const std::string \u0026className, std::string doc_string = \"\")# This constructor actually registers the class type. String argument namespaceName is an identifier for the namespace you would like this class to appear in. String argument className is the name you would like to see this class exposed as in Python and TorchScript. For example, if you pass foo as the namespace name and Bar as the className, the class will appear as torch.classes.foo.Bar in Python and TorchScript template\u003ctypename ...Types\u003einline class_ \u0026def(torch::detail::types\u003cvoid, Types...\u003e, std::string doc_string = \"\", std::initializer_list\u003carg\u003e default_args = {})# def() can be used in conjunction with torch::init() to register a constructor for a given C++ class type. For example, passing torch::init\u003cint, std::string\u003e() would register a two-argument constructor taking an int and a std::string as argument. template\u003ctypename Func, typename ...ParameterTypes\u003einline class_ \u0026def(InitLambda\u003cFunc, c10::guts::typelist::typelist\u003cParameterTypes...\u003e\u003e init, std::string doc_string = \"\", std::initializer_list\u003carg\u003e default_args = {})# template\u003ctypename Func\u003einline class_ \u0026def(std::string name, Func f, std::string doc_string = \"\", std::initializer_list\u003carg\u003e default_args = {})# This is the normal method registration API. name is the name that the method will be made accessible by in Python and TorchScript. f is a callable object that defines the method. Typically f will either be a pointer to a method on CurClass, or a lambda expression that takes a c10::intrusive_ptr\u003cCurClass\u003e as the first argument (emulating a this argument in a C++ method.) Examples: // Exposes method `foo` on C++ class `Foo` as `call_foo()` in // Python and TorchScript .def(\"call_foo\", \u0026Foo::foo) // Exposes the given lambda expression as method `call_lambda()` // in Python and TorchScript. .def(\"call_lambda\", [](const c10::intrusive_ptr\u003cFoo\u003e\u0026 self) { // do something }) template\u003ctypename Func\u003einline class_ \u0026def_static(std::string name, Func func, std::string doc_string = \"\", std::initializer_list\u003carg\u003e default_args = {})# Method registration API for static methods. template\u003ctypename GetterFunc, typename SetterFunc\u003einline class_ \u0026def_property(const std::string \u0026name, GetterFunc getter_func, SetterFunc setter_func, std::string doc_string = \"\")# Property registration API for properties with both getter and setter functions. template\u003ctypename GetterFunc\u003einline class_ \u0026def_property(const std::string \u0026name, GetterFunc getter_func, std::string doc_string = \"\")# Property registration API for properties with only getter function. template\u003ctypename T\u003einline class_ \u0026def_readwrite(const std::string \u0026name, T CurClass::* field)# Property registration API for properties with read-write access. template\u003ctypename T\u003einline class_ \u0026def_readonly(const std::string \u0026name, T CurClass::* field)# Property registration API for properties with read-only access. inline class_ \u0026_def_unboxed(const std::string \u0026name, std::function\u003cvoid(jit::Stack\u0026)\u003e func, c10::FunctionSchema schema, std::string doc_string = \"\")# This is an unsafe method registration API added for adding custom JIT backend support via custom C++ classes. It is not for general purpose use. template\u003ctypename GetStateFn, typename SetStateFn\u003einline class_ \u0026def_pickle(GetStateFn \u0026\u0026get_state, SetStateFn \u0026\u0026set_state)# def_pickle() is used to define exactly what state gets serialized or deserialized for a given instance of a custom C++ class in Python or TorchScript. This protocol is equivalent to the Pickle concept of __getstate__ and __setstate__ from Python (https://docs.python.org/2/library/pickle.html#object.__getstate__) Currently, both the get_state and set_state callables must be C++ lambda expressions. They should have the following signatures, where CurClass is the class you\u2019re registering and T1 is some object that encapsulates the state of the object. __getstate__(intrusive_ptr\u003cCurClass\u003e) -\u003e T1 __setstate__(T2) -\u003e intrusive_ptr\u003cCurClass\u003e T1 must be an object that is convertible to IValue by the same rules for custom op/method registration. For the common case, T1 == T2. T1 can also be a subtype of T2. An example where it makes sense for T1 and T2 to differ is if setstate handles legacy formats in a backwards compatible way. Example: .def_pickle( // __getstate__ [](const c10::intrusive_ptr\u003cMyStackClass\u003cstd::string\u003e\u003e\u0026 self) { return self-\u003estack_; }, [](std::vector\u003cstd::string\u003e state) { // __setstate__ return c10::make_intrusive\u003cMyStackClass\u003cstd::string\u003e\u003e( std::vector\u003cstd::string\u003e{\"i\", \"was\", \"deserialized\"}); }) Example: #include \u003ctorch/custom_class.h\u003e struct MyClass : torch::CustomClassHolder { int value; MyClass(int v) : value(v) {} int getValue() const { return value; } void setValue(int v) { value = v; } }; TORCH_LIBRARY(my_classes, m) { m.class_\u003cMyClass\u003e(\"MyClass\") .def(torch::init\u003cint\u003e()) .def(\"getValue\", \u0026MyClass::getValue) .def(\"setValue\", \u0026MyClass::setValue) .def_readwrite(\"value\", \u0026MyClass::value); } Registering Methods# Constructor: m.class_\u003cMyClass\u003e(\"MyClass\") .def(torch::init\u003cint\u003e()) // Constructor taking int Methods: m.class_\u003cMyClass\u003e(\"MyClass\") .def(\"getValue\", \u0026MyClass::getValue) .def(\"setValue\", \u0026MyClass::setValue) Properties: m.class_\u003cMyClass\u003e(\"MyClass\") .def_readwrite(\"value\", \u0026MyClass::value) // Read-write .def_readonly(\"const_value\", \u0026MyClass::const_value) // Read-only Using Custom Classes# From C++: auto my_obj = c10::make_intrusive\u003cMyClass\u003e(42); int val = my_obj-\u003egetValue(); From Python: import torch torch.classes.load_library(\"path/to/library.so\") obj = torch.classes.my_classes.MyClass(42) print(obj.getValue()) In TorchScript: @torch.jit.script def use_my_class(x: torch.classes.my_classes.MyClass) -\u003e int: return x.getValue()",
"author": {
"@type": "Organization",
"name": "PyTorch Contributors",
"url": "https://pytorch.org"
},
"image": "https://pytorch.org/docs/stable/_static/img/pytorch_seo.png",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "/api/library/custom_classes.html"
},
"datePublished": "2023-01-01T00:00:00Z",
"dateModified": "2023-01-01T00:00:00Z"
}
| docsearch:language | en |
| llm:site-type | documentation |
| llm:framework | PyTorch |
| llm:description | Custom classes in PyTorch C++ — registering C++ classes for use in TorchScript and Python. |
| llm:navigation-file | https://pytorch.org/docs/stable/llms.txt |
| llm:sitemap | https://pytorch.org/docs/stable/sitemap.xml |
| llm:version | main |
| llm:project | PyTorch |
| llm:page-type | documentation |
| og:image | https://docs.pytorch.org/docs/stable/_static/img/pytorch_seo.png |
| None | 3 |
Links:
Viewport: width=device-width, initial-scale=1