AI Logic

Glossary

Optimization Landscape

Updated:

Two slices of an optimization landscape. The left shows the loss along one direction in weight space, overlaying the training loss (solid line) and a slightly shifted test loss (dashed line): in the sharp valley the shift greatly increases the loss, while in the flat valley it barely changes. The right shows contour lines of the loss θ1² − θ2², where the central saddle point is the bottom of a valley along θ1 and the top of a hill along θ2

What Is the Optimization Landscape?

The optimization landscape (also called the loss landscape or loss surface) is the terrain of the loss obtained by treating the values of a neural network's weights as a "location" and the corresponding value of the loss function as "altitude." With two weights, it is a surface like the hills and valleys on a map. Real networks have millions to billions of weights, so the landscape has that many dimensions and cannot be seen directly.

Training amounts to searching for the lowest point of this terrain. Gradient descent measures the slope (gradient) at the current location and moves a little at a time in the downhill direction, much like a hiker descending into a valley in fog, relying only on the slope underfoot.

As a result, the shape of the terrain shows up directly as the difficulty of training. A single smooth bowl leads straight to the bottom, but a bumpy terrain can make the optimizer stall or bounce back and forth. Moreover, it is known that even among equally low valleys, the shape of the valley changes performance on unseen data (generalization).

Features of the Terrain: Local Minima, Saddle Points, and Flat vs. Sharp Valleys

The figure above shows typical features of the terrain as slices along one and two directions (the shapes are illustrative examples).

  • Local minimum: a valley lower than everything around it but not the lowest point (the global minimum). Because the gradient is 0 there, gradient descent stops. It was once believed that local minima were the main reason training is difficult.
  • Saddle point: a point that is the bottom of a valley in one direction and the top of a hill in another (right of the figure). The gradient is also 0 here. Dauphin et al. (2014) argued that as the dimension grows, saddle points make up a larger share of the points where the gradient is 0, and that the ratio of saddle points to local minima grows exponentially with the dimension. The area around a saddle point is flat with small gradients, which slows training.
  • Flat and sharp valleys: even with the same depth, there are wide, flat valleys and narrow, sharp valleys (left of the figure). The terrain shifts slightly between training data and test data, so the bottom of a sharp valley tends to have a larger loss on test data. Keskar et al. (2017) showed experimentally that training with a large batch size tends to converge to sharp valleys and a small batch size to flat valleys, and that sharper valleys generalize worse.

Goodfellow et al. (2015) connected the weights before and after training with a straight line and measured the loss along that line. For the models they examined, the loss decreased as if descending a single smooth slope with no obstacles. The authors suggested that the main difficulty of training is more likely the variation in the slope of the terrain (poor conditioning) and the noise in gradients computed from mini-batches than local minima or saddle points.

The apparent "sharpness" of a valley depends on how the weights are scaled. For example, in a ReLU network, scaling up the weights of one layer and scaling down the next layer's weights by the same factor leaves the output unchanged. Yet changing the scale of the weights changes how much the loss varies when moving the same distance, so the valley can look either sharp or flat. Therefore, when comparing the sharpness of valleys across models, first align the scale of the weights, as in the "filter normalization" below.

How to Visualize the Terrain

A terrain with millions of dimensions cannot be viewed directly. Instead, one draws slices centered on the trained weights θ∗\theta^* along one or two randomly chosen directions (Li et al. 2018, Eq. 1).

  1. Draw a random direction δ\delta with the same shape as the weights θ∗\theta^* (for 2D, δ\delta and η\eta) from a normal distribution.
  2. Scale the direction to match the magnitude of the weights (filter normalization). For each jj-th filter in layer ii, set the norm of the direction equal to the norm of the weights. di,j←di,j∥di,j∥ ∥θi,j∥d_{i,j} \leftarrow \frac{d_{i,j}}{\lVert d_{i,j} \rVert}\,\lVert \theta_{i,j} \rVert
  3. Vary the distance from the center α\alpha (for 2D, α\alpha and β\beta) in small steps, compute the loss, and plot it as a curve or contour map. f(α)=L(θ∗+α δ),f(α,β)=L(θ∗+α δ+β η)f(\alpha) = L(\theta^* + \alpha\,\delta), \qquad f(\alpha, \beta) = L(\theta^* + \alpha\,\delta + \beta\,\eta)

Without the scaling in step 2, as noted in the ⚠️ of the previous section, valleys can look sharp or flat merely because of differences in weight scale, making models impossible to compare. Filter normalization can also be applied to fully connected layers (the weights producing one output unit are treated as one filter).

