Skip to content

Commit f3e45d9

Browse files
author
Svetlana Karslioglu
authored
Merge branch 'main' into Create_copy_of_model
2 parents 4137d33 + eaa2e90 commit f3e45d9

19 files changed

+31
-83
lines changed

advanced_source/cpp_frontend.rst

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,9 +1216,6 @@ tensors and display them with matplotlib:
12161216
12171217
.. code-block:: python
12181218
1219-
from __future__ import print_function
1220-
from __future__ import unicode_literals
1221-
12221219
import argparse
12231220
12241221
import matplotlib.pyplot as plt

advanced_source/neural_style_tutorial.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,6 @@
4747
# - ``torchvision.models`` (train or load pretrained models)
4848
# - ``copy`` (to deep copy the models; system package)
4949

50-
from __future__ import print_function
51-
5250
import torch
5351
import torch.nn as nn
5452
import torch.nn.functional as F

advanced_source/rpc_ddp_tutorial.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
Combining Distributed DataParallel with Distributed RPC Framework
22
=================================================================
3-
**Authors**: `Pritam Damania <https://github.com/pritamdamania87>`_ and `Yi Wang <https://github.com/SciPioneer>`_
3+
**Authors**: `Pritam Damania <https://github.com/pritamdamania87>`_ and `Yi Wang <https://github.com/wayi1>`_
44

55
.. note::
66
|edit| View and edit this tutorial in `github <https://github.com/pytorch/tutorials/blob/main/advanced_source/rpc_ddp_tutorial.rst>`__.

beginner_source/chatbot_tutorial.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -92,11 +92,6 @@
9292
# After that, let’s import some necessities.
9393
#
9494

95-
from __future__ import absolute_import
96-
from __future__ import division
97-
from __future__ import print_function
98-
from __future__ import unicode_literals
99-
10095
import torch
10196
from torch.jit import script, trace
10297
import torch.nn as nn

