1. Foundations of PyTorch
Introduction to Tensors and Creation Methods
Tensors are the fundamental data structure in PyTorch, serving as the multi-dimensional generalization of scalars, vectors, and matrices. At their core, PyTorch tensors are highly optimized arrays that support automatic differentiation, making them the ideal vehicle for deep learning computations.
You can initialize tensors using a variety of constructors, including direct data conversion from standard Python lists or NumPy arrays. Using torch.tensor() or torch.from_numpy() creates tensors that share underlying memory with their source, providing high performance for data integration workflows.
import torch import numpy as np # Create a tensor from a nested list list_data = [[1.0, 2.0], [3.0, 4.0]] t1 = torch.tensor(list_data) # Create a tensor from a NumPy array numpy_arr = np.array([[5, 6], [7, 8]], dtype=np.float32) t2 = torch.from_numpy(numpy_arr) # Verify device and dtype print(f'Tensor t1 shape: {t1.shape}, dtype: {t1.dtype}') print(f'Tensor t2 device: {t2.device}')
Tensor Attributes and Mathematical Operations
Every PyTorch tensor is defined by its metadata: shape, dtype, and device. Understanding these attributes is critical for debugging tensor mismatch errors during model training. The shape property defines the dimensionality, while the dtype controls numerical precision, such as float32, float64, or int64.
PyTorch distinguishes between element-wise operations and algebraic matrix products. While element-wise multiplication (*) performs a Hadamard product, matrix multiplication is handled via the torch.matmul() function or the @ operator. Choosing the wrong operation is a common source of runtime errors in deep learning layers.
import torch a = torch.tensor([[1, 2], [3, 4]]) b = torch.tensor([[5, 6], [7, 8]]) # Element-wise product (Hadamard) element_wise = a * b # Matrix product (Dot product) matrix_product = a @ b print(f'Element-wise:\n{element_wise}') print(f'Matrix Multiply:\n{matrix_product}')
Device Management and Hardware Acceleration
PyTorch enables seamless migration of computations between CPUs, GPUs (CUDA), and Mac MPS devices using the .to() method or specific device-aware constructors. Properly managing device placement is essential for training large models, as data movement between host memory and device memory can be a significant bottleneck.
It is best practice to write device-agnostic code by checking torch.cuda.is_available() or torch.backends.mps.is_available(). This ensures that your research code runs on any machine, regardless of the available hardware backend.
device = 'cuda' if torch.cuda.is_available() else 'cpu' tensor = torch.rand(3, 3) # Move tensor to device tensor = tensor.to(device) # Perform operation on device result = tensor @ tensor.T print(f'Result device: {result.device}')
Knowledge Check
Ready to test your understanding of 1. Foundations of PyTorch?