<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andy Lo on Medium]]></title>
        <description><![CDATA[Stories by Andy Lo on Medium]]></description>
        <link>https://medium.com/@andylolu24?source=rss-9b10f678560b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tc1pCcaLoTNO-e9k2flVEA.jpeg</url>
            <title>Stories by Andy Lo on Medium</title>
            <link>https://medium.com/@andylolu24?source=rss-9b10f678560b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:51:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andylolu24/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Matrix Multiplication on GPU]]></title>
            <link>https://medium.com/data-science/matrix-multiplication-on-the-gpu-e920e50207a8?source=rss-9b10f678560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e920e50207a8</guid>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[matrix-multiplication]]></category>
            <dc:creator><![CDATA[Andy Lo]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 20:29:23 GMT</pubDate>
            <atom:updated>2023-10-10T15:51:43.037Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>How to achieve state-of-the-art matrix multiplication performance in CUDA.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KCCNpLV4mD063YOMiTdIA.png" /><figcaption>“A minimalist art taking inspiration from Matrix Multiplication, in the style of vaporwave” by DALLE-2</figcaption></figure><p>This blog came from a sudden realisation of how little I knew about how matrix multiplication works on the GPU. Having done so many ML projects, I feel like I ought to understand how the most important operation in ML works: What is this “Tensor Core” thing? Why does everyone say “<em>data movement is the bottleneck</em>”? How fast can GPUs actually go?</p><p>To answer these questions, I decided that I must go out of my PyTorch bubble and <strong>venture into the abyss of CUDA</strong>. I wrote this blog to document all that I have learnt, and hopefully anyone reading this wouldn’t have to go through the pain of digging through CUDA docs/code as I did.</p><p>If there is anything that I’ve learnt in this journey, it is <strong>concurrent matrix multiplication is HARD</strong>. Efficient matrix multiplication heavily depends on the specific hardware you are using and the problem size you are trying to solve. There is no one-size-fits-all solution.</p><p>Enough nagging, let’s dig in!</p><h3>Recap on GPU architecture</h3><p>Let’s remind ourselves how (NVIDIA) GPUs work. A GPU achieves parallelism by running many <strong>threads</strong>. Each thread is executed on a single CUDA core, though at a given time, only a subset of the threads are active so there can be many more threads than CUDA cores available. Each thread, no matter it is active or not, has its own set of <strong>registers</strong>.</p><p>A group of 32 threads is known as a <strong>warp</strong>. All threads in a warp must execute together (or be inactive together). In most cases, there are a lot more inactive warps than active warps, and the <strong>warp scheduler</strong> is responsible for choosing which warps to execute at a given time. This allows the GPU to hide the latency of memory accesses by scheduling other warps to execute while a warp is waiting for data.</p><p>A group of warps is known as a <strong>threadblock</strong>. All warps in a threadblock are executed in the same <strong>Streaming Multiprocessor</strong> (SM). Each threadblock has its own <strong>shared memory</strong> that can be accessed by all threads in the threadblock.</p><blockquote><strong>Note: Newer architectures</strong></blockquote><blockquote>From Volta architecture onwards, each thread also has its own program counter and call stack etc. This means that each thread in a warp can execute different instructions at the same time.</blockquote><blockquote>The Volta architecture also introduced <strong>Tensor Cores</strong> that are specialised to solve matrix multiplications of specific sizes. Each active warp have access to one Tensor Core.</blockquote><blockquote>In the newest Hopper architecture, there is a concept of <strong>threadblock clusters</strong> that represents a group of threadblocks. It gives the user more fine-grained control over the scheduling of threadblocks and allows the shared memory of one threadblock to be access by other threadblocks in the same cluster.</blockquote><h3>Parallelising matrix multiplication</h3><p>Suppose we want to compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*E-hQsENZ6P0wC-kz.png" /></figure><p>We say that the problem size is (<em>M</em>, <em>N</em>, <em>K</em>) in this case. To parallelise this operation, we can split <em>A</em> and <em>B</em> into smaller matrices, matrix multiply them individually, and concatenate the results to form <em>C</em>.</p><p>Specifically, we can partition <em>A</em> row-wise (i.e., <em>M</em> into chunks of size <em>M’</em>) and <em>B</em> column-wise (i.e., <em>N</em> into chunks of size <em>N’</em>) to give:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*j8TH9ybT7RjGzhJG.png" /></figure><p>We can see that each sub-matrix in <em>C</em> are independent of each other, so we can easily parallelise the computation of each sub-matrix.</p><p>In practice, <em>K</em> might be too large to directly load into memory and compute on. Instead, a typical implementation will also split <em>K</em> into chunks of size <em>K’</em>, iterate over each chunk, and accumulate (by summing) over the partial results. This is known as serial-<em>K</em> reduction. (As opposed to <em>parallel-K reduction</em>, see section below). Mathematically, this looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*7dkHFjSmJoQpzxxG.png" /></figure><blockquote><strong>Note: Padding</strong></blockquote><blockquote>At any point where the problem size is not divisible by the partition size, we need to add <strong>padding</strong>. This is typically done implicitly when we load the partitioned inputs (𝐴ᵢ,ₖ and 𝐵ₖ,ⱼ) into lower-level memory where we ensure the loaded partition (of size M’×K’ for 𝐴ᵢ,ₖ and K’×N’ for 𝐵ₖ,ⱼ) is always “full” by adding zeros. Special care needs to be taken when writing the results back to global memory to avoid out-of-bounds errors.</blockquote><p>On a high level, <strong>three nested partitions</strong> happen to parallelise matrix multiplication on the GPU:<br>1. The first partition happens on the <strong>threadblock</strong> level. Each threadblock is responsible for computing <em>Cᵢ,ⱼ = Aᵢ Bⱼ.</em><br>2. The second partition happens on the <strong>warp</strong> level. The threadblock-level problem <em>Cᵢ,ⱼ</em> is further partitioned such that each warp is responsible for computing <em>Cᵢ,ⱼ⁽ᵐⁿ⁾ = Aᵢ⁽ᵐ⁾ Bⱼ⁽ⁿ⁾</em>.<br>3. The third partition happens on the <strong>instruction</strong> level. Some instructions expect inputs of particular sizes. For example, second-generation Tensor Cores operate on problems of size (16, 8, 8) for <em>fp16</em>, whereas a direct implementation on CUDA cores by scalar multiplication would simply operate on size (1, 1, 1). The warp-level problem is thus even further partitioned such that each chunk has a suitable size for the instruction: <em>Cᵢ,ⱼ⁽ᵐⁿ⁾⁽ᵃᵇ⁾ = Aᵢ⁽ᵐ⁾⁽ᵃ⁾ Bⱼ⁽ⁿ⁾⁽ᵇ⁾.</em></p><p>There’s a good reason why we need three partition levels, as we will see in the next section.</p><h3>Data redundancy</h3><p>Matrix multiplication can easily become memory-bound if we naively re-fetch data from global memory to registers every time we perform a computation. The key observation is that many of the sub-inputs <em>Aᵢ</em> and <em>Bⱼ</em> are reused across different sub-matrix multiplications. For example, <em>Aᵢ</em> is required for <em>Cᵢ,₁ , Cᵢ,₂ </em>, ... and <em>Bⱼ</em> is required for <em>C</em>₁<em>,ⱼ </em>, <em>C</em>₂<em>,ⱼ </em>, … . We can get the best throughput if we can minimise redundant data movement and reuse the loaded data as much as possible.</p><p>In CUDA, there are three types of user-accessible memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*_RiB46vFjPHNsoFVJ-xAKQ.png" /></figure><p>Here’s a high-level view of how each memory type is utilised:</p><ol><li>Each threadblock will first load its required inputs <strong>from global memory into shared memory</strong>. Subsequent accesses to those data would thus be served by the shared memory instead of by the slower global memory.</li><li>Within each threadblock, each warp will first load its required inputs <strong>from shared memory into registers</strong>. Subsequent accesses to those data would be served by the fast registers directly.</li></ol><h3>Diving into the details</h3><h4>Threadblock level</h4><p>On the threadblock level, the problem is partitioned into sub-problems of size (<em>M’</em>, <em>N’</em>, <em>K’</em>). Thus, each threadblock is responsible for computing a fragment of <em>C</em>, denoted as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*lxoWLzRE0IeW65Ul.png" /></figure><p>Redundant data movement is minimised by loading the sub-inputs <em>Aᵢ,ₖ </em>and<em> Bₖ,ⱼ </em>into shared memory. When we are done with computing <em>Aᵢ,ₖ Bₖ,ⱼ</em>, the next chunk (<em>Aᵢ,ₖ₊₁ </em>and<em> Bₖ₊₁,ⱼ</em>) will be loaded.</p><h4>Warp level</h4><p>On the warp level, the sub-problem is further partitioned into sub-sub-problems of size (<em>M’’, N’’, K’’</em>). Thus, each <em>warp</em> is responsible for computing a fragment of <em>Cᵢ,ⱼ, </em>denoted as <em>Cᵢ,ⱼ⁽ᵐ ⁿ⁾</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*PqH4Jo0oU3JqljwK.png" /></figure><p>Redundant data movement is minimised by loading the sub-sub-inputs <em>Aᵢ,ₖ⁽ᵐ ˡ⁾ and Bₖ,ⱼ⁽ˡ ⁿ⁾</em> into <strong>registers</strong>. Any accesses to <em>Aᵢ,ₖ⁽ᵐ ˡ⁾ </em>and <em>Bₖ,ⱼ⁽ˡ ⁿ⁾</em> <em>within</em> a warp will then be served by the fast registers.</p><blockquote><strong>Note: Distributing data across registers</strong></blockquote><blockquote>It is worth noting that registers are <strong>thread-level only</strong>. This means that inputs in a register cannot be accessed by other threads in a warp. The exact way of how Aᵢ,ₖ⁽ᵐ ˡ⁾<em> </em>and Bₖ,ⱼ⁽ˡ ⁿ⁾ are partitioned into the registers of each thread depends on the specific instruction used. The NVIDIA docs on <a href="https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#warp-level-matrix-instructions">Warp Level Matrix Multiply-Accumulate Instructions</a> gives a detailed description for each instruction.</blockquote><h4>Tensor core level</h4><p>To actually perform the matrix multiplication, we use the <strong>Tensor Cores</strong> on the GPU. My GPU (RTX 2060) has the second generation Tensor Cores, which are specialised to solve fp16 problems of size (<em>M’’’, N’’’, K’’’</em>) = (16, 8, 8). Thus, we even further partition <em>Cᵢ,ⱼ⁽ᵐ ⁿ⁾</em> to fit the size expected by the instruction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/0*2dzM2sMVLh3EdgBg.png" /></figure><p>Here, all the inputs are already in the registers and thus the data movement overhead is minimal.</p><blockquote><strong>Note: Tensor Cores</strong></blockquote><blockquote>Tensor Core operations are <strong>warp-level instructions</strong>, meaning that all the threads in a warp need to execute the Tensor Core instruction at the same time, collaboratively preparing the data to be consumed by <strong>one</strong> Tensor Core.</blockquote><h3>Choosing the partition sizes</h3><p>So, given that we want to minimise data movement, we should just choose a partition size as large as possible to utilise all of the shared memory and registers, <em>right?</em> Well, not quite.</p><h4>Threadblock partition size</h4><p>Asymptotically, as the problem size increases, yes, we do want to use as much shared memory and registers as possible. However, for small problem sizes, we might run into two problems:</p><ol><li>Have a large partition size means that we will have fewer threadblocks. Since each threadblock can only execute on one SM, this might mean that we cannot utilise all the SMs.</li><li>For problem sizes that are not divisible by the partition size, we will have to add more padding to the inputs. This lowers the efficiency as less computation will be done on meaningful inputs.</li></ol><p>A typical implementation might use a partition size of (<em>M’, N’, K’</em>) = (128, 256, 32).</p><h4>Warp partition size</h4><p>In general, having a large warp partition size means there will be less redundant data movement, but at the cost of having fewer warps. Having too few warps means that we will not be able to hide the latency of memory accesses (because we might run out of other warps to schedule while the current warp is waiting for data).</p><p>A typical implementation might use a partition size of (<em>M’’, N’’, K’’</em>) = (64, 64, 32).</p><h4>Instruction partition size</h4><p>This is completely determined by what instructions your GPU supports. For my RTX 2060, the ptx instruction for fp16 Tensor Core matrix multiplication (with fp16 accumulation) is mma.sync.aligned.m16n8k8.row.col.f16.f16.f16.f16, which expects inputs of size (16, 8, 8).</p><h3>Even more optimisations</h3><p>The above techniques can get us close to the theoretical peak performance of the GPU when the problem size is large. However, for smaller problem sizes, they are not as efficient. There are two common techniques to further improve the performance of matrix multiplication: <strong>parallel-K reduction</strong> and <strong>software pipelining</strong>.</p><h4>Parallel-K reduction</h4><p>In cases where <em>M</em> and <em>N</em> are small, we might only have a few threadblocks. For example, if (<em>M’, N’</em>) = (128, 256) and the original problem size has <em>M</em> ≤ 128 and <em>N</em> ≤ 256, we will only have one threadblock, and so we are only utilising a fraction of the GPU’s compute power! (For example, my RTX 2060 has 30 SMs, so to maximise utilisation we want at least 30 threadblocks.)</p><p>In cases where <em>K</em> is large (even though <em>M</em> and <em>N</em> are small), we can leverage more parallelism by doing <strong>parallel-<em>K</em> reduction</strong>. Recall that in serial-<em>K</em> reduction, each threadblock iterates over the following sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/0*FwfRwoil6BjyylcT.png" /></figure><p>and accumulates the intermediate results into <em>Cᵢ,ⱼ. </em>In parallel-<em>K</em> reduction, we instead assign each threadblock to only compute <em>one element of the sum</em> (i.e. <em>Aᵢ,ₖ Bₖ,ⱼ</em>). This allows us to increase the number of threadblocks by a factor of <em>K/K’</em>, thus utilising more SMs.</p><p>The caveat is that now, we need to <em>allocate more memory</em> to store the results from each threadblock, and <em>invoke a second kernel</em> to perform a final reduction over the partial results to get <em>Cᵢ,ⱼ</em>.</p><h4>Software pipelining</h4><p>Normally, CUDA hides the latency of memory accesses by scheduling other warps to execute while a warp is waiting for data. This requires us to have enough warps to mask the latency.</p><p>However, the number of warps is typically relatively small when doing GEMM. This is because the number of warps is limited by “The number of available registers per threadblock divided by the number of registers required per warp”. For matrix multiplication, we use a lot of registers per warp to maximise data reuse. As a result, we might not have enough warps to mask the latency.</p><blockquote>“The accumulator elements typically occupy at least half a thread’s total register budget”. — CUTLASS Docs</blockquote><p>To mitigate this effect, we can use <strong>software pipelining</strong>. In essence, we can (manually) pre-load the inputs for the next iteration of the loop asynchronously using special instructions. While the inputs are being loaded, we can continue to compute on the current iteration. It is summarised by the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*em_tn_dK1GiJNVU_" /><figcaption>Software Pipelining from <a href="https://github.com/NVIDIA/cutlass/blob/main/media/docs/efficient_gemm.md">CUTLASS</a></figcaption></figure><p>This is made possible by the fact that the GPU is like any modern CPU: it can pipeline memory accesses and arithmetic operations as long as there is no data dependency between them. This is known as <strong>instruction-level parallelism</strong>.</p><h3>Matrix multiplication in action</h3><p>If you want to see how all these concepts come together in a real implementation, check out my implementation of training MNIST from scratch with CUDA. There, I trained a multi-layer perceptron on MNIST using CUDA, achieving <strong>6x speedup over optimised PyTorch</strong> for hidden size of 128:</p><p><a href="https://github.com/andylolu2/cuda-mnist">GitHub - andylolu2/cuda-mnist</a></p><h3>References</h3><p>1. <a href="https://github.com/NVIDIA/cutlass/blob/main/media/docs/">CUTLASS docs</a><br>2. <a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html">CUDA docs</a><br>3. <a href="https://github.com/NVIDIA/cutlass/tree/main/examples">CUTLASS examples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e920e50207a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/matrix-multiplication-on-the-gpu-e920e50207a8">Matrix Multiplication on GPU</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weight Decay and Its Peculiar Effects]]></title>
            <link>https://medium.com/data-science/weight-decay-and-its-peculiar-effects-66e0aee3e7b8?source=rss-9b10f678560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/66e0aee3e7b8</guid>
            <category><![CDATA[bias-variance-tradeoff]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[weight-decay]]></category>
            <category><![CDATA[l2-regularization]]></category>
            <category><![CDATA[deep-double-descent]]></category>
            <dc:creator><![CDATA[Andy Lo]]></dc:creator>
            <pubDate>Sat, 18 Dec 2021 08:32:37 GMT</pubDate>
            <atom:updated>2021-12-20T08:08:10.973Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>How it works, why it works, and some practical tips.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UGNg5Q1Yxn1zGFmO" /><figcaption>Photo by <a href="https://unsplash.com/@goodfreephoto_com?utm_source=medium&amp;utm_medium=referral">Good Free Photos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>. We all like something smooth, don’t we?</figcaption></figure><h3>What is weight decay?</h3><p>Weight decay, sometimes referred to as L2 normalization (though they are not exactly the same, <a href="https://towardsdatascience.com/weight-decay-l2-regularization-90a9e17713cd">here is good blog post explaining the differences</a>), is a common way to regularize neural networks. It helps the neural networks to learn smoother / simpler functions which most of the time generalizes better compared to spiky, noisy ones.</p><p>There are many regularizers, weight decay is one of them, and it does it job by pushing (decaying) the weights towards zero by some small factor at each step.</p><p>In code, this is implemented as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3b1e19c057d9754275ec0a8ede3c9ee/href">https://medium.com/media/b3b1e19c057d9754275ec0a8ede3c9ee/href</a></iframe><p>where weight_decay is a hyperparameter with typical values ranging from 1e-5 to 1.</p><p>In practice, you do not have to perform this update yourself. For example, optimizers in PyTorch have a weight_decay parameter that handles all the updates for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecbffc1827ee77202ee59ddd59c1dbc9/href">https://medium.com/media/ecbffc1827ee77202ee59ddd59c1dbc9/href</a></iframe><h3>Intuition of weight decay</h3><p>But how does weight decay actually help the model? Under what circumstances should we use it?</p><p>First, we have to understand why sometimes models fail to generalize.</p><h4>Classical regime</h4><p>In classical machine learning theory, we believe that there exists an “under-fitting” and an “over-fitting” region.</p><figure><img alt="Classical regime graph" src="https://cdn-images-1.medium.com/max/835/1*dhf2-w3XPAROzm_dmI6Jxw.png" /><figcaption>Train and test loss against model capacity in the classical regime taken from <a href="https://arxiv.org/abs/1812.11118">“Reconciling modern machine learning practice and the bias-variance trade-off”</a></figcaption></figure><p>In the under-fitting region, the model is “too simple” to capture the structure of the data and so there will both <strong>high train error</strong> and <strong>high test error</strong>.</p><p>In the over-fitting region, the model has enough capacity where it can just memorize the training dataset without learning the underlying structure of the data, leading to <strong>low train error</strong> but<strong> high test error</strong>.</p><p>In either case, the model fails to generalize. The classical wisdom is that the best models lie between these two regions.</p><p>Weight decay here acts as a method to <strong>lower the model’s capacity</strong> such that an over-fitting model does not overfit as much and gets pushed towards the sweet spot. This also shows that weight decay will have a negative impact if the model is originally operating in the under-fitting region.</p><h4>Modern regime</h4><p>However, very recent research reveals a phenomenon called “Deep Double Descent” to show that there actually exists a <em>third</em> region. While classical theory says that further increasing model complexity results in higher test error, empirical evidence suggests that test error will drop as we go beyond the “over-fitting” region into the “over-parameterized” region.</p><figure><img alt="Deep Double Descent graph" src="https://cdn-images-1.medium.com/max/1024/1*LVh9JNMo8rt9L7kIjHtvRQ.png" /><figcaption>The full picture of train and test loss against model capacity taken from <a href="https://arxiv.org/abs/1812.11118">“Reconciling modern machine learning practice and the bias-variance trade-off”</a></figcaption></figure><p>Empirical evidence shows that such boundary (called the “interpolation threshold”) between the over-fitting and over-parameterized regions occurs when the model just barely has enough capacity to achieve <strong>(near-)zero training loss</strong>.</p><p>At the interpolation threshold, there is <strong>only one</strong> set of parameters that can interpolate the entire training set. It is most likely the case that such particular interpolation will be quite bumpy and spiky because most datasets involve some degree of noise. When the model is forced to fit on all the noise with just barely enough capacity, it does not have additional room to make the function smooth outside the noisy training points, and so generalizes poorly.</p><p>As we further increase the model capacity, not only can it perfectly hit the training data points, it also gets the additional capacity to choose functions that smoothly interpolate between the space in between, and thus generalize better.</p><p><em>This is the part where weight decay comes in.</em></p><p>Out of all the possible interpolations that the model can learn, <strong>we want to bias our model towards the smoother, simpler ones</strong> such that it is able to generalize. And weight decay does exactly that. This is why weight decay is so powerful.</p><p>Though not totally accurate, I think the following meme sums up our current understanding quite well.</p><figure><img alt="IQ curve meme" src="https://cdn-images-1.medium.com/max/1024/1*TVyR_wyJlstmKLPIGUqIYg.jpeg" /><figcaption>Totally original meme by me</figcaption></figure><h3>Toy experiment</h3><p>To test the above properties, I trained a simple feed-forward network with skip connections to learn to perform addition on binary-encoded numbers. You can find the full source code here:</p><p><a href="https://github.com/andylolu2/ml-weight-decay">GitHub - andylolu2/ml-weight-decay</a></p><p>It is trained on 2 and 4 digit addition and tested on 3 digit addition to measure its generalization ability. Here is a sample training point:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b34efc574894f0f1eaf96c344fc31b0/href">https://medium.com/media/6b34efc574894f0f1eaf96c344fc31b0/href</a></iframe><p>My model consists 2 residual blocks, each with width 256, summing up to a total of 300K parameters, which would almost definitely operate within the “over-parameterized” region. I trained it for various values of the weight decay factor and here is a plot of it against the train and test accuracy:</p><figure><img alt="Plot of accuracy against weight decay factor λ" src="https://cdn-images-1.medium.com/max/1024/1*hwl1KqT4iXx-jBTEkcDqqQ.png" /><figcaption>Plot of accuracy against weight decay factor λ in my toy experiment</figcaption></figure><p>We can see that for this model, suitable values of λ is around 0.1.</p><p>On the left-hand side, where λ is too low, the model totally has enough capacity to fit the training dataset but is not biased towards finding simpler interpolations, so the test accuracy is very low.</p><p>On the right-hand side, where λ is too high, the model gets restricted too much by being forced to use very small weights so that it is not expressive enough to even fit the training data. Thus, both the train and test accuracy are low.</p><p>According to our intuition above, we expect to see a dip in test accuracy at the interpolation threshold — but we don’t. Why?</p><p>My best guess is because our dataset is totally noise-free and so that particular set of weights at the interpolation threshold does not get messed up and ends up generalizing well.</p><p>Just to further illustrate how important weight decay is in helping the model generalize, here are the training curves for the model with λ = 0.1:</p><figure><img alt="Training curves for λ = 0.1" src="https://cdn-images-1.medium.com/max/1024/1*EXUIrb5HwqFraJ1j-6TRMw.png" /><figcaption>Training curves for λ = 0.1 in my toy experiment</figcaption></figure><p>In the first 3665 steps, the model is able to achieve 100% accuracy with almost zero training loss. However, the test accuracy is still very low.</p><p>Over the course of the next 25K steps, it continues to minimize the weight norm (the sum of the squared model weights) while keeping a perfect train accuracy. This corresponds to finding to simpler interpolation for the training data, and we can clearly see a correlation between that and the increase in test accuracy.</p><p>Simpler interpolations = profit!</p><h3>Picking the right value</h3><p>OK, so weight decay is pretty useful. Now how can I pick the right <br>values of λ?</p><p>In general, there is no golden rule to picking the value of weight decay. Some trial and error is unavoidable. However, there are some rules that you can follow. Researchers proposing the AdamW optimizer has suggested the following rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*GOtpymM7W2bd47ipbM8AKQ.jpeg" /><figcaption>Normalized weight decay factor formula proposed in <a href="https://arxiv.org/abs/1711.05101">“Decoupled Weight Decay Regularization”</a></figcaption></figure><p>where <em>b</em> the batch size, <em>B</em> is the total number of training points, and <em>T</em> is the total number of epochs. Now the new hyperparameter to tune is <em>λ_norm</em>.</p><p>So they just replaced a hyperparameter with another hyperparameter… Hmm… How is this useful??</p><p>Well, it helps because the decouples the choices of <em>b</em>, <em>B</em> and <em>T</em> from the suitable weight decay value so it makes it easier to tune hyperparameters.</p><p>Though, you would still need search for good values of <em>λ_norm</em>. The authors found <em>λ_norm</em> in the range of 0.025 to 0.05 to be optimal for their networks trained on image classification. Maybe this can act as a useful starting point.</p><h3>Problems with batch normalization</h3><p>Nowadays we almost always put batch norm layers into our neural networks because it speeds up the training a lot. However, while I’m running my experiments, I often see this weird behavior of periodic fluctuations when I use batch norm layers with weight decay.</p><figure><img alt="Period fluctuations when training with batch norm and weight decay in my experiments" src="https://cdn-images-1.medium.com/max/1024/1*QqKseoCKe4XAqaAolKPFvA.png" /><figcaption>Weird period fluctuations when training with batch norm and weight decay with the default values in my toy experiment</figcaption></figure><p>It is certainly not the first time that I’ve seen this behavior. It seems like these fluctuations starts to appear when the model is about to converge. So what is causing it?</p><p>I turned to Google for answers and came across this paper:</p><p><a href="https://arxiv.org/abs/2106.15739">On the Periodic Behavior of Neural Network Training with Batch Normalization and Weight Decay</a></p><p>In summary, it has to do with how batch norm layers work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*uFo5qi7kCRoZRREdvpBDww.jpeg" /><figcaption>Equation of batch norm layer inspired by <a href="https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm1d.html?highlight=batch%20norm#torch.nn.BatchNorm1d">PyTorch Doc</a></figcaption></figure><p>The above shows the formula for how batch norm computes its outputs. Here, <em>x</em> is a feature with dimensions <em>(batch_size, 1)</em>. Crucially, it divides the values by the square root of the sum of the variance of <em>x</em> and some small value epsilon ϵ.</p><p>When we use weight decay, some weights gradually get pushed to zero. As the weight approaches zero, the value of <em>x </em>will also approach zero (or a constant value) no matter what inputs it gets from the previous layer.</p><p>As a result, the Var[<em>x</em>] across the batch becomes tiny such that when we pass that it to the batch norm layer, it divides it by a near-zero value, causing the final output to blow up. This causes the huge fluctuations as we see from the graph below.</p><p>After it blows up, the weight gets updated to some large value due to the huge gradient at that step, so the variance becomes high again. Again, the weight will start to decay, and the process repeats itself creating the periodic pattern.</p><p>In a practical point of view, to avoid such instabilities, I found that simply increasing the value of epsilon to something larger (like 1e-2 instead of the PyTorch default of 1e-5) works surprisingly well.</p><p>Just another useful thing to keep at the back of your head.</p><h3>Summary</h3><p>Weight decay is a regularization method to make models generalize better by learning smoother functions. In the classical (under-parameterized) regime, it helps to restrict models from over-fitting, while in the over-parameterized regime, it helps to guide models towards simpler interpolations. In practice, there is a sweet range of weight decay values that work the best.</p><p>Hope you found this blog useful!</p><h3>Code</h3><p><a href="https://github.com/andylolu2/ml-weight-decay">GitHub - andylolu2/ml-weight-decay</a></p><h3>References</h3><ol><li>Preetum Nakkiran, Gal Kaplun, Yamini Bansal, Tristan Yang, Boaz Barak, Ilya Sutskever. <a href="https://arxiv.org/abs/1912.02292"><em>Deep Double Descent: Where Bigger Models and More Data Hurt</em></a>. 2019. arXiv:1912.02292</li><li>Mikhail Belkin, Daniel Hsu, Siyuan Ma, Soumik Mandal. <a href="https://arxiv.org/abs/1812.11118"><em>Reconciling modern machine learning practice and the bias-variance trade-off</em></a>. 2019. arVix:1812.11118</li><li>Ekaterina Lobacheva, Maxim Kodryan, Nadezhda Chirkova, Andrey Malinin, Dmitry Vetrov. <a href="https://arxiv.org/abs/2106.15739"><em>On the Periodic Behavior of Neural Network Training with Batch Normalization and Weight Decay</em></a>. 2021. arVix:2106.15739</li><li>Ilya Loshchilov, Frank Hutter. <a href="https://arxiv.org/abs/1711.05101"><em>Decoupled Weight Decay Regularization</em></a>. 2019. arVix:1711.05101</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66e0aee3e7b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/weight-decay-and-its-peculiar-effects-66e0aee3e7b8">Weight Decay and Its Peculiar Effects</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>