Flat Posterior Does Matter For Bayesian Model Averaging

## Abstract

Abstract Bayesian neural network (BNN) approximates the posterior distribution of model parameters and utilizes the posterior for prediction via Bayesian Model Averaging (BMA). The quality of the posterior approximation is critical for achieving accurate and robust predictions. It is known that flatness in the loss landscape is strongly associated with generalization performance, and it necessitates consideration to improve the quality of the posterior approximation. In this work, we empirically demonstrate that BNNs often struggle to capture the flatness. Moreover, we provide both experimental and theoretical evidence showing that BMA can be ineffective without ensuring flatness. To address this, we propose Sharpness-Aware Bayesian Model Averaging (SA-BMA), a novel optimizer that seeks flat posteriors by calculating divergence in the parameter space. SA-BMA aligns with the intrinsic nature of BNN and the generalized version of existing sharpness-aware optimizers for DNN. In addition, we suggest a Bayesian Transfer Learning scheme to efficiently leverage pre-trained DNN. We validate the efficacy of SA-BMA in enhancing generalization performance in few-shot classification and distribution shift by ensuring flat posterior 1 1 1 Code for this paper is available in https://github.com/MLAI-Yonsei/SA-BMA . .

## 1 Introduction

Bayesian neural network (BNN) provides a theoretically grounded framework for modeling uncertainty in deep learning by approximating the posterior distribution of model parameters (MacKay, ; Hinton & Van Camp, ; Neal, ). The approximated posterior is used for making predictions through Bayesian Model Averaging (BMA) (Wasserman, ; Fragoso et al., ; Wilson & Izmailov, ; Zeng & Van den Broeck, ). It allows BNNs to account for uncertainty in predictions, leading to more reliable outcomes compared to the deterministic neural network (DNN) (Kapoor et al., ; Kristiadi et al., ). The accuracy and robustness of BNN predictions are heavily dependent on the quality of the approximated posterior (Kristiadi et al., ; Wenzel et al., ).

One key factor influencing posterior quality is the flatness of the loss landscape. Flat modes of the loss landscape have been strongly associated with better generalization performance, as they represent solutions that are less sensitive to small perturbations in model parameters (Hochreiter & Schmidhuber, ; Keskar et al., ; Neyshabur et al., ). The concept of flatness has been extensively studied in the context of DNNs, but no comprehensive analysis has been conducted on its role in BNNs or its impact on BMA. The significance of flatness in BNNs has only been explored in a limited number of studies. SA-BNN (Nguyen et al., ) incorporated a flat-seeking optimizer into BNNs with a theoretical foundation. However, SA-BNN adapted a DNN-based optimizer to BNNs without considering the probabilistic nature of BNNs, resulting in only limited improvements. On the other hand, E-MCMC (Li & Zhang, ) introduced a guidance model to achieve flat posteriors, but this approach is less suited for large-scale models.

In this work, we first demonstrate that BNNs often struggle to capture the flatness. In detail, we compare the flatness of various BNN frameworks, including SWAG, VI, and MCMC, against that of DNNs. Furthermore, we show that BMA can be ineffective without ensuring flatness in the posterior distribution. These findings highlight the need for an optimization strategy that accounts for the probabilistic nature of BNNs to effectively estimate flat posteriors.

Therefore, we propose Sharpness-Aware Bayesian Model Averaging (SA-BMA), a novel optimization approach that explicitly targets flat posterior distributions.
We first compute the adversarial posterior that belongs to the vicinity of the current posterior through divergence, which maximizes the BNN loss function. After that, we update the posterior by employing the gradient of the adversarial posterior with respect to the BNN loss. We show that the proposed SA-BMA is an extended version of previous flatness-aware optimizers, Sharpness-aware Minimization (SAM) (Foret et al., ), Fisher SAM (FSAM) (Kim et al., ), and Natural Gradient (NG) (Amari, ) with specific conditions. Additionally, we propose a Bayesian Transfer Learning scheme integrated with SA-BMA, allowing for more efficient utilization of pre-trained models. We prove that SA-BMA improves the generalization performance of BNNs, particularly in few-shot classification and distribution shift scenarios, by ensuring flatness in the posterior.

Our major contributions are summarized as follows:

- •
We demonstrate that BNN often struggle to capture the flatness. Moreover, we show that BMA can be ineffective without flatness in the posterior.
- •
We suggest a Bayesian-fitting flat posterior seeking optimizer, SA-BMA. SA-BMA is a parameter space loss geometric optimizer, a generalized version of other loss geometric optimizers, such as SAM, FSAM, and NG.
- •
We propose a Bayesian Transfer Learning scheme integrated with SA-BMA to efficiently utilize pre-trained models. This scheme aims to enhance the generalization performance of BNN, especially in few-shot classification and distribution shifts, by ensuring posterior flatness.

## 2 Preliminary

### 2.1 Bayesian Neural Network

Bayesian neural network (BNN) aims to estimate the posterior distribution $p(w|\mathcal{D})$ of model parameters $w\subseteq\mathbb{R}^{p}$ with observed data points $\mathcal{D}=\{(x,y)\}$ with inputs $x$ and outputs $y$. The posterior distribution $p(w|\mathcal{D})$ is calculated by Bayes’ Rule:

$$ $p(w|\mathcal{D})=\frac{p(\mathcal{D}|w)p(w)}{\int_{w}p(\mathcal{D}|w)p(w)dw},$ (1) $$

where $p(\mathcal{D}|w)$ and $p(w)$ denote the likelihood of data $\mathcal{D}$ and the prior distribution over $w$, respectively.
Due to the high dimensionality of neural networks, it is intractable to compute the marginal likelihood (evidence) of Eq. (1). Numerous studies have focused on approximating the posterior $p(w|\mathcal{D})$ with variational parameter $\theta\subseteq\mathbb{R}^{q}$ as $q_{\theta}(w|\mathcal{D})$, including Markov Chain Monte Carlo (MCMC) (Welling & Teh, ; Chen et al., ), Variational Inference (VI) (Graves, ; Ranganath et al., ; Blundell et al., ), and other variants employing DNN (MacKay, ; Ritter et al., ; Daxberger et al., ; Gal & Ghahramani, ; Maddox et al., ). Typically, model parameters are assumed to follow a Gaussian distribution $\mathcal{N}(\mu,\Sigma)$, where $\theta$ encompasses the mean $\mu$ and the covariance $\Sigma$.

Based on the approximated posterior, BNN makes predictions of the model on unobserved data $(x^{*},y^{*})$ through Bayesian Model Averaging (BMA):

$$ $\displaystyle p(y^{*}|x^{*},\mathcal{D})$ $\displaystyle\approx\int_{w}p(y^{*}|x^{*},w)q_{\theta}(w|\mathcal{D})dw$ (2) $\displaystyle\approx\frac{1}{M}\sum_{m=1}^{M}p(y^{*}|x^{*},w_{m}),\ \ w_{m} \sim q_{\theta}(w|\mathcal{D}),$ (3) $$

where $M$ denotes the number of sampled models. Unfortunately, the integral in Eq. (2) is intractable. Monte Carlo integration (Eq. (3)) is a representative method to approximate posterior predictive. BNNs marginalize diverse solutions over the posterior of model parameters through BMA.

### 2.2 Flatness and Optimization

Many studies have connected the flatness of loss surface and generalization (Hochreiter & Schmidhuber, ; ; Keskar et al., ; Neyshabur et al., ). The Hessian eigenvalue of loss is a widely adopted method for measuring the flatness of model, as smaller value indicates flatter regions in the loss landscape. However, due to the large size of neural networks, it is impractical to examine all eigenvalues. Therefore, maximal eigenvalue $\lambda_{1}(w)$ or ratio of eigenvalue $\lambda_{1}(w)/\lambda_{5}(w)$ is often used to compare flatness of model parameter, where $\lambda_{i}(w)$ denotes $i$-th maximal eigenvalue of model parameter $w$ (Keskar et al., ; Foret et al., ; Jastrzebski et al., ).

On the top of the connection between flatness and generalization, the local entropy (Baldassi et al., ; ) is one way to find flat minima. Typically, Entropy-SGD (Chaudhari et al., ) and Entropy-SGLD (Dziugaite & Roy, ) suggested finding flat modes by approximating the local entropy with a nested chain. On the other hand, SAM (Foret et al., ) aims to find parameters lie in the neighborhood $\gamma$ where the loss is consistently low by solving a min-max optimization problem. Within $\gamma$-ball neighborhood, the objective function of SAM is defined as:

$$ $l^{\gamma}_{\text{SAM}}(w)=\min_{w}\max_{\|\Delta w\|_{p}\leq\gamma}l(w+\Delta w),$ $$

where $l(\cdot)$ is the empirical loss function, such as cross-entropy loss in classification. $p$ is practically set to two, yielding $\Delta w=\gamma\nabla_{w}l(w)/\|\nabla_{w}l(w)\|_{2}$.
On the one hand, FSAM (Kim et al., ) proposed replacing the Euclidean ball in SAM with a natural non-Euclidean ball induced by Fisher information:

$$ $l^{\gamma}_{\text{FSAM}}(w)=\min_{w}\max_{\|F_{y}(w)\Delta w\|_{p}\leq\gamma^{ 2}}l(w+\Delta w),$ $$

where the Fisher information matrix (FIM) is approximated as $F_{y}(w)=1/|B|\nabla_{w}\log p(y|x,w)^{2}$ and $|B|$ denotes batch size. The Fisher inverse matrix is approximated as $F_{y}(w)^{-1}=1/\sqrt{1+\eta F_{y}(w)}$, with a hyperparameter $\eta$. This results in a closed-form perturbation, $\Delta w=\gamma\frac{(F_{y}(w)^{-1})^{2}\nabla_{w}l(w)}{\|F_{y}(w)^{-1}\nabla_
{w}l(w)\|_{2}}$, for $p=2$. In other words, by preconditioning approximated FIM $F_{y}(w)$ over predictive distribution, FSAM attempts to find curvature-aware perturbation. SAM and FSAM are derived under deterministic $w$, and the $F_{y}(w)$ is defined in predictive distribution $p(y|x,w)$, not in parameter space.

Figure: Figure 1: Flatness comparison between DNNs and BNNs. We measured the Error and NLL on CIFAR10 and CIFAR100. To assess flatness, we used the maximal Hessian eigenvalue of the loss, $\lambda_{1}$, where lower values indicate flatter models. BNN frameworks—VI, MCMC, and SWAG—were compared against DNNs trained with SGD and SAM, with SAM being a flatness-aware optimizer for DNNs. The results suggest that BNNs may not consistently capture flatness as effectively as DNNs.
Refer to caption: extracted/5909381/figure/sgd_to_sam_fig.png

## 3 Flatness Does Matter For Bayesian Model Averaging

We first cast a question of whether BNNs inherently captures the flatness. To answer this, we compare the flatness of DNNs and BNNs without flatness-aware optimizer and demonstrate empirically that BNNs often struggle to capture the flatness. We also show flatness does matter for BMA both experimentally and theoretically.

### 3.1 BNN Struggles To Capture The Flatness

