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

Diff for: advanced_source/cpp_frontend.rst

-3
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

Diff for: advanced_source/neural_style_tutorial.py

-2
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

Diff for: advanced_source/rpc_ddp_tutorial.rst

+1-1
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>`__.

Diff for: beginner_source/chatbot_tutorial.py

-5
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

Diff for: beginner_source/data_loading_tutorial.py

-1
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

Diff for: beginner_source/deploy_seq2seq_hybrid_frontend_tutorial.py

-5
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

Diff for: beginner_source/fgsm_tutorial.py

+9-15
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()

Diff for: beginner_source/transfer_learning_tutorial.py

-2
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

Diff for: conf.py

+8-1
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'):

Diff for: intermediate_source/char_rnn_classification_tutorial.py

-1
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

Diff for: intermediate_source/char_rnn_generation_tutorial.py

-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@
7575
and end up with a dictionary ``{language: [names ...]}``.
7676
7777
"""
78-
from __future__ import unicode_literals, print_function, division
7978
from io import open
8079
import glob
8180
import os

Diff for: intermediate_source/dynamic_quantization_bert_tutorial.rst

+2-17
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,6 @@ In this step we import the necessary Python modules for the tutorial.
9292

9393
.. code:: python
9494
95-
from __future__ import absolute_import, division, print_function
96-
9795
import logging
9896
import numpy as np
9997
import os
@@ -255,8 +253,6 @@ model before and after the dynamic quantization.
255253
torch.manual_seed(seed)
256254
set_seed(42)
257255
258-
# Initialize a global random number generator
259-
global_rng = random.Random()
260256
261257
262258
2.2 Load the fine-tuned BERT model
@@ -528,20 +524,9 @@ We can serialize and save the quantized model for the future use using
528524

529525
.. code:: python
530526
531-
def ids_tensor(shape, vocab_size, rng=None, name=None):
527+
def ids_tensor(shape, vocab_size):
532528
# Creates a random int32 tensor of the shape within the vocab size
533-
if rng is None:
534-
rng = global_rng
535-
536-
total_dims = 1
537-
for dim in shape:
538-
total_dims *= dim
539-
540-
values = []
541-
for _ in range(total_dims):
542-
values.append(rng.randint(0, vocab_size - 1))
543-
544-
return torch.tensor(data=values, dtype=torch.long, device='cpu').view(shape).contiguous()
529+
return torch.randint(0, vocab_size, shape=shape, dtype=torch.int, device='cpu')
545530
546531
input_ids = ids_tensor([8, 128], 2)
547532
token_type_ids = ids_tensor([8, 128], 2)

Diff for: intermediate_source/mario_rl_tutorial.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@
5353
# Super Mario environment for OpenAI Gym
5454
import gym_super_mario_bros
5555

56+
from tensordict import TensorDict
57+
from torchrl.data import TensorDictReplayBuffer, LazyMemmapStorage
5658

5759
######################################################################
5860
# RL Definitions
@@ -348,7 +350,7 @@ def act(self, state):
348350
class Mario(Mario): # subclassing for continuity
349351
def __init__(self, state_dim, action_dim, save_dir):
350352
super().__init__(state_dim, action_dim, save_dir)
351-
self.memory = deque(maxlen=100000)
353+
self.memory = TensorDictReplayBuffer(storage=LazyMemmapStorage(100000))
352354
self.batch_size = 32
353355

354356
def cache(self, state, next_state, action, reward, done):
@@ -373,14 +375,15 @@ def first_if_tuple(x):
373375
reward = torch.tensor([reward], device=self.device)
374376
done = torch.tensor([done], device=self.device)
375377

376-
self.memory.append((state, next_state, action, reward, done,))
378+
# self.memory.append((state, next_state, action, reward, done,))
379+
self.memory.add(TensorDict({"state": state, "next_state": next_state, "action": action, "reward": reward, "done": done}, batch_size=[]))
377380

378381
def recall(self):
379382
"""
380383
Retrieve a batch of experiences from memory
381384
"""
382-
batch = random.sample(self.memory, self.batch_size)
383-
state, next_state, action, reward, done = map(torch.stack, zip(*batch))
385+
batch = self.memory.sample(self.batch_size)
386+
state, next_state, action, reward, done = (batch.get(key) for key in ("state", "next_state", "action", "reward", "done"))
384387
return state, next_state, action.squeeze(), reward.squeeze(), done.squeeze()
385388

386389

Diff for: intermediate_source/seq2seq_translation_tutorial.py

-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@
7878
7979
**Requirements**
8080
"""
81-
from __future__ import unicode_literals, print_function, division
8281
from io import open
8382
import unicodedata
8483
import string

Diff for: intermediate_source/spatial_transformer_tutorial.py

-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
# License: BSD
2828
# Author: Ghassen Hamrouni
2929

30-
from __future__ import print_function
3130
import torch
3231
import torch.nn as nn
3332
import torch.nn.functional as F

Diff for: intermediate_source/torch_compile_tutorial.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969

7070
def foo(x, y):
7171
a = torch.sin(x)
72-
b = torch.cos(x)
72+
b = torch.cos(y)
7373
return a + b
7474
opt_foo1 = torch.compile(foo)
7575
print(opt_foo1(torch.randn(10, 10), torch.randn(10, 10)))
@@ -80,7 +80,7 @@ def foo(x, y):
8080
@torch.compile
8181
def opt_foo2(x, y):
8282
a = torch.sin(x)
83-
b = torch.cos(x)
83+
b = torch.cos(y)
8484
return a + b
8585
print(opt_foo2(torch.randn(10, 10), torch.randn(10, 10)))
8686

Diff for: prototype_source/graph_mode_dynamic_bert_tutorial.rst

+2-17
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,6 @@ Once all the necesessary packages are downloaded and installed we setup the code
4040

4141
.. code:: python
4242
43-
from __future__ import absolute_import, division, print_function
44-
4543
import logging
4644
import numpy as np
4745
import os
@@ -62,22 +60,9 @@ Once all the necesessary packages are downloaded and installed we setup the code
6260
from torch.quantization import per_channel_dynamic_qconfig
6361
from torch.quantization import quantize_dynamic_jit
6462
65-
global_rng = random.Random()
66-
67-
def ids_tensor(shape, vocab_size, rng=None, name=None):
63+
def ids_tensor(shape, vocab_size):
6864
# Creates a random int32 tensor of the shape within the vocab size
69-
if rng is None:
70-
rng = global_rng
71-
72-
total_dims = 1
73-
for dim in shape:
74-
total_dims *= dim
75-
76-
values = []
77-
for _ in range(total_dims):
78-
values.append(rng.randint(0, vocab_size - 1))
79-
80-
return torch.tensor(data=values, dtype=torch.long, device='cpu').view(shape).contiguous()
65+
return torch.randint(0, vocab_size, shape=shape, dtype=torch.int, device='cpu')
8166
8267
# Setup logging
8368
logger = logging.getLogger(__name__)

Diff for: prototype_source/numeric_suite_tutorial.py

-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424

2525
##############################################################################
2626

27-
from __future__ import print_function, division, absolute_import
2827
import numpy as np
2928
import torch
3029
import torch.nn as nn

Diff for: recipes_source/recipes/changing_default_device.py

-3
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,6 @@
4343
print(mod.weight.device)
4444
print(mod(torch.randn(128, 20)).device)
4545

46-
# And then globally return it back to CPU
47-
torch.set_default_device('cpu')
48-
4946
################################################################
5047
# This function imposes a slight performance cost on every Python
5148
# call to the torch API (not just factory functions). If this

0 commit comments

Comments
 (0)