beginner_source/data_loading_tutorial.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
1919
"""
2020

21-
from __future__ import print_function, division
2221
import os
2322
import torch
2423
import pandas as pd

beginner_source/deploy_seq2seq_hybrid_frontend_tutorial.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,6 @@
101101
# maximum length output that the model is capable of producing.
102102
#
103103

104-
from __future__ import absolute_import
105-
from __future__ import division
106-
from __future__ import print_function
107-
from __future__ import unicode_literals
108-
109104
import torch
110105
import torch.nn as nn
111106
import torch.nn.functional as F

beginner_source/fgsm_tutorial.py

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@
9090
# into the implementation.
9191
#
9292

93-
from __future__ import print_function
9493
import torch
9594
import torch.nn as nn
9695
import torch.nn.functional as F
@@ -99,13 +98,6 @@
9998
import numpy as np
10099
import matplotlib.pyplot as plt
101100

102-
# NOTE: This is a hack to get around "User-agent" limitations when downloading MNIST datasets
103-
# see, https://github.com/pytorch/vision/issues/3497 for more information
104-
from six.moves import urllib
105-
opener = urllib.request.build_opener()
106-
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
107-
urllib.request.install_opener(opener)
108-
109101

110102
######################################################################
111103
# Implementation
@@ -141,6 +133,8 @@
141133
epsilons = [0, .05, .1, .15, .2, .25, .3]
142134
pretrained_model = "data/lenet_mnist_model.pth"
143135
use_cuda=True
136+
# Set random seed for reproducibility
137+
torch.manual_seed(42)
144138

145139

146140
######################################################################
@@ -179,18 +173,18 @@ def forward(self, x):
179173
test_loader = torch.utils.data.DataLoader(
180174
datasets.MNIST('../data', train=False, download=True, transform=transforms.Compose([
181175
transforms.ToTensor(),
182-
])),
176+
])),
183177
batch_size=1, shuffle=True)
184178

185179
# Define what device we are using
186180
print("CUDA Available: ",torch.cuda.is_available())
187-
device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")
181+
device = torch.device("cuda" if use_cuda and torch.cuda.is_available() else "cpu")
188182

189183
# Initialize the network
190184
model = Net().to(device)
191185

192186
# Load the pretrained model
193-
model.load_state_dict(torch.load(pretrained_model, map_location='cpu'))
187+
model.load_state_dict(torch.load(pretrained_model, weights_only=True, map_location='cpu'))
194188

195189
# Set the model in evaluation mode. In this case this is for the Dropout layers
196190
model.eval()
@@ -290,7 +284,7 @@ def test( model, device, test_loader, epsilon ):
290284
if final_pred.item() == target.item():
291285
correct += 1
292286
# Special case for saving 0 epsilon examples
293-
if (epsilon == 0) and (len(adv_examples) < 5):
287+
if epsilon == 0 and len(adv_examples) < 5:
294288
adv_ex = perturbed_data.squeeze().detach().cpu().numpy()
295289
adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )
296290
else:
@@ -301,7 +295,7 @@ def test( model, device, test_loader, epsilon ):
301295

302296
# Calculate final accuracy for this epsilon
303297
final_acc = correct/float(len(test_loader))
304-
print("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct, len(test_loader), final_acc))
298+
print(f"Epsilon: {epsilon}\tTest Accuracy = {correct} / {len(test_loader)} = {final_acc}")
305299

306300
# Return the accuracy and an adversarial example
307301
return final_acc, adv_examples
@@ -387,9 +381,9 @@ def test( model, device, test_loader, epsilon ):
387381
plt.xticks([], [])
388382
plt.yticks([], [])
389383
if j == 0:
390-
plt.ylabel("Eps: {}".format(epsilons[i]), fontsize=14)
384+
plt.ylabel(f"Eps: {epsilons[i]}", fontsize=14)
391385
orig,adv,ex = examples[i][j]
392-
plt.title("{} -> {}".format(orig, adv))
386+
plt.title(f"{orig} -> {adv}")
393387
plt.imshow(ex, cmap="gray")
394388
plt.tight_layout()
395389
plt.show()

beginner_source/transfer_learning_tutorial.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@
3333
# License: BSD
3434
# Author: Sasank Chilamkurthy
3535

36-
from __future__ import print_function, division
37-
3836
import torch
3937
import torch.nn as nn
4038
import torch.optim as optim

conf.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import pytorch_sphinx_theme
3535
import torch
3636
import glob
37+
import random
3738
import shutil
3839
from custom_directives import IncludeDirective, GalleryItemDirective, CustomGalleryItemDirective, CustomCalloutItemDirective, CustomCardItemDirective
3940
import distutils.file_util
@@ -85,6 +86,11 @@
8586

8687
# -- Sphinx-gallery configuration --------------------------------------------
8788

89+
def reset_seeds(gallery_conf, fname):
90+
torch.manual_seed(42)
91+
torch.set_default_device(None)
92+
random.seed(10)
93+
8894
sphinx_gallery_conf = {
8995
'examples_dirs': ['beginner_source', 'intermediate_source',
9096
'advanced_source', 'recipes_source', 'prototype_source'],
@@ -94,7 +100,8 @@
94100
'backreferences_dir': None,
95101
'first_notebook_cell': ("# For tips on running notebooks in Google Colab, see\n"
96102
"# https://pytorch.org/tutorials/beginner/colab\n"
97-
"%matplotlib inline")
103+
"%matplotlib inline"),
104+
'reset_modules': (reset_seeds)
98105
}
99106

100107
if os.getenv('GALLERY_PATTERN'):

intermediate_source/char_rnn_classification_tutorial.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,6 @@
7474
``{language: [names ...]}``. The generic variables "category" and "line"
7575
(for language and name in our case) are used for later extensibility.
7676
"""
77-
from __future__ import unicode_literals, print_function, division
7877
from io import open
7978
import glob
8079
import os

0 commit comments

Comments
 (0)