We first investigate whether BNNs effectively capture flatness and find that they often struggle to do so. To assess flatness, we use $\lambda_{1}(w)$ and $\lambda_{1}(w)/\lambda_{5}(w)$, as criteria (Foret et al., ; Li & Zhang, ). For BMA, we compute the average of these metrics across $M$ model samples $w_{m},m=1,...,M$, as $1/M\sum_{m=1}^{M}\lambda_{1}(w_{m})$ and $1/M\sum_{m=1}^{M}\lambda_{1}(w_{m})/\lambda_{5}(w_{m})$ (detailed in Appendix A.1). We simply refer to these criteria as $\lambda_{1}$ and $\lambda_{1}/\lambda_{5}$. We also measure the Error ($100-\text{Accuracy}$), Expected Calibration Error (ECE) (Guo et al., ), and Negative Log Likelihood (NLL) to compare the generalization ability. We mainly set ResNet18 (RN18) (He et al., ) without Batch Normalization (BN) (Ioffe & Szegedy, ) as a backbone model. For BNN frameworks, we adopt VI, MCMC, and SWAG. To minimize the effect on measuring the flatness, we remove the BN and also do not adjust data augmentation. We present more detailed results of the analysis between flatness and performance across various settings in Appendix A.2, demonstrating consistent outcomes.

In Figure 1, BNNs do not consistently capture the loss geometry well. BNNs trained with SGD often exhibit higher $\lambda_{1}$ compared to DNN trained with SGD. They also show significantly higher $\lambda_{1}$ when compared to DNN trained with SAM. This is consistent with Figure 7 and 8 (Appendix A.2), trained on diverse learning rate schedulers. Therefore, we conclude that BNNs often struggle to capture flatness, raising the question of whether BMA, with its unique prediction approach, is also affected by flatness.

### 3.2 BMA Can Be Ineffective Without Flatness

Figure: (a) Correlation between flatness and generalization
Refer to caption: extracted/5909381/figure/corr/cifar10_swag-sgd-constant_corr.png

BNNs possess the benefit of BMA, which anticipates performance enhancement through model ensemble based on the approximated posterior distribution. However, following the fact that BNNs often struggle to capture the flatness, we cast another question: "Does the flatness also affect BMA?"

First, we consolidate that the correlation between flatness and generalization performance also exists in BMA. Figure 2(a) shows the affirmative correlation between performance and flatness throughout $30$ sampled model parameters from posterior trained on CIFAR10 with RN18 w/o BN. We provide additional plots in Figure 9 (Appendix A.3), demonstrating consistent results.

Second, we observe how performance changes when the sampling model parameter in BMA is performed based on flatness. We first sample $30$ models trained on CIFAR10 with RN18 w/o BN. Then, we start to do BMA through three criteria. "Flat" denotes starting model averaging from the flattest model, and "Sharp" means the opposite of "Flat". "Rand" denotes starting BMA from a random sample of prepared $30$ models. From Figure 2(b) and 2(c), we conclude that degradation or stagnation can appear without considering the flatness during BMA. Figure 10 and 11 (Appendix A.4) support the conclusion, as well. With a closer look at the "Flat" label, where progressively sharper models are contained, we observe that performances do not improve as the number of averaged models increases. These points prove the necessity of flatness in BMA.

Along with the experimental influence of flatness on BMA, we also show that the individual sampled models affect the flatness of BMA. Specifically, we suggest a theoretical bound of flatness on BMA through the Hessian eigenvalue of loss. The Hessian eigenvalue of loss is a typical measurement to compare the flatness of neural networks. BMA marginalizes diverse predictions by ensembling model output. The loss of the weight-averaged model is approximately the same as the loss of the ensemble model, with a small error term based on the difference between their outputs (Lemma 1 in Appendix E.1) (Izmailov et al., ; Wortsman et al., ; Rame et al., ). We demonstrate the flatness bound for WA and connect it to that of BMA. Through Weyl’s inequality (Weyl, ), the bound of the Hessian eigenvalue of $w_{\text{WA}}=1/M\sum_{m=1}^{M}w_{m}$ is defined as:

###### Theorem 1 .

With $M$ model sample $w_{m},m=1,...,M$, the maximal eigenvalue of averaged Hessian of loss $\lambda_{\text{max}}(H_{w_{\text{WA}}})$is bounded as follow:

$$ $\displaystyle\max\left(\Bigg{\{}\frac{1}{M}\bigg{(}\lambda_{\max}(H_{w_{m}})+ \sum_{\begin{subarray}{c}n=1\\ n\neq m\end{subarray}}^{M}\lambda_{\min}(H_{w_{n}})\bigg{)}\Bigg{\}}_{m=1}^{M} \right)\leq\lambda_{\max}(H_{w_{\text{WA}}})\leq\frac{\sum_{m=1}^{M}\lambda_{ \max}(H_{w_{m}})}{M}.$ $$

Theorem 1 implies that the flatness of BMA reflects the flatness of model samples. If a sampled model had a large Hessian eigenvalue, the lower bound of Hessian eigenvalue can be larger.
Namely, the ensembled model can be located in a sharp region by ensembling sharp model samples from posterior. Through empirical and theoretical analysis of flatness in BNNs, we confirm that a flat posterior is necessary to ensure the individual sampled models are flat, leading to more effective BMA.

###### Theorem 1 .

## 4 Bayesian Model Averaging with Flat Posterior

For more effective BMA, we propose a Bayesian flat-seeking optimizer (Section 4.1) and Bayesian transfer learning combined with diverse BNN frameworks (Section 4.2).

### 4.1 Bayesian Flat-seeking Optimizer

To deal with the probabilistic nature of BNN, we suggest a new objective function based on VI:

$$ $l_{\text{SA-BMA}}^{\gamma}(\theta)=\min_{\theta}\max_{d|\theta+\Delta\theta, \theta|\leq\gamma^{2}}l(\theta+\Delta\theta)+\beta\textrm{D}_{\textrm{KL}}[q_{ \theta}(w|\mathcal{D})||p(w)]$ (4) $$

$$ $\textrm{s.t.}\ \ d|\theta+\Delta\theta,\theta|=\textrm{D}_{\textrm{KL}}\big{[} q_{\theta+\Delta\theta}(w|\mathcal{D})\ ||\ q_{\theta}(w|\mathcal{D})\big{]},$ (5) $$

where $\theta$ and $\Delta\theta$ denote the variational parameters and perturbation on them, respectively. $l(\cdot)$ denotes empirical loss, such as NLL under $q_{\theta}(w|\mathcal{D})$, and $\beta$ is a hyperparameter that controls the influence of the prior.

Through the relationship between KL divergence and FIM, the objective function (Eq. (4)) is rewritten as:

$$ $l^{\gamma}_{\text{SA-BMA}}(\theta)=\min_{\theta}\max_{\Delta\theta^{T}F_{ \theta}(\theta)\Delta\theta\leq\gamma^{2}}l(\theta+\Delta\theta)+\beta\textrm{ D}_{\textrm{KL}}[q_{\theta}(w|\mathcal{D})||p(w)],$ (6) $$

where $F_{\theta}({\theta})=\mathbb{E}_{w,\mathcal{D}}[\nabla_{\theta}\log q_{\theta}
(w|\mathcal{D})\nabla_{\theta}\log q_{\theta}(w|\mathcal{D})^{T}]$. Note the FIM is defined over parameters. Accordingly, the adversarial posterior is directly obtained in the parameter space, enabling BNNs to better construct neighbor to flat minima.

In first step, we get the closed-form $\Delta\theta_{\text{SA-BMA}}$ ($\Delta\theta$ in Eq. (6)) as:

$$ $\Delta\theta_{\text{SA-BMA}}=\gamma\frac{F_{\theta}(\theta)^{-1}\nabla_{\theta }l(\theta)}{\sqrt{\nabla_{\theta}l(\theta)^{T}F_{\theta}(\theta)^{-1}\nabla_{ \theta}l(\theta)}}.$ (7) $$

Detailed formula derivation of the optimal perturbation for SA-BMA (Eq. (7)) is provided in Appendix E.2.

In second step, we update $\theta$ by gradients from adversarial posterior perturbated with $\Delta\theta_{\text{SA-BMA}}$:

$$ $\nabla_{\theta}l^{\gamma}_{\text{SA-BMA}}(\theta)\approx\nabla_{\theta}l( \theta+\Delta\theta_{\text{SA-BMA}}).$ (8) $$

SA-BMA enhances the estimation of flat posteriors by adapting SAM to the probabilistic nature of BNNs, defining adversarial perturbation ball directly in the parameter space.

##### Generalized version of geometric optimizers

Notably, SA-BMA is a generalized version of SAM, FSAM, and NG under deterministic parameters, as shown in Theorem 2. Proof of Theorem 2 are provided in Appendix E.3.

###### Theorem 2 .

(Informal) Suppose the model parameter $w$ is deterministic and the loss function $l(\cdot)$ is twice continuously differentiable. Let $\gamma^{\prime}=\gamma/\sqrt{\nabla_{\theta}l(\theta)^{T}F_{\theta}(\theta)^{-
1}\nabla_{\theta}l(\theta)}$, then

- i)
SA-BMA degenerates to FSAM by using the diagonal terms of FIM.
- ii)
SA-BMA degenerates to SAM if FIM is an identity matrix.
- iii)
Update rule of SA-BMA $\theta-\eta_{\text{SA-BMA}}\nabla_{\theta}l(\theta+\Delta\theta)$ degenerates to update rule of NG
$\theta-\eta_{\text{NG}}F_{y}(\theta)^{-1}\nabla_{\theta}l(\theta)$ with learning rate $\eta_{\text{SA-BMA}}=\frac{\eta_{\text{NG}}}{(1+\gamma^{\prime})}F_{\theta}(
\theta)^{-1}$.

SA-BMA replaces the output space FIM, used by existing DNN-based flat-seeking optimizers, with the parameter space FIM. By taking into account the off-diagonal terms of the FIM, SA-BMA more accurately estimates flatness, leading to more precise optimization. This makes SA-BMA better suited for BNNs. Additionally, SA-BMA becomes equivalent to NG when using a specific learning rate, suggesting the potential for accelerating convergence.

###### Theorem 2 .

### 4.2 Bayesian Transfer Learning

The proposed optimizer theoretically captures curvature more exactly, but it faces practical limitations when applied to neural networks with a large number of parameters. To address this limitation, we propose a Bayesian transfer learning scheme alongside the proposed optimizer. In this scheme, we leverage pre-trained DNN as a prior and train only a subset of the model’s parameters, enhancing scalability while maintaining performance. The proposed Bayesian transfer learning scheme consists of three steps, and Algorithm 1 (Appendix D.3) depicts how it operates.

First, we load a pre-trained DNN $w_{\text{MAP}}\subseteq\mathbb{R}^{p}$ optimized by Maximum A Posteriori (MAP). We change the loaded DNN into BNN on the source or downstream task $\mathcal{D}^{\text{pr}}$. Formally, we get $q^{\text{pr}}_{\theta}(w|\mathcal{D}^{\text{pr}})$. Various BNN frameworks, such as VI, SWAG, and others, can be employed to transform a DNN into a BNN. This study mainly employs MCMC, SWAG (Maddox et al., ), and MOPED (Krishnan et al., ) for VI. Note that the proposed optimizer is not employed in this step.

Second, we set the converted BNN as prior and initial points and train new posterior with the proposed optimizer, following objective function:

$$ $l^{\gamma}_{\text{SA-BMA}}(\theta)=\min_{\theta}\max_{\Delta\theta^{T}F_{ \theta}(\theta)\Delta\theta\leq\gamma^{2}}l(\theta+\Delta\theta)+\beta\textrm{ D}_{\textrm{KL}}[q_{\theta}(w|\mathcal{D}^{\text{ft}})||q^{\text{pr}}_{\theta} (w|\mathcal{D}^{\text{pr}})],$ (9) $$

