|
3 | 3 | import torch |
4 | 4 | import torch.utils.bundled_inputs |
5 | 5 | import io |
6 | | -from typing import List, NamedTuple |
| 6 | +from typing import Dict, List, NamedTuple |
7 | 7 |
|
8 | 8 | from torch.jit.mobile import _load_for_lite_interpreter |
9 | 9 | from torch.testing._internal.common_utils import TestCase, run_tests |
@@ -33,6 +33,69 @@ def forward(self, a: torch.Tensor): |
33 | 33 | mobile_module_result |
34 | 34 | ) |
35 | 35 |
|
| 36 | + |
| 37 | + def test_typing_dict_with_namedtuple(self): |
| 38 | + class Foo(NamedTuple): |
| 39 | + id: torch.Tensor |
| 40 | + |
| 41 | + class Bar(torch.nn.Module): |
| 42 | + def __init__(self): |
| 43 | + super(Bar, self).__init__() |
| 44 | + self.foo = Foo(torch.tensor(1)) |
| 45 | + |
| 46 | + def forward(self, a: torch.Tensor): |
| 47 | + self.foo = Foo(a) |
| 48 | + re: Dict[str, Foo] = dict() |
| 49 | + re["test"] = Foo(a) |
| 50 | + return self.foo, re["test"] |
| 51 | + |
| 52 | + # The corresponding bytecode is |
| 53 | + # (8, |
| 54 | + # ('__torch__.___torch_mangle_2.Bar.forward', |
| 55 | + # (('instructions', |
| 56 | + # (('STOREN', 1, 2), |
| 57 | + # ('DROPR', 1, 0), |
| 58 | + # ('DICT_CONSTRUCT', 0, 0), |
| 59 | + # ('STORE', 3, 0), |
| 60 | + # ('LOAD', 3, 0), |
| 61 | + # ('LOADC', 1, 0), |
| 62 | + # ('MOVE', 2, 0), |
| 63 | + # ('NAMED_TUPLE_CONSTRUCT', 1, 1), |
| 64 | + # ('OP', 0, 0), |
| 65 | + # ('MOVE', 3, 0), |
| 66 | + # ('LOADC', 1, 0), |
| 67 | + # ('DICT_INDEX', 0, 0), |
| 68 | + # ('LOADC', 0, 0), |
| 69 | + # ('TUPLE_INDEX', 0, 0), |
| 70 | + # ('RET', 0, 0))), |
| 71 | + # ('operators', (('aten::_set_item', 'str', 3),)), |
| 72 | + # ('constants', (0, 'test')), |
| 73 | + # ('types', |
| 74 | + # ('Dict[str,__torch__.Foo[NamedTuple, [[id, Tensor]]]]', |
| 75 | + # '__torch__.Foo[NamedTuple, [[id, Tensor]]]')), |
| 76 | + # ('register_size', 3)), |
| 77 | + # (('arguments', |
| 78 | + # ((('name', 'self'), |
| 79 | + # ('type', '__torch__.___torch_mangle_2.Bar'), |
| 80 | + # ('default_value', None)), |
| 81 | + # (('name', 'a'), ('type', 'Tensor'), ('default_value', None)))), |
| 82 | + # ('returns', |
| 83 | + # ((('name', ''), ('type', 'Tensor'), ('default_value', None)),))))) |
| 84 | + |
| 85 | + sample_input = torch.tensor(5) |
| 86 | + script_module = torch.jit.script(Bar()) |
| 87 | + |
| 88 | + script_module_result = script_module(sample_input) |
| 89 | + |
| 90 | + buffer_mobile = io.BytesIO(script_module._save_to_buffer_for_lite_interpreter()) |
| 91 | + buffer_mobile.seek(0) |
| 92 | + mobile_module = _load_for_lite_interpreter(buffer_mobile) |
| 93 | + mobile_module_result = mobile_module(sample_input) |
| 94 | + torch.testing.assert_allclose( |
| 95 | + script_module_result, |
| 96 | + mobile_module_result |
| 97 | + ) |
| 98 | + |
36 | 99 | def test_typing_namedtuple_custom_classtype(self): |
37 | 100 | class Foo(NamedTuple): |
38 | 101 | id: torch.Tensor |
|
0 commit comments