Stanford CS231N Deep Learning for Computer Vision I 2025 - YouTube
This course provides a definitive, end-to-end journey into the principles and practice of deep learning for computer vision. The course builds from the ground up, starting with the foundational challenge of image classification and the limitations of simple linear classifiers. It then constructs the core machinery of modern AI, detailing the architecture of neural networks, the mathematics of optimization (SGD, Adam), and the pivotal backpropagation algorithm that enables learning. The curriculum dedicates significant time to Convolutional Neural Networks (CNNs), tracing their evolution from foundational architectures like VGGNet to the revolutionary ResNet with its critical skip connections.
With these tools established, the course expands its scope to a wide array of core vision tasks, including object detection, semantic and instance segmentation, video understanding, and 3D vision, covering both classic and modern algorithmic approaches from R-CNN to Transformers and NeRFs. The latter half of the course pivots to the state-of-the-art, exploring the paradigm shift towards training on massive, unlabeled datasets through self-supervised learning (e.g., contrastive methods, masked autoencoders). This sets the stage for a deep dive into generative modeling, tracing the evolution from Variational Autoencoders (VAEs) and Generative Adversarial Networks (GANs) to the dominant paradigm of Diffusion Models. The architectural focus then shifts to the attention mechanism and the Transformer, the highly parallelizable and scalable architecture that now underpins not only vision but the entire field of AI.
The final lectures synthesize these concepts into the modern paradigm of multimodal foundation models (e.g., CLIP, LLaVA), which integrate vision and language, and address the massive systems challenge of large-scale distributed training. The course culminates by exploring the application of these powerful models in the physical world through robot learning and concludes with a critical discussion on human-centered AI, examining the ethical implications and societal impact of the technology. Ultimately, CS231n equips students not just with the technical skills to build vision systems, but with a deep, historical, and principled understanding of the field's past, present, and future.
L1: Introduction
The course is introduced by Professor Fei-Fei Li, who will be co-teaching with Professor Ehsan Adeli and graduate student Zane.
- Positioning the Course: Professor Li positions Computer Vision as a cornerstone of Artificial Intelligence (AI). She outlines the course's scope as the intersection of Computer Vision and Deep Learning, a subfield of Machine Learning that utilizes Neural Networks. The course will explore the technical core of this intersection, acknowledging its connections to other fields like NLP, robotics, neuroscience, and various application areas from medicine to business.
- Lecture Plan: The lecture will begin with a brief history of computer vision and deep learning, followed by a course overview from Professor Adeli.
Part 1: A Brief History of Computer Vision (Presented by Fei-Fei Li)
The history is framed as a long evolutionary and intellectual journey to understand and replicate sight.
- The Evolutionary Beginning (540 Million Years Ago): The lecture starts with the Cambrian Explosion, a period of rapid animal speciation. A leading theory attributes this explosion to the evolution of the first eyes. Vision transformed life from passive metabolism into an active, intelligent process of navigating an environment, finding food, and avoiding predators. Vision, she argues, is the primary driver behind the evolution of the nervous system and intelligence itself.
- Early Human Innovations: The lecture touches on early human attempts to understand and manipulate images, from ancient Greek and Chinese philosophers studying pinhole cameras to Leonardo da Vinci's work on the camera obscura.
- The Neuroscience Foundation (1950s): The modern scientific study of vision began with the seminal work of Hubel and Wiesel, who won a Nobel Prize for their experiments on the visual cortex of cats. Their key discoveries were:
- Neurons in the primary visual cortex respond to simple, oriented edges within specific receptive fields.
- The visual pathway is hierarchical: neurons in deeper layers of the brain respond to increasingly complex patterns by combining the inputs from simpler ones. This hierarchical structure would become a core inspiration for neural network architectures.
- The Birth of Computer Vision as a Field (1960s-1970s):
- 1963: Larry Roberts' PhD thesis on understanding 3D shapes from 2D images is considered the first in the field.
- 1966: An MIT summer project famously (and optimistically) aimed to "solve vision."
- 1970s: David Marr's influential book proposed a systematic pipeline for vision, moving from a "primal sketch" (edges) to a "2.5D sketch" (surfaces and depth) and finally to a full 3D model. This highlighted the core, ill-posed problem of vision: recovering a 3D world from 2D projections.
- The AI Winter and Continued Progress (1980s-1990s): While the broader AI field entered a "winter" due to unfulfilled promises, foundational research continued. Cognitive science revealed the importance of context in object recognition and the incredible speed of human visual processing (categorization within 150ms). This research pointed towards a crucial North Star for the field: object recognition in natural scenes. Early successes included face detection algorithms that were eventually integrated into consumer digital cameras.
- The Deep Learning Thread (Parallel History):
- 1980s-1990s: While computer vision focused on features and geometry, a parallel track of research was developing neural networks. Key milestones included Fukushima's Neocognitron (a hand-designed, hierarchical network inspired by the visual cortex) and the invention of the backpropagation learning algorithm by Rumelhart and Hinton, which was a watershed moment. Yann LeCun applied this to create a convolutional neural network (CNN) that could recognize handwritten digits for banks and postal services.
- The Inflection Point (2000s-2012): The field realized that a major bottleneck was the lack of large-scale data.
- ImageNet: To address this, Professor Li's team created ImageNet, a massive dataset of millions of labeled images. They launched the ImageNet Large Scale Visual Recognition Challenge (ILSVRC).
- 2012: The "AlexNet" moment. A deep convolutional neural network, created by Jeff Hinton and his students, dramatically outperformed all other approaches in the ILSVRC, cutting the error rate nearly in half. This event is widely considered the "Big Bang" of the modern deep learning revolution, demonstrating the power of combining deep neural networks, the backpropagation algorithm, large datasets, and powerful GPU hardware.
- The Modern Era (Post-2012): The AlexNet breakthrough triggered an explosion of progress. The field rapidly developed models for more complex tasks beyond classification, including object detection, image segmentation, video understanding, medical imaging, and generative AI (style transfer, DALL-E). The lecture concludes by acknowledging that while progress has been immense, vision is not "solved," and the field faces significant challenges, particularly regarding the societal impact of AI, such as inherited biases and ethical applications.
Part 2: Course Overview (Presented by Ehsan Adeli)
Professor Adeli outlines the structure and content of the course, which is divided into four main topics.
- Deep Learning Basics: The course begins with the fundamentals.
- Starting with image classification as the core task.
- Moving from simple linear classifiers to the need for non-linear models.
- Covering foundational concepts like overfitting/underfitting, regularization, and optimization.
- A deep dive into neural networks, how they are built, trained, and debugged.
- Perceiving and Understanding the Visual World: This section covers core computer vision tasks and the models used to solve them.
- Tasks: Moving beyond classification to semantic segmentation (labeling every pixel), object detection (locating objects with bounding boxes), and instance segmentation (identifying individual object instances). It also covers tasks involving time, such as video classification and multimodal understanding.
- Models: The focus will be on Convolutional Neural Networks (CNNs), but the course will also cover Recurrent Neural Networks (RNNs) and modern architectures like Transformers and attention.
- Generative and Interactive Visual Intelligence: This unit explores more advanced and recent topics.
- Self-Supervised Learning: Learning representations from vast amounts of unlabeled data.
- Generative Models: Creating new visual content, including style transfer and diffusion models. Students will implement a text-to-emoji generator.
- Vision-Language Models: Connecting images and text for tasks like image captioning and retrieval.
- 3D Vision and Embodied AI (robotics).
- Human-Centered Applications and Implications: The final part of the course will address the broader societal impact of the technology, building on the themes introduced by Professor Li. The course will conclude by looking ahead at the next topics: image classification and linear classifiers.
L2: Image Classification with Linear Classifiers
The lecture begins by recapping the course structure and sets the agenda: to formally define the image classification task and introduce two foundational data-driven approaches: the k-Nearest Neighbor (k-NN) algorithm and Linear Classifiers.
Part 1: The Image Classification Problem
The core task is to assign a single, predefined label (e.g., "cat," "dog") to an input image.
- The Semantic Gap: The fundamental challenge is the "semantic gap." To a human, an image of a cat is a holistic concept. To a computer, it is merely a large tensor of pixel values (e.g., an 800x600 RGB image is an 800 x 600 x 3 tensor of numbers from 0 to 255).
- Challenges of Visual Recognition: The lecture highlights the immense difficulty of this task by outlining several key challenges that drastically change the pixel values while leaving the semantic content unchanged:
- Viewpoint Variation: Changing the camera angle changes every pixel value.
- Illumination: The same object appears differently under different lighting.
- Background Clutter: The object of interest may be surrounded by distracting elements.
- Occlusion: The object may be partially hidden.
- Deformation: Objects like cats are not rigid and can appear in many shapes.
- Intra-class Variation: There is huge diversity within a single category (e.g., many different breeds, colors, and sizes of "cat").
Part 2: The Data-Driven Approach
Instead of trying to hard-code a set of rules to identify objects, the modern approach is data-driven, following a three-step pipeline:
- Collect Data: Gather a large dataset of images with their corresponding labels.
- Train a Classifier: Use a machine learning algorithm to learn a model that maps images to labels from the training data.
- Evaluate: Test the trained model on a new, unseen set of images to assess its performance.
Part 3: The k-Nearest Neighbor (k-NN) Classifier
This section introduces the first, and simplest, data-driven classifier.
- The Algorithm:
- Training: The train function is trivial—it simply memorizes the entire training dataset.
- Prediction: The predict function takes a new test image, compares it to every single image in the training set to find the most similar one(s), and assigns the label of the "nearest neighbor."
- Distance Metrics: To measure similarity, a distance function is needed. Two are introduced:
- L1 Distance (Manhattan Distance): The sum of absolute differences between pixel values. It is sensitive to the coordinate axes (features).
- L2 Distance (Euclidean Distance): The square root of the sum of squared differences. It is rotationally invariant and smoother.
- Computational Complexity: The major drawback of k-NN is highlighted. Training is instantaneous (O(1)), but prediction is extremely slow (O(N) for N training images), making it impractical for large-scale applications. The ideal classifier has a slow training phase and a fast prediction phase.
- From 1-NN to k-NN: To make the classifier more robust to outliers and noisy data, instead of finding just one nearest neighbor, it finds the k nearest neighbors and uses a majority vote to determine the label.
- Hyperparameters: k-NN introduces the concept of hyperparameters: choices about the algorithm's structure that are not learned from the data (in this case, the value of k and the choice of distance metric).
Part 4: Hyperparameter Tuning
This section covers the crucial process of selecting the best hyperparameters for a given problem.
- The Wrong Approaches:
- Tuning on the Training Set: This is a bad idea because it leads to overfitting (e.g., for k-NN, k=1 will always give 100% accuracy on the training data).
- Tuning on the Test Set: This is "cheating" because the model will be overly optimistic about its performance on new, unseen data. The test set should only be used once at the very end.
- The Right Approach:
- Validation Set: The training data is split into a training set and a smaller validation set. The model is trained on the training portion, and different hyperparameters are evaluated on the validation set.
- Cross-Validation: For smaller datasets, a more robust method is cross-validation. The training data is split into multiple "folds," and the process is repeated, with each fold serving as the validation set once. The results are then averaged to find the best hyperparameters.
Part 5: Linear Classifiers
The lecture then moves to the most important building block of modern deep learning: the linear classifier.
- The Parametric Approach: Unlike k-NN, a linear classifier is a parametric model. It learns a set of parameters (a weight matrix W and a bias vector b) that map an input image x to a set of class scores. The goal of training is to find the optimal W and b.
- Algebraic Viewpoint: The image is flattened into a single column vector x. The classification function is f(x, W, b) = Wx + b. If an image has D pixels and there are C classes, W is a C x D matrix and b is a C x 1 vector.
- Visual Viewpoint: Each row of the weight matrix W can be reshaped into an image, representing a learned template for each class.
- Geometric Viewpoint: In a high-dimensional feature space, the linear classifier learns a set of hyperplanes that separate the data points of different classes.
- The Loss Function: The core question becomes: how do we find the best W? We need a loss function (or objective function) that measures our "unhappiness" with the current set of parameters. The goal of training is to find the W that minimizes this loss.
- Softmax Classifier (Multinomial Logistic Regression):
- From Scores to Probabilities: The raw output scores from the linear function are uncalibrated. The softmax function is used to convert these scores into a valid probability distribution over the classes. This is done by exponentiating the scores (to make them positive) and then normalizing them to sum to 1.
- The Loss Function (Cross-Entropy Loss): The objective is to maximize the probability of the correct class. In a minimization framework, this is equivalent to minimizing the negative log-probability of the correct class. This loss function is also known as the cross-entropy loss, and its connection to information-theoretic concepts like KL-divergence is briefly explained.
The lecture concludes by noting that the next step is to figure out the optimization process—how to efficiently find the weights W that minimize this loss function, which will be the topic of the next session.
L3: Regularization and Optimization
The lecture begins with a recap of the previous session, reinforcing the core concepts of image classification.
- The Problem: The "semantic gap" between human perception and the computer's representation of an image as a grid of pixel values, compounded by challenges like illumination, deformation, occlusion, and intra-class variation.
- k-Nearest Neighbors (k-NN): A simple, data-driven approach where classification is based on the labels of the most similar images in the training set. This was used to introduce the concept of hyperparameter tuning using a train/validation/test split.
- Linear Classifiers: The foundational building block of neural networks. The lecture reviewed the algebraic, visual (templates), and geometric (decision boundaries) viewpoints of a linear classifier, which computes class scores via the function f(x, W, b) = Wx + b.
Part 1: Regularization
The first major topic is regularization, a technique to combat overfitting. The core idea is to intentionally make the model perform worse on the training data to help it generalize better to new, unseen test data.
- The Loss Function with Regularization: The total loss is defined as a sum of two components:
- Data Loss: Measures how well the model's predictions match the training labels (e.g., cross-entropy loss).
- Regularization Loss: A penalty term that depends only on the model's weights W, controlled by a hyperparameter λ (regularization strength).
- Occam's Razor: The intuition behind regularization is often linked to Occam's Razor: prefer simpler models. By penalizing complex or large weights, we encourage the model to find a simpler solution that is less likely to have memorized noise in the training data.
- Types of Regularization:
- L2 Regularization (Weight Decay): The penalty is the sum of the squared values of all weights. This encourages the model to use all of its weights but to keep them small and diffuse ("spread out").
- L1 Regularization: The penalty is the sum of the absolute values of all weights. This encourages sparsity, pushing many weights to become exactly zero and effectively performing feature selection.
Part 2: Optimization
With a loss function defined, the next step is optimization: the process of finding the set of weights W that minimizes the total loss.
- The Loss Landscape Analogy: Optimization is analogized to a blindfolded person trying to find the lowest point in a hilly landscape. The person can only feel the slope of the ground directly under their feet.
- Gradient Descent: The fundamental algorithm for optimization. It works by:
- Calculating the gradient of the loss function with respect to the weights. The gradient is a vector that points in the direction of the steepest ascent on the loss landscape.
- Taking a small step in the direction of the negative gradient (i.e., downhill).
- Repeating this process iteratively.
The size of the step is controlled by another hyperparameter: the learning rate or step size.
- Stochastic Gradient Descent (SGD): Calculating the gradient over the entire dataset is computationally expensive. SGD is a much more efficient variant where the gradient is estimated using only a small, random subset of the data called a minibatch.
Part 3: Challenges and Improvements in Optimization
This section covers the common problems with vanilla SGD and the advanced optimizers designed to solve them.
- Problems with SGD:
- Poor Conditioning: On loss landscapes shaped like long, narrow ravines, SGD tends to oscillate inefficiently across the steep walls instead of making progress along the flat valley floor.
- Local Minima and Saddle Points: SGD can get stuck in local minima or, more commonly in high dimensions, on saddle points where the gradient is zero.
- Noisy Gradients: The gradient estimate from a minibatch is noisy, causing the optimization path to zigzag.
- Solutions and Advanced Optimizers:
- SGD with Momentum: This method introduces a "velocity" term, which is a running average of past gradients. This helps the optimizer build speed in consistent directions (smoothing out noise and accelerating down ravines) and roll through small local minima and saddle points.
- RMSProp: This optimizer adapts the learning rate for each parameter individually. It keeps a running average of the squared gradients. Parameters with large gradients (steep directions) have their effective learning rate reduced, while parameters with small gradients (flat directions) have their learning rate increased. This helps dampen oscillations and speed up progress in flat regions.
- Adam (Adaptive Moment Estimation): The most popular and default optimizer in deep learning. It effectively combines the ideas of Momentum and RMSProp, keeping running averages of both the first moment (the gradient itself, like momentum) and the second moment (the squared gradient, like RMSProp). The lecture also touches on AdamW, a variant that decouples the L2 regularization (weight decay) from the moment calculations, which often performs better in practice.
Part 4: Learning Rate Schedules
The lecture concludes by discussing learning rate schedules, the practice of changing the learning rate during training.
- Motivation: A high learning rate is good for making rapid progress early in training, but a lower learning rate is needed later to fine-tune and settle into a good minimum.
- Common Schedules:
- Step Decay: Periodically dropping the learning rate by a fixed factor (e.g., by 10x every 30 epochs).
- Cosine Decay: A smooth schedule that follows half a cosine wave, starting high and gradually decreasing to zero.
- Linear Warmup: A very common practice where the learning rate starts low and linearly increases to its maximum value over the first few thousand iterations, which helps stabilize the beginning of training.
The lecture ends with a preview of the next topic: neural networks, which are built by stacking these linear classifiers together with non-linear activation functions in between.
L4: Neural Networks and Backpropagation
The lecture begins by positioning itself as a foundational session for the rest of the course. The topics of Neural Networks and Backpropagation are central to nearly all modern computer vision algorithms. The session starts with a recap of the previous lecture:
- The Goal: To build a classifier that maps an input image x to a set of class scores using a scoring function f(x, W).
- The Loss Function: A function L that quantifies how "unhappy" we are with the model's predictions. The total loss is a combination of a Data Loss (how well the model fits the training data) and a Regularization Loss (a penalty on the weights W to prevent overfitting).
- Optimization: The process of finding the weights W that minimize the total loss. The core algorithm is Gradient Descent, which iteratively takes small steps in the negative direction of the gradient ∇L. The lecture briefly reviewed Stochastic Gradient Descent (SGD) and more advanced optimizers like Adam.
Part 1: Neural Networks
This section introduces the concept of multi-layer neural networks as a way to overcome the limitations of linear classifiers.
- From Linear Classifiers to Neural Networks: A simple linear classifier is a single-layer network. A two-layer neural network is created by stacking two linear transformations, separated by a crucial component: a non-linear activation function.
- The Importance of Non-Linearity: The lecture emphasizes that without a non-linear activation function (like max(0, x)), a multi-layer network would mathematically collapse into a single, equivalent linear classifier, defeating the purpose of having multiple layers. Non-linearities allow the network to learn complex, non-linear decision boundaries.
- Activation Functions: A survey of common activation functions is provided:
- ReLU (Rectified Linear Unit): The most common and simple choice (max(0, x)).
- Leaky ReLU, ELU, GeLU, SiLU: Variants designed to address some of ReLU's limitations, such as "dead neurons."
- Sigmoid and Tanh: Older activation functions that are now used less frequently in hidden layers due to issues like "vanishing gradients," but are still useful in output layers.
- Capacity and Regularization: Adding more layers and more neurons per layer increases the model's capacity to learn complex functions. However, this also increases the risk of overfitting. The lecture makes a key practical point: it is generally better to use a slightly larger network and control overfitting with a strong regularization term (λ) than to use the network size itself as the primary regularizer.
Part 2: Backpropagation and Computational Graphs
The core of the lecture is a detailed, step-by-step explanation of backpropagation, the algorithm used to efficiently compute the gradients needed for optimization.
- The Challenge: Manually deriving the analytical gradient for a deep, complex neural network is tedious, error-prone, and becomes intractable as the network changes.
- The Solution - Computational Graphs: The first step is to represent the entire forward pass of the network—from inputs and weights to the final loss value—as a computational graph. Each node in the graph represents a basic mathematical operation (e.g., addition, multiplication, exp).
- Backpropagation as Chain Rule on a Graph: Backpropagation is an algorithm that applies the chain rule of calculus recursively on this graph. It works by:
- Performing a forward pass to compute the value at each node and the final loss.
- Starting at the final loss node (where the gradient of the loss with respect to itself is 1).
- Moving backward through the graph, node by node. At each node, it computes the downstream gradient (the gradient of the final loss with respect to the node's inputs) by multiplying the upstream gradient (the gradient from the next node in the graph) with the local gradient (the simple, pre-computed derivative of the node's own operation).
- Step-by-Step Examples: The lecture walks through two detailed examples to build intuition:
- A simple scalar function f = (x + y) * z, demonstrating how the chain rule propagates gradients backward through addition and multiplication gates.
- A more complex function representing a single neuron with a sigmoid activation, showing how a complex calculation can be broken down into a series of simple, modular gates, each with a known local gradient.
- Patterns in Gradients (Gradient Gates): The lecture highlights common patterns for different gates:
- Add Gate: Acts as a "gradient distributor," passing the upstream gradient equally to its inputs.
- Multiply Gate: Acts as a "gradient switcher," routing the upstream gradient multiplied by the other input's value.
- Max Gate: Acts as a "gradient router," passing the upstream gradient only to the input that had the maximum value during the forward pass.
Part 3: Backpropagation with Vectors and Matrices
The final section generalizes the concept from scalar values to the vectors and matrices used in real neural networks.
- Jacobians: When dealing with vector-to-vector functions, the local gradient is no longer a single number but a Jacobian matrix containing all the partial derivatives of each output element with respect to each input element.
- The Problem of Size: For matrix operations (e.g., matrix multiplication), the full Jacobian can be enormous (e.g., hundreds of gigabytes for a single layer), making it impossible to store or compute explicitly.
- The Solution - Efficient Vectorized Gradients: The lecture explains that we don't need to materialize the full Jacobian. By analyzing the structure of the operation (like a matrix multiply), we can derive a simple, efficient expression for the downstream gradient that is itself a matrix multiplication. For example, the gradient of the loss with respect to X in Y = XW involves multiplying the upstream gradient dY by W^T.
The lecture concludes by summarizing that backpropagation provides a modular and efficient way to compute gradients for any complex, differentiable function represented as a computational graph. This powerful algorithm is the engine that drives the learning process in virtually all deep neural networks, a topic that will be foundational for the upcoming lectures on convolutional neural networks.
L5: Image Classification with CNNs
The lecture begins with an introduction from a new instructor, Justin Johnson, and transitions into a recap of the first four lectures, framing them as the complete, foundational pipeline for any deep learning system.
- The Problem (Image Classification): Formulating a task in terms of tensor inputs (raw pixel values) and tensor outputs (class scores), using a linear classifier (f(x) = Wx + b) as the initial model.
- The Loss Function: Defining a way to measure how well a given set of weights W performs on a dataset. The lecture reviewed the softmax loss, a standard for classification.
- Optimization: The process of finding the optimal W that minimizes the loss. This is analogized to a blindfolded person navigating a "loss landscape." The core algorithm is gradient descent, with practical implementations like SGD with Momentum and Adam.
- From Linear Models to Neural Networks: The limitations of linear classifiers were highlighted—they can only learn a single "template" per class and can only solve linearly separable problems. This motivated the move to multi-layer neural networks, which stack linear layers with non-linear activation functions (like ReLU) in between.
- Backpropagation: The "magical" algorithm that makes training deep networks possible. It uses the chain rule on a computational graph to efficiently and automatically compute the gradients of the loss with respect to all model parameters, enabling optimization.
Part 1: Convolutional Neural Networks (CNNs) - A Better Architecture for Images
This section introduces CNNs as a specialized type of neural network designed to better handle the unique structure of images.
- The Problem with Fully Connected Networks for Images: The lecture points out a major flaw in applying standard multi-layer perceptrons (MLPs) to images: by flattening the image into a long vector, they destroy the inherent 2D spatial structure of the data.
- Feature Extraction vs. End-to-End Learning: The lecture contrasts two paradigms:
- Traditional Approach: A human expert hand-designs a feature extractor (e.g., color histograms, Histogram of Oriented Gradients) to convert the image into a meaningful feature vector, which is then fed into a simple learned classifier.
- Deep Learning Approach (End-to-End): The entire system, from raw pixels to final scores, is a single differentiable function (a neural network) whose parameters are all learned from data using gradient descent. The idea is that the network can learn a better feature representation than a human can design.
- The Convolutional Network Architecture: A typical CNN consists of a "body" of stacked convolutional and pooling layers that act as a learnable feature extractor, followed by a "head" of fully connected layers that perform the final classification based on these learned features. The lecture traces the history of this architecture from Yann LeCun's LeNet-5 (1998) to the revolutionary AlexNet (2012), which kicked off the deep learning boom by dominating the ImageNet challenge.
Part 2: The Convolution Layer
This is the core building block of a CNN and the main focus of the lecture.
- The Core Idea: Local Template Matching: The convolution layer replaces the global template matching of a fully connected layer with local template matching.
- Instead of a large filter the size of the entire image, a convolution layer uses a small, learnable filter or kernel (e.g., 5x5x3).
- This small filter is slid across every spatial location of the input image.
- At each location, a dot product is computed between the filter and the corresponding patch of the image. This dot product measures how well that local patch matches the template defined by the filter.
- The results of these dot products are collected into a 2D activation map or feature map.
- Multiple Filters: A single conv layer uses many different filters (e.g., 64 of them), each looking for a different local pattern. Each filter produces its own 2D activation map. These maps are then stacked together to form the output volume.
- Learned Filters: Crucially, the values within these filters are not hand-designed; they are parameters that are learned via backpropagation. Visualizations of the first layer of a trained AlexNet show that the network spontaneously learns to detect fundamental visual primitives like oriented edges and color blobs.
- Hyperparameters and Spatial Math: The lecture details the key hyperparameters of a conv layer:
- Kernel Size ( The spatial dimension of the filter (e.g., 3x3).
- Padding ( Adding zeros around the border of the input to control the output size. A common trick is to use padding to keep the spatial dimensions the same after the convolution.
- Stride ( The step size with which the filter is slid across the input. A stride greater than 1 results in downsampling.
- Receptive Field: The lecture explains that stacking conv layers causes the effective receptive field of neurons in deeper layers to grow. A neuron deep in the network is influenced by a larger region of the original input image. Using strided convolutions causes the receptive field to grow exponentially, allowing the network to aggregate global information efficiently.
Part 3: The Pooling Layer
The second key primitive for CNNs is the pooling layer.
- Concept: Cheap Downsampling: The primary function of a pooling layer is to downsample the spatial dimensions of the feature maps, making the representation smaller and more manageable. This also helps increase the receptive field of subsequent layers.
- Mechanism (Max Pooling): The most common form is max pooling. It works by dividing a feature map into non-overlapping tiles (e.g., 2x2) and taking the maximum value within each tile. It is a fixed, non-learned operation.
- Translation Equivariance: The lecture concludes by introducing a key mathematical property of both convolution and pooling: translation equivariance. This means that if you translate the input image, the output feature map is simply a translated version of the original output. This property bakes in the important prior knowledge that the identity of an object does not depend on its absolute position in the image, making CNNs inherently well-suited for visual tasks.
The lecture ends by setting the stage for the next session, which will explore how these convolutional and pooling layers are stitched together to form powerful CNN architectures.
L6: CNN Architectures
The lecture begins by positioning itself at an inflection point in the course, moving from the fundamentals of deep learning to more specialized topics in computer vision. It starts with a comprehensive recap of the core deep learning pipeline covered in previous lectures:
- The Problem: Formulating tasks like image classification in terms of tensor inputs and outputs.
- The Model: Using a function, like a linear classifier, to map inputs to outputs.
- The Loss Function: A mathematical way to measure how "bad" a model's predictions are.
- Optimization: The process of finding the model parameters that minimize the loss, typically using gradient descent and optimizers like Adam.
- Neural Networks: Overcoming the limitations of linear models by stacking layers with non-linear activations.
- Backpropagation: The core algorithm that enables efficient gradient computation for these complex models.
Part 1: How to Build CNNs - Architectures and Layers
This section focuses on the components and design principles of Convolutional Neural Networks (CNNs).
- Recap of Core CNN Layers:
- Convolution Layer: The fundamental building block. It uses small, learnable filters (or kernels) that act as local template matchers, sliding across the input image to produce activation maps.
- Pooling Layer: A simple, non-learned layer used for downsampling feature maps, most commonly through max pooling. This makes the representation more compact and increases the receptive field of subsequent layers.
- New Layers and Components:
- Normalization Layers (e.g., LayerNorm, BatchNorm): These layers are crucial for stabilizing training. They normalize the statistics (mean and standard deviation) of the activations within a layer. The key difference between variants like LayerNorm and BatchNorm is the set of activations over which these statistics are computed (per-sample for LayerNorm, across the batch for BatchNorm).
- Dropout: A powerful regularization technique. During training, it randomly sets a fraction of neuron activations to zero in each forward pass. This forces the network to learn more robust and redundant features, preventing it from becoming overly reliant on any single feature. During testing, dropout is turned off, and the activations are scaled to account for the fact that all neurons are now active.
- Activation Functions Revisited: The lecture reiterates the importance of non-linearities and surveys modern choices. While historical functions like Sigmoid suffer from vanishing gradients, ReLU became the standard for its simplicity and efficiency. More recently, smoother functions like GELU (used in Transformers) and SiLU (or Swish) have become popular for their improved performance.
- Classic CNN Architectures:
- VGGNet: A simple and influential architecture characterized by stacking multiple 3x3 convolution layers between pooling layers. The lecture explains that a stack of small 3x3 filters has the same receptive field as a single larger filter (e.g., 7x7) but is more computationally efficient and has more non-linearities, making it more expressive.
- ResNet (Residual Network): A revolutionary architecture that enabled the training of extremely deep networks (100+ layers). It solved the "degradation" problem (where deeper networks performed worse than shallower ones) by introducing residual connections or skip connections. These connections allow the network to easily learn an identity mapping by simply passing the input x around a block of layers and adding it to the output, so the block only needs to learn the "residual" F(x).
Part 2: How to Train CNNs - Practical Steps and Tricks
This section shifts from architecture design to the practical process of training a model effectively.
- Data Pre-processing: The standard first step is to normalize the input images by subtracting the mean and dividing by the standard deviation of the entire dataset, calculated on a per-channel (R, G, B) basis.
- Data Augmentation: A critical regularization technique. During training, random transformations are applied to each image to create new, plausible training examples. This makes it harder for the model to overfit and improves its generalization. Common augmentations include:
- Horizontal flipping
- Random resized cropping
- Color jittering (adjusting brightness, contrast, etc.)
- Transfer Learning: A cornerstone of modern computer vision practice, especially for smaller datasets.
- Concept: Instead of training a model from scratch, start with a model that has been pre-trained on a massive dataset like ImageNet.
- Methods:
- Feature Extractor: Freeze the pre-trained convolutional layers and only train a new, small classifier head on top. This is effective for very small or similar datasets.
- Fine-tuning: Initialize the entire network with the pre-trained weights but allow all layers to be updated during training on the new dataset, typically with a smaller learning rate. This is the most common and effective approach.
- Hyperparameter Tuning: The lecture concludes with a practical guide to finding good hyperparameters.
- Sanity Check: The most important debugging step is to first try to overfit on a tiny subset of the data (e.g., one or a few examples). If the model can't achieve zero loss on this small sample, there is likely a bug in the code.
- Search Strategy: Use random search over a defined range of hyperparameters rather than a grid search. Random search is more efficient at exploring the parameter space, especially when some hyperparameters are more important than others.
- Monitoring: Track both training and validation accuracy/loss curves. A large gap between them indicates overfitting, which can be addressed with more data or stronger regularization. If both are still improving, the model can likely benefit from more training.
L7: Recurrent Neural Networks
The lecture begins with a few clarifications from the previous session:
- Dropout Scaling: A clarification on dropout: during inference, activations are scaled by the probability of keeping a neuron, not dropping one, to maintain the same expected output magnitude as during training.
- Normalization and Initialization: An empirical demonstration showed that while a normalization layer (like LayerNorm) can help stabilize a poorly initialized network, it does not fully close the performance gap. Optimal performance still requires proper weight initialization (e.g., Kaiming initialization).
The lecture then introduces its main topic: sequence modeling, focusing on Recurrent Neural Networks (RNNs) as a foundational architecture before the era of Transformers.
Part 1: Sequence Modeling and Recurrent Neural Networks (RNNs)
This section defines the task of sequence modeling and introduces the core concepts of RNNs.
- Defining Sequence Tasks: The lecture categorizes sequence modeling problems:
- One-to-many: One fixed-size input to a variable-length output (e.g., image captioning).
- Many-to-one: A variable-length input to a fixed-size output (e.g., video classification).
- Many-to-many: A variable-length input to a variable-length output (e.g., video captioning or frame-level classification).
- The Core Idea of RNNs: The key feature of an RNN is its recurrent nature. It maintains an internal hidden state ( that is updated at each time step. The new hidden state (h_t) is a function of the current input (x_t) and the previous hidden state (h_{t-1}). This allows the network to maintain a "memory" of past information in the sequence.
- The RNN Formula: The basic "vanilla" RNN is defined by a simple recurrence relation: h_t = f_W(h_{t-1}, x_t), where f_W is a function (typically a tanh activation applied to a linear transformation) with a shared set of weights W that is applied at every time step. A separate weight matrix is used to produce an output y_t from the hidden state h_t.
- A Hand-Crafted Example: To build intuition, the lecture walks through a toy problem: detecting two consecutive '1's in a binary sequence. The instructor manually designs the weight matrices and hidden state representation for a simple RNN to solve this task, illustrating step-by-step how the hidden state tracks necessary information (the current and previous inputs) through the sequence.
Part 2: Training RNNs - Backpropagation Through Time (BPTT)
This section explains how RNNs are trained.
- The Challenge: Since the weights W are shared across all time steps, the gradient for W at any given time step depends on its influence at all previous time steps. A change in W at t=1 affects h_1, which in turn affects h_2, and so on, creating a long chain of dependencies.
- Backpropagation Through Time (BPTT): BPTT is the algorithm for computing gradients in an RNN. It involves "unrolling" the recurrent network through time into a deep, feed-forward-like computational graph and then applying standard backpropagation. The final gradient for the shared weights W is the sum of the gradients computed at each time step.
- Truncated BPTT: For very long sequences, unrolling the entire graph is computationally infeasible due to memory constraints. Truncated BPTT is the practical solution. It breaks the sequence into smaller, manageable chunks, performs BPTT within each chunk, and passes the final hidden state (but not the gradient) from one chunk to the next.
Part 3: Challenges of RNNs and the Rise of LSTMs
This section details the fundamental problems that made vanilla RNNs difficult to train and motivated more complex architectures.
- The Vanishing/Exploding Gradient Problem: The core issue with training RNNs on long sequences. During BPTT, the gradient is repeatedly multiplied by the same weight matrix W_hh at each step.
- If the singular values of W_hh are large, the gradient will grow exponentially, leading to an exploding gradient. This can be managed with gradient clipping.
- If the singular values are small (or the tanh activation saturates), the gradient will shrink exponentially towards zero, leading to a vanishing gradient. This is the more severe problem, as it prevents the model from learning long-range dependencies.
- LSTMs (Long Short-Term Memory): The most popular and successful variant of RNNs, designed specifically to combat the vanishing gradient problem.
- The Core Idea: LSTMs introduce a separate cell state ( that acts as an "information highway." This cell state has a direct, additive connection from one time step to the next, with minimal interference from non-linear activations.
- Gating Mechanisms: The flow of information into, out of, and within this cell state is controlled by three learnable gates:
- Forget Gate: Decides what information from the previous cell state should be discarded.
- Input Gate: Decides what new information from the current input should be added to the cell state.
- Output Gate: Decides what part of the cell state should be exposed to the hidden state and used for the final output.
- Analogy to ResNets: The additive nature of the LSTM's cell state is conceptually similar to the skip connections in ResNets, both providing a more direct path for gradients to flow through deep architectures (or long time sequences).
Part 4: Applications and the Modern Resurgence of RNN-like Models
- Classic Applications: The lecture showcases how RNNs (and LSTMs) were the workhorses for many vision-language tasks before Transformers, including image captioning, visual question answering (VQA), and visual dialogue. A character-level language model trained on Shakespeare is used to demonstrate their generative capabilities.
- The Modern Era (State-Space Models): The lecture concludes by noting a recent resurgence of RNN-like ideas in the form of State-Space Models (SSMs) like Mamba. These modern architectures retain the key advantages of RNNs—linear-time complexity and an unlimited context length—while using more sophisticated mathematical formulations to overcome the training difficulties of traditional RNNs, making them highly competitive with Transformers, especially for long-sequence tasks.
The lecture ends by setting the stage for the next session, which will cover the Transformer architecture itself.
L8: Attention and Transformers
The lecture begins by recapping the previous session on Recurrent Neural Networks (RNNs), which introduced architectures for processing variable-length sequences. This capability opened up new problem domains beyond the fixed-size inputs of CNNs, such as image captioning (one-to-many) and video classification (many-to-one).
Today's lecture will build on this foundation to introduce two pivotal concepts:
- Attention: A powerful neural network primitive that operates on sets of vectors.
- The Transformer: A revolutionary neural network architecture built around attention, which has become the dominant architecture for nearly all state-of-the-art deep learning applications today.
The lecture follows the historical development of these ideas, starting with the problems in RNNs that motivated the invention of attention.
Part 1: The Bottleneck in Sequence-to-Sequence RNNs
The lecture uses machine translation (e.g., English to Italian) as a motivating example for sequence-to-sequence (seq2seq) models.
- The Encoder-Decoder Architecture: A standard seq2seq RNN consists of two parts:
- An encoder RNN that reads the entire input sequence (e.g., "we see the sky") and compresses its meaning into a single, fixed-length context vector (.
- A decoder RNN that takes this context vector C and generates the output sequence one token at a time.
- The Information Bottleneck: The critical flaw in this design is that the entire meaning of the input sequence, regardless of its length, must be squeezed into that single, fixed-length context vector C. This creates an information bottleneck, making it impossible for the model to handle long sequences like paragraphs or books effectively.
Part 2: The Attention Mechanism
Attention was developed to solve this bottleneck. The core idea is to allow the decoder to look back at the entire input sequence at every step of its generation process.
- How Attention Works in an RNN:
- At each step, the decoder's current hidden state (s_t) is used as a query.
- This query is compared to the hidden states of all tokens in the encoder sequence (h_i), which act as data vectors. This comparison produces a set of alignment scores.
- A softmax is applied to these scores to create a probability distribution, or attention weights, over the input tokens. These weights indicate which parts of the input sequence are most relevant for generating the current output token.
- A new, dynamic context vector ( is computed as a weighted sum of all the encoder hidden states, using the attention weights.
- This new context vector is then used by the decoder to generate the next output token and update its hidden state.
- Interpretability: A key benefit of attention is its interpretability. By visualizing the attention weights, we can see which input words the model "attended to" when generating a specific output word, revealing how it learned alignments between languages.
Part 3: Generalizing Attention as a Standalone Operator
The lecture then abstracts the attention mechanism away from the RNN, defining it as a general and powerful computational primitive.
- The QKV (Query, Key, Value) Framework: The generalized attention mechanism is defined in terms of three components:
- Queries (Q): A set of vectors representing what you are "looking for."
- Keys (K): A set of vectors derived from the source data, used for comparison with the queries.
- Values (V): A set of vectors also derived from the source data, which are aggregated to form the output.
- The Attention Operation: The process is:
- Compute similarity scores between all queries and all keys, typically using a scaled dot product ((Q * K^T) / √d_k). The scaling factor is crucial for stabilizing gradients.
- Apply a softmax to the scores to get attention weights.
- Compute the output as a weighted sum of the Values, using the attention weights.
This entire operation can be implemented efficiently with a few matrix multiplications.
- Cross-Attention vs. Self-Attention:
- Cross-Attention: The queries come from one source, and the keys/values come from another (as in the RNN seq2seq example).
- Self-Attention: The queries, keys, and values are all derived from the same input sequence via different linear projections. This allows every element in a sequence to interact with every other element, creating a rich, context-aware representation.
Part 4: The Transformer Architecture
The Transformer is a neural network architecture that completely discards recurrence and convolution, relying almost entirely on self-attention.
- The Transformer Block: The core building block of a Transformer consists of:
- A multi-head self-attention layer (running multiple attention mechanisms in parallel).
- A feed-forward network (FFN) or MLP that processes each token's representation independently.
- Residual connections and layer normalization are used around both sub-layers for stable training, just like in ResNets.
- Stacking Blocks: A full Transformer is simply a stack of these blocks. While the original 2017 Transformer had around 12 blocks, modern models can have hundreds of blocks and trillions of parameters, demonstrating the architecture's incredible scalability.
- Permutation Equivariance: A key property of self-attention is that it is permutation equivariant. It treats the input as an unordered set of vectors, not a sequence. To provide positional information, explicit positional embeddings are added to the input vectors.
- Parallelizability: The biggest advantage of the Transformer over RNNs is its high parallelizability. Because there are no sequential dependencies within a sequence, all computations can be performed in parallel across the sequence dimension, making it extremely efficient to train on modern hardware like GPUs.
The lecture concludes by positioning the Transformer as the dominant, state-of-the-art architecture used across virtually all of deep learning today, thanks to its scalability, power, and efficiency. The next lecture will explore how to apply these powerful architectures to new computer vision tasks.
L9: Object Detention, Image Segmentation, Visualizing
The lecture begins by positioning itself as the bridge between the foundational concepts of neural networks and their practical application in building and training state-of-the-art Convolutional Neural Networks (CNNs). It starts with a recap of key topics from previous lectures:
- Linear Classifiers: The basic building block, mapping image pixels to class scores.
- Loss Functions: How to measure a model's performance (e.g., Softmax, Hinge Loss).
- Optimization: The process of finding the best model weights using Gradient Descent, with a focus on practical implementations like Stochastic Gradient Descent (SGD) and advanced optimizers like Adam.
- Neural Networks and Backpropagation: Stacking linear layers with non-linear activations to create more powerful models, and using backpropagation on a computational graph to efficiently compute gradients for training.
Part 1: Building CNNs - Layers and Architectures
This section details the specific layers used to construct CNNs and explores classic architectural patterns.
- Core CNN Layers (Recap):
- Convolution Layer: The workhorse of CNNs, which uses small, learnable filters to perform local template matching across the input image, producing activation maps.
- Pooling Layer: A simple, non-learned layer for downsampling feature maps (e.g., max pooling), which makes the representation more compact and increases the receptive field.
- Additional Key Layers:
- Normalization Layers (LayerNorm, BatchNorm): Crucial for stabilizing the training of deep networks. They normalize the statistics (mean and standard deviation) of the activations within a layer to prevent them from exploding or vanishing. The key difference between variants is the set of activations over which these statistics are computed.
- Dropout: A powerful regularization technique. During training, it randomly sets a fraction of neuron activations to zero, forcing the network to learn more robust and redundant features. It is turned off during testing.
- Classic CNN Architectures: The lecture walks through the evolution of influential CNN architectures.
- VGGNet: A simple yet effective architecture characterized by stacking multiple small 3x3 convolution layers between pooling layers. A key insight from VGG is that a stack of small filters is more computationally efficient and expressive than a single large filter with the same receptive field.
- ResNet (Residual Network): A revolutionary architecture that enabled the training of extremely deep networks (100+ layers). It solved the "degradation" problem (where deeper networks performed worse than shallower ones) by introducing residual or skip connections. These connections allow the network to easily learn an identity mapping, making optimization much easier and enabling the successful training of very deep models.
- Weight Initialization (Kaiming Initialization): A crucial step for successful training. The lecture explains that improper initialization can cause activations to either vanish to zero or explode to infinity as they propagate through the network. Kaiming Initialization is presented as the standard, principled method that scales the initial random weights based on the layer's input dimensions to ensure that activations maintain a stable variance throughout the network.
Part 2: Training CNNs - Practical Tricks of the Trade
This section moves from architectural design to the practical process of training a model effectively.
- Data Pre-processing: The standard first step is to normalize input images by subtracting the mean and dividing by the standard deviation of the training dataset, calculated on a per-channel (R, G, B) basis.
- Data Augmentation: A critical regularization technique to prevent overfitting. During training, random transformations (e.g., horizontal flipping, random resized cropping, color jittering) are applied to each image to create new, plausible training examples.
- Transfer Learning: The most important practical technique, especially when working with smaller datasets.
- Concept: Instead of training a model from scratch, start with a model that has been pre-trained on a massive dataset like ImageNet.
- Methods:
- Feature Extractor: Freeze the pre-trained convolutional layers and only train a new classifier head on top.
- Fine-tuning: Initialize the entire network with pre-trained weights but allow all layers to be updated during training on the new dataset, typically with a smaller learning rate. This is the most common and effective approach.
Part 3: From Classification to Detection and Segmentation
The lecture expands from the core task of image classification to more complex Computer Vision problems.
- Semantic Segmentation: The task of assigning a class label to every pixel in an image. The lecture introduces Fully Convolutional Networks (FCNs), which use an encoder-decoder structure to produce a full-resolution segmentation map. Key concepts like upsampling (e.g., transposed convolution) and the influential U-Net architecture (which uses skip connections between the encoder and decoder to preserve spatial detail) are explained.
- Object Detection: The task of locating objects with bounding boxes and assigning them a class label. The lecture traces the evolution of object detectors:
- Two-Stage Detectors (R-CNN, Fast R-CNN): These methods first use a Region Proposal Network (RPN) to identify candidate object locations and then run a classifier on each proposed region.
- Single-Stage Detectors (YOLO): A much faster approach that predicts all bounding boxes and class probabilities in a single pass over the image.
- Transformers for Detection (DETR): A modern approach that frames object detection as a direct set prediction problem, using a transformer encoder-decoder architecture with learnable "object queries."
- Instance Segmentation: The most granular task, which combines detection and segmentation to provide a unique pixel mask for each individual object instance. This is often solved by extending an object detector (like R-CNN) with an additional branch that predicts a mask for each detected box, as in Mask R-CNN.
Part 4: Visualization and Understanding
The final section covers techniques for interpreting what a trained CNN has learned.
- Saliency Maps: To understand which pixels in an input image were most important for a particular classification, one can compute the gradient of the class score with respect to the input pixel values. High-gradient pixels are the most "salient."
- Class Activation Mapping (CAM & Grad-CAM): These methods produce a heatmap that highlights the regions in an image that a CNN "looked at" to make a decision. Grad-CAM is a more general and widely used technique that uses gradients to determine the importance of different feature map channels, allowing for visualization of any layer in the network.
- Attention in Vision Transformers (ViTs): The lecture notes that for transformers, visualization is more straightforward. The attention maps learned by the self-attention layers inherently provide a way to see which parts of the image are attending to which other parts.
The lecture concludes by setting the stage for the next session, which will cover video understanding.
L10: Video Understanding
The lecture, delivered by guest speaker Dr. Ruohan Gao, begins by transitioning from the course's focus on 2D image understanding to the more complex domain of video understanding. While students are now familiar with tasks like image classification, object detection, and segmentation on static images, video introduces a crucial new dimension: time.
- What is a Video? A video is framed as a 4D tensor (T x C x H x W), essentially a volume of image frames stacked along a temporal axis (T).
- The Core Task (Video Classification): Similar to image classification, the goal is to assign a single label to a video clip, but the labels are typically actions (e.g., "running," "swimming," "jumping") rather than objects.
- The Challenge of Scale: Videos are enormous. A single minute of high-definition video can be over 10 GB. This poses significant challenges for storage, memory, and computation. The practical solution is to work with smaller, downsampled clips (e.g., 16 frames at a low spatial resolution). For longer videos, a common strategy is to train a classifier on short clips and then, at test time, average its predictions over multiple sampled clips from the long video.
Part 1: Architectures for Video Understanding
This section explores different architectural approaches for extracting features from video clips.
- Single-Frame CNN: The simplest baseline. Treat each frame of a video as an independent image, run a standard 2D CNN (image classifier) on each, and then average the predictions. This often works surprisingly well, especially for actions with little temporal variation.
- Fusion Strategies: These methods aim to combine information across frames.
- Late Fusion: Run a 2D CNN on each frame independently to extract feature vectors. Then, at a very "late" stage, aggregate these feature vectors across time, either by concatenating them or, more efficiently, by using a temporal pooling operation (e.g., max or average pooling). The main drawback is that important low-level motion cues may be lost by the time the features are fused.
- Early Fusion: The opposite approach. Stack the input frames along the channel dimension at the very "early" stage, and use a single, wide 2D convolution in the first layer to collapse all temporal information at once. The rest of the network is a standard 2D CNN. This is computationally cheap but may be too aggressive in collapsing temporal information.
- Slow Fusion (3D CNNs): The most principled approach. It replaces 2D convolutions and pooling with their 3D counterparts. The filters are now 3D kernels (e.g., 3x3x3) that slide through the video volume in both space and time. This allows the network to gradually and hierarchically learn spatio-temporal features. A key advantage is that it learns temporal shift-invariant features, meaning it can recognize a motion pattern regardless of when it occurs in the clip.
- Two-Stream Networks (Appearance + Motion): This approach is motivated by the observation that human perception is highly sensitive to motion.
- The Idea: Decompose the video into two separate streams:
- Appearance Stream: A standard 2D CNN that processes individual RGB frames.
- Motion Stream: A separate 2D CNN that operates on optical flow fields, which explicitly represent the pixel-wise motion between adjacent frames.
- The predictions from both streams are fused at the end. This method often outperforms single-stream models because optical flow provides a very strong, explicit signal for action recognition.
- The Idea: Decompose the video into two separate streams:
Part 2: Modeling Long-Term Temporal Structure
While CNNs are good at processing short clips, videos often have long-range dependencies.
- CNN + RNN/LSTM: A common strategy is to combine the strengths of both architectures. A 3D CNN is first used as a feature extractor to convert short video clips into a sequence of feature vectors. This sequence is then fed into an RNN or LSTM to model the long-term temporal relationships between the clips.
- Transformers and Self-Attention: The powerful self-attention mechanism can also be extended to video. Non-local Neural Networks introduced a "non-local block" that performs self-attention across both space and time within a feature map, allowing any point in the video volume to interact with any other point. Modern approaches like I3D (Inflated 3D ConvNets) start with a successful 2D CNN architecture (like ResNet) and "inflate" its kernels and weights into 3D, allowing for effective transfer learning from models pre-trained on ImageNet.
Part 3: Beyond Basic Classification - Multimodality and Efficiency
The lecture concludes by looking at more advanced topics and future directions in video understanding.
- Multimodality (Audio-Visual Learning): Real-world videos are not silent. The lecture highlights the importance of audio as another crucial modality. Combining visual and audio streams enables more complex tasks like visually-guided audio source separation (e.g., isolating a single person's voice from a crowd by looking at their face) and leads to more robust action recognition.
- Efficient Video Understanding: Processing every clip in a long video is prohibitively expensive. This has spurred research into efficiency, with methods that use a cheap modality (like audio) to predict "important moments" or learn a policy to dynamically decide which clips are worth processing with the expensive video model.
- Egocentric Video: The rise of wearable cameras (e.g., smart glasses) is creating a new frontier of egocentric video understanding, which involves processing first-person video and multi-channel audio to understand social interactions.
- Video Foundation Models: The final and most active area of research is connecting video to Large Language Models (LLMs) to create video foundation models that can answer questions about, describe, and reason over video content.
L11: Large Scale Distributed Training
The lecture begins by establishing that large-scale distributed training is no longer a niche topic but the standard for building state-of-the-art neural networks. While models were once trained on single GPUs, the norm today is to use thousands, or even tens of thousands, of devices concurrently. The lecture uses Llama 3 405B as a running example, not because it's necessarily the best model, but because Meta shared a rare and detailed technical report on its training process, providing a valuable window into how frontier models are built. This is contrasted with the secrecy of other top labs like OpenAI, whose GPT-4 paper famously disclosed no details about its architecture, hardware, or training methods.
Part 1: GPU Hardware and the Data Center as a Computer
This section provides a deep dive into the hardware that powers large-scale training, moving from a single GPU to the entire data center.
- Inside a Single GPU (e.g., NVIDIA H100): A modern GPU is a complex system with a distinct memory hierarchy:
- Slow, High-Capacity Memory: 80 GB of off-chip High-Bandwidth Memory (HBM).
- Fast, Low-Capacity Memory: 50 MB of on-chip L2 cache and even faster, smaller L1 caches/registers inside each compute core.
- The Compute Cores: The heart of the GPU is its ~132 Streaming Multiprocessors (SMs). Each SM contains:
- General-purpose FP32 cores for standard computation.
- Specialized Tensor Cores for matrix multiplication, which provide the vast majority (~16x more) of the device's throughput and operate in mixed precision (e.g., 16-bit inputs, 32-bit accumulation).
- The Exponential Growth of Compute: The lecture highlights the 1,000x increase in per-device compute over the last decade (from the K40 to the B200), driven primarily by the introduction and improvement of Tensor Cores. This exponential growth is the single biggest driver of progress in deep learning.
- The Data Center as One Giant Computer: The lecture zooms out to show how these individual GPUs are assembled into massive clusters. It details the communication hierarchy of the Llama 3 cluster:
- Single GPU: Very fast internal memory bandwidth (~3 TB/s).
- GPU Server: 8 GPUs connected with fast NVLink (~900 GB/s).
- GPU Pod: ~192 server racks (3,072 GPUs) connected via high-speed interconnects (~50 GB/s).
- Full GPU Cluster: 8 pods combined for a total of 24,576 GPUs.
The core mindset shift is to view this entire data center not as a collection of separate machines, but as a single, massively parallel supercomputer. The primary challenge is to write algorithms that can efficiently utilize all of its components despite the varying communication speeds.
Part 2: The Five Degrees of Parallelism
This section details the five main algorithmic strategies for splitting up the computation of a single neural network across thousands of GPUs. The goal is to keep all devices busy by overlapping communication with computation.
- Data Parallelism (DP):
- Concept: The simplest form. Each GPU holds a full copy of the model but processes a different slice of the data batch. After the backward pass, gradients are synchronized across all GPUs using an all_reduce operation.
- Problem (Memory): It's memory-inefficient because every GPU must store the entire model, its gradients, and the bulky optimizer states.
- Solution (FSDP - Fully Sharded Data Parallelism): To solve the memory issue, FSDP shards the model parameters, gradients, and optimizer states across the GPUs. During the forward/backward pass, each GPU fetches the parameters for the current layer on-demand from its peers, computes, and then discards them. This is made efficient by prefetching the next layer's weights while computing the current one.
- Pipeline Parallelism:
- Concept: The model is split by layers (depth-wise). GPU 0 computes layers 1-8, GPU 1 computes layers 9-16, and so on, passing activations sequentially.
- Problem (The "Bubble"): This is inherently inefficient, creating large bubbles of idle time where most GPUs are waiting.
- Solution: The bubble can be shrunk by splitting the batch into smaller "microbatches" and pipelining them through the stages concurrently.
- Tensor Parallelism:
- Concept: The model is split within layers by sharding the large weight matrices (width-wise). Each GPU computes a portion of a single matrix multiplication, and the results are synchronized.
- Use Case: It's extremely communication-intensive and is therefore almost exclusively used for the fastest, intra-node connections (e.g., across 8 GPUs in a single server).
- Context Parallelism (or Sequence Parallelism):
- Concept: Used for very long sequences. The sequence itself is sharded across GPUs. This is straightforward for most of the Transformer (MLPs, LayerNorm), but tricky for the attention mechanism, which requires all-to-all communication.
- Solutions: Specialized algorithms like Ring Attention or Ulysses Attention are used to parallelize the attention computation efficiently.
- Hybrid Sharded Data Parallelism (HSDP): A 2D approach that combines FSDP and DP, designed to map efficiently onto the data center's network topology. GPUs are arranged in a grid; FSDP is used along one axis (e.g., within a fast server), and standard DP is used along the other axis (e.g., across slower racks).
Part 3: Practical Scaling and the Guiding Light of MFU
- Activation Checkpointing: A memory-saving technique that is crucial for training large models. Instead of storing all activations during the forward pass (which consumes huge amounts of memory), they are discarded and recomputed on-the-fly during the backward pass, trading extra compute for memory.
- The Scaling Recipe: A practical, hierarchical recipe for scaling up is provided:
- Start with simple Data Parallelism for smaller models.
- As models grow, switch to FSDP to save memory.
- When activations become a bottleneck, enable Activation Checkpointing.
- At very large scales, switch to HSDP and introduce Pipeline/Tensor/Context Parallelism.
- The Guiding Metric (MFU - Model Flops Utilization): With so many complex knobs to tune, how do you know if your setup is efficient? The single most important metric is MFU. It measures what fraction of the hardware's theoretical peak FLOPs are actually being used for the model's forward and backward pass. An MFU above 30-40% is considered state-of-the-art for large-scale runs, and the goal of the systems engineer is to tune all the parallelism parameters to maximize this value.
The lecture concludes by emphasizing that modern large-scale training is a complex, multi-dimensional optimization problem that requires a deep understanding of both the algorithms and the underlying hardware to solve effectively.
L12: Self-Supervised Learning
The lecture begins by recapping the journey so far, emphasizing that while supervised learning on labeled data produces meaningful feature representations, the need for large-scale manual labeling is a major bottleneck. This sets the stage for the central question of the lecture: Can we train neural networks to learn good visual features without requiring huge, manually labeled datasets?
Part 1: The Concept of Self-Supervised Learning (SSL)
The lecture introduces Self-Supervised Learning as the paradigm that answers this question.
- The Core Idea: SSL leverages the inherent structure within the data itself to create supervisory signals. Instead of human-provided labels, the model is trained on a pretext task, for which the "labels" can be automatically generated from the data.
- The Two-Stage Pipeline:
- Pre-training (Self-Supervised): A neural network (the encoder) is trained on a large, unlabeled dataset using a pretext task. The goal is for the encoder to learn a rich, general-purpose feature representation of the data.
- Downstream Task (Supervised): The pre-trained encoder is then repurposed for a specific application (the downstream task). A simple, lightweight classifier head is added on top, and the system is fine-tuned on a much smaller, labeled dataset for the target task (e.g., image classification).
- What Makes a Good Pretext Task? The task should be challenging enough that to solve it, the model is forced to learn meaningful, high-level semantics about the visual world—what the lecture calls "visual common sense."
Part 2: SSL via Image Transformations (Pretext Tasks)
This section explores several classic pretext tasks based on applying transformations to images.
- Rotation Prediction:
- Task: An image is randomly rotated by one of four angles (0°, 90°, 180°, 270°). The model's task is to predict which of the four rotations was applied.
- Hypothesis: To know that a car is upside down (rotated 180°), the model must first learn what a car looks like right-side up. This forces it to learn about object orientation and structure.
- Relative Patch Prediction / Jigsaw Puzzles:
- Task: An image is divided into a 3x3 grid of patches. The model is given the center patch and one other random patch and must predict the relative position of the second patch (e.g., "top-left," "bottom-right"). A more complex version requires the model to reassemble a shuffled set of all nine patches into the correct order.
- Hypothesis: To solve the puzzle, the model must learn about the spatial relationships between object parts (e.g., an eye is typically above a mouth).
- Image Inpainting / Completion:
- Task: A portion of the image is masked out (e.g., a black square is placed over it). The model must predict the content of the missing patch.
- Hypothesis: To realistically fill in the missing region, the model needs to understand the context provided by the surrounding pixels.
- Image Colorization:
- Task: The model is given a grayscale version of an image (the L channel in LAB color space) and must predict the corresponding color channels (the A and B channels).
- Hypothesis: To correctly color an object (e.g., know that grass is green and the sky is blue), the model must first be able to recognize the object itself. The lecture also shows how this idea can be extended to video to learn to track objects over time.
Part 3: Masked Autoencoders (MAE) - A Modern Approach
The lecture then transitions to a state-of-the-art SSL method that builds upon the inpainting idea.
- Concept: Masked Autoencoders (MAE) are a powerful SSL framework based on a Transformer (ViT) architecture.
- The Asymmetric Encoder-Decoder:
- Masking: A very high percentage (e.g., 75%) of the input image patches are randomly masked out and discarded.
- Encoder: A large ViT encoder processes only the visible patches. This makes the pre-training process extremely efficient, as the encoder only does a fraction of the work.
- Decoder: A lightweight decoder takes the encoded representations of the visible patches, along with learnable "mask tokens" for the missing positions, and reconstructs the full image.
- Success: MAE has proven to be an incredibly effective pre-training method, demonstrating that models can learn powerful representations by predicting massive amounts of missing visual information.
Part 4: Contrastive Learning
The final section introduces a different, and highly influential, family of SSL methods: contrastive learning.
- The Core Idea: Instead of a reconstruction-based pretext task, contrastive learning is based on a similarity objective. The goal is to learn an embedding space where representations of "similar" images are pulled together, while representations of "dissimilar" images are pushed apart.
- Defining "Similar" and "Dissimilar":
- Positive Pairs (Similar): Two different random augmentations (e.g., crop, color jitter) of the same image are considered a positive pair.
- Negative Pairs (Dissimilar): Augmentations of different images are considered negative pairs.
- The InfoNCE Loss: The learning is driven by the InfoNCE (Noise Contrastive Estimation) loss function. For a given "anchor" image, the loss function aims to maximize the similarity score between the anchor and its positive pair, while simultaneously minimizing the similarity scores between the anchor and a large number of negative samples. Mathematically, this is equivalent to a multi-class cross-entropy loss where the goal is to correctly classify the positive pair out of a set of many negative decoys.
- Key Frameworks:
- SimCLR: A simple and powerful framework that uses a large batch size to source its negative samples. It also introduces a non-linear "projection head" during training to improve the quality of the learned representations.
- MoCo (Momentum Contrast): An approach that decouples the batch size from the number of negative samples. It maintains a large queue of past negative samples and uses a slow-moving momentum encoder to ensure the representations in the queue remain consistent, allowing it to work effectively with smaller batch sizes.
The lecture concludes by noting that these self-supervised methods, particularly contrastive learning and masked autoencoders, have been instrumental in enabling the training of large-scale foundation models that power many of today's vision applications.
L13: Generative Models 1
The lecture begins by recapping the previous session on Self-Supervised Learning (SSL). The core idea of SSL is to train a model on a large, unlabeled dataset using a pretext task (e.g., rotation prediction, image inpainting) for which "labels" can be automatically generated. This pre-training phase learns a powerful feature encoder, which can then be transferred and fine-tuned on a smaller, labeled dataset for a specific downstream task. The lecture briefly revisits contrastive learning methods like SimCLR and MoCo, highlighting their goal of pulling similar (augmented) samples together and pushing dissimilar ones apart in the feature space.
Part 1: The Taxonomy of Generative Models
The main topic of the lecture is generative models. The session starts by establishing a clear taxonomy to navigate this complex field.
- Supervised vs. Unsupervised Learning: A quick review to set the context. Supervised learning learns a mapping from inputs x to known labels y, while unsupervised learning aims to find latent structure in unlabeled data x.
- Discriminative vs. Generative Models: This is the core distinction.
- Discriminative Models: Learn the conditional probability P(y|x). They model a distribution over labels for a given input. The competition for probability mass is among the labels for each fixed input.
- Generative Models: Learn the probability of the data itself, P(x). They model a distribution over the entire space of possible data (e.g., all possible images). The competition for probability mass is among all possible images.
- Conditional Generative Models: Learn P(x|y). They model a distribution over data x conditioned on some label or context y. This is the most useful and common type of generative model, as it allows for controlled generation (e.g., "generate an image of a cat").
- The Taxonomy Tree: Generative models are further divided into two main branches:
- Explicit Density Models: These models allow you to explicitly compute the probability density P(x) for any given x.
- Tractable: The density is computed exactly (e.g., Autoregressive Models).
- Approximate: The model provides a lower bound or an approximation of the density (e.g., Variational Autoencoders).
- Implicit Density Models: These models do not allow you to compute P(x) directly, but you can sample from the distribution they have learned.
- Direct: Sampling is a single, feed-forward pass (e.g., Generative Adversarial Networks).
- Indirect: Sampling requires an iterative procedure (e.g., Diffusion Models).
- Explicit Density Models: These models allow you to explicitly compute the probability density P(x) for any given x.
Part 2: Autoregressive Models
This section covers the first leaf on the taxonomy tree: autoregressive models, a type of tractable, explicit density model.
- Maximum Likelihood Estimation (MLE): The foundational training principle. The goal is to find the model parameters that maximize the (log) likelihood of the observed training data.
- The Chain Rule of Probability: The key insight for autoregressive models. The joint probability of a sequence (x_1, x_2, ..., x_T) can be factored into a product of conditional probabilities: P(x_1) * P(x_2|x_1) * P(x_3|x_1, x_2) * ....
- Application to Data: This factorization turns the difficult problem of modeling a high-dimensional joint distribution into a series of simpler, next-step prediction problems.
- Text: This is a natural fit for text, which is an inherently 1D, discrete sequence. Models like RNNs and masked Transformers are used to predict the next token given the previous ones, directly optimizing the factored log-likelihood.
- Images: To apply this to images, the 2D grid of pixels is "rasterized" into a long 1D sequence of pixel values. The model then predicts each pixel (or sub-pixel channel) one by one. This is computationally very expensive for high-resolution images.
Part 3: Variational Autoencoders (VAEs)
The lecture then moves to the second branch of explicit models: VAEs, which provide an approximate density.
- Standard Autoencoders (AEs): An AE is a non-probabilistic, unsupervised model consisting of an encoder and a decoder. It is trained on a reconstruction task: the encoder compresses an input x into a low-dimensional latent vector , and the decoder tries to reconstruct the original x from z. The bottleneck z forces the model to learn a meaningful, compressed representation.
- The Problem with AEs for Generation: While the encoder learns a useful representation, the decoder cannot be used for generation because there is no principled way to sample new, valid latent vectors z. The distribution of z is complex and unknown.
- Variational Autoencoders (VAEs): VAEs solve this problem by making the autoencoder probabilistic. The core idea is to enforce a prior distribution (typically a simple unit Gaussian) on the latent space z.
- The VAE Architecture:
- The encoder (now a probabilistic model Q(z|x)) takes an input x and outputs the parameters (mean and variance) of a Gaussian distribution in the latent space.
- A latent vector z is sampled from this predicted distribution.
- The decoder (a probabilistic model P(x|z)) takes the sampled z and outputs the parameters of a distribution from which the original x can be reconstructed.
- The Training Objective (The ELBO): Training a VAE via direct maximum likelihood is intractable due to a difficult integral. Instead, VAEs are trained by maximizing the Evidence Lower Bound (ELBO), which is a lower bound on the true log-likelihood of the data. The ELBO consists of two terms that are traded off during training:
- Reconstruction Loss: Encourages the decoder to accurately reconstruct the input x from a sampled z.
- KL Divergence Loss: A regularization term that forces the distribution predicted by the encoder (Q(z|x)) to stay close to the simple Gaussian prior (P(z)).
- Generation with VAEs: After training, the encoder can be discarded. To generate a new sample, one simply draws a random vector z from the prior (the unit Gaussian) and passes it through the trained decoder.
The lecture concludes by setting the stage for the next session, which will cover the implicit density models: GANs and Diffusion Models.
L14: Generative Models 2
The lecture begins by recapping the previous session on generative models, reinforcing the taxonomy that divides them into two main families. Last time, the focus was on explicit density models, which provide a way to directly compute or approximate the probability density p(x) of a data point x.
- Autoregressive Models: These are tractable explicit models that factorize the joint probability of the data (e.g., pixels in an image) into a sequence of conditional probabilities using the chain rule, a task well-suited for RNNs and Transformers.
- Variational Autoencoders (VAEs): These are approximate explicit models that jointly train an encoder and a decoder. They learn a structured latent space by maximizing a lower bound (the ELBO) on the true data likelihood, trading off data reconstruction with a regularization term that forces the latent space to match a simple prior distribution (like a Gaussian).
Part 1: Generative Adversarial Networks (GANs)
The lecture then moves to the first category of implicit density models: Generative Adversarial Networks (GANs). These models can sample from a learned distribution but cannot explicitly compute its density.
- The Core Idea (The Minimax Game): GANs consist of two neural networks locked in an adversarial, two-player game:
- A Generator (G): Takes a random noise vector z (sampled from a simple prior like a Gaussian) and tries to generate a realistic data sample x that looks like it came from the true data distribution.
- A Discriminator (D): A classifier that takes an input sample (either a real one from the training set or a fake one from the generator) and tries to determine if it is real or fake.
- The Training Process: The two networks are trained in an alternating fashion:
- The discriminator is trained to maximize its classification accuracy (i.e., correctly label real samples as real and fake samples as fake).
- The generator is trained to minimize the discriminator's accuracy by producing samples that are so realistic they "fool" the discriminator into classifying them as real.
- Challenges of Training GANs:
- Instability: The minimax objective is notoriously unstable and difficult to optimize.
- Lack of a Convergent Loss: Unlike typical deep learning, there is no single loss function to monitor. The generator and discriminator losses fluctuate in opposition, making it hard to tell if the model is actually improving.
- Mode Collapse: A common failure mode where the generator learns to produce only a few, highly realistic samples, fooling the discriminator but failing to capture the full diversity of the data distribution.
- Successes and Legacy: Despite their difficulty, GANs (particularly advanced versions like StyleGAN) were the dominant generative modeling paradigm from roughly 2016 to 2021, producing the first truly high-resolution and photorealistic images. A key feature is their ability to learn smooth, interpolatable latent spaces.
Part 2: Diffusion Models
The second half of the lecture covers diffusion models, the implicit density models that have largely superseded GANs as the state-of-the-art for image and video generation.
- The Core Idea (Iterative Denoising): Diffusion models work through a two-stage process:
- Forward Process (Noise Corruption): A fixed process where a clean data sample x is gradually corrupted over a series of time steps t by adding Gaussian noise, until at t=1 it becomes pure noise z.
- Reverse Process (Denoising): A learned neural network is trained to reverse this process. It takes a noisy sample x_t at time t and predicts how to take a small step to make it slightly less noisy (i.e., closer to x_{t-1}).
- Training and Inference:
- Training: The network is trained on a simple objective: given a noisy sample x_t (created by corrupting a real image x), predict the noise that was added or, more simply, predict the "velocity" vector v = z - x that points from the clean image to the pure noise.
- Inference (Sampling): To generate a new image, the process is run in reverse. It starts with a sample of pure random noise (z) and then iteratively applies the trained denoising network for a fixed number of steps, gradually removing the noise until a clean image x emerges.
- Rectified Flow: A simple and intuitive formulation of diffusion is presented, where the noisy sample x_t is a linear interpolation between a clean image x and a noise vector z. The model is trained with a simple MSE loss to predict the direction vector v = z - x.
- Conditional Generation and Classifier-Free Guidance (CFG): To control the generation process (e.g., with a text prompt y), the model is trained conditionally. A key trick for improving quality is Classifier-Free Guidance (CFG). During training, the conditioning signal y is randomly dropped out. At inference time, the model makes two predictions—one conditional and one unconditional—and the final update direction is extrapolated further in the conditional direction. This significantly improves sample quality and prompt adherence at the cost of doubling the inference compute.
Part 3: Latent Diffusion Models - The Modern Pipeline
The lecture concludes by revealing that state-of-the-art models like Stable Diffusion are not standard diffusion models but Latent Diffusion Models, which combine all the generative modeling paradigms discussed.
- The Problem with Pixel-Space Diffusion: Running the iterative diffusion process on high-resolution images is computationally very expensive.
- The Latent Diffusion Solution:
- First, a powerful Variational Autoencoder (VAE) is trained to compress high-resolution images into a much smaller, lower-dimensional latent space. To ensure the reconstructions are sharp and not blurry (a common VAE issue), the VAE is often trained with an additional GAN-style adversarial loss.
- Next, a diffusion model (typically a Transformer-based one, or "DiT") is trained to operate entirely within this compact latent space.
- Finally, at inference time, the diffusion model generates a clean latent, which is then passed through the VAE's decoder once at the very end to produce the final, high-resolution image.
- Putting it All Together: The modern generative pipeline is a complex amalgamation: it uses a VAE for compression, a GAN for perceptual quality, a diffusion model for generation, and often a pre-trained autoregressive model (like a text encoder) to process the conditioning signal. This demonstrates how all the different families of generative models come together to create today's powerful systems for tasks like text-to-image and text-to-video generation.
L15: Vision
The lecture, delivered by guest speaker Professor Jiajun Wu, begins by transitioning the course's focus from 2D images to the more complex domain of 3D vision. The core challenge is immediately identified: while 2D images have a standard representation (a grid of pixels), 3D objects can be represented in many different, non-standard ways. The lecture is structured to first introduce these diverse 3D representations and then explore how deep learning methods have been adapted to work with them.
Part 1: A Taxonomy of 3D Representations
The first part of the lecture provides a comprehensive overview of how 3D object geometry can be represented, dividing the methods into two main families.
1. Explicit Representations: These methods directly describe the points on an object's surface.
- Point Clouds: The simplest form, representing an object as a raw, unordered set of 3D points (x, y, z coordinates). This is often the direct output of 3D scanners, but it lacks connectivity information, making it hard to infer surfaces.
- Polygonal Meshes: The most widely used representation in computer graphics. It consists of vertices (points) and faces (polygons, usually triangles) that connect them, explicitly defining the object's surface topology. Meshes are powerful but their irregular structure posed a significant challenge for early deep learning models.
- Parametric Surfaces (e.g., Bézier surfaces, Splines): These represent surfaces as mathematical functions that map a low-dimensional parameter space (e.g., 2D u,v coordinates) to the 3D surface. They are efficient for representing smooth, man-made objects.
The Trade-off of Explicit Representations: They make it very easy to sample points on the object's surface but make it very difficult to test if an arbitrary point in space is inside or outside the object.
2. Implicit Representations: These methods represent an object's surface implicitly, as the level set of a function.
- Implicit Functions: The surface is defined as the set of all points (x, y, z) where a function f(x, y, z) = 0. Points where f < 0 are inside, and points where f > 0 are outside. This function can be a simple algebraic equation (for a sphere) or, as we'll see, a complex neural network.
- Signed Distance Functions (SDFs): A specific type of implicit function where the value f(x, y, z) represents the signed distance to the nearest surface point.
- Voxels: The 3D equivalent of pixels. Space is divided into a regular 3D grid, and each voxel is assigned a binary value (0 or 1) indicating whether it is occupied by the object. This is a non-parametric implicit representation, created by sampling an implicit function on a grid.
The Trade-off of Implicit Representations: The inverse of explicit methods. They make it very easy to test if a point is inside or outside the object but make it very difficult to directly sample points on the surface.
Part 2: The Data Landscape for 3D Vision
Before diving into deep learning methods, the lecture covers the crucial topic of 3D data. A major challenge for 3D vision has been the relative scarcity of data compared to the billions of images available for 2D vision.
- Early Datasets (e.g., Princeton Shape Benchmark): Small-scale, with only a few dozen examples per category.
- The Rise of Large-Scale Datasets (e.g., ShapeNet): The first truly large-scale repository of 3D models (primarily synthetic CAD models), enabling the initial application of deep learning to 3D. It contains ~50,000 models across 55 categories.
- Modern Datasets (e.g., Objaverse, Objectron): Much larger datasets are now available, including massive collections of synthetic assets (Objaverse, with ~10 million models) and datasets of real-world objects captured with 360-degree videos (Objectron).
- Scene-Level Datasets (e.g., ScanNet): Datasets of entire indoor scenes captured with 3D scanners, enabling research on scene understanding.
Part 3: Deep Learning on 3D Data
This section details the evolution of deep learning methods designed to work with these different 3D representations.
- Early Approaches (View-Based Methods): The very first attempts avoided the complexity of 3D data altogether. They rendered a 3D object from multiple 2D viewpoints and then fed these 2D images into a standard, pre-trained 2D CNN, pooling the results for a final classification. This approach is still relevant today, given the power of modern 2D foundation models.
- Volumetric CNNs on Voxels: The most direct extension of 2D deep learning. The 3D object is represented as a voxel grid, and standard 2D convolutions are replaced with 3D convolutions. This was the approach used in the first deep generative models for 3D shapes. However, voxels are computationally expensive and memory-intensive due to their uniform sampling of space.
- Deep Learning on Point Clouds (PointNet): A groundbreaking architecture from Stanford that processes raw point clouds directly. The key challenge is permutation invariance (the output should not depend on the order of the points). PointNet solves this by applying a shared function (an MLP) to each point independently and then using a symmetric aggregation function (like max pooling) to combine the point features into a global shape representation.
- Deep Implicit Functions: This paradigm shift, occurring around 2019, embraced implicit representations. Instead of trying to predict an explicit structure like a voxel grid or point cloud, the neural network itself becomes the implicit function.
- The Model: A simple MLP is trained to take a 3D coordinate (x, y, z) as input and output a value indicating, for example, whether that point is inside or outside the object (occupancy) or its signed distance to the surface (SDF).
- Advantages: This approach produces continuous, high-resolution surfaces and is very memory efficient.
- Neural Radiance Fields (NeRF): The revolutionary method that combined deep implicit functions with principles from computer graphics.
- The Model: A NeRF is an MLP that learns an implicit function mapping a 3D coordinate (x, y, z) and a viewing direction (θ, φ) to a color (RGB) and a volume density (σ).
- Differentiable Rendering: The key innovation is coupling this neural representation with a differentiable volume rendering equation. This allows the model to be trained end-to-end directly from a set of 2D images of a scene, without needing any 3D ground truth data.
- 3D Gaussian Splatting: A very recent and highly efficient alternative to NeRF. It represents a scene with a set of explicit 3D Gaussians (like a point cloud of "blobs"). By combining this explicit representation with a differentiable rasterization pipeline, it achieves real-time rendering speeds that are orders of magnitude faster than NeRF while maintaining comparable quality.
Part 4: Beyond Elemental Geometry - Modeling Structure
The lecture concludes by looking beyond the raw geometry of surfaces to higher-level structural representations.
- Part-Based Representations: Modeling objects as a collection of semantic parts (e.g., a chair has legs, a seat, and a back).
- Hierarchical and Relational Structures (Graphs): Representing objects and scenes as hierarchical graphs that capture not only the parts but also their relationships and constraints (e.g., symmetry, connectivity).
- Procedural Modeling (Programs): Representing shapes as programs that generate the geometry. Recent work explores using LLMs to generate these programs, combining their semantic understanding with geometric primitives.
L16: Vision and Language
The lecture, delivered by guest speaker Professor Ranjay Krishna, begins by framing a major shift in the field: moving away from training specialized models for individual tasks (e.g., a dedicated image classifier) towards building foundation models.
- What is a Foundation Model? A large model pre-trained on a massive, diverse dataset to acquire a broad range of skills. It can then be adapted to many different downstream tasks with minimal or even zero additional training data ("zero-shot" or "few-shot" learning).
- Today's Focus: The lecture will focus on multimodal foundation models, specifically those that combine vision and language, and explore how they are built and used.
Part 1: Foundation Models for Image Classification (CLIP & CoCa)
This section explains how the principles of self-supervised learning were extended to create the first true foundation model for vision.
- The Core Idea (from SimCLR to CLIP): The lecture starts with a recap of SimCLR, a contrastive self-supervised learning method that learns to pull representations of different augmentations of the same image closer together while pushing representations of different images apart.
- CLIP (Contrastive Language-Image Pre-training): CLIP extends this idea into the multimodal space. Instead of contrasting two augmented images, it learns to match an image with its corresponding text caption. The model consists of two encoders—one for images and one for text—trained jointly with a symmetric contrastive loss on hundreds of millions of image-text pairs scraped from the internet.
- Zero-Shot Classification with CLIP: The key innovation of CLIP is its ability to perform zero-shot classification on new tasks without any fine-tuning. This is done by:
- Using the text encoder to create a vector representation for each of the new class names (e.g., "a photo of a dog," "a photo of a plane").
- Using the image encoder to create a vector for the input image.
- Performing a nearest-neighbor search to find which class text vector is most similar to the image vector.
- Why CLIP Works Well: CLIP's impressive generalization ability comes from two main factors: the massive scale of its training data (400M+ pairs) and the rich semantic supervision provided by natural language captions, which goes far beyond simple category labels.
- Limitations of CLIP: Despite its success, CLIP has significant limitations. It struggles with compositionality (e.g., distinguishing "a mug on grass" from "grass in a mug") and fine-grained recognition, a problem tied to the randomness of negative samples in its contrastive training objective.
- CoCa (Contrastive-Captioner): A follow-up model that improved upon CLIP by adding a second training objective. In addition to the contrastive loss, CoCa also includes a captioning loss, forcing the model to generate a text description from the image features. This stronger supervisory signal led to significant performance improvements.
Part 2: Multimodal Language Models (LLaVA & Flamingo)
This section covers the next evolution: integrating vision directly into Large Language Models (LLMs) to create powerful, conversational visual assistants.
- The Goal: To enable models to reason about and discuss images in a natural, multi-turn dialogue, moving beyond simple classification.
- LLaVA (Large Language and Vision Assistant): The pioneering open-source model in this space.
- Architecture: It takes the patch-level feature tokens from the penultimate layer of a pre-trained CLIP image encoder. These visual tokens are passed through a simple linear projection to align them with the LLM's embedding space and are then prepended to the text input.
- Training: The model is then fine-tuned on an instruction-following dataset to learn to generate textual responses conditioned on both the image and the text prompt.
- Flamingo: A more sophisticated architecture from DeepMind.
- Key Innovation: Instead of feeding the visual features only once at the input, Flamingo uses a perceiver resampler to create a small, fixed set of visual tokens. These tokens are then made available to every single layer of the LLM via a newly introduced gated cross-attention mechanism. This allows the language model to decide when and how to "look" at the image at each stage of its reasoning process.
- Few-Shot Learning: Flamingo was trained on a unique dataset of interleaved images and text, which enabled powerful in-context few-shot learning, where the model can be shown a few examples of a new task and then perform that task on a new image.
Part 3: The Frontier of Vision-Language Models (MoLMo)
This section discusses the speaker's own recent work on closing the performance gap between open-source and proprietary models like GPT-4V.
- The Problem: A significant performance gap existed between closed models (like GPT-4V and Gemini) and open-source alternatives (like LLaVA). Many open models were simply "distillations" of proprietary ones, meaning the community didn't know how to build them from scratch.
- MoLMo (More Language, More Modalities): The speaker's model, which was the first open-source model to match the performance of GPT-4V on human preference evaluations.
- The Secret Sauce: Data and Grounding: The key to MoLMo's success was not a new architecture but a much higher-quality, hand-curated dataset.
- Data Quality: Internet data is often "incidental," with text that is subjective or only loosely related to the image. The MoLMo dataset was created by having human annotators provide dense, objective descriptions of visual content, covering concepts that are rarely described online (e.g., relative spatial positions, materials, fine-grained details).
- Grounding: A key feature of the model is its ability to ground its textual responses in the image by outputting pixel coordinates. For example, when asked to count the boats, it points to each boat before giving the final count. This grounding ability makes its reasoning more verifiable and was a direct result of the high-quality data.
Part 4: Generalizing Outputs and Chaining Models
The lecture concludes by looking at how foundation models are being extended beyond text outputs and how they can be combined into more powerful systems.
- Foundation Models for Segmentation (SAM - Segment Anything Model):
- Goal: To create a general-purpose model that can segment any object in any image, guided by a user's prompt.
- Architecture: SAM takes an image and a prompt (which can be a point, a box, or text) and outputs a segmentation mask. It was trained on a massive, newly created dataset of over 1 billion masks, demonstrating again that data is the key to building powerful foundation models.
- Chaining Models: The final and most powerful idea is chaining—composing multiple specialized foundation models to solve complex tasks that no single model can handle alone.
- Example: A user asks a complex question about an image. An LLM acts as a "planner" or "agent," generating a Python program that makes calls to other models. It might call an object detector to find people, a segmentation model to isolate a region, and then use the results to formulate a final answer. This approach, popularized by the VisProg paper, allows for the creation of highly capable and versatile AI systems by leveraging the strengths of many different foundation models.
L17: Robot Learning
The lecture, delivered by guest speaker Professor Yunzhu Li, distinguishes robot learning from the traditional computer vision tasks covered so far. While supervised and self-supervised learning focus on perception and representation (mapping an input x to an output y), robot learning is about interaction.
- The Core Concept: The agent (robot) is not a passive observer. It takes actions that influence the state of the physical world. The world, in turn, provides feedback in the form of new observations (states) and rewards. The goal is to learn a sequence of actions that maximizes a given reward or objective.
- Recent Momentum: The field has seen a recent explosion of interest and investment, with numerous startups (Figure, Physical Intelligence) and large companies (Google, Tesla) developing general-purpose robots capable of complex physical tasks like folding clothes.
Part 1: Problem Formulation - The Language of Interaction
The lecture formalizes the robot learning problem using the framework of sequential decision-making.
- The Loop: An agent receives a state ( from the environment and, guided by a goal, chooses an action (. The action changes the environment, leading to a new state ( and a reward (.
- Key Components: This framework is general and can be applied to many domains beyond robotics, including games (Atari, Go), language modeling, and chatbots. The specific instantiation of the states, actions, and rewards defines the problem.
Part 2: The Uniqueness of Robot Perception
Robot perception differs significantly from standard computer vision.
- Situated and Multimodal: Robots are situated in a messy, unstructured world. They often rely on multiple sensory modalities (e.g., vision, depth, tactile, audio) to form a complete understanding.
- Embodied and Active: Unlike passive computer vision systems that process static datasets, robots are embodied agents that can actively perceive. They can move and interact with the environment to gather more information (e.g., poking an object to see if it's one piece or a pile). This closed loop between perception and action is fundamental.
Part 3: Algorithms for Robot Learning
This section provides a high-level overview of the major algorithmic paradigms in robot learning.
1. Reinforcement Learning (RL):
- Concept: Learning through trial and error. The robot interacts extensively with an environment (often a simulation) to discover which actions lead to high rewards.
- Successes: RL has been phenomenally successful, especially in robot locomotion, where it is now considered a nearly "solved" problem. Videos of quadrupeds from companies like Unitree demonstrate incredible agility and robustness, learned via RL in randomized simulations.
- Limitations: Model-free RL is extremely sample-inefficient, requiring millions or billions of interactions (equivalent to thousands of years of human experience for AlphaGo). This makes it difficult to apply directly in the real world, where trial and error can be slow and dangerous.
2. Model-Based Learning and Planning:
- Concept: This approach tries to make learning more efficient by first learning a model of the world (a "dynamics model"). This learned model acts as an internal simulator, predicting how the state of the world will change in response to an action: s_{t+1} = f(s_t, a_t).
- Planning: Once this forward model is learned, the robot can use it to plan. It can "imagine" the outcomes of different action sequences and use optimization techniques (like gradient descent on the trajectory) to find the sequence that best achieves its goal.
- State Representations: A key challenge is choosing the right state representation for the dynamics model. The lecture showcases examples using raw pixels, keypoints, and particles (for deformable objects like dough and granular media). The speaker's own work on a dumpling-making robot is presented as a case study, demonstrating a robust system that uses a learned particle-based dynamics model to plan multi-step, multi-tool manipulation tasks.
3. Imitation Learning:
- Concept: Learning by watching an expert. Instead of discovering a policy through trial and error, the model learns by mimicking a dataset of human demonstrations.
- Behavior Cloning: The simplest form, which treats the problem as a supervised learning task of mapping observed states to the expert's actions (a = π(s)). A key challenge is cascading errors, where small mistakes can lead the robot into states it has never seen before, causing it to fail.
- Modern Approaches (Diffusion Policies): Recent breakthroughs have applied powerful generative models, like diffusion models, to imitation learning. Diffusion policies have shown remarkable success in learning complex, dexterous manipulation tasks from a relatively small number of human demonstrations, representing a highly efficient way to get a working policy.
Part 4: The Frontier - Robotic Foundation Models
The final section covers the most recent and exciting trend: building robotic foundation models.
- The Goal: To create a single, general-purpose policy that can perform a wide variety of tasks, guided by high-level instructions (like language). These are often called Vision-Language-Action (VLA) models.
- The Recipe (e.g., Google's RT series, Pi-Zero): The typical approach is a multi-stage process:
- Start with a pre-trained Vision-Language Model (VLM): Leverage a powerful VLM to provide a strong semantic and visual prior.
- Pre-training / Co-fine-tuning: Fine-tune this VLM on a large, diverse dataset of robot demonstration data from many different tasks and robot embodiments.
- Post-training / Task-specific Fine-tuning: To achieve high performance on a specific new task, the general foundation model is further fine-tuned on a smaller dataset for that task.
- Challenges: The biggest challenge in this area is evaluation. Performance is highly sensitive to real-world conditions, and there is often a weak correlation between training loss and real-world success. The field is actively working on creating standardized, reproducible benchmarks (the "ImageNet for Embodied AI") to reliably measure progress. Another major area of research is building foundation world models that can learn the underlying physics and dynamics of the world from the vast amounts of interaction data being collected.
The lecture concludes with a vision of a future where these powerful foundation models enable robots to robustly perceive and interact with the complex, unstructured environments of the real world.
L18: Human-Centered AI
The lecture, delivered by guest speaker Professor Yunzhu Li, distinguishes robot learning from the passive perception tasks that have dominated the course so far.
- Supervised/Self-Supervised Learning: These paradigms learn a mapping from input data x to an output y (or a latent representation) from a static dataset.
- Robot Learning: This paradigm introduces a dynamic, interactive loop. The agent (robot) takes actions that physically change the environment. The environment, in turn, provides new observations (states) and rewards, guiding the agent's future decisions. The goal is to find a sequence of actions to maximize a reward or achieve a goal.
- Recent Momentum: The field is experiencing a boom, with significant investment and high-profile demonstrations from startups (Figure) and large companies (Tesla, Google), all aiming to build general-purpose robots.
Part 1: Problem Formulation and Robot Perception
- The RL Framework: The robot learning problem is formally defined using the language of reinforcement learning: an agent takes an action ( based on its current state ( and a goal, receives a new state ( and a reward ( from the environment. This framework is shown to be general enough to describe everything from controlling a cart-pole to playing Go to generating text with an LLM.
- The Uniqueness of Robot Perception: Robot vision is fundamentally different from standard computer vision. It is:
- Embodied: The robot has a physical body and experiences the world directly.
- Active: The robot can move and interact to gain more information (e.g., poke a pile of objects to see if it's one thing or many).
- Situated: The robot operates in the "here and now," with perception tightly coupled to the actions required for the current task.
Part 2: A Survey of Robot Learning Algorithms
This section provides a high-level overview of the major algorithmic paradigms in robot learning.
- Reinforcement Learning (RL):
- Concept: Learning through extensive trial and error. By interacting with an environment (often a simulation) millions or billions of times, the agent learns a policy that maps states to actions that maximize long-term reward.
- Successes: RL has been phenomenally successful in solving complex games (Atari, Go, StarCraft) and is now considered the dominant solution for robot locomotion. The lecture highlights that robust locomotion policies can be learned in highly randomized simulations and then successfully transferred to the real world (sim-to-real).
- Limitations: Model-free RL is extremely sample-inefficient and can be unsafe to train directly in the real world, which has limited its success in complex manipulation tasks.
- Model-Based Learning and Planning:
- Concept: To improve sample efficiency, this approach first learns a model of the world (a "dynamics model"). This learned model acts as an internal simulator, predicting how the state of the world will change in response to an action: s_{t+1} = f(s_t, a_t).
- Planning: Once this forward model is learned, the robot can use it to plan by "imagining" the outcomes of different action sequences and optimizing for the sequence that best achieves its goal.
- Case Study (Dumpling Robot): The speaker's work on a dumpling-making robot is presented. The system uses a learned, particle-based dynamics model to predict how dough will deform. This model enables the robot to plan a complex, multi-tool sequence of actions and robustly recover from human-introduced perturbations.
- Imitation Learning:
- Concept: Learning by mimicking a dataset of expert (usually human) demonstrations. This is a form of supervised learning that maps observed states to expert actions (a = π(s)).
- Modern Approaches (Diffusion Policies): Recent breakthroughs have applied powerful generative models, like diffusion models, to imitation learning. Diffusion policies have shown remarkable success in learning complex, dexterous manipulation tasks from a relatively small number of human demonstrations, representing a highly efficient way to get a working policy.
- Robotic Foundation Models:
- Concept: The latest trend, which aims to build a single, general-purpose policy that can perform a wide variety of tasks, often guided by high-level language instructions (Vision-Language-Action models).
- The Recipe (e.g., Google's RT series, Pi-Zero): The typical approach is to start with a powerful, pre-trained Vision-Language Model (VLM) and then co-fine-tune it on a large, diverse dataset of robot demonstration data.
Part 3: Challenges and the Human Perspective
The lecture concludes by focusing on the broader challenges and the human-centered aspects of AI and robotics.
- The Challenge of Evaluation: A major bottleneck for the field is the lack of standardized, reliable benchmarks. Real-world evaluation is costly and noisy, while simulation-based evaluation suffers from the sim-to-real gap. The field is in search of its "ImageNet moment"—a benchmark where progress directly correlates with real-world capabilities.
- AI Beyond Human Capabilities: The lecture revisits the theme of building AI to see what humans cannot see. This includes:
- Fine-grained recognition: Classifying thousands of species of birds or models of cars.
- Overcoming human limitations: Using AI to mitigate human attentional failures, such as in medical settings to prevent errors.
- Respecting privacy: Designing AI systems that can perform useful tasks (like monitoring elderly patients) without violating privacy, using techniques like specialized lenses or federated learning.
- AI for Augmentation, Not Replacement: The final and most important message is the need to build AI that augments human capabilities rather than simply replacing human labor.
- Addressing Labor Shortages: The lecture highlights critical labor shortages in areas like healthcare and elder care, where AI and robotics can have a profound positive impact.
- Human-Centered Design (The BEHAVIOR Benchmark): The speaker discusses their work on the BEHAVIOR benchmark, a large-scale, physically realistic simulation environment for everyday household activities. Crucially, the 1,000 tasks in the benchmark were chosen based on a large-scale survey asking people what they actually want help with. This revealed that humans want help with chores (cleaning) but not with socially or emotionally meaningful tasks (cooking breakfast, opening gifts).
- The Sci-Fi Future (Brain-Computer Interfaces): The lecture ends with a look at the frontier, showcasing a demo where a robot cooks a meal controlled entirely by non-invasive EEG brain signals, pointing towards a future where AI can help restore capabilities to severely paralyzed patients.
The ultimate take-home message is that the goal of AI should not just be to create intelligent systems, but to build tools that help people and are aligned with human values.