1 from __future__ 
import print_function
    20 from common_utils 
import IS_WINDOWS, IS_PPC, skipIfRocm, load_tests
    24 load_tests = load_tests
    27     import torchvision.models 
as models
    28     HAS_TORCHVISION = 
True    30     HAS_TORCHVISION = 
False    33 skipIfNoTorchVision = unittest.skipIf(
not HAS_TORCHVISION, 
"no torchvision")
    37 from common_utils 
import TestCase, run_tests, download_file
    42     def __getitem__(self, index):
    43         return torch.tensor([torch.rand(1).item(), random.uniform(0, 1)])
    54     def _check_checkpoint_sequential(
    57         module_lists_to_compare,
    63         if not isinstance(inputs, tuple):
    66         out_not_checkpointed = out.data.clone()
    69         grad_not_checkpointed = {
    70             name: param.grad.data.clone()
    71             for name, param 
in model.named_parameters()
    73         input_grad_not_checkpointed = [i.grad.data.clone() 
for i 
in inputs]
    74         for model_to_compare 
in module_lists_to_compare:
    76             detached_inputs = [i.detach() 
for i 
in inputs]
    77             for detached 
in detached_inputs:
    78                 detached.requires_grad = 
True    81             out = checkpoint_sequential(model_to_compare, num_chunks, *detached_inputs)
    82             out_checkpointed = out.data.clone()
    86                 name: param.grad.data.clone()
    87                 for name, param 
in model.named_parameters()
    89             input_grad_checkpointed = [d.grad.data.clone() 
for d 
in detached_inputs]
    91             self.
assertEqual(out_checkpointed, out_not_checkpointed)
    92             for i, j 
in zip(input_grad_not_checkpointed, input_grad_checkpointed):
    94             for name 
in grad_checkpointed:
    95                 self.
assertEqual(grad_checkpointed[name], grad_not_checkpointed[name])
    99     def test_checkpoint_trigger(self):
   101         class Net(nn.Module):
   104                 super(Net, self).__init__()
   107             def forward(self, input_var):
   112         modules = [Net() 
for _ 
in range(10)]
   115         input_var = torch.randn(3, 4, requires_grad=
True)
   116         out = checkpoint_sequential(modules, 2, input_var)
   120         for m 
in modules[:(len(modules) // 2)]:
   122         for m 
in modules[(len(modules) // 2):]:
   125     def test_checkpoint_valid(self):
   126         model = nn.Sequential(
   135         input_var = torch.randn(1, 100, requires_grad=
True)
   139         modules = list(model.children())
   140         out = checkpoint_sequential(modules, chunks, input_var)
   143                 outputs=[out], grad_outputs=[torch.ones(1, 5)], inputs=[input_var], create_graph=
True   146     def test_checkpoint(self):
   147         model = nn.Sequential(
   162             [list(model.children()), model],
   164             torch.randn(1, 100, requires_grad=
True)
   167     def test_checkpoint_module_list_multiple_args(self):
   168         class ModuleListNet(nn.Module):
   170                 super(ModuleListNet, self).__init__()
   172                     nn.Bilinear(100, 60, 50),
   181             def forward(self, *inputs):
   183                     if isinstance(inputs, tuple):
   184                         inputs = layer(*inputs)
   186                         inputs = layer(inputs)
   189         model = ModuleListNet()
   197             [list(model.module_list.children()), model.module_list],
   199             torch.randn(1, 100, requires_grad=
True),
   200             torch.randn(1, 60, requires_grad=
True)
   203     def test_checkpoint_rng_cpu(self):
   205             inp = torch.randn(20000, device=
'cpu').requires_grad_()
   206             phase1 = torch.nn.Dropout()
   207             phase2 = torch.nn.Dropout()
   212             state = torch.get_rng_state()
   217             grad_with_checkpointing = inp.grad
   219             torch.set_rng_state(state)
   226             grad_no_checkpointing = inp.grad
   228             self.
assertEqual(grad_with_checkpointing, grad_no_checkpointing)
   230     @unittest.skipIf(
not HAS_CUDA, 
'No CUDA')
   231     def test_checkpoint_rng_cuda(self):
   233             inp = torch.randn(20000, device=
'cuda').requires_grad_()
   234             phase1 = torch.nn.Dropout()
   235             phase2 = torch.nn.Dropout()
   240             state = torch.cuda.get_rng_state()
   245             grad_with_checkpointing = inp.grad
   247             torch.cuda.set_rng_state(state)
   254             grad_no_checkpointing = inp.grad
   256             self.
assertEqual(grad_with_checkpointing, grad_no_checkpointing)
   258     def test_checkpoint_non_tensor(self):
   260         def run_fn(tensor1, tensor2):
   263             return tensor1 + tensor2
   265         input_var = torch.randn(1, 100, requires_grad=
True)
   272         self.
dataset = torch.randn(5, 3, 3, 2)
   275     def test_random_seed(self):
   281             return next(iter(dataloader))
   283         torch.manual_seed(2018)
   285         torch.manual_seed(2018)
   289     def test_single_keep(self):
   290         dataloader = torch.utils.data.DataLoader(self.
dataset,
   294         dataiter = iter(dataloader)
   297     def test_single_drop(self):
   298         dataloader = torch.utils.data.DataLoader(self.
dataset,
   302         dataiter = iter(dataloader)
   305     @unittest.skip(
"FIXME: Intermittent CUDA out-of-memory error on Windows and time-out under ASAN")
   306     def test_multi_keep(self):
   307         dataloader = torch.utils.data.DataLoader(self.
dataset,
   311         dataiter = iter(dataloader)
   314     def test_multi_drop(self):
   315         dataloader = torch.utils.data.DataLoader(self.
dataset,
   319         dataiter = iter(dataloader)
   323 test_dir = os.path.abspath(os.path.dirname(str(__file__)))
   327     def test_deprecated(self):
   328         with self.
assertRaisesRegex(ImportError, 
"torch.utils.ffi is deprecated. Please use cpp extensions instead."):
   332 @unittest.skipIf(
'SKIP_TEST_BOTTLENECK' in os.environ.keys(), 
'SKIP_TEST_BOTTLENECK is set')
   334     def _run(self, command):
   335         """Returns (return-code, stdout, stderr)"""   337         from common_utils 
import PY3
   339         p = subprocess.Popen(command, stdout=subprocess.PIPE,  
   340                              stderr=subprocess.PIPE, shell=
True)
   341         output, err = p.communicate()
   344             output = output.decode(
"ascii")
   345             err = err.decode(
"ascii")
   346         return (rc, output, err)
   348     def _run_bottleneck(self, test_file, scriptargs=''):
   349         curdir = os.path.dirname(os.path.abspath(__file__))
   350         filepath = 
'{}/{}'.format(curdir, test_file)
   352             scriptargs = 
' {}'.format(scriptargs)
   353         rc, out, err = self.
_run(
   354             '{} -m torch.utils.bottleneck {}{}'.format(sys.executable, filepath, scriptargs))
   357     def _check_run_args(self):
   363         rc, out, err = self.
_run_bottleneck(
'bottleneck/test_args.py', 
'--foo foo --bar bar')
   366     def _fail_msg(self, msg, output):
   367         return '{}, output was:\n{}'.format(msg, output)
   369     def _check_environment_summary(self, output):
   370         results = re.search(
'Environment Summary', output)
   371         self.assertIsNotNone(results, self.
_fail_msg(
'Should have Enviroment Summary', output))
   374         results = re.search(
r'Environment Summary.*(\n.*){,5}\nPyTorch \d+\.\d+', output)
   375         self.assertIsNotNone(results, self.
_fail_msg(
'Should have PyTorch version', output))
   377     def _check_cprof_summary(self, output):
   378         results = re.search(
'cProfile output', output)
   379         self.assertIsNotNone(results, self.
_fail_msg(
'Should have cProfile output', output))
   383         results = re.search(
r'cProfile output.*(\n.*){6,50}\n.*autograd profiler output', output)
   384         self.assertIsNotNone(results, self.
_fail_msg(
   385             'Distance between cProfile and autograd prof out not in [6, 50] lines', output))
   387     def _check_autograd_summary(self, output):
   388         results = re.search(
'autograd profiler output', output)
   389         self.assertIsNotNone(results, self.
_fail_msg(
'Should have autograd profiler output', output))
   393         results = re.search(
r'autograd profiler output.*(\n.*){6,100}', output)
   394         self.assertIsNotNone(results, self.
_fail_msg(
   395             'Distance between autograd prof output and end of output not in [6, 100] lines', output))
   397     def _check_cuda(self, output):
   399             results = re.search(
'CUDA mode', output)
   400             self.assertIsNotNone(results, self.
_fail_msg(
'Should tell users CUDA', output))
   402             results = re.search(
'CUDA mode', output)
   403             self.assertIsNone(results, self.
_fail_msg(
'Should not tell users about CUDA', output))
   405     @unittest.skipIf(HAS_CUDA, 
'CPU-only test')
   406     def test_bottleneck_cpu_only(self):
   408         self.
assertEqual(rc, 0, 
'Run failed with\n{}'.format(err))
   416     @unittest.skipIf(
not HAS_CUDA, 
'No CUDA')
   418     def test_bottleneck_cuda(self):
   420         self.
assertEqual(rc, 0, 
'Run failed with\n{}'.format(err))
   433     def test_smoke(self):
   434         info_output = get_pretty_env_info()
   435         self.assertTrue(info_output.count(
'\n') >= 17)
   439     def test_prepare_onnx_paddings(self):
   442         paddings = prepare_onnx_paddings(len(sizes), pad)
   445     def test_check_onnx_broadcast(self):
   447         def try_check_onnx_broadcast(dims1, dims2, expect_broadcast, expect_fail):
   451                 broadcast = check_onnx_broadcast(dims1, dims2)
   460         try_check_onnx_broadcast(dims1, dims2, 
True, 
True)
   465         try_check_onnx_broadcast(dims1, dims2, 
True, 
False)
   470         try_check_onnx_broadcast(dims1, dims2, 
True, 
False)
   475         try_check_onnx_broadcast(dims1, dims2, 
True, 
False)
   480         try_check_onnx_broadcast(dims1, dims2, 
True, 
True)
   485         try_check_onnx_broadcast(dims1, dims2, 
False, 
False)
   490         try_check_onnx_broadcast(dims1, dims2, 
True, 
True)
   495         try_check_onnx_broadcast(dims1, dims2, 
True, 
False)
   505     def test_load_from_github(self):
   506         hub_model = hub.load(
   513     def test_set_dir(self):
   514         temp_dir = tempfile.gettempdir()
   515         hub.set_dir(temp_dir)
   516         hub_model = hub.load(
   521         assert os.path.exists(temp_dir + 
'/vision_master')
   522         shutil.rmtree(temp_dir + 
'/vision_master')
   525 if __name__ == 
'__main__':
 def assertEqual(self, x, y, prec=None, message='', allow_inf=False)
 
def _check_environment_summary(self, output)
 
Module caffe2.python.checkpoint. 
 
def _check_autograd_summary(self, output)
 
def _check_checkpoint_sequential(self, model, module_lists_to_compare, num_chunks, inputs)
 
def _fail_msg(self, msg, output)
 
def _run_bottleneck(self, test_file, scriptargs='')
 
def _check_run_args(self)
 
def _check_cuda(self, output)
 
def _check_cprof_summary(self, output)
 
def grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=False, only_inputs=True, allow_unused=False)