AI Wiki中文/EN

Loss landscapes: the same function can look sharper

损失地形

Rescale a two-layer linear model without changing predictions, compare Hessians and inspect normalized slices.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

A loss-landscape picture puts parameter perturbations on horizontal axes and loss on the vertical axis. It can reveal a ridge, a valley or a training path—but only along the directions that were chosen. A neural network with millions of parameters does not have a single faithful two-dimensional portrait.

There is a more basic problem: two parameter vectors can represent exactly the same prediction function yet look differently sharp under equal-sized coordinate perturbations. Dinh and colleagues use function-preserving scale transformations to expose this issue. We can reproduce the mechanism with just two scalar weights and verify every derivative.

Definitions and derivation

Take a two-layer scalar linear model and one training pair x=y=1:

fa,b(x)=abx,L(a,b)=12(ab−1)2,(a,b)↦(ca,b/c),c>0.f_{a,b}(x)=abx,\qquad L(a,b)=\tfrac12(ab-1)^2,\qquad (a,b)\mapsto(ca,b/c),\quad c>0.

The scale transformation leaves the product ab unchanged, so predictions are identical for every input x, not just the training point. Every point on ab=1 has zero training loss. Its gradient is (ab−1)(b,a). Differentiating again gives:

∇2L(a,b)=(b22ab−12ab−1a2),ab=1:eig⁡(∇2L)={0,a2+b2}.\nabla^2L(a,b)=\begin{pmatrix}b^2&2ab-1\\2ab-1&a^2\end{pmatrix},\qquad ab=1:\quad\operatorname{eig}(\nabla^2L)=\{0,a^2+b^2\}.

At (1,1), the nonzero Hessian eigenvalue is 2. At (10,0.1), it is 100.01. The functions are identical, but the largest local curvature differs by more than a factor of fifty. Adding an absolute 0.1 to b produces losses 0.005 and 0.5 respectively.

One remedy for this particular scale effect is to measure perturbations relative to parameter magnitudes. For two positive scalar filters, the normalized slice is:

S(u,v)=L ⁣((a,b)+(u∣a∣,v∣b∣)),a,b>0, ab=1:S(u,v)=12((1+u)(1+v)−1)2.S(u,v)=L\!\left((a,b)+(u|a|,v|b|)\right),\qquad a,b>0,\ ab=1:\quad S(u,v)=\tfrac12\big((1+u)(1+v)-1\big)^2.

The dependence on a and b cancels. Thus both parameterizations have exactly the same relative slice. Li and colleagues, Section 4, normalize random directions by the norm of each corresponding filter in a network. Our two-scalar construction is a small special case illustrating the motivation, not a reproduction of their neural-network plots. Filter normalization is not a proof of invariance to every reparameterization.

A zero Hessian eigenvalue also needs care. At (1,1), the direction (1,−1) has zero quadratic curvature. A straight displacement t in that direction produces product 1−t² and loss t⁴/2. The exact zero-loss set is curved; following a tangent line does not stay on it.

Both parameter pairs predict the same function. Absolute coordinate perturbations give different profiles; relative perturbations overlap. The two panels use different vertical scales, labeled in loss units.
Both parameter pairs predict the same function. Absolute coordinate perturbations give different profiles; relative perturbations overlap. The two panels use different vertical scales, labeled in loss units.

Run the calculation

Run this complete Python 3.12 / NumPy 1.26.4 program. It evaluates analytical derivatives and both absolute and relative slices; no stochastic training is needed for the counterexample.

import numpy as np


def loss(point):
    a, b = np.asarray(point, dtype=float)
    return float((a * b - 1) ** 2 / 2)


def gradient(point):
    a, b = np.asarray(point, dtype=float)
    return (a * b - 1) * np.array([b, a])


def hessian(point):
    a, b = np.asarray(point, dtype=float)
    return np.array([[b * b, 2 * a * b - 1], [2 * a * b - 1, a * a]])


def rescale(point, scale):
    point = np.asarray(point, dtype=float)
    if point.shape != (2,) or not np.isfinite(point).all() or not np.isfinite(scale) or not 0.01 <= scale <= 100:
        raise ValueError('Use two finite parameters and a positive bounded scale.')
    return point * np.array([scale, 1 / scale])


def surface(point, axis, relative=False):
    point, axis = np.asarray(point, dtype=float), np.asarray(axis, dtype=float)
    if point.shape != (2,) or axis.ndim != 1 or not 1 <= len(axis) <= 65 or not np.isfinite(np.r_[point, axis]).all():
        raise ValueError('Use a finite point and 1 to 65 slice coordinates.')
    scales = np.abs(point) if relative else np.ones(2)
    return np.array([[loss(point + scales * [u, v]) for u in axis] for v in axis])


