Stanford Finds Neural Networks Self-Stabilize Past Curvature Limits

Sharpness, Edge of Stability & Flat Minima | Stanford CS312 Lecture 6 with Suhas Kotha — Stanford Online

Stanford Online

Neural networks avoid divergence beyond classical stability thresholds because high-frequency gradient oscillations generate an implicit third-order force that actively suppresses landscape sharpness.

AI-assisted summary of Sharpness, Edge of Stability & Flat Minima | Stanford CS312 Lecture 6 with Suhas Kotha — original source. Check the original for full context.

Source published:

Key ideas

  • Deep neural networks trained beyond the classical quadratic stability threshold 2/eta self-stabilize via third-order Taylor terms instead of diverging exponentially. (2:23)
  • Central flows reconcile continuous modeling with empirical training by tracking the expected moving average path while averaging out chaotic high-frequency oscillations. (12:51)
  • Adaptive methods like RMSprop self-stabilize through two complementary forces: dynamic step-size reduction driven by gradient variance and active landscape curvature reduction. (39:18)
  • Sharpness-Aware Minimization (SAM) delivers substantial generalization benefits under label noise and fine-tuning, though its peak performance at batch size 1 optimizes average-case rather than worst-case neighborhood loss. (62:44)

Detailed notes

## Background This lecture was published on YouTube by Stanford Online on November 30, 2026, as part of the Stanford CS312: Deep Learning Alchemy course taught by Tatsunori Hashimoto and Suhas Kotha. Delivered by Suhas Kotha, the presentation examines loss landscapes, the edge of stability (EoS) phenomenon, self-stabilization, central flows, and Sharpness-Aware Minimization (SAM).

## TL;DR The lecture investigates why deep neural network training persists in dynamic equilibrium at the edge of stability without diverging exponentially, contrasting empirical behavior against classical convex quadratic intuition. Suhas Kotha unpacks the third-order Taylor expansion mechanism and the central flows framework, illustrating how fast oscillations along leading Hessian eigenvectors generate negative gradient drift that suppresses curvature. The discussion extends this framework across momentum, scalar and coordinate-wise RMSprop, and Adam, demonstrating how adaptive methods balance dynamic step-size adjustment and sharpness regularization. Finally, Kotha evaluates the relationship between flat minima and generalization, analyzing the practical mechanics, quirks, and downstream fine-tuning benefits of Sharpness-Aware Minimization (SAM).

## Atmosphere & style The lecture carries an informal yet intellectually rigorous academic tone, blending rigorous calculus and differential equations with playful, candid acknowledgments of deep learning as a field of empirical 'black magic' and alchemy. Kotha presents with an approachable, conversational speaking style, openly admitting where formal mathematical theory falls short and where practitioners must rely on heuristics. Watching the session feels like sitting in an advanced graduate seminar where theoretical paradigms break down in real time, shifting seamlessly from technical derivations to practical, grounded reflections on research trial and error.

## Bulletin - [02:23](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=143s) Deep neural networks trained beyond the classical quadratic stability threshold 2/eta self-stabilize via third-order Taylor terms instead of diverging exponentially. - [12:51](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=771s) Central flows reconcile continuous modeling with empirical training by tracking the expected moving average path while averaging out chaotic high-frequency oscillations. - [39:18](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=2358s) Adaptive methods like RMSprop self-stabilize through two complementary forces: dynamic step-size reduction driven by gradient variance and active landscape curvature reduction. - [01:02:44](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3764s) Sharpness-Aware Minimization (SAM) delivers substantial generalization benefits under label noise and fine-tuning, though its peak performance at batch size 1 optimizes average-case rather than worst-case neighborhood loss.

## Key takeaways - [02:23](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=143s) Classical convex optimization mandates learning rate eta < 2/S, but deep networks systematically violate this bound during training without exploding. - [04:34](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=274s) When sharpness surpasses 2/eta, networks enter an Edge of Stability (EoS) dynamic equilibrium characterized by fast oscillations along top Hessian eigenvectors. - [08:34](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=514s) Self-stabilization arises mathematically from third-order Taylor terms acting as an implicit negative gradient that reduces local curvature. - [11:15](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=675s) Standard gradient flow breaks down at the 2/eta threshold, whereas central flows successfully predict weight moving averages and held-out prediction trajectories. - [22:52](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1372s) In the river valley mental model, central flow traces the smooth floor while training iterates bounce chaotically between steep canyon walls. - [30:18](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1818s) Momentum affects stability thresholds inversely depending on batch size: it increases the threshold by (1 + beta) in full-batch settings but lowers it by (1 - beta) under small-batch noise. - [36:41](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=2201s) Scalar RMSprop operates around a stabilized effective sharpness of eta * S / sqrt(nu) ≈ 2 rather than raw Hessian sharpness. - [51:54](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3114s) Coordinate-wise RMSprop functions as diagonal preconditioning, solving a constrained optimization problem balancing preconditioned eigenvalue bounds against trace minimization. - [26:58](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1618s) Progressive sharpening causes networks to continuously migrate into sharper landscape regions until pinned by the EoS boundary, though its root cause remains theoretically unexplained. - [59:35](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3575s) Flatter minima frequently correlate with superior generalization, but reparameterization invariance issues prevent Hessian sharpness from serving as a universal mathematical guarantee. - [01:06:05](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3965s) Pre-training language models with SAM or higher learning rates suppresses sharpness and mitigates catastrophic forgetting during downstream fine-tuning. - [01:08:42](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=4122s) Sharpness currently serves best as an intuitive design heuristic for deep learning practitioners, as strict formal theorems frequently break down across realistic training regimes.

## Detailed walkthrough ### [00:05](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=5s) Course Context, Announcements, and Lecture Roadmap

Suhas Kotha introduces the second and final optimization lecture in CS312: Deep Learning Alchemy, focusing on loss landscapes, sharpness, and the phenomenon known as the Edge of Stability (EoS). Before diving into the technical content, Kotha shares administrative reminders: the first batch of tutorials begins that evening. Students should have received email notifications regarding potential rescheduling and must arrive ready to discuss Assignment 2 and Quiz 2, equipped with an understanding of their work and a couple of prepared questions.

The lecture is organized into three principal segments: 1. **The Edge of Stability Framework:** Exploring how sharpness evolves throughout a training trajectory, beginning with the simplest possible baseline—full-batch vanilla gradient descent—before layering on modern optimizer ingredients like momentum, adaptive learning rates, and finite batch size. 2. **Sharpness and Generalization:** Shifting from compute-limited regimes (step-bound) to data-limited settings to understand how sharpness impacts generalization. 3. **Sharpness-Aware Minimization (SAM):** Controlling and directly optimizing for sharpness using specialized training procedures.

Kotha attributes the foundation of the Edge of Stability material to researchers Jeremy Cohen and Alex Damian, praising them as exceptional researchers and communicators: “If the lecture is good, it's because of this and if it's bad, it's because of me.”

```mermaid flowchart TD accTitle: Lecture Structure on Sharpness and Edge of Stability accDescr: Three progressive segments covering Edge of Stability, generalization under data limits, and algorithmic control via SAM.

subgraph S1["1. Edge of Stability (EoS)"] A["Full-Batch Gradient Descent Baseline"] B["Interactions: Momentum, Adaptivity & Batch Size"] A --> B end

subgraph S2["2. Generalization & Data Constraints"] C["Sharp vs. Flat Minima"] D["Performance in Data-Limited Regimes"] C --> D end

subgraph S3["3. Controlling Sharpness"] E["Algorithmic Control & SAM"] end

S1 --> S2 --> S3 ```

---

[02:23](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=143s) Quadratic Intuition vs. Deep Learning Reality

Traditional optimization theory builds intuition from simple convex quadratics, such as $f(x) = \frac{1}{2} S x^2$, where the sharpness $S$ corresponds to the maximum eigenvalue of the Hessian matrix ($\lambda_{\max}(H)$). In this classical setup, convergence demands that the learning rate $\eta$ satisfies the stability condition $\eta < \frac{2}{S}$, meaning sharpness cannot exceed $\frac{2}{\eta}$. If the step size is chosen too large—such that $S > \frac{2}{\eta}$ along any Hessian eigenvector—the updates oscillate uncontrollably, divergence occurs, and iterates fly away toward infinity. The maximum eigenvalue serves as the bottleneck because stability along the top eigenvector dictates the maximum viable step size for the entire system.

Under this classical mental model, one might assume that deep neural network training remains strictly confined to the stable region where sharpness never exceeds $\frac{2}{\eta}$. However, empirical tracking of real training runs contradicts this belief. As training loss steadily decreases, measured sharpness climbs until it breaches the theoretical stability threshold $\frac{2}{\eta}$. Rather than exploding catastrophically, deep networks exhibit self-stabilizing dynamics.

- **Quadratic Objective:** $f(x) = \frac{1}{2} S x^2$ - **Hessian Peak Eigenvalue:** Sharpness is defined as $\lambda_{\max}(\nabla^2 L(\theta))$ - **Classical Stability Threshold:** $\lambda_{\max} \le \frac{2}{\eta}$; exceeding this causes exponential oscillation and divergence in linear/quadratic settings

---

[04:34](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=274s) The Self-Stabilization Phenomenon

Zooming in on the trajectory when sharpness crosses the $\frac{2}{\eta}$ threshold reveals non-trivial local dynamics. By projecting displacement along the leading Hessian eigenvector—representing the steepest direction across the loss "river valley"—one observes rapid back-and-forth oscillations across the valley walls once sharpness surpasses $\frac{2}{\eta}$. Classical quadratic analysis predicts that this instability should immediately rupture the training run and cause total divergence.

Instead of blowing up, the network exhibits self-stabilization: sharpness crests, drops back down below the threshold, and the cross-valley oscillations diminish. Over the entire trajectory, sharpness rises, hits instability, drops, rises again, and hovers in dynamic equilibrium around $\frac{2}{\eta}$. When asked whether this was simulated on a toy model, Kotha clarifies that this behavior is drawn directly from deep neural networks trained on real datasets (such as CIFAR on vision models) and generalizes across data modalities and architectures: “The standard quadratic intuition would have suggested you would have blown up here, but actually what happens is that you stabilize.”

Addressing how practitioners should reason about these dynamics, Kotha jokes about the trial-and-error nature of the field: “It's really you know field of black magic. It's really It's really scary stuff.”

---

[06:50](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=410s) Changing Learning Rates and the "Bouncing" Landscape Cartoon

The equilibrium value where sharpness tracks is governed directly by the learning rate. When the learning rate $\eta$ is decreased, the theoretical threshold $\frac{2}{\eta}$ moves upward. In response, the empirical sharpness climbs to and fluctuates around this higher plateau. This inverse relationship confirms that the network's stabilization ceiling is coupled to the learning rate step size rather than fixed architectural limits.

These findings invalidate the traditional cartoon of deep learning optimization, in which the parameter trajectory glides smoothly through an interior region where $\lambda_{\max} < \frac{2}{\eta}$ from initialization to the final minimizer. A more realistic mental model shows optimization bouncing along and across the boundary of the unstable zone, riding the edge of stability to reach its destination.

While these foundational observations are demonstrated using full-batch gradient descent (computing updates over the full dataset simultaneously), Kotha emphasizes that the same core phenomenology manifests in stochastic mini-batch settings (such as batch size 64) as well as across standard optimization components: - **Batching:** Mini-batch stochastic gradient descent (SGD) - **Momentum:** Heavy-ball and Nesterov acceleration - **Adaptivity:** Adaptive optimizers such as Adam and RMSprop

Full-batch gradient descent is analyzed first in isolation to pinpoint the core mathematical and empirical mechanics before examining its interactions with momentum, adaptive learning rates, and stochastic noise.

[08:34](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=514s) Taylor Expansions and the Third-Order Mechanism of Self-Stabilization

The edge of stability phenomenon is underpinned by a core property known as self-stabilization. To build an informal intuition for how this works, consider the loss landscape when the parameters are displaced along the eigenvector corresponding to the maximum eigenvalue of the Hessian matrix. Perturbing the current weights along the top eigenvector direction $u$ by a displacement factor $x$ allows the displaced loss to be approximated via a Taylor expansion:

```mermaid flowchart TD accTitle: Taylor Expansion Terms in Self-Stabilization accDescr: Decomposition of the Taylor expansion of the loss into gradient, quadratic oscillation, and sharpness reduction terms.

subgraph Expansion["Taylor Expansion of Displaced Loss"] T1["1st Order: Standard Gradient"] T2["2nd Order: Hessian Quadratic (Oscillations)"] T3["3rd Order: Sharpness Derivative (Stabilization)"] end

T1 --> Out1["Drives optimization step"] T2 --> Out2["Pulls back / causes oscillatory bounce"] T3 --> Out3["Acts as negative gradient of sharpness"] ```

The first term corresponds to the unperturbed gradient at that location. The second term incorporates the Hessian, weighted by the displacement magnitude, forming the standard quadratic local approximation. In a purely quadratic landscape, moving opposite to $u$ generates restoring forces that pull the iterate back, producing quadratic-looking oscillations.

Standard optimization analysis stops at this second order, but the self-stabilization analysis introduces a crucial change: it extends to the third-order term of the Taylor expansion. When this third-order term is expanded, it contains the expression $u^\top \nabla^2 L \, u$, which corresponds directly to the maximum eigenvalue of the Hessian—the sharpness. As Suhas Kotha highlights:

> “So in addition to doing the standard gradient descent and the second term, you are also having this third term which reduces your sharpness over the course of training.”

This third-order update acts effectively as the negative gradient of the sharpness, driving sharpness down during training. While higher-order terms (fourth, fifth, or sixth) are omitted, empirical observation demonstrates that this third-order component plays a decisive role. Furthermore, while the analysis focuses primarily on the top eigenvalue, empirical experiments confirm that this self-stabilization behavior occurs across other eigenvalues at the edge of stability as well.

[11:15](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=675s) Gradient Flow vs. Empirical Dynamics at the Edge of Stability

A foundational analytical technique for studying discrete gradient descent is to model weight trajectories using continuous-time differential equations, known as gradient flow:

$$\frac{dw}{dt} = -\eta \nabla L(w_t)$$

This ordinary differential equation suggests that at any instantaneous time $t$, the parameters move in the direction of the negative gradient scaled by the learning rate $\eta$. When comparing empirical discrete gradient descent (the observed blue trajectory) against the predictions made by continuous gradient flow (the red curve), gradient flow initially performs well. During early training, it precisely tracks the actual loss trajectory.

However, standard gradient flow accounts only for dynamics up to the second order, behaving like a quadratic model. Consequently, once training crosses the edge of stability threshold ($2/\eta$), standard gradient flow diverges completely from empirical reality. The differential equation predicts that sharpness will explode toward infinity. In actual neural network training, the model stabilizes: sharpness peaks, drops back down, and enters an oscillatory pattern. As Kotha observes:

> “So, this shows that the gradient flow has some predictive value in practice, but it does not have great predictive value because it stops at the region of interest, which is where the sharpness stabilizes.”

Because standard gradient flow breaks down precisely at this critical oscillatory transition, an alternative theoretical framework is required to model where iterates actually travel.

[12:51](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=771s) Central Flows: Tracking Time-Averaged Trajectories

To understand the model's path through the oscillatory regime without being blinded by high-frequency bounces, researchers employ a tool called the *central flow*. Instead of ignoring oscillations or tracking every individual bounce along the top eigenvector, the central flow models the average drift of the iterates by retaining the third-order Taylor expansion term.

Assuming a single dominant eigenvalue at the edge of stability, the instantaneous gradient at time step $t$ decomposes into three components: 1. The baseline gradient evaluated at the current iterate. 2. An oscillation component along the top eigenvector. 3. A sharpness reduction regularization term.

```mermaid flowchart LR accTitle: Central Flow Averaging accDescr: How taking time expectations cancels out fast oscillations while preserving the sharpness penalty.

A["Discrete Iterates in Oscillatory Regime"] --> B["Time Expectation E_t"] B --> C["High-frequency oscillations cancel to zero"] B --> D["Central Flow ODE: Gradient + Sharpness Penalty"] ```

When taking an expectation over time, the high-frequency oscillation terms cancel out to zero. The time-averaged differential equation is then governed by the base gradient alongside an explicit sharpness regularization penalty:

$$\frac{dw}{dt} = -\eta \nabla L(w) - \sigma^2(t) \nabla S(w)$$

Here, the sharpness penalty is modulated by an unknown time-dependent variance factor $\sigma^2(t)$, which reflects the amplitude of the oscillations along the maximum eigenvector. Kotha notes:

> “But if we were able to solve for what sigma squared t will be, then we can actually track the progress of gradient descent and see where the iterates are going, accounting for the fact that gradient descent is magically reducing the sharpness somehow.”

[16:29](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=989s) Deriving the Noise Schedule via Sharpness Invariance

To derive the functional form of the variance schedule $\sigma^2(t)$, central flow analysis relies on an empirical invariance: once training enters the edge of stability, the time-averaged sharpness ceases to grow and remains roughly constant around the stability threshold.

Enforcing this invariant mathematically means setting the total time derivative of sharpness to zero:

$$\frac{d S(w_t)}{dt} = 0$$

Applying the chain rule decomposes this total derivative into the inner product of the gradient of sharpness with respect to the parameters and the time derivative of the parameters:

$$\frac{d S(w_t)}{dt} = \nabla_w S(w_t)^\top \frac{dw_t}{dt} = 0$$

Substituting the central flow differential equation for $\frac{dw_t}{dt}$—which balances the standard loss gradient against the sharpness gradient scaled by the learning rate and the unknown oscillation magnitude $\sigma^2(t)$—yields an algebraic relationship. By setting this expansion to zero, one can directly solve for the explicit noise schedule $\sigma^2(t)$ required to keep the model pinned at the edge of stability.

[17:59](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1079s) Deriving the Central Flow Differential Equation

Suhas Kotha explains that by setting the sharpness derivative term to zero—reflecting the empirical reality that sharpness stops growing and stabilizes once it reaches a certain point—one can determine the exact noise schedule required to hold it steady. This combines the Taylor expansion reduction of deep learning dynamics with real-world observations to produce a differential equation tracking training. While standard gradient flow only captures first-order terms and breaks down entirely once training reaches the edge of stability, tracking the expectation of the weights and sharpness over time yields remarkably accurate theoretical predictions. The resulting differential equation models the expected moving average (EMA) of these critical optimization statistics, capturing the true macro-behavior of deep learning runs where standard continuous-time approximations fail.

