Skip to content

Commit c8591e7

Browse files
authored
Merge pull request #883 from jamesr66a/update_custom_class
Some small updates to custom C++ class tutorial for clarity
2 parents 2ea3972 + 0912b9d commit c8591e7

File tree

1 file changed

+49
-48
lines changed

1 file changed

+49
-48
lines changed

advanced_source/torch_script_custom_classes.rst

Lines changed: 49 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@ state in a member variable.
2929
#include <vector>
3030
3131
template <class T>
32-
struct Stack : torch::jit::CustomClassHolder {
32+
struct MyStackClass : torch::jit::CustomClassHolder {
3333
std::vector<T> stack_;
34-
Stack(std::vector<T> init) : stack_(init.begin(), init.end()) {}
34+
MyStackClass(std::vector<T> init) : stack_(init.begin(), init.end()) {}
3535
3636
void push(T x) {
3737
stack_.push_back(x);
@@ -42,11 +42,11 @@ state in a member variable.
4242
return val;
4343
}
4444
45-
c10::intrusive_ptr<Stack> clone() const {
46-
return c10::make_intrusive<Stack>(stack_);
45+
c10::intrusive_ptr<MyStackClass> clone() const {
46+
return c10::make_intrusive<MyStackClass>(stack_);
4747
}
4848
49-
void merge(const c10::intrusive_ptr<Stack>& c) {
49+
void merge(const c10::intrusive_ptr<MyStackClass>& c) {
5050
for (auto& elem : c->stack_) {
5151
push(elem);
5252
}
@@ -74,19 +74,19 @@ Now let's take a look at how we will make this class visible to TorchScript, a p
7474
// Notice a few things:
7575
// - We pass the class to be registered as a template parameter to
7676
// `torch::jit::class_`. In this instance, we've passed the
77-
// specialization of the Stack class ``Stack<std::string>``.
77+
// specialization of the MyStackClass class ``MyStackClass<std::string>``.
7878
// In general, you cannot register a non-specialized template
7979
// class. For non-templated classes, you can just pass the
8080
// class name directly as the template parameter.
8181
// - The single parameter to ``torch::jit::class_()`` is a
8282
// string indicating the name of the class. This is the name
8383
// the class will appear as in both Python and TorchScript.
84-
// For example, our Stack class would appear as ``torch.classes.Stack``.
84+
// For example, our MyStackClass class would appear as ``torch.classes.MyStackClass``.
8585
static auto testStack =
86-
torch::jit::class_<Stack<std::string>>("Stack")
87-
// The following line registers the contructor of our Stack
86+
torch::jit::class_<MyStackClass<std::string>>("MyStackClass")
87+
// The following line registers the contructor of our MyStackClass
8888
// class that takes a single `std::vector<std::string>` argument,
89-
// i.e. it exposes the C++ method `Stack(std::vector<T> init)`.
89+
// i.e. it exposes the C++ method `MyStackClass(std::vector<T> init)`.
9090
// Currently, we do not support registering overloaded
9191
// constructors, so for now you can only `def()` one instance of
9292
// `torch::jit::init`.
@@ -95,19 +95,19 @@ Now let's take a look at how we will make this class visible to TorchScript, a p
9595
// function as a method. Note that a lambda function must take a
9696
// `c10::intrusive_ptr<YourClass>` (or some const/ref version of that)
9797
// as the first argument. Other arguments can be whatever you want.
98-
.def("top", [](const c10::intrusive_ptr<Stack<std::string>>& self) {
98+
.def("top", [](const c10::intrusive_ptr<MyStackClass<std::string>>& self) {
9999
return self->stack_.back();
100100
})
101-
// The following four lines expose methods of the Stack<std::string>
101+
// The following four lines expose methods of the MyStackClass<std::string>
102102
// class as-is. `torch::jit::class_` will automatically examine the
103103
// argument and return types of the passed-in method pointers and
104104
// expose these to Python and TorchScript accordingly. Finally, notice
105105
// that we must take the *address* of the fully-qualified method name,
106106
// i.e. use the unary `&` operator, due to C++ typing rules.
107-
.def("push", &Stack<std::string>::push)
108-
.def("pop", &Stack<std::string>::pop)
109-
.def("clone", &Stack<std::string>::clone)
110-
.def("merge", &Stack<std::string>::merge);
107+
.def("push", &MyStackClass<std::string>::push)
108+
.def("pop", &MyStackClass<std::string>::pop)
109+
.def("clone", &MyStackClass<std::string>::clone)
110+
.def("merge", &MyStackClass<std::string>::merge);
111111
112112
113113
@@ -215,9 +215,9 @@ demonstrates that:
215215
# We can find and instantiate our custom C++ class in python by using the
216216
# `torch.classes` namespace:
217217
#
218-
# This instantiation will invoke the Stack(std::vector<T> init) constructor
218+
# This instantiation will invoke the MyStackClass(std::vector<T> init) constructor
219219
# we registered earlier
220-
s = torch.classes.Stack(["foo", "bar"])
220+
s = torch.classes.MyStackClass(["foo", "bar"])
221221
222222
# We can call methods in Python
223223
s.push("pushed")
@@ -233,16 +233,16 @@ demonstrates that:
233233
# For now, we need to assign the class's type to a local in order to
234234
# annotate the type on the TorchScript function. This may change
235235
# in the future.
236-
Stack = torch.classes.Stack
236+
MyStackClass = torch.classes.MyStackClass
237237
238238
@torch.jit.script
239-
def do_stacks(s : Stack): # We can pass a custom class instance to TorchScript
240-
s2 = torch.classes.Stack(["hi", "mom"]) # We can instantiate the class
239+
def do_stacks(s : MyStackClass): # We can pass a custom class instance to TorchScript
240+
s2 = torch.classes.MyStackClass(["hi", "mom"]) # We can instantiate the class
241241
s2.merge(s) # We can call a method on the class
242242
return s2.clone(), s2.top() # We can also return instances of the class
243243
# from TorchScript function/methods
244244
245-
stack, top = do_stacks(torch.classes.Stack(["wow"]))
245+
stack, top = do_stacks(torch.classes.MyStackClass(["wow"]))
246246
assert top == "wow"
247247
for expected in ["wow", "mom", "hi"]:
248248
assert stack.pop() == expected
@@ -252,7 +252,7 @@ Saving, Loading, and Running TorchScript Code Using Custom Classes
252252
253253
We can also use custom-registered C++ classes in a C++ process using
254254
libtorch. As an example, let's define a simple ``nn.Module`` that
255-
instantiates and calls a method on our Stack class:
255+
instantiates and calls a method on our MyStackClass class:
256256
257257
.. code-block:: python
258258
@@ -265,7 +265,7 @@ instantiates and calls a method on our Stack class:
265265
super().__init__()
266266
267267
def forward(self, s : str) -> str:
268-
stack = torch.classes.Stack(["hi", "mom"])
268+
stack = torch.classes.MyStackClass(["hi", "mom"])
269269
return stack.pop() + s
270270
271271
scripted_foo = torch.jit.script(Foo())
@@ -410,7 +410,7 @@ an attribute, you'll get the following error:
410410
class Foo(torch.nn.Module):
411411
def __init__(self):
412412
super().__init__()
413-
self.stack = torch.classes.Stack(["just", "testing"])
413+
self.stack = torch.classes.MyStackClass(["just", "testing"])
414414
415415
def forward(self, s : str) -> str:
416416
return self.stack.pop() + s
@@ -422,7 +422,7 @@ an attribute, you'll get the following error:
422422
.. code-block:: shell
423423
424424
$ python export_attr.py
425-
RuntimeError: Cannot serialize custom bound C++ class __torch__.torch.classes.Stack. Please define serialization methods via torch::jit::pickle_ for this class. (pushIValueImpl at ../torch/csrc/jit/pickler.cpp:128)
425+
RuntimeError: Cannot serialize custom bound C++ class __torch__.torch.classes.MyStackClass. Please define serialization methods via torch::jit::pickle_ for this class. (pushIValueImpl at ../torch/csrc/jit/pickler.cpp:128)
426426
427427
This is because TorchScript cannot automatically figure out what information
428428
save from your C++ class. You must specify that manually. The way to do that
@@ -436,20 +436,20 @@ the special ``def_pickle`` method on ``class_``.
436436
about how we use these methods.
437437
438438
Here is an example of how we can update the registration code for our
439-
``Stack`` class to include serialization methods:
439+
``MyStackClass`` class to include serialization methods:
440440
441441
.. code-block:: cpp
442442
443443
static auto testStack =
444-
torch::jit::class_<Stack<std::string>>("Stack")
444+
torch::jit::class_<MyStackClass<std::string>>("MyStackClass")
445445
.def(torch::jit::init<std::vector<std::string>>())
446-
.def("top", [](const c10::intrusive_ptr<Stack<std::string>>& self) {
446+
.def("top", [](const c10::intrusive_ptr<MyStackClass<std::string>>& self) {
447447
return self->stack_.back();
448448
})
449-
.def("push", &Stack<std::string>::push)
450-
.def("pop", &Stack<std::string>::pop)
451-
.def("clone", &Stack<std::string>::clone)
452-
.def("merge", &Stack<std::string>::merge)
449+
.def("push", &MyStackClass<std::string>::push)
450+
.def("pop", &MyStackClass<std::string>::pop)
451+
.def("clone", &MyStackClass<std::string>::clone)
452+
.def("merge", &MyStackClass<std::string>::merge)
453453
// class_<>::def_pickle allows you to define the serialization
454454
// and deserialization methods for your C++ class.
455455
// Currently, we only support passing stateless lambda functions
@@ -464,7 +464,7 @@ Here is an example of how we can update the registration code for our
464464
// custom operator API. In this instance, we've chosen to return
465465
// a std::vector<std::string> as the salient data to preserve
466466
// from the class.
467-
[](const c10::intrusive_ptr<Stack<std::string>>& self)
467+
[](const c10::intrusive_ptr<MyStackClass<std::string>>& self)
468468
-> std::vector<std::string> {
469469
return self->stack_;
470470
},
@@ -476,13 +476,13 @@ Here is an example of how we can update the registration code for our
476476
// to a new instance of the C++ class, initialized however
477477
// you would like given the serialized state.
478478
[](std::vector<std::string> state)
479-
-> c10::intrusive_ptr<Stack<std::string>> {
479+
-> c10::intrusive_ptr<MyStackClass<std::string>> {
480480
// A convenient way to instantiate an object and get an
481481
// intrusive_ptr to it is via `make_intrusive`. We use
482-
// that here to allocate an instance of Stack<std::string>
482+
// that here to allocate an instance of MyStackClass<std::string>
483483
// and call the single-argument std::vector<std::string>
484484
// constructor with the serialized state.
485-
return c10::make_intrusive<Stack<std::string>>(std::move(state));
485+
return c10::make_intrusive<MyStackClass<std::string>>(std::move(state));
486486
});
487487
488488
.. note::
@@ -503,7 +503,7 @@ now run successfully:
503503
class Foo(torch.nn.Module):
504504
def __init__(self):
505505
super().__init__()
506-
self.stack = torch.classes.Stack(["just", "testing"])
506+
self.stack = torch.classes.MyStackClass(["just", "testing"])
507507
508508
def forward(self, s : str) -> str:
509509
return self.stack.pop() + s
@@ -520,24 +520,25 @@ now run successfully:
520520
$ python ../export_attr.py
521521
testing
522522
523-
Defining Custom Operators that Take C++ Classes as Arguments
524-
------------------------------------------------------------
523+
Defining Custom Operators that Take or Return Bound C++ Classes
524+
---------------------------------------------------------------
525525
526526
Once you've defined a custom C++ class, you can also use that class
527-
as an argument to custom operator (i.e. free functions). Here's an
527+
as an argument or return from a custom operator (i.e. free functions). Here's an
528528
example of how to do that:
529529
530530
.. code-block:: cpp
531531
532-
std::string take_an_instance(const c10::intrusive_ptr<Stack<std::string>>& instance) {
533-
return instance->pop();
532+
c10::intrusive_ptr<MyStackClass<std::string>> manipulate_instance(const c10::intrusive_ptr<MyStackClass<std::string>>& instance) {
533+
instance->pop();
534+
return instance;
534535
}
535536
536537
static auto instance_registry = torch::RegisterOperators().op(
537538
torch::RegisterOperators::options()
538539
.schema(
539-
"foo::take_an_instance(__torch__.torch.classes.Stack x) -> str Y")
540-
.catchAllKernel<decltype(take_an_instance), &take_an_instance>());
540+
"foo::manipulate_instance(__torch__.torch.classes.MyStackClass x) -> __torch__.torch.classes.MyStackClass Y")
541+
.catchAllKernel<decltype(manipulate_instance), &manipulate_instance>());
541542
542543
Refer to the `custom op tutorial <https://pytorch.org/tutorials/advanced/torch_script_custom_ops.html>`_
543544
for more details on the registration API.
@@ -549,10 +550,10 @@ Once this is done, you can use the op like the following example:
549550
class TryCustomOp(torch.nn.Module):
550551
def __init__(self):
551552
super(TryCustomOp, self).__init__()
552-
self.f = torch.classes.Stack(["foo", "bar"])
553+
self.f = torch.classes.MyStackClass(["foo", "bar"])
553554
554-
def forward(self) -> str:
555-
return torch.ops._TorchScriptTesting.take_an_instance(self.f)
555+
def forward(self):
556+
return torch.ops.foo.manipulate_instance(self.f)
556557
557558
.. note::
558559

0 commit comments

Comments
 (0)