if __name__ == '__main__':
    base, stretched = np.array([1.0, 1.0]), rescale([1, 1], 10)
    axis = np.linspace(-0.1, 0.1, 9)
    for point in (base, stretched):
        print('parameters', point.tolist(), 'product', float(np.prod(point)),
              'Hessian eigenvalues', np.linalg.eigvalsh(hessian(point)).round(9).tolist())
        print('absolute b perturbation loss', round(loss(point + [0, 0.1]), 9),
              'relative b perturbation loss', round(loss(point + [0, 0.1 * abs(point[1])]), 9))
    print('relative surface difference', float(np.max(np.abs(surface(base, axis, True) - surface(stretched, axis, True)))))
    tangent = np.array([1.0, -1.0])
    print('zero-curvature tangent: t=0.1 loss', round(loss(base + 0.1 * tangent), 9))

Actual output:

parameters [1.0, 1.0] product 1.0 Hessian eigenvalues [0.0, 2.0]
absolute b perturbation loss 0.005 relative b perturbation loss 0.005
parameters [10.0, 0.1] product 1.0 Hessian eigenvalues [0.0, 100.01]
absolute b perturbation loss 0.5 relative b perturbation loss 0.005
relative surface difference 3.469446951953614e-17
zero-curvature tangent: t=0.1 loss 5e-05

The relative-surface discrepancy is about 3.5×10⁻¹⁷, consistent with floating-point rounding around an algebraic equality. The straight tangent displacement t=0.1 has loss 0.00005 despite zero quadratic curvature. Independent tests finite-difference the gradient to recover the Hessian and compare rescaled predictions on several inputs.

A k-by-k slice requires k² loss evaluations, regardless of how many parameter directions were omitted. A full d-dimensional Hessian costs O(d²) storage; directional curvature can instead be evaluated with Hessian–vector products. Neither a smooth slice nor one small eigenvalue establishes low population error.

When the method fails

Specify the slice center, direction construction, normalization, loss reduction and data before comparing pictures. Fix evaluation randomness and stateful-layer behavior so a pixel in the plot corresponds to a reproducible loss value. A cut through a saddle can look like a minimum if the negative-curvature direction is omitted.

The rescaling example concerns a linear factorization and the paper’s related homogeneous-network arguments. It does not assert that arbitrary tanh networks have the same scaling symmetry. Relative normalization also needs a convention for zero-norm filters: multiplying by zero produces no perturbation. SAM neighborhoods, weight decay and optimizer updates depend on coordinates too; compare their stated metrics rather than using “flat” as a synonym for “good.”

Exercises with answers

  1. Does rescaling (1,1) to (10,0.1) change f(x) on unseen inputs?

Answer 1: No. Both predict x for every input, because their weight products equal one.

  1. What are the Hessian eigenvalues at (2,0.5)?

Answer 2: Zero and 2²+0.5²=4.25.

  1. Why is a zero-curvature tangent not a flat straight path here?

Answer 3: The quadratic term vanishes, but the loss along the tangent is t⁴/2. Higher-order variation remains.

  1. What information is missing from a two-dimensional slice of a million-parameter model?

Answer 4: Behavior outside the selected two directions, including possible negative curvature and other low-loss routes.

Sources and next steps

Dinh’s scale-transformation argument motivates the identical-function counterexample. Li’s filter-normalization discussion motivates relative perturbations. All surfaces, derivatives and numbers in this chapter are original calculations. Continue with SAM for an optimizer that explicitly uses a parameter neighborhood.

Make a prediction, then check

What changes under the example’s function-preserving rescaling?

Choose one answer

Learning objectives

  • Construct identical functions with different coordinate sharpness.
  • Explain what normalized slices and zero curvature can and cannot show.

Prerequisites & connections

Explore related knowledge →

References

  1. Visualizing the Loss Landscape of Neural Nets — arXiv v3
    Hao Li; Zheng Xu; Gavin Taylor; Christoph Studer; Tom Goldstein · 2018
  2. Sharp Minima Can Generalize For Deep Nets
    Laurent Dinh; Razvan Pascanu; Samy Bengio; Yoshua Bengio · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. All eight programs use NumPy 1.26.4. Tests include augmentation geometry, exact quadratic certificates, finite differences, spectral solutions, conditional risk decompositions and masked neural-network training. CPU teaching calculations, not framework or GPU benchmarks.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • Bilingual SVGs generated with Matplotlib 3.9.1 from executed article functions: actual pixel replacement, conditional-risk quantiles and absolute/relative loss profiles. Captions distinguish probability from pixels, interquartile ranges from confidence intervals and separate plot scales. Locale figures and sample data are hash-bound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.