summaries: This paper extends the idea of Stochastic Weighting Averaging (SWA) to the context of Domain Generalization (DG). Theoretically, the authors argues that finding a flat minima improves domain generalization. Algorithmically, the authors modify SWA by increasing the number of samples being averaged (e.g. per iteration) and by selecting the interval from where the samples are taken. The proposed algorithm  is evaluated in  the DomainBed benchmark and shows compelling results. This paper studies how to improve the model performance on domain generalization problems from the perspective of loss landscape. Specifically, the authors propose to apply weight averaging (WA) to find flat minima and demonstrate this could lead to improve model generalization on unseen domains. Theoretically, the authors provide generalization bounds for the proposed method. Empirically, the proposed method achieves better performance on benchmark datasets compared with previous methods. This paper studies the domain generalization (DG) problem setting and proposes a modification to the stochastic weight averaging (SWA) method that leads to better performance on DG testbeds. The proposed method, named SWAD, uses the same basic idea as SWA but samples parameters more densely and uses additional techniques for preventing the incorporation of overfit parameters. Some theoretical analysis supports the general thrust of seeking flat minima for generalization. The focus of the paper, however, is empirical, as SWAD demonstrates improved performance compared to many prior methods on several DG testbeds. Furthermore, SWAD can be combined with these prior methods, such as CORAL, for even better performance. This paper provides some theoretical justification that so-called flat solutions exhibit better domain generalization along with a strongly performing training methodology, SWAD, for improving domain generalization. They first prove theorems bounding the domain generalization performance in terms of robust risk minimization. Then they propose an approach to finding flat solutions related to previous work on in distribution generalization, and they thoroughly explore this method with regard to the flatness of solutions found, its domain generalization performance, and also perform ablations of the method.  
abstractText: Domain generalization (DG) methods aim to achieve generalizability to an unseen target domain by using only training data from the source domains. Although a variety of DG methods have been proposed, a recent study shows that under a fair evaluation protocol, called DomainBed, the simple empirical risk minimization (ERM) approach works comparable to or even outperforms previous methods. Unfortunately, simply solving ERM on a complex, non-convex loss function can easily lead to sub-optimal generalizability by seeking sharp minima. In this paper, we theoretically show that finding flat minima results in a smaller domain generalization gap. We also propose a simple yet effective method, named Stochastic Weight Averaging Densely (SWAD), to find flat minima. SWAD finds flatter minima and suffers less from overfitting than does the vanilla SWA by a dense and overfit-aware stochastic weight sampling strategy. SWAD shows state-of-the-art performances on five DG benchmarks, namely PACS, VLCS, OfficeHome, TerraIncognita, and DomainNet, with consistent and large margins of +1.6% averagely on outof-domain accuracy. We also compare SWAD with conventional generalization methods, such as data augmentation and consistency regularization methods, to verify that the remarkable performance improvements are originated from by seeking flat minima, not from better in-domain generalizability. Last but not least, SWAD is readily adaptable to existing DG methods without modification; the combination of SWAD and an existing DG method further improves DG performances. Source code is available at https://github.com/khanrc/swad.
authors.name: Junbum Cha
authors.name: Sanghyuk Chun
authors.name: Kyungjae Lee
authors.name: Han-Cheol Cho
authors.name: Seunghyun Park
authors.name: Yunsung Lee
authors.name: Sungrae Park
authors.name: NAVER Clova
references.authors: Dengxin Dai Luc Van Gool
references.title: Dark model adaptation: Semantic image segmentation from daytime to nighttime
references.venue: In 2018 21st International Conference on Intelligent Transportation Systems (ITSC),
references.authors: Claudio Michaelis Benjamin Mitzkus Robert Geirhos Evgenia Rusak Oliver Bringmann Alexander S Ecker Matthias Bethge Wieland Brendel
references.title: Benchmarking robustness in object detection: Autonomous driving when winter is coming
references.authors: Terrance de Vries Ishan Misra Changhan Wang Laurens van der Maaten
references.title: Does object recognition work for everyone
references.venue: In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops,
references.authors: Kaiyu Yang Klint Qinami Li Fei-Fei Jia Deng Olga Russakovsky
references.title: Towards fairer datasets: Filtering and balancing the distribution of the people subtree in the imagenet hierarchy
references.venue: In Proceedings of the 2020 Conference on Fairness, Accountability, and Transparency,
references.authors: Robert Geirhos Patricia Rubisch Claudio Michaelis Matthias Bethge Felix A. Wichmann Wieland Brendel
references.title: Imagenet-trained cnns are biased towards texture; increasing shape bias improves accuracy and robustness
references.venue: In International Conference on Learning Representations,
references.authors: Sara Beery Grant Van Horn Pietro Perona
references.title: Recognition in terra incognita
references.venue: In Proceedings of the European Conference on Computer Vision (ECCV),
references.authors: Da Li Yongxin Yang Yi-Zhe Song Timothy M Hospedales
references.title: Deeper, broader and artier domain generalization
references.venue: In IEEE International Conference on Computer Vision,
references.authors: Krikamol Muandet David Balduzzi Bernhard Schölkopf
references.title: Domain generalization via invariant feature representation
references.venue: In International Conference on Machine Learning,
references.authors: Yaroslav Ganin Evgeniya Ustinova Hana Ajakan Pascal Germain Hugo Larochelle François Laviolette Mario Marchand Victor Lempitsky
references.title: Domain-adversarial training of neural networks
references.venue: Journal of machine learning research,
references.authors: Ya Li Mingming Gong Xinmei Tian Tongliang Liu Dacheng Tao
references.title: Domain generalization via conditional invariant representations
references.venue: In AAAI Conference on Artificial Intelligence,
references.authors: Hyojin Bahng Sanghyuk Chun Sangdoo Yun Jaegul Choo Seong Joon Oh
references.title: Learning de-biased representations with biased representations
references.venue: In International Conference on Machine Learning (ICML),
references.authors: Shanshan Zhao Mingming Gong Tongliang Liu Huan Fu Dacheng Tao
references.title: Domain generalization via entropy regularization
references.venue: Neural Information Processing Systems,
references.authors: Da Li Yongxin Yang Yi-Zhe Song Timothy Hospedales
references.title: Learning to generalize: Metalearning for domain generalization
references.venue: In AAAI Conference on Artificial Intelligence,
references.authors: Qi Dou Daniel C Castro Konstantinos Kamnitsas Ben Glocker
references.title: Domain generalization via model-agnostic learning of semantic features
references.venue: Neural Information Processing System,
references.authors: Yogesh Balaji Swami Sankaranarayanan Rama Chellappa
references.title: Metareg: Towards domain generalization using meta-regularization
references.venue: Neural Information Processing Systems,
references.authors: Marvin Zhang Henrik Marklund Abhishek Gupta Sergey Levine Chelsea Finn
references.title: Adaptive risk minimization: A meta-learning approach for tackling group shift
references.venue: arXiv preprint arXiv:2007.02931,
references.authors: Kaiyang Zhou Yongxin Yang Yu Qiao Tao Xiang
references.title: Domain generalization with mixstyle
references.venue: In International Conference on Learning Representations,
references.authors: Shiv Shankar Vihari Piratla Soumen Chakrabarti Siddhartha Chaudhuri Preethi Jyothi Sunita Sarawagi
references.title: Generalizing across domains via cross-gradient training
references.venue: In International Conference on Learning Representations,
references.authors: Fabio M Carlucci Antonio D’Innocente Silvia Bucci Barbara Caputo Tatiana Tommasi
references.title: Domain generalization by solving jigsaw puzzles
references.venue: In IEEE/CVF Conference on Computer Vision and Pattern Recognition,
references.authors: Martin Arjovsky Léon Bottou Ishaan Gulrajani David Lopez-Paz
references.title: Invariant risk minimization
references.venue: arXiv preprint arXiv:1907.02893,
references.authors: David Krueger Ethan Caballero Joern-Henrik Jacobsen Amy Zhang Jonathan Binas Remi Le Priol Aaron Courville
references.title: Out-of-distribution generalization via risk extrapolation (rex)
references.venue: arXiv preprint arXiv:2003.00688,
references.authors: Ishaan Gulrajani David Lopez-Paz
references.title: In search of lost domain generalization
references.venue: In International Conference on Learning Representations,
references.authors: Nitish Shirish Keskar Dheevatsa Mudigere Jorge Nocedal Mikhail Smelyanskiy Ping Tak Peter Tang
references.title: On large-batch training for deep learning: Generalization gap and sharp minima
references.venue: In International Conference on Learning Representations,
references.authors: Timur Garipov Pavel Izmailov Dmitrii Podoprikhin Dmitry P Vetrov Andrew Gordon Wilson
references.title: Loss surfaces, mode connectivity, and fast ensembling of dnns
references.venue: In Neural Information Processing Systems,
references.authors: Pavel Izmailov Dmitrii Podoprikhin Timur Garipov Dmitry Vetrov Andrew Gordon Wilson
references.title: Averaging weights leads to wider optima and better generalization
references.venue: Conference on Uncertainty in Artificial Intelligence,
references.authors: Pierre Foret Ariel Kleiner Hossein Mobahi Behnam Neyshabur
references.title: Sharpness-aware minimization for efficiently improving generalization
references.venue: In International Conference on Learning Representations,
references.authors: Gintare Karolina Dziugaite Daniel M Roy
references.title: Computing nonvacuous generalization bounds for deep (stochastic) neural networks with many more parameters than training data
references.venue: In Uncertainty in Artificial Intelligence,
references.authors: Yiding Jiang Behnam Neyshabur Hossein Mobahi Dilip Krishnan Samy Bengio
references.title: Fantastic generalization measures and where to find them
references.authors: V Vapnik
references.title: Statistical learning theory
references.venue: NY: Wiley,
references.authors: Seonguk Seo Yumin Suh Dongwan Kim Jongwoo Han Bohyung Han
references.title: Learning to optimize domain specific normalization for domain generalization
references.venue: European Conference on Computer Vision,
references.authors: Baochen Sun Kate Saenko
references.title: Deep coral: Correlation alignment for deep domain adaptation
references.venue: In European conference on computer vision,
references.authors: Hyeonseob Nam HyunJae Lee Jongchan Park Wonjun Yoon Donggeun Yoo
references.title: Reducing domain gap by reducing style bias
references.venue: In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition,
references.authors: Prithvijit Chattopadhyay Yogesh Balaji Judy Hoffman
references.title: Learning to balance specificity and invariance for in and out of domain generalization
references.venue: In European Conference on Computer Vision,
references.authors: Matthew Norton Johannes O Royset
references.title: Diametrical risk minimization: Theory and computations
references.venue: arXiv preprint arXiv:1910.10844,
references.authors: Hongyi Zhang Moustapha Cisse Yann N. Dauphin David Lopez-Paz
references.title: mixup: Beyond empirical risk minimization
references.venue: International Conference on Learning Representations,
references.authors: Sangdoo Yun Dongyoon Han Seong Joon Oh Sanghyuk Chun Junsuk Choe Youngjoon Yoo
references.title: Cutmix: Regularization strategy to train strong classifiers with localizable features
references.venue: In International Conference on Computer Vision (ICCV),
references.authors: Shai Ben-David John Blitzer Koby Crammer Alex Kulesza Fernando Pereira Jennifer Wortman Vaughan
references.title: A theory of learning from different domains
references.venue: Machine learning,
references.authors: Diederik P Kingma Jimmy Ba
references.title: Adam: A method for stochastic optimization
references.venue: In International Conference on Learning Representations,
references.authors: Pratik Chaudhari Anna Choromanska Stefano Soatto Yann LeCun Carlo Baldassi Christian Borgs Jennifer Chayes Levent Sagun Riccardo Zecchina
references.title: Entropy-sgd: Biasing gradient descent into wide valleys
references.venue: Journal of Statistical Mechanics: Theory and Experiment,
references.authors: Leslie N Smith
references.title: Cyclical learning rates for training neural networks
references.venue: IEEE winter conference on applications of computer vision (WACV),
references.authors: Kaiming He Xiangyu Zhang Shaoqing Ren Jian Sun
references.title: Deep residual learning for image recognition
references.venue: In IEEE Conference on Computer Vision and Pattern Recognition,
references.authors: Olga Russakovsky Jia Deng Hao Su Jonathan Krause Sanjeev Satheesh Sean Ma Zhiheng Huang Andrej Karpathy Aditya Khosla Michael Bernstein
references.title: Imagenet large scale visual recognition challenge
references.venue: International Journal of Computer Vision,
references.authors: Chen Fang Ye Xu Daniel N Rockmore
references.title: Unbiased metric learning: On the utilization of multiple datasets and web images for softening bias
references.venue: In IEEE International Conference on Computer Vision,
references.authors: Hemanth Venkateswara Jose Eusebio Shayok Chakraborty Sethuraman Panchanathan
references.title: Deep hashing network for unsupervised domain adaptation
references.venue: In IEEE conference on computer vision and pattern recognition,
references.authors: Sara Beery Grant Van Horn Pietro Perona
references.title: Recognition in terra incognita
references.venue: In European Conference on Computer Vision,
references.authors: Xingchao Peng Qinxun Bai Xide Xia Zijun Huang Kate Saenko Bo Wang
references.title: Moment matching for multi-source domain adaptation
references.venue: In IEEE/CVF International Conference on Computer Vision,
references.authors: Oren Nuriel Sagie Benaim Lior Wolf
references.title: Permuted adain: Reducing the bias towards global statistics in image classification
references.venue: In IEEE/CVF Conference on Computer Vision and Pattern Recognition,
references.authors: Shujun Wang Lequan Yu Caizi Li Chi-Wing Fu Pheng-Ann Heng
references.title: Learning from extrinsic and intrinsic supervisions for domain generalization
references.venue: In European Conference on Computer Vision,
references.authors: Shiori Sagawa Pang Wei Koh Tatsunori B. Hashimoto Percy Liang
references.title: Distributionally robust neural networks
references.venue: In International Conference on Learning Representations,
references.authors: Minghao Xu Jian Zhang Bingbing Ni Teng Li Chengjie Wang Qi Tian Wenjun Zhang
references.title: Adversarial domain adaptation with domain mixup
references.venue: In AAAI Conference on Artificial Intelligence,
references.authors: Shen Yan Huan Song Nanxiang Li Lincan Zou Liu Ren
references.title: Improve unsupervised domain adaptation with mixup training
references.venue: arXiv preprint arXiv:2001.00677,
references.authors: Yufei Wang Haoliang Li Alex C Kot
references.title: Heterogeneous domain generalization via domain mixup
references.venue: In IEEE International Conference on Acoustics, Speech and Signal Processing,
references.authors: Haoliang Li Sinno Jialin Pan Shiqi Wang Alex C Kot
references.title: Domain generalization with adversarial feature learning
references.venue: In IEEE Conference on Computer Vision and Pattern Recognition,
references.authors: Gilles Blanchard Aniket Anand Deshmukh Urun Dogan Gyemin Lee Clayton Scott
references.title: Domain generalization by marginal transfer learning
references.venue: Journal of Machine Learning Research,
references.authors: Zeyi Huang Haohan Wang Eric P Xing Dong Huang
references.title: Self-challenging improves crossdomain generalization
references.venue: European Conference on Computer Vision,
references.authors: Boris T Polyak Anatoli B Juditsky
references.title: Acceleration of stochastic approximation by averaging
references.venue: SIAM journal on control and optimization,
references.authors: Takeru Miyato Shin-ichi Maeda Masanori Koyama Shin Ishii
references.title: Virtual adversarial training: a regularization method for supervised and semi-supervised learning
references.venue: IEEE Transactions on Pattern Analysis and Machine Intelligence,
references.authors: Samuli Laine Timo Aila
references.title: Temporal ensembling for semi-supervised learning
references.venue: In International Conference on Learning Representations,
references.authors: Dan Hendrycks Thomas Dietterich
references.title: Benchmarking neural network robustness to common corruptions and perturbations
references.venue: In International Conference on Learning Representations,
references.authors: Dan Hendrycks Steven Basart Norman Mu Saurav Kadavath Frank Wang Evan Dorundo Rahul Desai Tyler Zhu Samyak Parajuli Mike Guo
references.title: The many faces of robustness: A critical analysis of out-of-distribution generalization
references.venue: arXiv preprint arXiv:2006.16241,
references.authors: Kai Yuanqing Xiao Logan Engstrom Andrew Ilyas Aleksander Madry
references.title: Noise or signal: The role of image backgrounds in object recognition
references.venue: In International Conference on Learning Representations,
references.authors: Hanjoo Kim Minkyu Kim Dongjoo Seo Jinwoong Kim Heungseok Park Soeun Park Hyunwoo Jo KyungHyun Kim Youngil Yang Youngkwan Kim
references.title: Nsml: Meet the mlaas platform with a real-world case study
references.venue: arXiv preprint arXiv:1810.09957,
sections.heading: 1 Introduction
sections.text: Independent and identically distributed (i.i.d.) condition is the underlying assumption of machine learning experiments. However, this assumption may not hold in real-world scenarios, i.e., the training and the test data distribution may differ significantly by distribution shifts. For example, a self-driving car should adapt to adverse weather or day-to-night shifts [1, 2]. Even in a simple image recognition scenario, systems rely on wrong cues for their prediction, e.g., geographic distribution [3], demographic statistics [4], texture [5], or backgrounds [6]. Consequently, a practical system should require generalizability to distribution shift, which is yet often failed by traditional approaches.
  Domain generalization (DG) aims to address domain shift simulated by training and evaluating on different domains. DG tasks assume that both task labels and domain labels are accessible. For example, PACS dataset [7] has seven task labels (e.g., “dog”, “horse”) and four domain labels (e.g., “photo”, “sketch”). Previous approaches explicitly reduced domain gaps in the latent space [8–
  ∗Equal contribution †Part of work done while at NAVER Clova Correspondence to: Junbum Cha <junbum.cha@kakaobrain.com>, Sungrae Park <sungrae.park@upstage.ai>
  35th Conference on Neural Information Processing Systems (NeurIPS 2021).
  12], obtained well-transferable model parameters by the meta-learning framework [13–16], data augmentation [17–19], or capturing causal relation [20, 21]. Despite numerous previous attempts for a decade, Gulrajani and Lopez-Paz [22] showed that a simple empirical risk minimization (ERM) approach works comparably or even outperforms the previous attempts on diverse DG benchmarks under a fair evaluation protocol, called “DomainBed”.
  Unfortunately, although ERM showed surprising empirical success on DomainBed, simply minimizing the empirical loss on a complex and non-convex loss landscape is typically not sufficient to arrive at a good generalization [23–26]. In particular, the connection between the generalization gap and the flatness of loss landscapes has been actively discussed under the i.i.d. condition [23–28]. Izmailov et al. [25] argued that seeking flat minima will lead to robustness against the loss landscape shift between training and test datasets, while a simple ERM converges to the boundary of a wide flat minimum and achieves insufficient generalization. In the DG scenario, because training and test loss landscapes differ more drastically due to the domain shift, we conjecture that the generalization gap between flat and sharp minima is larger than expected in the i.i.d. scenario.
  To show that flatter minima generalize better to unseen domains, we formulate a robust risk minimization (RRM) problem defined by the worst-case empirical risks within neighborhoods in parameter space [26, 34]. We theoretically show that the generalization gap of DG, i.e., the error on the target domain, is upper bounded by RRM, i.e., a flat optimal solution. Based on our theoretical observation, we modify stochastic weight averaging (SWA) [25], one of the popular existing flatness-aware solvers, by introducing a dense and overfit-aware stochastic weight sampling strategy. First, we suggest to sample weights densely, i.e., for every iteration. Also, we search the start and end iterations for averaging by considering the validation loss to avoid overfitting. We empirically show that the proposed Stochastic Weight Averaging Densely (SWAD) finds flatter minima than the vanilla SWA does, resulting in better generalization to unseen domains.
  Contribution. Our main contribution is introducing flatness into DG, and showing remarkably outperforming performances against existing DG methods. As shown in Table 1, our SWAD improves the average DG performances by 3.6pp against the ERM baseline and 1.6pp against the existing best methods. Furthermore, by combining SWAD and previous SOTA [31], we even achieve 0.4pp improvements against the vanilla SWAD results. We also empirically show that while popular indomain generalization methods without considering flatness, e.g., Mixup [35] or CutMix [36], are not effective to out-of-domain generalization (Table 3), flatness-aware methods, e.g., SWA [25] or SAM [26], are only effective methods to both in-domain and out-of-domain generalization.