```mermaid flowchart TD accTitle: Transition from Standard Gradient Flow to Central Flow accDescr: Diagram showing how standard gradient flow fails at the edge of stability, while central flow models the expected moving average by stabilizing sharpness.

subgraph StandardGF["Standard Gradient Flow"] A["First-Order Tracking<br/>(Gradient term only)"] --> B{"Edge of Stability<br/>Reached?"} B -->|"No"| C["Accurate Trajectory Predictions"] B -->|"Yes"| D["Dynamics Breakdown<br/>(Cannot capture oscillations)"] end

subgraph CentralFlow["Central Flow Dynamics"] E["Taylor Expansion + Noise Schedule"] --> F["Set dS/dt = 0<br/>(Sharpness stabilized)"] F --> G["Track Expectation of Weights & Sharpness"] G --> H["Accurate EMA Loss & Parameter Predictions"] end ```

- Standard gradient flow breaks down dynamically at the edge of stability because it only tracks first-order gradient terms. - Setting the rate of change of sharpness to zero yields a noise schedule matching empirical edge-of-stability stabilization. - The central flow differential equation tracks the expected moving average of network weights and sharpness rather than micro-oscillations.

---

[19:24](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1164s) Student Q&A: Oscillations, Predictive Surprises, and Double Descent

Opening the floor to questions, Kotha clarifies the fundamental premise of central flow when asked if its goal is merely removing the second-order Taylor term rather than eliminating oscillations. Kotha confirms that the technique incorporates the third-order term while deliberately averaging out the chaotic, high-frequency oscillations that make exact trajectory modeling intractable. When a student questions whether predicting flat sharpness is trivial because the derivative was set to zero by construction, Kotha clarifies that the real surprise lies elsewhere: the system accurately predicts the expected moving average of the loss amidst constant spiking, and successfully forecasts the trajectory of network outputs on single held-out examples over training.

Another student asks whether central flows could model or predict the double descent phenomenon. Kotha notes a distinction: double descent typically evaluates generalization as sample counts vary across separate runs, whereas central flow models optimization dynamics along a single trajectory. While an optimization run displaying an internal rise and fall of loss might conceptually be tracked by central flow, double descent fundamentally asks how much value can be squeezed out of limited samples, whereas the lecture's analysis operates in the standard deep learning class regime of one-pass training where data points are never repeated. Regarding loss spikes, Kotha adds that while the averaged differential equation cannot pinpoint exact micro-spikes, empirical observations confirm they coincide precisely with oscillations along top eigenvectors and sharp fluctuations in network predictions.

> “So it's to add the third term and then it's also to average out that second term. So to not reason about the oscillations because the oscillations themselves are like this extremely chaotic process that's really hard to model.” — *Suhas Kotha*

---

[22:52](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1372s) Multi-Eigenvector Extensions and the River Valley Mental Model

Extending the mathematical framework beyond a single direction, Kotha shows that solving the central flow equations jointly across all eigenvectors accurately predicts the evolution of every eigenvalue—both those pinned at the edge of stability and those remaining below the threshold. Standard gradient flow degrades rapidly over identical step intervals, whereas central flow accurately preserves the time-averaged output predictions on individual examples.

Kotha links this behavior directly to the "River Valley" analogy introduced in the previous lecture. In this landscape, gradient descent bounces aggressively back and forth between the steep valley walls along the sharp directions, producing chaotic motion. By tracking the expected moving average of the weights, central flow strips away the wall-to-wall bouncing and directly follows progress along the bottom of the riverbed. Because central flow strips out this bouncing noise, its raw trajectory actually predicts a lower loss and smaller gradient norm than what is observed in practice. However, because central flow precisely computes the sharpness at every step, one can add the predicted oscillation noise back into the loss and gradient norm, yielding an exact match to the empirical training run.

```mermaid flowchart LR accTitle: River Valley Mental Model of Central Flow accDescr: Flowchart illustrating how central flow separates valley floor progress from cross-wall oscillation noise to reconstruct true loss.

subgraph ValleyFloor["River Valley Floor (EMA)"] A["Expected Weight Trajectory"] --> B["Base Loss & Small Gradient Norm"] end

subgraph CrossWall["Sharp Direction (Walls)"] C["High Sharpness"] --> D["Chaotic Bouncing & Oscillation Noise"] end

B & D --> E["True Observed Trajectory<br/>(Higher loss spikes & gradient norm)"] ```

- Central flow extends jointly across all Hessian eigenvectors, predicting both stable and stabilizing eigenvalues over time. - The raw central flow tracks the valley floor, smoothing out chaotic wall-to-wall oscillations. - Re-injecting the model's calculated noise variance into the central flow recovers the exact empirical loss values and gradient norms observed during training runs.

---

[25:31](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1531s) Disentangling Movement Types and Summary of Edge of Stability

Kotha highlights an important nuance in the River Valley visualization by separating training movement into two distinct mechanisms that can easily be conflated. The first source of movement is the fast, wall-to-wall oscillation across the sharp direction. The second source is the slow evolution of the sharpness itself over the course of training: as sharpness rises above and dips below the stability threshold, it causes a subtle vertical bend in the valley walls, altering the height at which the optimizer bounces relative to the floor.

Wrapping up the theoretical foundations of edge of stability and central flow, Kotha contrasts classical theory with empirical neural network behavior. Under a standard quadratic model, if the learning rate or sharpness exceeds a critical threshold, optimization must diverge and blow up catastrophically. In sharp contrast, modern neural networks self-stabilize: as soon as sharpness crosses the edge of stability threshold, the network dynamics actively push the sharpness back down, entering a persistent regime of bounded oscillations right along the boundary.

> “So if you'll notice in this picture, there's actually a subtle bend across the height as you're moving across time. So there's both these oscillations along the sharp direction, but there's also oscillations on how far you are from the bottom of the floor because the sharpness itself is changing over the course of training.” — *Suhas Kotha*

- **Fast movement:** Rapid oscillations bouncing between steep walls along the sharp eigenvector direction. - **Slow movement:** Height shifts along the valley walls caused by the network's sharpness changing and self-stabilizing around the threshold. - **Quadratic model breakdown:** Classical convex quadratic analysis predicts unbounded divergence beyond the stability threshold, whereas neural networks depress their own sharpness and survive at the threshold.

[26:58](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1618s) Learning Rate Annealing and Progressive Sharpening at the Edge of Stability

By averaging parameters over time, one can construct an effective differential equation—the central flow—that traces the true underlying trajectory of the neural network without getting bogged down tracking every high-frequency oscillation. When an audience member asks how this framework interacts with learning rate annealing, a dual dynamic emerges. If the learning rate $\eta$ decreases slowly, the oscillation amplitude shrinks because it scales directly with $\eta$, bringing the trajectory tighter to the central path (the "river"). At the same time, because Edge of Stability (EoS) maintains a sharpness threshold around $2/\eta$, dropping $\eta$ raises the stability ceiling, causing the underlying landscape to grow progressively sharper.

```mermaid flowchart TD accTitle: Learning Rate Annealing Effects at Edge of Stability accDescr: Diagram illustrating how decreasing the learning rate simultaneously dampens trajectory oscillations and pushes the model toward sharper landscape regions.

subgraph Anneal["Learning Rate Annealing (η Decreases)"] A["Decrease Learning Rate η"] end

subgraph Effects["Simultaneous Dynamics"] B["Oscillation Dampening<br/>(Amplitude ~ η shrinks)"] C["Stability Ceiling Increases<br/>(2/η increases)"] end

subgraph Result["Landscape Trajectory"] D["Closer Tracking of Central Path ('River')"] E["Progressive Sharpening Drives Model<br/>to Sharper Minima"] end

A --> B A --> C B --> D C --> E ```

When an audience member presses for physical intuition beyond the mathematical ratio $2/\eta$—asking why the landscape would naturally get sharper rather than remaining where it is—Suhas Kotha and the audience reflect on the mysterious drive known as progressive sharpening. Optimization exerts a persistent, inherent tendency to push parameters into sharper territory until hitting the EoS barrier. As Suhas Kotha puts it: “Yeah, as far as I know we don't know why progressive sharpening happens. It's just like a thing.” He elaborates that progressive sharpening acts almost like an invisible force driving models toward sharper regions; once the model hits EoS, the self-stabilization mechanism halts further sharpening. When the learning rate is annealed downward, the allowable stability ceiling widens, allowing progressive sharpening to kick back in and push the parameters into even sharper regions.

- Tracking time-averaged parameters yields a continuous differential equation that describes macroscopic learning progress while filtering out high-frequency bounces. - Central flows provide accurate predictions for loss trajectories across diverse neural network architectures and data distributions. - Annealing the learning rate simultaneously suppresses the trajectory's oscillation amplitude and increases the local sharpness $2/\eta$.

[30:18](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=1818s) Bridging Full-Batch Theory to Adam: Momentum, Mini-Batches, and Adaptation

The clean theoretical guarantees established for Edge of Stability and central flows have largely been derived under the idealized assumption of full-batch gradient descent. Bridging the gap from full-batch gradient descent to practical modern optimizers like Adam requires addressing three missing pieces: the incorporation of momentum, the transition from full-batch to stochastic mini-batch gradient descent, and the adaptive coordinate-wise normalization of gradients by their running root-mean-square magnitude. While a fully unified theory combining all three components is still work in progress, their individual interactions reveal distinct mechanistic shifts.

Momentum functions by accumulating previous gradients across iterations via an exponential decay parameter $\beta$. Under full-batch gradient descent at the Edge of Stability, successive gradient vectors bounce across valley walls, exhibiting a cosine similarity of approximately $-1$. When expanding the momentum update as an infinite geometric series:

$$g_t + \beta g_{t-1} + \beta^2 g_{t-2} + \dots$$

The strict alternation in sign turns the summation into an alternating series where each step scales by $-\beta$. Summing this series yields an effective dampening factor of $\frac{1}{1 + \beta}$. Because the momentum accumulation damps these oscillating updates, the effective step size is reduced, allowing the optimization process to tolerate a higher curvature before becoming unstable. As Suhas Kotha notes: “And that means that the sharpness would increase by a factor of one plus beta.” Consequently, the critical sharpness threshold scales upward from $2/\eta$ to roughly $2(1 + \beta)/\eta$.

- Extending EoS analysis to Adam requires solving three components: momentum accumulation, mini-batch gradient noise, and adaptive preconditioning. - In full-batch gradient descent at EoS, successive gradients are anti-correlated (cosine similarity $\approx -1$). - Full-batch momentum damps bouncing gradients by $\frac{1}{1 + \beta}$, increasing the stable sharpness limit by a factor of $(1 + \beta)$.

[33:35](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=2015s) Mini-Batch SGD and the Noise-Dominated Momentum Regime

Switching from full-batch gradient descent to stochastic mini-batch gradient descent fundamentally alters gradient dynamics. In SGD, mini-batch sampling introduces significant stochasticity, plunging the optimizer into a noise-dominated regime. Rather than displaying an anti-correlated cosine similarity near $-1$, successive gradient updates have a cosine similarity near $0$, acting as largely independent, uncorrelated random variables rather than clean opposing vectors.

```mermaid flowchart LR accTitle: Full-Batch versus Mini-Batch Momentum Mechanics accDescr: Comparison of momentum accumulation under full-batch gradient descent versus stochastic mini-batch gradient descent.

subgraph FullBatch["Full-Batch Regime"] direction TB F1["Successive Gradients: Cosine Similarity ≈ -1"] F2["Alternating Sum: 1 - β + β² -..."] F3["Dampened by factor: 1 / (1 + β)"] F4["Sharpness Threshold Increases by (1 + β)"] F1 --> F2 --> F3 --> F4 end

subgraph MiniBatch["Mini-Batch Regime"] direction TB M1["Successive Gradients: Cosine Similarity ≈ 0"] M2["Independent Random Variables (Variance Sum)"] M3["Amplified by factor: 1 / (1 - β)"] M4["Sharpness Threshold Decreases by (1 - β)"] M1 --> M2 --> M3 --> M4 end ```

Because successive gradients behave independently rather than canceling each other out, the momentum calculation shifts from summing alternating vectors to accumulating the variance of independent terms:

$$\operatorname{Var}\left(\sum_{k=0}^{\infty} \beta^k g_{t-k}\right) = \sum_{k=0}^{\infty} \beta^{2k} \operatorname{Var}(g)$$

Summing the series in this uncorrelated setting results in a scaling amplification of roughly $\frac{1}{1 - \beta}$ on the effective step. As a result, momentum in small-batch SGD amplifies the noise and inflates the effective learning rate instead of dampening oscillations. This dynamic lowers the effective stability threshold by a factor of $(1 - \beta)$, creating the opposite effect of the full-batch case:

- Full-batch updates feature anti-correlated gradients (cosine similarity $\approx -1$), where momentum cancels out oscillations and increases the sharpness threshold by $(1 + \beta)$. - Mini-batch updates feature uncorrelated gradients (cosine similarity $\approx 0$), where momentum accumulates variance, amplifying step sizes by $\frac{1}{1 - \beta}$. - The amplified step size in the mini-batch regime depresses the sharpness threshold by $(1 - \beta)$ rather than raising it.

[035:37] Empirical Verification of Momentum and Stochastic Batch Regimes

Suhas Kotha points out that theoretical predictions regarding momentum ($\beta$) and batch size are verified in empirical deep learning experiments. In the full-batch setting, increasing momentum increases the stability threshold. In stark contrast, when operating in the small-batch regime (such as a batch size of 8), increasing momentum actually decreases the sharpness threshold. Suhas notes that students will explore these dynamics hands-on in their upcoming class assignment. While literature exists examining the noise-dominated regime for the edge of stability, an exact, fully solved theoretical account of mini-batch gradient descent under these conditions remains open:

> “There are some references here if you want to look at some current analyses of what the noise dominated regime would look like for edge of stability, but there isn’t like a full solved mini-batch version out there. So we’ll see when that happens.”

[036:41] Introducing Adaptivity: Scalar RMSprop and Effective Sharpness

Turning to the final piece of the optimization puzzle, Suhas introduces adaptivity, explaining that adaptive optimizers introduce subtle nuances in how they interact with the edge of stability. Taking the methodological approach of analyzing the simplest possible model before scaling up, he begins with **Scalar RMSprop**. Standard RMSprop or Adam tracks a coordinate-wise vector of squared gradients, but Scalar RMSprop maintains a single scalar estimate across all parameters. It uses an exponential moving average (EMA) parameter, $\beta_2$, to accumulate the squared gradient norms over time into a running average scalar, $\nu$. The gradient updates are then normalized by $\sqrt{\nu}$.

Under Scalar RMSprop, the step size is no longer the constant learning rate $\eta$, but rather an effective step size given by $\eta / \sqrt{\nu}$. In standard gradient descent, sharpness stabilizes around the threshold $2 / \eta$. In this adaptive setting, the quantity that stabilizes is the **effective sharpness**, denoted by $\frac{\eta S}{\sqrt{\nu}}$ (where $S$ is the top eigenvalue of the Hessian). Empirically, as the unnormalized running norm $\nu$ grows over training, the raw sharpness $S$ also climbs. However, the normalized effective sharpness stabilizes tightly around 2.

```mermaid flowchart TD accTitle: Scalar RMSprop Effective Sharpness Flow accDescr: Diagram illustrating how gradient norms feed into scalar RMSprop to establish effective step size and effective sharpness. subgraph Adaptivity["Scalar RMSprop Accumulation"] G["Squared Gradient Norm ||g_t||²"] -->|"EMA with β₂"| Nu["Running Variance ν"] Nu -->|"Square Root"| SqrtNu["√ν"] end subgraph Dynamics["Training Stabilization Dynamics"] SqrtNu -->|"Scales Learning Rate η"| Step["Effective Step Size: η / √ν"] Step -->|"Interacts with Raw Sharpness S"| EffS["Effective Sharpness: ηS / √ν ≈ 2"] end ```

[039:18] The Two Balancing Forces of Self-Stabilization in RMSprop

Adaptive methods alter self-stabilization because they introduce a second competing mechanism to control sharpness. In standard gradient descent, oscillations along the top eigenvector trigger an explicit sharpness regularization that suppresses the raw Hessian sharpness. Under RMSprop, this first force remains, but a second force emerges via the denominator:

> “So in RMSprop, there’s actually two forces that are going to self-stabilization rather than just one force, and this is like maybe the most important nuance of what adaptive methods do.”

When the model enters the oscillatory regime, the gradient norms abruptly spike. This surge in gradient magnitude accelerates the growth of the EMA term $\nu$. Because $\nu$ increases, the effective learning rate $\eta / \sqrt{\nu}$ automatically drops. Consequently, the effective sharpness drops due to the growth of $\sqrt{\nu}$ rather than a direct reduction in the physical curvature of the loss surface.

```mermaid flowchart LR accTitle: Two Forces of Stabilization in Adaptive Optimizers accDescr: Flowchart contrasting the two distinct forces that suppress effective sharpness in Scalar RMSprop. Osc["Oscillations at Edge of Stability"] --> Force1["Force 1: Physical Curvature Reduction"] Osc --> Force2["Force 2: Dynamic Step-Size Reduction"] Force1 -->|"Sharpness Regularization"| DecS["Reduces Raw Sharpness S"] Force2 -->|"Spikes Gradient Norms"| IncNu["Increases EMA ν → Shrinks η / √ν"] DecS --> Stab["Effective Sharpness ηS / √ν Stabilizes at 2"] IncNu --> Stab ```

The momentum parameter $\beta_2$ dictates which of the two forces dominates: - **Low $\beta_2$:** The running average $\nu$ responds rapidly to gradient spikes. Both forces act simultaneously, meaning the effective step size contracts quickly, allowing raw sharpness $S$ to continue climbing while effective sharpness remains bounded. - **High $\beta_2$:** The running average $\nu$ adapts very sluggishly to gradient spikes. The second force is effectively disabled, leaving only the primary sharpness regularization force. As a result, effective sharpness takes longer to stabilize, and the terminal raw sharpness of the model settles at a much lower value.

