    Avoiding spurious sharpness minimization broadens applicability of SAM


                      Sidak Pal Singh 1 Hossein Mobahi 2 Atish Agarwala 2 Yann Dauphin 2


                          Abstract                                  commonly held belief is that it is important for models to
                                                                    converge to well-behaved and robust solutions. The ‘regu-
     Curvature regularization techniques like Sharp-
                                                                    larity’ of the model is often obtained using regularization
     ness Aware Minimization (SAM) have shown
                                                                    techniques, which — even in the day and age of LLMs —
     great promise in improving generalization on vi-
                                                                    remain an indispensable part of any training algorithm.
     sion tasks. However, we find that SAM performs
     poorly in domains like natural language process-               Some of the most prominent regularization methods
     ing (NLP), often degrading performance — even                  include weight decay (Krogh & Hertz, 1991), dropout (Sri-
     with twice the compute budget. We investigate the              vastava et al., 2014), data augmentation (Ciregan et al.,
     discrepancy across domains and find that in the                2012; Krizhevsky et al., 2012), Mixup (Zhang, 2017), and
     NLP setting, SAM is dominated by regularization                curvature-based controls (Foret et al., 2020; Wu et al., 2020).
     of the logit statistics –— instead of improving                In recent years, curvature regularization techniques have
     the geometry of the function itself. We use this               gained popularity due to their effectiveness in promoting
     observation to develop an alternative algorithm                generalization. These techniques bias learning dynamics
     we call F UNCTIONAL -SAM, which regularizes                    to areas of lower curvature (i.e., less sharp regions) in the
     curvature only through modification of the                     loss landscape (Chaudhari et al., 2017; Keskar et al., 2017;
     statistics of the overall function implemented                 Foret et al., 2020; Pittorino et al., 2020; Wu et al., 2020).
     by the neural network, and avoids spurious                     The origins of these curvature or sharpness minimization
     minimization through logit manipulation. Further-              techniques can be traced back to the classical ideas of
     more, we argue that preconditioning the SAM                    minimum description length (Rissanen, 1978; Hinton &
     perturbation also prevents spurious minimization,              Van Camp, 1993; Hochreiter & Schmidhuber, 1997). Lately,
     and when combined with F UNCTIONAL -SAM,                       their development has been inspired by their success in a
     it gives further improvements. Our proposed                    large-scale correlational study (Jiang et al., 2019) and in
     algorithms show improved performance over                      the NeurIPS generalization competition (Jiang et al., 2020).
     A DAM W and SAM baselines when trained for
                                                                    Sharpness minimization has demonstrated significant im-
     an equal number of steps, in both fixed-length
                                                                    provement on vision tasks. In contrast, there has not been
     and Chinchilla-style training settings, at various
                                                                    much uptake of these methods in NLP1 and, especially for as
     model scales (including billion-parameter scale).
                                                                    cornerstone (Brown et al., 2020) a task in NLP as language
     On the whole, our work highlights the importance
                                                                    modeling. Curiously enough, we observe that Sharpness
     of more precise characterizations of sharpness
                                                                    Aware Minimization (SAM), one of the best studied sharp-
     in broadening the applicability of curvature
                                                                    ness regularization methods (Foret et al., 2020), shows poor
     regularization to large language models (LLMs).
                                                                    performance here; indeed, its validation metrics are typi-
                                                                    cally worse than A DAM W throughout training (Figure 1),
1. Introduction                                                     despite using more computation per step. Hence, this raises
                                                                    the following questions which form the basis of our work:
One of the most fundamental questions in machine learning
research is: how do we train models that are useful beyond
                                                                           What are the reasons for SAM’s poor perfor-
their training data? This question arises in multiple scenar-
                                                                           mance in language modeling? How can they be
ios — from generalizing to unseen samples, dealing with
                                                                           addressed to successfully yield generalization ben-
distribution shift, and fine-tuning on specific domains. A
                                                                           efits, while being equal in cost as SAM?
   1
     Google Research 2 Google DeepMind. Correspondence to:
Sidak Pal Singh <ssidak@google.com>.                                Towards this end, in Section 3, we perform a novel analysis
                     nd                                                1
Proceedings of the 42 International Conference on Machine                The most notable exception of SAM in NLP is in the fine-
Learning, Vancouver, Canada. PMLR 267, 2025. Copyright 2025         tuning scenario (Bahri et al., 2022), where the parameters are con-
by the author(s).                                                   strained to move smaller distances by the very nature of the setup.

                                                                1
                                      Avoiding spurious sharpness minimization broadens applicability of SAM

                                Nanodo 23.9M trained on C4                   seek to model the input-output relation via a neural network
                        5.00                                 SAM             f θ (x) : Rd 7→ RK with learnable parameters θ ∈ Rp , such
                                                             AdamW           that f θ (x) ≈ y , ∀ (x, y) ∈ D. We take the usual route
                        4.75                                                 of empirical risk minimization (Vapnik, 1991)
                                                                                                                        P and consider
      Validation Loss


                        4.50                 3.55                            θ ∗ := argminθ ∈ΘΘ L(θθ ) with L(θθ ) := n1 ni=1 ℓ(zi ; θ ) and
                        4.25                                                 where, S = {zi }ni=1 is the training set of size n and ℓ
                                             3.50                            denotes the loss function. Hereafter we will consider the
                        4.00                                                 loss to be cross-entropy, which is the most popular choice;
                                             3.45
                        3.75                          8000      10000        however, our analyses extend to other loss functions as well.
                        3.50                                                 Under the above setup, Foret et al. (2020) formulates
                               2000   4000     6000      8000    10000       sharpness-aware minimization as the following min-max
                                       Training steps                        problem: minθ max∥ϵϵ∥≤ρ L(θθ + ϵ ) , where ϵ denotes a per-
                                                                             turbation of the parameters. In particular, the inner maxi-
Figure 1: Evaluation loss curves of A DAM W and SAM for
                                                                             mization is approximated to first order in the perturbation,
Nanodo decoder-only Transformer model (Liu et al., 2024)
on the C4 dataset (Raffel et al., 2020).                                                       max L(θθ ) + ϵ ⊤ ∇θ L(θθ ) ,                 (1)
                                                                                               ∥ϵϵ∥≤ρ

of the path SAM takes to sharpness reduction, and show                       which subsequently yields ϵ ∗ (θθ ) = ρ ∇θ L(θθ )/∥∇θ L(θθ )∥
that it can be split into two contributions — one which                      as the optimal perturbation. In SAM (Foret et al., 2020),
modifies the logit statistics to reduce sharpness, and the                   the authors propose making an update along the direction,
other which modifies the geometry of the function itself.
We measure these two contributions and find that in vision                                                                  ∇θ L(θ)
                                                                                   g SAM = −∇θ L(θ + ρ ϵ∗ ), ϵ∗ ≡                    .      (2)
(where SAM works well) the contributions are relatively                                                                    ∥∇θ L(θ)∥
balanced; in contrast, in language modeling settings the
logit path to sharpness minimization dominates.                              3. The Dual Routes to Sharpness Minimization
We hypothesize that the functional path to sharpness mini-                   In this section, we develop a diagnostic tool to understand
mization needs to be amplified in the language setting, and                  the failures of SAM in language modeling settings. Our
in Section 4, develop a novel sharpness minimization algo-                   theoretical analysis shows that there are two possible routes
rithm called F UNCTIONAL -SAM that achieves this. Addi-                      to sharpness minimization via SAM— the logit path and
tionally, we motivate another algorithm, PRECONDITIONED                      the functional path. We derive quantities which can be used
SAM, based on preconditioning, and give a theoretical ar-                    to measure the extent to which each route is active. We
gument that shows it promotes the functional path.                           find that each path is relatively balanced in vision, but in
In Section 5, we show that F UNCTIONAL -SAM and PRE -                        language modeling settings (where SAM performs poorly)
CONDITIONED SAM provide improvements over baseline
                                                                             the logit path overwhelms the functional path.
A DAM W when trained on the C4 dataset using the Nan-
odo Transformer codebase (Liu et al., 2024). Moreover,                       3.1. The Penalty Formalization
F UNCTIONAL -SAM and PRECONDITIONED SAM can be                               We begin by looking at PENALTY-SAM, an alternative ver-
combined to yield maximal gains. This resulting com-                         sion of SAM that is often used in theoretical analyses (An-
bination consistently improves validation metrics in both                    driushchenko & Flammarion, 2022; Dauphin et al., 2024)
fixed number of steps as well as Chinchilla-like scaling set-                and whose gradient matches g SAM to first order in ρ:
tings (Hoffmann et al., 2022) at a variety of model sizes,
spanning three orders of magnitude.                                                            min L(θθ ) + ρ ∥∇θ L(θθ )∥ ,                 (3)
                                                                                                θ           |   {z      }
                                                                                                                    SP
We conclude with an extensive discussion, in Section 8,
of additional SAM variants that may be useful in other                       We can think of the added gradient norm term as a sharpness
domains as well as important future directions implied by                    penalty SP. To understand how SP influences optimization,
our work.                                                                    we investigate the structure of its gradient:
                                                                                                                                
                                                                                               ∂                    ∂