sections.heading: 2 A Theoretical Relationship between Flatness and Domain Generalization
sections.text: Let D := {Di}Ii be a set of training domains, where Di is a distribution over input space X , and I is the total number of domains. From each domain, we observe n training data points which consist of input x and target label y, (xij , y i j) n j=1 ∼ Di. We also define a set of target domain T := {Ti} T i similarly, where the number of target domains T is usually set to one. For the sake of simplicity, unlike Ben-David et al. [37], we assume that there exists a global labeling function h(x) that generates target label for multiple domains, i.e., yij = h(x i j) for all i and j. Domain generalization (DG) aims to find a model parameter θ ∈ Θ which generalizes well over both multiple training domains D and unseen target domain T . More specifically, let us consider a bounded instance loss function ` : Y × Y → [0, c], such that `(y1, y2) = 0 holds if and only if y1 = y2 where Y is a set of labels. For simplicity, we set c to one in our proofs, but we note that `(·, ·) can be generalized for any bounded loss function. Then, we can define a population loss over multiple domains by ED(θ) = 1I ∑I i=1 Exi∼Di [`(f(xi; θ), yi))], where f(·; θ) is a model parameterized by θ. Formally,
  the goal of DG is to find a model which minimizes both ED(θ) and ET (θ) by only minimizing an empirical risk ÊD(θ) := 1In ∑I i=1 ∑n j=1 `(f(x i; θ), yi)) over training domains D.
  In practice, ERM, i.e., arg minθ ÊD(θ), can have multiple solutions that provide similar values of the training losses but significantly different generalizability on ED(θ) and ET (θ). Unfortunately, the typical optimization methods, such as SGD and Adam [38], often lead sub-optimal generalizability as finding sharp and narrow minima even under the i.i.d. assumption [23–28]. In the DG scenario, the generalization gap between empirical loss and target domain loss becomes even worse due to domain shift. Here, we provide a theoretical interpretation of the relationship between finding a flat minimum and minimizing the domain generalization gap, inspired by previous studies [23–28].
  We consider a robust empirical loss function defined by the worst-case loss within neighborhoods in the parameter space as ÊγD(θ) := max‖∆‖≤γ ÊD(θ + ∆), where ‖ · ‖ denotes the L2 norm and γ is a radius which defines neighborhoods of θ. Intuitively, if γ is sufficiently larger than the “radius” of a sharp optimum θs of ÊD(θ), θs is no longer an optimum of ÊγD(θ) as well as its neighborhoods within the γ-ball. On the other hand, if an optimum θf has larger “radius” than γ, there exists a local optimum within γ-ball – See Figure 1. Hence, solving the robust risk minimization (RRM), i.e., arg minθ ÊγD(θ), will find
  a near solution of a flat optimum showing better generalizability [26, 34]. However, as domain shift worsen the generalization gap by breaking the i.i.d. assumption, it is not trivial that RRM will find an optimum with better DG performance. To answer the question, we first show the generalization bound between ÊγD and ET as follows: Theorem 1. Consider a set of N covers {Θk}Nk=1 such that the parameter space Θ ⊂ ∪Nk Θk where diam(Θ) := supθ,θ′∈Θ ‖θ− θ′‖2, N := ⌈ (diam(Θ)/γ) d ⌉
  and d is dimension of Θ. Let vk be a VC dimension of each Θk. Then, for any θ ∈ Θ, the following bound holds with probability at least 1− δ,
  ET (θ) < ÊγD(θ) + 1
  2I I∑ i=1 Div(Di, T ) + max k∈[1,N ]
  √ vk ln (m/vk) + ln(N/δ)
  m , (1)
  where m = nI is the number of the training samples and Div(Di, T ) := 2 supA |PDi(A)−PT (A)| is a divergence between two distributions.
  Proof can be done similarly as [37] and [34]. In Theorem 1, the test loss ET (θ) is bounded by three terms: (1) the robust empirical loss ÊγD(θ), (2) the discrepancy between training distribution and test distribution, i.e., the quantity of domain shift, and (3) a confidence bound related to the radius γ and the number of the training samples m. Our theorem is similar to Ben-David et al. [37], while our theorem does not have the term related to the difference in labeling functions across the domains. It is because we simply assume there is no difference between labeling functions for each domain for simplicity. If one assumes a different labeling function, the dissimilarity term can be derived easily because it is independent and compatible with our main proof. More details of Theorem 1, including proof and discussions on the confidence bound, are in Appendix C.1 and C.2.
  From Theorem 1, one can conjure that minimizing the robust empirical loss is directly related to the generalization performances on the target distribution. We show that the domain generalization gap on the target domain T by the optimal solution of RRM, θ̂γ , is upper bounded as follows: Theorem 2. Let θ̂γ denote the optimal solution of the RRM, i.e., θ̂γ := arg minθ ÊγD(θ), and let v be a VC dimension of the parameter space Θ. Then, the gap between the optimal test loss, minθ′ ET (θ′), and the test loss of θ̂γ , ET (θ̂γ), has the following bound with probability at least 1− δ.
  ET (θ̂γ)−min θ′ ET (θ′) ≤ ÊγD(θ̂ γ)−min θ′′ ÊD(θ′′) +
  1
  I I∑ i=1 Div(Di, T )
  + max k∈[1,N ]
  √ vk ln (m/vk) + ln (2N/δ)
  m +
  √ v ln (m/v) + ln (2/δ)
  m
  (2)
  Proof is in Appendix C.3. It implies that if we find the optimal solution of the RRM (i.e., θ̂γ), then the generalization gap in the test domain (i.e., ET (θ̂γ) − minθ′ ET (θ′)) is upper bounded by the gap between the RRM and ERM (i.e., ÊγD(θ̂γ)−minθ′′ ÊD(θ′′)). Other terms in Theorem 2 are the discrepancy between the train domains D and the target domain T , and the confidence bounds caused by sample means. We remark that if we choose a proper γ, the optimal solution of the RRM will find a point near a flat optimum of ERM as shown in Figure 1. Hence, Theorem 2 and the intuition from Figure 1 imply that seeking a flat minimum of ERM will lead to a better domain generalization gap.
sections.heading: 3 SWAD: Domain Generalization by Seeking Flat Minima
sections.text: We have shown that flat minima will bring a better domain generalization. In this section, we propose Stochastic Weight Averaging Densely (SWAD) algorithm, and provide empirical quantitative and qualitative analyses on SWAD and flatness to understand why SWAD works better than ERM.
sections.heading: 3.1 A baseline method: stochastic weight averaging
sections.text: Since the importance of flatness in loss landscapes has emerged [23–28], several methods have been proposed to find flat minima [25, 26, 39]. We select stochastic weight averaging (SWA) [25] as a baseline, which finds flat minima by a weight ensemble approach. More specifically, SWA updates a pretrained model (namely, a model trained with sufficiently enough training epochs, K0) with a cyclical [40] or high constant learning rate scheduling. SWA gathers model parameters for every K epochs during the update and averages them for the model ensemble. SWA finds an ensembled solution of different local optima found by a sufficiently large learning rate to escape a local minimum. Izmailov et al. [25] empirically showed that SWA finds flatter minima than ERM. We also considered sharpness-aware minimization (SAM) [26], which is another popular flatness-aware solver, but SWA finds flatter minima than SAM (See Figure 3). We illustrate an overview of SWA in Figure 2a.
sections.heading: 3.2 Dense and overfit-aware stochastic weight sampling strategy
sections.text: Despite its advantages, directly applying SWA to DG task has two problems. First, SWA averages a few weights (usually less than ten) by sampling weights for every K epochs, results in an inaccurate approximation of flat minima on a high-dimensional parameter space (e.g., 23M for ResNet-50 [41]). Furthermore, a common DG benchmark protocol uses relatively small training epochs (e.g., Gulrajani and Lopez-Paz [22] trained with less than two epochs for DomainNet benchmark), resulting in insufficient stochastic weights for SWA. From this motivation, we propose a “dense” sampling strategy for gathering sufficiently enough stochastic weights.
  In addition, widely used DG datasets, such as PACS (≈ 10K images, 7 classes) and VLCS (≈ 11K images, 5 classes), are relatively smaller than large-scale datasets, such as ImageNet [42] (≈ 1.2M images, 1K classes). In this case, we observe that a simple ERM approach is rapidly reached to a local optimum only within a few epochs, and easily suffers from the overfitting issue, i.e., the validation loss is increased after a few training epochs. It implies that directly applying the vanilla SWA will suffer from the overfitting issue by averaging sub-optimal solutions (i.e., overfitted parameters). Hence, we need an “overfit-aware” sampling scheduling to omit the sub-optimal solutions for SWA.
  The main idea of Stochastic Weight Averaging Densely (SWAD) is a dense and overfit-aware stochastic weight gathering strategy. First, instead of collecting weights for every K epochs, SWAD collects weights for every iteration. This dense sampling strategy easily collects sufficiently many weights than the sparse one. We also employ overfit-aware sampling scheduling by considering traces of the validation loss. Instead of sampling weights from K0 pretraining epochs to the final epoch, we search the start iteration (when the validation loss achieves a local optimum for the first time) and the end iteration (when the validation loss is no longer decreased, but keep increasing). More specifically, we introduce three parameters: an optimum patient parameter Ns, an overfitting patient parameter Ne, and the tolerance rate r for searching the start iteration ts and the end iteration te. First, we search ts which satisfies mini∈[0,...,Ns−1] E (ts+i) val = E (ts) val , where E (i) val denotes the validation loss at iteration i. Simply, ts is the first iteration where the loss value is no longer decreased during Ns iterations. Then, we find te satisfying mini∈[0,1,...,Ne−1] E (te+i) val > rE (ts) val . In other words, te is the first iteration where the validation loss values exceed the tolerance r during Ne iterations.
  We illustrate the overview of SWAD and the comparison of SWAD to SWA in Figure 2. Detailed pseudo code is provided in Appendix B.4. We compare SWAD with other possible SWA strategies in §4.3 and show that our design choice works better for DG tasks.
sections.heading: 3.3 Empirical analysis of SWAD and flatness
sections.text: Here, we analyze solutions found by SWAD in terms of flatness. We first verify that the SWAD solution is flatter than those of ERM, SWA, and SAM. Our loss surface visualization shows that the SWAD solution is located on the center of the flat region, while ERM finds a boundary solution. Finally, we show that the sharp boundary solutions by ERM are not generalized well, resulting in sensitivity to the model selection. All following empirical analyses are conducted on PACS dataset, validating by all four domains (art painting, cartoon, photo, and sketch).
  Local flatness anaylsis. To begin with, we quantify the local flatness of a model parameter θ by assuming that flat minima will have smaller changes of loss value within its neighborhoods than sharp minima. For the given model parameter θ, we compute the expected loss value changes between θ and parameters on the sphere surrounding θ with radius γ, i.e., Fγ(θ) = E‖θ′‖=‖θ‖+γ [E(θ′)− E(θ)]. In
  practice, Fγ(θ) is approximated by Monte-Carlo sampling with 100 samples. Note that the proposed local flatness Fγ(θ) is computationally efficient than measuring curvature using the Hessian-based quantities. Also, Fγ(θ) has an unbiased finite sample estimator, while the worst-case loss value, i.e., max‖θ′‖=‖θ‖+γ [E(θ′)− E(θ)] has no unbiased finite sample estimator.
  In Figure 3, we compare Fγ(θ) of ERM, SAM, SWA with cyclic learning rate, SWA with constant learning rate, and SWAD by varying radius γ. SAM and SWA find the solutions with lower local flatness than ERM on average. SWAD finds the most flat minimum in every experiment.
  Loss surface visualization. We visualize the loss landscapes by choosing three model weights on the optimization trajectory (θ1, θ2, θ3)2, and computing the loss values by linear combinations of θ1, θ2, θ33 as [25]. More details are in Appendix B.5. In Figure 4, we observe that for all cases, ERM solutions are located at the boundary of a flat minimum of training loss, resulting in poor generalizability in test domains, that is aligned with our theoretical analysis and empirical flatness analysis. Since ERM solutions are located on the boundary of a flat loss surface, we observe that ERM solutions are very sensitive to model selection. In Figure 5, we illustrate the validation accuracies for each train-test domain combination of PACS by ERM, over training iterations (one epoch is equivalent to 83 iterations). We first observe that ERM rapidly reaches the best accuracy within only a few training epochs, namely less than 6 epochs. Furthermore, the ERM validation accuracies fluctuate a lot, and the final performance is very sensitive to the model selection criterion.
  On the other hand, we observe that SWA solutions are located on the center of the training loss surfaces as well as of the test loss surfaces (Figure 4). Also, our overfit-aware stochastic weight gathering strategy (denoted as the vertical dot lines in Figure 5) prevents the ensembled weight from overfitting and makes SWAD model selection-free.
  2We choose weights at iteration 2500, 3500, 4500 during the training. 3Each point is defined by two axes u and v computed by u = θ2 − θ1 and v = (θ3−θ1)−〈θ3−θ1,θ2−θ1〉‖θ2−θ1‖2·(θ2−θ1) .
sections.heading: 4 Experiments
sections.heading: 4.1 Evaluation protocols
sections.text: Dataset and optimization protocol. Following Gulrajani and Lopez-Paz [22], we exhaustively evaluate our method and comparison methods on various benchmarks: PACS [7] (9,991 images, 7 classes, and 4 domains), VLCS [43] (10,729 images, 5 classes, and 4 domains), OfficeHome [44] (15,588 images, 65 classes, and 4 domains), TerraIncognita [45] (24,788 images, 10 classes, and 4 domains), and DomainNet [46] (586,575 images, 345 classes, and 6 domains).
  For a fair comparison, we follow training and evaluation protocol by Gulrajani and Lopez-Paz [22], including the dataset splits, hyperparameter (HP) search and model selection (while SWAD does not need it) on the validation set, and optimizer HP, except the HP search space and the number of iterations for DomainNet. We use a reduced HP search space to reduce the computational costs. We also tripled the number of iterations for DomainNet from 5,000 to 15,000 because we observe that 5,000 is not sufficient to convergence. We re-evaluate ERM with 15,000 iterations, and observe 3.1pp average performance improvement (40.9%→ 44.0%) in DomainNet. For training, we choose a domain as the target domain and use the remaining domains as the training domain where 20% samples are used for validation and model selection. ImageNet [42] trained ResNet-50 [41] is employed as the initial weight, and optimized by Adam [38] optimizer with a learning rate of 5e-5. We construct a mini-batch containing all domains where each domain has 32 images. We set SWAD HPs Ns to 3, Ne to 6, and r to 1.2 for VLCS and 1.3 for the others by HP search on the validation sets. Additional implementation details, such as other HPs, are given in Appendix B.
  Evaluation metrics. We report out-of-domain accuracies for each domain and their average, i.e., a model is trained and validated on training domains and evaluated on the unseen target domain. Each out-of-domain performance is an average of three different runs with different train-validation splits.
  4.2 Main results
  Comparison with domain generalization methods. We report the full out-of-domain performances on five DG benchmarks in Table 2. The full tables including outof-domain accuracies for each domain are in Appendix E. In all experiments, our SWAD achieves significant performance gain against ERM as well as the previous best results: +2.6pp in PACS, +0.3pp in VLCS, +1.4pp in TerraIncognita, +1.9pp in OfficeHome, and +2.9pp in DomainNet comparing to the previous best results. We observe that SWAD provides two practical advantages comparing to previous methods. First, SWAD does not need any modification on training objectives or model architecture, i.e., it is universally applicable to any other methods. As an example, we show that SWAD actually improves the performances of other DG methods, such as CORAL [31] in Table 4. Moreover, as we discussed before, SWAD is free to the model selection,
  resulting in stable performances (i.e., small standard errors) on various benchmarks. Note that we only compare results with ResNet-50 backbone for a fair comparison. We describe the implementation details of each comparison method and the hyperparameter search protocol in Appendix B.
  Comparison with conventional generalization methods. We also compare SWAD with other conventional generalization methods to show that the remarkable domain generalization gaps by SWAD is not achieved by better generalization, but by seeking flat minima. The comparison methods include flatness-aware optimization methods, such as SAM [26], ensemble methods, such as EMA [56], data augmentation methods, such as Mixup [35] and CutMix [36], and consistency regularization methods, such as VAT [57] and Π-model [58]. We also split in-domain datasets into training (60%), validation (20%), and test (20%) splits, while no in-domain test set used for Table 2. Every experiment is repeated three times.
  The results are shown in Table 3. We observe that all conventional methods helps in-domain generalization, i.e., performing better than ERM on in-domain test set. However, their out-of-domain performances are similar to or even worse than ERM. For example, CutMix and Π-model improve in-domain performances by 1.0pp and 0.2pp but degrade out-of-domain performances by 1.5pp and 1.8pp. SAM, another method for seeking flat minima, slightly increases both in-domain and out-of-domain performances but the out-of-domain performance is not statistically significant. We will discuss performances of SAM in other benchmarks later. In contrast, the vanilla SWA and our SWAD significantly improve both in-domain and out-of-domain performances. SWAD improves the performances by SWA with statistically significantly gaps: 1.2pp on the out-of-domain and 0.6pp on the in-domain. Further comparison between SWA and SWAD is provided in §4.3.
  Combinations with other methods. Since SWAD does not require any modification on training procedures and model architectures, SWAD is universally applicable to any other methods. Here, we combine SWAD with ERM, CORAL [31], and SAM [26]. Results are shown in Table 4. Both CORAL and SAM solely show better performances than ERM with +1.2pp average out-of-domain accuracy gap. Note that SAM is not a DG method but a sharpness-aware optimization method to find flat minima. It supports our theoretical motivation: DG can be achieved by seeking flat minima.
  By applying SWAD on the baselines, the performances are consistently improved by 3.6pp on ERM, 2.8pp on CORAL, and 1.0pp on SAM. Interestingly, CORAL + SWAD show the best performances with both incorporating different advantages of utilizing domain labels and seeking flat minima. We also observe that SAM + SWAD shows worse performance than ERM + SWAD, while SAM performs better than ERM. We conjecture that it is because the objective control by SAM restricts the model parameter diversity durinig training, reducing the diversity for SWA ensemble. However, applying SWAD on SAM still leads to better performances than the sole SAM. The results demonstrate that the application of SWAD on other baselines is a simple yet effective method for DG.
sections.heading: 4.4 Exploring the other applications: ImageNet robustness
sections.heading: 4.3 Ablation study
sections.text: Since SWAD does not rely on domain labels, it can be applied to other robustness tasks not containing domain labels. Table 6 show the generalizability of SWAD on ImageNet [42] and its shifted benchmarks, namely, ImageNet-C [59], ImageNet-R [60], and background challenge (BGC) [61]. SWAD consistently improves robustness performances against the ERM baseline and the SWA baseline. These results support that our method is robustly and widely applicable to improve both in-domain and out-of-domain generalizability. The detailed setup is provided in Appendix B.6.
sections.heading: 5 Discussion and Limitations
sections.text: Despite many benefits from SWAD, such as the significant performance improvements, model selection-free property, working plug-and-play manner for various methods, there are some potential limitations. Here, we discuss the limitations of SWAD for further improvements.
  Confidence error in Theorem 1. While the confidence error in Theorem 1 tells the effect of γ on generalization error bound, there exists a limitation in that the confidence error term shows improper behavior with respect to γ if γ is close to zero. The behavior we expect is that the confidence error of RRM converges to the confidence error of ERM as γ decreases to zero, however, the current theorem does not show such tendency since the confidence bound diverges to infinity when γ goes to zero. However, we would like to note that this limitation is not a drawback of RRM, but it is caused by the looseness of the union bound which is a mathematical technique used to derive the confidence error of RRM. Our RRM formulation has a similarity to previous works [26, 34] and we note that the counter-intuitive behavior of the confidence bound and γ also appears in Foret et al. [26].
  SWAD is not a perfect flatness-aware optimization method. Note that SWAD is not a perfect and theoretically guaranteed solver for flat minima, but a heuristic approximation with empirical benefits. However, even if a better flatness-aware optimization method is proposed, our theoretical contribution still holds: showing the relationship between flat minima and DG.
  SWAD does not strongly utilize domain-specific information. In Theorem 2, the domain generalization gap is bounded by three factors: flat minima, domain discrepancy, and confidence bound. Most of the existing approaches focus on domain discrepancy, reducing the difference between the source domains and the target domain by domain invariant learning [8–12]. SWAD focuses on the first factor, the flat minima. While the domain labels are used to construct a mini-batch, SWAD does not strongly utilize domain-specific information. It implies that if one can consider both flatness and domain discrepancy, better domain generalization can be achievable. Table 4 gives us a clue: the combination of CORAL (utilizing domain-specific information) and SWAD (seeking flat minima) shows the best performance among all comparison methods. As a future research direction, we encourage studying a method that can achieve both flat optima and small domain discrepancy.
sections.heading: 6 Concluding Remarks
sections.text: In this paper, we theoretically and empirically demonstrate that domain generalization (DG) is achievable by seeking flat minima. We propose SWAD that captures flatter minima than the vanilla SWA does. The extensive experiments on five DG benchmarks show superior performances of SWAD compared with existing DG methods. In addition, combinations of SWAD and existing DG methods even show better performances than the vanilla SWAD. We theoretically and empirically observe that seeking flat minima can achieve better generalizability to both in-domain and out-of-domain, while strong in-domain generalization methods without consideration of flatness, e.g., Mixup or CutMix, cannot guarantee to achieve out-of-domain generalizability in both theory and practice. This study first brings the concept of flatness into DG tasks, and shows strong empirical performances not only in DG but also in ImageNet benchmarks. We hope that this study promotes a new research direction of seeking flat minima for domain generalization and other robustness tasks.
  Acknowledgments and Disclosure of Funding
  NAVER Smart Machine Learning (NSML) [62] and Kakao Brain Cloud platform have been used in experiments. This work was supported by IITP grant funded by the Korea government (MSIT) (No. 2021-0-01341, AI Graduate School Program, CAU).
title: SWAD: Domain Generalization by Seeking Flat Minima