[042:39] Central Flows for Scalar RMSprop

Suhas notes that a naïve gradient flow analysis of an adaptive optimizer—which leaves out higher-order Taylor expansion terms—predicts that effective sharpness blows up without bound, entirely missing the edge-of-stability phenomenon. To capture the true trajectory, one must derive a **Central Flow** for Scalar RMSprop that models both the time-averaged trajectory and the oscillation dynamics.

This framework maintains two coupled components: 1. A continuous differential equation for the parameter weights that combines the gradient of the loss with an explicit sharpness regularization drift term, scaled by the time-varying effective learning rate $\eta / \sqrt{\nu}$. 2. A differential equation tracking the growth of the running variance $\nu$, which is driven upward by the magnitude of the oscillations along the top eigenvector.

By matching the theoretical expansion with the empirical constraint that effective sharpness remains pinned at 2, one can uniquely solve for the oscillation magnitude schedule $\sigma^2(t)$. The resulting continuous RMSprop central flow accurately reproduces experimental trajectories: it tracks loss descent, accurately predicts the growth curve of raw sharpness $S$, accounts for the expansion of $\nu$, and preserves the constant effective sharpness invariant throughout training. In short, Scalar RMSprop continually tunes its own effective step size to operate safely at the absolute edge of stability.

[45:31](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=2731s) Adaptive Optimizers and Sharpness Regularization in Scalar RMSProp

Suhas Kotha explains that scalar RMSProp operates by stabilizing the second-moment accumulator $\nu$ such that the invariance condition holds, aligning the step size to roughly $2/S$, where $S$ denotes sharpness. This dynamic adjustment ensures that the optimizer applies the correct step size relative to the local sharpness of the training landscape at any given time. Providing intuition for practitioners, Kotha highlights: “So, when people talk about adaptive optimizers, this is one intuition for what adaptive optimizers actually are. They're like effectively maintaining their like their their new state such that the step adapts to the exact sharpness of the landscape that you're training on.”

However, step size adaptation is only half the story. As weights evolve under this $2/S$ regime, the system simultaneously undergoes an implicit sharpness regularization term. In scalar RMSProp, two complementary mechanisms operate at once: 1. The step size continuously adapts to match the landscape sharpness. 2. The implicit regularization actively pushes sharpness downward throughout training.

```mermaid flowchart LR accTitle: Dual Mechanics of Scalar RMSProp accDescr: Diagram illustrating how scalar RMSProp combines step size adaptation and sharpness reduction to accelerate loss minimization. subgraph Mechanics["Scalar RMSProp Optimization"] A["Accumulator &nu; Stabilizes"] --> B["Step Size Adapts to 2/S"] A --> C["Implicit Sharpness Regularization"] end B --> D["Stable, Faster Loss Decay"] C --> D ```

---

[46:58](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=2818s) Ablating Sharpness Regularization and the True Role of Learning Rate

Using the central flow formulation, one can conceptually ablate the implicit sharpness regularization term while retaining step size adaptation to observe the consequences. When central flow incorporates both effects, it closely tracks empirical scalar RMSProp. However, removing the implicit sharpness reduction term causes the loss to decrease far more slowly. Without that regularization, sharpness escalates significantly over training. Because $\nu$ grows and sharpness rises, the effective step size decays rapidly, dragging down optimization speed. RMSProp must therefore navigate a balance: it must adapt to the landscape while actively depressing sharpness, since flatter regions allow larger steps and faster progress.

This dynamic clarifies a common misconception about the learning rate in Adam and RMSProp. Higher learning rates accelerate optimization not simply by taking wider parameter jumps—since updates are scaled inversely by $\sqrt{\nu}$—but by amplifying sharpness regularization. As Kotha summarizes: “If you have a higher learning rate in Adam or RMS prop what's actually going on is that you're increasing your sharpness regularization and by increasing the sharpness regularization, you're increasing your effective step size. And that's the method in which increasing your learning rate actually accelerates training, but it's not necessarily just because you're taking bigger updates.”

---

[49:27](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=2967s) Extending Central Flows to Coordinate-Wise RMSProp

Kotha advances from scalar RMSProp to full coordinate-wise RMSProp, where effective step sizes are normalized per parameter rather than globally across all weights. Full RMSProp functions as diagonal preconditioning, rescaling each entry of the gradient update by the learning rate divided by $\sqrt{\nu}$ (or equivalently, scaling the update by a diagonal matrix $P$). In empirical runs, full RMSProp exhibits far fewer aggregate loss spikes than plain gradient descent, yet individual coordinate trajectories continue to display high-frequency oscillations. Analyzing the eigenvalues of the effective, preconditioned Hessian demonstrates that coordinate-wise RMSProp also operates at the Edge of Stability.

```mermaid flowchart TD accTitle: Preconditioning in Full RMSProp accDescr: Flow showing how per-coordinate gradient scaling relates to the effective preconditioned Hessian and stability bounds. subgraph Precond["Coordinate-Wise Preconditioning"] G["Gradient &nabla;L"] --> P["Rescale by &eta; / &radic;&nu;"] P --> H["Effective Hessian H_eff"] end H --> E["Eigenvalues Satisfy Edge of Stability"] ```

---

[51:54](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3114s) RMSProp's Stationary Preconditioner as a Constrained Optimization Program

Deriving the central flow for full RMSProp reveals that the stationary preconditioner $P$—which stabilizes over training toward $\text{diag}(\sqrt{\nu}/\eta)$—solves an underlying constrained optimization program. The program incorporates explicit terms balancing stability and training throughput:

* **Stability Constraint:** It constrains the eigenvalues of the preconditioned Hessian to lie beneath the stability threshold (below $2$ over the effective step size), ensuring stable progression across all directions. * **Trace Minimization ($\text{Tr}(P)$):** The trace of $P$ corresponds to the sum of the reciprocals of the coordinate learning rates. Minimizing $\text{Tr}(P)$ drives up the effective step sizes across all coordinates simultaneously.

Discarding the second term and removing the diagonal restriction causes the solution of this optimization program to become the Hessian itself. Kotha observes: “So this is in some sense as close as you can get to doing the Hessian if you're going to constrain yourself to be doing diagonal training.” Conversely, the remaining term in the joint program incorporates the magnitude of the gradient, which exerts an opposing drag on optimization speed. Full RMSProp represents the dynamic compromise of minimizing this combined program.

[54:43](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3283s) Central Flows, Adaptive Methods, and the Trade-Offs of Sharpness Reduction

When analyzing optimizers like RMSprop through the lens of continuous central flows, the dynamics can be decomposed into distinct driving forces. If an algorithm were able to optimize purely for descent along the loss without side effects, training could proceed much faster. However, practical algorithms normalize the gradient on every update, modulating the effective step size so that the effective sharpness self-stabilizes. This process introduces a core duality: the optimizer adapts to the local curvature of the loss landscape, but it also implicitly reduces sharpness.

```mermaid flowchart LR accTitle: Trade-off of Adaptive Optimization accDescr: Visualizing how per-step gradient normalization adapts step size, stabilizes effective sharpness, and affects training speed. subgraph Dynamics ["Per-Step Dynamics"] direction TB A["Normalize Gradient"] --> B["Modulate Effective Step Size"] B --> C["Stabilize Effective Sharpness"] end subgraph Effects ["Optimizer Trade-offs"] direction TB C --> D["Adapts to Curvature<br/>(Enables higher step size)"] C --> E["Implicitly Reduces Sharpness<br/>(Minimizes learning speed)"] end ```

While reducing sharpness is mathematically annoying to reason about, it is fundamentally beneficial because it prevents instability, boosts the allowable effective step size, and lets models train stably for longer horizons. By examining what the central flow optimizes over the entire trajectory, researchers can formally analyze how closely adaptive algorithms like RMSprop mimic true second-order methods, opening avenues for future algorithm designs that attain speedups without unintentionally throttling their own training velocity.

[55:55](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3355s) Edge of Stability: Limitations, Open Questions, and Coursework

Although Edge of Stability (EOS) theory offers powerful predictions, several unresolved gaps remain where the theory does not cleanly hold: - **Loss functions**: Most theoretical derivations assume mean squared error (MSE); the behavior is considerably less clean under standard cross-entropy loss. - **Batch sizes and modern optimizers**: The theory has not been completely solved for finite mini-batch settings, nor for modern production optimizers that string together multiple adaptive components and momentum terms. - **High learning rates**: The central flow approximation can break down entirely when learning rates become excessively large. - **Progressive sharpening**: The foundational cause of progressive sharpening in deep networks remains an open mystery. As Suhas notes, referring to co-instructor Tatsunori Hashimoto: “As Tatsu said, nobody really knows why. It's just like some magic fact that happens, and this is something that we don't have a good model or theoretical explanation for, so that would be really nice.”

In upcoming homework assignments, students will train models using the course's standard recipe, track how sharpness evolves, test whether and where edge-of-stability dynamics emerge, and develop an empirical intuition for how various hyperparameters shift the stability boundary. Kotha jokes with the class that any student who manages to theoretically explain progressive sharpening in their assignment will receive substantial extra credit, remarking, “I hope that's not controversial the course staff, yeah.”

[57:21](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3441s) Motivation: Sharpness in Compute vs. Data-Limited Generalization

Sharpness matters for two primary reasons in deep learning: 1. **Optimization speed (compute-limited regime)**: Sharpness dictates the effective learning rate and governs how fast training progresses without blowing up. 2. **Generalization (data-limited regime)**: Unlike the earlier part of the course where models train on unlimited data streams for a fixed step count (meaning validation and training losses track each other almost identically), real-world setups often feature a constrained sample budget.

In limited-data settings, repeatedly cycling through training data allows training loss to drop continuously while validation loss begins to diverge due to overfitting. A long-standing intuition in deep learning suggests that flatter minima generalize better than sharper ones. The standard mental model imagines separate training and test loss landscapes. Because these surfaces differ slightly under limited data, a flat basin ensures that small perturbations between train and test distributions cause minimal degradation in performance, whereas sitting inside an overfitted, razor-sharp minimum can result in catastrophic loss spikes upon slight evaluation shifts.

```mermaid flowchart TD accTitle: Generalization under Shifted Landscapes accDescr: Contrasting flat and sharp minima when evaluating training versus test landscapes. subgraph FlatMin ["Flatter Minimum"] F1["Training Loss Basin"] -->|"Distribution Shift"| F2["Test Loss: Small Penalty"] end subgraph SharpMin ["Sharp Minimum"] S1["Overfitted Training Well"] -->|"Distribution Shift"| S2["Test Loss: Severe Spike"] end ```

[59:35](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3575s) The Murky Reality: Metric Correlations, Counterexamples, and Knobs

Despite the appealing narrative surrounding flat minima, the empirical reality remains fraught with contradictions: - **Empirical studies**: In the paper *Fantastic Generalization Measures*, researchers evaluated massive sweeps of models against dozens of theorist-proposed predictors (such as weight norms and spectral bounds). Sharpness emerged as one of the most promising predictors of generalization performance, though as Kotha observes, “In fact, the author I believe he gets really mad if you say that sharpness is the one that all works because he thinks that these work. But at least sharpness is one of the more promising contenders.” - **Conflicting evidence**: Other empirical studies find either zero correlation or direct negative correlations where sharper minima yield superior test accuracy over flatter ones. - **The reparameterization issue**: Sharpness, as measured via the Hessian, depends entirely on how the network is parameterized. One can rescale weights to change the curvature arbitrarily without altering the underlying mathematical function computed by the network, making raw sharpness a tricky and sometimes misleading diagnostic. - **Control knobs**: Prior to explicit sharpness-targeted algorithms, practitioners relied on crude levers to force models toward flatter regions, primarily by raising the learning rate (driving larger oscillations that bounce out of sharp ravines past the $2/\eta$ threshold) or lowering the batch size to inject gradient noise.

[01:02:44](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3764s) Sharpness-Aware Minimization (SAM) and Neighborhood Loss

While standard optimizers merely observe sharpness or modify hyperparameters indirectly, a distinct class of optimization algorithms directly targets sharpness. The primary method in this space is Sharpness-Aware Minimization (SAM). The core intuition aligns directly with the geometric concept of flat minima: rather than simply seeking a parameter configuration that achieves low loss at a single point, the optimizer searches for weights where the entire surrounding neighborhood achieves low loss. If every point in a local ball around the current weights retains good loss, the model must reside in a flat region; conversely, if the neighborhood suffers from high loss while the center looks favorable, the optimizer has landed in a sharp minimum.

```mermaid flowchart LR accTitle: SAM Optimization Mechanics accDescr: Diagram illustrating how Sharpness-Aware Minimization finds a worst-case perturbation before taking its gradient step. subgraph LocalNeighborhood["Neighborhood Search"] A["Current Iterate w"] -->|"Find worst-case in ball"| B["Perturbed Point w + ε"] end subgraph UpdateStep["Gradient Update"] B -->|"Evaluate loss & gradient"| C["∇L(w + ε)"] C -->|"Update weights"| D["Next Iterate w'"] end ```

Mathematically, SAM operationalizes this concept by evaluating the gradient not at the current iterate, but at the worst-case loss found within a small ball around the current weights. Although connected theoretically to minimizing the maximum eigenvalue of the Hessian, SAM computes this dynamically by identifying a point in the neighborhood that produces poor loss and stepping against that worst-case adversary. In benchmark evaluations, SAM demonstrates clear wins over standard stochastic gradient descent (SGD). This advantage becomes particularly pronounced in difficult generalization regimes, such as when substantial label noise is introduced. As Suhas Kotha points out:

> “And SAM does like a lot better than like plain SGD in these types of regimes, especially as you increase the amount of label noise.”

- SAM replaces the objective $\min_w L(w)$ with an adversarial neighborhood objective $\min_w \max_{\|\epsilon\| \le \rho} L(w + \epsilon)$. - In experimental comparisons against SGD, SAM consistently delivers lower loss across diverse benchmarks. - SAM proves exceptionally resilient when trained on corrupted datasets, such as setups where 20% of data labels are randomly altered.

---

[01:04:35](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3875s) What Does SAM Actually Optimize? The Small Batch Surprise

Despite being conceived as a direct method for minimizing sharpness, SAM exhibits a thorny gap between theoretical motivation and empirical reality. In deeper theoretical investigations—such as papers examining SAM's ability to efficiently improve generalization—researchers found that SAM actually performs best when the batch size is minimized rather than run in full-batch mode. In fact, setting the mini-batch size down to $m = 1$ yields the strongest generalization gains.

This finding complicates the original narrative. When analyzing the batch-size-one regime, mathematical proofs reveal that SAM does not actually minimize the worst-case perturbation or the maximum eigenvalue of the Hessian; instead, it optimizes against an average-case perturbation, effectively evaluating a randomly sampled point within the local ball. The fact that SAM functions best under dynamics that diverge from its original design illustrates a pervasive pattern across machine learning research. As Suhas Kotha reflects:

> “That algorithm kind of works well and people don't know why and they find that it works for completely different reason than originally posited and then they analyze that instead.”

- Papers analyzing SAM's mechanics demonstrate that its empirical peak occurs at very small batch sizes ($m = 1$), rather than in full-batch optimization. - At batch size one, SAM minimizes average-case neighborhood loss rather than worst-case sharpness or top Hessian eigenvalues. - This discrepancy highlights a classic deep learning research cycle: researchers construct an intuitive toy model, invent an approximating algorithm, discover that it works for reasons unrelated to the premise, and subsequently re-theorize the phenomenon.

---

[01:06:05](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=3965s) Sharpness-Aware Pre-training and Fine-Tuning Robustness

Even when an optimization heuristic rests on flawed initial assumptions, it can yield powerful practical tools. One notable application appears in the paper *Sharpness-Aware Pre-training*, which explores the downstream stability of language models. The hypothesis is straightforward: if pre-training guides a model into a flatter basin of the loss landscape, subsequent fine-tuning updates will not aggressively displace the weights into entirely different loss regimes, thereby mitigating catastrophic forgetting of pre-training knowledge.

To test this, researchers pre-trained language models using either standard AdamW or SAM. While the baseline pre-training loss achieved by SAM was slightly worse or roughly equivalent to AdamW, the post-fine-tuning results revealed a stark contrast. Models trained with AdamW suffered extensive forgetting on the core pre-training distribution, whereas models optimized via SAM retained their original capabilities far more effectively. Practitioners can also modulate sharpness indirectly without SAM's computational overhead simply by elevating the learning rate, since the edge-of-stability threshold caps sharpness around $2/\eta$. Elevating $\eta$ forces the optimizer toward flatter minima, creating a Pareto-dominant tradeoff between pre-training loss and fine-tuning transferability. Suhas Kotha underscores how this upends conventional evaluation practices:

> “This is one of the few like I would say few examples where pre-training loss actually doesn't give you a good prediction for how good your model is because if you know you're going to fine-tune the model afterward, instead of only caring about your loss, it's also important to care about your sharpness over here because that affects how well like stable and like how good the fine-tuning dynamics also look like.”

- Language models pre-trained with SAM exhibit significantly less catastrophic forgetting during downstream fine-tuning compared to those trained with AdamW. - Raising the learning rate $\eta$ indirectly forces lower sharpness due to the $2/\eta$ stability boundary, trading off pure pre-training training loss for superior transfer robustness. - Validation loss on pre-training data is insufficient on its own to forecast downstream performance; landscape geometry and sharpness dictate fine-tuning resilience.

---

[01:08:42](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=4122s) Testimonials from the Field: The Alchemy of Researching Sharpness

Addressing the broader conceptual standing of sharpness, Suhas Kotha frames it as one of the softest, most frustrating mental models in deep learning alchemy. To capture the emotional reality of working in this area, Kotha gathered testimonials from PhD peers who devoted portions of their graduate studies to studying sharpness and flat minima. The reactions reveal a polarized landscape: one subset of researchers finds sharpness intensely fascinating and productive for motivating new pre-training heuristics, while another camp feels deeply misled by its elusive definitions.

