[
  {
    "path": "CITATION.bib",
    "content": "@misc{tuningplaybookgithub,\n  author = {Varun Godbole and George E. Dahl and Justin Gilmer and Christopher J. Shallue and Zachary Nado},\n  title = {Deep Learning Tuning Playbook},\n  url = {https://github.com/google-research/tuning_playbook},\n  year = {2023},\n  note = \"Version 1\"\n}\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# How to Contribute\n\n-   This is not an officially supported Google product.\n\n-   We'd love to hear your feedback!\n\n    -   If you like the playbook, please leave a star! Or email\n        deep-learning-tuning-playbook \\[at\\] googlegroups.com. Testimonials help\n        us justify creating more resources like this.\n    -   If anything seems incorrect, please file an issue to start a discussion.\n        For questions or other messages where an issue isn't appropriate, please\n        open a new discussion topic on GitHub.\n\n-   As discussed in the preamble, this is a living document. We anticipate\n    making periodic improvements, both small and large. If you’d like to be\n    notified, please watch our repository (see instructions).\n\n-   Please don't file a pull request without first coordinating with the authors\n    via the issue tracking system.\n\n\n## Contributor License Agreement\n\nContributions to this project must be accompanied by a Contributor License\nAgreement (CLA). You (or your employer) retain the copyright to your\ncontribution; this simply gives us permission to use and redistribute your\ncontributions as part of the project. Head over to\n<https://cla.developers.google.com/> to see your current agreements on file or\nto sign a new one.\n\nYou generally only need to submit a CLA once, so if you've already submitted one\n(even if it was for a different project), you probably don't need to do it\nagain.\n\n## Code Reviews\n\nAll submissions, including submissions by project members, require review. We\nuse GitHub pull requests for this purpose. Consult\n[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more\ninformation on using pull requests.\n\n## Community Guidelines\n\nThis project follows\n[Google's Open Source Community Guidelines](https://opensource.google/conduct/)."
  },
  {
    "path": "LICENSE",
    "content": "Creative Commons Attribution 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution 4.0 International Public License (\"Public License\"). To the\nextent this Public License may be interpreted as a contract, You are\ngranted the Licensed Rights in consideration of Your acceptance of\nthese terms and conditions, and the Licensor grants You such rights in\nconsideration of benefits the Licensor receives from making the\nLicensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  j. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  k. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part; and\n\n            b. produce, reproduce, and Share Adapted Material.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public\nlicenses. Notwithstanding, Creative Commons may elect to apply one of\nits public licenses to material it publishes and in those instances\nwill be considered the “Licensor.” The text of the Creative Commons\npublic licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that\nmaterial is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the\npublic licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n"
  },
  {
    "path": "README.md",
    "content": "# Deep Learning Tuning Playbook\n\n*This is not an officially supported Google product.*\n\n**Varun Godbole<sup>&dagger;</sup>, George E. Dahl<sup>&dagger;</sup>, Justin Gilmer<sup>&dagger;</sup>, Christopher J. Shallue<sup>&Dagger;</sup>, Zachary Nado<sup>&dagger;</sup>**\n\n\n&dagger; Google Research, Brain Team\n\n&Dagger; Harvard University\n\n## Table of Contents\n\n-   [Who is this document for?](#who-is-this-document-for)\n-   [Why a tuning playbook?](#why-a-tuning-playbook)\n-   [Guide for starting a new project](#guide-for-starting-a-new-project)\n    -   [Choosing the model architecture](#choosing-the-model-architecture)\n    -   [Choosing the optimizer](#choosing-the-optimizer)\n    -   [Choosing the batch size](#choosing-the-batch-size)\n    -   [Choosing the initial configuration](#choosing-the-initial-configuration)\n-   [A scientific approach to improving model performance](#a-scientific-approach-to-improving-model-performance)\n    -   [The incremental tuning strategy](#the-incremental-tuning-strategy)\n    -   [Exploration vs exploitation](#exploration-vs-exploitation)\n    -   [Choosing the goal for the next round of experiments](#choosing-the-goal-for-the-next-round-of-experiments)\n    -   [Designing the next round of experiments](#Designing-the-next-round-of-experiments)\n    -   [Determining whether to adopt a training pipeline change or\n        hyperparameter\n        configuration](#Determining-whether-to-adopt-a-training-pipeline-change-or-hyperparameter-configuration)\n    -   [After exploration concludes](#After-exploration-concludes)\n-   [Determining the number of steps for each training run](#Determining-the-number-of-steps-for-each-training-run)\n    -   [Deciding how long to train when training is not compute-bound](#Deciding-how-long-to-train-when-training-is-not-compute-bound)\n    -   [Deciding how long to train when training is compute-bound](#Deciding-how-long-to-train-when-training-is-compute-bound)\n-   [Additional guidance for the training pipeline](#Additional-guidance-for-the-training-pipeline)\n    -   [Optimizing the input pipeline](#Optimizing-the-input-pipeline)\n    -   [Evaluating model performance](#evaluating-model-performance)\n    -   [Saving checkpoints and retrospectively selecting the best checkpoint](#Saving-checkpoints-and-retrospectively-selecting-the-best-checkpoint)\n    -   [Setting up experiment tracking](#Setting-up-experiment-tracking)\n    -   [Batch normalization implementation details](#Batch-normalization-implementation-details)\n    -   [Considerations for multi-host pipelines](#Considerations-for-multi-host-pipelines)\n-   [FAQs](#faqs)\n-   [Acknowledgments](#acknowledgments)\n-   [Citing](#citing)\n-   [Contributing](#contributing)\n\n## Who is this document for?\n\nThis document is for engineers and researchers (both individuals and teams)\ninterested in **maximizing the performance of deep learning models**. We assume\nbasic knowledge of machine learning and deep learning concepts.\n\nOur emphasis is on the **process of hyperparameter tuning**. We touch on other\naspects of deep learning training, such as pipeline implementation and\noptimization, but our treatment of those aspects is not intended to be complete.\n\nWe assume the machine learning problem is a supervised learning problem or\nsomething that looks a lot like one (e.g. self-supervised). That said, some of\nthe prescriptions in this document may also apply to other types of problems.\n\n## Why a tuning playbook?\n\nCurrently, there is an astonishing amount of toil and guesswork involved in\nactually getting deep neural networks to work well in practice. Even worse, the\nactual recipes people use to get good results with deep learning are rarely\ndocumented. Papers gloss over the process that led to their final results in\norder to present a cleaner story, and machine learning engineers working on\ncommercial problems rarely have time to take a step back and generalize their\nprocess. Textbooks tend to eschew practical guidance and prioritize fundamental\nprinciples, even if their authors have the necessary experience in applied work\nto provide useful advice. When preparing to create this document, we couldn't\nfind any comprehensive attempt to actually explain *how to get good results with\ndeep learning*. Instead, we found snippets of advice in blog posts and on social\nmedia, tricks peeking out of the appendix of research papers, occasional case\nstudies about one particular project or pipeline, and a lot of confusion. There\nis a vast gulf between the results achieved by deep learning experts and less\nskilled practitioners using superficially similar methods. At the same time,\nthese very experts readily admit some of what they do might not be\nwell-justified. As deep learning matures and has a larger impact on the world,\nthe community needs more resources covering useful recipes, including all the\npractical details that can be so critical for obtaining good results.\n\nWe are a team of five researchers and engineers who have worked in deep learning\nfor many years, some of us since as early as 2006. We have applied deep learning\nto problems in everything from speech recognition to astronomy, and learned a\nlot along the way. This document grew out of our own experience training neural\nnetworks, teaching new machine learning engineers, and advising our colleagues\non the practice of deep learning. Although it has been gratifying to see deep\nlearning go from a machine learning approach practiced by a handful of academic\nlabs to a technology powering products used by billions of people, deep learning\nis still in its infancy as an engineering discipline and we hope this document\nencourages others to help systematize the field's experimental protocols.\n\nThis document came about as we tried to crystalize our own approach to deep\nlearning and thus it represents the opinions of the authors at the time of\nwriting, not any sort of objective truth. Our own struggles with hyperparameter\ntuning made it a particular focus of our guidance, but we also cover other\nimportant issues we have encountered in our work (or seen go wrong). Our\nintention is for this work to be a living document that grows and evolves as our\nbeliefs change. For example, the material on debugging and mitigating training\nfailures would not have been possible for us to write two years ago since it is\nbased on recent results and ongoing investigations. Inevitably, some of our\nadvice will need to be updated to account for new results and improved\nworkflows. We do not know the *optimal* deep learning recipe, but until the\ncommunity starts writing down and debating different procedures, we cannot hope\nto find it. To that end, we would encourage readers who find issues with our\nadvice to produce alternative recommendations, along with convincing evidence,\nso we can update the playbook. We would also love to see alternative guides and\nplaybooks that might have different recommendations so we can work towards best\npractices as a community. Finally, any sections marked with a 🤖 emoji are places\nwe would like to do more research. Only after trying to write this playbook did\nit become completely clear how many interesting and neglected research questions\ncan be found in the deep learning practitioner's workflow.\n\n## Guide for starting a new project\n\nMany of the decisions we make over the course of tuning can be made once at the\nbeginning of a project and only occasionally revisited when circumstances\nchange.\n\nOur guidance below makes the following assumptions:\n\n-   Enough of the essential work of problem formulation, data cleaning, etc. has\n    already been done that spending time on the model architecture and training\n    configuration makes sense.\n-   There is already a pipeline set up that does training and evaluation, and it\n    is easy to execute training and prediction jobs for various models of\n    interest.\n-   The appropriate metrics have been selected and implemented. These should be\n    as representative as possible of what would be measured in the deployed\n    environment.\n\n### Choosing the model architecture\n\n***Summary:*** *When starting a new project, try to reuse a model that already\nworks.*\n\n-   Choose a well established, commonly used model architecture to get working\n    first. It is always possible to build a custom model later.\n-   Model architectures typically have various hyperparameters that determine\n    the model's size and other details (e.g. number of layers, layer width, type\n    of activation function).\n    -   Thus, choosing the architecture really means choosing a family of\n        different models (one for each setting of the model hyperparameters).\n    -   We will consider the problem of choosing the model hyperparameters in\n        [Choosing the initial configuration](#choosing-the-initial-configuration)\n        and\n        [A scientific approach to improving model performance](#a-scientific-approach-to-improving-model-performance).\n-   When possible, try to find a paper that tackles something as close as\n    possible to the problem at hand and reproduce that model as a starting\n    point.\n\n### Choosing the optimizer\n\n***Summary:*** *Start with the most popular optimizer for the type of problem at\nhand.*\n\n-   No optimizer is the \"best\" across all types of machine learning problems and\n    model architectures. Even just\n    [comparing the performance of optimizers is a difficult task](https://arxiv.org/abs/1910.05446).\n    🤖\n-   We recommend sticking with well-established, popular optimizers, especially\n    when starting a new project.\n    -   Ideally, choose the most popular optimizer used for the same type of\n        problem.\n-   Be prepared to give attention to **\\*****all****\\*** hyperparameters of the\n    chosen optimizer.\n    -   Optimizers with more hyperparameters may require more tuning effort to\n        find the best configuration.\n    -   This is particularly relevant in the beginning stages of a project when\n        we are trying to find the best values of various other hyperparameters\n        (e.g. architecture hyperparameters) while treating optimizer\n        hyperparameters as\n        [nuisance parameters](#identifying-scientific-nuisance-and-fixed-hyperparameters).\n    -   It may be preferable to start with a simpler optimizer (e.g. SGD with\n        fixed momentum or Adam with fixed $\\epsilon$, $\\beta_{1}$, and\n        $\\beta_{2}$) in the initial stages of the project and switch to a more\n        general optimizer later.\n-   Well-established optimizers that we like include (but are not limited to):\n    -   [SGD with momentum](#what-are-the-update-rules-for-all-the-popular-optimization-algorithms)\n        (we like the Nesterov variant)\n    -   [Adam and NAdam](#what-are-the-update-rules-for-all-the-popular-optimization-algorithms),\n        which are more general than SGD with momentum. Note that Adam has 4\n        tunable hyperparameters\n        [and they can all matter](https://arxiv.org/abs/1910.05446)!\n        -   See\n            [How should Adam's hyperparameters be tuned?](#how-should-adams-hyperparameters-be-tuned)\n\n### Choosing the batch size\n\n***Summary:*** *The batch size governs the training speed and shouldn't be used\nto directly tune the validation set performance. Often, the ideal batch size\nwill be the largest batch size supported by the available hardware.*\n\n-   The batch size is a key factor in determining the *training time* and\n    *computing resource consumption*.\n-   Increasing the batch size will often reduce the training time. This can be\n    highly beneficial because it, e.g.:\n    -   Allows hyperparameters to be tuned more thoroughly within a fixed time\n        interval, potentially resulting in a better final model.\n    -   Reduces the latency of the development cycle, allowing new ideas to be\n        tested more frequently.\n-   Increasing the batch size may either decrease, increase, or not change the\n    resource consumption.\n-   The batch size should *not be* treated as a tunable hyperparameter for\n    validation set performance.\n    -   As long as all hyperparameters are well-tuned (especially the learning\n        rate and regularization hyperparameters) and the number of training\n        steps is sufficient, the same final performance should be attainable\n        using any batch size (see\n        [Shallue et al. 2018](https://arxiv.org/abs/1811.03600)).\n    -   Please see [Why shouldn't the batch size be tuned to directly improve\n        validation set\n        performance?](#why-shouldnt-the-batch-size-be-tuned-to-directly-improve-validation-set-performance)\n\n#### Determining the feasible batch sizes and estimating training throughput\n\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   For a given model and optimizer, there will typically be a range of batch\n    sizes supported by the available hardware. The limiting factor is usually\n    accelerator memory.\n-   Unfortunately, it can be difficult to calculate which batch sizes will fit\n    in memory without running, or at least compiling, the full training program.\n-   The easiest solution is usually to run training jobs at different batch\n    sizes (e.g. increasing powers of 2) for a small number of steps until one of\n    the jobs exceeds the available memory.\n-   For each batch size, we should train for long enough to get a reliable\n    estimate of the *training throughput*\n\n<p align=\"center\">training throughput = (# examples processed per second)</p>\n\n<p align=\"center\">or, equivalently, the <em>time per step</em>.</p>\n\n<p align=\"center\">time per step = (batch size) / (training throughput)</p>\n\n-   When the accelerators aren't yet saturated, if the batch size doubles, the\n    training throughput should also double (or at least nearly double).\n    Equivalently, the time per step should be constant (or at least nearly\n    constant) as the batch size increases.\n-   If this is not the case then the training pipeline has a bottleneck such as\n    I/O or synchronization between compute nodes. This may be worth diagnosing\n    and correcting before proceeding.\n-   If the training throughput increases only up to some maximum batch size,\n    then we should only consider batch sizes up to that maximum batch size, even\n    if a larger batch size is supported by the hardware.\n    -   All benefits of using a larger batch size assume the training throughput\n        increases. If it doesn't, fix the bottleneck or use the smaller batch\n        size.\n    -   **Gradient accumulation** simulates a larger batch size than the\n        hardware can support and therefore does not provide any throughput\n        benefits. It should generally be avoided in applied work.\n-   These steps may need to be repeated every time the model or optimizer is\n    changed (e.g. a different model architecture may allow a larger batch size\n    to fit in memory).\n\n</details>\n\n#### Choosing the batch size to minimize training time\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n<p align=\"center\">Training time = (time per step) x (total number of steps)</p>\n\n-   We can often consider the time per step to be approximately constant for all\n    feasible batch sizes. This is true when there is no overhead from parallel\n    computations and all training bottlenecks have been diagnosed and corrected\n    (see the\n    [previous section](#determining-the-feasible-batch-sizes-and-estimating-training-throughput)\n    for how to identify training bottlenecks). In practice, there is usually at\n    least some overhead from increasing the batch size.\n-   As the batch size increases, the total number of steps needed to reach a\n    fixed performance goal typically decreases (provided all relevant\n    hyperparameters are re-tuned when the batch size is changed;\n    [Shallue et al. 2018](https://arxiv.org/abs/1811.03600)).\n    -   E.g. Doubling the batch size might halve the total number of steps\n        required. This is called **perfect scaling**.\n    -   Perfect scaling holds for all batch sizes up to a critical batch size,\n        beyond which one achieves diminishing returns.\n    -   Eventually, increasing the batch size no longer reduces the number of\n        training steps (but never increases it).\n-   Therefore, the batch size that minimizes training time is usually the\n    largest batch size that still provides a reduction in the number of training\n    steps required.\n    -   This batch size depends on the dataset, model, and optimizer, and it is\n        an open problem how to calculate it other than finding it experimentally\n        for every new problem. 🤖\n    -   When comparing batch sizes, beware the distinction between an example\n        budget/[epoch](https://developers.google.com/machine-learning/glossary#epoch)\n        budget (running all experiments while fixing the number of training\n        example presentations) and a step budget (running all experiments with\n        the number of training steps fixed).\n        -   Comparing batch sizes with an epoch budget only probes the perfect\n            scaling regime, even when larger batch sizes might still provide a\n            meaningful speedup by reducing the number of training steps\n            required.\n    -   Often, the largest batch size supported by the available hardware will\n        be smaller than the critical batch size. Therefore, a good rule of thumb\n        (without running any experiments) is to use the largest batch size\n        possible.\n-   There is no point in using a larger batch size if it ends up increasing the\n    training time.\n\n</details>\n\n#### Choosing the batch size to minimize resource consumption\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n-   There are two types of resource costs associated with increasing the batch\n    size:\n    1.  *Upfront costs*, e.g. purchasing new hardware or rewriting the training\n        pipeline to implement multi-GPU / multi-TPU training.\n    2.  *Usage costs*, e.g. billing against the team's resource budgets, billing\n        from a cloud provider, electricity / maintenance costs.\n-   If there are significant upfront costs to increasing the batch size, it\n    might be better to defer increasing the batch size until the project has\n    matured and it is easier to assess the cost-benefit tradeoff. Implementing\n    multi-host parallel training programs can introduce\n    [bugs](#considerations-for-multi-host-pipelines) and\n    [subtle issues](#batch-normalization-implementation-details) so it is\n    probably better to start off with a simpler pipeline anyway. (On the other\n    hand, a large speedup in training time might be very beneficial early in the\n    process when a lot of tuning experiments are needed).\n-   We refer to the total usage cost (which may include multiple different kinds\n    of costs) as the \"resource consumption\". We can break down the resource\n    consumption into the following components:\n\n<p align=\"center\">Resource consumption = (resource consumption per step) x (total number of steps)</p>\n\n-   Increasing the batch size usually allows us to\n    [reduce the total number of steps](#choosing-the-batch-size-to-minimize-training-time).\n    Whether the resource consumption increases or decreases will depend on how\n    the consumption per step changes.\n    -   Increasing the batch size might *decrease* the resource consumption. For\n        example, if each step with the larger batch size can be run on the same\n        hardware as the smaller batch size (with only a small increase in time\n        per step), then any increase in the resource consumption per step might\n        be outweighed by the decrease in the number of steps.\n    -   Increasing the batch size might *not change* the resource consumption.\n        For example, if doubling the batch size halves the number of steps\n        required and doubles the number of GPUs used, the total consumption (in\n        terms of GPU-hours) will not change.\n    -   Increasing the batch size might *increase* the resource consumption. For\n        example, if increasing the batch size requires upgraded hardware, the\n        increase in consumption per step might outweigh the reduction in the\n        number of steps.\n\n</details>\n\n#### Changing the batch size requires re-tuning most hyperparameters\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n-   The optimal values of most hyperparameters are sensitive to the batch size.\n    Therefore, changing the batch size typically requires starting the tuning\n    process all over again.\n-   The hyperparameters that interact most strongly with the batch size, and therefore are most important to tune separately for each batch size, are the optimizer hyperparameters (e.g. learning rate, momentum) and the regularization hyperparameters.\n-   Keep this in mind when choosing the batch size at the start of a project. If\n    you need to switch to a different batch size later on, it might be\n    difficult, time consuming, and expensive to re-tune everything for the new\n    batch size.\n\n</details>\n\n#### How batch norm interacts with the batch size\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n-   Batch norm is complicated and, in general, should use a different batch size\n    than the gradient computation to compute statistics. See the\n    [batch norm section](#batch-normalization-implementation-details) for a\n    detailed discussion.\n\n</details>\n\n### Choosing the initial configuration\n\n-   Before beginning hyperparameter tuning we must determine the starting point.\n    This includes specifying (1) the model configuration (e.g. number of\n    layers), (2) the optimizer hyperparameters (e.g. learning rate), and (3) the\n    number of training steps.\n-   Determining this initial configuration will require some manually configured\n    training runs and trial-and-error.\n-   Our guiding principle is to find a simple, relatively fast, relatively\n    low-resource-consumption configuration that obtains a \"reasonable\" result.\n    -   \"Simple\" means avoiding bells and whistles wherever possible; these can\n        always be added later. Even if bells and whistles prove helpful down the\n        road, adding them in the initial configuration risks wasting time tuning\n        unhelpful features and/or baking in unnecessary complications.\n        -   For example, start with a constant learning rate before adding fancy\n            decay schedules.\n    -   Choosing an initial configuration that is fast and consumes minimal\n        resources will make hyperparameter tuning much more efficient.\n        -   For example, start with a smaller model.\n    -   \"Reasonable\" performance depends on the problem, but at minimum means\n        that the trained model performs much better than random chance on the\n        validation set (although it might be bad enough to not be worth\n        deploying).\n-   Choosing the number of training steps involves balancing the following\n    tension:\n    -   On the one hand, training for more steps can improve performance and\n        makes hyperparameter tuning easier (see\n        [Shallue et al. 2018](https://arxiv.org/abs/1811.03600)).\n    -   On the other hand, training for fewer steps means that each training run\n        is faster and uses fewer resources, boosting tuning efficiency by\n        reducing the time between cycles and allowing more experiments to be run\n        in parallel. Moreover, if an unnecessarily large step budget is chosen\n        initially, it might be hard to change it down the road, e.g. once the\n        learning rate schedule is tuned for that number of steps.\n\n## A scientific approach to improving model performance\n\nFor the purposes of this document, the ultimate goal of machine learning\ndevelopment is to maximize the utility of the deployed model. Even though many\naspects of the development process differ between applications (e.g. length of\ntime, available computing resources, type of model), we can typically use the\nsame basic steps and principles on any problem.\n\nOur guidance below makes the following assumptions:\n\n-   There is already a fully-running training pipeline along with a\n    configuration that obtains a reasonable result.\n-   There are enough computational resources available to conduct meaningful\n    tuning experiments and run at least several training jobs in parallel.\n\n### The incremental tuning strategy\n\n***Summary:*** *Start with a simple configuration and incrementally make\nimprovements while building up insight into the problem. Make sure that any\nimprovement is based on strong evidence to avoid adding unnecessary complexity.*\n\n-   Our ultimate goal is to find a configuration that maximizes the performance\n    of our model.\n    -   In some cases, our goal will be to maximize how much we can improve the\n        model by a fixed deadline (e.g. submitting to a competition).\n    -   In other cases, we want to keep improving the model indefinitely (e.g.\n        continually improving a model used in production).\n-   In principle, we could maximize performance by using an algorithm to\n    automatically search the entire space of possible configurations, but this\n    is not a practical option.\n    -   The space of possible configurations is extremely large and there are\n        not yet any algorithms sophisticated enough to efficiently search this\n        space without human guidance.\n-   Most automated search algorithms rely on a hand-designed *search space* that\n    defines the set of configurations to search in, and these search spaces can\n    matter quite a bit.\n-   The most effective way to maximize performance is to start with a simple\n    configuration and incrementally add features and make improvements while\n    building up insight into the problem.\n    -   We use automated search algorithms in each round of tuning and\n        continually update our search spaces as our understanding grows.\n-   As we explore, we will naturally find better and better configurations and\n    therefore our \"best\" model will continually improve.\n    -   We call it a *launch* when we update our best configuration (which may\n        or may not correspond to an actual launch of a production model).\n    -   For each launch, we must make sure that the change is based on strong\n        evidence – not just random chance based on a lucky configuration – so\n        that we don't add unnecessary complexity to the training pipeline.\n\nAt a high level, our incremental tuning strategy involves repeating the\nfollowing four steps:\n\n1.  Identify an appropriately-scoped goal for the next round of experiments.\n2.  Design and run a set of experiments that makes progress towards this goal.\n3.  Learn what we can from the results.\n4.  Consider whether to launch the new best configuration.\n\nThe remainder of this section will consider this strategy in much greater\ndetail.\n\n### Exploration vs exploitation\n\n***Summary:*** *Most of the time, our primary goal is to gain insight into the\nproblem.*\n\n-   Although one might think we would spend most of our time trying to maximize\n    performance on the validation set, in practice we spend the majority of our\n    time trying to gain insight into the problem, and comparatively little time\n    greedily focused on the validation error.\n    -   In other words, we spend most of our time on \"exploration\" and only a\n        small amount on \"exploitation\".\n-   In the long run, understanding the problem is critical if we want to\n    maximize our final performance. Prioritizing insight over short term gains\n    can help us:\n    -   Avoid launching unnecessary changes that happened to be present in\n        well-performing runs merely through historical accident.\n    -   Identify which hyperparameters the validation error is most sensitive\n        to, which hyperparameters interact the most and therefore need to be\n        re-tuned together, and which hyperparameters are relatively insensitive\n        to other changes and can therefore be fixed in future experiments.\n    -   Suggest potential new features to try, such as new regularizers if\n        overfitting is an issue.\n    -   Identify features that don't help and therefore can be removed, reducing\n        the complexity of future experiments.\n    -   Recognize when improvements from hyperparameter tuning have likely\n        saturated.\n    -   Narrow our search spaces around the optimal value to improve tuning\n        efficiency.\n-   When we are eventually ready to be greedy, we can focus purely on the\n    validation error even if the experiments aren't maximally informative about\n    the structure of the tuning problem.\n\n### Choosing the goal for the next round of experiments\n\n***Summary:*** *Each round of experiments should have a clear goal and be\nsufficiently narrow in scope that the experiments can actually make progress\ntowards the goal.*\n\n-   Each round of experiments should have a clear goal and be sufficiently\n    narrow in scope that the experiments can actually make progress towards the\n    goal: if we try to add multiple features or answer multiple questions at\n    once, we may not be able to disentangle the separate effects on the results.\n-   Example goals include:\n    -   Try a potential improvement to the pipeline (e.g. a new regularizer,\n        preprocessing choice, etc.).\n    -   Understand the impact of a particular model hyperparameter (e.g. the\n        activation function)\n    -   Greedily minimize validation error.\n\n### Designing the next round of experiments\n\n***Summary:*** *Identify which hyperparameters are scientific, nuisance, and\nfixed hyperparameters for the experimental goal. Create a sequence of studies to\ncompare different values of the scientific hyperparameters while optimizing over\nthe nuisance hyperparameters. Choose the search space of nuisance\nhyperparameters to balance resource costs with scientific value.*\n\n#### Identifying scientific, nuisance, and fixed hyperparameters\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   For a given goal, all hyperparameters will be either **scientific\n    hyperparameters**, **nuisance hyperparameters**, or **fixed\n    hyperparameters**.\n    -   Scientific hyperparameters are those whose effect on the model's\n        performance we're trying to measure.\n    -   Nuisance hyperparameters are those that need to be optimized over in\n        order to fairly compare different values of the scientific\n        hyperparameters. This is similar to the statistical concept of\n        [nuisance parameters](https://en.wikipedia.org/wiki/Nuisance_parameter).\n    -   Fixed hyperparameters will have their values fixed in the current round\n        of experiments. These are hyperparameters whose values do not need to\n        (or we do not want them to) change when comparing different values of\n        the scientific hyperparameters.\n        -   By fixing certain hyperparameters for a set of experiments, we must\n            accept that conclusions derived from the experiments might not be\n            valid for other settings of the fixed hyperparameters. In other\n            words, fixed hyperparameters create caveats for any conclusions we\n            draw from the experiments.\n-   For example, if our goal is to \"determine whether a model with more hidden\n    layers will reduce validation error\", then the number of hidden layers is a\n    scientific hyperparameter.\n    -   The learning rate is a nuisance hyperparameter because we can only\n        fairly compare models with different numbers of hidden layers if the\n        learning rate is tuned separately for each number of layers (the optimal\n        learning rate generally depends on the model architecture).\n    -   The activation function could be a fixed hyperparameter if we have\n        determined in prior experiments that the best choice of activation\n        function is not sensitive to model depth, or if we are willing to limit\n        our conclusions about the number of hidden layers to only cover this\n        specific choice of activation function. Alternatively, it could be a\n        nuisance parameter if we are prepared to tune it separately for each\n        number of hidden layers.\n-   Whether a particular hyperparameter is a scientific hyperparameter, nuisance\n    hyperparameter, or fixed hyperparameter is not inherent to that\n    hyperparameter, but changes depending on the experimental goal.\n    -   For example, the choice of activation function could be a scientific\n        hyperparameter (is ReLU or tanh a better choice for our problem?), a\n        nuisance hyperparameter (is the best 5-layer model better than the best\n        6-layer model when we allow several different possible activation\n        functions?), or a fixed hyperparameter (for ReLU nets, does adding batch\n        normalization in a particular position help?).\n-   When designing a new round of experiments, we first identify the scientific\n    hyperparameters for our experimental goal.\n    -   At this stage, we consider all other hyperparameters to be nuisance\n        hyperparameters.\n-   Next, we convert some of the nuisance hyperparameters into fixed\n    hyperparameters.\n    -   With limitless resources, we would leave all non-scientific\n        hyperparameters as nuisance hyperparameters so that the conclusions we\n        draw from our experiments are free from caveats about fixed\n        hyperparameter values.\n    -   However, the more nuisance hyperparameters we attempt to tune, the\n        greater the risk we fail to tune them sufficiently well for each setting\n        of the scientific hyperparameters and end up reaching the wrong\n        conclusions from our experiments.\n        -   As described\n            [below](#striking-a-balance-between-informative-and-affordable-experiments),\n            we could counter this risk by increasing the computational budget,\n            but often our maximum resource budget is less than would be needed\n            to tune over all non-scientific hyperparameters.\n    -   We choose to convert a nuisance hyperparameter into a fixed\n        hyperparameter when, in our judgment, the caveats introduced by fixing\n        it are less burdensome than the cost of including it as a nuisance\n        hyperparameter.\n        -   The more a given nuisance hyperparameter interacts with the\n            scientific hyperparameters, the more damaging it is to fix its\n            value. For example, the best value of the weight decay strength\n            typically depends on the model size, so comparing different model\n            sizes assuming a single specific value of the weight decay would not\n            be very insightful.\n-   Although the type we assign to each hyperparameter depends on the\n    experimental goal, we have the following rules of thumb for certain\n    categories of hyperparameters:\n    -   Of the various optimizer hyperparameters (e.g. the learning rate,\n        momentum, learning rate schedule parameters, Adam betas etc.), at least\n        some of them will be nuisance hyperparameters because they tend to\n        interact the most with other changes.\n        -   They are rarely scientific hyperparameters because a goal like \"what\n            is the best learning rate for the current pipeline?\" doesn't give\n            much insight – the best setting could easily change with the next\n            pipeline change anyway.\n        -   Although we might fix some of them occasionally due to resource\n            constraints or when we have particularly strong evidence that they\n            don't interact with the scientific parameters, we should generally\n            assume that optimizer hyperparameters must be tuned separately to\n            make fair comparisons between different settings of the scientific\n            hyperparameters, and thus shouldn't be fixed.\n            -   Furthermore, we have no *a priori* reason to prefer one\n                optimizer hyperparameter value over another (e.g. they don't\n                usually affect the computational cost of forward passes or\n                gradients in any way).\n    -   In contrast, the *choice* of optimizer is typically a scientific\n        hyperparameter or fixed hyperparameter.\n        -   It is a scientific hyperparameter if our experimental goal involves\n            making fair comparisons between two or more different optimizers\n            (e.g. \"determine which optimizer produces the lowest validation\n            error in a given number of steps\").\n        -   Alternatively, we might make it a fixed hyperparameter for a variety\n            of reasons, including (1) prior experiments make us believe that the\n            best optimizer for our problem is not sensitive to current\n            scientific hyperparameters; and/or (2) we prefer to compare values\n            of the scientific hyperparameters using this optimizer because its\n            training curves are easier to reason about; and/or (3) we prefer to\n            use this optimizer because it uses less memory than the\n            alternatives.\n    -   Hyperparameters introduced by a regularization technique are typically\n        nuisance hyperparameters, but whether or not we include the\n        regularization technique at all is a scientific or fixed hyperparameter.\n        -   For example, dropout adds code complexity, so when deciding whether\n            to include it we would make \"no dropout\" vs \"dropout\" a scientific\n            hyperparameter and the dropout rate a nuisance hyperparameter.\n            -   If we decide to add dropout to our pipeline based on this\n                experiment, then the dropout rate would be a nuisance\n                hyperparameter in future experiments.\n    -   Architectural hyperparameters are often scientific or fixed\n        hyperparameters because architecture changes can affect serving and\n        training costs, latency, and memory requirements.\n        -   For example, the number of layers is typically a scientific or fixed\n            hyperparameter since it tends to have dramatic consequences for\n            training speed and memory usage.\n-   In some cases, the sets of nuisance and fixed hyperparameters will depend on\n    the values of the scientific hyperparameters.\n    -   For example, suppose we are trying to determine which optimizer out of\n        Nesterov momentum and Adam results in the lowest validation error. The\n        scientific hyperparameter is the `optimizer`, which takes values\n        `{\"Nesterov_momentum\", \"Adam\"}`. The value\n        `optimizer=\"Nesterov_momentum\"` introduces the nuisance/fixed\n        hyperparameters `{learning_rate, momentum}`, but the value\n        `optimizer=\"Adam\"` introduces the nuisance/fixed hyperparameters\n        `{learning_rate, beta1, beta2, epsilon}`.\n    -   Hyperparameters that are only present for certain values of the\n        scientific hyperparameters are called **conditional hyperparameters**.\n    -   We should not assume two conditional hyperparameters are the same just\n        because they have the same name! In the above example, the conditional\n        hyperparameter called `learning_rate` is a *different* hyperparameter\n        for `optimizer=\"Nesterov_momentum\"` versus `optimizer=\"Adam\"`. Its role\n        is similar (although not identical) in the two algorithms, but the range\n        of values that work well in each of the optimizers is typically\n        different by several orders of magnitude.\n\n</details>\n\n#### Creating a set of studies\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n-   Once we have identified the scientific and nuisance hyperparameters, we\n    design a \"study\" or sequence of studies to make progress towards the\n    experimental goal.\n    -   A study specifies a set of hyperparameter configurations to be run for\n        subsequent analysis. Each configuration is called a \"trial\".\n    -   Creating a study typically involves choosing the hyperparameters that\n        will vary across trials, choosing what values those hyperparameters can\n        take on (the \"search space\"), choosing the number of trials, and\n        choosing an automated search algorithm to sample that many trials from\n        the search space. Alternatively, we could create a study by specifying\n        the set of hyperparameter configurations manually.\n-   The purpose of the studies is to run the pipeline with different values of\n    the scientific hyperparameters, while at the same time **\"optimizing away\"**\n    (or \"optimizing over\") the nuisance hyperparameters so that comparisons\n    between different values of the scientific hyperparameters are as fair as\n    possible.\n-   In the simplest case, we would make a separate study for each configuration\n    of the scientific parameters, where each study tunes over the nuisance\n    hyperparameters.\n    -   For example, if our goal is to select the best optimizer out of Nesterov\n        momentum and Adam, we could create one study in which\n        `optimizer=\"Nesterov_momentum\"` and the nuisance hyperparameters are\n        `{learning_rate, momentum}`, and another study in which\n        `optimizer=\"Adam\"` and the nuisance hyperparameters are `{learning_rate,\n        beta1, beta2, epsilon}`. We would compare the two optimizers by\n        selecting the best performing trial from each study.\n    -   We can use any gradient-free optimization algorithm, including methods\n        such as Bayesian optimization or evolutionary algorithms, to optimize\n        over the nuisance hyperparameters, although\n        [we prefer](#why-use-quasi-random-search-instead-of-more-sophisticated-black-box-optimization-algorithms-during-the-exploration-phase-of-tuning)\n        to use quasi-random search in the\n        [exploration phase](#exploration-vs-exploitation) of tuning because of a\n        variety of advantages it has in this setting.\n        [After exploration concludes](#after-exploration-concludes), if\n        state-of-the-art Bayesian optimization software is available, that is\n        our preferred choice.\n-   In the more complicated case where we want to compare a large number of\n    values of the scientific hyperparameters and it is impractical to make that\n    many independent studies, we can include the scientific parameters in the\n    same search space as the nuisance hyperparameters and use a search algorithm\n    to sample values of *both* the scientific and nuisance hyperparameters in a\n    single study.\n    -   When taking this approach, conditional hyperparameters can cause\n        problems since it is hard to specify a search space unless the set of\n        nuisance hyperparameters is the same for all values of the scientific\n        hyperparameters.\n    -   In this case,\n        [our preference](#why-use-quasi-random-search-instead-of-more-sophisticated-black-box-optimization-algorithms-during-the-exploration-phase-of-tuning)\n        for using quasi-random search over fancier black-box optimization tools\n        is even stronger, since it ensures that we obtain a relatively uniform\n        sampling of values of the scientific hyperparameters. Regardless of the\n        search algorithm, we need to make sure somehow that it searches the\n        scientific parameters uniformly.\n\n</details>\n\n#### Striking a balance between informative and affordable experiments\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n-   When designing a study or sequence of studies, we need to allocate a limited\n    budget in order to adequately achieve the following three desiderata:\n    1.  Comparing enough different values of the scientific hyperparameters.\n    2.  Tuning the nuisance hyperparameters over a large enough search space.\n    3.  Sampling the search space of nuisance hyperparameters densely enough.\n-   The better we can achieve these three desiderata, the more insight we can\n    extract from our experiment.\n    -   Comparing as many values of the scientific hyperparameters as possible\n        broadens the scope of the insights we gain from the experiment.\n    -   Including as many nuisance hyperparameters as possible and allowing each\n        nuisance hyperparameter to vary over as wide a range as possible\n        increases our confidence that a \"good\" value of the nuisance\n        hyperparameters **exists** in the search space for each configuration of\n        the scientific hyperparameters.\n        -   Otherwise, we might make unfair comparisons between values of the\n            scientific hyperparameters by not searching possible regions of the\n            nuisance parameter space where better values might lie for some\n            values of the scientific parameters.\n    -   Sampling the search space of nuisance hyperparameters as densely as\n        possible increases our confidence that any good settings for the\n        nuisance hyperparameters that happen to exist in our search space will\n        be found by the search procedure.\n        -   Otherwise, we might make unfair comparisons between values of the\n            scientific parameters due to some values getting luckier with the\n            sampling of the nuisance hyperparameters.\n-   Unfortunately, improvements in *any* of these three dimensions require\n    either increasing the number of trials, and therefore increasing the\n    resource cost, or finding a way to save resources in one of the other\n    dimensions.\n    -   Every problem has its own idiosyncrasies and computational constraints,\n        so how to allocate resources across these three desiderata requires some\n        level of domain knowledge.\n    -   After running a study, we always try to get a sense of whether the study\n        tuned the nuisance hyperparameters well enough (i.e. searched a large\n        enough space extensively enough) to fairly compare the scientific\n        hyperparameters (as described in greater detail\n        [below](#extracting-insight-from-experimental-results)).\n\n</details>\n\n### Extracting insight from experimental results\n\n***Summary:*** *In addition to trying to achieve the original scientific goal of\neach group of experiments, go through a checklist of additional questions and,\nif issues are discovered, revise the experiments and rerun them.*\n\n-   Ultimately, each group of experiments has a specific goal and we want to\n    evaluate the evidence the experiments provide toward that goal.\n    -   However, if we ask the right questions, we will often find issues that\n        need to be corrected before a given set of experiments can make much\n        progress towards their original goal.\n        -   If we don’t ask these questions, we may draw incorrect conclusions.\n    -   Since running experiments can be expensive, we also want to take the\n        opportunity to extract other useful insights from each group of\n        experiments, even if these insights are not immediately relevant to the\n        current goal.\n-   Before analyzing a given set of experiments to make progress toward their\n    original goal, we should ask ourselves the following additional questions:\n    -   [Is the search space large enough?](#identifying-bad-search-space-boundaries)\n        -   If the optimal point from a study is near the boundary of the search\n            space in one or more dimensions, the search is probably not wide\n            enough. In this case, we should run another study with an expanded\n            search space.\n    -   [Have we sampled enough points from the search space?](#not-sampling-enough-points-in-the-search-space)\n        -   If not, run more points or be less ambitious in the tuning goals.\n    -   What fraction of the trials in each study are **infeasible** (i.e.\n        trials that diverge, get really bad loss values, or fail to run at all\n        because they violate some implicit constraint)?\n        -   When a very large fraction of points in a study are **infeasible**\n            we should try to adjust the search space to avoid sampling such\n            points, which sometimes requires reparameterizing the search space.\n        -   In some cases, a large number of infeasible points can indicate a\n            bug in the training code.\n    -   [Does the model exhibit optimization issues?](#how-can-optimization-failures-be-debugged-and-mitigated)\n    -   [What can we learn from the training curves of the best trials?](#examining-the-training-curves)\n        -   For example, do the best trials have training curves consistent with\n            problematic overfitting?\n-   If necessary, based on the answers to the questions above, refine the most\n    recent study (or group of studies) to improve the search space and/or sample\n    more trials, or take some other corrective action.\n-   Once we have answered the above questions, we can move on to evaluating the\n    evidence the experiments provide towards our original goal (for example,\n    [evaluating whether a change is useful](#detecting-whether-a-change-is-useful-with-isolation-plots)).\n\n#### Identifying bad search space boundaries\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n-   A search space is suspicious if the best point sampled from it is close to\n    its boundary. We might find an even better point if we expanded the search\n    range in that direction.\n-   To check search space boundaries, we like to plot completed trials on what\n    we call **basic hyperparameter axis plots** where we plot the validation\n    objective value versus one of the hyperparameters (e.g. learning rate). Each\n    point on the plot corresponds to a single trial.\n    -   The validation objective value for each trial should usually be the best\n        value it achieved over the course of training.\n\n<p align=\"center\" id=\"figure-1\">\n    <img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/bad_search_space.png\" width=\"49%\" alt=\"Example of bad search space boundaries\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/good_search_space.png\" width=\"49%\" alt=\"Example of good search space boundaries\">\n</p>\n\n<p align=\"center\"><b>Figure 1:</b> Examples of bad search space boundaries and acceptable search space boundaries.</p>\n\n-   The plots in [Figure 1](#figure-1) show the error rate (lower is better)\n    against the initial learning rate.\n-   If the best points cluster towards the edge of a search space (in some\n    dimension), then the search space boundaries might need to be expanded until\n    the best observed point is no longer close to the boundary.\n-   Often, a study will include \"infeasible\" trials that diverge or get very bad\n    results (marked with red Xs in the above plots).\n    -   If all trials are infeasible for learning rates greater than some\n        threshold value, and if the best performing trials have learning rates\n        at the edge of that region, the model [may suffer from stability issues\n        preventing it from accessing higher learning\n        rates](#how-can-optimization-failures-be-debugged-and-mitigated).\n\n</details>\n\n#### Not sampling enough points in the search space\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n-   In general,\n    [it can be very difficult to know](#how-many-trials-are-needed-to-get-good-results-with-quasi-random-search)\n    if the search space has been sampled densely enough. 🤖\n-   Running more trials is of course better, but comes at an obvious cost.\n-   Since it is so hard to know when we have sampled enough, we usually sample\n    what we can afford and try to calibrate our intuitive confidence from\n    repeatedly looking at various hyperparameter axis plots and trying to get a\n    sense of how many points are in the \"good\" region of the search space.\n\n</details>\n\n#### Examining the training curves\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n***Summary:*** *Examining the training curves is an easy way to identify common\nfailure modes and can help us prioritize what actions to take next.*\n\n-   Although in many cases the primary objective of our experiments only\n    requires considering the validation error of each trial, we must be careful\n    when reducing each trial to a single number because it can hide important\n    details about what’s going on below the surface.\n-   For every study, we always look at the **training curves** (training error\n    and validation error plotted versus training step over the duration of\n    training) of at least the best few trials.\n-   Even if this is not necessary for addressing the primary experimental\n    objective, examining the training curves is an easy way to identify common\n    failure modes and can help us prioritize what actions to take next.\n-   When examining the training curves, we are interested in the following\n    questions.\n-   Are any of the trials exhibiting **problematic overfitting?**\n    -   Problematic overfitting occurs when the validation error starts\n        *increasing* at some point during training.\n    -   In experimental settings where we optimize away nuisance hyperparameters\n        by selecting the \"best\" trial for each setting of the scientific\n        hyperparameters, we should check for problematic overfitting in *at\n        least* each of the best trials corresponding to the settings of the\n        scientific hyperparameters that we’re comparing.\n        -   If any of the best trials exhibits problematic overfitting, we\n            usually want to re-run the experiment with additional regularization\n            techniques and/or better tune the existing regularization parameters\n            before comparing the values of the scientific hyperparameters.\n            -   This may not apply if the scientific hyperparameters include\n                regularization parameters, since then it would not be surprising\n                if low-strength settings of those regularization parameters\n                resulted in problematic overfitting.\n        -   Reducing overfitting is often straightforward using common\n            regularization techniques that add minimal code complexity or extra\n            computation (e.g. dropout, label smoothing, weight decay), so it’s\n            usually no big deal to add one or more of these to the next round of\n            experiments.\n        -   For example, if the scientific hyperparameter is \"number of hidden\n            layers\" and the best trial that uses the largest number of hidden\n            layers exhibited problematic overfitting, then we would usually\n            prefer to try it again with additional regularization instead of\n            immediately selecting the smaller number of hidden layers.\n        -   Even if none of the \"best\" trials are exhibiting problematic\n            overfitting, there might still be a problem if it occurs in *any* of\n            the trials.\n            -   Selecting the best trial suppresses configurations exhibiting\n                problematic overfitting and favors those that do not. In other\n                words, it will favor configurations with more regularization.\n            -   However, anything that makes training worse can act as a\n                regularizer, even if it wasn't intended that way. For example,\n                choosing a smaller learning rate can regularize training by\n                hobbling the optimization process, but we typically don't want\n                to choose the learning rate this way.\n            -   So we must be aware that the \"best\" trial for each setting of\n                the scientific hyperparameters might be selected in such a way\n                that favors \"bad\" values of some of the scientific or nuisance\n                hyperparameters.\n-   Is there high step-to-step variance in the training or validation error late\n    in training?\n    -   If so, this could interfere with our ability to compare different values\n        of the scientific hyperparameters (since each trial randomly ends on a\n        \"lucky\" or \"unlucky\" step) and our ability to reproduce the result of\n        the best trial in production (since the production model might not end\n        on the same \"lucky\" step as in the study).\n    -   The most likely causes of step-to-step variance are batch variance (from\n        randomly sampling examples from the training set for each batch), small\n        validation sets, and using a learning rate that’s too high late in\n        training.\n    -   Possible remedies include increasing the batch size, obtaining more\n        validation data, using learning rate decay, or using Polyak averaging.\n-   Are the trials still improving at the end of training?\n    -   If so, this indicates that we are in the\n        [\"compute bound\" regime](#determining-the-number-of-steps-for-each-training-run)\n        and we may benefit from\n        [increasing the number of training steps](#Deciding-how-long-to-train-when-training-is-compute-bound)\n        or changing the learning rate schedule.\n-   Has performance on the training and validation sets saturated long before\n    the final training step?\n    -   If so, this indicates that we are in the\n        [\"not compute-bound\"](#determining-the-number-of-steps-for-each-training-run)\n        regime and that we may be able to\n        [decrease the number of training steps](#deciding-how-long-to-train-when-training-is-not-compute-bound).\n-   Although we cannot enumerate them all, there are many other additional\n    behaviors that can become evident from examining the training curves (e.g.\n    training loss *increasing* during training usually indicates a bug in the\n    training pipeline).\n\n</details>\n\n#### Detecting whether a change is useful with isolation plots\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n\n<p align=\"center\" id=\"figure-2\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/isolation_plot.png\" width=\"49%\" alt=\"Isolation plot that investigates the best value of weight decay for ResNet-50\ntrained on ImageNet.\">\n</p>\n\n<p align=\"center\"><b>Figure 2:</b> Isolation plot that investigates the best value of weight decay for ResNet-50 trained on ImageNet.</p>\n\n-   Often, the goal of a set of experiments is to compare different values of a\n    scientific hyperparameter.\n    -   For example, we may want to determine the value of weight decay that\n        results in the best validation error.\n-   An **isolation plot** is a special case of the basic hyperparameter axis\n    plot. Each point on an isolation plot corresponds to the performance of the\n    *best* trial across some (or all) of the nuisance hyperparameters.\n    -   In other words, we plot the model performance after \"optimizing away\"\n        the nuisance hyperparameters.\n-   An isolation plot makes it easier to perform an apples-to-apples comparison\n    between different values of the scientific hyperparameter.\n-   For example, [Figure 2](#figure-2) reveals the value of weight decay that\n    produces the best validation performance for a particular configuration of\n    ResNet-50 trained on ImageNet.\n    -   If our goal is to determine whether to include weight decay at all, then\n        we would compare the best point from this plot against the baseline of\n        no weight decay. For a fair comparison, the baseline should also have\n        its learning rate equally well tuned.\n-   When we have data generated by (quasi)random search and are considering a\n    continuous hyperparameter for an isolation plot, we can approximate the\n    isolation plot by bucketing the x-axis values of the basic hyperparameter\n    axis plot and taking the best trial in each vertical slice defined by the\n    buckets.\n\n</details>\n\n#### Automate generically useful plots\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   The more effort it is to generate plots, the less likely we are to look at\n    them as much as we should, so it behooves us to set up our infrastructure to\n    automatically produce as many of them as possible.\n-   At a minimum, we automatically generate basic hyperparameter axis plots for\n    all hyperparameters that we vary in an experiment.\n-   Additionally, we automatically produce training curves for all trials and\n    make it as easy as possible to find the best few trials of each study and\n    examine their training curves.\n-   There are many other potential plots and visualizations we can add that can\n    be useful. Although the ones described above are a good starting point, to\n    paraphrase Geoffrey Hinton, \"Every time you plot something new, you learn\n    something new.\"\n\n</details>\n\n### Determining whether to adopt a training pipeline change or hyperparameter configuration\n\n***Summary:*** *When deciding whether to make a change to our model or training\nprocedure or adopt a new hyperparameter configuration going forward, we need to\nbe aware of the different sources of variation in our results.*\n\n-   When we are trying to improve our model, we might observe that a particular\n    candidate change initially achieves a better validation error compared to\n    our incumbent configuration, but find that after repeating the experiment\n    there is no consistent advantage. Informally, we can group the most\n    important sources of variation that might cause such an inconsistent result\n    into the following broad categories:\n    -   **Training procedure variance**, **retrain variance**, or **trial\n        variance**: the variation we see between training runs that use the same\n        hyperparameters, but different random seeds.\n        -   For example, different random initializations, training data\n            shuffles, dropout masks, patterns of data augmentation operations,\n            and orderings of parallel arithmetic operations, are all potential\n            sources of trial variance.\n    -   **Hyperparameter search variance**, or **study variance**: the variation\n        in results caused by our procedure to select the hyperparameters.\n        -   For example, we might run the same experiment with a particular\n            search space, but with two different seeds for quasi-random search\n            and end up selecting different hyperparameter values.\n    -   **Data collection and sampling variance**: the variance from any sort of\n        random split into training, validation, and test data or variance due to\n        the training data generation process more generally.\n-   It is all well and good to make comparisons of validation error rates\n    estimated on a finite validation set using fastidious statistical tests, but\n    often the trial variance alone can produce statistically significant\n    differences between two different trained models that use the same\n    hyperparameter settings.\n-   We are most concerned about study variance when trying to make conclusions\n    that go beyond the level of an individual point in hyperparameters space.\n    -   The study variance depends on the number of trials and the search space\n        and we have seen cases where it is larger than the trial variance as\n        well as cases where it is much smaller.\n-   Therefore, before adopting a candidate change, consider running the best\n    trial N times to characterize the run-to-run trial variance.\n    -   Usually, we can get away with only recharacterizing the trial variance\n        after major changes to the pipeline, but in some applications we might\n        need fresher estimates.\n    -   In other applications, characterizing the trial variance is too costly\n        to be worth it.\n-   At the end of the day, although we only want to adopt changes (including new\n    hyperparameter configurations) that produce real improvements, demanding\n    complete certainty that something helps isn't the right answer either.\n-   Therefore, if a new hyperparameter point (or other change) gets a better\n    result than the baseline (taking into account the retrain variance of both\n    the new point and the baseline as best we can), then we probably should\n    adopt it as the new baseline for future comparisons.\n    -   However, we should only adopt changes that produce improvements that\n        outweigh any complexity they add.\n\n### After exploration concludes\n\n***Summary:*** *Bayesian optimization tools are a compelling option once we’re\ndone exploring for good search spaces and have decided what hyperparameters even\nshould be tuned at all.*\n\n-   At some point, our priorities will shift from learning more about the tuning\n    problem to producing a single best configuration to launch or otherwise use.\n-   At this point, there should be a refined search space that comfortably\n    contains the local region around the best observed trial and has been\n    adequately sampled.\n-   Our exploration work should have revealed the most essential hyperparameters\n    to tune (as well as sensible ranges for them) that we can use to construct a\n    search space for a final automated tuning study using as large a tuning\n    budget as possible.\n-   Since we no longer care about maximizing our insight into the tuning\n    problem, many of\n    [the advantages of quasi-random search](#why-use-quasi-random-search-instead-of-more-sophisticated-black-box-optimization-algorithms-during-the-exploration-phase-of-tuning)\n    no longer apply and Bayesian optimization tools should be used to\n    automatically find the best hyperparameter configuration.\n    -   [Open-Source Vizier](https://github.com/google/vizier) implements\n        a variety of sophisticated algorithms for tuning ML models, including\n        Bayesian Optimization algorithms.\n    -   If the search space contains a non-trivial volume of divergent points\n        (points that get NaN training loss or even training loss many standard\n        deviations worse than the mean), it is important to use black box\n        optimization tools that properly handle trials that diverge (see\n        [Bayesian Optimization with Unknown Constraints](https://arxiv.org/abs/1403.5607)\n        for an excellent way to deal with this issue). [Open-Source Vizier](https://github.com/google/vizier)\n        has support for divergent points by marking trials as infeasible, although it may not use our preferred approach from [Gelbart et al.](https://arxiv.org/abs/1403.5607), depending on how it is configured.\n-   At this point, we should also consider checking the performance on the test\n    set.\n    -   In principle, we could even fold the validation set into the training\n        set and retraining the best configuration found with Bayesian\n        optimization. However, this is only appropriate if there won't be future\n        launches with this specific workload (e.g. a one-time Kaggle\n        competition).\n\n## Determining the number of steps for each training run\n\n-   There are two types of workloads: those that are compute-bound and those\n    that are not.\n-   When training is **compute-bound**, training is limited by how long we are\n    willing to wait and not by how much training data we have or some other\n    factor.\n    -   In this case, if we can somehow train longer or more efficiently, we\n        should see a lower training loss and, with proper tuning, an improved\n        validation loss.\n    -   In other words, *speeding up* training is equivalent to *improving*\n        training and the \"optimal\" training time is always \"as long as we can\n        afford.\"\n    -   That said, just because a workload is compute-limited doesn't mean\n        training longer/faster is the only way to improve results.\n-   When training is **not compute-bound**, we can afford to train as long as we\n    would like to, and, at some point, training longer doesn't help much (or\n    even causes problematic overfitting).\n    -   In this case, we should expect to be able to train to very low training\n        loss, to the point where training longer might slightly reduce the\n        training loss, but will not meaningfully reduce the validation loss.\n    -   Particularly when training is not compute-bound, a more generous\n        training time budget can make tuning easier, especially when tuning\n        learning rate decay schedules, since they have a particularly strong\n        interaction with the training budget.\n        -   In other words, very stingy training time budgets might require a\n            learning rate decay schedule tuned to perfection in order to achieve\n            a good error rate.\n-   Regardless of whether a given workload is compute-bound or not, methods that\n    increase the variance of the gradients (across batches) will usually result\n    in slower training progress, and thus may increase the number of training\n    steps required to reach a particular validation loss. High gradient variance\n    can be caused by:\n    -   Using a smaller batch size\n    -   Adding data augmentation\n    -   Adding some types of regularization (e.g. dropout)\n\n### Deciding how long to train when training is *not* compute-bound\n\n-   Our main goal is to ensure we are training long enough for the model to\n    reach the best possible result, while avoiding being overly wasteful in the\n    number of training steps.\n-   When in doubt, err on the side of training longer. Performance should never\n    degrade when training longer, assuming retrospective (optimal) checkpoint\n    selection is used properly and checkpoints are frequent enough.\n-   Never tune the `max_train_steps` number in a study. Pick a value and use it\n    for all trials. From these trials, plot the training step that retrospective\n    checkpoint selection finds in order to refine the choice of\n    `max_train_steps`.\n    -   For example, if the best step is always during the first 10% of\n        training, then the maximum number of steps is way too high.\n    -   Alternatively, if the best step is consistently in the last 25% of\n        training we might benefit from training longer and re-tuning the decay\n        schedule.\n-   The ideal number of training steps can change when the architecture or data\n    changes (e.g. adding data augmentation).\n-   Below we describe how to pick an initial candidate value for\n    `max_train_steps` based on the number of steps necessary to \"perfectly fit\"\n    the training set using a constant learning rate.\n    -   Note, we are not using the phrase \"perfectly fit the training set\" in a\n        precise or mathematically well-defined way. It is merely meant as an\n        informal descriptor to indicate a very low training loss.\n        -   For example, when training with the log loss, absent regularization\n            terms, we might see the training loss keep slowly improving until we\n            reach floating point limits as the network weights grow without\n            bound and the predictions of the model on the training set become\n            increasingly confident. In this case, we might say the model\n            \"perfectly fit\" the training set around the time the\n            misclassification error reached zero on the training set.\n    -   The starting value for `max_train_steps` we find may need to be\n        increased if the amount of gradient noise in the training procedure\n        increases.\n        -   For example, if data augmentation or regularizers like dropout are\n            introduced to the model.\n    -   It may be possible to decrease `max_train_steps` if the training process\n        improves somehow.\n        -   For example, with a better tuned optimizer or a better tuned\n            learning rate schedule.\n\n#### Algorithm for picking an initial candidate for max_train_steps using a learning rate sweep\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   This procedure assumes it is possible to not only \"perfectly\" fit the\n    training set, but to do so using a constant learning rate schedule.\n-   If it is possible to perfectly fit the entire training set, then there must\n    exist a configuration (with some value of `max_train_steps`) that perfectly\n    fits the training set; find any such configuration and use its value of\n    `max_train_steps` as a starting point `N`.\n-   Run a constant learning rate sweep (i.e. grid search the learning rate)\n    without data augmentation and without regularization where each trial trains\n    for `N` steps.\n-   The number of steps required for the fastest trial in the sweep to reach\n    perfect training performance is our initial guess for `max_train_steps`.\n-   **NOTE:** Bad search spaces can make it possible to engage in\n    self-deception.\n    -   For example, if all the learning rates in a study are too small, we\n        might incorrectly conclude that a very large value of `max_train_steps`\n        is necessary.\n    -   At a minimum, we should check that the optimal learning rate in the\n        study is not at the boundary of the search space.\n\n</details>\n\n### Deciding how long to train when training is compute-bound\n\n-   In some cases, training loss keeps improving indefinitely and our patience\n    and computational resources become the limiting factors.\n-   If training loss (or even validation loss) keeps improving indefinitely,\n    should we always train as long as we can afford? Not necessarily.\n    -   We might be able to tune more effectively by running a larger number of\n        shorter experiments and reserving the longest \"production length\" runs\n        for the models we hope to launch.\n    -   As the training time for trials approaches our patience limit, tuning\n        experiments become more relevant for our potential launch candidates,\n        but we can complete fewer of them.\n    -   There are probably many questions we can answer while only training for\n        ~10% of the production length, but there is always a risk that our\n        conclusions at this time limit will not apply to experiments at 20% of\n        the production length, let alone 100%.\n-   Tuning in multiple rounds with increasing, per-trial training step limits is\n    a sensible approach.\n    -   We can do as many rounds as we want, but usually 1-3 are the most\n        practical.\n    -   Essentially, try to obtain as much understanding of the problem as\n        possible using trials with a very quick turnaround time, trading off\n        tuning thoroughness with relevance to the final, longest runs.\n    -   Once a given per-trial time limit has generated useful insights, we can\n        increase the training time and continue tuning, double-checking our\n        conclusions from the shorter runs as needed.\n-   As a starting point, we recommend two rounds of tuning:\n    -   Round 1: Shorter runs to find good model and optimizer hyperparameters.\n    -   Round 2: Very few long runs on good hyperparameter points to get the\n        final model.\n-   The biggest question going from `Round i` &rarr; `Round i+1` is how to\n    adjust learning rate decay schedules.\n    -   One common pitfall when adjusting learning rate schedules between rounds\n        is using all the extra training steps with too small of a learning rate.\n\n#### Round 1\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   Unfortunately, there is no guarantee that good hyperparameters found in\n    short, incomplete training are still good choices when training length is\n    significantly increased. However, for some kinds of hyperparameters, they\n    are often correlated enough for Round 1 to be useful.\n-   What hyperparameter values found in shorter runs do we expect to transfer to\n    longer training runs? For all of this, we need more research. But based on\n    what we know so far, here are the authors’ suspicions in order of decreasing\n    probability of transferring:\n    -   Very likely to transfer\n        -   Early training instability can be resolved in the first round of\n            tuning using a smaller number of training steps. Perhaps these\n            hyperparameters are the closest thing to a sure bet for transfer\n            that we have.\n            -   Warmup length\n            -   Initialization\n    -   Likely to transfer\n        -   Model architecture - A dramatic win in the model architecture will\n            usually transfer, but there are probably many counterexamples.\n    -   Might transfer\n        -   Optimization algorithm/optimizer hyperparameters - We think this\n            would \"loosely\" transfer. It’s definitely weaker than the things\n            above it.\n        -   Data augmentation\n        -   Regularization\n            -   If it isn't possible to perfectly fit the training set, the\n                model might be in a regime where regularization is unlikely to\n                help very much.\n    -   Unlikely to transfer\n        -   Learning rate schedule: unlikely to transfer perfectly.\n            -   [This paper](https://arxiv.org/abs/2203.15556) suggests that\n                even decay schedule transfers, but we don't believe this is true\n                in general. Example: Tuning sqrt decay on small # of training\n                steps then extending to large # will result in the majority of\n                training occurring at overly small steps.\n                -   One can likely do \"good enough\" with most schedules in the\n                    limit of extreme training budget, but noticeable performance\n                    improvements can likely be seen if it is tuned.\n            -   [Understanding Short-Horizon Bias in Stochastic\n                Meta-Optimization](https://arxiv.org/abs/1803.02021) describes\n                the dangers of trying to pick learning rates myopically.\n\n</details>\n\n#### Round 2\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   Run the best hyperparameter configuration from Round 1.\n-   **(Speculation)** 🤖 Use the extra steps to extend the period of training at\n    a high learning rate.\n    -   E.g. if linear schedule then keep the length of the decay fixed from\n        Round 1 and extend the period of constant lr in the beginning.\n    -   For cosine decay, just keep the base lr from Round 1 and extend\n        `max_train_steps` as in\n        [Chinchilla paper](https://arxiv.org/abs/2203.15556).\n-   More rounds might make sense for teams with very mature modeling and tuning\n    pipelines and very long and expensive production training runs, but they\n    will often be overkill.\n    -   We've described how to transfer from Step 1 &rarr; Step 2. If we didn't care\n        about analysis time and if making efficient use of compute was the\n        overriding concern, then the ideal would be to exponentially increase\n        the length of training runs (and thus the end-to-end time to complete a\n        study) over many different rounds of tuning.\n        -   At each round we systematically ensure our choices continue to hold\n            up.\n        -   New ideas go through a pipeline that progressively derisks them\n            using increasingly long-running experiments from Step i to Step i+1.\n\n</details>\n\n## Additional guidance for the training pipeline\n\n### Optimizing the input pipeline\n\n***Summary:*** *The causes and interventions of input-bound pipelines are highly\ntask-dependent; use a profiler and look out for common issues.*\n\n-   Use an appropriate profiler to diagnose input-bound pipelines. For example,\n    [Perfetto](https://jax.readthedocs.io/en/latest/profiling.html) for JAX or\n    [TensorFlow profiler](https://www.tensorflow.org/guide/profiler) for\n    TensorFlow.\n-   Ultimately, the specific causes and interventions will be highly\n    task-dependent. Broader engineering considerations (e.g. minimizing disk\n    footprint) may warrant worse input pipeline performance.\n-   Common causes:\n    -   Data are not colocated with the training process, causing I/O latency\n        (this might happen when reading training data over a network).\n    -   Expensive online data preprocessing (consider doing this once offline\n        and saving).\n    -   Unintentional synchronization barriers that interfere with data pipeline\n        prefetching. For example, when synchronizing metrics between the device\n        and host in CommonLoopUtils\n        ([link](https://github.com/google/CommonLoopUtils/blob/fea2518ada8814a78e1492023fd9f00edb0b0568/clu/metrics.py#L291)).\n-   Common tips:\n    -   Instrument input pipeline to prefetch examples (e.g.\n        [tf.data.Dataset.prefetch](https://www.tensorflow.org/guide/data_performance#prefetching))\n    -   Remove unused features/metadata from each as early in the pipeline as\n        possible.\n    -   Increase the replication of the number of jobs generating examples for\n        the input pipeline. For example, by using the\n        [tf.data service](https://www.tensorflow.org/api_docs/python/tf/data/experimental/service).\n\n### Evaluating model performance\n\n***Summary:*** *Run evaluation at larger batch sizes than training. Run\nevaluations at regular step intervals, not regular time intervals.*\n\n#### Evaluation settings\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   There are several settings in which we can evaluate the performance of our\n    models.\n    -   **Online evaluation** - metrics are collected when the model is serving\n        predictions in a production environment.\n    -   **Offline evaluation** - metrics are collected when the model is run on\n        offline train/validation/test sets that are representative of the\n        production environment.\n    -   **Periodic evaluations** - metrics are collected during model training\n        that might either be a proxy for the offline evaluation, and/or on a\n        subset of the data used in offline evaluation.\n-   Online evaluation is the gold standard, but is often impractical during the\n    model development phase.\n-   Depending on the problem, offline evaluation can be fairly involved and\n    computationally expensive.\n-   Periodic evaluations are the most practical and economical choice, but may\n    not fully represent the production environment.\n    -   Our goal during periodic evaluation is to use an expedient proxy of the\n        offline evaluation, without sacrificing the reliability of the signal we\n        get during training.\n\n</details>\n\n#### Setting up periodic evaluations\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   We run periodic evaluations during training to monitor its progress in real\n    time, to\n    [facilitate retrospective model checkpoint selection](#saving-checkpoints-and-retrospectively-selecting-the-best-checkpoint),\n    and so that we can\n    [examine the training curves at the end of training](#examining-the-training-curves).\n-   The simplest configuration is to perform both training and periodic\n    evaluations within the same compute instance, periodically alternating\n    between training and evaluation.\n    -   In this case, the batch size used to perform evaluations should be *at\n        least* as large as the batch size used for training because model\n        activations don't need to be maintained during evaluation, lowering the\n        computational requirements per example.\n-   Periodic evaluations should be done at regular step intervals, not time\n    intervals.\n    -   Evaluating based on time intervals can make it harder to interpret the\n        training curves, especially when training may suffer from preemptions of\n        the training jobs, network latency issues, etc.\n-   Periodicity in valid/test metrics (when using a shuffled\n    train/validation/test split) can indicate implementation bugs such as test\n    data having overlap with training data, or training data not being properly\n    shuffled. Evaluating at regular step intervals can make these issues easier\n    to catch.\n-   Partial batches can occur when the evaluation sets are not divisible by the\n    batch size. Ensure that the padded examples are correctly weighted to prevent\n    the loss function from being biased by them. Often, these padded examples\n    can be given a weight of zero.\n-   Save sufficient information per evaluation to support offline analysis.\n    Ideally, we would save predictions on a selection of individual examples\n    since they can be invaluable for debugging.\n    -   Generating artifacts like\n        [SavedModels](https://www.tensorflow.org/guide/saved_model) make it easy\n        to do ad-hoc model inspection after evaluation jobs finish.\n\n</details>\n\n#### Choosing a sample for periodic evaluation\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   The periodic evaluation job might not run fast enough to compute metrics on\n    the full offline evaluation set in a reasonable amount of time. This often\n    necessitates sampling data for periodic evaluation.\n-   We consider the following factors when constructing a sampled dataset:\n    -   <ins>Sample size</ins>\n        -   Check that the performance computed on the sampled dataset used by\n            the periodic job matches the performance on the whole offline\n            evaluation set, i.e. there is no skew between the sampled set and\n            the full dataset.\n        -   The dataset used for periodic evaluation should be small enough that\n            it’s easy to generate model predictions over its entirety, but large\n            enough that improvements to the model can be accurately measured\n            (i.e. not overwhelmed by label noise).\n        -   It should be large enough to accommodate multiple such evaluations\n            across trials in sequence, and still produce accurate estimates.\n            That is, to avoid adaptively \"fitting\" to the validation set over\n            time, in a way that doesn't generalize to a held-out test set.\n            However, this consideration is rarely a practical concern.\n    -   <ins>Imbalanced datasets</ins>\n        -   For imbalanced datasets, performance on rare classes of examples\n            will often be noisy.\n        -   For datasets with a small number of examples in a class label, log\n            the number of examples predicted correctly to get more insight into\n            accuracy improvements (.05 sensitivity improvement sounds exciting,\n            but was it just one more example correct?).\n\n</details>\n\n### Saving checkpoints and retrospectively selecting the best checkpoint\n\n***Summary:*** *Run training for a fixed number of steps and retrospectively\nchoose the best checkpoint from the run.*\n\n-   Most deep learning frameworks support\n    [model checkpointing](https://flax.readthedocs.io/en/latest/api_reference/flax.training.html).\n    That is, the current state of the model is periodically preserved on disk.\n    This allows the training job to be resilient to compute instance\n    interruptions.\n-   The best checkpoint is often not the last checkpoint, particularly when the\n    validation set performance does not continue to increase over time but\n    rather fluctuates about a particular value.\n-   Set up the pipeline to keep track of the N best checkpoints seen so far\n    during training. At the end of training, model selection is then a matter of\n    choosing the best checkpoint seen during training. We call this\n    **retrospective optimal checkpoint selection**.\n-   Supporting prospective early stopping is usually not necessary, since we’re\n    pre-specifying a trial budget and are preserving the N best checkpoints seen\n    so far.\n\n### Setting up experiment tracking\n\n***Summary:*** *When tracking different experiments, make sure to note a number\nof essentials like the best performance of a checkpoint in the study, and a\nshort description of the study.*\n\n-   We've found that keeping track of experiment results in a spreadsheet has\n    been helpful for the sorts of modeling problems we've worked on. It often\n    has the following columns:\n    -   Study name\n    -   A link to wherever the config for the study is stored.\n    -   Notes or a short description of the study.\n    -   Number of trials run\n    -   Performance on the validation set of the best checkpoint in the study.\n    -   Specific reproduction commands or notes on what unsubmitted changes were\n        necessary to launch training.\n-   Find a tracking system that captures at least the information listed above\n    and is convenient for the people doing it. Untracked experiments might as\n    well not exist.\n\n### Batch normalization implementation details\n\n***Summary:*** *Nowadays batch norm can often be replaced with LayerNorm, but in\ncases where it cannot, there are tricky details when changing the batch size or\nnumber of hosts.*\n\n-   Batch norm normalizes activations using their mean and variance over the\n    current batch, but in the multi-device setting these statistics are\n    different on each device unless explicitly synchronized.\n-   Anecdotal reports (mostly on ImageNet) say calculating these normalizing\n    statistics using only ~64 examples actually works better in practice (see\n    Ghost Batch Norm from [this paper](https://arxiv.org/abs/1705.08741)).\n-   Decoupling the total batch size and the number of examples used to calculate\n    batch norm statistics is particularly useful for batch size comparisons.\n-   Ghost batch norm implementations do not always correctly handle the case\n    where the per-device batch size > virtual batch size. In this case we'd\n    actually need to subsample the batch on each device in order to get the\n    proper number of batch norm statistic examples.\n-   Exponential moving averages used in test mode batch norm are just a linear\n    combination of training statistics, so these EMAs only need to be\n    synchronized before saving them in checkpoints. However, some common\n    implementations of batch norm do not synchronize these EMAs and only save\n    the EMA from the first device.\n\n### Considerations for multi-host pipelines\n\n***Summary:*** *for logging, evals, RNGs, checkpointing, and data sharding,\nmulti-host training can make it very easy to introduce bugs!*\n\n-   Ensure the pipeline is only logging and checkpointing on one host.\n-   Make sure before evaluation or checkpointing is run, the batch norm\n    statistics are synchronized across hosts.\n-   It is critical to have RNG seeds that are the same across hosts (for model\n    initialization), and seeds that are different across hosts (for data\n    shuffling/preprocessing), so make sure to mark them appropriately.\n-   Sharding data files across hosts is usually recommended for improved\n    performance.\n\n## FAQs\n\n### What is the best learning rate decay schedule family?\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n-   It’s an open problem. It’s not clear how to construct a set of rigorous\n    experiments to confidently answer what the \"best\" LR decay schedule is.\n-   Although we don't know the best schedule family, we're confident that it’s\n    important to have some (non-constant) schedule and that tuning it matters.\n-   Different learning rates work best at different times during the\n    optimization process. Having some sort of schedule makes it more likely for\n    the model to hit a good learning rate.\n\n</details>\n\n### Which learning rate decay should I use as a default?\n\n<details><summary><em>[Click to expand]</em></summary>\n<br>\n\n-   Our preference is either linear decay or cosine decay, and a bunch of other\n    schedule families are probably good too.\n\n</details>\n\n### Why do some papers have complicated learning rate schedules?\n\n<details><summary><em>[Click to expand]</em></summary>\n<br>\n\n-   It’s not uncommon to see papers with complicated piecewise learning rate\n    (LR) decay schedules.\n-   Readers often wonder how the authors arrived at such a complicated schedule.\n-   Many complicated LR decay schedules are the result of tuning the schedule as\n    a function of the validation set performance in an ad hoc way:\n    1.  Start a single training run with some simple LR decay (or a constant\n        learning rate).\n    2.  Keep training running until the performance seems to stagnate. If this\n        happens, pause training. Resume it with a perhaps steeper LR decay\n        schedule (or smaller constant learning rate) from this point. Repeat\n        this process until the conference/launch deadline.\n-   Blithely copying the resulting *schedule* is generally not a good idea since\n    the best particular schedule will be sensitive to a host of other\n    hyperparameter choices.\n    -   Better to copy the *algorithm* that produced the schedule, although this\n        is rarely possible when arbitrary human judgment produced the schedule.\n-   This type of validation-error-sensitive schedule is fine to use if it can be\n    fully automated, but human-in-the-loop schedules that are a function of\n    validation error are brittle and not easily reproducible, so we recommend\n    avoiding them.\n    -   Before publishing results that used such a schedule, please try to make\n        it fully reproducible.\n\n</details>\n\n### How should Adam’s hyperparameters be tuned?\n\n<details><summary><em>[Click to expand]</em></summary>\n<br>\n\n-   As discussed above, making general statements about search spaces and how\n    many points one should sample from the search space is very difficult. Note\n    that not all the hyperparameters in Adam are equally important. The\n    following rules of thumb correspond to different \"budgets\" for the number of\n    trials in a study.\n    -   If < 10 trials in a study, only tune the (base) learning rate.\n    -   If 10-25 trials, tune learning rate and $\\beta_1$.\n    -   If 25+ trials, tune the learning rate, $\\beta_1$ and $\\epsilon$.\n    -   If one can run substantially more than 25 trials, additionally tune\n        $\\beta_2$.\n\n</details>\n\n### Why use quasi-random search instead of more sophisticated black box optimization algorithms during the exploration phase of tuning?\n\n<details><summary><em>[Click to expand]</em></summary>\n\n-   Quasi-random search (based on\n    [low-discrepancy sequences](https://en.wikipedia.org/wiki/Low-discrepancy_sequence))\n    is our preference over fancier black box optimization tools when used as\n    part of an iterative tuning process intended to maximize insight into the\n    tuning problem (what we refer to as the \"exploration phase\"). Bayesian\n    optimization and similar tools are more appropriate for the exploitation\n    phase.\n-   Quasi-random search based on randomly shifted low-discrepancy sequences can\n    be thought of as \"jittered, shuffled grid search\", since it uniformly, but\n    randomly, explores a given search space and spreads out the search points\n    more than random search.\n-   The advantages of quasi-random search over more sophisticated black box\n    optimization tools (e.g. Bayesian optimization, evolutionary algorithms)\n    include:\n    1.  Sampling the search space non-adaptively makes it possible to change the\n        tuning objective in post hoc analysis without rerunning experiments.\n        -   For example, we usually want to find the best trial in terms of\n            validation error achieved at any point in training. But the\n            non-adaptive nature of quasi-random search makes it possible to find\n            the best trial based on final validation error, training error, or\n            some alternative evaluation metric without rerunning any\n            experiments.\n    2.  Quasi-random search behaves in a consistent and statistically\n        reproducible way.\n        -   It should be possible to reproduce a study from six months ago even\n            if the implementation of the search algorithm changes, as long as it\n            maintains the same uniformity properties. If using sophisticated\n            Bayesian optimization software, the implementation might change in\n            an important way between versions, making it much harder to\n            reproduce an old search. It isn’t always possible to roll back to an\n            old implementation (e.g. if the optimization tool is run as a\n            service).\n    3.  Its uniform exploration of the search space makes it easier to reason\n        about the results and what they might suggest about the search space.\n        -   For example, if the best point in the traversal of quasi-random\n            search is at the boundary of the search space, this is a good (but\n            not foolproof) signal that the search space bounds should be\n            changed. [This section](#identifying-bad-search-space-boundaries)\n            goes into more depth. However, an adaptive black box optimization\n            algorithm might have neglected the middle of the search space\n            because of some unlucky early trials even if it happens to contain\n            equally good points, since it is this exact sort of non-uniformity\n            that a good optimization algorithm needs to employ to speed up the\n            search.\n    4.  Running different numbers of trials in parallel versus sequentially will\n        not produce statistically different results when using quasi-random\n        search (or other non-adaptive search algorithms), unlike with adaptive\n        algorithms.\n    5.  More sophisticated search algorithms may not always handle infeasible\n        points correctly, especially if they aren't designed with neural network\n        hyperparameter tuning in mind.\n    6.  Quasi-random search is simple and works especially well when many tuning\n        trials will be running in parallel.\n        -   Anecdotally[^3], it is very hard for an adaptive algorithm to beat a\n            quasi-random search that has 2X its budget, especially when many\n            trials need to be run in parallel (and thus there are very few\n            chances to make use of previous trial results when launching new\n            trials).\n        -   Without expertise in Bayesian optimization and other advanced black\n            box optimization methods, we might not achieve the benefits they\n            are, in principle, capable of providing. It is hard to benchmark\n            advanced black box optimization algorithms in realistic deep\n            learning tuning conditions. They are a very active area of current\n            research, and the more sophisticated algorithms come with their own\n            pitfalls for inexperienced users. Experts in these methods are able\n            to get good results, but in high-parallelism conditions the search\n            space and budget tend to matter a lot more.\n-   That said, if our computational resources only allow a small number of\n    trials to run in parallel and we can afford to run many trials in sequence,\n    Bayesian optimization becomes much more attractive despite making our tuning\n    results harder to interpret.\n\n[^3]: Ben Recht and Kevin Jamieson\n    [pointed out](http://www.argmin.net/2016/06/20/hypertuning/) how strong\n    2X-budget random search is as a baseline (the\n    [Hyperband paper](https://jmlr.org/papers/volume18/16-558/16-558.pdf)\n    makes similar arguments), but it is certainly possible to find search\n    spaces and problems where state-of-the-art Bayesian optimization\n    techniques crush random search that has 2X the budget. However, in our\n    experience beating 2X-budget random search gets much harder in the\n    high-parallelism regime since Bayesian optimization has no opportunity to\n    observe the results of previous trials.\n\n</details>\n\n### Where can I find an implementation of quasi-random search?\n\n<details><summary><em>[Click to expand]</em></summary>\n<br>\n\n-   [Open-Source Vizier](https://github.com/google/vizier) has an [implementation\n    of quasi-random search](https://github.com/google/vizier/blob/main/vizier/_src/algorithms/designers/quasi_random.py). Set `algorithm=\"QUASI_RANDOM_SEARCH\"` in [this usage example](https://oss-vizier.readthedocs.io/en/latest/guides/user/running_vizier.html).\n-   An alternative implementation exists\n    [here](https://github.com/mlcommons/algorithmic-efficiency/blob/main/algorithmic_efficiency/halton.py).\n-   Both implementations above generate a Halton sequence for a given search space (intended to\n    implement a shifted, scrambled Halton sequence as recommended in\n    https://arxiv.org/abs/1706.03200).\n-   If a quasi-random search algorithm based on a low-discrepancy sequence is\n    not available, it is possible to substitute pseudo random uniform search\n    instead, although this is likely to be slightly less efficient.\n    -   In 1-2 dimensions, grid search is also acceptable, although not in\n        higher dimensions (see\n        [Bergstra & Bengio, 2012](https://www.jmlr.org/papers/v13/bergstra12a.html)).\n\n</details>\n\n### How many trials are needed to get good results with quasi-random search?\n\n<details><summary><em>[Click to expand]</em></summary>\n<br>\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/have_we_sampled_enough.png\" width=\"49%\" alt=\"A box plot showing the importance of sampling enough\">\n</p>\n\n<p align=\"center\"><b>Figure 3:</b> A ResNet-50 was tuned on ImageNet with 100\ntrials. Via bootstrapping, different amounts of tuning budget were simulated.\nBox plots of the best performances for each trial budget are plotted above.\n\n-   There is no way to answer this question in general, but we can look at\n    specific examples.\n-   As the Figure 3 shows, the number of trials in a study can have a\n    substantial impact on the results.\n    -   Notice how large the interquartile ranges are when 6 trials were\n        sampled, versus when 20 trials were sampled.\n    -   Even with 20 trials, it is likely that the difference between especially\n        lucky and unlucky studies will be larger than the typical variation\n        between re-trains of this model on different random seeds, with fixed\n        hyperparameters, which for this workload might be around +/- 0.1% on a\n        validation error rate of \\~23%.\n\n</details>\n\n### How can optimization failures be debugged and mitigated?\n\n<details><summary><em>[Click to expand]</em></summary>\n<br>\n\n\n***Summary:*** *If the model is experiencing optimization difficulties, it’s\nimportant to fix them before trying other things. Diagnosing and correcting\ntraining failures is an active area of research.*\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/stride_instability.png\" width=\"80%\" alt=\"Changing the strides in a single residual block in a WideResnet results in training instability.\">\n</p>\n\n\n<p align=\"center\"><b>Figure 4:</b> Changing the strides in a single residual block (2x2 -> 1x1) in a WideResnet results in training instability. This does not degrade performance at low learning rates, but high learning rates no longer train well due to the instability. Applying 1000 steps of learning rate warmup resolves this particular instance of instability, allowing stable training at max learning rate of .1.</p>\n\n#### Identifying unstable workloads\n\n-   Any workload will become unstable if the learning rate is too large.\n    Instability is only an issue when it forces us to use a learning rate that’s\n    too small.\n-   There are at least two types of training instability worth distinguishing:\n    1.  Instability at initialization/early in training.\n    2.  Sudden instability in the middle of training.\n-   We can take a systematic approach to identifying stability issues in our\n    workload.\n    1.  Do a learning rate sweep and find the best learning rate lr*.\n    2.  Plot training loss curves for learning rates just above lr*.\n    3.  If the learning rates > lr* show loss instability (loss goes up not down\n        during periods of training), then it is likely that fixing the\n        instability will result in better training.\n-   Log the L2 norm of the full loss gradient during training, outlier values\n    can result in spurious instability in the middle of training. This can\n    inform how to pick gradient/update clipping.\n\n**NOTE:** Some models show very early instability followed by a recovery that\nresults in slow but stable training. **Common evaluation schedules can miss\nthese issues by not evaluating frequently enough!**\n\nTo check for this, we can train for an abbreviated run of just \\~500 steps using\n`lr = 2 * current best`, but evaluate every step.\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/more_frequent_evals.png\" width=\"80%\" alt=\"Illustration of the value of more frequent evaluations at the start of\ntraining.\">\n</p>\n\n<p align=\"center\"><b>Figure 5:</b> Illustration of the value of more frequent evaluations at the start of training. Useful if there’s a suspicion that the model suffers from early training instability.</p>\n\n#### Potential fixes for common instability patterns\n\n-   Apply learning rate warmup\n    -   Best for early training instability.\n-   Apply gradient clipping\n    -   Good for both early and mid training instability, may fix some bad inits\n        that warmup cannot.\n-   Try a new optimizer\n    -   Sometimes Adam can handle instabilities that Momentum can’t. This is an\n        active area of research.\n-   We can ensure that we’re using best practices/initializations for our model\n    architecture (examples below).\n    -   Add residual connections and normalization if the model doesn't contain\n        it already.\n-   Normalization should be inside the residual. E.g. x + f(Norm(x)).\n-   Norm(x + f(x)) known to cause issues.\n-   Try initializing residual branches to 0 (e.g.\n    [ReZero init](https://arxiv.org/abs/2003.04887)).\n-   Lower the learning rate\n    -   This is a last resort.\n\n#### Learning rate warmup\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/instability_during_warmup.png\" width=\"80%\" alt=\"An example of instability during a warmup period (note the horizontal axis log\nscale).\">\n</p>\n\n<p align=\"center\"><b>Figure 6:</b> An example of instability during a warmup period (note the horizontal axis log scale). 40k steps of warmup was needed for successful training in this case.</p>\n\n##### When to apply learning rate warmup\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/axis_model_with_instability.png\" width=\"49%\" alt=\"Axis plot for model with instability\">\n</p>\n\n<p align=\"center\"><b>Figure 7a:</b> An example of a hyperparameter axis plot for a model exhibiting training instability. The best learning rate is at the edge of what is feasible. An \"infeasible\" trial is defined as one that either produces NaNs or uncharacteristically high values of the loss.</p>\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/loss_model_with_instability.png\" width=\"49%\" alt=\"Loss curve for model with instability\">\n</p>\n\n<p align=\"center\"><b>Figure 7b:</b> The training loss of a model trained with a learning rate where we see instability.</p>\n\n-   Figure 7a shows a hyperparameter axis plot that indicates a model\n    experiencing optimization instabilities, because the best learning rate is\n    right at the edge of instability.\n-   Figure 7b shows how this can be double-checked by examining the training\n    loss of a model trained with a learning rate either 5x or 10x larger than\n    this peak. If that plot shows a sudden rise in the loss after a steady\n    decline (e.g. at step \\~10k in the figure above), then the model likely\n    suffers from optimization instability.\n\n##### How to apply learning rate warmup\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/beneficial_effect_warmup.png\" width=\"80%\" alt=\"Beneficial effect of warmup on training instabilities\">\n</p>\n\n<p align=\"center\"><b>Figure 8:</b> Beneficial effect of learning rate warmup on addressing training instabilities.</p>\n\n-   Using the section immediately above, we assume that the practitioner has\n    already identified the learning rate at which the model becomes unstable.\n    This is the `unstable_base_learning_rate`.\n-   Warmup involves prepending a learning rate schedule that ramps up the\n    learning rate from 0 to some stable `base_learning_rate`, that is at least\n    one order of magnitude larger than `unstable_base_learning_rate`. The\n    default would be to try a `base_learning_rate` that’s 10x\n    `unstable_base_learning_rate`. Although note that it’d be possible to run\n    this entire procedure again for something like 100x\n    `unstable_base_learning_rate`. The specific schedule is:\n    -   Ramp up from 0 to `base_learning_rate` over `warmup_steps`.\n    -   Train at a constant rate for `post_warmup_steps`.\n-   Our goal is to find the shortest number of `warmup_steps` that allows us to\n    access peak learning rates that are much higher than\n    `unstable_base_learning_rate`.\n-   So for each `base_learning_rate`, we need to tune `warmup_steps` and\n    `post_warmup_steps`. It’s usually fine to set `post_warmup_steps` to be\n    `2*warmup_steps`.\n-   Warmup can be tuned independently of an existing decay schedule.\n    `warmup_steps` should be swept at a few different orders of magnitude. For\n    example, an example study could try [10, 10<sup>3</sup>, 10<sup>4</sup>,\n    10<sup>5</sup>]. The largest feasible point shouldn't be more than 10% of\n    `max_train_steps`.\n-   Once a `warmup_steps` that doesn't blow up training at `base_learning_rate`\n    has been established, it should be applied to the baseline model.\n    Essentially, we prepend this schedule onto the existing schedule, and use\n    the optimal checkpoint selection discussed above to compare this experiment\n    to the baseline. For example, if we originally had 10,000 `max_train_steps`\n    and did `warmup_steps` for 1000 steps, the new training procedure should run\n    for 11,000 steps total.\n-   If long `warmup_steps` are required for stable training (>5% of\n    `max_train_steps`), `max_train_steps` may need to be increased to account\n    for this.\n-   There isn't really a \"typical\" value across the full range of workloads.\n    Some models only need 100 steps, while others (particularly transformers)\n    may need 40k+.\n\n#### Gradient clipping\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/google-research/tuning_playbook/main/assets/gradient_clipping.png\" width=\"80%\" alt=\"Gradient clipping on early training instabilities\">\n</p>\n\n<p align=\"center\"><b>Figure 9:</b> Illustration of gradient clipping correcting early training instability.</p>\n\n-   Gradient clipping is most useful when large or outlier gradient issues\n    occur.\n-   Clipping can fix either early training instability (large gradient norm\n    early), or mid training instabilities (sudden gradient spikes mid training).\n-   Sometimes longer warmup periods can correct instabilities that clipping does\n    not: see [this section above](#How-to-apply-learning-rate-warmup).\n    -   🤖 What about clipping during warmup?\n-   The ideal clip thresholds are just above the \"typical\" gradient norm.\n-   Here’s an example of how gradient clipping could be done:\n    -   If the norm of the gradient $\\left | g \\right |$ is greater than the\n        gradient clipping threshold $\\lambda$, then do ${g}'= \\lambda \\times \\frac{g}{\\left | g \\right |}$ where ${g}'$ is the new gradient.\n-   Log the unclipped gradient norm during training. By default, generate:\n    -   A plot of gradient norm vs step\n    -   A histogram of gradient norms aggregated over all steps\n-   Choose a gradient clipping threshold based on the 90th percentile of\n    gradient norms.\n    -   The threshold will be workload dependent, but 90% is a good starting\n        point. If it doesn't work, this threshold can be tuned.\n    -   🤖 What about some sort of adaptive strategy?\n-   If we try gradient clipping and the instability issues remain, we can try it\n    harder (i.e. make the threshold smaller).\n-   Extremely aggressive gradient clipping is in essence a strange way of\n    reducing the learning rate. If we find ourselves using extremely aggressive\n    clipping, we probably should just cut the learning rate instead.\n-   We would usually consider having >50% of the updates getting clipped somehow\n    as \"extremely aggressive\".\n-   If we need to do extremely aggressive gradient clipping to deal with our\n    instability issues, then we might as well reduce the learning rate.\n\n</details>\n\n### Why do you call the learning rate and other optimization parameters hyperparameters? They are not parameters of any prior distribution.\n\n<details><summary><em>[Click to expand]</em></summary>\n<br>\n\n-   It is true that the term \"hyperparameter\" has a precise\n    [meaning](https://en.wikipedia.org/wiki/Hyperparameter) in Bayesian machine\n    learning and referring to the learning rate and most of the other parameters\n    we tune in deep learning as \"hyperparameters\" is an abuse of terminology.\n-   We would prefer to use the term \"metaparameter\" for learning rates,\n    architectural parameters, and all the other things we tune in deep learning,\n    since it avoids the potential for confusion that comes from misusing the\n    word \"hyperparameter\" (confusion that is especially likely when discussing\n    Bayesian optimization where the probabilistic response surface models have\n    their own true hyperparameters).\n-   Unfortunately, although potentially confusing, the term hyperparameter has become\n    extremely common in the deep learning community.\n-   Therefore, for a document, such as this one, intended for a wide audience\n    that includes many people who are unlikely to be aware of this technicality,\n    we made the choice to contribute to one source of confusion in the\n    field in hopes of avoiding another.\n-   That said, we might make a different choice when publishing a research\n    paper, and we would encourage others to use \"metaparameter\" instead in most\n    contexts.\n\n</details>\n\n### Why shouldn't the batch size be tuned to directly improve validation set performance?\n\n<details><summary><em>[Click to expand]</em></summary>\n<br>\n\n-   Changing the batch size *without changing any other details of the training pipeline* will often affect the validation set performance.\n-   However, the difference in validation set performance between two batch sizes typically goes away if the training pipeline is optimized independently for each batch size.\n-   The hyperparameters that interact most strongly with the batch size, and therefore are most important to tune separately for each batch size, are the optimizer hyperparameters (e.g. learning rate, momentum) and the regularization hyperparameters.\n    - Smaller batch sizes introduce more noise into the training algorithm due to sample variance, and this noise can have a regularizing effect. Thus, larger batch sizes can be more prone to overfitting and may require stronger regularization and/or additional regularization techniques.\n- In addition, [the number of training steps may need to be adjusted](#choosing-the-batch-size-to-minimize-training-time) when changing the batch size.\n-   Once all these effects are taken into account, there is currently no convincing evidence that the batch size affects the maximum achievable validation performance (see [Shallue et al. 2018](https://arxiv.org/abs/1811.03600)).\n\n</details>\n\n### What are the update rules for all the popular optimization algorithms?\n\n<details><summary><em>[Click to expand]</em></summary>\n\n<br>\n\n#### Stochastic gradient descent (SGD)\n\n$$\\theta_{t+1} = \\theta_{t} - \\eta_t \\nabla \\mathcal{l}(\\theta_t)$$\n\n#### Momentum\n\n$$v_0 = 0$$\n\n$$v_{t+1} = \\gamma v_{t} + \\nabla \\mathcal{l}(\\theta_t)$$\n\n$$\\theta_{t+1} = \\theta_{t} - \\eta_t v_{t+1}$$\n\n#### Nesterov\n\n$$v_0 = 0$$\n\n$$v_{t+1} = \\gamma v_{t} + \\nabla \\mathcal{l}(\\theta_t)$$\n\n$$\\theta_{t+1} = \\theta_{t} - \\eta_t( \\gamma v_{t+1} + \\nabla \\mathcal{l}(\\theta_{t}))$$\n\n#### RMSProp\n\n$$v_0 = 1 \\text{,} m_0 = 0$$\n\n$$v_{t+1} = \\rho v_{t} + (1 - \\rho) \\nabla \\mathcal{l}(\\theta_t)^2$$\n\n$$m_{t+1} = \\gamma m_{t} + \\frac{\\eta_t}{\\sqrt{v_{t+1} + \\epsilon}}\\nabla \\mathcal{l}(\\theta_t)$$\n\n$$\\theta_{t+1} = \\theta_{t} - m_{t+1}$$\n\n#### ADAM\n\n$$m_0 = 0 \\text{,} v_0 = 0$$\n\n$$m_{t+1} = \\beta_1 m_{t} + (1 - \\beta_1) \\nabla \\mathcal{l} (\\theta_t)$$\n\n$$v_{t+1} = \\beta_2 v_{t} + (1 - \\beta_2) \\nabla \\mathcal{l}(\\theta_t)^2$$\n\n$$b_{t+1} = \\frac{\\sqrt{1 - \\beta_2^{t+1}}}{1 - \\beta_1^{t+1}}$$\n\n$$\\theta_{t+1} = \\theta_{t} - \\alpha_t \\frac{m_{t+1}}{\\sqrt{v_{t+1}} + \\epsilon} b_{t+1}$$\n\n#### NADAM\n\n$$m_0 = 0 \\text{,} v_0 = 0$$\n\n$$m_{t+1} = \\beta_1 m_{t} + (1 - \\beta_1) \\nabla \\mathcal{l} (\\theta_t)$$\n\n$$v_{t+1} = \\beta_2 v_{t} + (1 - \\beta_2) \\nabla \\mathcal{l} (\\theta_t)^2$$\n\n$$b_{t+1} = \\frac{\\sqrt{1 - \\beta_2^{t+1}}}{1 - \\beta_1^{t+1}}$$\n\n$$\\theta_{t+1} = \\theta_{t} - \\alpha_t \\frac{\\beta_1 m_{t+1} + (1 - \\beta_1) \\nabla \\mathcal{l} (\\theta_t)}{\\sqrt{v_{t+1}} + \\epsilon} b_{t+1}$$\n\n</details>\n\n## Acknowledgments\n\n-   We owe a debt of gratitude to Max Bileschi, Roy Frostig, Zelda Mariet, Stan\n    Bileschi, Mohammad Norouzi, Chris DuBois and Charles Sutton for reading the\n    manuscript and providing valuable feedback.\n-   We reused some experimental data for several plots that were originally\n    produced by Naman Agarwal for other joint research.\n-   We would like to thank Will Chen for invaluable advice on the presentation of the document.\n-   We would also like to thank Rohan Anil for useful discussions.\n\n## Citing\n\n```\n@misc{tuningplaybookgithub,\n  author = {Varun Godbole and George E. Dahl and Justin Gilmer and Christopher J. Shallue and Zachary Nado},\n  title = {Deep Learning Tuning Playbook},\n  url = {http://github.com/google-research/tuning_playbook},\n  year = {2023},\n  note = {Version 1.0}\n}\n```\n\n## Contributing\n\n-   This is not an officially supported Google product.\n\n-   We'd love to hear your feedback!\n\n    -   If you like the playbook, please [leave a star](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars#starring-a-repository)! Or email\n        deep-learning-tuning-playbook \\[at\\] googlegroups.com. Testimonials help\n        us justify creating more resources like this.\n    -   If anything seems incorrect, please file an issue to start a discussion.\n        For questions or other messages where an issue isn't appropriate, please\n        open a new discussion topic on GitHub.\n\n-   As discussed in the preamble, this is a living document. We anticipate\n    making periodic improvements, both small and large. If you’d like to be\n    notified, please watch our repository (see [instructions](https://docs.github.com/en/account-and-profile/managing-subscriptions-and-notifications-on-github/setting-up-notifications/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)).\n\n-   Please don't file a pull request without first coordinating with the authors\n    via the issue tracking system.\n\n### Contributor License Agreement\n\nContributions to this project must be accompanied by a Contributor License\nAgreement (CLA). You (or your employer) retain the copyright to your\ncontribution; this simply gives us permission to use and redistribute your\ncontributions as part of the project. Head over to\n<https://cla.developers.google.com/> to see your current agreements on file or\nto sign a new one.\n\nYou generally only need to submit a CLA once, so if you've already submitted one\n(even if it was for a different project), you probably don't need to do it\nagain.\n\n### Code Reviews\n\nAll submissions, including submissions by project members, require review. We\nuse GitHub pull requests for this purpose. Consult\n[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more\ninformation on using pull requests.\n\n### Community Guidelines\n\nThis project follows\n[Google's Open Source Community Guidelines](https://opensource.google/conduct/).\n"
  }
]