2. Setup and Background                                                       ∇θ SP(θθ ) := ρ ∥∇θ L(θθ )∥ =             ∇θ L(θθ ) · ϵ ∗ (θθ ) .
                                                                                               ∂θθ                  ∂θθ
                                                                                                                                             (4)
Let us assume that we are given data points z ∈ Z drawn
i.i.d. from some (unknown) distribution D, where the sam-                    The gradient itself can be decomposed by the chain rule as
ples z are input-output tuples (x, y), with the input x ∈ Rd
of dimension d and the targets y ∈ RK of dimension K. We                                    ∇θ L(θθ ) := ∇θ F (θθ ) · ∇F L(θθ ) ,           (5)

                                                                         2
                                Avoiding spurious sharpness minimization broadens applicability of SAM
                                            ⊤
where F (θθ ) = f θ (x1 )⊤ · · · f θ (xn )⊤    ∈ RKn collates                     τlogit , τfunc , τcross , where the three sum to 1:
the output over the entire dataset. The first term ∇θ F (θθ )
represents the Jacobian (derivative of the model function                                           ∥δlogit ∥2             ∥δfunc ∥2
                                                                                          τlogit :=           2
                                                                                                                , τfunc :=           ,
outputs with respect to parameters); while the second term                                          ∥∇θ SP∥                ∥∇θ SP∥2
                                                                                                                                            (9)
∇F L(θθ ) is the derivative of the loss with respect to the                                           ⟨δlogit , δfunc ⟩
                                                                                          τcross := 2
outputs and which comes out to be the difference of the                                                 ∥∇θ SP∥2
(softmax-ed) logits and the targets.
                                                                                  Hence based on their values, we can realize whether sharp-
Using the product rule, we can rewrite Eqn. 4 as,                                 ness minimization will prioritise reduction of logit sharp-
                                                                                ness more or that of functional sharpness, as well as how
                      ∂
                                       · ϵ ∗ (θθ ) +
                                   
         ∇θ F (θθ ) ·     ∇F L(θθ )                                               correlated they are by looking at the cross term.
                      ∂θθ
       |                  {z                    }
         SP gradient from logit perturbation := δlogit                            3.3. Composition of Sharpness Gradient in Practice
                                          
               ∂
                   (∇θ F (θθ )) · ∇F L(θθ ) · ϵ ∗ (θθ )             .   (6)       We will now analyze SAM’s behavior in language model-
               ∂θθ
             |                  {z                   }                            ing, focusing on how the sharpness gradient composition
       SP gradient from perturbing the function Jacobian := δfunc                 reveals key differences between its application in language
The first term δlogit represents the logit-path to sharpness                      and vision tasks. More concretely, we consider next-token
minimization — directly optimizing the sharpness via the                          prediction task in the case of language using the C4 dataset
effect of the logits on the loss. In contrast, the second term                    and image classification in the case of vision. Since the typ-
δfunc represents the functional-path to sharpness minimiza-                       ical vocabulary sizes in language is in the order of tens
tion — that is, sharpness minimization via modification of                        of thousands, so besides ImageNet-1K, we adopt other
the Jacobian statistics.                                                          datasets like JFT (Sun et al., 2017) and ImageNet-21K (Rid-
                                                                                  nik et al., 2021) to make the settings further comparable
                                                                                  in terms of number of outputs. For both settings, we em-
3.2. Contribution of Logit and Functional paths
                                                                                  ploy Transformer-based networks, Nanodo (Liu et al., 2024),
We can explicitly relate the logit and functional paths to                        which is a simplified version of GPT-2 (Radford et al., 2019),
sharpness minimization (δlogit and δfunc in Eqn. 6) with                          in language modeling and Vision Transformer (ViT, Doso-
a decomposition of the Hessian of the loss HL = ∇θ2 L,                            vitskiy et al., 2021) for vision tasks. Furthermore, in both
                                                                                  cases, we train with A DAM W as the optimizer and measure
∇θ SP = δlogit + δfunc = HG · ϵ ∗ + HF · ϵ ∗ = HL · ϵ ∗                           the normalized sharpness gradient contributions (Eqn. 9)
                                                   (7)                            throughout training using exact Hessian-vector products.
where, we use the Gauss-Newton Decomposition of the                               We present the results for Nanodo, C4 as well as ViT with
Hessian (Schraudolph, 2002), namely:                                              ImageNet-1K and JFT in Figure 2, and that on ImageNet-
                                                                                  21K in Appendix A.1.
                             n
                          1X
                                ∇θ f θ (xi ) ∇2f ℓi ∇θ f θ (xi )⊤
                                                  
HL = HG + HF =                                                                    Observations. Comparing these figures, we find a stark con-
                          n i=1                                                   trast between the language and vision settings. For vision,
                     n     K                                                      we find that the τlogit starts close to 0 but that τlogit and
                 1XX
             +         [∇f ℓi ]k · ∇θ2 f θk (xi )                       (8)       τfunc quickly become comparable for most of the training
                 n i=1                                                            process (Figure 2, leftmost and second from left). In con-
                          k=1
                                                                                  trast for language, the logit-related gradient fraction τlogit
where, the Generalized Gauss Newton (GGN) (HG ) and
                                                                                  is close to 1 while the sharpness gradient related to the
the functional Hessian (HF ) (Singh et al., 2021) are the
                                                                                  functional part is much smaller Figure 2 (second from right
component matrices of the loss Hessian (HL ). The GGN
                                                                                  and rightmost). In all cases, τcross tends to be negative
term captures the curvature of the linearized model; in con-
                                                                                  through most of training (see Figure 4 in the Appendix).
trast, the functional Hessian (also known as the Nonlinear
                                                                                  This suggests that the two paths to sharpness regularization
Modeling Error) captures curvature due to model second
                                                                                  are antagonistic — taking one path moves you against the
derivatives (Dauphin et al., 2024).
                                                                                  other. In language modeling, the dominance of the logit
Thus, we can interpret the gradient through the logit and                         path, combined with negative τcross , means that the overall
functional paths based on the Hessian component they de-                          contribution from the gradient of SP is unaligned, or even
pend upon — the GGN and functional Hessian respectively.                          anti-aligned, with the functional path to sharpness.
Normalized composition of Sharpness Gradient. To                                  Logit Sharpness vs Functional Sharpness. The above
better gauge which mode of sharpness gradient domi-                               observations suggest that in NLP settings, SAM is heav-
nates, we will measure the following natural quantities,                          ily biased towards minimizing sharpness by reducing the

                                                                              3
                                                 Avoiding spurious sharpness minimization broadens applicability of SAM

                                                          ViT, ImageNet1k                                                              ViT JFT
                                      100                                                                           100

             Sharpness composition




                                                                                           Sharpness composition
                                      10 1                                                                         10 1


                                      10 2                                                                         10 2


                                      10 3                                                                         10 3
                                             0     7540     15080 22620 30160 37700                                       0   10680 21360 32040 42720 53400
                                                        Training Steps                                                             Training Steps
                                                      23.9 M, Nanodo, C4                                                       1208.01 M, Nanodo, C4
                                       100                                                                         100
              Sharpness composition




                                                                                          Sharpness composition
                                      10 1                                                                         10 1


                                      10 2                                                                         10 2
                                                                                                                                                          τlogit
                                                                                                                                                          τfunc
                                      10 3                                                                         10 3
                                             0       1600       3200    4800   6400                                       0    41150    82300    123450   164600
                                                           Training Steps                                                          Training Steps

Figure 2: Normalized sharpness contributions τlogit and τfunc show dramatically different trends across modalities. For
ViT trained on ImageNet-1K (leftmost) and JFT (second from left), τlogit starts near 0 but quickly increases to a comparable
magnitude as τfunc . For Transformer models trained on C4 (second from right and rightmost), τlogit ≫ τfunc after the first
few steps of training. This suggests that the pathways to sharpness regularization are more imbalanced in NLP compared to
vision settings, which may contribute to the poor performance of SAM in NLP settings. τcross (plotted in Appendix A.1) is
usually negative, suggesting the two methods of sharpness regularization tend to be antagonistic.


gradient of the loss with respect to the logits. There is                                     These observations lead to the hypothesis that if we could
not much sharpness reduction happening due to making                                          encourage a reduction of functional sharpness in lieu of
the function more well-behaved. While both of these con-                                      logit sharpness, then sharpness minimization might in fact
tribute to decreasing sharpness, the underlying mechanisms                                    work for language modeling too. In the next section, we op-
show interesting differences. Recalling the relation of logit-                                erate under this hypothesis and derive simple but principled
sharpness to the Gauss-Newton term HG , we see that a                                         modifications of the SAM update rule.
simple but spurious way to decrease it is by making the
network over-confident about its predictions. This is be-                                     4. Algorithms to promote the functional path
cause of the presence of the term ∇2f ℓi , which equates to
                                                                                                 to sharpness minimization