where $\mathcal{D}^{\text{ft}}$ represents the downstream dataset used for fine-tuning, and $l(\cdot)$ denotes the empirical loss function. To reduce computational complexity, we also incorporate a subnetwork BNN strategy, which has been extensively explored in recent studies (Izmailov et al., ; Daxberger et al., ; Sharma et al., ; Snoek et al., ; Daxberger et al., ; Harrison et al., ). In this work, we set the trainable parameters to parameters of normalization and last layers. Additionally, we reinitialize the last layer using a simple Gaussian distribution $\mathcal{N}(0,\alpha I)$ during fine-tuning on the downstream dataset, where $\alpha$ is a hyperparameter controlling the variance. This approach is expected to facilitate scalable and stable training by leveraging pre-trained DNNs.

## 5 Experiments

We first verify that SA-BMA effectively converges to flat minima using a synthetic example (Section 5.1). Then, we demonstrate that training from scratch with SA-BMA optimizer leads to improved generalization performance (Section 5.2). In addition, by integrating Bayesian transfer learning, we show that SA-BMA performs well in few-shot image classification tasks (Section 5.3) and is robust to distribution shifts (Section 5.4). Finally, we visualize the loss surface and compare the Hessian eigenvalues numerically, further confirming that the model approximates flat posteriors (Section 5.5).

### 5.1 Synthetic Example

Figure: (a) MCMC
Refer to caption: extracted/5909381/figure/posterior_approx/MCMC-SGLD_posterior_approx.png

We conduct a toy experiment designed to create sharp and flat modes. We run various methods, including SGD, MCMC with SGLD, SWAG, and VI, to compare them with SA-BMA combined with VI and SWAG. The results in Figure 3 and 12 (Appendix B) show that the baseline methods based on SGD and SGLD converge to the sharp mode without any consideration for flatness. In contrast, the proposed SA-BMA consistently converged to the flat mode, regardless of the BNN framework combined. We provide the setting and additional results in Appendix B.

### 5.2 Learning from scratch

Table: Table 1: Performance of learning from scratch with RN18 and modified ViT-B/16^†. SA-BMA (VI), SA-BMA (MCMC), and SA-BMA (SWAG) indicate the specific BNN framework combined with SA-BMA. Bold highlights the best performance within each BNN framework, while red indicates the overall best performance across all frameworks. SA-BMA leads better performance across all BNN frameworks and shows superior performance both on the CIFAR10 and CIFAR100.

We evaluate the performance of SA-BMA by combining it with various BNN frameworks, VI, MCMC, and SWAG. For this, we train both RN18 and ViT-B/16^† models from scratch in CIFAR10 and CIFAR100 (Krizhevsky et al., ). We use modified ViT-B/16^† (Dosovitskiy et al., ) to deal with the underfitting issue over small dataset of ViT-B/16 (Liu et al., ; Zhu et al., ). SA-BMA was applied only to the normalization and last layers, while all other layers were trained using SGD. We compare the performance of SA-BMA with DNNs trained using SGD, SAM, and FSAM, as well as BNN frameworks—SWAG, VI, and MCMC—and prior methods like F-SWAG (Nguyen et al., ), bSAM (Möllenhoff & Khan, ), and E-MCMC (Li & Zhang, ). For MCMC and E-MCMC, we consistently use SGLD in all experiments, evaluating models based on accuracy (ACC), ECE, and NLL.
As shown in Table 1, SA-BMA consistently improved performance when integrated with all BNN frameworks, demonstrating superior results compared to all baselines. Experimental details are provided in Appendix C.

### 5.3 Few-shot image classification with Bayesian Transfer Learning

We also evaluate the performance of the proposed SA-BMA on a few-shot image classification task in the context of transfer learning. In this experiment, we adopt RN18 and ViT-B/16 pre-trained on ImageNet (IN) 1K (Russakovsky et al., ) as backbone.
We add baselines for the Bayesian transfer learning baseline MOPED (Krishnan et al., ) and Pre-Train Your Loss (PTL) (Shwartz-Ziv et al., ) in this setting.
Detailed configuration for experiments is provided in Appendix D.

First, we evaluate our model in CIFAR10 and CIFAR100 (Krizhevsky et al., ) with ten images per class, each. As illustrated in Table 2, SA-BMA with diverse BNN frameworks consistently outperforms existing baselines in terms of both accuracy and uncertainty quantification. Unlike scratch learning, SA-BMA (VI) outperforms SA-BMA (SWAG) in few-shot image classification tasks. This can be attributed to the nature of few-shot tasks, where VI, which only learns a diagonal covariance, is less prone to underfitting due to the limited amount of data.

Table: Table 2: Downstream task performance with RN18 and ViT-B/16 pre-trained on IN 1K. Bold highlights the best performance within each BNN framework, while red indicates the overall best performance across all frameworks. SA-BMA shows superior performance both on the CIFAR10 and CIFAR100 10-shot, with the sole exception being the ECE on the CIFAR100 10-shot in RN18.

Table: Table 3: Downstream task accuracy with RN50 and ViT-B/16 pre-trained on IN 1K. SA-BMA (SWAG) denotes using SWAG to convert pre-trained model into BNN. Bold and underline denote best and second best performance each. SA-BMA demonstrates superior performance across all 16-shot datasets.

Table: Table 4: Downstream task accuracy of CLIP with visual encoder, RN50 and ViT-B/16. Bold and underline denote best and second best performance each. SA-BMA shows superior performance in average over five datasets.

We also conduct extra experiments on four fine-grained image classification benchmarks, EuroSAT (Helber et al., ), Flowers102 (Nilsback & Zisserman, ), Pets (Parkhi et al., ), and UCF101 (Soomro et al., ). From this point, we conduct all experiments using SA-BMA with SWAG for efficiency. We observe that SA-BMA achieves the best accuracy (Table 3) and NLL (Table 15 in Appendix F) across all datasets, as well. We demonstrate that SA-BMA synergizes the advantages of sharpness-aware optimization and Bayesian transfer learning in a few-shot learning context.

In addition, we employ ResNet50 (RN50) and ViT-B/16 in CLIP (Radford et al., ), widely-adopted vision-language model (VLM). We fine-tune only the last layer of the CLIP visual encoder on the IN 1K 16-shot dataset and evaluate the trained model on IN and its variants—IN-V2 (Recht et al., ), IN-R (Hendrycks et al., ), IN-A (Hendrycks et al., ), and IN-S (Wang et al., )—following the protocols outlined in Radford et al. (); Zhu et al. (); Lin et al. (). Table 4 shows that SA-BMA outperforms baselines in the in-distribution evaluation and also shows better or comparable robustness in the out-of-distribution datasets both in RN50 and ViT-B/16, which leads to superior performance in average.

### 5.4 Robustness on Distribution Shift

Figure: Figure 4: Accuracy under distributional shift. We evaluate the accuracy of RN18 and ViT-B/16 models trained on CIFAR10 and CIFAR100 10-shot across all severity levels of CIFAR10C and CIFAR100C. SA-BMA consistently outperforms all baseline methods across all levels of corruption.
Refer to caption: extracted/5909381/figure/severity_plot.png

In Figure 4, we show the accuracy on a corrupted dataset, CIFAR10C and CIFAR100C (Hendrycks & Dietterich, ), to verify the robustness and generalization performance of SA-BMA. We find that our proposed SA-BMA outperforms other methods across both CIFAR10C and CIFAR100C datasets on backbone models RN18 and ViT-B/16. SA-BMA consistently makes robust predictions across corruption levels from mild level to severe level. We conclude that SA-BMA provides robust predictions under distribution shift across all severities compared to the baselines, as well as under in-distribution image classification. Detailed result is provided in Appendix G.

### 5.5 Flatness Analysis

Table: Table 5: Hessian analysis on RN18 trained with CIFAR10 10-shot. SA-BMA shows the lowest score on both maximal eigenvalue $\lambda_{1}$ and eigenvalue ratio $\lambda_{1}/\lambda_{5}$, proving it leads the model to flatter minima.

To substantiate the flatness in the loss surface of the SA-BMA model, we compare the sampled models from the posterior approximated with SA-BMA and PTL. The backbone model is RN18, and the trained dataset is CIFAR10 10-shot. As shown in Figure 5, we compare the sampled weight of SA-BMA and PTL in diverse views and show SA-BMA converging to a flatter loss basin with lower loss. Additional results and the protocol to visualize the loss basin are provided in Appendix H.

We also quantitatively compare the sharpness of models. Table 5 presents the results of analyzing the eigenvalue of model Hessian for both DNN and BNN series baseline models, as well as SA-BMA. $\lambda_{1}$ and $\lambda_{5}$ represent the largest eigenvalue and the fifth largest eigenvalue, respectively. We used the maximal eigenvalue $\lambda_{1}$ and ratio $\lambda_{1}/\lambda_{5}$ as a metric (Foret et al., ; Li et al., ; Li & Zhang, ). SA-BMA has the lowest value compared to all other baselines, which can be interpreted as our model being the flattest. It supports our visual results, highlighting the superior flatness and improved generalization of SA-BMA.

Figure: Figure 5: Comparison of the loss surfaces of SA-BMA (grey) and PTL (light blue) models. The loss surface comparison offers an intuitive view of SA-BMA achieving a lower, flatter loss surface than PTL, underlining the importance of flatness in model design.
Refer to caption: extracted/5909381/figure/loss_surface/loss_surface_Blues_seed2.png

## 6 Related Works

### 6.1 Flatness and BNN

Recent works have suggested flat-seeking optimizers combined with BNN. First, SWAG (Maddox et al., ) implicitly approximated posterior toward flatter optima based on SWA (Izmailov et al., ). However, SWAG can fail to find flat minima, leading to limited improvement in generalization, as shown in Section 3.1. bSAM (Möllenhoff & Khan, ) showed that SAM can be interpreted as a relaxation of the Bayes and quantified uncertainty with SAM. Yet, bSAM only focused on uncertainty quantification by simply modifying Adam-based SAM (Khan et al., ), not newly considering the parametric geometry for perturbation. Moreover, scaling the variance with the number of data points hampers the direct implementation of bSAM in few-shot settings. SA-BNN (Nguyen et al., ) proposed a sharpness-aware posterior derived directly from the variational objective and proved the effectiveness experimentally and theoretically. However, they just employ the L2 norm to calculate the perturbation of SAM without considering the difference between the nature of DNN and BNN. E-MCMC (Li & Zhang, ) proposed an efficient MCMC algorithm capable of effectively sampling the posterior within a flat basin by removing the nested chain of Entropy-SGD and Entropy-SGLD. Still, E-MCMC necessitates a guidance model, which doubles the parameters and heavily hinders its employment over large-scale models. SA-BMA is the first to reflect the parameter space in the perturbation step of SAM for stochastic models, considering the nature of BNNs.

### 6.2 Bayesian Transfer Learning

There are several works on performing transfer learning on BNN with prior. PTL (Shwartz-Ziv et al., ) constructs BNN by learning closed-form posterior approximation of the pre-trained model on the source task and uses it as a prior for the downstream task after scaling. The work requires additional training on the source task, which makes it restrictive when it is impossible to access the source task dataset. MOPED (Krishnan et al., ) employs pre-trained BNN as a prior for VI based on the empirical Bayes method. Using pre-trained DNN, MOPED enhances accessibility to BNN, however, it is only applicable to Mean-field VI (MFVI).
Non-parametric transfer learning (NPTL) (Lee et al., ) suggested adopting non-parametric learning to make posterior flexible in terms of distribution shift. Our proposed scheme for Bayesian transfer learning can approximate the distribution of parameters within either the downstream dataset or the source dataset, which allows us to leverage more sophisticated and large-scale pre-trained models. Moreover, it is the first study considering flatness in Bayesian transfer learning.

