PyTorch For Machine Learning
PyTorch For Machine Learning
Modules
Autograd module
PyTorch uses a method called automatic differentiation. A recorder records what operations have
performed, and then it replays it backward to compute the gradients. This method is especially powerful
when building neural networks to save time on one epoch by calculating differentiation of the parameters at
the forward pass.[26]
Optim module
torch.optim is a module that implements various optimization algorithms used for building neural
networks. Most of the commonly used methods are already supported, so there is no need to build them
from scratch.[27]
nn module
PyTorch autograd makes it easy to define computational graphs and take gradients, but raw autograd can be
a bit too low-level for defining complex neural networks. This is where the nn module can help. The nn
module provides layers and tools to easily create a neural networks by just defining the layers of the
network.[28]
PyTorch also contains many other useful submodules such as data loading utilities and distributed training
functions.
Example
The following program shows the low-level functionality of the library with a simple example
1 import torch
2 dtype = torch.float
3 device = torch.device("cpu") # This executes all calculations on the CPU
4 # device = torch.device("cuda:0") # This executes all calculations on the GPU
5
6 # Creation of a tensor and filling of a tensor with random numbers
7 a = torch.randn(2, 3, device=device, dtype=dtype)
8 print(a) # Output of tensor A
9 # Output: tensor([[-1.1884, 0.8498, -1.7129],
10 # [-0.8816, 0.1944, 0.5847]])
11
12 # Creation of a tensor and filling of a tensor with random numbers
13 b = torch.randn(2, 3, device=device, dtype=dtype)
14 print(b) # Output of tensor B
15 # Output: tensor([[ 0.7178, -0.8453, -1.3403],
16 # [ 1.3262, 1.1512, -1.7070]])
17
18 print(a*b) # Output of a multiplication of the two tensors
19 # Output: tensor([[-0.8530, -0.7183, 2.58],
20 # [-1.1692, 0.2238, -0.9981]])
21
22 print(a.sum()) # Output of the sum of all elements in tensor A
23 # Output: tensor(-2.1540)
24
25 print(a[1,2]) # Output of the element in the third column of the second row (zero based)
26 # Output: tensor(0.5847)
27
28 print(a.max()) # Output of the maximum value in tensor A
29 # Output: tensor(-1.7129)
The following code-block shows an example of the higher level functionality provided nn module. A
neural network with linear layers is defined in the example.
1 import torch
2 from torch import nn # Import the nn sub-module from PyTorch
3
4 class NeuralNetwork(nn.Module): # Neural networks are defined as classes
5 def __init__(self): # Layers and variables are defined in the __init__ method
6 super(NeuralNetwork, self).__init__() # Must be in every network.
7 self.flatten = nn.Flatten() # Defining a flattening layer.
8 self.linear_relu_stack = nn.Sequential( # Defining a stack of layers.
9 nn.Linear(28*28, 512), # Linear Layers have an input and output shape
10 nn.ReLU(), # ReLU is one of many activation functions provided by nn
11 nn.Linear(512, 512),
12 nn.ReLU(),
13 nn.Linear(512, 10),
14 )
15
16 def forward(self, x): # This function defines the forward pass.
17 x = self.flatten(x)
18 logits = self.linear_relu_stack(x)
19 return logits
See also
Free and open-
source software
portal
References
1. Chintala, Soumith (1 September 2016). "PyTorch Alpha-1 release" (https://github.com/pytorc
h/pytorch/releases/tag/v0.1.1).
2. "Release 2.0.1" (https://github.com/pytorch/pytorch/releases/tag/v2.0.1). 8 May 2023.
Retrieved 28 May 2023.
3. Claburn, Thomas (12 September 2022). "PyTorch gets lit under The Linux Foundation" (http
s://www.theregister.com/2022/09/12/pytorch_meta_linux_foundation/). The Register.
4. Yegulalp, Serdar (19 January 2017). "Facebook brings GPU-powered machine learning to
Python" (https://www.infoworld.com/article/3159120/artificial-intelligence/facebook-brings-gp
u-powered-machine-learning-to-python.html). InfoWorld. Retrieved 11 December 2017.
5. Lorica, Ben (3 August 2017). "Why AI and machine learning researchers are beginning to
embrace PyTorch" (https://www.oreilly.com/ideas/why-ai-and-machine-learning-researchers-
are-beginning-to-embrace-pytorch). O'Reilly Media. Retrieved 11 December 2017.
6. Ketkar, Nikhil (2017). "Introduction to PyTorch". Deep Learning with Python. Apress,
Berkeley, CA. pp. 195–208. doi:10.1007/978-1-4842-2766-4_12 (https://doi.org/10.1007%2F
978-1-4842-2766-4_12). ISBN 9781484227657.
7. "Natural Language Processing (NLP) with PyTorch – NLP with PyTorch documentation" (htt
p://dl4nlp.info/en/latest/). dl4nlp.info. Retrieved 2017-12-18.
8. Patel, Mo (2017-12-07). "When two trends fuse: PyTorch and recommender systems" (http
s://www.oreilly.com/ideas/when-two-trends-fuse-pytorch-and-recommender-systems).
O'Reilly Media. Retrieved 2017-12-18.
9. Mannes, John. "Facebook and Microsoft collaborate to simplify conversions from PyTorch to
Caffe2" (https://techcrunch.com/2017/09/07/facebook-and-microsoft-collaborate-to-simplify-c
onversions-from-pytorch-to-caffe2/). TechCrunch. Retrieved 2017-12-18. "FAIR is
accustomed to working with PyTorch – a deep learning framework optimized for achieving
state of the art results in research, regardless of resource constraints. Unfortunately in the
real world, most of us are limited by the computational capabilities of our smartphones and
computers."
10. Arakelyan, Sophia (2017-11-29). "Tech giants are using open source frameworks to
dominate the AI community" (https://venturebeat.com/2017/11/29/tech-giants-are-using-open
-source-frameworks-to-dominate-the-ai-community/). VentureBeat. Retrieved 2017-12-18.
11. "PyTorch strengthens its governance by joining the Linux Foundation" (https://pytorch.org/bl
og/PyTorchfoundation/). pytorch.org. Retrieved 2022-09-13.
12. "The C++ Frontend" (https://pytorch.org/cppdocs/frontend.html). PyTorch Master
Documentation. Retrieved 2019-07-29.
13. Karpathy, Andrej. "PyTorch at Tesla - Andrej Karpathy, Tesla" (https://www.youtube.com/watc
h?v=oBklltKXtDE).
14. "Uber AI Labs Open Sources Pyro, a Deep Probabilistic Programming Language" (https://en
g.uber.com/pyro/). Uber Engineering Blog. 2017-11-03. Retrieved 2017-12-18.
15. PYTORCH-TRANSFORMERS: PyTorch implementations of popular NLP Transformers (htt
ps://pytorch.org/hub/huggingface_pytorch-transformers/), PyTorch Hub, 2019-12-01,
retrieved 2019-12-01
16. PYTORCH-Lightning: The lightweight PyTorch wrapper for ML researchers. Scale your
models. Write less boilerplate (https://github.com/PyTorchLightning/pytorch-lightning/),
Lightning-Team, 2020-06-18, retrieved 2020-06-18
17. "Ecosystem Tools" (https://pytorch.org/ecosystem/). pytorch.org. Retrieved 2020-06-18.
18. GitHub - catalyst-team/catalyst: Accelerated DL & RL (https://github.com/catalyst-team/cataly
st), Catalyst-Team, 2019-12-05, retrieved 2019-12-05
19. "Ecosystem Tools" (https://pytorch.org/ecosystem/). pytorch.org. Retrieved 2020-04-04.
20. "PyTorch – About" (https://web.archive.org/web/20180615190804/https://pytorch.org/about/).
pytorch.org. Archived from the original (https://pytorch.org/about/) on 2018-06-15. Retrieved
2018-06-11.
21. "Caffe2 Merges With PyTorch" (https://medium.com/@Synced/caffe2-merges-with-pytorch-a
89c70ad9eb7). 2018-04-02.
22. Edwards, Benj (2022-09-12). "Meta spins off PyTorch Foundation to make AI framework
vendor neutral" (https://arstechnica.com/information-technology/2022/09/meta-spins-off-pytor
ch-foundation-to-make-ai-framework-vendor-neutral/). Ars Technica.
23. "PyTorch 2.0 brings new fire to open-source machine learning" (https://venturebeat.com/ai/p
ytorch-2-0-brings-new-fire-to-open-source-machine-learning/). VentureBeat. 15 March 2023.
Retrieved 16 March 2023.
24. "Introducing Accelerated PyTorch Training on Mac" (https://pytorch.org/blog/introducing-acce
lerated-pytorch-training-on-mac/). pytorch.org. Retrieved 2022-06-04.
25. "An Introduction to PyTorch – A Simple yet Powerful Deep Learning Library" (https://www.an
alyticsvidhya.com/blog/2018/02/pytorch-tutorial/). analyticsvidhya.com. 2018-02-22.
Retrieved 2018-06-11.
26. "The Fundamentals of Autograd — PyTorch Tutorials 2.0.1+cu117 documentation" (https://py
torch.org/tutorials/beginner/introyt/autogradyt_tutorial.html). pytorch.org. Retrieved 16 May
2023.
27. "torch.optim — PyTorch 2.0 documentation" (https://pytorch.org/docs/stable/optim.html).
pytorch.org. Retrieved 16 May 2023.
28. "torch.nn — PyTorch 2.0 documentation" (https://pytorch.org/docs/stable/nn.html).
pytorch.org. Retrieved 16 May 2023.
External links
Official website (https://pytorch.org)