forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_jit.py
16479 lines (13499 loc) · 569 KB
/
test_jit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Owner(s): ["oncall: jit"]
import torch
# This is how we include tests located in test/jit/...
# They are included here so that they are invoked when you call `test_jit.py`,
# do not run these test files directly.
from jit.test_tracer import TestTracer, TestMixTracingScripting # noqa: F401
from jit.test_recursive_script import TestRecursiveScript # noqa: F401
from jit.test_type_sharing import TestTypeSharing # noqa: F401
from jit.test_logging import TestLogging # noqa: F401
from jit.test_backends import TestBackends, TestBackendsWithCompiler # noqa: F401
from jit.test_backend_nnapi import TestNnapiBackend # noqa: F401
from jit.test_list_dict import TestList, TestDict, TestNamedTuple, TestScriptDict, TestScriptList # noqa: F401
from jit.test_async import TestAsync # noqa: F401
from jit.test_data_parallel import TestDataParallel # noqa: F401
from jit.test_models import TestModels # noqa: F401
from jit.test_modules import TestModules # noqa: F401
from jit.test_autodiff import TestAutodiffJit # noqa: F401
from jit.test_autodiff_subgraph_slicing import TestAutodiffSubgraphSlicing # noqa: F401
from jit.test_custom_operators import TestCustomOperators # noqa: F401
from jit.test_export_modes import TestExportModes # noqa: F401
from jit.test_graph_rewrite_passes import TestGraphRewritePasses # noqa: F401
from jit.test_class_type import TestClassType # noqa: F401
from jit.test_builtins import TestBuiltins, TestTensorBuiltins # noqa: F401
from jit.test_ignore_context_manager import TestIgnoreContextManager # noqa: F401
from jit.test_symbolic_shape_analysis import TestSymbolicShapeAnalysis # noqa: F401
from jit.test_op_decompositions import TestOpDecompositions # noqa: F401
from jit.test_unsupported_ops import TestUnsupportedOps # noqa: F401
from jit.test_freezing import TestFreezing, TestFrozenOptimizations, TestMKLDNNReinplacing # noqa: F401
from jit.test_peephole import TestPeephole # noqa: F401
from jit.test_alias_analysis import TestAliasAnalysis # noqa: F401
from jit.test_save_load import TestSaveLoad, TestSaveLoadFlatbuffer # noqa: F401
from jit.test_save_load_for_op_version import TestSaveLoadForOpVersion # noqa: F401
from jit.test_module_containers import TestModuleContainers # noqa: F401
from jit.test_python_bindings import TestPythonBindings # noqa: F401
from jit.test_python_ir import TestPythonIr # noqa: F401
from jit.test_functional_blocks import TestFunctionalBlocks # noqa: F401
from jit.test_remove_mutation import TestRemoveMutation # noqa: F401
from jit.test_torchbind import TestTorchbind # noqa: F401
from jit.test_module_interface import TestModuleInterface # noqa: F401 # noqa: F401
from jit.test_with import TestWith # noqa: F401
from jit.test_enum import TestEnum # noqa: F401
from jit.test_string_formatting import TestStringFormatting # noqa: F401
from jit.test_profiler import TestProfiler # noqa: F401
from jit.test_slice import TestSlice # noqa: F401
from jit.test_ignorable_args import TestIgnorableArgs # noqa: F401
from jit.test_hooks import TestHooks # noqa: F401
from jit.test_warn import TestWarn # noqa: F401
from jit.test_isinstance import TestIsinstance # noqa: F401
from jit.test_cuda import TestCUDA # noqa: F401
from jit.test_python_builtins import TestPythonBuiltinOP # noqa: F401
from jit.test_typing import TestTyping # noqa: F401
from jit.test_hash import TestHash # noqa: F401
from jit.test_complex import TestComplex # noqa: F401
from jit.test_jit_utils import TestJitUtils # noqa: F401
from jit.test_scriptmod_ann import TestScriptModuleInstanceAttributeTypeAnnotation # noqa: F401
from jit.test_types import TestTypesAndAnnotation # noqa: F401
from jit.test_misc import TestMisc # noqa: F401
from jit.test_upgraders import TestUpgraders # noqa: F401
from jit.test_pdt import TestPDT # noqa: F401
from jit.test_tensor_creation_ops import TestTensorCreationOps # noqa: F401
from jit.test_module_apis import TestModuleAPIs # noqa: F401
from jit.test_script_profile import TestScriptProfile # noqa: F401
from jit.test_convert_activation import TestFunctionalToInplaceActivation, TestInplaceToFunctionalActivation # noqa: F401
from jit.test_parametrization import TestParametrization # noqa: F401
from jit.test_attr import TestGetDefaultAttr # noqa: F401
from jit.test_aten_pow import TestAtenPow # noqa: F401
from jit.test_optimize_for_mobile_preserve_debug_info import TestOptimizeForMobilePreserveDebugInfo # noqa: F401
from jit.test_union import TestUnion # noqa: F401
from jit.test_batch_mm import TestBatchMM # noqa: F401
from jit.test_dtype_analysis import TestDtypeAnalysis, TestDtypeCustomRulesCPU # noqa: F401
from jit.test_device_analysis import TestDeviceAnalysis # noqa: F401
from jit.test_dce import TestDCE # noqa: F401
from jit.test_sparse import TestSparse # noqa: F401
from jit.test_tensor_methods import TestTensorMethods # noqa: F401
from jit.test_dataclasses import TestDataclasses # noqa: F401
# Torch
from torch import Tensor
from torch._C import TensorType, BoolType, parse_ir, _propagate_shapes
from torch.autograd import Variable
from torch.jit.annotations import BroadcastingList2, BroadcastingList3, Any # noqa: F401
from torch.nn.utils.rnn import PackedSequence
from torch.testing import FileCheck, make_tensor
import torch.autograd.profiler
import torch.cuda
import torch.jit
import torch.jit._logging
import torch.jit.frontend
import torch.nn as nn
import torch.nn.functional as F
# Testing utils
from torch.testing._internal import jit_utils
from torch.testing._internal.common_jit import check_against_reference
from torch.testing._internal.common_utils import run_tests, IS_WINDOWS, TEST_WITH_UBSAN, \
suppress_warnings, BUILD_WITH_CAFFE2, IS_SANDCASTLE, GRAPH_EXECUTOR, ProfilingMode, TestCase, \
freeze_rng_state, slowTest, TemporaryFileName, skipIfCompiledWithoutNumpy, \
enable_profiling_mode_for_profiling_tests, TEST_MKL, set_default_dtype, num_profiled_runs, \
skipIfCrossRef, IS_MACOS, skipIfTorchDynamo
from torch.testing._internal.jit_utils import JitTestCase, enable_cpu_fuser, disable_autodiff_subgraph_inlining, \
_trace, do_input_map, get_execution_plan, make_global, \
execWrapper, _inline_everything, _tmp_donotuse_dont_inline_everything, \
RUN_CUDA
from torch.testing._internal.jit_metaprogramming_utils import (
get_script_args,
create_input, unpack_variables,
additional_module_tests, EXCLUDE_SCRIPT_MODULES,
get_nn_module_name_from_kwargs, get_nn_mod_test_name, script_method_template)
from torch.testing._internal.common_nn import module_tests, new_module_tests, criterion_tests
# For testing truediv in python 2
from torch.testing._internal.test_module.future_div import div_int_future, div_float_future
from torch.testing._internal.test_module.no_future_div import div_int_nofuture, div_float_nofuture
# Standard library
from collections import defaultdict, namedtuple, OrderedDict
from copy import deepcopy
from itertools import product
from textwrap import dedent
from typing import List, Dict, NamedTuple, Optional, Tuple, Union
import copy
import functools
import inspect
import io
import itertools
import math
import numpy as np
import os
import pickle
import pickletools
import random
import re
import shutil
import string
import sys
import tempfile
import types
import typing
import unittest
import warnings
import zipfile
def canonical(graph):
return torch._C._jit_pass_canonicalize(graph).str(False)
def LSTMCellF(input, hx, cx, *params):
return LSTMCell(input, (hx, cx), *params)
def doAutodiffCheck(testname):
# TODO: setting false on test itself is not working
if "test_t_" in testname or testname == "test_t":
return False
if GRAPH_EXECUTOR == ProfilingMode.SIMPLE:
return False
if GRAPH_EXECUTOR == ProfilingMode.LEGACY:
return True
# these tests are disabled because BailOut nodes
# inserted by ProfilingExecutor interfere with
# subgraph slicing of Differentiable Graphs
test_exceptions = [
# functional
'test_nn_dropout',
'test_nn_log_softmax',
'test_nn_relu',
'test_nn_softmax',
'test_nn_threshold',
'test_nn_lp_pool2d',
'test_nn_lp_pool1d',
'test_nn_gumbel_softmax_hard',
'test_nn_gumbel_softmax',
'test_nn_multilabel_soft_margin_loss',
'test_nn_batch_norm',
'test_nn_max_pool2d_with_indices',
# AutogradJitGenerated
'test___rdiv___constant',
'test___rdiv___scalar_constant',
'test_split',
'test_split_dim',
'test_split_dim_neg0',
'test_split_size_list',
'test_split_size_list_dim',
'test_split_size_list_dim_neg0',
'test_split_with_sizes',
'test_split_with_sizes_dim',
'test_split_with_sizes_dim_neg0',
'test_split_with_sizes_size_0',
'test_nn_max_pool2d_with_indices',
]
if testname in test_exceptions:
return False
return True
# TODO: enable TE in PE when all tests are fixed
torch._C._jit_set_texpr_fuser_enabled(GRAPH_EXECUTOR == ProfilingMode.PROFILING)
torch._C._jit_set_profiling_executor(GRAPH_EXECUTOR != ProfilingMode.LEGACY)
def LSTMCell(input, hidden, w_ih, w_hh, b_ih=None, b_hh=None):
hx, cx = hidden
gates = F.linear(input, w_ih, b_ih) + F.linear(hx, w_hh, b_hh)
ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)
ingate = torch.sigmoid(ingate)
forgetgate = torch.sigmoid(forgetgate)
cellgate = torch.tanh(cellgate)
outgate = torch.sigmoid(outgate)
cy = (forgetgate * cx) + (ingate * cellgate)
hy = outgate * torch.tanh(cy)
return hy, cy
def LSTMCellC(*args, **kwargs):
hy, cy = LSTMCellF(*args, **kwargs)
return torch.cat((hy, cy))
def LSTMCellS(x, hx, cx, w_ih, w_hh, b_ih, b_hh):
gates = x.mm(w_ih.t()) + hx.mm(w_hh.t()) + b_ih + b_hh
ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)
ingate = torch.sigmoid(ingate)
forgetgate = torch.sigmoid(forgetgate)
cellgate = torch.tanh(cellgate)
outgate = torch.sigmoid(outgate)
cy = (forgetgate * cx) + (ingate * cellgate)
hy = outgate * torch.tanh(cy)
return hy, cy
# Code reference: https://github.com/pytorch/translate/blob/master/pytorch_translate/rnn_cell.py#L27:44
def MiLSTMCell(x, hx, cx, w_ih, w_hh, alpha, beta_i, beta_h, bias):
Wx = x.mm(w_ih.t())
Uz = hx.mm(w_hh.t())
# Section 2.1 in https://arxiv.org/pdf/1606.06630.pdf
gates = alpha * Wx * Uz + beta_i * Wx + beta_h * Uz + bias
# Same as LSTMCell after this point
ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)
ingate = ingate.sigmoid()
forgetgate = forgetgate.sigmoid()
cellgate = cellgate.tanh()
outgate = outgate.sigmoid()
cy = (forgetgate * cx) + (ingate * cellgate)
hy = outgate * cy.tanh()
return hy, cy
def get_lstm_inputs(device, training=False, seq_length=None):
input_shape = (3, 10) if seq_length is None else (seq_length, 3, 10)
input = torch.randn(*input_shape, dtype=torch.float, device=device, requires_grad=training)
hx = torch.randn(3, 20, dtype=torch.float, device=device, requires_grad=training)
cx = torch.randn(3, 20, dtype=torch.float, device=device, requires_grad=training)
module = nn.LSTMCell(10, 20).to(device, torch.float) # Just to allocate weights with correct sizes
if training:
params = tuple(module.parameters())
else:
params = tuple(p.requires_grad_(False) for p in module.parameters())
return (input, hx, cx) + params
def get_milstm_inputs(device, training=False):
minibatch = 3
input_size = 10
hidden_size = 20
x = torch.randn(minibatch, input_size, device=device, dtype=torch.float)
hx = torch.randn(minibatch, hidden_size, device=device, dtype=torch.float)
cx = torch.randn(minibatch, hidden_size, device=device, dtype=torch.float)
ih = torch.randn(4 * hidden_size, input_size, device=device, dtype=torch.float, requires_grad=training)
hh = torch.randn(4 * hidden_size, hidden_size, device=device, dtype=torch.float, requires_grad=training)
alpha = torch.randn(4 * hidden_size, dtype=torch.float, device=device, requires_grad=training)
ibeta = torch.randn(4 * hidden_size, dtype=torch.float, device=device, requires_grad=training)
hbeta = torch.randn(4 * hidden_size, dtype=torch.float, device=device, requires_grad=training)
bias = torch.randn(4 * hidden_size, dtype=torch.float, device=device, requires_grad=training)
return x, hx, cx, ih, hh, alpha, ibeta, hbeta, bias
def get_fn(file_name, script_path):
import importlib.util
spec = importlib.util.spec_from_file_location(file_name, script_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
fn = module.fn
return fn
def get_grad_executor(plan_state, diff_graph_idx=None, skip_check=False):
if diff_graph_idx is None:
nodes = list(plan_state.graph.nodes())
if not skip_check:
nodes = list(filter(lambda n : n.kind() != "prim::BailOut" and n.kind() != "prim::BailoutTemplate", nodes))
if len(nodes) == 1 or (len(nodes) == 2 and nodes[1].kind() == "prim::TupleConstruct"):
pass
elif len(nodes) == 2 and nodes[0].kind() == "prim::RequiresGradCheck" and nodes[1].kind() == "prim::If":
pass
else:
raise RuntimeError("Can't get a grad_executor for a non-differentiable graph")
grad_executors = list(plan_state.code.grad_executor_states())
return grad_executors[diff_graph_idx or 0]
def all_backward_graphs(script_module, diff_graph_idx=None):
# Note: for Python 2 the order seems to be unstable
ge_state = script_module.get_debug_state()
fwd_plan = get_execution_plan(ge_state)
grad_executor_state = get_grad_executor(fwd_plan, diff_graph_idx=diff_graph_idx)
bwd_plans = list(grad_executor_state.execution_plans.values())
return [p.graph.copy() for p in bwd_plans]
def backward_graph(script_module, diff_graph_idx=None, skip_check=False):
ge_state = script_module.get_debug_state()
fwd_plan = get_execution_plan(ge_state)
grad_executor_state = get_grad_executor(fwd_plan, diff_graph_idx=diff_graph_idx, skip_check=skip_check)
bwd_plan = get_execution_plan(grad_executor_state)
# Running JIT passes requires that we own the graph (with a shared_ptr).
# The debug state struct does not own its graph so we make a copy of it.
return bwd_plan.graph.copy()
# helper function to get sum of List[Tensor]
def _sum_of_list(tensorlist):
s = 0
for t in tensorlist:
s += t.sum()
return s
# has to be at top level or Pickle complains
class FooToPickle(torch.nn.Module):
def __init__(self):
super(FooToPickle, self).__init__()
self.bar = torch.jit.ScriptModule()
class TestJit(JitTestCase):
@unittest.skip("Requires a lot of RAM")
def test_big(self):
m = torch.jit.ScriptModule()
gig = int(1024 * 1024 * 1024 / 4)
# a small tensor in the first 4GB
m.v0 = nn.Parameter(torch.full((2,), 1, dtype=torch.float))
# a large tensor in the first 4GB that ends outside of it
m.v1 = nn.Parameter(torch.full((5, gig), 2, dtype=torch.float))
# a small tensor in >4GB space
m.v2 = nn.Parameter(torch.full((2,), 3, dtype=torch.float))
# s large tensor in the > 4GB space
m.v3 = nn.Parameter(torch.full((5, gig), 4, dtype=torch.float))
m2 = self.getExportImportCopy(m)
self.assertEqual(tuple(m.parameters()), tuple(m2.parameters()))
def test_inferred_as_tensor(self):
with self.assertRaisesRegex(RuntimeError, "Inferred the value for argument 'dim' to be of type 'Tensor' "
"because it was not annotated with an explicit type"):
@torch.jit.script
def dot(points, query, dim):
return (points * query).sum(dim)
def test_constants_pkl(self):
# This test asserts that the serialization archive includes a `constants.pkl`
# file. This file is used by `torch.load` to determine whether a zip file
# is a normal eager-mode serialization zip or a jit serialization zip. If
# you are deleting `constants.pkl`, make sure to update `torch.serialization.load`
# so it is still able to figure out which is which.
@torch.jit.script
def fn(x):
return x
buf = io.BytesIO()
torch.jit.save(fn, buf)
buf.seek(0)
files = zipfile.ZipFile(buf).filelist
self.assertTrue(any(['archive/constants.pkl' == f.filename for f in files]))
def test_script_fn_pkl(self):
with self.assertRaisesRegex(pickle.PickleError, "ScriptFunction cannot be pickled"):
@torch.jit.script
def fn(x: torch.Tensor) -> torch.Tensor:
return x
pkl_fn = pickle.dumps(fn, protocol=0)
def test_restore_device(self):
class M(torch.jit.ScriptModule):
def __init__(self, cpu_device_str):
super(M, self).__init__()
self.p0 = nn.Parameter(torch.tensor([0.3], dtype=torch.float,
device=cpu_device_str))
self.b0 = torch.tensor([0.9], dtype=torch.float,
device=cpu_device_str)
# main purpose is checking map_location works
m = M("cpu")
m2 = self.getExportImportCopy(m)
self.assertEqual(tuple(m.parameters()), tuple(m2.parameters()))
self.assertEqual(tuple(m.buffers()), tuple(m2.buffers()))
self.assertFalse(m2.p0.is_cuda)
self.assertFalse(m2.b0.is_cuda)
@unittest.skipIf(not RUN_CUDA, "restore device requires CUDA")
def test_restore_device_cuda(self):
class MyModule(torch.jit.ScriptModule):
def __init__(self):
super(MyModule, self).__init__()
self.register_buffer('b0', torch.randn(1, 3))
self.p0 = nn.Parameter(torch.randn(2, 3))
@torch.jit.script_method
def forward(self, x):
return x + self.b0 + self.p0
m = MyModule()
m.cuda(torch.cuda.device_count() - 1)
cuda_device_str = 'cuda:' + str(torch.cuda.device_count() - 1)
self.assertTrue(m.p0.is_cuda)
self.assertTrue(m.b0.is_cuda)
# restore to the saved devices
m2 = self.getExportImportCopy(m)
self.assertEqual(tuple(m.parameters()), tuple(m2.parameters()))
self.assertEqual(tuple(m.buffers()), tuple(m2.buffers()))
self.assertEqual(str(m2.p0.device), cuda_device_str)
self.assertEqual(str(m2.b0.device), cuda_device_str)
# restore all to cpu using string
cpu_device_str = 'cpu'
m3 = self.getExportImportCopy(m, map_location=cpu_device_str)
self.assertEqual(str(m3.p0.device), cpu_device_str)
self.assertEqual(str(m3.b0.device), cpu_device_str)
# restore all to first gpu using device
m4 = self.getExportImportCopy(
m3, map_location=torch.device('cuda:0'))
self.assertEqual(str(m4.p0.device), 'cuda:0')
self.assertEqual(str(m4.b0.device), 'cuda:0')
# compute and compare the results
input = torch.rand(2, 3).cuda(torch.cuda.device_count() - 1)
origin_result = m(input)
self.assertEqual(origin_result, m2(input))
self.assertEqual(origin_result, m3(input.cpu()))
self.assertEqual(origin_result, m4(input.cuda(0)))
def test_trace_retains_train(self):
class M(torch.nn.Module):
def forward(self, x):
return x
m = M()
m.eval()
tm = torch.jit.trace(m, (torch.rand(3)))
self.assertEqual(tm.training, m.training)
@unittest.skipIf(not RUN_CUDA, "restore device requires CUDA")
def test_restore_shared_storage_on_cuda(self):
class Foo(torch.jit.ScriptModule):
def __init__(self):
super(Foo, self).__init__()
whole_tensor = torch.randn(4, 5, dtype=torch.float, device='cpu')
self.p0 = nn.Parameter(whole_tensor.narrow(0, 0, 1))
self.register_buffer('b0', whole_tensor.narrow(0, 3, 1))
m = Foo()
m2 = self.getExportImportCopy(m, map_location=torch.device('cuda:0'))
self.assertEqual(tuple(m.parameters()), tuple(m2.parameters()))
self.assertEqual(tuple(m.buffers()), tuple(m2.buffers()))
self.assertTrue(m2.p0.is_cuda)
self.assertTrue(m2.b0.is_cuda)
self.assertTrue(m2.p0.is_shared())
self.assertTrue(m2.b0.is_shared())
self.assertEqual(m2.b0.storage().data_ptr(), m2.p0.storage().data_ptr())
def test_add_relu_fusion(self):
class M(torch.nn.Module):
def __init__(self, relu_op):
super(M, self).__init__()
self.relu_op = relu_op
def forward(self, a, b, c):
tmp = torch.add(a, b)
x = self.relu_op(tmp)
d = torch.add(a, c)
return x + d
a = torch.rand((7, 11))
a = a * -10
a = a + 5
b = torch.rand((7, 11))
c = torch.rand((7, 11))
m = torch.jit.script(M(torch.relu))
orig_res = m(a, b, c)
torch._C._jit_pass_fuse_add_relu(m.graph)
buffer = io.BytesIO()
torch.jit.save(m, buffer)
buffer.seek(0)
m = torch.jit.load(buffer)
new_res = m(a, b, c)
FileCheck().check_not("aten::relu(") \
.check("aten::_add_relu(") \
.run(m.graph)
torch.testing.assert_close(orig_res, new_res)
# add, relu_
a = torch.rand((7, 11))
a = a * -10
a = a + 5
b = torch.rand((7, 11))
c = torch.rand((7, 11))
m = torch.jit.script(M(torch.relu_))
orig_res = m(a, b, c)
torch._C._jit_pass_fuse_add_relu(m.graph)
buffer = io.BytesIO()
torch.jit.save(m, buffer)
buffer.seek(0)
m = torch.jit.load(buffer)
new_res = m(a, b, c)
FileCheck().check_not("aten::relu_(") \
.check("aten::_add_relu(") \
.run(m.graph)
torch.testing.assert_close(orig_res, new_res)
class Madd_(torch.nn.Module):
def __init__(self, relu_op):
super(Madd_, self).__init__()
self.relu_op = relu_op
def forward(self, a, b):
x = a.add_(b)
x = self.relu_op(x)
return x
# add_, relu_
a = torch.rand((7, 11))
a = a * -10
a = a + 5
b = torch.rand((7, 11))
# Because in place add_ will overwrite a
a_copy = a.clone()
m = torch.jit.script(Madd_(torch.relu_))
orig_res = m(a, b)
torch._C._jit_pass_fuse_add_relu(m.graph)
buffer = io.BytesIO()
torch.jit.save(m, buffer)
buffer.seek(0)
m = torch.jit.load(buffer)
new_res = m(a_copy, b)
FileCheck().check_not("aten::add_(") \
.check_not("aten::relu_(") \
.check("aten::_add_relu_(") \
.run(m.graph)
torch.testing.assert_close(orig_res, new_res)
# Since _add_relu_ does inplace mutation ensure
# a_copy is modified
torch.testing.assert_close(orig_res, a_copy)
class Madd_out(torch.nn.Module):
def __init__(self, relu_op):
super(Madd_out, self).__init__()
self.relu_op = relu_op
def forward(self, a, b):
x = torch.add(a, b, out=a)
x = self.relu_op(x)
return x
a = torch.rand((7, 11))
a = a * -10
a = a + 5
b = torch.rand((7, 11))
# add_out, relu_
a = torch.rand((7, 11))
a = a * -10
a = a + 5
b = torch.rand((7, 11))
# Because in place add_ will overwrite a
a_copy = a.clone()
m = torch.jit.script(Madd_out(torch.relu_))
orig_res = m(a, b)
torch._C._jit_pass_fuse_add_relu(m.graph)
buffer = io.BytesIO()
torch.jit.save(m, buffer)
buffer.seek(0)
m = torch.jit.load(buffer)
new_res = m(a_copy, b)
FileCheck().check_not("aten::add(") \
.check_not("aten::relu_(") \
.check("aten::_add_relu(") \
.run(m.graph)
torch.testing.assert_close(orig_res, new_res)
# Since _add_relu_ with out=a does inplace mutation ensure
# a_copy is modified
torch.testing.assert_close(orig_res, a_copy)
def test_repeat_interleave_script(self):
def fn(input: torch.Tensor, repeats: torch.Tensor) -> torch.Tensor:
output = input.repeat_interleave(repeats)
return output
fn_scripted = torch.jit.script(fn)
input = torch.tensor([5, 7], dtype=torch.int64)
repeats = torch.tensor([3, 6], dtype=torch.int64)
output = fn(input, repeats)
output_scripted = fn_scripted(input, repeats)
self.assertEqual(output_scripted, output)
@unittest.skipIf(GRAPH_EXECUTOR != ProfilingMode.LEGACY, "Simple executor doesn't have shape information")
def test_peephole_optimize_shape_ops(self):
def test_input(func, input, result):
# if result == 2 we will trigger a bailout and
# the unprofiled graph should return the correct result
self.assertEqual(func(input, profile_and_replay=True), result)
gre = func.graph_for(input)
FileCheck().check_not("prim::If").run(gre)
def test_dim():
@torch.jit.script
def func(x):
if x.dim() == 1:
return 1
else:
return 2
test_input(func, torch.tensor([0.5]), 1)
test_input(func, torch.tensor([[0.5]]), 2)
test_dim()
def test_size_index():
@torch.jit.script
def func(x):
if x.size(0) == 1:
return 1
else:
return 2
test_input(func, torch.rand([1, 2]), 1)
test_input(func, torch.rand([1, 3]), 1)
@torch.jit.script
def neg_index(x):
if x.size(-2) == 1:
return 1
else:
return 2
test_input(neg_index, torch.rand([1, 2]), 1)
test_input(neg_index, torch.rand([1, 3]), 1)
if GRAPH_EXECUTOR == ProfilingMode.PROFILING:
test_size_index()
def test_dtype():
@torch.jit.script
def func(x):
if x.dtype == torch.float32:
return 1
else:
return 2
test_input(func, torch.tensor(0.5, dtype=torch.float32), 1)
test_input(func, torch.tensor(0.5, dtype=torch.int64), 2)
test_dtype()
def test_is_floating_poiint():
@torch.jit.script
def func(x):
if x.is_floating_point():
return 1
else:
return 2
test_input(func, torch.tensor(0.5, dtype=torch.float32), 1)
test_input(func, torch.tensor(0.5, dtype=torch.int64), 2)
test_is_floating_poiint()
def test_device():
@torch.jit.script
def func_1(x):
if x.device == torch.device('cuda:0'):
a = 0
else:
a = 1
return a
@torch.jit.script
def func_2(x):
if x.is_cuda:
a = 0
else:
a = 1
return a
test_input(func_1, torch.tensor(0.5), 1)
test_input(func_2, torch.tensor(0.5), 1)
if RUN_CUDA:
test_input(func_1, torch.tensor(0.5, device="cuda:0"), 0)
test_input(func_2, torch.tensor(0.5, device="cuda:0"), 0)
test_device()
def test_attrs(self):
def foo(x):
return (
# x.dtype, TODO: dtype long -> instance conversion
x.device,
x.shape,
x.is_cuda,
x.is_mkldnn,
x.is_quantized,
x.requires_grad,
x.T,
x.mT,
x.H,
x.mH
# x.layout TODO: layout long -> instance conversion
)
scripted = torch.jit.script(foo)
x = torch.rand(3, 4)
self.assertEqual(scripted(x), foo(x))
def test_layout(self):
@torch.jit.script
def check(x, y):
return x.layout == y.layout
x = torch.rand(3, 4)
y = torch.rand(3, 4)
self.assertTrue(check(x, y))
def test_matrix_transpose(self):
@torch.jit.script
def check(x):
return torch.equal(x.mT, x.transpose(-2, -1))
x = torch.rand(3, 4)
self.assertTrue(check(x))
def test_transpose(self):
@torch.jit.script
def check(x):
return torch.equal(x.T, x.t())
x = torch.rand(3, 4)
self.assertTrue(check(x))
def test_matrix_conj_transpose(self):
@torch.jit.script
def check(x):
return torch.equal(x.mH, x.transpose(-2, -1).conj())
x = torch.rand(3, 4)
self.assertTrue(check(x))
x = make_tensor((3, 4), device="cpu", dtype=torch.complex64)
self.assertTrue(check(x))
def test_conj_transpose(self):
@torch.jit.script
def check(x):
return torch.equal(x.H, x.t().conj())
x = torch.rand(3, 4)
self.assertTrue(check(x))
x = make_tensor((3, 4), device="cpu", dtype=torch.complex64)
self.assertTrue(check(x))
def test_T_mT_H_mH(self):
def T(x):
return x.mT
def mT(x):
return x.mT
def H(x):
return x.H
def mH(x):
return x.mH
x = torch.rand(3, 4)
y = make_tensor((3, 4), device="cpu", dtype=torch.complex64)
self.checkScript(T, (x, ))
self.checkScript(mT, (x, ))
self.checkScript(H, (x, ))
self.checkScript(mH, (x, ))
self.checkScript(T, (y, ))
self.checkScript(mT, (y, ))
self.checkScript(H, (y, ))
self.checkScript(mH, (y, ))
def test_nn_conv(self):
class Mod(nn.Module):
def __init__(self, conv):
super().__init__()
self.conv = conv
def forward(self, input):
return self.conv(input)
inputs = [
# Conv
(Mod(nn.Conv1d(16, 33, 3, stride=2)), torch.randn(20, 16, 5)),
(Mod(nn.Conv2d(16, 33, 3, stride=2)), torch.randn(20, 16, 5, 10)),
(Mod(nn.Conv3d(16, 33, 3, stride=2)), torch.randn(20, 16, 3, 5, 4)),
# ConvTransposed
(Mod(nn.ConvTranspose1d(16, 33, 3, stride=2)), torch.randn(20, 16, 5)),
(Mod(nn.ConvTranspose2d(16, 33, 3, stride=2)), torch.randn(20, 16, 5, 10)),
(Mod(nn.ConvTranspose3d(16, 33, 3, stride=2)), torch.randn(20, 16, 3, 5, 4)),
]
for m, inp in inputs:
self.checkModule(m, (inp,))
@unittest.skipIf(GRAPH_EXECUTOR != ProfilingMode.PROFILING, 'Not implemented for Simple or Legacy')
def test_debug_flush_compilation_cache(self):
def foo(x):
return x + 2
class Mod(nn.Module):
def __init__(self):
super(Mod, self).__init__()
def forward(self, t):
return t + 2
m = torch.jit.script(Mod())
x = torch.rand(1, 10)
with enable_profiling_mode_for_profiling_tests():
jitted = self.checkScript(foo, (x,))
# shouldn't throw
states = jitted.get_debug_state()
# after flushing there shouldn't be
# no opt plan
jitted._debug_flush_compilation_cache()
with self.assertRaisesRegex(RuntimeError, "INTERNAL ASSERT FAILED"):
states = jitted.get_debug_state()
NUM_RUNS = 1
with num_profiled_runs(NUM_RUNS):
m(x)
m(x)
fwd = m._c._get_method("forward")
states = m.get_debug_state()
# after flushing there shouldn't be
# no opt plan
fwd._debug_flush_compilation_cache()
with self.assertRaisesRegex(RuntimeError, "INTERNAL ASSERT FAILED"):
states = m.get_debug_state()
def test_numel(self):
@torch.jit.script
def get_numel_script(x):
return x.numel()
x = torch.rand(3, 4)
numel = get_numel_script(x)
self.assertEqual(numel, x.numel())
def test_element_size(self):
@torch.jit.script
def get_element_size_script(x):
return x.element_size()
x = torch.rand(3, 4)
element_size = get_element_size_script(x)
self.assertEqual(element_size, x.element_size())
def test_Sequential(self):
class Seq(nn.Module):
def __init__(self):
super(Seq, self).__init__()
self.seq = nn.Sequential(nn.Linear(10, 20), nn.Linear(20, 30))
@torch.jit.script_method
def forward(self, x):
for l in self.seq:
x = l(x)
return x
m = torch.jit.script(Seq())
assert m.graph # ensure jit was able to compile
def test_ModuleList(self):
class Mod(nn.Module):
def __init__(self):
super(Mod, self).__init__()
self.model = nn.ModuleList([nn.Linear(10, 10) for _ in range(10)])
self.model += (nn.Linear(10, 20),)
self.model.append(nn.Linear(20, 30))
self.model.extend([nn.Linear(30, 40), nn.Linear(40, 50)])
def forward(self, v):
for m in self.model:
v = m(v)
return v
m = torch.jit.script(Mod())
assert m.graph # ensure jit was able to compile
def test_disabled(self):
torch.jit._state.disable()
try:
def f(x, y):
return x + y
self.assertIs(torch.jit.trace(f, (torch.randn(2, 2), torch.randn(2, 2))), f)
self.assertIs(torch.jit.script(f), f)
class MyModule(torch.jit.ScriptModule):
@torch.jit.script_method
def method(self, x):
return x
# XXX: Unfortunately ScriptModule won't simply become Module now,
# because that requires disabling the JIT at startup time, which
# we can't do in here.
# We need to or those two conditions to make it work with all versions of Python
self.assertTrue(inspect.ismethod(MyModule.method) or inspect.isfunction(MyModule.method))
finally:
torch.jit._state.enable()
def test_train_eval(self):
class Sub(nn.Module):
def forward(self, input):
if self.training:
return input
else:
return -input
class MyModule(torch.jit.ScriptModule):
def __init__(self, module):
super(MyModule, self).__init__()
self.module = module
@torch.jit.script_method
def forward(self, input):
return self.module(input) + 1
m = MyModule(Sub())
input = torch.rand(3, 4)
self.assertEqual(input + 1, m(input))
m.eval()
self.assertEqual(-input + 1, m(input))
# test batchnorm and dropout train/eval
input = torch.randn(6, 10)
batchnorm = nn.BatchNorm1d(10)
dropout = nn.Dropout(p=0.2)
m_batchnorm = MyModule(batchnorm)
self.assertEqual(batchnorm(input) + 1, m_batchnorm(input))
batchnorm.eval()
m_batchnorm.eval()
self.assertEqual(batchnorm(input) + 1, m_batchnorm(input))
m_dropout = MyModule(dropout)
dropout.eval()
m_dropout.eval()
self.assertEqual(dropout(input) + 1, m_dropout(input))
def test_nn_lp_pool2d(self):
class Mod(torch.nn.Module):
def __init__(self):
super().__init__()
self.l = torch.nn.LPPool2d(2, 3)
self.n = torch.nn.LPPool2d(2, (7, 1))
def forward(self, x):
return (self.l(x),
self.n(x),
torch.nn.functional.lp_pool2d(x, float(2), 3),
torch.nn.functional.lp_pool2d(x, 2, 3),
torch.nn.functional.lp_pool2d(x, float(2), (7, 1)))
self.checkModule(Mod(), (torch.rand(1, 3, 7, 7),))
def test_nn_lp_pool1d(self):
class Mod(torch.nn.Module):
def __init__(self):
super().__init__()