## 7 Conclusion

This study shows the limitations of BNNs in capturing the flatness, which is crucial for generalization performance. We also show that BMA can fail to yield optimal results without explicitly considering flatness. To address this issue, we introduce Sharpness-Aware Bayesian Model Averaging (SA-BMA), which seeks to find a flat posterior by capturing flatness in the parameter space. SA-BMA is the generalized version of existing sharpness-aware optimizers for DNN and aligns with the intrinsic nature of BNN. We further propose a Bayesian Transfer Learning scheme, which enables efficient fine-tuning of pre-trained DNNs while maintaining scalability with SA-BMA. Through extensive experiments, we demonstrate that SA-BMA significantly enhances the generalization performance of BNNs in diverse scenarios. Our work highlights the importance of flatness in posterior approximations and provides a practical solution to improve the predictive robustness and accuracy of BNNs.

## Appendix A Additional Results For Flatness Dose Matter For Bayesian Model Averaging

### A.1 Details About Hessian Eigenvalue of loss with BMA

Figure: (a) Flatness of BMA
Refer to caption: extracted/5909381/figure/flatness_description.png

To measure the flatness of BNNs and compare them with DNNs, we introduce a new metric specifically designed for this study. Unlike DNNs, where model parameters are typically treated as point estimate, BNNs represent model parameters as random variables, necessitating an appropriate approach for measuring flatness. As shown in Figure 6(b), the maximal eigenvalue of the Hessian of the loss function is commonly used to evaluate flatness quantitatively in DNNs (Keskar et al., ; Foret et al., ; Jastrzebski et al., ). To assess flatness in BNNs, we followed BMA protocol. BMA samples model weights from the approximated posterior, calculates the outputs of the sampled individual models, and ensemble the outputs, as shown in Figure 6(a). Thus, similar to how BMA operates, we measured the flatness of individual model weights and subsequently ensemble these measurements to derive a comprehensive metric.

### A.2 Flatness Comparison

To prove that BNN cannot guarantee flatness, we run a variety of experiments for flatness comparison. Since it’s uncommon, we do not run DNN or VI with SWAG learning rate scheduler for additional flatness comparisons. First, Table 6 summarizes the comparison results covering different models with a wide range of combinations with learning methods, optimizers, and schedulers. We conducted on RN18 w/o BN and data augmentation. We use MOPED as the VI framework.

Table: Table 6: Flatness Comparison on DNN and BNN with sharpness-aware optimization methods. We observe that BNN does not find the flatness-aware local minima, and the compatibility of BNN and the previous sharpness-aware optimization (SAM) is limited. All experiments were repeated three times with RN18 w/o BN.

Second, we compare the flatness with ResNet18 pre-trained on ImageNet 1K, provided in torchvision. Note that the ResNet18 contains Batch Normalization, and data augmentation is also applied in this setting. Table 7 consistently shows the SWAG cannot guarantee the flatness with Batch Normalization and data augmentation, either.

Table: Table 7: Flatness Comparison on DNN and BNN with sharpness-aware optimization methods. We observe that BNN does not find the flatness-aware local minima even with BN and data augmentation. All experiments were repeated three times with ResNet18 pre-trained on ImageNet 1K.

Third, we train the pre-trained RN18 with CIFAR10 10-shot and CIFAR100 10-shot. In other words, we only use 10 data per class in this setting. Table 8 shows identical results with other flatness comparisons. SWAG cannot guarantee flatness without SAM.

Table: Table 8: Flatness Comparison on DNN and BNN with sharpness-aware optimization method. We observe that BNN does not find the flatness-aware local minima, and the compatibility of BNN and the previous sharpness-aware optimization (SAM) is limited. All experiments were repeated three times with ResNet18 pre-trained ImageNet 1K in few-shot setting.

Fourth, we measure the flatness of last-layer SWAG (L-SWAG) and VI (L-VI) in Table 9. We use the trained DNN models as an initial weight for L-SWAG. For example, a DNN model trained with constant lr scheduling and SGD optimizer is the base model for L-SWAG, which trains with the same lr schedule and optimizer. For L-VI, we only set stochastic parameters for last layer. Again, SWAG failed to show better flatness compared to DNN with SAM.

Table: Table 9: Flatness Comparison on DNN and L-SWAG applied to the DNN. We confirm that using pre-existed flatness-aware optimization on the last layer of BNN cannot be enough to pull the model to a flat basin. All experiments were repeated three times with ResNet18 w/o BN.

Figure: Figure 7: Comparison of Error, NLL, and ECE with various schedulers on CIFAR10 in relation to the maximum eigenvalue $\lambda_{1}$.
Refer to caption: extracted/5909381/figure/flat_bma/flatness_comparision_cifar10.png

Figure: Figure 8: Comparison of Error, NLL, and ECE with various schedulers on CIFAR100 in relation to the maximum eigenvalue $\lambda_{1}$.
Refer to caption: extracted/5909381/figure/flat_bma/flatness_comparision_cifar100.png

In Figure 1, only the Error and NLL in relation to the maximum eigenvalue $\lambda_{1}$ are presented for training with the Constant scheduler. Figures 7 and 8 show the Error, NLL, and additionally ECE with various schedulers and datasets. These figures depict the experimental results on CIFAR10 and CIFAR100, respectively. Similar to what was observed in Figure 1, BNN does not guarantee the flatness.

### A.3 Correlation Between Flatness and Generalization

Together with flatness comparisons in A.2, we check the correlation between flatness and generalization performance of sampled models throughout all considered learning rate schedulers. We present the scatter plot of the model, sampled from RN18 w/o BN trained on CIFAR10 and CIFAR100 in the first and second rows of Figure 9. Each column of Figure 9 denotes Constant scheduler, Cosine Decay scheduler, and SWAG lr scheduler, respectively. All the models are trained with SWAG and SGD momentum, and we set maximal eigenvalue $\lambda_{1}$ as a flatness measure. Correlation with flatness and each generalization performance metric is suggested in the legend, as well. Regardless of the scheduler and dataset, all generalization performances, error, ECE, and NLL strongly correlate with flatness.

Figure: (a) Constant scheduler
Refer to caption: extracted/5909381/figure/corr/cifar10_swag-sgd-constant_corr.png

### A.4 Progressive BMA Based On Flatness

We also inspect the influence of flatness on BMA performance throughout all considered schedulers. We prepared 30 sampled models, trained on CIFAR10 and CIFAR100 with RN18 w/o BN. "Flat" denotes starting BMA from sampling the flattest model. "Sharp" denotes starting BMA by sampling the sharpest model. "Rand" denotes starting BMA from a random sample of prepared 30 models. Figure 10 and 11 shows the results in CIFAR10 and CIFAR100, respectively. Each row means Constant, Cosine Decay, and SWAG lr scheduler, and each column denotes the classification error, ECE, and NLL.

Generally, we observe that there is no significant improvement or limited improvement in performance when gradually applying BMA from flat models. Following the observation, we conclude flatness should be taken into account for efficient BMA. This observation is particularly pronounced in classification error ((a), (d), (g) of Figure 10 and 11). However, the trend is inconsistent in ECE. It is an interesting topic for future research.

Figure: (a) Error
Refer to caption: extracted/5909381/figure/flat_bma/cifar10_swag-sgd-constant_acc.png

Figure: (a) Error
Refer to caption: extracted/5909381/figure/flat_bma/cifar100_swag-sgd-constant_acc.png

## Appendix B Additional Results For Synthetic Example

Figure: (a) SGD
Refer to caption: extracted/5909381/figure/posterior_approx/DNN-SGD_posterior_approx.png

Following Li & Zhang (), we construct a loss surface following the distribution $\frac{1}{2}(\mathcal{N}([-2,-1]^{T},0.5I))+\frac{1}{2}(\mathcal{N}([2,1]^{T},I))$ and set the initial point at $(-0.4,-0.4)$. Unlike other SGD-based methods, SA-BMA efficiently identifies flat modes regardless of the underlying BNN frameworks.

## Appendix C Experimental Details:Learning From Scratch

### C.1 SA-BMA with diverse BNN frameworks

In Eq. (4), SA-BMA can be applied with various BNN frameworks by using an empirical loss function $l(\cdot)$ and adjusting the parameter $\beta$. We commonly set $l(\cdot)$ as cross-entropy loss in context of image classification task. Note that SA-BMA was applied only to the normalization layers and the last layer, while all other layers were trained using SGD.

##### SA-BMA (VI)

For VI, we follow the loss function of Eq. (4).

##### SA-BMA (MCMC)

We mainly adopt SGLD for MCMC in this work. For SGLD, we incorporated noise into Eq. (4) without KLD term ($\beta=0$) based on the learning rate and the hyperparameter, temperature. In this approach, during the first step, the adversarial posterior is computed without any noise (Eq. (7)). In the second step, both the noise and the adversarial posterior are used together in the learning process.

##### SA-BMA (SWAG)

SWAG updates the first and second moments along the trajectory of SWA and uses these moments to approximate the posterior with a Gaussian distribution. In Eq. (4), $\beta$ is fixed to 0, and as the trajectory of SWA is optimized through SA-BMA, posterior approximation can be performed accordingly.

### C.2 Hyperparameters for Experiments

In this section, we provide the details of the experimental setup for Section 5.2. In the other experiments, the range of hyperparameters, excluding the number of epochs, is shared across different backbones and methods. For all experiments, the hyperparameters are selected using grid-search. Configuration of best hyperparameters for each baseline is summarized in Table 10 and Table 11.

Table: Table 10: Hyperparameter Configuration for CIFAR10

Table: Table 11: Hyperparameter Configuration for CIFAR100

##### Stochastic Gradient Descent with Momentum (SGD)

In this study, we adopt Stochastic Gradient Descent with Momentum as an optimizer for DNN. Learning rate schedule is fixed to cosine decay. We run 300 epochs. The hyperparameter tuning range included learning rate in [1e-4, 1e-3, 1e-2].

##### Sharpness Aware Minimization (SAM)

We set SGD with momentum as the base optimizer of SAM. It also ran upon a cosine decay learning rate scheduler. All the range of hyperparameters is shared with SGD with Momenmtum. Additional hyperparameter $\gamma$, the ball size of perturbation, is in [1e-2, 5e-2, 0.1].

##### Fisher SAM (FSAM)

We set SGD with momentum as the base optimizer of FSAM. It also ran upon a cosine decay learning rate scheduler. All the range of hyperparameters is shared with SGD with Momenmtum. Additional hyperparameter $\eta$, regularize Fisher impact, is in [1e-2, 1e-1, 1].

##### SAM as an optimal relaxation of Bayes (bSAM)

We use a cosine learning rate decay scheme. We run 300 epochs with fixed $\beta_{1}$ and $\beta_{2}$. The hyperparameter tuning rage included: learning rate in [1e-1, 3e-1, 5e-1, 8e-1, 1], weight decay in [1e-4, 5e-4, 1e-3, 1e-2], damping in [1e-1, 1e-2, 1e-3], and $\gamma$ in [1e-3, 1e-2, 5e-2, 1e-1, 5e-1]. Damping parameter stabilizes the method by adding constant when updating variance estimate.

##### Variational Inference (VI)

