Skip to content

Commit 7c1d85d

Browse files
authored
Merge branch 'master' into patch-1
2 parents 6c6ceea + cf3251f commit 7c1d85d

File tree

4 files changed

+141
-289
lines changed

4 files changed

+141
-289
lines changed

advanced_source/torch_script_custom_classes.rst

Lines changed: 82 additions & 56 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::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
}
@@ -63,7 +63,7 @@ There are several things to note:
6363
is to ensure consistent lifetime management of the object instances between languages
6464
(C++, Python and TorchScript).
6565
- The second thing to notice is that the user-defined class must inherit from
66-
``torch::jit::CustomClassHolder``. This ensures that everything is set up to handle
66+
``torch::CustomClassHolder``. This ensures that everything is set up to handle
6767
the lifetime management system previously mentioned.
6868

6969
Now let's take a look at how we will make this class visible to TorchScript, a process called
@@ -73,41 +73,41 @@ Now let's take a look at how we will make this class visible to TorchScript, a p
7373
7474
// Notice a few things:
7575
// - We pass the class to be registered as a template parameter to
76-
// `torch::jit::class_`. In this instance, we've passed the
77-
// specialization of the Stack class ``Stack<std::string>``.
76+
// `torch::class_`. In this instance, we've passed the
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.
81-
// - The single parameter to ``torch::jit::class_()`` is a
81+
// - The single parameter to ``torch::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::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
92-
// `torch::jit::init`.
93-
.def(torch::jit::init<std::vector<std::string>>())
92+
// `torch::init`.
93+
.def(torch::init<std::vector<std::string>>())
9494
// The next line registers a stateless (i.e. no captures) C++ lambda
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>
102-
// class as-is. `torch::jit::class_` will automatically examine the
101+
// The following four lines expose methods of the MyStackClass<std::string>
102+
// class as-is. `torch::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())
@@ -307,7 +307,7 @@ Let's populate ``infer.cpp`` with the following:
307307
#include <memory>
308308
309309
int main(int argc, const char* argv[]) {
310-
torch::jit::script::Module module;
310+
torch::script::Module module;
311311
try {
312312
// Deserialize the ScriptModule from a file using torch::jit::load().
313313
module = torch::jit::load("foo.pt");
@@ -394,6 +394,31 @@ And now we can run our exciting C++ binary:
394394
395395
Incredible!
396396
397+
Moving Custom Classes To/From IValues
398+
-------------------------------------
399+
400+
It's also possible that you may need to move custom classes into or out of
401+
``IValue``s, such as when you take or return ``IValue``s from TorchScript methods
402+
or you want to instantiate a custom class attribute in C++. For creating an
403+
``IValue`` from a custom C++ class instance:
404+
405+
- ``torch::make_custom_class<T>()`` provides an API similar to c10::intrusive_ptr<T>
406+
in that it will take whatever set of arguments you provide to it, call the constructor
407+
of T that matches that set of arguments, and wrap that instance up and return it.
408+
However, instead of returning just a pointer to a custom class object, it returns
409+
an ``IValue`` wrapping the object. You can then pass this ``IValue`` directly to
410+
TorchScript.
411+
- In the event that you already have an ``intrusive_ptr`` pointing to your class, you
412+
can directly construct an IValue from it using the constructor ``IValue(intrusive_ptr<T>)``.
413+
414+
For converting ``IValue``s back to custom classes:
415+
416+
- ``IValue::toCustomClass<T>()`` will return an ``intrusive_ptr<T>`` pointing to the
417+
custom class that the ``IValue`` contains. Internally, this function is checking
418+
that ``T`` is registered as a custom class and that the ``IValue`` does in fact contain
419+
a custom class. You can check whether the ``IValue`` contains a custom class manually by
420+
calling ``isCustomClass()``.
421+
397422
Defining Serialization/Deserialization Methods for Custom C++ Classes
398423
---------------------------------------------------------------------
399424
@@ -410,7 +435,7 @@ an attribute, you'll get the following error:
410435
class Foo(torch.nn.Module):
411436
def __init__(self):
412437
super().__init__()
413-
self.stack = torch.classes.Stack(["just", "testing"])
438+
self.stack = torch.classes.MyStackClass(["just", "testing"])
414439
415440
def forward(self, s : str) -> str:
416441
return self.stack.pop() + s
@@ -422,7 +447,7 @@ an attribute, you'll get the following error:
422447
.. code-block:: shell
423448
424449
$ 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)
450+
RuntimeError: Cannot serialize custom bound C++ class __torch__.torch.classes.MyStackClass. Please define serialization methods via def_pickle for this class. (pushIValueImpl at ../torch/csrc/jit/pickler.cpp:128)
426451
427452
This is because TorchScript cannot automatically figure out what information
428453
save from your C++ class. You must specify that manually. The way to do that
@@ -436,20 +461,20 @@ the special ``def_pickle`` method on ``class_``.
436461
about how we use these methods.
437462
438463
Here is an example of how we can update the registration code for our
439-
``Stack`` class to include serialization methods:
464+
``MyStackClass`` class to include serialization methods:
440465
441466
.. code-block:: cpp
442467
443468
static auto testStack =
444-
torch::jit::class_<Stack<std::string>>("Stack")
445-
.def(torch::jit::init<std::vector<std::string>>())
446-
.def("top", [](const c10::intrusive_ptr<Stack<std::string>>& self) {
469+
torch::class_<MyStackClass<std::string>>("MyStackClass")
470+
.def(torch::init<std::vector<std::string>>())
471+
.def("top", [](const c10::intrusive_ptr<MyStackClass<std::string>>& self) {
447472
return self->stack_.back();
448473
})
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)
474+
.def("push", &MyStackClass<std::string>::push)
475+
.def("pop", &MyStackClass<std::string>::pop)
476+
.def("clone", &MyStackClass<std::string>::clone)
477+
.def("merge", &MyStackClass<std::string>::merge)
453478
// class_<>::def_pickle allows you to define the serialization
454479
// and deserialization methods for your C++ class.
455480
// Currently, we only support passing stateless lambda functions
@@ -464,7 +489,7 @@ Here is an example of how we can update the registration code for our
464489
// custom operator API. In this instance, we've chosen to return
465490
// a std::vector<std::string> as the salient data to preserve
466491
// from the class.
467-
[](const c10::intrusive_ptr<Stack<std::string>>& self)
492+
[](const c10::intrusive_ptr<MyStackClass<std::string>>& self)
468493
-> std::vector<std::string> {
469494
return self->stack_;
470495
},
@@ -476,13 +501,13 @@ Here is an example of how we can update the registration code for our
476501
// to a new instance of the C++ class, initialized however
477502
// you would like given the serialized state.
478503
[](std::vector<std::string> state)
479-
-> c10::intrusive_ptr<Stack<std::string>> {
504+
-> c10::intrusive_ptr<MyStackClass<std::string>> {
480505
// A convenient way to instantiate an object and get an
481506
// intrusive_ptr to it is via `make_intrusive`. We use
482-
// that here to allocate an instance of Stack<std::string>
507+
// that here to allocate an instance of MyStackClass<std::string>
483508
// and call the single-argument std::vector<std::string>
484509
// constructor with the serialized state.
485-
return c10::make_intrusive<Stack<std::string>>(std::move(state));
510+
return c10::make_intrusive<MyStackClass<std::string>>(std::move(state));
486511
});
487512
488513
.. note::
@@ -503,7 +528,7 @@ now run successfully:
503528
class Foo(torch.nn.Module):
504529
def __init__(self):
505530
super().__init__()
506-
self.stack = torch.classes.Stack(["just", "testing"])
531+
self.stack = torch.classes.MyStackClass(["just", "testing"])
507532
508533
def forward(self, s : str) -> str:
509534
return self.stack.pop() + s
@@ -520,24 +545,25 @@ now run successfully:
520545
$ python ../export_attr.py
521546
testing
522547
523-
Defining Custom Operators that Take C++ Classes as Arguments
524-
------------------------------------------------------------
548+
Defining Custom Operators that Take or Return Bound C++ Classes
549+
---------------------------------------------------------------
525550
526551
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
552+
as an argument or return from a custom operator (i.e. free functions). Here's an
528553
example of how to do that:
529554
530555
.. code-block:: cpp
531556
532-
std::string take_an_instance(const c10::intrusive_ptr<Stack<std::string>>& instance) {
533-
return instance->pop();
557+
c10::intrusive_ptr<MyStackClass<std::string>> manipulate_instance(const c10::intrusive_ptr<MyStackClass<std::string>>& instance) {
558+
instance->pop();
559+
return instance;
534560
}
535561
536562
static auto instance_registry = torch::RegisterOperators().op(
537563
torch::RegisterOperators::options()
538564
.schema(
539-
"foo::take_an_instance(__torch__.torch.classes.Stack x) -> str Y")
540-
.catchAllKernel<decltype(take_an_instance), &take_an_instance>());
565+
"foo::manipulate_instance(__torch__.torch.classes.MyStackClass x) -> __torch__.torch.classes.MyStackClass Y")
566+
.catchAllKernel<decltype(manipulate_instance), &manipulate_instance>());
541567
542568
Refer to the `custom op tutorial <https://pytorch.org/tutorials/advanced/torch_script_custom_ops.html>`_
543569
for more details on the registration API.
@@ -549,10 +575,10 @@ Once this is done, you can use the op like the following example:
549575
class TryCustomOp(torch.nn.Module):
550576
def __init__(self):
551577
super(TryCustomOp, self).__init__()
552-
self.f = torch.classes.Stack(["foo", "bar"])
578+
self.f = torch.classes.MyStackClass(["foo", "bar"])
553579
554-
def forward(self) -> str:
555-
return torch.ops._TorchScriptTesting.take_an_instance(self.f)
580+
def forward(self):
581+
return torch.ops.foo.manipulate_instance(self.f)
556582
557583
.. note::
558584

beginner_source/deep_learning_60min_blitz.rst

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ Goal of this tutorial:
3030
/beginner/blitz/autograd_tutorial
3131
/beginner/blitz/neural_networks_tutorial
3232
/beginner/blitz/cifar10_tutorial
33-
/beginner/blitz/data_parallel_tutorial
3433

3534
.. galleryitem:: /beginner/blitz/tensor_tutorial.py
3635
:figure: /_static/img/tensor_illustration_flat.png
@@ -44,9 +43,6 @@ Goal of this tutorial:
4443
.. galleryitem:: /beginner/blitz/cifar10_tutorial.py
4544
:figure: /_static/img/cifar10.png
4645

47-
.. galleryitem:: /beginner/blitz/data_parallel_tutorial.py
48-
:figure: /_static/img/data_parallel.png
49-
5046
.. raw:: html
5147

5248
<div style='clear:both'></div>

0 commit comments

Comments
 (0)