@@ -29,9 +29,9 @@ state in a member variable.
29
29
#include <vector>
30
30
31
31
template <class T>
32
- struct Stack : torch::jit::CustomClassHolder {
32
+ struct MyStackClass : torch::jit::CustomClassHolder {
33
33
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()) {}
35
35
36
36
void push(T x) {
37
37
stack_.push_back(x);
@@ -42,11 +42,11 @@ state in a member variable.
42
42
return val;
43
43
}
44
44
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_);
47
47
}
48
48
49
- void merge(const c10::intrusive_ptr<Stack >& c) {
49
+ void merge(const c10::intrusive_ptr<MyStackClass >& c) {
50
50
for (auto& elem : c->stack_) {
51
51
push(elem);
52
52
}
@@ -74,19 +74,19 @@ Now let's take a look at how we will make this class visible to TorchScript, a p
74
74
// Notice a few things:
75
75
// - We pass the class to be registered as a template parameter to
76
76
// `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>``.
78
78
// In general, you cannot register a non-specialized template
79
79
// class. For non-templated classes, you can just pass the
80
80
// class name directly as the template parameter.
81
81
// - The single parameter to ``torch::jit::class_()`` is a
82
82
// string indicating the name of the class. This is the name
83
83
// 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 ``.
85
85
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
88
88
// 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)`.
90
90
// Currently, we do not support registering overloaded
91
91
// constructors, so for now you can only `def()` one instance of
92
92
// `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
95
95
// function as a method. Note that a lambda function must take a
96
96
// `c10::intrusive_ptr<YourClass>` (or some const/ref version of that)
97
97
// 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) {
99
99
return self->stack_.back();
100
100
})
101
- // The following four lines expose methods of the Stack <std::string>
101
+ // The following four lines expose methods of the MyStackClass <std::string>
102
102
// class as-is. `torch::jit::class_` will automatically examine the
103
103
// argument and return types of the passed-in method pointers and
104
104
// expose these to Python and TorchScript accordingly. Finally, notice
105
105
// that we must take the *address* of the fully-qualified method name,
106
106
// 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);
111
111
112
112
113
113
@@ -215,9 +215,9 @@ demonstrates that:
215
215
# We can find and instantiate our custom C++ class in python by using the
216
216
# `torch.classes` namespace:
217
217
#
218
- # This instantiation will invoke the Stack (std::vector<T> init) constructor
218
+ # This instantiation will invoke the MyStackClass (std::vector<T> init) constructor
219
219
# we registered earlier
220
- s = torch.classes.Stack ([" foo" , " bar" ])
220
+ s = torch.classes.MyStackClass ([" foo" , " bar" ])
221
221
222
222
# We can call methods in Python
223
223
s.push(" pushed" )
@@ -233,16 +233,16 @@ demonstrates that:
233
233
# For now, we need to assign the class's type to a local in order to
234
234
# annotate the type on the TorchScript function. This may change
235
235
# in the future.
236
- Stack = torch.classes.Stack
236
+ MyStackClass = torch.classes.MyStackClass
237
237
238
238
@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
241
241
s2.merge(s) # We can call a method on the class
242
242
return s2.clone (), s2.top () # We can also return instances of the class
243
243
# from TorchScript function/methods
244
244
245
- stack, top = do_stacks(torch.classes.Stack ([" wow" ]))
245
+ stack, top = do_stacks(torch.classes.MyStackClass ([" wow" ]))
246
246
assert top == " wow"
247
247
for expected in [" wow" , " mom" , " hi" ]:
248
248
assert stack.pop () == expected
@@ -252,7 +252,7 @@ Saving, Loading, and Running TorchScript Code Using Custom Classes
252
252
253
253
We can also use custom-registered C++ classes in a C++ process using
254
254
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:
256
256
257
257
.. code-block:: python
258
258
@@ -265,7 +265,7 @@ instantiates and calls a method on our Stack class:
265
265
super().__init__()
266
266
267
267
def forward(self, s : str) -> str:
268
- stack = torch.classes.Stack (["hi", "mom"])
268
+ stack = torch.classes.MyStackClass (["hi", "mom"])
269
269
return stack.pop() + s
270
270
271
271
scripted_foo = torch.jit.script(Foo())
@@ -410,7 +410,7 @@ an attribute, you'll get the following error:
410
410
class Foo(torch.nn.Module):
411
411
def __init__(self):
412
412
super().__init__()
413
- self.stack = torch.classes.Stack (["just", "testing"])
413
+ self.stack = torch.classes.MyStackClass (["just", "testing"])
414
414
415
415
def forward(self, s : str) -> str:
416
416
return self.stack.pop() + s
@@ -422,7 +422,7 @@ an attribute, you'll get the following error:
422
422
.. code-block:: shell
423
423
424
424
$ 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)
426
426
427
427
This is because TorchScript cannot automatically figure out what information
428
428
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_``.
436
436
about how we use these methods.
437
437
438
438
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:
440
440
441
441
.. code-block:: cpp
442
442
443
443
static auto testStack =
444
- torch::jit::class_<Stack <std::string>>("Stack ")
444
+ torch::jit::class_<MyStackClass <std::string>>("MyStackClass ")
445
445
.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) {
447
447
return self->stack_.back();
448
448
})
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)
453
453
// class_<>::def_pickle allows you to define the serialization
454
454
// and deserialization methods for your C++ class.
455
455
// 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
464
464
// custom operator API. In this instance, we've chosen to return
465
465
// a std::vector<std::string> as the salient data to preserve
466
466
// from the class.
467
- [](const c10::intrusive_ptr<Stack <std::string>>& self)
467
+ [](const c10::intrusive_ptr<MyStackClass <std::string>>& self)
468
468
-> std::vector<std::string> {
469
469
return self->stack_;
470
470
},
@@ -476,13 +476,13 @@ Here is an example of how we can update the registration code for our
476
476
// to a new instance of the C++ class, initialized however
477
477
// you would like given the serialized state.
478
478
[](std::vector<std::string> state)
479
- -> c10::intrusive_ptr<Stack <std::string>> {
479
+ -> c10::intrusive_ptr<MyStackClass <std::string>> {
480
480
// A convenient way to instantiate an object and get an
481
481
// 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>
483
483
// and call the single-argument std::vector<std::string>
484
484
// 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));
486
486
});
487
487
488
488
.. note::
@@ -503,7 +503,7 @@ now run successfully:
503
503
class Foo(torch.nn.Module):
504
504
def __init__(self):
505
505
super().__init__()
506
- self.stack = torch.classes.Stack (["just", "testing"])
506
+ self.stack = torch.classes.MyStackClass (["just", "testing"])
507
507
508
508
def forward(self, s : str) -> str:
509
509
return self.stack.pop() + s
@@ -520,24 +520,25 @@ now run successfully:
520
520
$ python ../export_attr.py
521
521
testing
522
522
523
- Defining Custom Operators that Take C++ Classes as Arguments
524
- ------------------------------------------------------------
523
+ Defining Custom Operators that Take or Return Bound C++ Classes
524
+ ---------------------------------------------------------------
525
525
526
526
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
528
528
example of how to do that:
529
529
530
530
.. code-block:: cpp
531
531
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;
534
535
}
535
536
536
537
static auto instance_registry = torch::RegisterOperators().op(
537
538
torch::RegisterOperators::options()
538
539
.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 >());
541
542
542
543
Refer to the ` custom op tutorial < https://pytorch.org/tutorials/advanced/torch_script_custom_ops.html> ` _
543
544
for more details on the registration API.
@@ -549,10 +550,10 @@ Once this is done, you can use the op like the following example:
549
550
class TryCustomOp(torch.nn.Module):
550
551
def __init__(self):
551
552
super(TryCustomOp, self).__init__()
552
- self.f = torch.classes.Stack (["foo", "bar"])
553
+ self.f = torch.classes.MyStackClass (["foo", "bar"])
553
554
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)
556
557
557
558
.. note::
558
559
0 commit comments