We use MOPED to change DNN into BNN, first. We set prior mean and variance as 0 and 1, respectively. Besides, we set the posterior mean as 0 and variance as 1e-3. We adopt Reparameterization as type of VI. The essential hyperparmeter for MOPED is $\delta$, which adjusts how much to incorporate pre-trained weights. The $\delta$ was searched in [1e-3, 5e-3, 1e-2]. Moreover, we add a hyperparameter $\beta$ for MOPED that can balance the loss term in VI. The $\beta$ is in range [1e-2, 1e-1 ,1]

##### MCMC

We consistently use SGLD (Welling & Teh, ) for MCMC in this work. It ran upon a cyclic cosine decay learning rate scheduler. The number of cycles was ranged in [2, 4]. The number of sampled models is in [10, 20, 28]. We search temperature in [1e-5, 5e-4, 1e-4, 5e-3, 1e-3, 1e-2].

##### Entropy-MCMC (E-MCMC)

We use a cosine learning rate decay scheme, annealing the learning rate to zero. We run 300 epochs. We search $\eta$ in [1e-4, 5e-3, 1e-3, 5e-2, 1e-2, 1e-1] and a system temperature $T$ in [1e-4, 5e-4, 1e-3, 5e-3, 1e-2]. Note that the $\eta$ handles flatness, and the system temperature adjusts the weight update’s step size.

##### SWAG

We use a cosine learning rate decay scheme for SWAG. All the range of hyperparameters is shared with SGD with Momenmtum. Additionally, we search for three additional hyperparameters for SWAG, capturing DNN snapshots and calculating statistics. First, the epoch to start SWA is in [161, 201], and epoch is 300. Second, the frequency of capturing the model snapshot is in [1, 2, 3]. Third, the low rank for covariance is in [2, 3, 5, 7, 10].

##### F-SWAG

F-SWAG shares hyperparameter with SWAG, except $\gamma$. We search $\gamma$ in [1e-2, 5e-2, 1e-1].

##### Sharpness-aware Bayesian Model Averaging (SA-BMA)

In case of SA-BMA (VI), we set $\mathcal{N}(0,1e-3)$ as prior and $\delta$ as 1e-3 to make DNN to BNN using MOPED. After getting prior distribution, we search three hyperparameters: learning rate and $\gamma$. The hyperparameter tuning range included: learning rate in [1e-3, 5e-3, 1e-2, 5e-2], $\gamma$ in [1e-2, 5e-2, 1e-1, 5e-1]. We set weight decay as $5e-4$ for all backbones and train the model over 300 epochs with early stopping. We fix $\beta$ as 1e-8 for all experiments. In case of SA-BMA (MCMC), we search learning rate, temperature for learning rate scheduling, and $\gamma$. The hyperparameter ranges are [1e-3, 5e-3, 1e-2, 5e-2] for learning rate, [1e-4, 5e-3, 1e-3, 5e-2, 1e-2, 1e-1] for temperature, and [5e-3, 1e-2, 5e-2, 1e-1, 5e-1] for $\gamma$. In case of SA-BMA (SWAG), we follow the hyperparameter for SWAG, except $\gamma$ in [1e-2, 5e-2, 1e-1].

## Appendix D Experimental Details:Few-shot Image Classification with Bayesian Transfer Learning

### D.1 SA-BMA with diverse BNN frameworks

Diverse BNN frameworks can be adopted for Bayesian Transfer Learning. Specifically, there are several options for making pre-trained DNN into BNN. In this work, we mainly adopt MOPED and SWAG for the converting.

In addition, SA-BMA can be applied with various BNN frameworks by using an empirical loss function
$l(\cdot)$ and adjusting the parameter $\beta$ in Eq. (9). We commonly set $l(\cdot)$ as cross-entropy loss in context of image
classification task.

##### SA-BMA (VI)

First, we convert pre-trained DNN into BNN with MOPED. We set the converted BNN as prior, $q_{\theta}^{\text{pr}}(w|\mathcal{D}^{\text{pr}})$ in Eq. (9), and initial point of model. We only train parameters of normalization and last layer and freeze others. We train them with the loss function of Eq. (9).

##### SA-BMA (MCMC)

For SGLD, it is unnecessary to convert pre-trained DNN into BNN. Instead, we directly set the pre-trained DNN as initialization. We incorporated noise into Eq. (9) without the KLD term ($\beta=0$) based on the learning rate and the hyperparameter, temperature. During the first step, the adversarial posterior is computed without any
noise (Eq. (7)). In the second step, both the noise and the adversarial posterior are used together in the learning process.

##### SA-BMA (SWAG)

SWAG is also one of the options to convert pre-trained DNN into BNN. Specifically, we run a few epochs with source or downstream datasets to make BNN from pre-trained DNN. After this step, we set the BNN as the prior, $q_{\theta}^{\text{pr}}(w|\mathcal{D}^{\text{pr}})$ in Eq. (9). We also let the converted BNN as initialization and train with downstream dataset. We optimize model with the loss function in Eq. (9).

### D.2 Hyperparameters for Experiments

In this section, we provide the details of the experimental setup for Section 5.3. In the other experiments, the range of hyperparameters, excluding the number of epochs, is shared across different backbones and methods.

First, we provide remarks for each baseline method, followed by the tables of hyperparameter configuration with respect to downstream datasets and the baselines. For all experiments, the hyperparameters are selected using grid-search. Configuration of best hyperparameters for each baseline is summarized in Table 12 and Table 13. We ran all experiments using GeForce RTX 3090 and NVIDIA RTX A6000 with GPU memory of 24,576MB and 49,140 MB.

Table: Table 12: Hyperparameter Configuration for CIFAR10

Table: Table 13: Hyperparameter Configuration for CIFAR100

##### Stochastic Gradient Descent with Momentum (SGD)

In this study, we adopt Stochastic Gradient Descent with Momentum as an optimizer for DNN. Learning rate schedule is fixed to cosine decay with warmup length of 10. We tested [100, 150] epoch and set 100 epoch as the best option. In overall experiments, we set momentum as 0.9. The hyperparameter tuning range included learning rate in [1e-4, 1e-3, 1e-2], and weight decay in [1e-4, 5e-4, 1e-3, 1e-2].

##### Sharpness Aware Minimization (SAM)

We set SGD with momentum as the base optimizer of SAM. It also ran upon a cosine decay learning rate scheduler. All the range of hyperparameters is shared with SGD with Momenmtum. Additional hyperparameter $\gamma$, the ball size of perturbation, is in [1e-2, 5e-2, 1e-1].

##### Fisher SAM (FSAM)

We set SGD with momentum as the base optimizer of FSAM. It also ran upon a cosine decay learning rate scheduler. All the range of hyperparameters is shared with SGD with Momenmtum. Additional hyperparameter $\eta$, regularize Fisher impact, is in [1e-2, 1e-1, 1].

##### SAM as an optimal relaxation of Bayes (bSAM)

We use a cosine learning rate decay scheme, annealing the learning rate to zero. We fine-tuned pre-trained models for 150 epochs with fixed $\beta_{1}$ and $\beta_{2}$. The hyperparameter tuning range included: learning rate in [1e-3, 1e-2, 5e-2, 1e-1, 0.25, 0.5, 1], weight decay in [1e-3, 1e-2, 1e-1], damping in [1e-3, 1e-2, 1e-1], noise scaling parameter in [1e-4, 1e-3, 1e-2, 1e-1], and $\gamma$ in [1e-3, 1e-2, 5e-2, 1e-1]. Damping parameter stabilizes the method by adding constant when updating variance estimate. Since SAM as Bayes optimizer depends on the number of samples to scale the prior, we introduced additional noise scaling parameters to mitigate the gap between the experimental settings, where SAM as Bayes assumed training from scratch and our method assumed few-shot fine-tuning on the pre-trained model. We multiplied noise scaling parameter to the variance of the Gaussian noise to give strong prior, assuming pre-trained model.

##### Model Priors with Empirical Bayes using DNN (MOPED)

MOPED was a baseline to compare for Bayesian Transfer Learning. It employs pre-trained DNN and transforms it into Mean-Field Variational Inference (MFVI). We set prior mean and variance as 0 and 1, respectively. Besides, we set the posterior mean as 0 and variance as 1e-3. We adopt Reparameterization as type of VI. The essential hyperparameter for MOPED is $\delta$, which adjusts how much to incorporate pre-trained weights. The $\delta$ was searched in [5e-2, 1e-1, 2e-1]. Moreover, we add a hyperparameter $\beta$ for MOPED that can balance the loss term in VI. The $\beta$ is in range [1e-2, 1e-1, 1].

##### MCMC

We consistently use SGLD (Welling & Teh, ) for MCMC in this work. It ran upon a cyclic cosine decay learning rate scheduler. The number of cycles was ranged in [2, 4]. The number of sampled models is in [10, 20, 28]. We search temperature in [1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1].

##### Pre-train Your Loss (PTL)

The backbones both ResNet18 and Vit-B/16 were refined through fine-tuning with a classification head for the target task, leveraging a prior distribution learned from SWAG on the ImageNet 1k dataset using SGD. First, the hyperparameter tuning range of the pre-training epoch is [2, 3, 5, 15, 30] to generate the prior distribution on the source task, ImageNet 1k. The learning rate was 0.1. We approximated the covariance low rank as 5. Second, in the downstream task, the fine-tuning optimizer is SGLD with a cosine learning rate schedule, sampling 30 in 5 cycles. The hyperparameter tuning range included: learning rate in [1e-4, 1e-3, 1e-2, 5e-2, 6e-2, 1e-1, 5e-1], weight decay in [1e-4, 1e-3 ,1e-2 ,1e-1], and prior scale in [1e+4, 1e+5, 1e+6]. Prior scaling in the downstream task is to reflect the mismatch between the pre-training and downstream tasks and to add coverage to parameter settings that might be consistent with the downstream. Training was conducted over 150 epochs; tuning range of fine-tuning epoch is [100, 150, 200, 300, 1000].

##### Entropy-MCMC (E-MCMC)

We use a cosine learning rate decay scheme, annealing the learning rate to zero. We set the range of the hyperparameter sweep to the surroundings of the best hyperparameter in E-MCMC for ResNet18: learning rate in [5e-3, 5e-2, 5e-1], weight decay in [1e-4, 1e-3, 1e-2], $\eta$ in [1e-6, 5e-6, 1e-5, 5e-5, 1e-4, 4e-4, 5e-3, 8e-3, 1e-2] and a system temperature $T$ in [1e-5, 1e-4, 1e-3]. In this study, we performed an extensive exploration of the hyperparameter space of ViT-B/16, as it has a mechanism different from the CNN family and may not be found near the best hyperparameter range of ResNet18: learning rate in [1e-3, 5e-3, 1e-2, 5e-2, 5e-1], weight decay in [1e-5, 1e-4, 5e-4, 1e-3, 1e-2, 5e-2], $\eta$ in [5e-7, 1e-6, 5e-6, 5e-5, 1e-4, 4e-4, 5e-4, 1e-3, 8e-3, 1e-2, 1e-1] and a system temperature $T$ in [1e-6, 5e-6, 1e-5, 5e-5, 1e-4, 1e-3, 1e-2, 1e-1]. We fine-tuned pre-trained models for 150 epochs. Note that the $\eta$ handles flatness, and the system temperature adjusts the weight update’s step size.

##### SWAG

