PyTorch Introduction
PyTorch is an open-source Python machine learning library based on the Torch library, implemented at a low level in C++, and used in the field of artificial intelligence, such as computer vision and natural language processing.
PyTorch was originally developed by Meta Platforms' AI research team and is now part of the Linux Foundation.
Much deep learning software is built on PyTorch, including Tesla Autopilot, Uber's Pyro, Hugging Face's Transformers, PyTorch Lightning, and Catalyst.
PyTorch has two main features:
- NumPy-like tensor computation that can be accelerated on hardware accelerators such as GPUs or MPS.
- Deep neural networks based on an automatic differentiation system.
PyTorch includes submodules such as torch.autograd, torch.nn, and torch.optim.
PyTorch includes a variety of loss functions, including MSE (mean squared error = L2 norm), cross-entropy loss, and negative log-likelihood loss (useful for classifiers), among others.

PyTorch Features
-
Dynamic Computation Graphs: PyTorch's computation graphs are dynamic, meaning they are built at runtime and can change at any time. This provides great flexibility for experimentation and debugging, as developers can execute code line by line and inspect intermediate results.
-
Automatic Differentiation: PyTorch's automatic differentiation system allows developers to easily compute gradients, which is essential for training deep learning models. It automatically computes the gradients of the loss function with respect to the model parameters via the backpropagation algorithm.
-
Tensor Computation: PyTorch provides NumPy-like tensor operations that can run on both the CPU and GPU, accelerating the computation process. Tensors are the fundamental data structure in PyTorch, used to store and manipulate data.
-
Rich API: PyTorch provides a large number of predefined layers, loss functions, and optimization algorithms, which are common components for building deep learning models.
-
Multi-Language Support: Although PyTorch uses Python as its main interface, it also provides a C++ interface, allowing lower-level integration and control.
Dynamic Computation Graph
One of PyTorch's most notable features is its dynamic computation graph mechanism.
Unlike TensorFlow's static computation graph, PyTorch builds the computation graph at execution time, meaning that with each computation, the graph automatically changes according to the shape of the input data.
Advantages of dynamic computation graphs:
- More flexible, especially for scenarios requiring conditional logic or recursion.
- Easy to debug and modify, with the ability to inspect intermediate results directly.
- Closer to the style of Python programming, easy to get started with.
Tensor and Autograd
The core data structure in PyTorch is Tensor, a multi-dimensional matrix that can be computed efficiently on the CPU or GPU. Tensor operations support the automatic differentiation (Autograd) mechanism, which automatically computes gradients during backpropagation; this is crucial for gradient descent optimization algorithms in deep learning.
Tensor:
- Support switching between the CPU and GPU.
- Provides a NumPy-like interface and supports element-wise operations.
- Supports automatic differentiation for convenient gradient computation.
Autograd:
- PyTorch's built-in automatic differentiation engine automatically tracks all tensor operations and computes gradients during backpropagation.
- Pass
requires_gradattribute, you can specify that a tensor requires gradient computation. - Supports efficient backpropagation, suitable for neural network training.
Model Definition and Training
PyTorch provides the torch.nn module that allows users to define neural network models by subclassing the nn.Module class. Use the forward function to specify the forward pass; automatic backpropagation (via autograd) and gradient computation are also handled internally by PyTorch.
Neural Network Module (torch.nn):
- Provides common layers (such as linear, convolutional, and pooling layers, etc.).
- Supports defining complex neural network architectures (including networks with multiple inputs and outputs).
- Compatible with and used together with optimizers (such as
torch.optim).
GPU Acceleration
PyTorch fully supports running on the GPU to accelerate deep learning model training. Through a simple .to(device) method, users can transfer models and tensors to the GPU for computation. PyTorch supports multi-GPU training and can significantly improve computational efficiency using NVIDIA CUDA technology.
GPU support:
- Automatically select the GPU or CPU.
- Support accelerating computation via CUDA.
- Support multi-GPU parallel computing (
DataParallelortorch.distributed).
Ecosystem and Community Support
As an open-source project, PyTorch has a large community and ecosystem. It is not only widely used in academia, but also extensively deployed in industry, particularly in areas such as computer vision and natural language processing. PyTorch also provides many deep learning-related tools and libraries, such as:
- torchvision: datasets and models for computer vision tasks.
- torchtext: datasets and preprocessing tools for natural language processing tasks.
- torchaudio: a toolkit for audio processing.
- PyTorch Lightning: a high-level library that simplifies PyTorch code, focused on rapid iteration for research and experimentation.
Comparison with Other Frameworks
Due to its flexibility, ease of use, and community support, PyTorch has become the preferred framework for many deep learning researchers and developers.
TensorFlow vs PyTorch
- PyTorch's dynamic computation graph makes it more flexible and suitable for rapid experimentation and research, while TensorFlow's static computation graph offers more room for optimization in production environments.
- PyTorch is more convenient for debugging, while TensorFlow is more mature in deployment, supporting a wider range of hardware and platforms.
- In recent years, TensorFlow has also introduced dynamic graphs (such as TensorFlow 2.x), making the two increasingly similar in functionality.
- Other deep learning frameworks, such as Keras and Caffe, also have some applications, but due to its flexibility, ease of use, and community support, PyTorch has become the preferred framework for many deep learning researchers and developers.
| Feature | TensorFlow | PyTorch |
|---|---|---|
| Developing Company | Facebook (FAIR) | |
| Computation Graph Type | Static computation graph (define then execute) | Dynamic computation graph (define and execute immediately) |
| Flexibility | Low (the graph is built at compile time and hard to modify) | High (the graph is created dynamically at execution time, easy to modify and debug) |
| Debugging | Harder (requires using tf.debugging or external tools for debugging) |
Easy (can be debugged directly in Python) |
| Ease of Use | Low (more complex, more APIs, steeper learning curve) | High (concise API, syntax closer to Python, easy to get started) |
| Deployment | Strong (supports a wide range of hardware such as TensorFlow Lite and TensorFlow.js) | Relatively weak (fewer deployment tools and platforms, though TensorFlow support exists) |
| Community Support | Very strong (mature and large community, extensive tutorials and documentation) | Very strong (active community, especially in academia, fast-growing ecosystem) |
| Model training | Supports distributed training and multiple devices (such as CPU, GPU, TPU) | Supports distributed training, multiple GPUs, CPUs and TPUs |
| API levels | High-level API: Keras; low-level API: TensorFlow Core | High-level APIs: TorchVision, TorchText, etc.; low-level API: Torch |
| Performance | High (mature in optimization, suitable for production) | High (suitable for research and prototyping, production performance improving) |
| Automatic differentiation | Pass tf.GradientTape Implements dynamic differentiation (more complex) |
Pass autograd Dynamic differentiation (more concise and intuitive) |
| Tuning and scalability | Strong (runs on multiple platforms such as TensorFlow Serving) | Relatively weak (excels in academic and experimental settings but has less production support) |
| Framework flexibility | Relatively low (TensorFlow 2.x introduced dynamic graphs but is still not fully flexible) | High (dynamic graphs bring greater flexibility) |
| Supports multiple languages | Supports multiple languages (Python, C++, Java, JavaScript, etc.) | Primarily supports Python (but also has a C++ API) |
| Compatibility and migration | TensorFlow 2.x has good backward compatibility | Poor compatibility with TensorFlow, harder to migrate |
PyTorch vs NumPy
| Feature | PyTorch | NumPy |
|---|---|---|
| Goals | Dedicated to deep learning | General-purpose scientific computing |
| GPU support | Native CUDA support | No direct support |
| Automatic differentiation | Built-in automatic differentiation | Gradients must be computed manually |
| Neural networks | Rich neural network modules | Must be implemented from scratch |
| Learning Cost | Relatively high | Relatively low |
History and development of PyTorch
PyTorch's predecessor was Torch, a scientific computing framework based on the Lua language. As Python rose in the machine learning field, the Facebook team decided to port Torch's core ideas to Python, giving birth to PyTorch.
- 2016: Facebook releases PyTorch 0.1
- 2017: PyTorch 0.2 introduces distributed training support
- 2018: PyTorch 1.0 released, adding production deployment capabilities
- 2019: PyTorch 1.3 introduces mobile support
- 2020: PyTorch 1.6 adds automatic mixed precision training
- 2021: PyTorch 1.9 introduces TorchScript and the C++ frontend
- 2022: PyTorch 1.12 optimizes performance and stability
- 2023: PyTorch 2.0 released, introducing compiled mode for major performance gains