diag(pi ) − pi p⊤i , where pi = softmax(f θ (xi )). And thus
as pi becomes more one-hot (irrespective of leading to the                                    From the PENALTY-SAM formulation in Eqn. 3 and the
correct output or the incorrect), the logit sharpness will get                                form of the corresponding sharpness gradients in Eqn. 7, we
reduced.                                                                                      can see that the functional path to sharpness can, in principle,
                                                                                              be amplified by manipulating δlogit and δfunc . However,
In contrast, the functional sharpness is connected to the func-
                                                                                              while PENALTY-SAM is competitive with the SAM
tional Hessian, and the ways of decreasing it (such as via
                                                                                              algorithm, it is less robust than SAM due to ill-behaved
modeling the target better pi → yi ; or reducing the second-
                                                                                              second derivatives (Dauphin et al., 2024). In contrast to
derivative of the function with respect to the parameters
                                                                                              PENALTY-SAM, the perturbation approach in SAM does
∥∇θ2 f ∥ → 0 and hence encouraging a functional simplic-
                                                                                              not explicitly involve second-derivatives in the gradient.
ity) are intuitively more desirable, even though setting a
                                                                                              Therefore, it is important to develop strategies that promote
particular proportion of it might be unclear.

                                                                                      4
                                  Avoiding spurious sharpness minimization broadens applicability of SAM

the functional path using the methodology taken in SAM.                            heterogeneity and improves conditioning.
In this section, we discuss two strategies — one direct and                        Naively combining SAM and A DAM W creates a potential
the other indirect — that promote the functional path to                           mismatch — the SAM perturbation is carried out with re-
sharpness minimization, using algorithms which maintain                            spect to the unpreconditioned geometry. We hypothesize
the benefits of the SAM formulation.                                               that this mismatch offers grounds for spurious sharpness
                                                                                   minimization. To rectify this, we consider preconditioning
4.1. F UNCTIONAL -SAM                                                              the perturbation ϵ ∗ with the inverse of the same second-
                                                                                   moment statistics M from A DAM W, resulting in the update:
The simplest way to promote the functional path would
be to use a perturbation which aligns more with δfunc                                g PRECOND SAM ≡ −∇θ L θ + ρe M−1 (θθ ) ∇θ L(θθ ) , (12)
                                                                                                                                     
than δlogit . We can find such a perturbation by decom-
posing the SAM update rule from Eqn. 2, as follows:                                where ρe := ρ/∥M−1 (θθ ) ∇θ L(θθ )∥, and g PRECOND SAM is
                                                                                   then passed to the rest of Adam in lieu of the gradient
∇θ L(θθ + ρ ϵ ∗ ) = [∇θ F (θθ ) · ∇F L(θθ + ρ ϵ ∗ ) − ∇θ L(θ)]                     ∇θ L(θθ ).
                    |                    {z                  }
                                    δlogit up to first order in ρ
                                                                                   Another motivation for PRECONDITIONED SAM is that
                   ∗
+ [∇θ F (θθ + ρ ϵ ) · ∇F L(θθ ) − ∇θ L(θ)] + ∇θ L(θ) + O(ρ )               2       the gradients often align with the principal eigenspaces of
  |                   {z                 }                                         HG (Gur-Ari et al., 2018). This would amplify δlogit over
              δfunc up to first order in ρ
                                                                    (10)
                                                                                   δfunc , since δlogit = HG · ϵ ∗ and ϵ ∗ is parallel to the
                                                                                   gradient. Preconditioning ϵ ∗ by H−1 G reduces this effect,
The first term is δlogit up to first order in ρ, and the sec-                      thereby promoting the functional path over the logit path
ond term is δfunc up to first order in ρ. This suggests the                        (see Appendix B.1 for a more detailed argument). Although
following update rule which we call F UNCTIONAL -SAM:                              H−1G would be the best preconditioner in this regard, it is
                                                                                   expensive to estimate generally and A DAM W already gives
      g F UNC -SAM = −∇θ F (θθ + ρ ϵ ∗ ) · ∇F L(θθ )                (11)           us a diagonal estimator in its own preconditioner M−1 at
where, we discard the δlogit contribution. Further,                                no additional cost.
F UNCTIONAL -SAM uses the same perturbation ϵ ∗ as the                             To conclude, this algorithm (Eqn. 12) has only marginally
SAM formulation, but only perturbs the Jacobian — thus                             higher computational cost than standard SAM + A DAM W,
emphasizing the functional path to sharpness as desired.                           and provides an indirect way to improve the contribution of
This update rule can be implemented as efficiently as regular                      the functional path to sharpness minimization.
SAM using the very same vector-Jacobian product opera-
tions that are used to compute gradient in most autodiffer-
                                                                                   5. Empirical Evaluation
entiation frameworks. In Appendix C, we provide the JAX
code snippets for SAM and F UNCTIONAL -SAM, demon-                                 5.1. Setup
strating that the difference in their implementation is a mat-
ter of a few lines. Further, like SAM, F UNCTIONAL -SAM                            Training Lengths. In order to evaluate language mod-
remains compatible with methods like A DAM W which take                            els of multiple sizes, we consider (pre-)training them in
a gradient and then further process it.                                            two scenarios: (a) when the training length is kept fixed
                                                                                   across scales and (b) when the training length is adjusted as
Overall, the update rule in Eqn. 11 has the same cost as                           per compute-optimality considerations (Kaplan et al., 2020;
the SAM update rule, and keeps the benefit of the finite-                          Hoffmann et al., 2022).
differences based perturbation approach to sharpness estima-
tion that keeps SAM robust — meeting all our initial goals.                        (a) Fixed-Length Training Scheme. In this setup, we train all
                                                                                   the models for 10K steps, which amounts to seeing roughly
                                                                                   a total of 1.3 billion tokens. The results for this setting are
4.2. PRECONDITIONED SAM
                                                                                   presented in Table 2. (b) Chinchilla-style Training Hori-
In language modeling, Transformers (Vaswani, 2017) are                             zon Scheme. Unlike traditional image-classification based
almost exclusively trained with A DAM W or other adaptive                          scenarios, training language models often involves deter-
methods, and SGD-based training is known to be signifi-                            mining compute-optimal scaling laws, and whereby models
cantly worse (Liu et al., 2020). This is commonly attributed                       are trained on a corpus size in proportion to their parame-
to the presence of heterogeneity in the gradients (Liu et al.,                     ters. Specifically, we follow the 20× over-training policy
2020; Noci et al., 2022; Pan & Li, 2023) and the curva-                            suggested in the Chinchilla (Hoffmann et al., 2022) training
ture (Zhang et al., 2024; Ormaniec et al., 2024; Jiang et al.,                     regime, and use it together with the fixed-depth scheme,
2024) across different “modules” (layer types, layers at dif-                      as considered in Everett et al. (2024). The corresponding
ferent depths, etc.), with the idea that A DAM W alleviates                        results are shown in Table 3.

                                                                               5
                         Avoiding spurious sharpness minimization broadens applicability of SAM

Training Details and Hyperparameters. In both scenar-             efits from preconditioning; we hypothesize that the func-
ios, we consider a batch size of 256 sequences, of maxi-          tional route to sharpness also benefits from reduction in
mum length 512, and evaluate model at 5 different sizes:          heterogeneity across modules and better matching between
2M (for prototyping), 23.9M, 42.5M, 117.9M, and 1208M             inner and outer optimization geometries. Hereafter, we will
in terms of non-embedding parameters (see details in Ap-          use the preconditioned variant for F UNCTIONAL -SAM, in-
pendix A.6), and trained with A DAM W (Kingma & Ba,               stead of just the plain F UNCTIONAL -SAM, to reduce the
2017; Loshchilov & Hutter, 2019) as the underlying opti-          computational costs associated with testing at larger model
mizer on the C4 dataset (Raffel et al., 2020). We used a          scales. This relationship merits further study, which is out-
decoupled weight decay parameter set to 10−4 for all ex-          side the scope of our work.
perimental settings. We use the Nanodo (Liu et al., 2024)
framework to implement these minimal decoder-only Trans-          5.3. Results at Multiple Model Scales
former models, in Flax (Heek et al., 2024) together with
JAX (Bradbury et al., 2018).                                      Hyperparameter Setup. For thoroughness, at each model
                                                                  size separately, we simultaneously tune learning rate and
                                                                  perturbation strength ρ in our experiments, even though this
5.2. Comparison of direct and indirect approaches
                                                                  may be difficult at even bigger model sizes or when faced
Before carrying out an extensive evaluation across differ-        with computational constraints. The upside of this much
ent model scales, we do initial prototyping on a smaller          harder testing ground is to provide us the key assurance that
model size. This lets us save computational resources and         the resulting gains cannot be obtained through other means
scale up the most promising methods. In particular, we are        such as strong hyperparameter tuning of baselines. These
interested in knowing which methods out of direct and indi-       results can be found in Tables 2 and 3.2
rect approaches, and their combinations, are most relevant.
                                                                  In the case of billion-plus parameter model, this procedure