We use a cosine learning rate decay scheme for SWAG. All the range of hyperparameters is shared with SGD with Momenmtum. Additionally, we search three additional hyperparameters for SWAG, capturing DNN snapshots and calculating statistics. First, the epoch to start SWA is in [51, 76, 101] and epoch is in [100, 150]. Second, the frequency to capture the model snapshot is in [1, 2, 3]. Third, the low rank for covariance is in [2, 3, 5, 7, 10].

##### F-SWAG

F-SWAG shares hyperparameter with SWAG, except $\gamma$. We search $\gamma$ in [1e-2, 5e-2, 1e-1].

##### Sharpness-aware Bayesian Model Averaging (SA-BMA)

In case of SA-BMA (SWAG), we train SWAG on source task IN 1K to make prior distribution and follow the pre-training protocol of PTL. In case of employing MOPED to make prior distribution, we do not go through any training step. In case of SA-BMA (VI), we just set $\delta$ as 0.05 for MOPED and make DNN into BNN. In case of SA-BMA (MCMC), we just set pre-trained weight as initialization and run experiments. After getting prior distribution, we search three hyperparameters: learning rate, $\gamma$, and $\alpha$. The hyperparamter tuning range included: learning rate in [1e-3, 5e-3, 1e-2, 5e-2], $\gamma$ in [5e-3, 8e-3, 1e-2, 5e-2, 1e-1, 5e-1, 7e-1], and $\alpha$ in [1e-6, 1e-5, 1e-4, 1e-3]. We set weight decay as $5e-4$ for all backbones and train the model over 150 epochs with early stopping. We fix $\beta$ as 1e-8 for all experiments.

### D.3 Algorithm of SA-BMA

Training algorithm of SA-BMA with Bayesian transfer learning can be depicted as Algorithm 1. In the first step, load a model pre-trained on the source task. Note that the pre-trained models do not have to be BNN. Namely, it is capable of using DNN, which can be easier to find than pre-trained BNN. Second, change the loaded DNN into BNN on the source or downstream task. Every BNN framework, containing VI, SWAG, LA, etc., can be adopted to make DNN into BNN. This study mainly employs PTL  (Shwartz-Ziv et al., ) and MOPED (Krishnan et al., ) for this step. We can skip this second step if you load a pre-trained BNN model before. Third, train the subnetwork of the converted BNN model with the proposed flat-seeking seeking optimizer. It allows model to converge into flat minina efficiently.

Figure: Algorithm 1 SA-BMA with Bayesian Transfer Learning

### D.4 Efficiency of SA-BMA with Bayesian Transfer Learning

**Table 14: Efficiency of SA-BMA with Bayesian Transfer Learning.**
| Method | Optim | Num. of Tr Param. |
| --- | --- | --- |
| DNN | SGD | $p$ |
| SAM | $p$ |  |
| FSAM | $p$ |  |
| SWAG | SGD | $p$ |
| F-SWAG | SAM | $p$ |
| VI | bSAM | $p$ |
| MOPED | SGD | $2p$ |
| E-MCMC | SGLD | $2p$ |
| PTL | SGLD | $p$ |
| SA-BMA | SA-BMA | $(K+2)p_{1}$ |

BNN often struggles with high computation and memory complexity, which makes optimizing large-scale BNN hard. However, SA-BMA only optimizes the last (classifier) and normalization layer, which only requires vector-sized learnable parameters. Table 14 provides the scalability of SA-BMA and baselines in the fine-tuning stage given pre-trained model. SA-BMA only requires fewer learnable parameters since $p_{1}\ll p$ and low rank $K$ are even fewer than DNN, where $p_{1}$ denotes the number of parameters in normalization and last layers. It only needs $1\%$ of learnable parameters compared to other methods in case of RN18 and ViT-B/16. SA-BMA efficiently adapts the model in a few-shot setting.

## Appendix E Proof and Derivation

### E.1 Proof of Theorem 1

The derivation of Theorem 1 can be straightforward using Wely’s inequality (Weyl, ).

We assume $M$ model $w_{m},m=1,..,M$, whose Hessian matrices $H_{w_{m}}$ are Hermitian. $w_{\text{avg}}=1/M\sum_{m=1}^{M}w_{m}$ is simple weight averaging and the Hessian of $w_{\text{avg}}$ also be a Hermitian matrix. Let’s say $\lambda_{n}(H_{w_{m}})$ is $n$-th maximal eigenvalue of $H_{w_{m}}$ and assume there are $N$ eigenvalues. $\lambda_{\max}(H_{w_{m}})$ is same as $\lambda_{1}(H_{w_{m}})$. Weyl’s inequality (Theorem 3) is known to bound the eigenvalues of Hermitian matrices.

###### Theorem 3 .

(Weyl’s Inequality) For Hermitian matrices $C_{m}\in\mathbb{C}^{p\times p}$, $k,l=1,...,M$,

$$ $\displaystyle\lambda_{k+l-1}(C_{i}+C_{j})\leq\lambda_{k}(C_{i})+\lambda_{l}(C_ {j})\leq\lambda_{k+l-N}(C_{i}+C_{j}).$ $$

Let $k=1$ and $l=1$, then Eq. (3) can be written as:

$$ $\displaystyle\lambda_{1}(C_{i}+C_{j})\leq\lambda_{1}(C_{i})+\lambda_{1}(C_{j}).$ $$

As we have $M$ Hermitian matrices, it can be expanded as:

$$ $\displaystyle\lambda_{1}(\frac{1}{M}\sum_{m=1}^{M}H_{w_{m}})\leq\frac{1}{M} \sum_{m=1}^{M}\lambda_{1}(H_{w_{m}}).$ (11) $$

One the other hand, we can let $(k,l)=\{(1,N),(N,1)\}$ and rewrite the Eq. (3) as:

$$ $\displaystyle\max\{\lambda_{1}(C_{i})+\lambda_{N}(C_{j}),\lambda_{N}(C_{i})+ \lambda_{1}(C_{j})\}\leq\lambda_{1}(C_{i}+C_{j}).$ $$

Again, set $M$ Hermitian matrices we have, it can be expanded as:

$$ $\max\left(\Bigg{\{}\frac{1}{M}\bigg{(}\lambda_{1}(H_{w_{m}})+\sum_{\begin{ subarray}{c}n=1\\ n\neq m\end{subarray}}^{M}\lambda_{N}(H_{w_{n}})\bigg{)}\Bigg{\}}_{m=1}^{M} \right)\leq\lambda_{1}(\frac{1}{M}\sum_{m=1}^{M}H_{w_{m}}).$ (12) $$

By combining Eq. (11) with Eq. (12) and substituting $\lambda_{1}$ to $\lambda_{1}{\text{max}}$ and $\lambda_{N}$ to $\lambda_{\text{min}}$, the flatness of averaged weight parameter is bounded as:

$$ $\max\left(\Bigg{\{}\frac{1}{M}\bigg{(}\lambda_{\text{max}}(H_{w_{m}})+\sum_{ \begin{subarray}{c}n=1\\ n\neq m\end{subarray}}^{M}\lambda_{\text{min}}(H_{w_{n}})\bigg{)}\Bigg{\}}_{m= 1}^{M}\right)\leq\lambda_{\text{max}}(\frac{1}{M}\sum_{m=1}^{M}H_{w_{m}})\leq \frac{\sum_{m=1}^{M}\lambda_{\text{max}}(H_{w_{m}})}{M}.$ (13) $$

BMA marginalizes diverse predictions by ensembling model output. As shown in Lemma 1, it is closely related to weight averaging (WA) (Izmailov et al., ; Wortsman et al., ; Rame et al., ).

###### Lemma 1 .

((Rame et al., )) Given predictions of model $f_{m}(\cdot)$ parameterized by $\{w_{m}\}_{m=1}^{M}$, $w_{\text{WA}}=\frac{1}{M}\sum_{m=1}^{M}w_{m}$, prediction of averaged model $f_{\text{WA}}$ parameterized by $w_{\text{WA}}$, prediction of BMA $f_{\text{BMA}}$, and arbitrary twice differentiable loss function $l(\cdot)$, let $\Delta=\|f_{\text{BMA}}(x)-f_{\text{WA}}(x)\|_{2}$. Then, $\forall(x,y)$

$$ $\displaystyle l(f_{\text{WA}}(x),y)$ $\displaystyle=l(f_{\text{BMA}}(x),y)+O(\Delta).$ $$

As the predictions of BMA and WA get closer, we can say the Hessian of loss for BMA and WA become approximately identical.
Specifically, they becomes equivalent as $O(\Delta)$ goes to zero, where the predictions of BMA and WA are same.

###### Theorem 3 .

###### Lemma 1 .

### E.2 Derivation of Bayesian Flat-Seeking Optimizer

#### E.2.1 Setting

Let model parameter $w\subseteq\mathbb{R}^{p}$ and $w\sim\mathcal{N}(\mu,\Sigma)$.
While fully-factorized or mean-field covariance is de facto in Bayesian Deep Learning, it cannot capitalize on strong points of Bayesian approach.
Inspired from SWAG, we approximate covariance combining diagonal covariance $\sigma\subseteq\mathbb{R}^{p}$ and low-rank matrix $L\subseteq\mathbb{R}^{p\times K}$ with low-rank component $K$.
Then, we can simply sample $w=\mu+\frac{1}{\sqrt{2}}(\sigma z_{1}+Lz_{2})$, where $z_{1}\sim\mathcal{N}(0,I_{p})$ and $z_{2}\sim\mathcal{N}(0,I_{K})$ where $p$, $K$ denotes the number of parameter, low-rank component, respectively. We treat flattened $\mu$, $\sigma$, and $L$, and concatenate as $\theta=\text{Concat}(\mu;\sigma;L)$.

#### E.2.2 Objective function

We compose our objective function with probabilistic weight, using KL Divergence as a metric to compare between two weights.

$$ $l^{\gamma}_{\text{SA-BMA}}(\theta)=\max_{d|\theta+\Delta\theta,\theta|\leq \gamma^{2}}l(\theta+\Delta\theta)+\beta\textrm{D}_{\textrm{KL}}(p_{\theta}(w| \mathcal{D})||p(w))$ (14) $$

$$ $\textrm{s.t.}\ \ d|\theta+\Delta\theta,\theta|=\textrm{D}_{\textrm{KL}}\big{[} p_{\theta+\Delta\theta}(w|\mathcal{D})||p_{\theta}(w|\mathcal{D})\big{]}.$ (15) $$

#### E.2.3 Optimization

##### From KL Divergence to Fisher Information Matrix

We can consider three options of perturbation on mean and covariance parameters of $w$: 1) Perturbation on mean, 2) perturbation on mean and diagonal variance, 3) Perturbation on mean and whole covariance. All of them can be approximated to Fisher Information Matrix.
Here, we show the relation between KLD and FIM considering the probation option 3.

Following FSAM, we deal with parameterized and conditioned as same notation:

$$ $p_{\theta+\Delta\theta}(w|\mathcal{D})=p(w|\mathcal{D},\theta+\Delta\theta).$ $$

By definition of KL divergence, we rewrite Eq. (15) as:

$$ $\textrm{D}_{\textrm{KL}}[p(w|\mathcal{D},\theta+\Delta\theta)||p(w|\mathcal{D} ,\theta)]=\int_{w}p(w|\mathcal{D},\theta+\Delta\theta)\ \log\frac{p(w|\mathcal {D},\theta+\Delta\theta)}{p(w|\mathcal{D},\theta)}dw.$ (16) $$

In Eq. (16), we apply first-order Taylor Expansion:

$$ $\begin{split}&p(w|\mathcal{D},\theta+\Delta\theta)\approx p(w|\mathcal{D}, \theta)+\nabla_{\theta}p(w|\mathcal{D},\theta)^{T}\Delta\theta.\\ &\log p(w|\mathcal{D},\theta+\Delta\theta)\approx\log p(w|\mathcal{D},\theta)+ \nabla_{\theta}\log p(w|\mathcal{D},\theta)^{T}\Delta\theta.\\ \end{split}$ (17) $$

Substitute right terms of Eq. (16) with Eq. (LABEL:eq:taylor_expansion_app):

$$ $\displaystyle\int_{w}p(w|\mathcal{D},\theta+\Delta\theta)\ \log\frac{p(w| \mathcal{D},\theta+\Delta\theta)}{p(w|\mathcal{D},\theta)}dw$ $\displaystyle=\int_{w}\big{(}p(w|\mathcal{D},\theta)+\Delta\theta^{T}\nabla_{ \theta}p(w|\mathcal{D},\theta)\big{)}\nabla_{\theta}\log p(w|\mathcal{D}, \theta)^{T}\Delta\theta\ dw$ $\displaystyle=\int_{w}p(w|\mathcal{D},\theta)\nabla_{\theta}\log p(w|\mathcal{ D},\theta)^{T}\Delta\theta dw$ $\displaystyle\ \ +\int_{w}\Delta\theta^{T}p(w|\mathcal{D},\theta)\nabla_{ \theta}\log p(w|\mathcal{D},\theta)\nabla_{\theta}\log p(w|\mathcal{D},\theta) ^{T}\Delta\theta\ dw.$ (18) $$

First term of Eq. (18) is equal to 0:

$$ $\begin{split}&\int_{w}p(w|\mathcal{D},\theta)\nabla_{\theta}\log p(w|\mathcal{ D},\theta)\ dw\\ &=\int_{w}p(w|\mathcal{D},\theta)\frac{\nabla_{\theta}p(w|\mathcal{D},\theta)} {p(w|\mathcal{D},\theta)}\ dw\\ &=\int_{w}\nabla_{\theta}p(w|\mathcal{D},\theta)\ dw\ =\nabla_{\theta}\int_{w} p(w|\mathcal{D},\theta)=0.\\ \end{split}$ (19) $$

We can rewrite Eq. (16) using Eq. (18), Eq. (LABEL:eq:pf_zero_term_app) and find it’s related to Fisher information matrix by the definition of expectation:

$$ $\begin{split}&D_{KL}[p(w|\mathcal{D},\theta+\Delta\theta)||p(w|\mathcal{D}, \theta)]\\ &=\int_{w}\Delta\theta^{T}p(w|\mathcal{D},\theta)\nabla_{\theta}\log p(w| \mathcal{D},\theta)\nabla_{\theta}\log p(w|\mathcal{D},\theta)^{T}\Delta\theta \\ &=\Delta\theta^{T}\mathbb{E}_{w}[\nabla_{\theta}\log p(w|\mathcal{D},\theta) \nabla_{\theta}\log p(w|\mathcal{D},\theta)^{T}]\Delta\theta\\ &=\Delta\theta^{T}F_{\theta}(\theta)\Delta\theta,\\ \end{split}$ (20) $$

where $F_{\theta}(\theta)=\mathbb{E}_{w,\mathcal{D}}[\nabla_{\theta}\log p(w|\mathcal
{D},\theta)\nabla_{\theta}\log p(w|\mathcal{D},\theta)^{T}]$.

It’s too expensive to calculate Fisher information matrix $F(\theta)$ in practice.
We introduce a pseudo inverse for Fisher information matrix $F_{\theta}(\theta)^{-1}$ with Samelson inverse of a vector (Gentle, ; Sidi, ; Wynn, ) :

$$ $F_{\theta}(\theta)^{-1}=\frac{\nabla_{\theta}\log p(w|\mathcal{D},\theta) \nabla_{\theta}\log p(w|\mathcal{D},\theta)^{T}}{\|\nabla_{\theta}\log p(w| \mathcal{D},\theta)\|^{4}}.$ (21) $$

##### Lagrangian Dual Problem

From the result of Eq. (20), we can rewrite the Eq. (14):

$$ $l^{\gamma}_{\text{SA-BMA}}(\theta)=\max_{\Delta\theta^{T}F_{\theta}(\theta) \Delta\theta\leq\gamma^{2}}l(\theta+\Delta\theta).$ (22) $$

We can reach the optimal perturbation of SA-BMA $\Delta\theta^{*}$ by using Taylor Expansion on $l(\theta+\Delta\theta)$ of Eq. (14):

$$ $l(\theta+\Delta\theta)=l(\theta)+\nabla_{\theta}l(\theta)^{T}\Delta\theta.$ (23) $$

Using Eq. (23), we can rewrite Eq. (14) as Lagrangian dual problem:

$$ $L(\Delta\theta,\lambda)=l(\theta)+\nabla l_{\theta}(\theta)^{T}\Delta\theta- \lambda(\Delta\theta^{T}F_{\theta}(\theta)\Delta\theta-\gamma^{2}).$ (24) $$

Differentiating Eq. (24), we get $\Delta\theta^{*}$:

$$ $\displaystyle\frac{\alpha L(\Delta\theta,\lambda)}{\alpha\Delta\theta}=\nabla_ {\theta}l(\theta)^{T}-2\lambda\Delta\theta^{T}F_{\theta}(\theta)=0$ $\displaystyle\therefore\ \Delta\theta^{*}=\frac{1}{2\lambda}F_{\theta}(\theta) ^{-1}\nabla_{\theta}l(\theta).$ (25) $$

Putting $\Delta\theta^{*}$ of Eq. (E.2.3) into $\Delta\theta$ of Eq. (24), we can rewrite Eq. (24):

$$ $\begin{split}L(\Delta\theta^{*},\lambda)&=l(\theta)+\frac{1}{2\lambda}\nabla_{ \theta}l(\theta)^{T}F_{\theta}(\theta)^{-1}\nabla_{\theta}l(\theta)\\ &-\frac{1}{4\lambda}\nabla_{\theta}l(\theta)^{T}F_{\theta}(\theta)^{-1}\nabla_ {\theta}l(\theta)+\lambda\gamma^{2}.\end{split}$ (26) $$

By taking derivative of Eq. (26) w.r.t. $\lambda$, we can also get $\lambda^{*}$:

$$ $\displaystyle\frac{\alpha L(\Delta\theta^{*},\lambda)}{\alpha\lambda}=-\frac{1 }{2\lambda^{2}}\nabla_{\theta}l(\theta)^{T}F_{\theta}(\theta)^{-1}\nabla_{ \theta}l(\theta)+\frac{1}{4\lambda^{2}}\nabla_{\theta}l(\theta)^{T}F_{\theta}( \theta)^{-1}\nabla_{\theta}l(\theta)+\gamma^{2}=0$ $\displaystyle 4\lambda^{2}\gamma^{2}=\nabla_{\theta}l(\theta)^{T}F_{\theta}( \theta)^{-1}\nabla_{\theta}l(\theta)$ $\displaystyle\therefore\ \lambda^{*}=\frac{\sqrt{\nabla_{\theta}l(\theta)^{T}F _{\theta}(\theta)^{-1}\nabla_{\theta}l(\theta)}}{2\gamma}.$ (27) $$

Finally, we get our $\Delta\theta^{*}_{SA-BMA}$ by substituting Eq. (E.2.3) into
Eq. (E.2.3):

$$ $\Delta\theta_{\text{SA-BMA}}^{*}=\gamma\frac{F_{\theta}(\theta)^{-1}\nabla_{ \theta}l(\theta)}{\sqrt{\nabla_{\theta}l(\theta)^{T}F_{\theta}(\theta)^{-1} \nabla_{\theta}l(\theta)}}.$ (28) $$

### E.3 Proof of Theorem 2

#### E.3.1 SA-BMA to FSAM

Theorem 2 shows that SA-BMA is degenerated to FSAM under DNN and diagonal FIM setting. Deterministic parameters draw out the constant prior $p(w|x)=c$ and mean-only variational parameters $w=\theta$.

First, we can rewrite the log posterior $\log p_{\theta}(w|x,y)$ with Bayes rule:

$$ $\log p_{\theta}(w|x,y)=\log p_{\theta}(y|x,w)+\log p_{\theta}(w|x)-Z,$ (29) $$

where $Z$ is constant independent of $w$. Is is noted that the log posterior is divided into the log predictive distribution and log prior. Also, note that the prior is conditioned on the data to align with a generalized notation. The prior can depend on the input; however, this dependence is often ignored in practice (Marek et al., ).

By taking derivative with respect to $\theta$ on Eq. (29), the constant $Z$ goes to 0 0:

$$ $\nabla_{\theta}\log p_{\theta}(w|x,y)=\nabla_{\theta}p_{\theta}(y|x,w)+\nabla_ {\theta}\log p_{\theta}(w|x).$ $$

We have constant prior $p(w|x)=c$ in deterministic setting and it makes the gradient of log posterior and log predictive distribution:

$$ $\nabla_{\theta}\log p_{\theta}(w|x,y)=\nabla_{\theta}p_{\theta}(y|x,w).$ (30) $$

Underlying Eq. (30), it is possible to substitute the gradient of log posterior into the gradient of log predictive distribution and FIM over posterior goes to FIM over predictive distribution:

$$ $\displaystyle F_{\theta}(\theta)=$ $\displaystyle\mathbb{E}_{w,\mathcal{D}}[\nabla_{\theta}\log p_{\theta}(w|x,y) \nabla_{\theta}\log p_{\theta}(w|x,y)^{T}]$ $\displaystyle=\mathbb{E}_{w,\mathcal{D}}[\nabla_{\theta}\log p_{\theta}(y|x,w) \nabla_{\theta}\log p_{\theta}(y|x,w)^{T}].$ (31) $$

By taking diagonal computation over Eq. (E.3.1), it goes to $F_{y}(\theta)$. After that, using the fact that mean-only variational parameters, SA-BMA degnerates to FSAM with $F_{y}(\theta)$ finally.

$$ $\Delta\theta_{\text{SA-BMA}}=\gamma\frac{F_{y}(\theta)^{-1}\nabla_{\theta}l( \theta)}{\sqrt{F_{y}(\theta)^{-1}\nabla_{\theta}l(\theta)F_{y}(\theta)^{-1}}}.$ (32) $$

#### E.3.2 SA-BMA to SAM

It is simple to show that SA-BMA is extended version of SAM by defining FIM over output distribution $F_{y}(w)$ as identity matrix $I$ in Eq. (32), SA-BMA goes to SAM.

$$ $\Delta\theta_{\text{SA-BMA}}=\gamma\frac{\nabla_{w}l(w)}{\|\nabla_{w}l(w)\|_{2 }}.$ (33) $$

#### E.3.3 SA-BMA to NG

Theorem 2 also states the NG can be approximated with SA-BMA under specific conditions.
The update rule of natural gradient and SA-BMA can be written as Eq. (34) and Eq. (35), respectively.

$$ $\displaystyle\theta\leftarrow\theta+\eta_{\text{NG}}F_{y}(\theta)^{-1}\nabla_{ \theta}l(\theta).$ (34) $\displaystyle\theta\leftarrow\theta+\eta_{\text{SA-BMA}}\nabla_{\theta}l( \theta+\Delta\theta).$ (35) $$

where $\eta_{\text{NG}}$ and $\eta_{\text{SA-BMA}}$ denote the learning rate of NG and SA-BMA. Note that we assume the log likelihood as loss fuction.