The classroom erupted in laughter as Kotha shared the sentiment that many feel they spent years of their lives chasing a mysterious object without making concrete progress. Sharpness serves as a quintessential cautionary tale for deep learning practitioners. If approached with the strict mathematical expectations of a formal theorem, it inevitably leads to dead ends; however, when treated as an imperfect, qualitative heuristic, it can guide practitioners toward effective algorithms. Suhas Kotha summarizes the necessary mindset when navigating this territory:

> “I think this is really like the closest you can get to like the alchemy of these things where it's like it is like a useful mental model and like ways that you can't really predict, but a lot of the times if you like really strictly obey it the same way that you'd like obey a theorem or a result in a math class, you're just going to be completely in like a wrong place and be all like you're going to have a horrible time.”

- Peer testimonials highlight divergent experiences: some celebrate sharpness as an invaluable compass for algorithm design, while others express regret over chasing ambiguous, non-predictive formulations. - Sharpness exemplifies the "alchemy" of deep learning, functioning as a heuristic that generates useful algorithmic intuition even when formal mathematical predictions break down.

[01:10:18](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=4218s) Controlling Sharpness: Convergence Speed, Generalization, and Algorithmic Design

Suhas Kotha ties together the practical implications of sharpness and the edge of stability, pointing out how restricting sharpness can directly accelerate convergence and increase overall training speed. Beyond faster optimization, he notes there are certain settings where managing sharpness yields measurable benefits for generalization performance. While practitioner interest often leans toward directly optimizing sharpness, doing so in practice remains deeply challenging: researchers and engineers currently understand how various hyperparameters interact with sharpness empirically, yet lack precise levers to modulate it on command.

Being able to explicitly dial in the sharpness of a loss landscape would be transformative for deep learning workflows, offering significant payoffs in compute efficiency, training velocity, and downstream generalization. Furthermore, Kotha stresses that conceptualizing training through the lens of sharpness provides a valuable mental model when formulating practical algorithms, especially in targeted domains like model fine-tuning.

As Suhas Kotha puts it regarding the missing control knobs in modern training: “We guess we have an understanding of how the hyperparameters interact with it, but we don't have a great way of directly modulating the sharpness itself, which would be pretty big in terms of like compute like training speed and generalization if you could directly control the sharpness to be the value that we care about.” He then opens the floor for any final questions before concluding the lecture.

- **Edge of Stability & Speed**: Limiting landscape sharpness allows for accelerated convergence and faster training throughput. - **Generalization Benefits**: Managing sharpness can lead to better downstream model generalization under specific, bounded conditions. - **Modulation Challenge**: While hyperparameter heuristics provide indirect influence, there is currently no robust mechanism to directly modulate sharpness to a target value. - **Mental Framework**: Sharpness dynamics serve as a foundational mental model for designing modern machine learning algorithms, particularly fine-tuning protocols.

## Notable quotes > [46:58](https://www.youtube.com/watch?v=Om_E0KNlXrE&t=2818s) If you have a higher learning rate in Adam or RMS prop what's actually going on is that you're increasing your sharpness regularization and by increasing the sharpness regularization, you're increasing your effective step size. — Suhas Kotha

## Mentioned Stanford University, CS312: Deep Learning Alchemy, Suhas Kotha, Percy Liang, Tatsunori Hashimoto, Jeremy Cohen, Alex Damian, Sharpness-Aware Minimization (SAM), CIFAR, Adam, RMSprop, AdamW, SGD, Nesterov, Scalar RMSprop, Fantastic Generalization Measures, Sharpness-Aware Pre-training

## Video description Browse Stanford's online courses in deep learning: https://stanford.io/4zhLWFN

Why does training keep running at the edge of stability instead of blowing up? In this Stanford CS312: Deep Learning Alchemy lecture, Suhas Kotha covers sharpness, self-stabilization, and flat minima, including the edge of stability phenomenon, central flows, and sharpness-aware minimization (SAM).

Questions this lecture covers: - What is the edge of stability in neural network training? - How does gradient descent self-stabilize when sharpness gets too high? - Do flat minima generalize better than sharp minima? - What is sharpness-aware minimization (SAM)?

About the speaker: Suhas Kotha is a Computer Science PhD student at Stanford advised by Percy Liang and Tatsunori Hashimoto, researching language model pre-training, including how to train when compute is abundant relative to data. Suhas co-created CS312: Deep Learning Alchemy and previously studied at Carnegie Mellon University.

Readings: - Edge of Stability: https://arxiv.org/abs/2103.00065 - Central Flows: https://arxiv.org/abs/2410.24206 - SAM: https://arxiv.org/abs/2010.01412

Course website: https://deep-learning-alchemy.github.io/ Watch the full CS312 playlist: https://www.youtube.com/playlist?list=PLXRTcAYPI4AU

Recorded October 15, 2026, in CS312: Deep Learning Alchemy, a Stanford University course taught by Tatsunori Hashimoto and Suhas Kotha.

#DeepLearning #Optimization