In Table 1, we present results on a model with 2M non-
                                                                  however amounted to extremely high computational costs,
embedding parameters trained in the fixed-length regime.
                                                                  and so we instead tuned the learning rate for the baseline
                                                                  AdamW first. Subsequently, we tuned ρ for all SAM meth-
Table 1: Effect of Preconditioning the SAM perturbation
                                                                  ods based on this corresponding optimal learning rate for
on F UNC -SAM with 2M parameter model when trained
                                                                  AdamW.
for 50K steps and at a peak learning rate of 0.001. Lower
is better.                                                        Observations. We find that in both the training regimes,
                                                                  our proposed algorithms, namely PRECOND F UNCTIONAL -
         M ETHOD                    E VAL L OSS                   SAM and PRECOND SAM, significantly outperform SAM,
                                                                  at all the model scales in Tables 2 and 3. The gains typi-
         A DAM W                        3.901                     cally range from 5 · 10−3 − 10−2 , are largest for 117.9M
         SAM                            3.910                     parameters. We find that SAM performs the worst of the
                                                                  lot, even worse than A DAM W while being 2× computa-
         PRECOND   SAM                  3.889
                                                                  tionally expensive. The numbers reported for SAM repre-
         F UNC -SAM                     3.880                     sent the smallest ρ tested (0.1), since it monotonically gets
         PRECOND F UNC -SAM             3.861                     worse with increasing ρ. Overall, we find that PRECOND
                                                                  F UNCTIONAL -SAM achieves the best results, followed by
We notice that the plain version of F UNCTIONAL -SAM              a mix of PRECOND SAM and A DAM W.
outperforms both A DAM W and preconditioned SAM. But,             At the billion-parameter scale, PRECOND SAM and
F UNCTIONAL -SAM can be further improved by using pre-            SAM show susceptibility to numerical instabilities
conditioning alongside, yielding a significant improvement        (yielding NaNs) across training regimes, whereas PRECOND
in terms of evaluation loss. Also, it should be noted that        F UNCTIONAL -SAM is significantly more robust. In the
the standard deviation across different seeds is typically        relatively cheaper fixed-length runs where we could carry
around ∼ 0.002. Moreover, mid-third decimal differences           out additional investigation, we find that warming up the
in evaluation loss are typical of the gains provided by new       perturbation radius or a lower learning rate choice can
optimization methods for pre-training LLMs look like, e.g.,       sometimes mitigate these issues for PRECOND SAM and
in CASPR (Duvvuri et al., 2024), and even in newer variants       SAM, however, they are still outperformed by our best
of attention (Leviathan et al., 2024), as well as when fus-
                                                                      2
ing LLMs (Mavromatis et al., 2024) or when deduplicating                For brevity, we omit the standard deviation for the baselines
training corpus (Lee et al., 2021). Thus, the kind of gains       in these Tables. But in the Appendix, the reader can also find the
                                                                  full table with standard deviations for all baseline methods as well.
shown in Table 1 are indeed significant.                          The standard deviation for the baselines results are nevertheless
The experiments suggest that F UNCTIONAL -SAM also ben-           very similar.


                                                              6
                           Avoiding spurious sharpness minimization broadens applicability of SAM

Table 2: Evaluation loss comparison of different methods               5.4. Discussion
in a fixed-length (10K steps) training setup, where the op-
timal learning rate is found for each model size separately.           The above-mentioned results demonstrate that the issue
Results are averaged over 5 seeds. For completeness, the               with SAM in NLP can be successfully resolved through
optimal values of the perturbation strength for PRECOND                PRECOND F UNCTIONAL -SAM. The significant improve-
F UNCTIONAL -SAM at the various scales are respectively                ments in validation performance above are especially
0.5, 0.5, 0.4, 0.4. Lower is better.                                   intriguing if we bear in mind that these are obtained (a)
                                                                       even when using a clean corpus such as C4 and (b) training
                                                                       in an online fashion where no batch is seen more than once
               PRECOND          PRECOND
S IZE                                         SAM A DAM W              due to massive size of the C4 corpus (even when training
              F UNC -SAM           SAM                                 for longer duration like in the Chinchilla setup). These are
23.9 M 3.425 ±0.5×10−3             3.431      3.450     3.430          ideal conditions which may not always hold. This suggests
                                                                       that further improvements in generalization may occur
42.5 M  3.344 ±2.2×10−3            3.350      3.366     3.349          when training on noisy corpora or in multipass settings; we
117.9 M 3.218 ±2.2×10−3            3.224      3.257     3.228          leave exploration of these potential effects for future work.
1208 M 3.048 ±1.5×10−3             3.059      NaN       3.056
                                                                       All in all, these results confirm the benefits imparted by
                                                                       F UNCTIONAL -SAM and PRECONDITIONED SAM over
                                                                       SAM, and these improvements in generalization over
                                                                       A DAM W restore the promise of sharpness regularization.
method, PRECOND F UNCTIONAL -SAM, which obtains
a lower evaluation loss and does not need a perturbation
warm-up in either training regime.                                     6. Ablation Studies
                                                                       Perturbation strengths. In the above-mentioned results,
                                                                       the best values for SAM typically occur around perturbation
Table 3: Evaluation loss comparison of different methods in            radius ρ = 0.1, which, in our experiments, happens to
Chinchilla like training (Everett et al., 2024), where the opti-       be the smallest nonzero perturbation radius considered.
mal learning rate is found for each model size separately. All         However, if we employ larger perturbation radii, the
results have been averaged over 5 seeds, except for the more           performance of SAM rapidly deteriorates, as shown in
expensive billion parameter runs which are based on a single           Figure 3 (left), which moreover suggests that the optimal
seed. For completeness, the optimal values of the perturba-            value of perturbation size ρ is 0 — i.e., not using SAM
tion strength for PRECOND F UNCTIONAL -SAM at the vari-                at all. In contrast, the optimal value of perturbation for
ous scales are respectively 0.7, 0.5, 0.4, 0.5. Lower is better.       PRECOND F UNCTIONAL -SAM tends to be much larger,
                                                                       across all values of learning rate as shown in Figure 3
               PRECOND          PRECOND                                (right). This explains why we needed to modify the
S IZE                                        SAM      A DAM W
             F UNC -SAM           SAM                                  relative magnitudes of the sharpness contributions using
                                                                       PRECOND F UNCTIONAL -SAM— the logit term degrades
23.9 M     3.492 ±2.9×10−3        3.498      3.516      3.497          performance at even small ρ, overwhelming the potential
42.5 M     3.340 ±2.0×10−3        3.348      3.359      3.344          gains from the functional path to sharpness minimization.
117.9 M    3.070 ±2.2×10−3        3.074      3.094      3.079          Non-linearity Choice. While all the above experimental
1208 M          2.557             2.562      NaN        2.561          results utilize GeLU non-linearity, we also carry out exper-
                                                                       iments with ReLU as the choice of non-linearity. These
                                                                       results can be found in Table 8 of the Appendix, but the key
We note that for the 1208M parameter models, ρ was tuned               observation is that similar improvements are observed in the
more coarsely due to computational costs. Despite less                 evaluation loss when using PRECOND F UNCTIONAL -SAM
tuning, the gains for PRECOND F UNCTIONAL -SAM persist                 for ReLU based architectures as well.
at this scale in the Chinchilla training horizon experiments.
                                                                       6.1. Sharpness of Final Solutions
In Tables 6 and 7 of the appendix, we also illustrate how
the results fare if a common learning rate of 0.0001 is used           Here, we confirm that the generalization benefits imparted
across all model scales. Interestingly, we find that PRECOND           by PRECOND F UNCTIONAL -SAM are brought about
F UNCTIONAL -SAM is much less sensitive to the lack of                 convergence to a solution with lower curvature, as shown
rightly tuned learning rate than the baselines. As a matter            in the Table 4 for the 23.9M model. Similar results can also
of fact, in such settings we find the corresponding gains to           be found on other model sizes, and Table 9 of the Appendix
be even bigger.                                                        shows them for the 117.9M model.

                                                                   7
                          Avoiding spurious sharpness minimization broadens applicability of SAM




Figure 3: Effect of increasing perturbation strength ρ for SAM (left) and PRECOND F UNCTIONAL -SAM (right) across
various peak learning rates, in an equal compute setup. Each cell shows the evaluation loss, averaged over 5 seeds, at the
corresponding values of learning rate and perturbation radius. The best performing value of perturbation strength at a given
learning rate is marked by white squares, while the overall best learning rate and perturbation strength pair is marked in
green. We see that with SAM any non-zero ρ does worse than the baseline (ρ = 0), while PRECOND F UNCTIONAL -SAM,
with the same compute costs, shows improvements at all values of peak learning rates (Nanodo trained on C4, 23.9M
parameters, Chinchilla like setup).