Using this method, Li et al. drew the landscapes of image classification models on CIFAR-10 and showed the following.

  • Residual connections make the terrain smoother: when the residual connections were removed from ResNet, the terrain changed abruptly with depth from nearly convex (a single bowl) to a highly bumpy shape. ResNets with residual connections did not show this change even when made deeper.
  • Widening makes valleys flatter: models with more filters per layer had less noticeable bumps and flatter valleys.
  • Terrain smoothness and error rate change together: models whose terrain became bumpy also had much worse error rates on test data.
LayersWith residual connectionsWithout residual connections
20 layers7.37%8.18%
56 layers5.89%13.31%
110 layers5.79%16.44%

(Error rates on the CIFAR-10 test data. Table 2 of Li et al. 2018. The 56-layer model without residual connections reaches 10.83% when the learning rate is lowered to 0.01.)

How the Terrain Relates to Training Techniques

Many techniques in deep learning can be explained as ways to make the terrain easier to descend, or to make it easier to reach flat valleys.

TechniqueEffect on the terrainSource
Residual connections (ResNet, DenseNet)The terrain is less likely to become bumpy even when the network is deeperLi et al. 2018
Wider layersValleys become flatter and bumps less noticeableLi et al. 2018
Small batch size (SGD)Gradient noise helps escape sharp valleys, making convergence to flat valleys more likelyKeskar et al. 2017
SAMDirectly seeks locations where the surrounding loss is also small (flat valleys)Foret et al. 2021
  • The terrain is determined by everything: the model architecture, the activation function, the data, and the loss function. Even with the same data, changing the architecture changes the terrain.
  • "Flatter valleys generalize better" is a widely used idea, but as noted in the ⚠️ of the previous section, the conclusion can depend on how sharpness is measured. Use it as a guideline and confirm with performance on validation data.

PyTorch example

Show code
python
import copy

import torch
import torch.nn as nn


def loss_on_line(model_start, model_end, loss_fn, x, y, num_points=21):
    """Connect the weights before and after training with a straight line and measure the loss along it (the 1D slice of Goodfellow et al. 2015).

    α = 0 is before training, α = 1 is after training. θ(α) = (1 − α)·θ_start + α·θ_end
    """
    probe = copy.deepcopy(model_end)
    start = dict(model_start.named_parameters())
    end = dict(model_end.named_parameters())
    results = []
    probe.eval()
    with torch.no_grad():
        for i in range(num_points):
            alpha = i / (num_points - 1)
            for name, param in probe.named_parameters():
                param.copy_((1 - alpha) * start[name] + alpha * end[name])
            results.append((alpha, loss_fn(probe(x), y).item()))
    return results


# Try it on a small model (dummy data)
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 3))
model_start = copy.deepcopy(model)          # keep the weights before training
x, y = torch.randn(256, 20), torch.randint(0, 3, (256,))
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
for _ in range(200):
    optimizer.zero_grad()
    loss_fn(model(x), y).backward()
    optimizer.step()

for alpha, loss in loss_on_line(model_start, model, loss_fn, x, y):
    print(f"α = {alpha:.2f}  loss = {loss:.4f}")

FAQ

Q. Are the optimization landscape and the loss landscape the same thing?
A.

Yes, they refer to the same thing. In English it is usually called the loss landscape or loss surface. The name compares the shape of the loss function's values, as the weights change, to a terrain.

Q. Does getting stuck in a local minimum make training fail?
A.

In large networks, this is thought to rarely be the main problem. Dauphin et al. (2014) argued that in high dimensions, most points with zero gradient at high loss are saddle points, and local minima with high loss are exponentially rare. In the experiments of Goodfellow et al. (2015), training was likewise not observed to be stopped by local minima or saddle points along its path.

Q. How can I look at the landscape of my own model?
A.

The simplest method is to connect the weights before and after training with a straight line and measure the loss along it (see the implementation example). To compare valley shapes across models, draw slices along random directions with the filter normalization of Li et al. (2018). A 2D contour map requires computing the loss at every grid point, so it is a good idea to try it with a smaller dataset.

References

  1. H. Li, Z. Xu, G. Taylor, C. Studer, and T. Goldstein, "Visualizing the Loss Landscape of Neural Nets," NeurIPS, 2018.
  2. I. J. Goodfellow, O. Vinyals, and A. M. Saxe, "Qualitatively characterizing neural network optimization problems," ICLR, 2015.
  3. Y. N. Dauphin, R. Pascanu, C. Gulcehre, K. Cho, S. Ganguli, and Y. Bengio, "Identifying and attacking the saddle point problem in high-dimensional non-convex optimization," NeurIPS, 2014.
  4. N. S. Keskar, D. Mudigere, J. Nocedal, M. Smelyanskiy, and P. T. P. Tang, "On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima," ICLR, 2017.
  5. P. Foret, A. Kleiner, H. Mobahi, and B. Neyshabur, "Sharpness-Aware Minimization for Efficiently Improving Generalization," ICLR, 2021.