[Source](https://www.youtube.com/watch?v=Om_E0KNlXrE)

Reading summary

Suhas Kotha presents the Edge of Stability framework, showing that deep neural networks breach classical quadratic stability bounds without diverging by actively self-stabilizing around a critical sharpness threshold. While theoretical constructs like central flows explain how curvature and step size interact in gradient descent and adaptive optimizers, empirical tools like Sharpness-Aware Minimization demonstrate that managing landscape sharpness directly impacts optimization velocity and fine-tuning generalization. Self-Stabilization at the Edge of Stability (2:23) Classical optimization theory based on convex quadratics dictates that gradient descent diverges when sharpness—measured by the Hessian matrix's maximum eigenvalue $\lambda_{\max}$—exceeds the stability threshold of $2/\eta$. In deep neural networks, however, empirical tracking reveals that sharpness steadily increases during training until it crosses $2/\eta$. Rather than exploding toward infinity, networks enter a self-stabilizing regime where iterates oscillate rapidly between the steep walls of a loss valley along the leading eigenvector, causing sharpness to peak, drop, and settle into a dynamic equilibrium around $2/\eta$. This behavior disproves the traditional cartoon of optimization smoothly traversing a convex interior. Instead, optimization bounces along the boundary of instability. Lowering the learning rate $\eta$ mechanically elevates the $2/\eta$ ceiling, driving the network to equilibrate at progressively higher sharpness plateaus. Taylor expansions show that this stabilizing counterforce originates in the third-order expansion term, which acts as a negative gradient on sharpness itself. Central Flows and Time-Averaged Trajectories (12:51) Continuous-time gradient flow models fail precisely where training reaches the Edge of Stability because standard first-order approximations predict runaway divergence past $2/\eta$. To overcome this limitation, researchers model optimization trajectories using central flows. By accounting for the third-order Taylor term and taking expectations over time, central flows average out high-frequency cross-valley oscillations to reveal the macroscopic parameter drift along the floor of the loss basin. The central flow differential equation pairs the standard loss gradient with an explicit sharpness regularization penalty modulated by an oscillation variance term $\sigma^2(t)$. Because empirical sharpness ceases growth once it reaches the Edge of Stability ($dS/dt = 0$), theorists can explicitly solve for the required noise schedule. When multi-eigenvector dynamics are accounted for, central flow accurately predicts the moving averages of loss, parameter states, and output predictions on individual examples. Momentum Regimes and Adaptive Curvature Balancing (30:18) Bridging idealized full-batch theory to practical optimizers exposes diverging mechanics across momentum and batch regimes. In full-batch optimization, consecutive gradients oscillate with a cosine similarity near $-1$, forming an alternating series dampened by $1/(1+\beta)$ and raising the tolerable sharpness bound to approximately $2(1+\beta)/\eta$. In contrast, stochastic mini-batch settings yield nearly uncorrelated gradients with cosine similarity near $0$, amplifying variance by $1/(1-\beta)$ and lowering the stability threshold as momentum increases. Under adaptive optimizers like RMSprop, the quantity that stabilizes is the effective sharpness, $\eta S / \sqrt{\nu}$, which settles around 2. Adaptive methods control curvature via two competing forces: physical reduction of Hessian sharpness and dynamic reduction of the effective step size when gradient spikes inflate the running second-moment scalar $\nu$. Extended to coordinate-wise updates, RMSprop acts as a stationary preconditioner that balances eigenvalue stability constraints against trace minimization to maximize coordinate-wise learning rates. Generalization Realities and Neighborhood Minimization (57:21) In data-limited regimes, flatter minima are hypothesized to generalize better because slight distribution shifts between training and test loss basins yield smaller performance degradations. However, Kotha emphasizes that empirical evidence remains contradictory: reparameterizing network weights can arbitrarily rescale Hessian eigenvalues without altering the underlying function, and certain benchmarks show uncorrelated or negative relationships between flatness and test accuracy. Sharpness-Aware Minimization (SAM) attempts to directly enforce flatness by computing updates on worst-case loss perturbations within a local parameter ball. Curiously, SAM achieves its strongest empirical generalization gains at a mini-batch size of $m=1$, where theoretical analysis proves it actually minimizes average-case neighborhood loss rather than worst-case Hessian sharpness. Despite this theoretical gap, flat-basin methods like SAM and high-learning-rate training demonstrate tangible utility in language model pre-training, significantly mitigating catastrophic forgetting during downstream fine-tuning. Theoretical frameworks for the Edge of Stability and central flows still exhibit critical blind spots. Current derivations largely depend on mean squared error loss and idealized batching, leaving behavior under cross-entropy loss, modern multi-component optimizers, and finite mini-batches incompletely solved. Most fundamentally, the underlying driver of progressive sharpening—why deep models naturally drift toward sharper landscapes in the first place—remains an unexplained mystery.

Source quotes

[46:58] Suhas Kotha: If you have a higher learning rate in Adam or RMS prop what's actually going on is that you're increasing your sharpness regularization and by increasing the sharpness regularization, you're increasing your effective step size.

Original transcript

[0:05] So we are finishing up our last lecture [0:08] on optimization. So for optimization [0:09] two, this is our second lecture on lost [0:11] landscapes and we're covering mostly [0:13] sharpness and most of this lecture will [0:15] be dedicated to like the this phenomenon [0:16] called adjustability. Uh before we get [0:18] into it, just some couple of [0:19] announcements. One is that tutorials are [0:22] going to start uh starting the first set [0:24] of tutorials is going to be this [0:25] evening. You should have received an [0:26] email. You might have been rescheduled [0:28] if you needed to be rescheduled, but uh [0:29] you just show up to your [0:31] your tutorial. Uh just be prepared to [0:33] talk about assignment two and quiz two. [0:35] So just have an understanding of what [0:36] you did for that and what you did on the [0:38] quiz and also just come prepared with [0:40] maybe like a question or two about what [0:41] you did on that assignment just to make [0:43] sure you're like familiar with that [0:44] content. [0:46] Okay, great. So as an overview of what [0:48] we're covering today, we're going to [0:49] study mostly sharpness [0:51] and uh there's going to be three rough [0:53] things that we're covering. First, we're [0:54] going to be covering the adjustability, [0:56] which is this uh like theoretical [0:58] empirical framework that covers how [0:59] sharpness evolves over the course of the [1:01] training run. [1:02] And uh we're going to be starting with [1:05] basically analyzing a very simple [1:06] algorithm. So we'll be analyzing like [1:07] full batch plain gradient descent, [1:09] basically the simplest algorithm you can [1:11] come up with. And then afterward, we'll [1:12] be analyzing the interaction between the [1:15] like basic framework and how it [1:16] interacts with modern optimizer [1:17] components like momentum, adaptivity, [1:20] uh and batch size. [1:22] And uh just for context, we're going to [1:24] be really closely following this [1:25] tutorial. So this adjustability line of [1:27] work has been led by two main [1:28] researchers, Jeremy Cohen and Alex [1:30] Damian, and they're both incredible [1:32] researchers and even more than that, [1:33] they're incredible communicators. So uh [1:35] this lecture will be heavily following [1:37] this tutorial if you want to read it [1:38] yourself. If the lecture is good, it's [1:40] because of this and if it's bad, it's [1:42] because of me. So just [1:44] make sure you're aware of that. [1:44] [laughter] [1:46] Um, uh, the next thing we're going to be [1:49] covering is this is going to be slightly [1:51] away from the standard setting that [1:52] you're used to but we're going to be [1:53] thinking about how sharpness influences [1:54] model performance when you're limited by [1:56] data rather than when you're limited by [1:58] the number of steps that you're taking [1:59] on the [2:00] So this is going to touch on some [2:01] concepts that are in the generalization [2:02] unit. It's not something that you're [2:03] strictly going to be studying [2:04] specifically inside of [2:06] this assignment, but it's like good to [2:07] be aware of. [2:09] And finally we're going to cover this [2:10] like fun way like now that we know that [2:12] sharpness is an important thing and we [2:13] can analyze what's going on with [2:14] sharpness, how can we actually optimize [2:16] for it or control it during the training [2:17] procedure and covering optimizers and [2:19] things. [2:22] Cool. [2:23] So now we can start going over the [2:26] traditional intuition. So if you think [2:28] about optimization similar to like our [2:30] noisy quadratic model, let's say that we [2:32] had a function that we're trying to [2:33] optimize 1/2 SX squared. [2:35] Uh in this case like if you were [2:36] thinking about the sharpness, the [2:38] sharpness would be S or like the as [2:41] we've been referring to so far the [2:42] sharpness is the maximum eigen value of [2:44] the Hessian. [2:45] So in this case intuitively you don't [2:47] want to set set the learning rate too [2:48] high. If you set the learning rate small [2:50] enough according to the standard like [2:51] convex optimization, you're going to [2:53] converge to the minimum by taking steps [2:55] that get you closer and closer. But if [2:57] you set your step size too large, what [2:58] might happen is that you're just going [3:00] to oscillate out and basically go away [3:02] from the minimum. And this is the [3:03] standard intuition for how gradient [3:05] descent works on quadratics. And if you [3:07] have this intuition, you might have the [3:09] like what you'll notice is that [3:12] you like for if you're optimizing a [3:13] quadratic and you set the learning rate [3:15] too high [3:16] for any of the directions. So you have [3:17] like the eigen values of the Hessian for [3:19] all of the directions and if any of [3:21] those directions has the learning rate [3:22] too high such that the sharpness is [3:25] above two over Ada, then your training [3:27] run is going to diverge and you're going [3:29] to oscillate in one of these directions. [3:31] Usually we the only reason we care about [3:33] the maximum eigen value is because [3:34] that's the limiting factor. Your [3:35] learning rate can like has to be such [3:37] that you're not unstable along the [3:39] maximum eigen vector. [3:42] So if you have this intuition about how [3:44] deep learning works, you might believe [3:46] that [3:47] what happens in actual training is that [3:49] the sharpness stays under a specific [3:51] threshold. So we talked about this [3:53] threshold two over Ada and if Ada was [3:55] such that the sharpness was higher than [3:56] this threshold, then training would be [3:58] unstable. So you might believe that all [4:00] of deep neural network training operates [4:02] in this regime where you stay stable and [4:04] you never actually exit this region [4:06] where the sharpness is greater than two [4:07] over eight. [4:10] So if you were to take this to a real [4:12] deep learning run, if you saw this deep [4:14] learning run where the training loss is [4:15] slowly going down, what you'll observe [4:17] empirically is that the sharpness is [4:18] going up and at some point the sharpness [4:21] might exceed this two over eight a [4:22] threshold. So for your learning rate it [4:24] might go above and then after you see [4:26] this region you might be really [4:27] concerned and you might be worried that [4:29] the whole run is going to blow up at [4:30] this point because now you're past the [4:32] stable region. [4:34] So if you like really zoom in what [4:36] happens when you get into this region is [4:39] the sharpness keeps climbing and you can [4:41] also notice that the model is also [4:43] oscillating. So here we're measuring the [4:44] displacement along the top Hessian [4:46] eigenvector, basically how far the model [4:48] is moving in that direction. So if [4:50] you're thinking about the river valley [4:52] like the valley is the sharpest [4:54] direction and this oscillation is [4:55] suggesting that you're oscillating along [4:57] this direction during training and this [4:59] happens specifically when the sharpness [5:01] exceeds that two over eight a threshold. [5:03] So you might see this and you might be [5:05] really concerned being like the training [5:06] run is going to blow up and it's going [5:07] to completely diverge at this point. [5:12] Interestingly, empirically what happens [5:14] is that the sharpness magically goes [5:15] down. After it exceeds this threshold [5:18] for some reason the sharpness goes back [5:20] down at which point it will return back [5:22] up again, but it does go back down [5:25] first and the oscillations actually [5:27] decrease at this point as well. [5:30] So if you put this all together to look [5:32] at a full training run, what you'll [5:34] notice is that the sharpness increases [5:36] and then it decreases and then it [5:37] increases and then it decreases and it [5:39] basically stabilizes around this two [5:41] over eight a threshold. [5:42] The standard quadratic intuition would [5:44] have suggested you would have blown up [5:45] here, but actually what happens is that [5:47] you stabilize. [5:49] Any questions about the these [5:50] experiments? [5:56] Yes. [5:56] >> How does the [5:57] full batch gradient descent [6:00] compare to model term? [6:01] >> Uh this is actually a deep neural [6:02] network that you're training on real [6:04] data at this point. [6:05] So, if you did this for a quadratic as [6:07] the earlier plots showed, the sharpness [6:09] would just keep climbing and you would [6:10] completely diverge. [6:14] I believe this one might be a CIFAR. So, [6:17] it's training on like images and it's [6:18] like vision. But uh these types of [6:20] phenomena that we're going to cover [6:21] today, I can show a plot later, but uh [6:23] they hold across data modalities and [6:24] architectures and such. [6:29] Yeah. [6:30] >> We'll be building actually [6:33] [clears throat] [6:35] >> Uh we'll get to that in the end of like [6:37] how to actually reason about sharpness [6:39] when you're actually training models. [6:40] It's really you know field of black [6:43] magic. It's really [6:44] It's really scary stuff. [laughter] [6:48] [snorts] [6:50] Cool. So, just to be clear about the [6:52] core phenomenology, the sharpness [6:53] actually uh stabilizes at this unstable [6:56] threshold rather than the training run [6:58] actually blowing up. [7:00] And uh if you do this run with a [7:02] different learning rate, what ends up [7:04] happening is that the sharpness also [7:06] stabilizes, but it stabilizes at a [7:07] different threshold. If you recall, the [7:09] threshold at which uh your training run [7:12] would blow up would be 2 / eta. And [7:14] that's why if you decrease the learning [7:16] rate to train slower, the threshold [7:17] increases because 2 / eta is now twice [7:19] as high and you stabilize at this higher [7:21] point rather than this lower point. [7:28] So, maybe the picture that we had [7:30] earlier where the model from [7:31] initialization to its final training [7:33] point stays in the region where the [7:35] sharpness is under this 2 / eta [7:36] threshold is flawed. And what's actually [7:38] happening is you're bouncing around the [7:40] stable region to get to where you [7:41] actually want to end up. [7:43] And maybe this is a different cartoon [7:44] for what's going on during deep network [7:46] training. [7:47] [snorts] [7:50] So, uh just to be clear as uh people [7:52] have mentioned, we're doing full batch [7:54] gradient descent here, which means that [7:55] we're taking the entire training data [7:56] set and doing a gradient update at once [7:59] rather than the small batch training [8:00] like batch size 64 training that's usual [8:02] for the course. [8:03] Uh we are going to get to that at some [8:05] point, but uh just to be clear like [8:06] these phenomena related to this have [8:08] also been observed for stochastic [8:10] gradient descent like mini-batch as [8:11] well. And also for all sorts of other [8:14] optimization tricks. Like the three main [8:15] things missing for full batch gradient [8:17] descent is using a like like what is it? [8:21] Using a batch size, using momentum, and [8:23] then also using adaptive optimizers. And [8:25] we're going to cover the interaction [8:26] with these three. But just to start, [8:27] we're going to cover full batch gradient [8:28] descent and see what happens in this [8:30] case just as an isolated example. [8:34] So [8:36] the core phenomena that happens is this [8:38] self-stabilization property. So we're [8:39] going to start with an informal [8:40] rendering of what this property looks [8:42] like. [8:43] So first, what we can do is we can think [8:45] about the loss as you have some [8:47] displacement along the maximum maximum [8:49] eigenvalue of the Hessian. So what that [8:51] means is you take your weight and you [8:53] add some perturbation. So along the [8:55] direction of the maximum eigenvalue, so [8:57] this is U, and you have some factor X [8:59] which controls how far away how far [9:01] displaced you are along this direction. [9:04] So what you can do is you can estimate [9:06] what the loss is over here by taking a [9:08] Taylor expansion. So if you take a [9:10] Taylor expansion and take the first term [9:12] and the second term, [9:13] the first term corresponds to just the [9:15] gradient at the point itself not being [9:17] displaced along the eigenvalue. [9:20] The second term over here corresponds to [9:22] the Hessian and it's like the Hessian [9:25] like upweighted by basically how far you [9:27] are displaced. And this is like the [9:28] quadratic local approximation. So as we [9:30] talked about in last lecture, the [9:31] Hessian is this like local approximation [9:33] of the loss landscape that behaves [9:34] quadratically. [9:36] This would suggest like this is like a [9:38] quadratic approximation to what the loss [9:40] is as you're displaced along the maximum [9:42] like eigenvalue. [9:45] This behaves like a quadratic in that if [9:48] you move in the opposite direction of U, [9:51] then you will oscillate. So this term [9:52] will actually pull you back in and it [9:54] will cause the quadratic-looking [9:55] oscillations that we were seeing [9:56] earlier. [9:59] The main change that the adjustability [10:01] analysis that the self-stabilization [10:03] analysis makes is that instead of only [10:05] taking the second term of the Taylor [10:07] expansion, they then look at the third [10:09] term of the Taylor expansion. [10:12] [snorts] When you look at this third [10:13] term, once you expand it, you'll notice [10:16] that this second term over here is [10:18] corresponds to U transpose a Hessian U [10:21] and this is actually equivalent to the [10:24] maximum eigen value of the Hessian. [10:26] So what you're doing when you're taking [10:28] this third update is that this third [10:30] update is equivalent to the gradient of [10:33] the sharpness and [10:35] this third update is actually decreasing [10:37] your sharpness. [10:38] So in addition to doing the standard [10:40] gradient descent and the second term, [10:42] you are also having this third term [10:44] which reduces your sharpness over the [10:46] course of training. [10:48] Now there's no reason that this third [10:50] term would fully explain all of gradient [10:52] descent. For example, we might be [10:54] missing a fourth term and a fifth term [10:55] and a sixth term. But what we can do is [10:57] we can empirically check whether these [10:58] sorts of terms actually make a [10:59] difference. [11:02] But sorry, first here's just an [11:04] experiment where you can show that this [11:05] happen the edge of stability phenomenon [11:07] happens for all the eigen values, not [11:08] just the max one, but we're going to [11:10] start by analyzing the max one. [11:14] So [11:15] to start, we're going to basically show [11:16] an analysis tool [11:18] that people can use if you stick to the [11:20] second order approximation. [11:23] A common analysis tool that people will [11:24] use to analyze gradient descent is to [11:26] build [11:27] a differential equation that corresponds [11:29] to how the weights are actually moving. [11:31] So instead of taking the instead of [11:34] taking discrete gradient updates, these [11:36] discrete gradient updates kind of you [11:38] can take a continuous approximation of [11:39] them and basically saying [11:40] instantaneously at time T, the model is [11:43] moving according to this differential [11:45] equation. [11:46] So minus Ada times the gradient, which [11:48] kind of makes sense. [11:50] At that given point in time, you're [11:51] moving in that gradient direction with [11:53] some learning rate. [11:55] If you write down this differential [11:57] equation, then you can track how loss [11:59] evolves over the course of training. So [12:01] this blue line corresponds to empirical [12:02] gradient descent versus this red line [12:05] corresponds to if we were tracking what [12:06] the differential equation predicts the [12:07] loss would look like. [12:09] What you'll notice is that at the start [12:10] of training, the gradient flow makes an [12:12] excellent for how training proceeds, and [12:14] is tracking everything very well. But, [12:16] as we talked about, gradient flow only [12:18] keeps up to the second order. [12:20] Behaves like the quadratic. So, after [12:22] you cross the edge of stability, the [12:24] gradient flow will completely blow up [12:25] and say that your sharpness just keeps [12:26] increasing and increasing. [12:28] Versus empirically, what we're finding [12:30] is we're finding this stabilization [12:31] effect where the sharpness goes back [12:32] down and oscillates. [12:35] So, this shows that the gradient flow [12:36] has some predictive value in practice, [12:39] but it does not have great predictive [12:41] value because it stops at the region of [12:43] interest, which is where the sharpness [12:44] stabilizes. [12:51] So, instead of tracking what gradient [12:53] flow does, so gradient flow is tracking [12:57] the the like the red line over here, [12:59] what we'll notice is that at some point [13:01] we enter this oscillatory regime where [13:03] we're oscillating. And uh in this [13:06] regime, [13:07] instead of tracking the the gradient [13:09] flow does a poor job of predicting where [13:11] you go, and we need a different type of [13:13] tool to track where exactly the model is [13:15] going. And this tool that we're going to [13:17] be [13:18] using is called the central flow. [13:21] The central flow, instead of tracking [13:22] where the model is going in like the [13:24] central flow will account for the third [13:26] term in that Taylor expansion and track [13:28] where the model is going uh [13:30] over its oscillations rather than just [13:32] ignoring those oscillatory terms. [13:37] So, just to explain how the central flow [13:39] works, [13:40] uh we can go through the math of using [13:42] this third term in the Taylor expansion. [13:46] So, let's say that we only had one [13:47] eigenvalue at the edge of stability. [13:49] What happens is that we have our our [13:52] weights at time T, [13:54] and we have some perturbation that's [13:56] happening along the top eigenvector. [14:02] We can do the Taylor expansion that we [14:04] talked about earlier where we can expand [14:05] the gradient at time T into three [14:07] separate terms. So, the gradient uh just [14:10] the standard gradient at that time step [14:13] plus some oscillation term [14:15] plus the sharpness reduction term. [14:18] So these are the three terms of the [14:19] Taylor expansion, and what you'll notice [14:21] is that when you're doing uh gradient [14:22] descent, you have the you see a lot of [14:25] oscillation in the sharpness. [14:29] But instead what you can do is you can [14:30] track gradient descent if you had [14:32] instead averaged over time. [14:34] So instead of tracking this oscillation [14:36] term, you can take the expectation over [14:39] time, and these oscillations will cancel [14:41] out when you take this expectation over [14:43] time. [14:45] When you take this expectation over [14:46] time, what you're left with is that [14:48] gradient descent, the differential [14:50] equation at least uh after taking the [14:52] expectation, only has this gradient term [14:55] and it has this sharpness regularization [14:56] term. [14:59] Once you have uh this term, [15:02] what you can do is that [15:05] you can see that over the course of [15:06] training there is a gradient that you're [15:08] taking [15:09] and there is also some sharpness penalty [15:11] that's going on, but you don't know how [15:13] much the sharpness penalty is changing. [15:15] There is some like schedule that's [15:17] happening to the sharpness penalty such [15:19] that over at certain points of time the [15:21] sharpness is decreasing more or [15:22] decreasing less [15:24] and it's governed by how far you are [15:26] away from the actual [15:28] uh how far you are oscillating along the [15:30] maximum eigenvalue. [15:32] So you want to measure how far you are [15:34] how far you're oscillating around this [15:35] maximum eigenvalue. [15:38] And this corresponds to some [15:40] differential equation that that modifies [15:42] the gradient flow. So if you recall the [15:43] gradient flow, what you had is that you [15:45] had the weights evolving over time [15:47] updating by learning rate times the [15:49] gradient. But what we're noticing is [15:51] that if you do if you take the third [15:52] order term of the expansion, then you [15:54] have this additional term which is [15:56] operating on the sharpness penalty over [15:57] the course of training as well. [16:00] So you have this additional term which [16:02] minimizes your sharpness as well and [16:04] it's according to some noise schedule [16:06] the sigma squared t which we don't know [16:09] uh but we can actually solve for [16:10] mathematically what it would be. But if [16:12] we were able to solve for what sigma [16:13] squared t will be, then we can actually [16:15] track the progress of gradient descent [16:17] and see where the iterates are going, [16:19] accounting for the fact that gradient [16:20] descent is magically reducing the [16:22] sharpness somehow. [16:29] So you can do a bit of math to see what [16:31] that noise schedule should actually be. [16:35] So to go through what that math looks [16:36] like, the core assumption that the math [16:38] makes is that we know that after a [16:42] certain amount of time we enter this [16:44] regime where the sharpness stabilizes. [16:46] So for tracking the trajectory averaged [16:48] over time, we know that the sharpness [16:50] also stabilizes at that point in time. [16:53] So you want to enforce the invariant [16:54] that the sharpness isn't changing once [16:56] you enter the edge of stability regime. [16:59] If you enforce this invariant that the [17:00] sharpness isn't changing at this point, [17:02] that basically means that the derivative [17:04] of the sharpness with respect to time is [17:06] zero and is flat and is not changing. [17:09] So we roughly want to solve for what [17:10] differential equation would satisfy [17:12] these properties where it matches the [17:13] third order Taylor expansion and it also [17:16] has the fact that the sharpness is not [17:17] changing at this point in time. And this [17:20] is the core theoretical assumption [17:21] that's motivated by the empirics of [17:23] tracking how the sharpness changes over [17:24] time. [17:26] So once you want to solve for the [17:28] sharpness not changing over time, [17:32] you can expand out what the derivative [17:33] of the sharpness is. So first, the [17:35] derivative of the sharpness with respect [17:37] to time can be decomposed via the chain [17:38] rule into the derivative of the [17:40] sharpness with respect to the weights [17:41] and the derivative of the weights with [17:42] respect to time. [17:44] Then we know how the weights evolve over [17:46] training. We know that the weights [17:48] evolve with some fixed learning rate [17:51] that modulates both the gradient and how [17:53] fast we're increasing the sharpness. [17:56] And once you expand this out, then to [17:59] set this term equal to zero to make sure [18:02] that the sharpness is not changing over [18:04] time, you must have that the noise [18:05] schedule equals this quantity over here. [18:08] So based on our empirical observation [18:10] that we made that the sharpness has [18:12] stabilized and where it's not changing [18:14] over time, we can come up with a [18:15] differential equation that's consistent [18:17] with our empirical reduction of deep [18:20] learning to this Taylor expansion, and [18:22] it's also consistent with our empirical [18:24] observation of what's actually going on [18:25] with sharpness. [18:30] So here is the main plot that's quite [18:32] surprising, which is that this [18:34] simplification that we make makes [18:35] excellent predictions for what happens [18:37] in deep learning practice. So to recall, [18:40] if you have gradient descent where the [18:41] loss is slowly decreasing, the gradient [18:43] flow, which only tracks the first order [18:46] term like the gradient, will make a good [18:48] prediction until you hit the edge of [18:49] stability. [clears throat] But once you [18:51] hit the edge of stability, it cannot [18:52] capture the correct dynamics. [18:54] Interestingly, by tracking the average [18:56] of the weights over time and seeing how [18:57] the weights how the expectation of the [18:59] weights evolve and the expectation of [19:01] the sharpness evolve over time, then you [19:03] can see that you you make the [19:04] theoretical prediction that the [19:06] sharpness stabilizes at the threshold [19:07] that we see empirically. And we kind of [19:10] have a prediction for how everything [19:11] evolves like on average. So all of our [19:15] differential equation tracks the [19:17] expected moving average of all these [19:18] statistics that we care about. [19:22] Yeah. [19:24] That's a good time for questions. [19:28] You can go over any of the derivations [19:30] again if you're very [19:31] intense. [19:33] Yes. [19:34] >> So the idea of central flow is just to [19:36] remove that second term Taylor expansion [19:39] not not remove the oscillation? [19:41] >> Exactly. So it's to add the third term [19:43] and then it's also to average out that [19:45] second term. So to not reason about the [19:47] oscillations because the oscillations [19:49] themselves are like this extremely [19:50] chaotic process that's really hard to [19:52] model. And if you take this expectation [19:54] to remove this second term, then you can [19:56] actually track the like like basically [19:58] morally what's happening over the [20:00] training process. You can track the [20:01] important parts you care about without [20:03] having to pay attention to the noise of [20:04] the sharpness actually oscillating or [20:05] something. [20:08] Yes. [20:10] >> Um like [20:12] which which of these boxes should I [20:13] think is interesting? Cuz I guess for [20:15] the second box, you literally set like [20:17] DSDT to zero. So [20:19] it's not surprising that it should like [20:21] stabilize there. [20:22] >> That's true. So I the surprising [20:25] predictions are first the loss [20:27] predictions. So, being able to predict [20:28] the EMA of the loss even though the loss [20:30] is like spiking all the time. And [20:32] another interesting prediction that [20:33] you're making is that what you're doing [20:35] is you're measuring the network output [20:36] on just like one specific example. [20:38] Because you know how the weight how the [20:40] average of the weights is developing [20:41] over time, you can evaluate what that [20:43] weight what prediction that weight would [20:45] make on a specific example. And even [20:47] though your prediction might oscillate [20:48] over the course of training, you're also [20:50] predicting how that evolves. [20:52] So, maybe it's this assumption on the [20:54] sharpness still gives you a faithful [20:56] interpretation of how the weights are [20:57] evolving and how the weights evolve [20:58] affect both the loss and your [20:59] predictions and all these other [21:00] quantities. [21:05] Any other questions? [21:11] Yes. [21:12] >> Used to study double descent? [21:14] >> Uh double descent. [21:16] Uh so which double descent are you [21:18] thinking about? [21:18] >> Like if you were seeing okay the loss [21:20] increases over the time then predict [21:22] okay when the loss is again going to go [21:24] down [21:25] it's like the whole double descent [21:27] phenomenon can be tracked with [21:29] >> Yeah. So, I guess in double descent like [21:32] the x-axis is like number of samples, [21:35] but maybe it's not like number of [21:36] samples over a single training [21:37] trajectory, but it's like number of [21:38] samples like if I gave the number of [21:40] samples to like a specific learning [21:41] algorithm how much loss would it get. [21:43] So, I feel like double descent has less [21:45] to say about optimization dynamics, but [21:47] I guess that if you saw that like for [21:49] one training run the loss went up and [21:50] then went back down, if that was true [21:52] within a training run too [21:54] uh ideally the central flow would make [21:55] that prediction as well. [21:57] But I do think that uh there's a very [21:58] like double descent is usually more [22:00] about generalization. So, if you have a [22:01] limited number of samples, how much [22:03] value can you squeeze out of them. All [22:04] of the experiments that we're doing here [22:05] and basically all the experiments you've [22:07] done in the class are in this one pass [22:08] regime where you're never like repeating [22:09] any of the data and this operates in [22:11] like kind of a different regime. [22:13] Yeah. Yes. [22:15] >> Are these [22:16] in [clears throat] [22:16] train loss completely explained by the [22:19] fact that that those are the points [22:20] where the sharpness is bigger than [22:24] So, where the spikes are happening I [22:26] don't if there's like a like the the [22:28] differential equation can't actually [22:29] make that prediction because it's only [22:31] tracking the average things. But if [22:32] you're empirically tracking where the [22:34] loss spikes are happening, uh maybe in [22:36] the earlier plot you saw that the loss [22:37] spikes happen right when the network [22:39] output predictions are also like [22:40] oscillating or like the like the [22:42] displacement around along the [22:43] eigenvector is also oscillating. So, at [22:45] least empirically you can see that these [22:47] both agree. [22:52] Okay. [22:55] So, uh this is pretty cool because [22:57] instead of doing this for one [22:58] eigenvector, so our math that we did was [23:00] only for one eigenvector, but you can [23:01] actually solve this for all the [23:02] eigenvectors jointly as well. And you [23:04] get this model that predicts all of the [23:06] eigenvalues over training as well. So, [23:09] it predicts even the ones that are not [23:10] at the edge of stability how well it [23:12] does and also the ones that enter the [23:13] edge of stability. [23:14] And uh as you can see like compared to [23:16] gradient flow which would make like [23:17] pretty horrible predictions if you take [23:18] a certain number of steps. [23:24] And also this was also what we were [23:26] talking about earlier which is that you [23:27] can track the oscillations even [23:28] predictions in specific examples. Even [23:30] though these predictions have like [23:31] pretty large oscillations, the time [23:34] average trajectory maintains like a [23:37] reasonable [23:38] estimate of what's going on. [23:44] So, uh the central flow has like pretty [23:47] interesting interactions with the River [23:48] Valley mental model that we were talking [23:49] about from last lecture. So, if you [23:51] recall, we had an like an intuition that [23:54] what gradient descent is doing is that [23:55] along the sharp direction of the loss [23:57] landscape, gradient descent is bouncing [23:59] from wall to wall. [24:00] And this is kind of like this [24:03] oscillation is kind of chaotic and hard [24:04] to track. One cool thing that the [24:06] central flow does is that it tracks the [24:08] expectation of the weights over time. [24:10] So, when you track this moving average [24:12] of the weights, what you're doing is [24:13] that you're actually tracking [24:16] progress along the river direction. And [24:20] the central flow is actually tracking [24:21] what's going on when you're at the [24:23] bottom of the river rather than what's [24:24] happening in this oscillatory period. [24:26] So, for example in training where your [24:29] gradient descent is like oscillating [24:30] quite a bit, [24:32] uh your loss might actually be like [24:34] higher than what the central flow [24:36] predicted. [24:37] And this is because the central flow is [24:39] kind of getting rid of the noise that [24:40] happens from doing all of these [24:41] oscillations. But one cool thing that [24:43] you can do is that the central flow also [24:46] predicts how much noise is there because [24:47] it knows the sharpness at any given [24:49] point. So you can add that back into the [24:51] loss and you'll notice that when you add [24:52] this back into the loss, you actually [24:54] predict the loss value of the true [24:55] trajectory rather than your expected [24:57] weight trajectory. [25:04] Uh this can also be seen in the gradient [25:06] norm as well because the gradient norm [25:08] is going to be higher in this bouncing [25:09] region versus you're moving smaller [25:11] amounts in the river direction. So [25:12] that's why uh the central flow, the [25:15] basic one would predict that you're not [25:16] actually moving that much, but if you [25:18] add it in the noise component, then you [25:20] would predict basically how the gradient [25:21] norm is actually evolving over the [25:22] course of training. [25:31] So uh yeah, [25:32] uh just and I think this like river [25:34] valley picture is like a little nuanced. [25:36] So I just want to separate out like two [25:37] separate sources of movement that's [25:38] happening. So one is that you're [25:40] actually oscillating from wall to wall [25:42] and this is the type of movement that we [25:43] talked about in the like first lecture. [25:45] But uh the other thing that's happening [25:47] is that the sharpness itself is changing [25:49] over the course of training and this is [25:50] also like stabilizing towards some [25:52] threshold by going above the threshold [25:53] and below the threshold and this kind of [25:55] changes the height you are along the [25:57] wall. So if you'll notice in this [25:58] picture, there's actually a subtle bend [26:00] across the height as you're moving [26:01] across time. So there's both these [26:03] oscillations along the sharp direction, [26:05] but there's also oscillations on how far [26:06] you are from the bottom of the floor [26:08] because the sharpness itself is changing [26:09] over the course of training. So there's [26:11] like two different sources of like [26:14] movement going on here which can get [26:15] kind of confusing about. [clears throat] [26:25] So just to summarize what we've talked [26:26] about for the adjustability in central [26:28] flow so far, [26:31] uh we have the quadratic model which [26:33] would predict that optimization diverges [26:35] once sharpness exceeds some threshold. [26:37] So if the like learning rate was too [26:39] high you or like the sharpness was too [26:40] high then your training run should blow [26:42] up and diverge. [26:44] interestingly modern neural networks at [26:46] least empirically we notice that they [26:47] reduce the sharpness whenever you exit [26:50] to some certain threshold and there's [26:51] this behavior where you actually [26:52] oscillate [26:55] or stabilize along this threshold and in [26:58] by tracking the parameters averaged over [27:00] time you can actually build this [27:01] differential equation that tracks the [27:03] like true progress of the neural network [27:05] without having to reason about all these [27:06] oscillations. So you can see the how the [27:08] high level quantities [27:14] Yeah, any other questions here? Or Yeah. [27:16] >> Can you illustrate how uh this [27:19] approach benefits from annealing? [27:21] >> Of annealing? [27:23] So if you [clears throat] increase sorry [27:26] decrease your learning rate [27:28] the [27:29] let's see [27:30] [snorts] [27:33] the sharpness should go up, right? Uh [27:35] does that get you to the bottom though? [27:37] >> Uh it also reduces the [27:39] that also support like the [27:42] part of the [27:43] >> Oh I see I see. Yes. Do you want to say [27:45] it or [27:46] >> Oh yeah so so if you if you anneal then [27:48] like there's two effect that will [27:49] happen. It's like one is that like [27:51] because the [27:52] the sharpness is roughly one over like [27:54] then you should get to sharper places [27:57] but on the other hand the oscillation is [27:58] also decreased because your the [28:00] oscillation term at the very beginning [28:02] is like proportional to learning rate. [28:03] So like eventually you will have you [28:05] will move closer to the river part uh [28:07] but while the the the landscape itself [28:09] will get sharper. So two things will [28:10] happen at the same time. [28:16] >> Yes? [28:16] >> Can you show the second part of that [28:17] again? Why does the landscape get [28:19] sharper? [28:19] >> Oh because like if you look at the the [28:21] original uh [28:24] uh like [28:25] with the original EOS like you know that [28:28] EOS happens when like roughly a [28:30] sharpness is like two over learning [28:31] rate. So when your learning rate [28:33] decrease assuming you are decreasing it [28:34] relatively slowly, then like you if you [28:36] are always near your loss, then you will [28:38] have like sharper and sharper landscape [28:39] because learning rate is decreasing. So [28:41] two over learning rate should increase. [28:43] >> Is there like an intuition for why that [28:45] happens besides like [28:47] I get I get I get the formula but like [28:49] why would it get [28:51] >> Uh why would it You mean intuitively? I [28:54] guess [28:56] I guess it's if you can imagine this [28:58] similar to because I'm moving slow [29:01] smaller every step but I always like was [29:03] trying to being at the edge of stability [29:05] in the sense that if there's there's [29:07] always a force that want to increase my [29:08] sharpness to the largest possible. So [29:10] like uh by by moving smaller then this [29:12] will make the my landscape going sharper [29:14] and sharper because there the the forces [29:16] of progressive sharpening will just [29:18] continually drive me towards like [29:20] sharper region. [29:21] >> That makes sense. [29:23] >> Yeah, as far as I know we don't know why [29:24] progressive sharpening happens. It's [29:26] just like a thing. [29:27] >> It's a thing. [29:28] >> it's like an invisible force. It's like [29:29] we think that you know there's an [29:31] invisible force progressive sharpening [29:33] and through various mechanisms like [29:35] models tend to for sharper places and [29:37] then once they hit EOS the stabilization [29:39] mechanism kind of keeps you there. So if [29:41] you change your learning rate it's a [29:42] dynamic thing, right? Like your stable [29:44] region increases and then you'll like [29:45] keep progressive sharpening kicks in [29:46] again and you'll keep you know getting [29:47] pushed out to the sharper and sharper [29:49] region. [29:58] >> And another thing you can do is you can [29:59] also track how edge stability works for [30:01] like uh how central flows predict loss [30:04] for other types of architectures and [30:05] other types of data as well and it does [30:07] like a reasonable prediction of how [30:09] different training runs go. [30:18] So there's a couple of made like main [30:20] modifications that are missing. So all [30:21] of this edge of stability and central [30:23] flow analysis we've done so far has been [30:25] on this full batch gradient descent [30:26] setting and if we're reasoning about an [30:28] optimizer like Adam, there's like three [30:29] main components that are missing to get [30:31] to Adam. One is reasoning about how [30:33] momentum changes everything. One is [30:35] reasoning about how doing mini batch [30:36] gradient descent rather than doing full [30:38] batch gradient descent changes [30:39] everything. And finally, there is this [30:41] other like reasoning about the adaptive [30:43] part of our optimizer where we're [30:45] normalizing all of the gradients by like [30:47] the like the average squared gradient as [30:49] well over the course of training. [30:51] So [30:52] we'll spend more time on the adaptive [30:53] optimizers, but there's like a few [30:54] things to say about momentum and [30:56] mini-batch. Though again, not all of [30:57] these are fully solved yet and there's [30:59] another like step where you glue all of [31:01] these pieces together and not all of [31:02] this is completely done, but [31:04] I think it's in progress right now. [31:07] So first we can talk about an [31:09] interaction with momentum. So if you [31:11] recall [31:12] what momentum is, it's just accumulating [31:13] the gradient over iterations. So we're [31:15] taking the gradient and then we're [31:17] adding like with some decay value beta, [31:19] we are accumulating the gradient every [31:21] gradient update and then applying that [31:22] gradient on the weights. [31:24] So one way to reason about momentum is [31:28] one way to reason about how momentum [31:29] interacts with all of this [31:30] adjustability, it's a reason about [31:32] what's the like actual effective [31:33] learning rate that's happening when we [31:35] train with momentum. [31:38] So [31:39] to start, [31:41] if you remember from the first lecture, [31:42] when we trained with full batch gradient [31:44] descent, we had this visual where we can [31:47] track the cosine similarity between [31:49] successive gradients in the updates and. [31:51] We found that the successive gradients [31:52] had basically negative one cosine [31:54] similarity with each other, and they [31:55] were basically pointing in like [31:56] completely opposite directions and. This [31:58] kind of like attracts with our mental [32:00] model of the gradient descent bouncing [32:02] around. [32:03] So we know that the gradients are quite [32:05] like different from each other at least [32:07] in this full batch setting and [32:09] what you can do is that you can [32:11] basically just do some back of napkin [32:13] math. So if you're thinking about what [32:14] gradient you're going to be applying [32:15] with momentum, it's roughly this like [32:17] geometric series of the most recent [32:20] gradient plus beta times the gradient [32:21] before that plus beta squared times the [32:23] gradient before that and such like that. [32:25] But if you have this assumption that all [32:27] the gradients, first of all, are roughly [32:28] the same size and are also pointing in [32:30] different directions, then you can [32:31] accumulate this geometric series by [32:33] applying negative beta every time. And [32:35] when you accumulate all of this, you get [32:37] that the gradient is actually being [32:38] rescaled by this one plus beta form, [32:41] one plus beta. [32:42] So, we saw a similar derivation for the [32:43] noisy quadratic model, and the [32:45] motivation over there is that when we [32:46] have momentum in this oscillatory [32:49] regime, you can actually pump up your [32:50] learning rate if you wanted to. At least [32:52] in the noisy quadratic model, you could [32:53] pump up your learning rate by a bit, and [32:55] that's like the main benefit of momentum [32:57] in that regime. [32:59] But in general, the main point is that [33:00] the training is actually happening at [33:02] this one plus beta dampened factor. [33:04] And that means that the sharpness would [33:06] increase by a factor of one plus beta. [33:08] So, for whatever learning rate I'm [33:09] plugging in beta, now you should think [33:11] of the learning rate as effectively like [33:12] beta over one plus beta. And when you do [33:15] two over the learning rate, which is [33:17] where the sharpness stabilizes, then you [33:19] would find the sharpness actually like [33:21] roughly increases by a factor of one [33:22] plus beta. [33:24] So, this is an intuition for how [33:25] momentum would increase that threshold [33:27] at which sharpness happens for the same [33:28] learning rate. [33:35] Now, this is this analysis is when we do [33:37] the full batch gradient descent case. Uh [33:39] we're not going to work through the full [33:40] mini batch case because it's also not [33:41] fully solved, but the mini batch case at [33:43] least has a pretty interesting [33:44] interaction with how the like with the [33:47] momentum term at least. [33:48] So, if we recall from last lecture as [33:51] well, we also measured the successive [33:53] gradient similarity between gradient [33:55] updates when we are in the SGD regime [33:57] rather than the full batch gradient [33:58] descent regime. [33:59] We still have the intuition that there's [34:00] like some oscillation going on, but as [34:03] but in SGD what happens is that each [34:05] gradient update itself is like much more [34:06] noisy, and we can say that we're in a [34:09] noise dominated regime. When you're in [34:11] this regime, the successive gradient [34:13] updates have closer to zero cosine [34:15] similarity with each other rather than [34:16] have close to negative one cosine [34:18] similarity with each other. So, even if [34:19] this oscillation is happening, the noise [34:21] is making it such that the cosine [34:22] similarity is like close to zero. [34:25] When you're in this regime, we have to [34:26] do a different napkin math for how the [34:28] gradients accumulate. [34:29] So, instead of the gradients pointing in [34:32] just the direct opposite directions now, [34:34] they're basically like random variables [34:35] that are like uncorrelated with each [34:36] other, and you have to accumulate their [34:38] variance over the momentum term. So, if [34:40] you want to think about the update [34:41] you're actually applying, you want to [34:42] reason about the variance of the [34:44] gradient plus beta times the previous [34:46] gradient plus beta squared times the [34:47] previous gradient and such. And now we [34:49] have this assumption that rather than [34:50] being like anti-correlated, they're just [34:52] like independent. So we would have to [34:53] separate the variances into separate [34:55] terms. Now the [snorts] variance of the [34:56] gradient plus varia variance of [34:59] gradient times beta [35:01] uh and so on. And if you solve for the [35:03] geometric series this time, what you'll [35:04] notice is that the gradient is actually [35:06] up like the scaled up by dividing by one [35:09] minus beta. So in this regime, in this [35:11] small batch regime, the momentum has a [35:12] different interaction and from the noise [35:14] dominated aspect, it's actually [35:16] amplifying the gradient. And because of [35:18] this, if you want to reason about where [35:20] like the training stabilizes, it [35:22] stabilizes at two over beta, but the [35:24] effective learning rate now is decreased [35:26] by a factor of one minus like divided by [35:28] one minus beta. So you're multiplying [35:30] that threshold by one minus beta as [35:31] well. So momentum in the mini batch case [35:34] would actually lower your threshold, [35:35] whereas momentum in the full batch case [35:37] would increase your threshold. [35:45] Uh anyway, these are the types of things [35:47] that you'll also explore in your [35:48] assignment. [35:53] And uh yeah, for example, this paper uh [35:55] shows this empirically. What they do is [35:57] that they train uh different models. So [35:58] they train at the full batch case and [36:00] they also train at the small batch case, [36:02] so batch size equals eight, and they [36:03] vary the beta. And you can see that [36:05] these theoretical predictions about [36:06] where the sharpness should stabilize [36:08] actually do get reflected in practice [36:10] where increasing beta increases its [36:11] threshold for full batch, but increas [36:13] increasing beta decreases its threshold [36:15] for small batch regime. [36:19] [snorts] [36:23] Uh there are some uh references here if [36:25] you want to look at [36:26] some current analyses of what the noise [36:28] dominated regime would look like for [36:29] adjustability. And uh [36:32] but there isn't like a full mini solved [36:34] mini batch version out there. So we'll [36:36] see when that happens. [36:39] Cool. [36:41] So now the final component that we [36:43] haven't talked about yet is the [36:44] adaptivity, which has a lot of nuance [36:46] for how it interacts with the [36:47] adjustability. So, the way that we're [36:49] going to study adaptivity is similar to [36:50] the approach that we took so far, which [36:52] is analyze the simplest possible case [36:54] and then slowly expand. We're going to [36:55] start with the simplest possible like [36:57] adaptive optimizer that we can come up [36:58] with. So, it's called scalar RMS prop. [37:02] What this algorithm does is that it [37:04] accumulates the squared gradient norm [37:06] using some EMA. So, you first pick some [37:07] parameter beta two that will keep an EMA [37:10] of what the squared gradients are so far [37:12] over time. [37:13] And then what you're going to do is that [37:15] you're going to do a gradient update [37:16] where you normalize everything by the [37:18] square square root of the average [37:20] squared gradient norm. [37:22] One important detail over here is that [37:23] we're going to start by analyzing scalar [37:25] RMS prop. And scalar RMS prop means that [37:27] you have a single scalar for all of the [37:29] parameters, rather than Adam which [37:30] usually maintains one separate scalar [37:32] per each parameter. [37:39] Uh in this algorithm, instead of [37:41] thinking about the learning rate being [37:42] Ada, we should be thinking about the [37:43] learning rate as being Ada over uh the [37:46] like square root of the average squared [37:47] gradient norm like the new. [37:49] So, [37:50] uh we have Ada over square root and [37:53] therefore instead of the threshold being [37:55] S over Ada like it was before, the [37:57] threshold we kind of expect it to be S [37:59] square root Ada [38:00] over uh mu in this case. [38:03] What's that? Uh [38:05] mu over [38:07] that mu [38:10] So, this motivates a different type of [38:11] quantity which is the effective [38:12] sharpness. And instead of actually [38:14] tracking the original sharpness which [38:16] depends on the uh these terms uh the the [38:18] learning rate and square gradient norm, [38:19] we'll be tracking the effective [38:21] sharpness instead. And this is a [38:22] quantity we expect to stabilize even if [38:24] the uh like Ada [38:26] the square gradient norm is changing [38:28] over the course of training. [38:31] So, if we measure this empirically for [38:32] RMS prop, we'll find exactly what we [38:35] predict. The sharpness itself is [38:36] changing uh like uh differently. So, if [38:39] you track this uh [38:41] what is the Greek character for this [38:42] like [38:42] >> Mu. [38:43] >> Mu, right? Okay. So, if you have mu, uh [38:46] mu is growing over time. [38:48] And that actually messes up with what [38:50] your effective step size is. So that [38:52] change like the sharpness itself is [38:54] changing over the course of training. [38:55] But if you consider this normalized [38:57] version where you take eta s over new, [38:59] then this itself stabilizes at this [39:02] value of two that we predict. So if you [39:04] look at s over eta, that would stabilize [39:05] at two over eta. [clears throat] [39:10] But in this case, the sharpness itself [39:13] unnormalized is so growing. [39:18] So in RMS prop, there's actually two [39:21] forces that are going to solve [39:22] stabilization rather than just one [39:24] force. And this is like maybe the most [39:25] important nuance of what adaptive [39:27] methods do. [39:29] Normally in gradient descent, we found [39:31] that the oscillations or like how far [39:33] you're deviating along the max like [39:35] eigenvector [39:36] increase the amount of sharpness [39:38] regularization that we're doing and [39:39] decrease the sharpness even further. And [39:41] that was the main force that we were [39:42] analyzing up till now. But now there's [39:44] actually a second force which is another [39:46] way to change your sharpness is to [39:48] actually change what this gradient norm [39:50] looks like over the course of training. [39:52] So if you have a lot of oscillations, [39:55] what happens is that the gradient norm [39:57] suddenly increases. So you're now [39:59] oscillating a lot. The gradients are [40:00] like a lot bigger. And when you're in [40:02] this oscillatory regime, [40:04] new itself is going to grow. So your EMA [40:07] itself is going to grow. And when your [40:09] EMA grows, your effective sharpness also [40:12] changes [40:13] because [40:14] you like your sorry your effective step [40:16] size eta over new also like decreases. [40:20] And this would affect your effective [40:22] sharpness as well. And this affects the [40:23] effective sharpness by changing square [40:25] root of new rather than by changing the [40:28] actual value of the true sharpness [40:29] itself. [40:35] So just for like some intuition about [40:37] what's going on, another thing that we [40:38] can do is we can increase the momentum [40:41] that we use we increase the beta two [40:42] parameter that we use that we use to [40:44] accumulate the like the gradient average [40:46] square gradient norm. [40:48] If you increase this parameter, what is [40:50] that new grows more slowly. So it's [40:53] equivalent to have like having less of [40:55] the second effect, having less of this [40:56] effect where new is the thing that's [40:57] changing the sharpness. [40:59] And when you increase this, then what [41:01] happens is that the effective sharpness [41:02] takes more time to stabilize because the [41:05] second force that holds the effective [41:07] sharpness down doesn't exist. [41:09] So now the effective sharpness is [41:11] decreasing more slowly. [41:13] And the gradient norm is also like uh [41:16] what is it? [41:18] Yeah, the new itself is also growing [41:20] more slowly. [41:23] So [41:24] when you're in this regime, what happens [41:26] is that there are two forces that pull [41:27] down the sharpness. There's the force of [41:29] like the actual gradient and there is [41:31] the other force which is this thing that [41:33] doesn't actually change the sharpness, [41:34] but what it does is it just changes new. [41:36] So in the regime where you have like a [41:38] lower beta two, it means that you have [41:40] both of these forces [41:42] and the sharpness actually continues to [41:44] increase. But in this regime where you [41:46] have higher beta two, it's just the [41:48] first force and the sharpness decreases [41:50] even further. [41:54] So the the effect like momentum has a [41:57] pretty complicated interaction with what [41:58] happens with the true sharpness even [41:59] though the effective sharpness will [42:01] still stabilize around two. [42:10] So if you like play this out in the long [42:12] run, what happens is that since if you [42:15] have a higher beta two and you have less [42:16] of this sharpness regularization coming [42:18] from growing eta [42:20] or growing new, then what ends up [42:22] happening is that the sharpness [42:23] decreases over the like the the terminal [42:25] sharpness is much lower when you have [42:28] higher beta two. [42:39] So similar to how we did the gradient [42:40] flow earlier for uh SGD, what we can do [42:43] is we can measure the uh like gradient [42:46] flow, but also if we were doing this [42:47] adaptive optimizer. So this is ignoring [42:49] like the third term of the Taylor [42:51] expansion and kind of just thinking [42:52] about how the gradient evolves over the [42:53] course of training. And similarly here, [42:55] we would see that the effective [42:56] sharpness just shoots up over the course [42:58] of training and there's no like [42:59] stabilization effect happening. [43:03] But we can similarly to how we derived [43:06] the central flow for SGD, we can also [43:08] derive a central flow for when we have [43:10] this parameter like this new being [43:12] tracked over time. [43:14] So first, we have this time average [43:16] gradient. So we have we could cancelled [43:19] out the oscillation term and we just [43:21] have the gradient and the sharpness [43:22] regularization that we're familiar with. [43:26] And the other thing that we have to [43:27] track in this version is that we also [43:29] have to track how the gradient norm [43:30] grows over the course of training. So [43:32] the gradient norm also grows depending [43:34] on the oscillations as well. [43:38] And then if you combine both of these [43:40] facts, then we have a prediction that [43:42] the weights are growing over the course [43:44] the weights are evolving over the course [43:46] of training following [43:48] Ada times the gradient of the loss. [43:51] Again, this is this is like changed by [43:53] the effective step size. [43:55] And you also have the second like [43:56] sharpness regularization term. The main [43:58] difference is that you have this [44:00] effective step size over here rather [44:02] than just the Ada. And this Ada itself [44:04] follows its own differential equation [44:06] that grows over the course of training [44:07] based on how the gradient norm is [44:08] growing over the course of training. [44:16] So we can solve this again and basically [44:19] there is another unique choice of sigma [44:21] squared that you can solve for basically [44:23] like the oscillation schedule. There's [44:24] only one such that satisfies both the [44:26] theoretical cons construction of like [44:28] what we expected from the Taylor [44:29] expansion and also the empirical [44:31] observation that the effective sharpness [44:32] stabilizes. And if you solve for this [44:34] set, you get your own very own noise [44:36] schedule and you get a central flow that [44:37] works for RMS prop scalar RMS prop. [44:40] And you'll notice that this also does a [44:41] pretty good job of predicting. So it [44:43] first maintains the invariant that the [44:45] effective sharpness stays the same. It [44:46] also tracks how the evolution of the [44:48] like like regular sharpness grows over [44:51] the course of training. It also tracks [44:52] other things like loss and how a [44:54] new8 grows over the course of training. [45:05] So, [45:06] just to give some commentary on scalar [45:08] RMS prop is doing. So, we know that the [45:11] effective sharpness is staying stable [45:13] and the sharpness itself is growing. [45:15] And while all of this is happening, the [45:16] effective step size is also decreasing. [45:19] So, the way to think about this is that [45:21] scalar RMS prop is actually balancing [45:23] the effective step size to maintain the [45:25] stability at any given point in time. [45:27] So, there is this maximum step size that [45:29] you can take at any given point in time, [45:31] which corresponds to making sure your [45:32] step size is like a like like like a 2 [45:35] over s. And what scalar RMS prop does is [45:39] it stabilizes the new such that this [45:42] invariance is held and you're trying to [45:44] do like the correct learning rate step [45:46] at any given point in time. So, it's [45:48] taking this update sets like adapting to [45:50] the sharpness of the landscape that [45:52] you're training on. [45:53] So, when people talk about adaptive [45:54] optimizers, this is one intuition for [45:56] what adaptive optimizers actually are. [45:58] They're like effectively maintaining [46:00] their like their their new state such [46:03] that the step adapts to the exact [46:05] sharpness of the landscape that you're [46:06] training on. [46:14] So, [46:15] to finish up what scalar RMS prop is [46:17] doing, there's actually this is not the [46:20] only thing that's happening when you're [46:21] doing scalar RMS prop. So, if we have [46:23] this view that the weights are evolving [46:25] according to this like correctly set [46:27] step size, which is 2 over sharpness, we [46:30] still have this sharpness regularization [46:32] term that happens. And in addition to [46:35] also adapting the step size to make sure [46:37] that you're taking the correctly sized [46:38] step at any given point in time, you [46:40] still have this sharpness regularization [46:42] term that's also decreasing your [46:43] sharpness over the course of training. [46:45] So, both adaptive step size is [46:47] happening, but you also have the [46:49] sharpness [46:50] the traditional sharpness regularization [46:51] that we talked about earlier. [46:57] So, [46:58] one cool thing that you can do now that [47:00] you have this central flow setup is that [47:02] you can see what would happen if I had [47:04] an optimizer that only adapted to the [47:06] step size but didn't actually have this [47:08] implicit sharpness regularization. The [47:10] way you can do it is by taking you can [47:12] take your central flow and you can [47:13] remove the term that does that implicit [47:15] sharpness reduction and see what happens [47:17] over to the course of training. [47:19] So in this diagram what you'll see is [47:21] that central flow and scalar RMS prop [47:23] agree and this is a result that we're [47:24] familiar with. But if you remove this [47:26] term the central flow without sharpness [47:28] regularization suggests that if you [47:30] don't have this sharpness regularization [47:31] your loss decreases much more slowly [47:33] much more slowly. [47:35] The main mechanism in which this happens [47:37] is that if you remove this sharpness [47:38] regularization the sharpness is going to [47:40] be increasing a lot more over the course [47:42] of training [47:43] and as the sharpness increases over the [47:45] course of training your effective step [47:47] size which itself depends on the [47:48] sharpness is going to be changing as [47:50] well. [47:51] So instead of the effective step size [47:53] the effective step size is going to [47:54] decay as we talked about because new is [47:56] going to be growing over the course of [47:57] training anyway but if you don't have [47:59] the sharpness regularization then your [48:01] effective step size is going to decrease [48:03] even faster and your training is going [48:04] to be slower. [48:05] So there's a sense in which there's two [48:07] things you want to do. You want to both [48:09] adapt to the loss landscape but you also [48:11] want to keep your sharpness low because [48:12] your sharpness low allows you to like [48:14] keeping your sharpness low and being in [48:15] flatter areas allows you to train faster [48:17] and train with larger step sizes and RMS [48:19] prop kind of has to balance both of [48:21] these desiderata when they're like when [48:23] it operates as an optimizer. [48:28] [snorts] [48:35] So yeah basically this is the same [48:37] explanation. If you have a larger [48:39] learning rate then you have like the you [48:41] can have like higher sharpness [48:42] regularization to increase your [48:44] effective step size. [48:46] And this is like a kind of subtle point [48:48] about what the learning rate in Adam is [48:50] actually doing. [48:52] If you have a higher learning rate in [48:54] Adam or RMS prop what's actually going [48:56] on is that you're increasing your [48:57] sharpness regularization and by [48:59] increasing the sharpness regularization, [49:01] you're increasing your effective step [49:02] size. And that's the method in which [49:04] increasing your learning rate actually [49:05] accelerates training, but it's not [49:07] necessarily just because you're taking [49:08] bigger updates. That's not guaranteed by [49:09] increasing your learning rates in Adam [49:11] because your learning rates in Adam are [49:12] scaled by this by new. [49:20] Uh any questions at the end of this [49:21] point? [49:27] Cool. So finally, we can upgrade from to [49:30] the final [49:31] algorithm that we're going to be [49:32] considering, which is instead of [49:33] thinking about scalar RMS prop, we can [49:35] have full RMS prop. And what full RMS [49:37] prop means is that you basically do the [49:40] same like regular like same effective [49:43] step size, but you do it per parameter [49:45] rather than doing it as global for all [49:47] of the parameters at once. [49:49] Uh qualitatively, this actually behaves [49:51] quite similar to the scalar RMS prop, [49:52] but [49:54] there there's just some key differences. [49:56] But [49:57] one way to think about the what RMS prop [49:59] is doing is that it's equivalent to [50:00] doing diagonal preconditioning. So it's [50:02] taking your gradient update and it's [50:04] rescaling all of the entries by this [50:06] square root new over the learning rate. [50:10] And [50:11] this diagonal preconditioning, it's [50:13] unclear whether this diagonal like a [50:15] priori it's unclear whether this is like [50:17] the right diagonal preconditioning or [50:18] whether it's a wrong one. And maybe like [50:22] as we talked about last lecture, a good [50:23] diagonal like a good preconditioner is [50:25] using the Hessian. [50:26] And it's important to see whether this [50:28] kind of corresponds to using the Hessian [50:30] or whether it's doing something [50:31] completely different. And this is [50:32] something that we can actually build [50:33] intuition for when we're using in the [50:35] central flow world. [50:39] So first, this is just showing how RMS [50:42] prop training works. It's actually has a [50:44] lot less loss spikes than we were seeing [50:46] earlier, but even though it has less of [50:47] these oscillations in loss, it still has [50:49] these oscillations in the individual [50:51] coordinates. [50:53] So that suggests that there's still some [50:54] oscillatory behavior going on when [50:55] you're doing RMS prop. [50:58] And we can think about uh [51:00] we're actually doing, which is that [51:02] we're instead of reasoning about the [51:04] Hessian, which is like the lost [51:05] landscape without any preconditioning, [51:07] we can reason about what happens to the [51:08] lost landscape after doing the [51:10] preconditioning, which is rescaling all [51:11] of the coordinates by learning rate over [51:13] square root new. [51:15] And we want to see whether the like the [51:18] eigen values of the effective Hessian [51:20] obey edge stability and we find that [51:22] they do in fact obey the edge stability [51:24] in this case. [51:30] So now what you can do is you can go [51:32] through a bunch of math which I have [51:33] skipped over here, but you can solve for [51:35] a central flow that also holds for RMS [51:37] prop. The central flow gets uglier and [51:39] uglier as you add more of these tools, [51:40] but there is some central flow that [51:42] exists for this and you can solve it and [51:45] you'll like notice that it makes the [51:46] correct empirical predictions about how [51:48] the eigen values and such evolve over [51:50] the course of training. [51:54] So there is some brief intuition about [51:56] what RMS prop's preconditioner is [51:58] actually doing. So what matrix are you [52:00] using to rescale all of the updates? [52:03] So [52:04] if you think about uh the [52:05] preconditioner, so the preconditioner is [52:07] equivalent to square root of new over [52:10] the learning rate. [52:12] If you solve for what this stationary [52:14] version of this preconditioner actually [52:16] is, so what this preconditioner [52:18] stabilizes to over the course of [52:20] training, [52:21] what it stabilizes to is solving this [52:23] constraint constraint program. So I [52:25] haven't gone through the math to show [52:26] you how this happens, but you can show [52:28] that if you solve for the central flow, [52:29] this is what the preconditioner actually [52:31] looks like. [52:32] And the preconditioner has a couple of [52:33] properties. [52:35] So it first has this constraint about [52:37] stability. So it makes sure that all of [52:40] the Hessian eigen values are underneath [52:43] the effective the like two times the [52:45] effective step size or two over the [52:47] effective step size. So it makes sure [52:49] that you're [clears throat] training [52:50] stably in all of the directions. [52:52] And it also has these other two terms [52:54] which it might as well. [52:56] So the constraint makes sure that you're [52:59] training stably. [53:01] And this first term that you're doing [53:02] over here, the trace of P, the trace of [53:05] P is equal to the sum of the inverse the [53:08] sum of the reciprocals of all the [53:10] learning rates. And since you're [53:11] minimizing this, what you're effectively [53:13] doing is you're trying to increase your [53:15] effective step size in all the [53:16] dimensions at once. [53:17] So if you ignored the second term in [53:20] this optimization program, what you're [53:21] doing is that you're making sure that [53:23] your training is stable while also [53:25] maximizing your learning rate as much as [53:26] possible. So this is what RMS prop is [53:29] intuitively doing if you had ignored the [53:31] second term. [53:32] And now since we have the differential [53:34] equations, we can actually check whether [53:36] this leads to a loss improvement or not. [53:37] And what you'll notice is that if you [53:39] were to do this gradient descent where [53:41] you are optimizing for the trace of P [53:42] every single time, you would get much [53:44] faster training than if you had just [53:45] done plain gradient descent where you [53:47] were not optimizing for these effective [53:48] learning rates properly. [53:54] And interestingly, if you drop this [53:56] second term and you also drop the [53:57] constraint about P being diagonal, then [54:00] you actually the solution to this [54:01] program is in fact the Hessian itself. [54:04] So this is in some sense as close as you [54:06] can get to doing the Hessian if you're [54:07] going to constrain yourself to be doing [54:09] diagonal training. [54:14] Uh [54:15] like on the other hand, there is this [54:18] second term and it's actually like [54:20] directly the optimization speed like [54:21] you're measuring the magnitude of the [54:23] gradient and you're adding that [54:25] literally to the minimization problem. [54:27] So in some sense, doing this [54:28] minimization is actually slowing down [54:30] your slowing down your training. You [54:31] would ideally like to do only this trace [54:33] of P thing, but you have to add this [54:34] other thing. This is more of a comment [54:36] of what RMS prop is actually doing when [54:38] you're training. RMS prop is solving for [54:40] the minimization of this joint program [54:42] and that's why it leads and it leads to [54:43] this slower training than if you were [54:44] hypothetically able to only optimize [54:46] this first term. [54:48] So this is one way in which we can [54:49] analyze the current algorithms and maybe [54:51] this might give inspiration for some [54:52] people about how to change your like [54:54] learning algorithms such that you get [54:56] the correct speed up without having to [54:57] pay the price of implicitly minimizing [54:59] the learning speed as well. [55:05] So just to summarize, uh, we are [55:07] basically normalizing the gradient every [55:09] single update, and we are modulating the [55:12] effective step size, and the effective [55:13] sharpness is what stabilizes when you [55:15] modulate the effective step size. And [55:17] the algorithm has two properties. One is [55:19] that it adapts to the curvature of the [55:20] loss landscape, but it also reduces the [55:23] sharpness, which is quite annoying. And [55:26] the but like I'm sorry, well the [55:28] reducing the sharpness part is quite [55:29] good. It's annoying to reason about, but [55:31] at least reducing the sharpness is what [55:32] allows you to train faster because it [55:34] allows you to boost your effective step [55:35] size and train for longer. [55:37] And you can actually reason about how [55:39] similar RMS prop is to second order [55:41] methods by looking at what the central [55:43] flow is actually optimizing over the [55:44] course of training. [55:47] Uh, any questions here? [55:55] Okay, cool. So, that's all we have to [55:57] say for adjustability. [55:59] Uh, just to add some quick, uh, parts [56:01] like so far we've shown a lot of great [56:03] predictions that adjustability have [56:04] made. There's still a couple of parts [56:06] that aren't fully solved for [56:07] adjustability, and these are like some [56:08] rough corners that you might also see on [56:10] your homework. One is that [56:12] adjustability, we've all done this [56:13] analysis for like different like mean [56:15] square error, but it doesn't hold as [56:16] cleanly for cross entropy loss. [56:18] It also like doesn't we don't have it [56:20] fully solved for like the batch size [56:21] setting which you'll be training in your [56:22] homework. Also for like the full modern [56:25] optimizers like stringing everything [56:26] together, and also like sometimes the [56:28] like central flow broke breaks for like [56:30] higher learning rates. [56:32] The so just to give you some context for [56:35] what's going on in your assignment is [56:36] that you're going to be training models [56:38] using the standard course recipe, and [56:40] you're going to be seeing how the [56:41] sharpness evolves over the course of [56:42] training and seeing whether [56:43] adjustability happens or not, and also [56:45] where it happens, and building some [56:46] intuition for how different [56:47] hyperparameters in the course interact [56:49] with what the adjustability actually [56:50] looks like. [56:52] Finally, one very open question for all [56:54] of this stuff is why progressive [56:55] sharpening happens in the first place. [56:57] As Tatsu said, nobody really knows why. [56:58] It's just like some magic fact that [56:59] happens, and this is something that we [57:01] don't have a good model or theoretical [57:02] explanation for, so that would be really [57:04] nice. [57:05] Um, it will give you a lot of extra [57:06] credit if you're able to figure out why [57:07] in your homework. [57:08] [laughter] [57:11] I hope that's not controversial the [57:12] course staff, yeah. [57:14] [laughter] [57:21] Cool. So we spent a lot of time talking [57:23] about sharpness and like all these [57:24] mental models for why sharpness how [57:26] sharpness changes over the course of [57:27] training. [57:28] Maybe it's worth motivating why we care [57:30] about sharpness in the first place or [57:31] what are reasons that people use it in [57:33] actual like deep learning training runs. [57:35] So sharpness as we talked about so far, [57:38] there is one reason why we care about it [57:40] because sharpness affects the effective [57:42] like learning rate and how fast you do [57:43] the training during the course of [57:44] training. So that's from the [57:46] optimization speed perspective you care [57:47] a lot about sharpness and we've covered [57:49] that also far. Another reason that we [57:51] care about sharpness is more from a [57:53] generalization perspective. [57:55] So [57:57] right now in this class all of our [57:59] training runs have been done with [58:00] unlimited data and you're doing a fixed [58:01] number of steps. Another regime that you [58:03] might care about which we'll study more [58:05] in the generalization homework is if you [58:06] have a fixed amount of data, what's the [58:08] most you can learn from this fixed [58:09] number of samples? [58:11] And in this setting the train loss and [58:14] the validation loss are not the exact [58:15] same. So in your setting train loss and [58:17] validation loss are like pretty close to [58:19] each other because every time you see a [58:20] new batch of training data it's [58:21] effectively like a new batch of data [58:23] that you can validate on. But that's not [58:25] the case in this regime where you [58:26] actually like have a limited number of [58:28] samples. You might be training on your [58:29] train samples many times and it's easy [58:31] to continue bringing down your train [58:32] loss by repeating the data, but your [58:34] validation loss will start going up [58:35] because you're overfitting to the [58:36] specific set of training data that you [58:38] have. [58:39] Here people have this like pretty like [58:42] it's this pretty old intuition that [58:44] people have that ending up in regions [58:47] that are flatter will have models that [58:49] learn more robust functions or like [58:51] generalizing functions that have better [58:53] loss than models that end up in sharper [58:55] regions. [58:56] One cartoon that's commonly brought up [58:58] is you can think of the loss landscape [58:59] of the training function and the loss [59:01] landscape of the test function. And as [59:03] we talked about these loss landscapes [59:04] are slightly different in this world [59:06] where you're limited by data. And [59:07] because these loss landscapes are [59:08] different maybe you want to be in a [59:10] world where the minimum's is So the [59:11] different you pay a less less of a price [59:13] in the difference between these loss [59:15] landscapes versus if you're in the sharp [59:16] minimum, maybe you've overfit to the [59:18] loss landscape. And if you had a small [59:19] perturbation of it, you'd get pretty [59:21] poor loss. [59:23] So this is like one of this is like an [59:25] extremely like dark magic intuition that [59:27] people have about deep learning, that [59:28] ending up in these flatter areas will [59:30] have better generalization for like all [59:32] sorts of like downstream use cases. [59:35] So one like study that you can start [59:37] from over here is this paper called [59:39] Fantastic Generalization Measures. And [59:41] what they do is they train like a [59:43] gazillion models and they track a bunch [59:45] of these statistics that theorists [59:46] predict should predict how well the [59:48] model has generalized or how well the [59:49] model has learned something. There's a [59:51] ton of these different types of [59:52] statistics, but what you can do is you [59:54] can measure between measure the [59:55] correlation between the value of the [59:57] statistic and the value of the model [59:59] performance itself and see which [60:01] statistics are most predictive. Things [60:03] like the norm of the weights or such [60:05] like that might be like core intuitions [60:07] on like things that are predictive [60:08] because like maybe smaller models [60:09] generalize better or something like [60:10] this. But you actually find that at [60:13] least in this paper, they report that [60:15] most of the most like promising one it's [60:18] not perfect and it doesn't do great, but [60:19] the most promising one at least is [60:21] sharpness. [60:22] In fact, the author I believe he gets [60:23] really mad if you say that sharpness is [60:25] the one that all works because he thinks [60:27] that these work. But at least sharpness [60:29] is one of the more promising contenders [60:31] in this list of [laughter] [60:32] generalization measures that people have [60:34] found over the course of working on this [60:35] for a long time. [60:37] Unfortunately, the picture is very very [60:39] complicated and even though sharpness [60:41] looks predictive in this paper, in other [60:43] papers when they try tracking sharpness, [60:45] they find the complete opposite [60:46] conclusion. Sometimes they can find even [60:47] a negative correlation that the sharper [60:49] minima even generalize even better. So [60:51] if you can look at this plot over here, [60:52] you have the sharpness on the x-axis and [60:54] error on the y-axis and you can find [60:57] examples where you correlate really [60:59] well, where lower sharpness means lower [61:01] error. And there's also the complete [61:04] opposite where sometimes higher [61:05] sharpness means lower error instead. [61:09] And you know, it's just one of these [61:10] things where it's like sometimes it's [61:11] right and sometimes it's wrong. And you [61:13] know. [61:14] [laughter] [61:16] In fact, if you really want to go [61:17] extreme on this, you can actually come [61:19] up with very like clean counter examples [61:21] where the global minima are like [61:22] extremely extremely sharp. So this [61:24] picture that the flatter minima [61:26] generalize better is kind of flawed. [61:30] So so yeah, this is like examples where [61:33] one like specific example that really [61:34] gets an issue is that the sharpness [61:37] depends on how you parameterize the [61:38] model. So the way you set the weights [61:40] affects exactly what the sharpness [61:41] values are, even if these weights [61:43] compute the exact same function because [61:44] the Hessian depends on the weights. And [61:46] you can basically take the same [61:47] function, just change how you [61:49] parameterize it and then you would get [61:50] different sharpness for your minima. So [61:52] this is one sense in which sharpness is [61:53] this like really thorny metric that's [61:55] like unclear how much it actually means. [61:59] Uh, on the other hand, a lot of people [62:01] really believe that sharpness was a good [62:03] thing and at least from at least like [62:05] maybe the generalization picture is a [62:07] lot murkier, but maybe people believe [62:09] that flatter minima are a good idea. But [62:11] people and we also know that sharpness [62:13] in the compute perspective is also good [62:14] because it accelerates your training or [62:16] having like flatter minima is good [62:18] or flatter training is good. [62:20] And [62:21] even if we wanted to optimize for the [62:22] sharpness, up till now we've only had a [62:24] few knobs to do this. We can do things [62:26] like increase our learning rate, which [62:28] we know would actually decrease our [62:29] sharpness because it would like increase [62:32] the oscillations or and also like the [62:34] two over eight of threshold. [62:36] Uh, the other thing is like we can lower [62:38] our batch size and enter this even more [62:39] noisy regime and that's like another way [62:41] in which we can like enter flatter [62:43] regions. [62:44] But we don't have a way of directly [62:45] optimizing for it. There's a class of [62:47] algorithms which actually directly [62:49] optimize for the sharpness rather than [62:51] just like observe it or see what's going [62:53] on or change the hyperparameters. So the [62:55] core like the main algorithm that people [62:57] think about is sharpness aware [62:58] minimization. [63:00] So it's like the core intuition for [63:02] sharpness aware minimization, which kind [63:04] of tracks with what a flatter minima [63:05] looks like, is that instead of looking [63:07] for weights that achieve good loss, you [63:09] want to look for weights such that the [63:10] entire neighborhood achieves good loss. [63:12] So it's if the entire neighborhood [63:14] achieve good loss, you must be in like a [63:15] flatter region versus if your [63:17] neighborhood gets bad loss and you get [63:19] good loss, you probably just find a [63:20] sharp minima and not a flat minima. [63:23] The one way you can operationalize this [63:25] is that you can take a gradient not on [63:26] your current weights, but on the worst [63:29] case loss of the weights in like a small [63:31] ball around you. [63:33] So this has like this mathematically is [63:34] also connected to the maximum [63:36] eigenvalue, but this is the way the like [63:38] optimizer operates it operationalizes [63:40] it, which is that it looks for the loss [63:42] in your neighborhood, tries to find a [63:44] point which gets bad loss in your [63:46] neighborhood, and you optimize against [63:47] this point rather than optimizing for [63:49] the current iterate that you're actually [63:50] around. [63:51] And this should hopefully get you to [63:53] like flatter regions of the loss [63:54] landscape. [63:56] So if you look at the original paper, [63:58] there seem to be like some pretty good [64:00] wins. So if you compare SAM, which is [64:01] sharpness aware minimization versus SGD, [64:04] you get like a lower loss on a like a [64:06] lot of different benchmarks. And also [64:07] there's this interesting regime where [64:09] you can think about like specifically [64:10] you add a lot of label noise into your [64:12] data. So you take a lot of the data [64:14] points and you corrupt them, like 20% of [64:15] them you just completely change the [64:17] labels. And this regime is like it [64:18] should be harder to generalize in. And [64:20] SAM does [64:22] SAM does like a lot better than like [64:23] plain SGD in these types of regimes, [64:25] especially as you increase the amount of [64:26] label noise. [64:27] So this is one intuition that people [64:29] have for like a region where like SAM is [64:31] like quite good. [64:35] Um and but SAM [64:38] even though we've motivated in terms of [64:39] minimizing the actual sharpness, it's [64:41] like a really thorny algorithm because [64:43] what it actually optimizes is slightly [64:44] different. And if you think about it [64:45] very carefully, you actually end up [64:47] getting completely different pictures [64:48] for what is actually optimizing. [64:50] So [64:52] has this paper called SAM for [64:54] efficiently improving generalization. [64:55] And in this paper, what they found is [64:57] that if you decrease the batch size, so [65:00] you have this lower values of M, this is [65:02] a region regime where SAM performs the [65:04] best rather than the full batch case. [65:06] The like batch size one case actually [65:08] gets the best generalization. [65:10] And interestingly, what you can prove is [65:12] that in this batch size one case, what [65:13] you're actually minimizing is not the [65:16] sharpness, which is like the maximum [65:17] eigenvalue and like the worst case [65:19] perturbation. What you're actually [65:20] measuring is a average case [65:23] perturbation. So you're sampling like [65:25] basically a random point in the ball [65:26] around you and optimizing for that [65:28] rather than optimizing for like the like [65:30] maximum eigenvalue. [65:32] And the fact that this works the best in [65:34] the low batch size regime suggests that [65:36] the reason that SAM works might not be [65:38] about actually minimizing the sharpness, [65:40] but might be about some all some sorts [65:41] of other things. But this is kind of a [65:43] characteristic picture of how some [65:44] people might have these like intuitions [65:46] from these toy models that they build. [65:47] Try designing some algorithm that tries [65:49] to approximate it. That algorithm kind [65:51] of works well and people don't know why [65:53] and they find that it works for [65:54] completely different reason than [65:55] originally posited and then they analyze [65:57] that instead. [65:58] So this is like a pretty common workflow [66:00] for a lot of deep learning research. [66:05] Um even though this sharpness picture I [66:07] feel like uh has been painted kind of [66:09] murkily in that like sometimes it [66:10] doesn't generalize and sometimes it [66:12] generalizes. This is one of those mental [66:13] models where even though it's wrong a [66:15] lot of the time, it can be right [66:16] sometimes and the times when it's right [66:18] can actually give you a good algorithm [66:20] that you can use in practice, which is [66:21] kind of what you care about like uh [66:23] being able to understand how it works so [66:25] you can pose something new [66:27] uh even if the original reason you posed [66:29] it for ends up being wrong. [66:31] So one intuition that people have is [66:34] that uh well so one this paper called [66:36] Sharpness-Aware Pre-training has this [66:38] intuition that if you ended up in [66:40] flatter regions of the loss landscape, [66:42] then maybe fine tuning would be a lot [66:43] more convenient and it would be a lot [66:44] more like uh destructive towards the [66:46] down like towards the pre-train [66:48] initialization's performance. [66:50] So for example like if you're in a [66:51] flatter region and you are taking [66:53] gradient updates with fine tuning, it [66:54] would be less destructive than you if [66:56] you're in a sharper region and the [66:57] second you take gradient updates, you [66:58] completely destroy where you were or [66:59] you'd end up in completely different [67:00] regimes of the loss landscape. So what [67:02] this paper does is they pre-train [67:04] language models either using like a [67:06] standard optimizer, I believe Adam W in [67:08] this case, or you can use [67:09] sharpness-aware minimization. [67:11] If you look at the pre-trained [67:13] performance, they're SAM is slightly [67:15] worse, but it's like similar to this uh [67:16] optimizer. The interesting thing is [67:18] after fine tuning, what you find is that [67:21] you like face a lot of like forgetting [67:23] in your downstream in like your original [67:25] pre-training task that you actually [67:26] cared about. But for these models that [67:28] were optimized via sharpness or [67:29] minimization, you actually experience [67:31] less forgetting. So this is one sense in [67:33] which ending up in the flatter region [67:34] might have actually helped you. [67:36] Another way you can test for this [67:37] hypothesis is use one of the more [67:38] indirect ways of modulating sharpness [67:40] that we talked about earlier, which is [67:41] that instead of actually like directly [67:43] optimizing for the sharpness, we can [67:44] just like increase the learning rate [67:46] because we know that higher learning [67:47] rates Well, the threshold for [67:50] adjustability is like two over eight up. [67:51] So if you increase the learning rate, [67:53] you're decreasing the sharpness. And as [67:55] you decrease the sharpness, you might [67:56] actually hurt your final performance, [67:58] but in terms of the tradeoff that you [68:00] get between your pre-training loss and [68:01] your fine-tuning loss, it's actually [68:03] Pareto dominant to be in these regimes [68:05] where the sharpness of your like you [68:07] tradeoff the performance of your [68:09] pre-trained model in exchange for [68:10] sharpness of your pre-trained model. [68:13] I also bring this up because so far in [68:14] this class, we've been using validation [68:16] loss as a proxy for all of our [68:18] downstream model performance. But this [68:20] is another example of where pre-training [68:22] This is one of the few like I would say [68:24] few examples where pre-training loss [68:26] actually doesn't give you a good [68:27] prediction for how good your model is [68:28] because if you know you're going to [68:29] fine-tune the model afterward, instead [68:31] of only caring about your loss, it's [68:32] also important to care about your [68:33] sharpness over here because that affects [68:35] how well like stable and like how good [68:36] the fine-tuning dynamics also look like. [68:41] No. [68:42] Any other questions? [68:51] Okay. [68:54] So I think like sharpness is this thing [68:56] that's like a really really like hard [68:58] and I think it's like probably one of [69:00] the softest mental models that we're [69:01] like covering in this class where it's [69:03] like extremely hard to reason about and [69:04] sometimes it's useful and it's like [69:05] extremely frustrating. So I have a [69:08] couple of friends who worked on [69:09] sharpness over the course of their PhD. [69:10] So I asked to collect testimonials from [69:12] them of how it felt like to work on [69:14] sharpness. [69:15] So [69:16] you know, some of these people are a [69:17] little happy. So the second person [69:19] thinks that sharpness is like extremely [69:21] interesting and one of the best things [69:22] ever and you You they're the people that [69:24] write papers about sharpness who are [69:25] pre-training and like using their mental [69:27] model for all these other algorithms. [69:29] A lot of other people are really like [69:31] disturbed by sharpness and feel like [69:33] they wasted a large time of their life [69:34] trying to understand this really [69:35] mysterious object and never made any [69:37] progress on it. [69:38] [laughter] And it's one of I think this [69:40] is like a really like great example of [69:42] these things in deep learning. I think [69:43] this is really like the closest you can [69:44] get to like the alchemy of these things [69:46] where it's like it is like a useful [69:47] mental model and like ways that you [69:49] can't really predict, but a lot of the [69:51] times if you like really strictly obey [69:53] it the same way that you'd like obey a [69:54] theorem or a result in a math class, [69:56] you're just going to be completely in [69:57] like a wrong place and be all like [69:59] you're going to have a horrible time. [70:01] So yeah, just just beware if you think [70:04] about working on sharpness in the [70:05] future, but I think it is very exciting [70:07] and it is very interesting, but you [70:09] know, you just have to be prepared for [70:11] what's going to happen. [70:13] Cool. So just to summarize what we've [70:14] talked about sharpness. So sharpness has [70:16] these properties where first it [70:18] accelerates convergence and these are [70:19] the types of things you can see in the [70:20] adjustability where you like if you [70:22] limit the sharpness you can increase [70:23] your training speed. [70:25] And there are also some like limited [70:27] conclusions where it can actually [70:28] improve your generalization or improve [70:29] your training. [70:30] And like you can also try to directly [70:33] optimize for sharpness, but directly [70:35] optimizing for it is a little hard. We [70:36] guess we have an understanding of how [70:37] the hyperparameters interact with it, [70:39] but we don't have a great way of [70:40] directly modulating the sharpness [70:41] itself, which would be pretty big in [70:43] terms of like compute like training [70:45] speed and generalization if you could [70:46] directly control the sharpness to be the [70:48] value that we care about. [70:49] And also it can be like a helpful mental [70:51] model in designing like algorithms that [70:53] you care about for example in the case [70:55] such as fine tuning. [70:57] Yeah, any other questions? [71:03] That's all I have for today.