Table 4: Comparison of different methods based on Hessian           2024; Li & Giannakis, 2024). Some of these methods have
HL and GGN HG maximum eigenvalue and trace for the                  shown small improvements on vision tasks. We believe
23.9M model trained as per Chinchilla like training setup,          our decomposition approach is orthogonal to this line of
with a peak learning rate of 0.001. Lower is better for             research. Therefore, the obtained F UNCTIONAL -SAM al-
all metrics. The best entry is in bold, the second best is          gorithm is substantially different from prior work.
underlined.
                                                                    Studies exploring preconditioning for SAM. Other work
                                                                    has also suggested that the perturbation step in SAM
M ETHOD       E VAL L OSS λmax (HL ) tr(HL )        tr(HG )         should be taken in an alternative geometry. Our approach to
A DAM W          3.688        10.61     4897.52     4745.03         preconditioning is most similar to Fisher SAM (Kim et al.,
                                                                    2022), and the concurrent work of Zhang et al. (2025) which
SAM              3.706         2.71     3324.58     3231.46         describes a more general preconditioning scheme for SAM.
                                                                    Our key insight is that it is useful to take the SAM pertur-
PRECOND
                 3.663         5.62     3182.78     3097.87         bation in the exact same geometry used by the optimizer,
SAM                                                                 which can be accomplished for negligible cost in the case of
PRECOND
                 3.631                                              Adam and its variants. Furthermore, our work is primarily
                               6.20     2687.12     2503.86
F UNC -SAM                                                          driven by the problem of making SAM work in language
                                                                    modeling, which is far from the focus of these other works.
                                                                    Role of the indefinite Hessian term. At a more conceptual
We notice that all sharpness minimization methods yield             level, our study aligns with recent works (Singh et al., 2021;
lower value of the maximum eigenvalue and the trace,                Dauphin et al., 2024) which underscore paying more impor-
as compared to A DAM W. Interestingly, we also find that            tance to the functional Hessian, the understudied indefinite
SAM results in the lowest Hessian maximum eigenvalue,               term of the Hessian in the Gauss-Newton decomposition,
even though it performs much worse than A DAM W when                as opposed to focusing solely on the positive semi-definite
evaluating on the validation set. This further highlights how       GGN term as suggested by prior studies (Sagun et al., 2018;
SAM, by default, in language modeling tasks is set up to            Papyan, 2019; Jacot et al., 2020). The decomposition of the
minimize sharpness spuriously. In contrast, we see that for         sharpness gradient into logit and functional modes, along
both of our proposed methods, the improved generalized              with the demonstrated significance of F UNCTIONAL -SAM
performance comes hand-in-hand with better landscape                in NLP tasks (which is closely tied to the functional Hes-
properties of their solutions.                                      sian), highlights the risks of over-reliance on the GGN and
                                                                    the corresponding outlier spectrum of the Hessian — espe-
7. Related work                                                     cially in the context of regularization of sharpness.