The $\nabla_{\theta}l(\theta+\Delta\theta)$ in Eq. (35) can be approximated with Taylor Expansion, the connection between Hessian and FIM, and Eq. (E.3.1) in DNN setup:

$$ $\displaystyle\nabla_{\theta}l(\theta+\Delta\theta)$ $\displaystyle\approx\nabla_{\theta}l(\theta)+\nabla^{2}_{\theta}\Delta\theta$ $\displaystyle=\nabla_{\theta}l(\theta)+\nabla^{2}_{\theta}l(\theta)\cdot\gamma \frac{F_{\theta}(\theta)^{-1}\nabla_{\theta}l(\theta)}{\sqrt{\nabla_{\theta}l( \theta)^{T}F_{\theta}(\theta)^{-1}\nabla_{\theta}l(\theta)}}$ $\displaystyle=\nabla_{\theta}l(\theta)+\gamma^{\prime}\nabla_{\theta}^{2}l( \theta)F_{\theta}(\theta)^{-1}\nabla_{\theta}l(\theta)\ \bigg{(}\because\text{ Let}\ \gamma^{\prime}=\frac{\gamma}{\sqrt{\nabla_{\theta}l(\theta)^{T}F_{ \theta}(\theta)^{-1}\nabla_{\theta}l(\theta)}}\bigg{)}$ $\displaystyle=[I+\gamma^{\prime}\nabla^{2}_{\theta}l(\theta)F_{\theta}(\theta) ^{-1}]\nabla_{\theta}l(\theta)$ $\displaystyle\approx(1+\gamma^{\prime})\nabla_{\theta}l(\theta)\ (\because \nabla_{\theta}^{2}l(\theta)\approx F_{y}(\theta),F_{\theta}(\theta)=F_{y}( \theta)).$ (36) $$

By using the denoted learning rate $\eta_{\text{SA-BMA}}=\frac{\eta_{\text{NG}}}{I+\gamma^{\prime}}F_{\theta}(
\theta)^{-1}$, Eq. (E.3.1), and Eq. (E.3.3), update rule of SA-BMA approximates to NG.

## Appendix F Fine-Grained Image Classification

In addition to classification accuracy, SA-BMA shows superior performance compared to the baseline in NLL metric, indicating that SA-BMA effectively quantifies uncertainty.

Table: Table 15: Downstream task NLL with RN50 and ViT-B/16 pre-trained on IN 1K. SA-BMA (SWAG) denotes using SWAG to convert pre-trained model into BNN. Bold and underline denote best and second best performance each. SA-BMA demonstrates superior performance across all 16-shot datasets, including EuroSAT , Oxford Flowers, Oxford Pets, and UCF101.

## Appendix G Performance under Distribution shift

We adopt the corrupted dataset CIFAR10/100C to test the robustness over distribution shift. The corrupted dataset transform the CIFAR10/100-test dataset, which has been modified to shift the distribution of the test data further away from the training data. It contains 19 kinds of corrupt options, such as varying brightness or contrast to adding Gaussian noise. The severity level indicates the strength of the transformation and is typically expressed as a number from 1 to 5, where the higher the number, the stronger the transformation. In Figure 13, our method ensures relatively robust performance in the data distribution shift, even as the severity increases.

Figure: Figure 13: NLL performance of ResNet 18 and ViT-B/16 on corrupted CIFAR10 and CIFAR100, respectively (Hendrycks & Dietterich, ).
Refer to caption: extracted/5909381/figure/severity_nll_plot.png

We also provide the detailed results of three repeated experiments with corrupted sets.

Figure: (a) RN18 CIFAR10C

## Appendix H Additional Loss Surface Of Sampled Model

Figure: (a) seed 1
Refer to caption: extracted/5909381/figure/loss_surface/loss_surface_Blues_seed1.png

As shown in Figure 5, we sampled four model parameters from the posterior, which were trained on CIFAR10 with RN18. It shows the consistent and robust trend of flatness of SA-BMA in the loss surface. In Figure 14, commencing with the leftmost panel, a 3D surface plot illustrates the loss surface, revealing the SA-BMA model’s comparatively flatter topology against the PTL model. This initial plot intuitively demonstrates that the SA-BMA model exhibits a flatter loss surface compared to the PTL model. Following this, the second visualization compresses the information along a diagonal plane into a 1D scatter plot. This transformation reveals areas obscured in the 3D view, highlighting that SA-BMA maintains a considerably flatter and lower-loss landscape. The third and fourth images showcase the loss surface through 2D contour plots, from which one can easily discern that the area representing the lowest loss is significantly more expansive for SA-BMA than for PTL.

## Appendix I Limitation and Future Works

This study has several limitations. Firstly, calculating the FIM in weight space rather than output space makes it intractable to compute the FIM for the entire model parameter. Obtaining the FIM for the entire model weight space could lead to much more powerful performance improvements, making it one potential direction for future work. Secondly, the assumption of the existence of pre-trained models is necessary for Bayesian transfer learning. In situations where pre-trained weights are not available, performance improvements may be somewhat limited.

## Peer Reviews

confidence: 4
contribution: 2
initial_rating: 3
presentation: 3
questions: - How to measure the flatness of a BNN, as it involves a set of NNs? Do the authors average the flatness of all samples in Fig. 1 and 2?
soundness: 2
strengths: - This paper targets the generalization of BNNs, which is an important problem.
- The paper provides empirical and theoretical analysis to support the need for flatness in BNNs.
summary: The paper proposes a sharpness-aware Bayesian neural network (BNNs) to ensure the found modes are flat. A new Bayesian transfer learning scheme is also developed to leverage the pre-trained deep neural networks.
weaknesses: - The overall goal of the paper is vague. As far as I understand, the proposed method increases the flatness of the variational parameter \theta, not the model parameter w. However, the literature shows flatter w leads to better generalization. The seems to be a gap. The meaning of "flatness in BNNs" is not very clear in the paper.
- Previous works have demonstrated the benefits of including flatness in BNNs, e.g. Möllenhoff & Khan, 2022, Nguyen et al., 2023, Li & Zhang, 2023. The additional insights offered by Sec 3 are unclear.
- It is unclear how Theorem 1 indicates that BNN needs flatness. This theorem basically shows the relationship between the flatness of the weight-averaged model and the flatness of individual models. It does not explain the benefits of ensuring flatness in BNNs.
- Variational inference (VI) approximates the posterior through an optimization problem. We can naively apply SAM to the objective of VI. The difference and benefit of the proposed objectives in Eq.4 and 5 over this naive version are unclear.
- In the experiment section, the proposed method is applied to VI, SWAG, and MCMC. However, it is unclear how the method is compatible with SWAG and MCMC. 
- The proposed Bayesian transfer learning scheme is a straightforward application to transfer learning. The novelty of this part is low.

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 3
questions: - SAM training is already more expensive than vanilla gradient descent, adding VI on top (now you need to sample to estimate ELBO), won't it be too expensive? This begs another question, how much improvement can be gained by using SA-BMA when compared with LA on SAM solution? I see LA implemented in your code but there are no results of LA in the paper. I would be interested to see an experiment comparing LA on SGD solution, LA on SAM solution, and SA-BMA.

- How do you ensure VI has been trained successfully? I see in multiple cases VI ends up with higher NLL and ECE than MAP, which seems strange.
soundness: 2
strengths: - The connection between the proposed objective and existing works is well-analyzed

- Well written and easy to follow
summary: Flat optima has been shown to connect with good generalization in point estimation for neural networks. The authors study flatness for Bayesian neural networks and propose a flatness-seeking optimizer, Sharpness-Aware Bayesian Model Averaging (SA-BMA), for VI. Specifically, the authors first show empirically that (1) BNN's posterior tends to land in a sharper loss region; (2) when making a prediction with MC estimation, using flat samples will result in better performance. Based on the empirical finding, the authors propose a new learning objective for VI, which also accounts for flatness as well as a Bayesian Transfer Learning scheme for efficient computation for large models. Experiment results have shown SA-BMA can improve generalization in few-shot classification and distribution shift.
weaknesses: - In Bayesian deep learning in the end we have a distribution, here the authors use the averaged Hessian eigenvalues of different sampled weights as the measurement of flatness. I'm not fully convinced this is a good measurement of a flatness over a distribution. 

- The proposed objective is expensive to train.

---

confidence: 4
contribution: 3
initial_rating: 6
presentation: 3
questions: Please refer to the weaknesses.
soundness: 3
strengths: 1. I notice that this is a resubmission paper. Compared with the last version, more analysis on the flatness of the loss landscape and the relations between flatness and general performances are included. I respect the authors' efforts in studying the geometry of loss landscape.

2. The empirical analysis using Hessian eigenvalues clearly demonstrates why finding flat modes is important to the overall performance.

3. Comprehensive experiments are conducted to demonstrate the effectiveness of SA-BMA.
summary: This paper proposes a flatness-aware optimizer for Bayesian model averaging, which applies to a variety of Bayesian inference algorithms. The introduced optimizer SA-BMA is generalized from the SAM optimizer. This paper also has a clear empirical proof of why flatness is important and why existing Bayesian inference methods ignore flatness.
weaknesses: 1. The experiments on real-world datasets are limited to CIFAR10/100. I expect to see results on large-scale dataset like ImageNet to show the scalability of SA-BMA.

2. Figure 5 may lead to a misunderstanding that PTL and SA-BMA change the loss surface (in the first 2 figures).

---

confidence: 3
contribution: 1
initial_rating: 3
presentation: 3
questions: - How many posterior samples have you used for Figure 2a?
- How large are your Bayesian ensembles for the final experiments, i.e. how many times do you sample from your posterior to approximate the PPD integral?
soundness: 3
strengths: The paper does propose an interesting combination of lines of work in deep learning, it missed out on evaluating whether this combination is useful in my opinion, though. I do see the plots in Figure 2 as a negative result in this way, and think based on this one could have written an interesting paper on flatness-seeking methods approximating Bayesian averages.
summary: This paper proposes to use sharpness-aware minimization for Bayesian models. It proposes a framework that can be used with 3 different posterior approximation methods.
weaknesses: - I do not think there is a need for flatness-aware optimization in Bayesian models. That is because Bayesian models are building an average over all models with high likelihood (or posterior likelihood for informative priors). Taking this average will naturally lead to including a lot of models from flat optima, as they are simply wider and thus have more mass (in the prior). This in my opinion is underlined by the experiments in Figure 2b-c, where we can see that by simply using a larger Ensemble, thus approximating the true PPD more closely, we get the same effect as when choosing models that lie in wide optima. I hope I did understand this experiment right and the 30 models that you speak about are 30 samples from your posterior.
    - One more point on this: I can imagine that this argument does not work well for the particular problems that VI has, as it will always try to find a simple Gaussian distribution that represents the posterior.
- The flatness difference in Experiment 5.1 looks marginal at mere 2x radius of the optimum and a worse likelihood. This toy experiment would be more interesting if both optima had the same likelihood, but one being *much* more narrow.
- Your language is missing a lot of articles, but generally feels more like a draft than a paper. I guess you are not a native English speaker, I am neither, so this does not affect the score much for me, but I can recommend you to use LLMs/DeepL to improve your English writing.
- The accuracies seen in the experiments seem to be far away from the state of the art for the models, see e.g. this torch tutorial https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/  
- SAM is known to increase the time each step takes, this algorithm should have the same impact. A comparison of performance over time is missing, though.