Improved variants of SAM in Vision. An extensive line               SAM in NLP. Prior works building on SAM in NLP have
of work has attempted to propose better definitions of sharp-       been restricted to the fine-tuning setting (Bahri et al., 2022),
ness — particularly those which are less sensitive to details       domain transfer (Sherborne et al., 2024) or on small-scale
of parameterization (Kwon et al., 2021; Tahmasebi et al.,           machine translation setups (Li & Giannakis, 2024). To

                                                                8
                          Avoiding spurious sharpness minimization broadens applicability of SAM

the best of our knowledge, SAM has hitherto not been                 simple demonstration with one-shot pruning in Figure 5
successfully applied to language modeling, particularly in           where we see that F UNCTIONAL -SAM shows a more grace-
any scaling setting.                                                 ful degradation as opposed to A DAM W with increasing
                                                                     sparsity. We leave a detailed study to future work.
8. Discussion and Future Work                                        Efficiency. A common drawback of sharpness minimization
                                                                     methods is that they require twice the gradient computation
There are several important aspects that we would like to
                                                                     per step, and hence are twice as expensive as compared to
elaborate on, which could spark interesting future work:
                                                                     other optimizers like A DAM W. In this paper, our singular
Interpolating smoothly between paths to sharpness mini-              focus has been to address the ineffectiveness of SAM in
mization. In this work, we focused on F UNCTIONAL -SAM               language modeling, which we have been able to carry out
due to our diagnosis of issues in language modeling. How-            successfully through the proposed F UNCTIONAL -SAM and
ever, one can imagine that there might be other domains              its preconditioning variants. However, these algorithms still
where F UNCTIONAL -SAM gives spurious minimization,                  share the same 2× computational burden like SAM itself,
and the alternative “L OGIT-SAM” may need to be empha-               and thus additional work is required in the future to make it
sized. Our implementation of F UNCTIONAL -SAM can                    suitable for deployment. Thankfully, since F UNCTIONAL -
be extended to a more continuous “A NGLE -SAM” which                 SAM is structured similarly to SAM, most advancements
can smoothly interpolate between the extremes, which we              in efficient implementations of SAM should be useful for
discuss in detail in Appendix D. Though we did not find              F UNCTIONAL -SAM as well. Given the plethora of recent
A NGLE -SAM necessary in the language modeling setting,              work in this area for vision (Du et al., 2022; Liu et al., 2022;
there might be other model-dataset-optimizer triples where           Becker et al., 2024; Xie et al., 2024), we are optimistic about
it would prove beneficial.                                           the development of efficient F UNCTIONAL -SAM variants
                                                                     for language modeling in the near future.
The Perturbation Scope. One of the key takeaways from
this work is how scoping the perturbation to the level of the        Data-bound scenarios and model size constraints. In any
function Jacobian suffices to enable the benefits of SAM in          case, we would like to emphasize that our primary compar-
NLP tasks. This scoping can be generalized to any set of             ison point in the paper is that at equal number of steps —
paths or branches in the computational graph. For example,           which is becoming an increasingly relevant scenario. This
the output of network with residual connections can be               is because industrial settings are often bound by data avail-
decomposed into multiple streams like f (x) = f1 (x) +               ability or a limited model size (e.g., inference constraints).
f2 (x) + · · · + fm (x) and practitioners can choose to either       Therefore, here extra training time is acceptable for better
have the perturbation go through all or some of them. This           final quality.
perspective opens the door to many more creative levels of
perturbation scoping and new regularization techniques.              9. Conclusion
Optimal Perturbation Transfer. At the largest scales,
                                                                     Our work thoroughly highlights the ineffectiveness of SAM
extensive tuning of the perturbation radius is unfeasible;
                                                                     for language modeling and uncovers the underlying reasons
F UNCTIONAL -SAM and its variants will benefit from
                                                                     behind such an occurrence. We show that this arises because
improved parameterizations that optimally transfer the per-
                                                                     sharpness reduction in NLP settings is prone to logit ma-
turbation radius across model scales. The recently explored
                                                                     nipulation, and hence spurious sharpness minimization, —
layerwise perturbation scaling regime for SAM in vision
                                                                     rather than being driven by promoting the simplicity of the
tasks (Haas et al., 2024) may be promising for language too.
                                                                     network function. Based on this insight, we propose address-
Utility for Downstream tasks and deployment. An                      ing this issue via F UNCTIONAL -SAM and preconditioning.
added advantage of training with sharpness minimization              We demonstrate that both these simple but principled modi-
methods is that the resulting flatter solutions can adapt more       fications to SAM restore its generalization properties across
gracefully to the post-training pipeline, like downstream            multiple model scales.
fine-tuning or model compression. These benefits have been
                                                                     More broadly, we believe that our novel foray into functional
demonstrated in prior work such as (Liu et al., 2023), where
                                                                     and logit modes of sharpness reduction will reinvigorate the
a lower Hessian trace at the solution has been shown to
                                                                     existing research into SAM, and pave the way for advanced
correlate better with performance on downstream tasks, and
                                                                     curvature regularization techniques. Lastly, we are excited
we expect similar benefits to also hold with F UNCTIONAL -
                                                                     about the nuanced characterization of sharpness introduced
SAM and its variants, given the obtained flatter solutions
                                                                     here and hope that it advances our fundamental understand-
(see Tables 4, 9). Likewise prior work (Na et al., 2022) has
                                                                     ing of sharpness, its dynamics, and the broader nature of
also advocated the use of such methods when subsequent
                                                                     loss landscapes.
model compression is intended, and we also present a very

                                                                 9
                          Avoiding spurious sharpness minimization broadens applicability of SAM

Impact Statement                                                        for image recognition at scale, 2021. URL https:
                                                                        //arxiv.org/abs/2010.11929.
This paper presents work whose goal is to advance the field
of Machine Learning. There are many potential societal                Du, J., Zhou, D., Feng, J., Tan, V. Y., and Zhou, J. T.
consequences of our work, none which we feel must be                    Sharpness-aware training for free. arXiv preprint
specifically highlighted here.                                          arXiv:2205.14083, 2022.

                                                                      Duvvuri, S. S., Devvrit, F., Anil, R., Hsieh, C.-J., and
References
                                                                        Dhillon, I. S. Combining axes preconditioners through
Andriushchenko, M. and Flammarion, N. Towards un-                       kronecker approximation for deep learning. In The
  derstanding sharpness-aware minimization, 2022. URL                  Twelfth International Conference on Learning Represen-
  https://arxiv.org/abs/2206.06232.                                     tations, 2024.

Bahri, D., Mobahi, H., and Tay, Y. Sharpness-aware mini-              Everett, K., Xiao, L., Wortsman, M., Alemi, A. A., Novak,
  mization improves language model generalization, 2022.                R., Liu, P. J., Gur, I., Sohl-Dickstein, J., Kaelbling, L. P.,
  URL https://arxiv.org/abs/2110.08529.                                 Lee, J., et al. Scaling exponents across parameterizations
                                                                        and optimizers. arXiv preprint arXiv:2407.05872, 2024.
Becker, M., Altrock, F., and Risse, B. Momentum-sam:
  Sharpness aware minimization without computational                  Foret, P., Kleiner, A., Mobahi, H., and Neyshabur, B.
  overhead, 2024. URL https://arxiv.org/abs/                            Sharpness-aware minimization for efficiently improving
  2401.12033.                                                           generalization. arXiv preprint arXiv:2010.01412, 2020.
Bradbury, J., Frostig, R., Hawkins, P., Johnson, M. J., Leary,        Gur-Ari, G., Roberts, D. A., and Dyer, E. Gradient
  C., Maclaurin, D., Necula, G., Paszke, A., VanderPlas, J.,            descent happens in a tiny subspace. arXiv preprint
  Wanderman-Milne, S., and Zhang, Q. JAX: composable                    arXiv:1812.04754, 2018.
  transformations of Python+NumPy programs, 2018. URL
  http://github.com/jax-ml/jax.                                       Haas, M., Xu, J., Cevher, V., and Vankadara, L. C. µP2 : Ef-
                                                                        fective sharpness aware minimization requires layerwise
Brown, T. B., Mann, B., Ryder, N., Subbiah, M., Kaplan,                 perturbation scaling, 2024. URL https://arxiv.
  J., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G.,             org/abs/2411.00075.
  Askell, A., Agarwal, S., Herbert-Voss, A., Krueger, G.,
  Henighan, T., Child, R., Ramesh, A., Ziegler, D. M., Wu,            Heek, J., Levskaya, A., Oliver, A., Ritter, M., Rondepierre,
  J., Winter, C., Hesse, C., Chen, M., Sigler, E., Litwin, M.,          B., Steiner, A., and van Zee, M. Flax: A neural network
  Gray, S., Chess, B., Clark, J., Berner, C., McCandlish,               library and ecosystem for JAX, 2024. URL http://
  S., Radford, A., Sutskever, I., and Amodei, D. Language               github.com/google/flax.
  models are few-shot learners, 2020. URL https://
  arxiv.org/abs/2005.14165.                                           Hinton, G. E. and Van Camp, D. Keeping the neural net-
                                                                        works simple by minimizing the description length of the
Chaudhari, P., Choromanska, A., Soatto, S., LeCun, Y., Bal-             weights. In Proceedings of the sixth annual conference
  dassi, C., Borgs, C., Chayes, J., Sagun, L., and Zecchina,            on Computational learning theory, pp. 5–13, 1993.
  R. Entropy-sgd: Biasing gradient descent into wide val-
  leys, 2017. URL https://arxiv.org/abs/1611.                         Hochreiter, S. and Schmidhuber, J. Flat minima. Neu-
  01838.                                                                ral Computation, 9:1–42, 1997. URL https://api.
                                                                        semanticscholar.org/CorpusID:733161.
Ciregan, D., Meier, U., and Schmidhuber, J. Multi-column
  deep neural networks for image classification. In 2012              Hoffmann, J., Borgeaud, S., Mensch, A., Buchatskaya, E.,
  IEEE conference on computer vision and pattern recogni-               Cai, T., Rutherford, E., de Las Casas, D., Hendricks,
  tion, pp. 3642–3649. IEEE, 2012.                                      L. A., Welbl, J., Clark, A., Hennigan, T., Noland, E.,
                                                                        Millican, K., van den Driessche, G., Damoc, B., Guy,
Dauphin, Y. N., Agarwala, A., and Mobahi, H. Neglected                 A., Osindero, S., Simonyan, K., Elsen, E., Rae, J. W.,
  hessian component explains mysteries in sharpness regu-              Vinyals, O., and Sifre, L. Training compute-optimal large
  larization, 2024.                                                     language models, 2022. URL https://arxiv.org/
                                                                        abs/2203.15556.
Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn,
  D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer,              Jacot, A., Gabriel, F., and Hongler, C. The asymptotic
  M., Heigold, G., Gelly, S., Uszkoreit, J., and Houlsby,               spectrum of the hessian of dnn throughout training, 2020.
  N. An image is worth 16x16 words: Transformers                        URL https://arxiv.org/abs/1910.02875.

                                                                 10
                         Avoiding spurious sharpness minimization broadens applicability of SAM

Jiang, K., Malik, D., and Li, Y. How does adaptive optimiza-        Li, B. and Giannakis, G. Enhancing sharpness-aware op-
   tion impact local neural network geometry? Advances in             timization through variance suppression. Advances in
   Neural Information Processing Systems, 36, 2024.                   Neural Information Processing Systems, 36, 2024.

Jiang, Y., Neyshabur, B., Mobahi, H., Krishnan, D., and Ben-        Liu, H., Xie, S. M., Li, Z., and Ma, T. Same pre-training loss,
   gio, S. Fantastic generalization measures and where to             better downstream: Implicit bias matters for language
   find them, 2019. URL https://arxiv.org/abs/                        models, 2023. URL https://openreview.net/
   1912.02178.                                                        forum?id=F5uYcwABMu.

Jiang, Y., Foret, P., Yak, S., Roy, D. M., Mobahi, H., Dz-          Liu, L., Liu, X., Gao, J., Chen, W., and Han, J. Understand-
   iugaite, G. K., Bengio, S., Gunasekar, S., Guyon, I.,              ing the difficulty of training transformers. arXiv preprint
   and Neyshabur, B. Neurips 2020 competition: Pre-                   arXiv:2004.08249, 2020.
   dicting generalization in deep learning, 2020. URL
   https://arxiv.org/abs/2012.07976.                                Liu, P. J., Novak, R., Lee, J., Wortsman, M., Xiao, L., Ev-
                                                                      erett, K., Alemi, A. A., Kurzeja, M., Marcenac, P., Gur,
Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B.,               I., Kornblith, S., Xu, K., Elsayed, G., Fischer, I., Pen-
  Chess, B., Child, R., Gray, S., Radford, A., Wu, J.,                nington, J., Adlam, B., and Dickstein, J.-S. Nanodo: A
  and Amodei, D. Scaling laws for neural language mod-                minimal transformer decoder-only language model im-
  els, 2020. URL https://arxiv.org/abs/2001.                          plementation in JAX., 2024. URL http://github.
  08361.                                                              com/google-deepmind/nanodo.

Keskar, N. S., Mudigere, D., Nocedal, J., Smelyanskiy,              Liu, Y., Mai, S., Chen, X., Hsieh, C.-J., and You, Y. Towards
  M., and Tang, P. T. P. On large-batch training for deep             efficient and scalable sharpness-aware minimization. In
  learning: Generalization gap and sharp minima, 2017.                Proceedings of the IEEE/CVF Conference on Computer
  URL https://arxiv.org/abs/1609.04836.                               Vision and Pattern Recognition, pp. 12360–12370, 2022.

Kim, M., Li, D., Hu, S. X., and Hospedales, T. Fisher sam:          Loshchilov, I. and Hutter, F. Decoupled weight decay regu-
  Information geometry and sharpness aware minimisation.              larization, 2019. URL https://arxiv.org/abs/
  In International Conference on Machine Learning, pp.                1711.05101.
  11148–11161. PMLR, 2022.
                                                                    Mavromatis, C., Karypis, P., and Karypis, G. Pack of llms:
Kingma, D. P. and Ba, J. Adam: A method for stochastic op-           Model fusion at test-time via perplexity optimization.
  timization, 2017. URL https://arxiv.org/abs/                       arXiv preprint arXiv:2404.11531, 2024.
  1412.6980.
                                                                    Na, C., Mehta, S. V., and Strubell, E. Train flat,
Krizhevsky, A., Sutskever, I., and Hinton, G. E. Imagenet             then compress: Sharpness-aware minimization learns
  classification with deep convolutional neural networks.             more compressible models. In Findings of the Asso-
  Advances in neural information processing systems, 25,              ciation for Computational Linguistics: EMNLP 2022,
  2012.                                                               pp. 4909–4936. Association for Computational Lin-
                                                                      guistics, 2022. doi: 10.18653/v1/2022.findings-emnlp.
Krogh, A. and Hertz, J. A simple weight decay can im-                 361. URL http://dx.doi.org/10.18653/v1/
  prove generalization. Advances in neural information                2022.findings-emnlp.361.
  processing systems, 4, 1991.
                                                                    Noci, L., Anagnostidis, S., Biggio, L., Orvieto, A., Singh,
Kwon, J., Kim, J., Park, H., and Choi, I. K. Asam: Adaptive           S. P., and Lucchi, A. Signal propagation in transformers:
 sharpness-aware minimization for scale-invariant learn-             Theoretical perspectives and the role of rank collapse.
 ing of deep neural networks. In International Conference            Advances in Neural Information Processing Systems, 35:
 on Machine Learning, pp. 5905–5914. PMLR, 2021.                      27198–27211, 2022.

Lee, K., Ippolito, D., Nystrom, A., Zhang, C., Eck, D.,             Ormaniec, W., Dangel, F., and Singh, S. P. What does it
  Callison-Burch, C., and Carlini, N. Deduplicating train-            mean to be a transformer? insights from a theoretical
  ing data makes language models better. arXiv preprint               hessian analysis, 2024. URL https://arxiv.org/
  arXiv:2107.06499, 2021.                                             abs/2410.10986.

Leviathan, Y., Kalman, M., and Matias, Y. Selec-                    Pan, Y. and Li, Y. Toward understanding why adam con-
  tive attention improves transformer. arXiv preprint                 verges faster than sgd for transformers. arXiv preprint
  arXiv:2410.02703, 2024.                                             arXiv:2306.00204, 2023.

                                                               11
                          Avoiding spurious sharpness minimization broadens applicability of SAM

Papyan, V. The full spectrum of deepnet hessians at scale:           Srivastava, N., Hinton, G., Krizhevsky, A., Sutskever, I.,
  Dynamics with sgd training and sample size, 2019. URL                and Salakhutdinov, R. Dropout: a simple way to prevent
  https://arxiv.org/abs/1811.07062.                                    neural networks from overfitting. The journal of machine
                                                                       learning research, 15(1):1929–1958, 2014.
Pennington, J. and Bahri, Y. Geometry of neural net-
  work loss surfaces via random matrix theory. In                    Sun, C., Shrivastava, A., Singh, S., and Gupta, A. Revisit-
  Precup, D. and Teh, Y. W. (eds.), Proceedings of                     ing unreasonable effectiveness of data in deep learning
  the 34th International Conference on Machine Learn-                  era, 2017. URL https://arxiv.org/abs/1707.
  ing, volume 70 of Proceedings of Machine Learning                    02968.
  Research, pp. 2798–2806. PMLR, 06–11 Aug 2017.
                                                                     Tahmasebi, B., Soleymani, A., Bahri, D., Jegelka, S., and
  URL https://proceedings.mlr.press/v70/
                                                                       Jaillet, P. A universal class of sharpness-aware minimiza-
  pennington17a.html.
                                                                       tion algorithms, 2024. URL https://arxiv.org/
Pittorino, F., Lucibello, C., Feinauer, C., Malatesta, E. M.,          abs/2406.03682.
   Perugini, G., Baldassi, C., Negri, M., Demyanenko, E.,            Vapnik, V. Principles of risk minimization for learning the-
   and Zecchina, R. Entropic gradient descent algorithms               ory. Advances in neural information processing systems,
   and wide flat minima. CoRR, abs/2006.07897, 2020. URL               4, 1991.
   https://arxiv.org/abs/2006.07897.
                                                                     Vaswani, A. Attention is all you need. Advances in Neural
Radford, A., Wu, J., Child, R., Luan, D., Amodei, D.,                  Information Processing Systems, 2017.
  Sutskever, I., et al. Language models are unsupervised
  multitask learners. OpenAI blog, 1(8):9, 2019.                     Wu, D., tao Xia, S., and Wang, Y. Adversarial weight
                                                                      perturbation helps robust generalization, 2020. URL
Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S.,            https://arxiv.org/abs/2004.05884.
  Matena, M., Zhou, Y., Li, W., and Liu, P. J. Exploring
  the limits of transfer learning with a unified text-to-text        Xie, W., Pethick, T., and Cevher, V. Sampa: Sharpness-
  transformer. Journal of machine learning research, 21                aware minimization parallelized, 2024. URL https:
  (140):1–67, 2020.                                                    //arxiv.org/abs/2410.10683.
                                                                     Zhang, H. mixup: Beyond empirical risk minimization.
Ridnik, T., Ben-Baruch, E., Noy, A., and Zelnik-Manor,
                                                                       arXiv preprint arXiv:1710.09412, 2017.
  L. Imagenet-21k pretraining for the masses, 2021. URL
  https://arxiv.org/abs/2104.10972.                                  Zhang, Y., Chen, C., Ding, T., Li, Z., Sun, R., and Luo,
                                                                       Z.-Q. Why transformers need adam: A hessian perspec-
Rissanen, J. Modeling by shortest data description. Auto-              tive, 2024. URL https://arxiv.org/abs/2402.
  matica, 14(5):465–471, 1978.                                         16788.
Sagun, L., Evci, U., Guney, V. U., Dauphin, Y., and Bottou,          Zhang, Y., Li, B., and Giannakis, G. B. Precondi-
  L. Empirical analysis of the hessian of over-parametrized            tioned sharpness-aware minimization: Unifying anal-
  neural networks, 2018. URL https://arxiv.org/                        ysis and a novel learning algorithm. arXiv preprint
  abs/1706.04454.                                                      arXiv:2501.06603, 2025.

Schraudolph, N. N. Fast curvature matrix-vector products
  for second-order gradient descent. Neural Computation,
  14:1723–1738, 2002.

Sherborne, T., Saphra, N., Dasigi, P., and Peng, H. Tram:
  Bridging trust regions and sharpness aware minimiza-
  tion, 2024. URL https://arxiv.org/abs/2310.
  03646.

Singh, S. P., Bachmann, G., and Hofmann, T. Analytic
  insights into structure and rank of neural network hes-
  sian maps. In Beygelzimer, A., Dauphin, Y., Liang,
  P., and Vaughan, J. W. (eds.), Advances in Neural In-
  formation Processing Systems, 2021. URL https:
  //openreview.net/forum?id=otDgw7LM7Nn.

                                                                12
                                           Avoiding spurious sharpness minimization broadens applicability of SAM

A. Additional Results
A.1. Sharpness Composition Plots

                                                  ViT, ImageNet1k                                                               ViT ImageNet21K
                                 100                                                                             100
        Sharpness composition




                                                                                        Sharpness composition
                                10 1                                                                             10 1

                                   0                                                                               0

                                10 1                                                                             10 1

                                 100                                                                             100
                                       0   7540     15080 22620 30160 37700                                             0   11580 23160 34740 46320 57900
                                                   Training Steps                                                                Training Steps
                                                      ViT JFT                                                                  23.9 M, Nanodo, C4
                                 100                                                                              100
        Sharpness composition




                                                                                         Sharpness composition
                                10 1                                                                             10 1

                                   0                                                                                0

                                10 1                                                                             10 1

                                 100                                                                              100
                                       0   10680 21360 32040 42720 53400                                                0     1600    3200    4800   6400
                                                Training Steps                                                                   Training Steps
                                            1208.01 M, Nanodo, C4
                                100
       Sharpness composition




                                10 1
                                10 2
                                  0
                                10 2                                    τlogit
                                10 1                                    τfunc
                                                                        τcross
                                100
                                       0    41150      82300   123450     164600
                                                  Training Steps

Figure 4: Sharpness contributions τlogit , τfunc and τcross for various datasets. τcross tends to be negative for most of
training.




                                                                                   13
                           Avoiding spurious sharpness minimization broadens applicability of SAM

A.2. Detailed Table Results
Below in Table 5, we include the standard deviation for each of the baseline method as well, in addition to that listed for
PRECOND F UNCTIONAL -SAM in Table 3.

Table 5: Evaluation loss comparison of different methods in Chinchilla like training (Everett et al., 2024), where the optimal
learning rate is found for each model size separately. All results have been averaged over 5 seeds, except for the more
expensive billion parameter runs which are based on a single seed. Lower is better.

                                  PRECOND            PRECOND
                   S IZE                                                   SAM               A DAM W
                                 F UNC -SAM              SAM
                   23.9 M      3.492 ±2.9×10−3    3.498 ±3.6×10−3      3.516 ±2.9×10−3    3.497 ±2.9×10−3
                   42.5 M      3.340 ±2.0×10−3    3.348 ±1.7×10−3      3.359 ±3.4×10−3    3.344 ±2.5×10−3
                   117.9 M     3.070 ±2.2×10−3    3.074 ±4.0×10−3      3.094 ±3.1×10−3    3.079 ±2.7×10−3
                   1208 M           2.557              2.562                NaN                2.561


A.3. Results across Scales at a common learning rate

Table 6: Evaluation loss comparison of different methods in a fixed-length (10K steps) training setup at a common learning
rate of 0.001. Lower is better.

                                              PRECOND        PRECOND
                                  S IZE                                   SAM     A DAM W
                                             F UNC -SAM        SAM
                                  23.9 M         3.527         3.547      3.587     3.565
                                  42.5 M         3.414         3.439      3.462     3.451
                                  117.9 M        3.252         3.266      3.288     3.280
                                  1208 M         3.054         NaN        NaN       3.081


Table 7: Evaluation loss comparison of different methods in Chinchilla like training (Everett et al., 2024) at a common
learning rate of 0.001. Lower is better.

                                              PRECOND        PRECOND
                                  S IZE                                   SAM     A DAM W
                                             F UNC -SAM        SAM
                                  23.9 M         3.631         3.663      3.706     3.688
                                  42.5 M         3.414         3.435      3.460     3.445
                                  117.9 M        3.096         3.108      3.126     3.120
                                  1208 M         2.612         NaN        NaN       2.627




                                                             14
                        Avoiding spurious sharpness minimization broadens applicability of SAM

A.4. Results across non-linearities

Table 8: Comparison of SAM variants across non-linearities for a Nanodo model with 2M (non-embedding parameters) on
C4 dataset.

                                N ON -L INEARITY      M ETHOD              E VAL L OSS
                                                      PRECOND
                                GeLU                                            3.8614
                                                      F UNCTIONAL -SAM
                                                      PRECOND
                                GeLU                                            3.8894
                                                      SAM
                                GeLU                  A DAM W                   3.9069

                                                      PRECOND
                                ReLU                                            3.8777
                                                      F UNCTIONAL -SAM
                                                      PRECOND
                                ReLU                                            3.8937
                                                      SAM
                                ReLU                  A DAM W                   3.9145


A.5. Hessian spectra results at another model size

Table 9: Comparison of different methods based on Hessian HL and GGN HG metrics for the 117.9M model trained as per
Chinchilla like training setup.

                              M ETHOD      E VAL L OSS λmax (HL )     tr(HL )     tr(HG )
                              PRECOND
                                              3.096          8.884   2790.650 2746.559
                              F UNC -SAM
                              PRECOND
                                              3.108          7.415   2920.445 2060.214
                              SAM
                              SAM             3.126          3.381   2235.759 2222.779

                              A DAM W         3.120          9.259   3299.497 3285.881


A.6. Architectural Details.
The 23.9M, 42.5M, 117.9M, and 1208M models have the same depth of 6, and whose width has been scaled together with
the number of heads. In particular, these correspond to h = 9, 12, 20, and 64 heads per block and the width m scales as
m = 64 × h, and the MLP dimension is f = 4 × m. The 2M model used for prototyping has depth 3, 4 heads per block,
width m = 256 and MLP dimension f = 1024.




                                                            15
                           Avoiding spurious sharpness minimization broadens applicability of SAM

A.7. Downstream benefits of sharpness minimization




Figure 5: Effect of one-shot (unstructured) global magnitude pruning: We see that sharpness minimization methods tend
to degrade more gracefully as increasing number of parameters are pruned. Also, from this figure we can see that the
performance gained imparted by F UNCTIONAL -SAM over A DAM W is equivalent to setting about 25% parameters of zero,
and is thus significant.


B. Additional theory
B.1. Argument for reducing matrix-vector products with inverse preconditioning
We will use a random matrix model to reason about the effects of preconditioning with a matrix inverse. Random matrices
have been used to model the spectra of the Hessian of the large models found in machine learning, and in particular treating
the Gauss-Newton and the functional Hessian/NME as independent yields quantitative insights about the structure of the
overall Hessian (Pennington & Bahri, 2017).
Consider two N × N symmetric invertible matrices A and B. Suppose A and B are random and freely independent. Free
independence is the non-commutative analog to classical independence, implied by classical independence of entries in the
limit of large matrix size (Pennington & Bahri, 2017). The key feature it induces is
                                              E[tr[Aj Bk ]] = E[tr[Aj ]]E[tr[Bk ]]                                      (13)
for any j, k, where tr is the trace.
Given a random unit vector v, the expected squared lengths of the matrix vector products with A and B are given by
                                                1                            1
                                  E[∥Av∥2 ] = E[tr[A2 ]], E[∥Bv∥2 ] = E[tr[B2 ]]                                   (14)
                                               N                             N
The ratio r1 of magnitudes is given by
                                                  E[∥Bv∥2 ]       E[tr[B2 ]]
                                             r1 ≡              =                                                   (15)
                                                  E[∥Av∥2 ]       E[tr[A2 ]]

Now consider the norm of w = A−1 v passed through each matrix:
                                            1                  1
                                 E[∥Aw∥2 ] = , E[∥Bw∥2 ] = E[tr[A−1 B2 A−1 ]]                                           (16)
                                            N                N
The new ratio of magnitudes r2 is given by
                                          E[∥Bw∥2 ]          −1 2 −1        E[tr[B2 ]]
                                   r2 ≡             = E[tr[A   B A   ]] =                                               (17)
                                          E[∥Aw∥2 ]                       E[tr[A−2 ]]−1
From Jensen’s inequality, tr[A2 ] ≥ tr[A−2 ]−1 . Therefore r2 > r1 ; preconditioning by the inverse of A causes matrix-vector
products to upweigh products with B relative to products with A, relative to the unpreconditioned product.
In neural network settings, there are non-trivial relationships between the gradient, the Gauss-Newton matrix HG and the
functional Hessian HF ; however, the eigenvectors and eigenvalues of HG and HF are only weakly related. Therefore even
though the exact calculations in the example above don’t hold, we suspect that generically preconditioning by H−1G will
downweigh HG ϵ∗ compared to HF ϵ∗ .

                                                              16
                         Avoiding spurious sharpness minimization broadens applicability of SAM

C. Code Snippets for SAM and F UNCTIONAL -SAM
from jax import grad, vjp
from jax.tree_util import tree_map
from utils import normalize_grad

def sam_gradients(params, loss_fn, rho):

     # compute the usual loss gradient
     dL_dtheta = grad(loss_fn)(params)

     # normalize the gradients
     dL_dtheta = normalize_grad(dL_dtheta)

     # perturb the parameters
     perturbed_params = tree_map(lambda a, b: a + rho * b, params, dL_dtheta)

     # compute the gradient as by SAM
     sam_grad = grad(loss_fn)(perturbed_params)

     return sam_grad


def functional_sam_gradients(params, loss_fn, network_fn, rho):

     # compute the usual loss gradient, but also extract dL_dlogits
     (dL_dlogits), dL_dtheta = grad(loss_fn, hax_aux=True)(params)

     # normalize the gradients
     dL_dtheta = normalize_grad(dL_dtheta)

     # perturb the parameters
     perturbed_params = tree_map(lambda a, b: a + rho * b, params, dL_dtheta)

     # set up the VJP at the perturbed parameters
     _, dF_dtheta_fn = vjp(lambda theta: network_fn(theta), perturbed_params)

     # do the VJP with the (unperturbed) dL_dlogits
     functional_sam_grad = dF_dtheta_fn(dL_dlogits)[0]

     return functional_sam_grad
Listing 1: Illustration of how to get the gradients in the two methods. Functional SAM differs from the SAM implementation
only in the last couple lines




                                                           17
                            Avoiding spurious sharpness minimization broadens applicability of SAM

D. A NGLE -SAM
In this section, we present a general variant of SAM, which includes both F UNCTIONAL -SAM and SAM as its particular
instantiations. The core idea is that once we have been able to decompose the sharpness gradient into those arising from
logit and functional paths, we can design our bespoke or custom versions of SAM which lean more or less towards one path
than another.
To do so, let’s assume that out custom path is at an angle ϕ with the functional path. We weigh the functional path by a
factor of cos(ϕ), while we weigh the logit path by sin(ϕ). Then the gradient update in A NGLE -SAM can be described as:


  g A NGLE -SAM := ∇θ L(θθ ) + sin(ϕ) · glogit + cos(ϕ) · gfunc                                                           (18)
                                                    ∗                                         ∗
  = ∇θ L(θθ ) + sin(ϕ) · [∇θ F (θθ ) · ∇F L(θθ + ρ ϵ ) − ∇θ L(θθ )] + cos(ϕ) · [∇θ F (θθ + ρ ϵ ) · ∇F L(θθ ) − ∇θ L(θθ )] (19)
   = ∇θ L(θθ ) + ρ sin(ϕ) · HG · ϵ ∗ + ρ cos(ϕ) · HF · ϵ ∗ + O(ρ2 )                                                                    (20)

We see that ϕ = π4 recovers SAM upto first order in ρ, while ϕ = 0 would yield F UNCTIONAL -SAM and ϕ = π2 would
result in a variant that optimizes solely along the logit path and which can thus be called L OGIT-SAM. All in all, this shows
how A NGLE -SAM is a clean generalization of SAM, that equips it with a perturbation angle in addition to the usual
perturbation radius ρ.
At some level, this above formulation could be viewed as making an assumption that these two paths are orthogonal3 . On
another level, one can simply think of these weights as a mere strategy to obtain convenient weight settings that have their
sum of squares as unity.
We expect that this approach might pay dividends in different model-dataset-optimizer triples, and we expect this to be an
interesting direction for future work.




   3
     This is not far-fetched. As we noted in our experiments, these two paths tend to be anti-correlated, but often the correlation is quite
small in magnitude and and approaches zero.

                                                                    18
