<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.3.4">Jekyll</generator><link href="https://wenwenkong.github.io/feed.xml" rel="self" type="application/atom+xml"/><link href="https://wenwenkong.github.io/" rel="alternate" type="text/html" hreflang="en"/><updated>2026-09-28T16:32:37+00:00</updated><id>https://wenwenkong.github.io/feed.xml</id><title type="html">blank</title><subtitle># add description here if you want </subtitle><entry><title type="html">Swin Transformer Notes</title><link href="https://wenwenkong.github.io/blog/2026/Swin-notes/" rel="alternate" type="text/html" title="Swin Transformer Notes"/><published>2026-09-27T00:00:00+00:00</published><updated>2026-09-27T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2026/Swin-notes</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2026/Swin-notes/"><![CDATA[<p>This post covers the essence of the Swin Transformer (Liu et al., 2021). In the original work, the authors found that</p> <blockquote> <p>The proposed Swin Transformer achieves strong performance on the recognition tasks of image classification, object detection, and semantic segmentation.</p> </blockquote> <p>Rather than going into the experimental details, this post focuses on the core ideas behind the model. In a nutshell, Swin Transformer is a <strong>hierarchical transformer</strong> whose representations are computed using <strong>s</strong>hifted <strong>win</strong>dows - that’s where its name (“<strong>S</strong>hifted <strong>Win</strong>dow <strong>Transformer</strong>”) comes from. The hierarchical design and the window-based self-attention with shifted windows are the two key structures of Swin that we will walk through in more detail later.</p> <hr/> <h2 id="motivation"><strong>Motivation</strong></h2> <p>Transformer is the default backbone of NLP applications: the same basic architecture can power language modeling, translation, question answering, and many other tasks. In computer vision, CNNs play a similar “general-purpose backbone” role. The Swin Transformer paper sets out to close this gap:</p> <blockquote> <p>In this paper, we seek to expand the applicability of Transformer such that it can serve as a general-purpose backbone for computer vision, as it does for NLP and as CNNs do in vision.</p> </blockquote> <p>However, it’s challenging to transfer Transformer’s high performance in the language domain to the vision domain. The challenge comes from differences between the two modalities: <strong>scale</strong> and <strong>resolution</strong>.</p> <h3 id="scale-challenge">Scale challenge</h3> <p>For typical sentence-level NLP tasks, Transformers operate on a single scale of tokens in a 1D sequence and do not rely on explicit multi-scale representations.<sup id="fnref:nlp-hier" role="doc-noteref"><a href="#fn:nlp-hier" class="footnote" rel="footnote">1</a></sup> In contrast, visual elements can vary substantially in scale: small textures, medium-sized objects, large structures. Classical CNN backbones such as ResNet (He et al., 2016), often combined with a feature pyramid network (FPN; Lin et al., 2017), handle this wide range of scales using <strong>hierarchical feature maps</strong> that gradually reduce spatial resolution while increasing channel depth. ViT (see more in <a href="https://wenwenkong.com/blog/2025/ViT-notes/">this post</a>), on the other hand, uses fixed-sized patches throughout the network and keeps a single feature resolution (see Figure 1b). Though this works well for image classification, in its original form (Dosovitskiy et al., 2021) it is not well suited as a general-purpose backbone for dense prediction tasks such as object detection or semantic segmentation.<sup id="fnref:vit-variants" role="doc-noteref"><a href="#fn:vit-variants" class="footnote" rel="footnote">2</a></sup></p> <h3 id="resolution-challenge">Resolution challenge</h3> <p>Images are also much higher resolution than typical text sequences. Standard self-attention has \(O(N^2)\) complexity in the number of tokens \(N\), because it computes interactions between all pairs of tokens. As a result, applying global self-attention at high resolution quickly becomes prohibitively expensive, especially for dense tasks that need fine spatial detail at the pixel level.</p> <h3 id="how-swin-addresses-these-challenges">How Swin addresses these challenges</h3> <p>Swin Transformer is designed around these challenges. It introduces a <strong>hierarchical representation</strong> to handle scale variation, and <strong>window-based self-attention with shifted windows</strong> to make attention feasible at high resolution - reducing the computational complexity from quadratic in the number of tokens to approximately linear - while still allowing information to flow across the image.</p> <hr/> <h2 id="core-ideas">Core ideas</h2> <p>In this section, we introduce Swin’s two structural ideas: <strong>hierarchical representation</strong> and <strong>shifted windows</strong>. We also explain why Swin achieves an approximate <strong>linear computational complexity</strong>.</p> <h3 id="hierarchical-representation">Hierarchical representation</h3> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/swin_notes/1_Swin_vs_ViT-480.webp 480w,/assets/img/posts/swin_notes/1_Swin_vs_ViT-800.webp 800w,/assets/img/posts/swin_notes/1_Swin_vs_ViT-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/swin_notes/1_Swin_vs_ViT.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> Swin builds a hierarchical feature pyramid by merging patches in deeper stages (gray grids), similar to CNN backbones. Compared to ViT’s single-scale feature map, this multi-stage structure supports multi-scale visual patterns (adapted from Liu et al., 2021). </div> <p>The gray grids in Figure 1a represent patch-level feature maps at different spatial resolutions. Shallow layers contain many patch tokens arranged at a higher resolution. As neighboring tokens are merged, deeper layers contain fewer, coarser patch tokens, where each token represents a larger area of the original image and typically has a larger embedding dimension. This progression from high-resolution, fine-grained features to low-resolution, more abstract features is what we mean by a <strong>hierarchical feature representation</strong>.</p> <p>The red boxes represent the local windows within which self-attention is computed. Instead of attending over all patches globally, Swin partitions the feature map into these red-outlined local windows, and applies self-attention only inside each window. This greatly reduces the computational cost compared with global attention.</p> <p>In summary, Swin combines a CNN-like feature hierarchy with local window-based attention, giving it both multi-scale representations and efficient computation. Here, the gray grids show what the representation consists of (i.e. the spatial grid of patch tokens), while the red boxes show where self-attention is computed (i.e. within local windows over those tokens).</p> <p>Figure 2 provides an alternative visualization of the architectural differences between ViT and Swin Transformer.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/swin_notes/2_Swin_vs_ViT-480.webp 480w,/assets/img/posts/swin_notes/2_Swin_vs_ViT-800.webp 800w,/assets/img/posts/swin_notes/2_Swin_vs_ViT-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/swin_notes/2_Swin_vs_ViT.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 2.</b> An alternative visualization of the architectural differences between ViT and Swin Transformer (adapted from Arkin et al., 2022). </div> <h3 id="why-window-based-attention-scales-linearly">Why window-based attention scales linearly</h3> <p>We mentioned above that Swin’s self-attention is much cheaper than global self-attention. This efficiency comes from limiting self-attention to fixed-sized local windows. To understand why, let us introduce some notation:</p> <ul> <li>\(N\): the total number of tokens (gray patches in Figure 1a) in the feature map at a given stage</li> <li>\(M\): the side length of each window</li> <li>\(M^2\): number of tokens in each local attention window (red boxes in Figure 1a). For example, the original Swin paper sets the side length of \(M = 7\) by default, so each \(7 \times 7\) window contains \(M^2 = 49\) tokens.</li> <li>Note: <ul> <li>Each token corresponds to a progressively larger region of the original image at deeper stages due to patch merging.</li> <li>Swin tiles the feature map with \(N/M^2\) non-overlapping windows, with each token belonging to exactly one window.</li> </ul> </li> </ul> <p><strong>Global self-attention (ViT-style)</strong></p> <p>In global self-attention, every token can attend to every other token. This means:</p> <ul> <li>We construct an \(N \times N\) attention matrix, where each entry represents the interaction between a pair of tokens.</li> <li>The pairwise-attention cost therefore scales like \(O(N^2)\).</li> </ul> <p>As image resolution increases while the patch size remains fixed, the image is divided into more patches and therefore produces more tokens (\(N\)). The quadratic cost of global self-attentil thus quickly becomes prohibitive for high-resolution feature maps.</p> <p><strong>Window-based self-attention (Swin)</strong></p> <p>Swin changes the picture by restricting attention to local windows:</p> <ul> <li>The feature map is partitioned into \(N/M^2\) non-overlapping windows, each with \(M^2\) tokens.</li> <li>Within each window, we compute self-attention only among those \(M^2\) tokens. The cost per window is: \(O({M^2}^2) = O(M^4)\)</li> <li>Across the whole feature map, the total cost becomes: \((N/M^2) \times O(M^4) = O(NM^2)\)</li> </ul> <p>Here, \(M\) (the side length of each window) is a fixed hyperparameter of the model (e.g., always \(7×7\) in the original Swin paper). It does not grow with image size. As we increase image resolution, \(N\) increases (i.e. more gray patches), but \(M^2\) (i.e. the number of tokens per window) stays the same. Therefore, <strong>for a fixed window size, the self-attention cost grows approximately linearly with the number of tokens, instead of quadratically as in global self-attention.</strong></p> <p>Note: The full complexity expressions in Equations (1) and (2) of Liu et al. (2021) also include the linear projections used to compute queries \((Q)\), keys \((K)\), values \((V)\), and attention output. These projection costs are the same for global and window-based attention. The simplified derivation here focuses on the pairwise-attention term, which is where their computational complexities differ.</p> <h3 id="shifted-window">Shifted window</h3> <p>Though Swin can reduce cost by restricting attention to local windows, that creates an isolation problem: tokens in different windows cannot interact within the same attention block. Swin addresses this in the following Swin Transformer block at the same stage using the shifted window approach, allowing information to flow across window boundaries.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/swin_notes/3_shifted_window-480.webp 480w,/assets/img/posts/swin_notes/3_shifted_window-800.webp 800w,/assets/img/posts/swin_notes/3_shifted_window-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/swin_notes/3_shifted_window.jpg" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 3.</b> Window-based and shifted window self-attention. In one layer, self-attention is computed only within non-overlapping local windows (red boxes). In the next layer, the windows are shifted so that tokens can attend across previous window boundaries (reproduced from Liu et al. 2021). </div> <h4 id="how-shifted-window-enables-cross-window-communication">How shifted window enables cross-window communication</h4> <p>Figure 3 illustrates how shifting the window partition between two consecutive blocks enables cross-window communication. In one block (\(L\)), Swin computes self-attention within non-overlapping windows. In the following block (\(L + 1\)) at the same stage, Swin shifts the window partition by half-window size in all directions, resulting in new windows that cross the previous window boundaries. As a result, some tokens that previously belonged to separate windows now appear in the same shifted window and attend to one another.</p> <p>The window partition alternates between these two configurations across consecutive blocks. Thus, block (\(L+2\)) returns to the regular window partition used in (\(L\)), while block (\(L+3\)) uses the shifted partition again, as in (\(L+1\)). In other words, the shift does not accumulate across blocks. In practice, Swin implements the shifted-window configuration using a cyclic shift and an attention mask, which we will discuss in the Architecture section.</p> <h4 id="sliding-windows-vs-shifted-windows">Sliding windows vs shifted windows</h4> <p>How does the shifted-window mechanism differ from sliding-window attention (Ramachandran et al., 2019)? Although both restrict self-attention to local neighborhoods, they differ in how those neighborhoods are defined and organized. In Swin, the feature map is partitioned into non-overlapping windows, and all query tokens within the same window share the same set of key and value tokens. In contrast, in sliding-window self-attention, the local neighborhood is centered on each query token, so different queries attend to different sets of keys and values. Figures 4-5 illustrate this distinction.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/swin_notes/4_Query_centered_attention-480.webp 480w,/assets/img/posts/swin_notes/4_Query_centered_attention-800.webp 800w,/assets/img/posts/swin_notes/4_Query_centered_attention-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/swin_notes/4_Query_centered_attention.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 4.</b> Query-centered local self-attention. For each query, attention is computed only over a local spatial neighborhood centered on that query. If the query position changes, its neighborhood moves with it. Adapted from Figures 1 and 3 of Ramachandran et al. (2019). </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/swin_notes/5_sliding_vs_shifted_windows-480.webp 480w,/assets/img/posts/swin_notes/5_sliding_vs_shifted_windows-800.webp 800w,/assets/img/posts/swin_notes/5_sliding_vs_shifted_windows-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/swin_notes/5_sliding_vs_shifted_windows.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 5.</b> Visual comparison of (a) sliding-window, (b) window-based, and (c) shifted-window self-attention. In sliding-window attention, the local neighborhood moves with the query. In window-based attention, queries within the same non-overlapping window share a common key and value set. Swin shifts the window partition between consecutive blocks to enable cross-window communication. Panel (c) previews the cyclic-shift operation used to implement this shifted partition, which will be discussed in the Architecture section. Adapted from Hassani et al. (2023), Neighborhood Attention Transformer, CVPR 2023 presentation slides. </div> <h2 id="architecture">Architecture</h2> <p>In this section, we explore how the core ideas are assembled into the actual Swin backbone.</p> <h3 id="overall-architecture">Overall architecture</h3> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/swin_notes/6_Swin_architecture-480.webp 480w,/assets/img/posts/swin_notes/6_Swin_architecture-800.webp 800w,/assets/img/posts/swin_notes/6_Swin_architecture-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/swin_notes/6_Swin_architecture.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 6.</b> Overall architecture of the Swin Transformer. The left panel shows the four hierarchical stages and patch-merging layers, and the right panel expands two successive Swin Transformer blocks, illustrating the alternation between W-MSA and SW-MSA. Reproduced from Liu et al. (2021). </div> <p>Let’s first have a high-level overview of the Swin model architecture. Figure 6 (reproduced from Figure 3 of Liu et al. 2021) covers the main pieces, and we will unpack the key components below.</p> <p><strong>Stages</strong></p> <p>The original Swin Transformer models consist of four hierarchical stages, with spatial resolution progressively reduced between stages through patch merging (Figure 6a).</p> <p><strong>Patch size and embedding dimensions</strong></p> <p>Liu et al. (2021) use a patch size of \(4 \times 4\), each patch therefore contains \((4\times 4\times 3 = 48)\) raw pixel values. After patch partitioning, the image is represented as a grid of \((H/4 \times W/4)\) patches, each with a \(48-\)dimensional feature vector. A linear embedding layer then projects each patch vector into a learned \(C-\)dimensional feature vector, giving the input to Stage 1 a shape of \(H/4 \times W/4 \times C\). Note that here \(C\) plays conceptually the same role as the embedding dimension \(D\) in ViT.</p> <p><strong>Patch merging between stages</strong></p> <p>Patch merging reduces spatial resolution while increasing the embedding dimension. At each patch-merging layer, Swin groups neighboring tokens in fixed \(2\times 2\) blocks. This \(2\times 2\) grouping is a design choice that gives a natural \(2\times\) spatial downsampling in both height and width, similar to stride-2 downsampling in a CNN.</p> <p>If the incoming tokens at a given stage have embedding dimension \(d\), where \(d\) is used here as a generic notation for that stage’s current embedding dimension, the four \(d\)-dimensional token vectors are concatenated into a \(4d\)-dimensional vector and then linearly projected to \(2d\). Thus, each patch-merging step halves the spatial resolution in both directions while doubling the embedding dimension.</p> <p>Therefore, starting with embedding dimension \(C\) in Stage 1, repeated patch-merging produces the following stage-wise progression:</p> \[\frac{H}{4}\times\frac{W}{4}\times C \rightarrow \frac{H}{8}\times\frac{W}{8}\times 2C \rightarrow \frac{H}{16}\times\frac{W}{16}\times 4C \rightarrow \frac{H}{32}\times\frac{W}{32}\times 8C.\] <p><strong>Swin Transformer blocks</strong></p> <p>Each stage contains multiple Swin Transformer blocks; the number of blocks varies across Swin variants. Within each stage, successive blocks always alternate between W-MSA (window-based multi-head self-attention) and SW-MSA (shifted-window multi-head self-attention), as illustrated by the two consecutive blocks in Figure 6b.</p> <h3 id="cyclic-shifting">Cyclic shifting</h3> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/swin_notes/7_Cyclic_shift_schematic_diagram-480.webp 480w,/assets/img/posts/swin_notes/7_Cyclic_shift_schematic_diagram-800.webp 800w,/assets/img/posts/swin_notes/7_Cyclic_shift_schematic_diagram-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/swin_notes/7_Cyclic_shift_schematic_diagram.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 7.</b> Schematic of the cyclic-shift and masking mechanism. Reproduced from Wang et al. (2025). This schematic illustrates the same mechanism as Figure 4 of Liu et al. (2021), but presents it in a clearer way. </div> <p>We have seen conceptually how shifted windows enable cross-window communication (Figure 3). But directly implementing the shifted partition introduces an efficiency problem at the feature-map boundaries: it creates more windows, including smaller partial windows along the edges. For example, in the example shown in Figure 7, the number of windows increases from 4 to 9. Swin addresses this using cyclic shifting and attention masking.</p> <p>Cyclic shifting works by shifting the feature map toward the top-left by approximately half a window size \(M/2\), where \(M\) denotes the side length of each \(M\times M\) attention window. Tokens that cross the top boundary wrap to the bottom, those that cross the left boundary warp to the right, and those that cross both wrap to the bottom-right (Figure 7). This rearrangement allows the shifted configuration to be processed using the same number of regular \(M\times M\) computational windows as regular window partitioning. However, it also places sub-windows that were not adjacent in the original feature map into the same computational window. Masked MSA therefore ensures tokens only attend to other tokens within the same sub-window. For example, in Figure 8, all tokens within region 5 can attend to one another, whereas regions 8 and 2 share a computational window only because of cyclic wraparound, so attention between regions 8 and 2 is masked out. After Masked MSA, a reverse cyclic shift moves the entire feature map back to its original spatial arrangement. See also my sketch in Figure 8 for a visual explanation.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/swin_notes/8_cyclic_shift_sketch-480.webp 480w,/assets/img/posts/swin_notes/8_cyclic_shift_sketch-800.webp 800w,/assets/img/posts/swin_notes/8_cyclic_shift_sketch-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/swin_notes/8_cyclic_shift_sketch.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 8.</b> My sketch to better understand how the cyclic shifting and masked MSA work. </div> <hr/> <h2 id="references">References</h2> <ul> <li> <p>Arkin, E., Yadikar, N., Xu, X., Aysa, A., &amp; Ubul, K. (2023). <a href="https://doi.org/10.1007/s11042-022-13801-3">A survey: Object detection methods from CNN to transformer</a>. <em>Multimedia Tools and Applications, 82</em>, 21353–21383.</p> </li> <li> <p>Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., &amp; Houlsby, N. (2021). <a href="https://arxiv.org/abs/2010.11929">An image is worth 16×16 words: Transformers for image recognition at scale</a>. <em>International Conference on Learning Representations (ICLR)</em>.</p> </li> <li> <p>Hassani, A., Walton, S., Li, J., Li, S., &amp; Shi, H. (2023). <a href="https://cvpr2023.thecvf.com/media/cvpr-2023/Slides/23172.pdf"><em>Neighborhood Attention Transformer</em> — CVPR 2023 presentation slides</a>. IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR 2023).</p> </li> <li> <p>He, K., Zhang, X., Ren, S., &amp; Sun, J. (2016). <a href="https://doi.org/10.1109/CVPR.2016.90">Deep residual learning for image recognition</a>. <em>Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)</em>, 770–778.</p> </li> <li> <p>Lin, T.-Y., Dollár, P., Girshick, R., He, K., Hariharan, B., &amp; Belongie, S. (2017). <a href="https://doi.org/10.1109/CVPR.2017.106">Feature pyramid networks for object detection</a>. <em>Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)</em>, 2117–2125.</p> </li> <li> <p>Liu, Z., Lin, Y., Cao, Y., Hu, H., Wei, Y., Zhang, Z., Lin, S., &amp; Guo, B. (2021). <a href="https://doi.org/10.1109/ICCV48922.2021.00986">Swin Transformer: Hierarchical Vision Transformer using shifted windows</a>. <em>Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV)</em>, 10012–10022.</p> </li> <li> <p>Ramachandran, P., Parmar, N., Vaswani, A., Bello, I., Levskaya, A., &amp; Shlens, J. (2019). <a href="https://proceedings.neurips.cc/paper/2019/hash/3416a75f4cea9109507cacd8e2f2aefc-Abstract.html">Stand-alone self-attention in vision models</a>. <em>Advances in Neural Information Processing Systems (NeurIPS), 32</em>.</p> </li> <li> <p>Wang, H., Zhang, F., &amp; Yi, R. (2025). <a href="https://doi.org/10.3390/s25226890">Multi-scale deformable transformer with iterative query refinement for hot-rolled steel surface defect detection</a>. <em>Sensors, 25</em>(22), 6890.</p> </li> </ul> <h2 id="footnote">Footnote</h2> <div class="footnotes" role="doc-endnotes"> <ol> <li id="fn:nlp-hier" role="doc-endnote"> <p>Some NLP models do use hierarchical structures for longer documents (e.g., sentence -&gt; paragraph -&gt; document), such as Hierarchical Attention Networks for document classification (Yang et al., 2016), but those are more specialized and not the typical setup for the tasks we are referring to here. <a href="#fnref:nlp-hier" class="reversefootnote" role="doc-backlink">&#8617;</a></p> </li> <li id="fn:vit-variants" role="doc-endnote"> <p>There are ViT-based variants that introduce multi-scale or hierarchical features and are used successfully for detection and segmentation. Examples include Pyramid Vision Transformer (PVT; Wang et al., 2021) and Multi-scale Vision Transformers (MViT; Fan et al., 2021). These architectures are ViT-inspired but explicitly add the kind of hierarchical structure and multi-scale features that the original single-scale ViT lacks. <a href="#fnref:vit-variants" class="reversefootnote" role="doc-backlink">&#8617;</a></p> </li> </ol> </div>]]></content><author><name></name></author><category term="computer-vision"/><summary type="html"><![CDATA[Learning notes of Swin Transformer]]></summary></entry><entry><title type="html">Vision Transformer (ViT) Notes</title><link href="https://wenwenkong.github.io/blog/2025/ViT-notes/" rel="alternate" type="text/html" title="Vision Transformer (ViT) Notes"/><published>2025-11-08T00:00:00+00:00</published><updated>2025-11-08T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2025/ViT-notes</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2025/ViT-notes/"><![CDATA[<p>This post focuses on understanding the core idea and model architecture of the Vision Transformer (ViT).</p> <p>Before ViT, convolutional architectures remained dominant in computer vision. Classic Convolutional Neural Networks (CNNs) such as VGG and especially ResNet, with its residual skip connections, were state of the art. In the original ViT paper (<a href="https://arxiv.org/abs/2010.11929">Dosovitskiy et al., 2021, An image is worth 16 x 16 words: transformers for image recognition at scale</a>), the authors applied transformers to image classification tasks and found that, when trained on large datasets, ViT can match or even surpass the performance of top convolutional networks.</p> <hr/> <h2 id="core-idea">Core idea</h2> <h4 id="from-words-to-patches">From words to patches</h4> <p>ViT processes sequences of image patches just as transformers process sequences of word tokens in natural language processing (NLP). In NLP, a transformer takes a sequence of word embeddings as input and learns contextual relationships among them through self-attention. Similarly, ViT splits an image into fixed-size patches, flattens each patch, linearly embeds the patches into vectors, and feeds the resulting sequence of patch embeddings into a standard transformer encoder.</p> <p>Besides this <em>words vs patches</em> analogy, ViT also mirrors how transformers are trained in NLP. Dosovitskiy et al. (2021) note that:</p> <blockquote> <p>The dominant approach [in NLP] is to pre-train on a large text corpus and then fine-tune on a smaller task-specific dataset.</p> </blockquote> <blockquote> <p>Large Transformer-based models are often pre-trained on large corpora and then fine-tuned for the task at hand: BERT uses a denoising self-supervised pre-training task, while the GPT line of work uses language modeling as its pre-training task.</p> </blockquote> <p>ViT follows a similar pattern: it excels when first trained on large image datasets and then fine-tuned for smaller, domain-specific tasks. We will get to this point later in the post when discussing why ViT benefits so much from large-scale pretraining. For a deeper look at pretraining in large language models, see my <a href="https://wenwenkong.com/blog/2025/gen-ai-llm-2/">previous post</a>.</p> <h4 id="cnns-vs-vit">CNNs vs. ViT</h4> <p>In machine learning, <em>inductive bias</em> refers to the built-in assumptions a model makes about data before seeing any examples. Dosovitskiy et al. (2021) noted that ViT has much less image-specific inductive bias than CNNs, quote:</p> <blockquote> <p>… In CNNs, locality, two-dimensional neighborhood structure, and translation equivariance are baked into each layer throughout the whole model. In ViT, only MLP layers are local and translationally equivariant, while the self-attention layers are global.</p> </blockquote> <p>The table below summarizes how CNNs and ViT differ in their built-in assumptions about images.</p> <table style="border-collapse: collapse; width: 100%;"> <tr style="background-color: #f4f4f4;"> <th style="border: 1px solid #ddd; padding: 8px;">Inductive biases</th> <th style="border: 1px solid #ddd; padding: 8px;">CNNs</th> <th style="border: 1px solid #ddd; padding: 8px;">ViTs</th> </tr> <tr> <td style="border: 1px solid #ddd; padding: 8px;"><b>Locality</b></td> <td style="border: 1px solid #ddd; padding: 8px;">Convolution filters look at local pixel neighborhoods (small receptive fields).</td> <td style="border: 1px solid #ddd; padding: 8px;">No built-in locality; all patches can attend to each other globally.</td> </tr> <tr style="background-color: #f9f9f9;"> <td style="border: 1px solid #ddd; padding: 8px;"><b>2D neighborhood</b></td> <td style="border: 1px solid #ddd; padding: 8px;">Operates directly on 2D image grids; spatial adjacency is hard-coded.</td> <td style="border: 1px solid #ddd; padding: 8px;">Flattened into 1D sequence of patches; 2D structure not explicit.</td> </tr> <tr> <td style="border: 1px solid #ddd; padding: 8px;"><b>Translation equivariance</b></td> <td style="border: 1px solid #ddd; padding: 8px;">A shifted input produces shifted feature maps (invariance to object position).</td> <td style="border: 1px solid #ddd; padding: 8px;">No inherent equivariance; positional embeddings must be learned.</td> </tr> </table> <h4 id="why-vit-excels-with-large-datasets">Why ViT excels with large datasets</h4> <p>Because ViT does not come with strong image-specific inductive biases, it treats all patches equally and relies on self-attention to decide which regions of an image are important. This explains why ViT performs worse on small datasets but excels on large ones.</p> <p>When the training dataset is small, CNNs often outperform ViTs because their built-in assumptions help them learn meaningful patterns even with limited data. In contrast, ViT has to learn locality, edges, textures, and other visual structures from scratch, making it more data-hungry and less efficient at small scales. With large datasets, however, ViT can learn spatial and structural patterns directly from data rather than relying on hard-coded assumptions. Its global self-attention becomes a major advantage, enabling the model to capture long-range dependencies across the entire image and ultimately surpass CNNs.</p> <hr/> <h2 id="architecture">Architecture</h2> <p>In this section, we walk through the ViT model architecture using Figure 1 and Equations (1)-(4) from Dosovitskiy et al. (2021). Figure 1 (below) is an annotated version of the original figure from the paper, showing how an image is divided into patches, embedded, and processed through the transformer encoder. Google Research <a href="https://research.google/blog/transformers-for-image-recognition-at-scale/">blog</a> also provides an animated visualization that illustrates the ViT workflow.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/vit_notes/1_vit_architecture_annotated-480.webp 480w,/assets/img/posts/vit_notes/1_vit_architecture_annotated-800.webp 800w,/assets/img/posts/vit_notes/1_vit_architecture_annotated-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/vit_notes/1_vit_architecture_annotated.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> Annotated ViT architecture (adapted from Dosovitskiy et al., 2021). </div> <p>Here is how ViT is defined mathematically:</p> \[\begin{aligned} \mathbf{z}_0 &amp;= \big[\, x_{\text{class}};\; x_{p}^{1}\,\mathbf{E};\; x_{p}^{2}\,\mathbf{E};\; \dots;\; x_{p}^{N}\,\mathbf{E} \,\big] + E_{\text{pos}}, \quad \mathbf{E}\in \mathbb{R}^{(P^{2}\!\cdot C)\times D},\; E_{\text{pos}}\in \mathbb{R}^{(N+1)\times D} \quad &amp;(1) \\ \mathbf{z}'_{\ell} &amp;= \mathrm{MSA}\!\left(\mathrm{LN}(\mathbf{z}_{\ell-1})\right) + \mathbf{z}_{\ell-1}, \quad \ell=1,\dots,L \quad &amp;(2) \\ \mathbf{z}_{\ell} &amp;= \mathrm{MLP}\!\left(\mathrm{LN}(\mathbf{z}'_{\ell})\right) + \mathbf{z}'_{\ell}, \quad \ell=1,\dots,L \quad &amp;(3) \\ \mathbf{y} &amp;= \mathrm{LN}\!\left(\mathbf{z}^{\,0}_{L}\right) \quad &amp;(4) \end{aligned}\] <h4 id="equation-1-embedding">Equation (1): embedding</h4> <p>Equation (1) corresponds to the embedding stage in Figure 1. The input image is represented as \(x \in \mathbb{R}^{H \times W \times C}\), where \(H\), \(W\), and \(C\) denote height, width, and number of channels. The image is divided into \(N\) patches, \(x_p \in \mathbb{R}^{N \times (P^2 \cdot C)}\), where \((P, P)\) represents the resolution of each image patch. Each patch vector is multiplied by a learnable projection matrix \(E\) to get a \(D\)-dimensional embedding. A special classification token \(x{\text{class}}\) is prepended - its embedding will later represent the whole image. A positional embedding \(E_{\text{pos}}\) is also added to retain spatial information. These form the input sequence \(\mathbf{z}_0\) that will be feeded to the transformer.</p> <p><strong>Understanding constant \(D\)</strong></p> <p>Transformers are designed to process sequences where every token has the same dimensionality across all layers. This uniformity makes stacking layers simple: each layer takes a sequence of vectors of shape \([N \times D]\) and outputs another sequence \([N \times D]\). Here, \(D\) indicates the <strong>embedding dimension</strong> (sometimes called the <em>hidden size</em>). Every patch embedding and every intermediate vector inside the transformer has size \(D\).</p> <p>\(D\) is a hyperparameter. With enough data, a larger \(D\) usually means higher model capacity and better performance — but it also requires more compute and memory. In a nutshell, \(D\) is a design choice controlling how much information each token can represent and how big the transformer is.</p> <p><strong>Understanding the trainable linear layer \(\mathbf{E}\)</strong></p> <p>A raw image patch of size \(P \times P \times C\) is flattened into a vector, but the transformer expects tokens of dimension \(D\). So a trainable linear layer (denoted as \(\mathbf{E}\)) maps flattened patches into the \(D\)-dimensional embedding space. After this step, all tokens (patches + [CLS]) live in the same latent space.</p> <p>Let’s walk through the logic using the ViT-Base configuration. Suppose the image size is \(224 \times 224 \times 3\), patch size is \(16 \times 16\), and embedding dimension \(D = 768\).</p> <ol> <li> <p><strong>Split into patches.</strong><br/> Each patch = \(16 \times 16 \times 3 = 768\) raw pixel values.<br/> Total number of patches = \((224 / 16)^2 = 196\).</p> </li> <li> <p><strong>Flatten each patch.</strong><br/> Flatten \(16 \times 16 \times 3\) into a vector of length 768.<br/> Before projection, each patch is a 768-dimensional vector of raw pixel intensities.</p> </li> <li> <p><strong>Project to the embedding dimension \(D\).</strong><br/> Note: although the patch length (768) and \(D\) (768) are identical in this example (ViT-Base), they are <em>not the same thing</em>.<br/> The flattened patch values are <strong>raw pixel values</strong>, while \(D\) represents the <strong>dimension of learned embeddings</strong> that the transformer requires in a consistent latent space.<br/> Even when \(P \times P \times C = D\), we still need a linear projection — it’s not about matching dimensions, it’s about <em>learning a mapping from raw pixels → latent embedding space</em>.</p> <p>ViT applies a trainable linear layer \(\mathbf{E}\):</p> \[\mathbf{e} = \mathbf{W} \mathbf{x} + \mathbf{b}\] <p>where:</p> <ul> <li>\(\mathbf{x}\) = flattened patch (size \(P^2 C\), here 768)</li> <li>\(\mathbf{W}\) = learnable weight matrix (size \((P^2 C) \times D\))</li> <li>\(\mathbf{b}\) = bias term (size \(D\))</li> <li>\(\mathbf{e}\) = patch embedding (size \(D\))</li> </ul> </li> <li> <p><strong>Build the sequence.</strong><br/> Each of the 196 patches is now projected to a 768-dimensional embedding vector.<br/> Add one learnable [CLS] token (also 768-dimensional). The sequence length becomes 197, each of size 768 — so the input to the transformer is a \([197 \times 768]\) matrix.</p> </li> <li> <p><strong>Transformer layers.</strong><br/> Each transformer layer takes a \([197 \times 768]\) input and outputs another \([197 \times 768]\) matrix.</p> </li> </ol> <h4 id="equation-2-multi-head-self-attention-msa">Equation (2): multi-head self-attention (MSA)</h4> <p>Equation (2) represents the self-attention sub-layer in each transformer block. Inside each transformer block, the input passes through <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html">layer normalization (LN)</a> and then <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html">multi-head self-attention (MSA)</a>: \(\mathrm{MSA}\!\left(\mathrm{LN}(\mathbf{z}_{\ell-1})\right)\). Each token (patch embedding) attends to all others globally, capturing relationships across the entire image. The residual connection \(\mathbf{z}_{\ell-1}\) (skip arrow in Figure 1) helps stabilize gradient flow during training.</p> <h4 id="equation-3-feed-forward-mlp">Equation (3): feed-forward (MLP)</h4> <p>Equation (3) describes the feed-forward network (or <a href="https://scikit-learn.org/stable/modules/neural_networks_supervised.html">MLP</a>) that follows self-attention. After the attention step, the output is normalized again and passed through a two-layer MLP (with a <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.GELU.html">GELU</a> activation in between): \(\mathrm{MLP}(x) = W_2 \, \mathrm{GELU}(W_1 x + b_1) + b_2\). Another residual connection adds the input back to the output.</p> <p>Together, Equations (2) and (3) make up a transformer block - stacked \(L\) times as shown in Figure 1.</p> <h4 id="equation-4-classification-head">Equation (4): classification head</h4> <p>Equation (4) corresponds to the output head of the model. After L transformer blocks, the output (i.e., the class token embedding \(\mathbf{z}^{0}_{L}\) that represents the entire image) is extracted. \(\mathbf{z}^{0}_{L}\) is layer-normalized and used for classification through a linear classifier. The linear classifier in ViT can be viewed as a standard logistic regression layer that takes the final class token embedding as input and outputs logits for each class.</p> <hr/> <h2 id="implementation">Implementation</h2> <p>In this section, we demonstrate a jupyter notebook that maps the core ViT equations to a minimal PyTorch implementation. It follows the paper’s equations (1) to (4) and mirrors the structure of open-source ViT implementations (<a href="https://github.com/google-research/vision_transformer">Google Research</a>, <a href="https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py">timm</a>, <a href="https://huggingface.co/docs/transformers/model_doc/vit">Hugging Face</a>).</p> <details class="notebook-frame"> <summary class="notebook-header"> ▶️ Notebook: ViT — From Equations to Code (click to expand) </summary> <div class="jupyter-notebook" style="position: relative; width: 100%; margin: 0 auto;"> <div class="jupyter-notebook-iframe-container"> <iframe src="/assets/jupyter/posts/vit_notes/vit_mini_implementation.ipynb.html" style="position: absolute; top: 0; left: 0; border-style: none;" width="100%" height="100%" onload="this.parentElement.style.paddingBottom = (this.contentWindow.document.documentElement.scrollHeight + 10) + 'px'"></iframe> </div> </div> </details> <hr/> <h2 id="references">References</h2> <ul> <li> <p><strong>Dosovitskiy, A.</strong>, Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., &amp; Houlsby, N. (2021). <em>An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale.</em> <a href="https://arxiv.org/abs/2010.11929">Paper</a></p> </li> <li> <p><strong>Google Research ViT</strong>: <a href="https://github.com/google-research/vision_transformer">Repo</a></p> </li> <li> <p><strong>timm: PyTorch Image Models</strong> (Ross Wightman) Vision Transformer source: <a href="https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py">Code</a></p> </li> <li> <p><strong>Hugging Face Transformers — Vision Transformer (ViT)</strong>: <a href="https://huggingface.co/docs/transformers/model_doc/vit">Documentation</a>, <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/models/vit/modeling_vit.py">code</a></p> </li> </ul>]]></content><author><name></name></author><category term="computer-vision"/><summary type="html"><![CDATA[Learning notes and mini-implementation of ViT]]></summary></entry><entry><title type="html">GenAI with LLMs (6) LLM powered applications</title><link href="https://wenwenkong.github.io/blog/2025/gen-ai-llm-6/" rel="alternate" type="text/html" title="GenAI with LLMs (6) LLM powered applications"/><published>2025-08-30T00:00:00+00:00</published><updated>2025-08-30T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2025/gen-ai-llm-6</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2025/gen-ai-llm-6/"><![CDATA[<p>This post covers LLM powered applications from the <strong>Generative AI With LLMs</strong> course offered by DeepLearning.AI.</p> <h2 id="model-optimizations-for-deployment">Model optimizations for deployment</h2> <h4 id="distillation">Distillation</h4> <p>Distillation uses a larger model (the teacher model) to train a smaller model (the student model). Then use the smaller model for inference to lower the storage and compute budget. The student model learns to statistically mimic the behavior of the teacher model, either just in the final prediction layer, or in the model’s hidden layers as well.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/1_distillation-480.webp 480w,/assets/img/posts/genai_llm_6/1_distillation-800.webp 800w,/assets/img/posts/genai_llm_6/1_distillation-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/1_distillation.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> Distillation. Source: course lecture. </div> <p><strong>Distillation workflow:</strong></p> <ul> <li>Start with a <b>fine-tuned</b> LLM as the teacher model, and create a smaller LLM for student model.</li> <li>Freeze the teacher model’s weights and use it to generate completions for the training data. Meanwhile, also generate completions for the training data using the student model.</li> <li>The <b>knowledge distillation</b> between teacher and student model is achieved by minimizing a loss function called the <b>distillation loss</b>. To calculate the loss, distillation compares the probability distribution over tokens produced by the student model’s softmax layer to that of the teacher model’s softmax layer.</li> <li>Adding a <b>temperature</b> parameter to the softmax function. Why? <ul> <li>The teacher model is already fine-tuned on the training data, so the probability distribution likely closely matches the ground truth data and won’t have much variation in tokens. That’s why Distillation applies a little trick adding a temperature parameter to the softmax function.</li> <li>With a temperature parameter greater than one, the probability distribution becomes broader and less strongly peaked. This softer distribution provides you with a set of tokens that are similar to the ground truth tokens.</li> </ul> </li> <li>In parallel, you train the student model to generate the correct predictions based on your ground truth training data. Here, you don’t vary the temperature setting, and instead, use the standard softmax function. Distillation refers to the student model outputs as the <b>hard predictions</b> and <b>hard labels</b>. The loss between the hard predictions and hard labels is the <b>student loss</b>.</li> <li>The combined distillation and student losses are used to updated the weights of the student model via back propagation.</li> </ul> <p>The key benefit of distillation methods is that the smaller student model can be used for inference in deployment instead of the teacher model. In practice, distillation is not as effective for generative decoder models. It’s typically more effective for encoder only models such as BERT that have a lot of representation redundancy.</p> <h4 id="quantization">Quantization</h4> <p>We introduced the concept of quantization in the <a href="https://wenwenkong.com/blog/2025/gen-ai-llm-2/">LLM pre-training note</a>. After a model is trained, we can perform <b>post training quantization (PTQ)</b> to optimize for deployment. PTQ transforms a model’s weights to a lower precision representation, such as 16-bit floating point for 8-bit integer.</p> <ul> <li>To reduce the model size and memory footprint, as well as the compute resources needed for model serving, <b>quantization can be applied to just the model weights or to both weights and activation layers</b>. In general, quantization approaches that include activations can have a higher impact on model performance.</li> <li>Quantization also requires an extra calibration step to statistically capture the dynamic range of the original parameter values.</li> <li>Trade-off: sometimes quantization results in a small percentage reduction in model evaluation metrics. That reduction can often be worth the cost saving and performance gains.</li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/2_PTQ-480.webp 480w,/assets/img/posts/genai_llm_6/2_PTQ-800.webp 800w,/assets/img/posts/genai_llm_6/2_PTQ-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/2_PTQ.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 2.</b> Post training quantization. Source: course lecture. </div> <h4 id="pruning">Pruning</h4> <p><b>Pruning</b> is to reduce model size for inference by eliminating weights that are not contributing much to overall model performance. These are the weights with values very close to or equal to zero.</p> <ul> <li>Some pruning methods require full retraining of the model, while others fall into the category of parameter efficient fine tuning, such as LoRA.</li> <li>There are also methods that focus on post-training pruning.</li> </ul> <p>In theory, pruning reduces model size and improves performance. In practice, however, there may not be much impact on the size and performance if only a small percentage of the model weights are close to zero.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/3_pruning-480.webp 480w,/assets/img/posts/genai_llm_6/3_pruning-800.webp 800w,/assets/img/posts/genai_llm_6/3_pruning-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/3_pruning.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 3.</b> Pruning. Source: course lecture. </div> <h2 id="retrieval-augmented-generation-rag">Retrieval augmented generation (RAG)</h2> <p>RAG helps LLMs update their understanding of the world and overcomes the <a href="https://en.wikipedia.org/wiki/Knowledge_cutoff">knowledge cutoff issue</a>. While we could retrain the model on new data, this would quickly become expensive, and require repeated retraining to regularly update the model with new knowledge. A more flexible and less expensive way to overcome knowledge cutoff is to <b>give model access to additional external data at inference time</b>.</p> <p>RAG isn’t a specific set of technologies, but rather a framework for providing LLMs access to data they did not see during training. <b>A number of different implementations exist</b>, and the one you choose will depend on the details of your task, and the format of data to work with.</p> <p>RAG can be used to integrate multiple types of external information sources. In the following, we briefly introduce using <b>vector store</b> for RAG. Vector store contains vector representation of text, and enables a fast and efficient kind of relevant search based on similarity.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/4_RAG-480.webp 480w,/assets/img/posts/genai_llm_6/4_RAG-800.webp 800w,/assets/img/posts/genai_llm_6/4_RAG-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/4_RAG.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 4.</b> RAG integrates with many types of data sources. Source: course lecture. </div> <h4 id="data-preparation-for-vector-store">Data preparation for vector store</h4> <p>Two considerations:</p> <ol> <li>Data must fit inside context window</li> </ol> <ul> <li>The external data sources can be chopped into many chunks, each of which will fit in the context window. Packages like <b>Langchain</b> can handle this.</li> </ul> <ol> <li>Data must be in format that allows its relevance to be assessed at inference time: <b>embedding vectors</b></li> </ol> <ul> <li>RAG methods take the small chunks of external data and process them through embedding models to create embedding vectors for each. These embedding vectors can be stored in structures called vector stores, which allow for fast searching of datasets and efficient identification of semantically related text.</li> </ul> <p><b>Vector databases</b> are a particular implementation of a vector store, where each vector is also identified by a <b>key</b>. This allows for the text generated by RAG to include a <b>citation</b> for the document from which it was received.</p> <h2 id="chain-of-thought-prompting">Chain-of-thought prompting</h2> <p>Chain-of-thought prompting works by including a series of intermediate reasoning steps into any examples that you use for one or few-shot inference. By structuring the examples in this way, you’re essentially teaching the model how to reason through the task to reach a solution.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/5_CoT-480.webp 480w,/assets/img/posts/genai_llm_6/5_CoT-800.webp 800w,/assets/img/posts/genai_llm_6/5_CoT-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/5_CoT.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 5.</b> Chain-of-Thought prompting can help LLMs reason. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/6_CoT-480.webp 480w,/assets/img/posts/genai_llm_6/6_CoT-800.webp 800w,/assets/img/posts/genai_llm_6/6_CoT-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/6_CoT.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 6.</b> Chain-of-Thought prompting can help LLMs reason. Source: course lecture. </div> <h2 id="program-aided-language-models-pal">Program-aided language models (PAL)</h2> <p>PAL pairs LLM with an external code interpreter to carry out calculations. The strategy behind PAL is to have the LLM generate completions where reasoning steps are accompanied by computer code. This code is then passed to an interpreter to carry out the calculations necessary to solve the problem. You specify the output format for the model by including examples for one or few shot inferences in the prompt.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/7_PAL-480.webp 480w,/assets/img/posts/genai_llm_6/7_PAL-800.webp 800w,/assets/img/posts/genai_llm_6/7_PAL-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/7_PAL.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 7.</b> PAL example. Source: course lecture. </div> <p>To prepare for inference with PAL,</p> <ul> <li>Format prompt to contain one or more examples; each example should contain a question followed by reasoning steps in lines of Python code that solves the problem</li> <li>Append the new question to the prompt template; the resulting PAL formatted prompt now contains both the example and the problem to solve</li> <li>Pass the combined prompt to LLM, which generates a completion that is in the form of a Python script having learned how to format the output based on the example in the prompt</li> <li>Hand off the script to a Python interpreter, which will be used to run the code and generate an answer</li> <li>Append the text containing the answer, forming a prompt that includes the correct answer in the context</li> <li>Pass the updated the prompt to LLM, and it generates a completion that contains the correct answer</li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/8_PAL-480.webp 480w,/assets/img/posts/genai_llm_6/8_PAL-800.webp 800w,/assets/img/posts/genai_llm_6/8_PAL-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/8_PAL.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 8.</b> PAL at inference. Source: course lecture. </div> <p>How to automate the process? The <b>orchestrator</b> is a technical component that manage the flow of information and the initiation of calls to external data sources or applications. It can also decide what actions to take based on the information contained in the output of the LLM. The LLM doesn’t have to decide to run the code, it just has to write the script which the orchestrator then passes to the external interpreter to run.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/9_PAL_orchestrator-480.webp 480w,/assets/img/posts/genai_llm_6/9_PAL_orchestrator-800.webp 800w,/assets/img/posts/genai_llm_6/9_PAL_orchestrator-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/9_PAL_orchestrator.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 9.</b> PAL architecture. Source: course lecture. </div> <h2 id="react-combining-reasoning-and-action">ReAct: Combining reasoning and action</h2> <p>ReAct is a prompting strategy that combines chain-of-thought reasoning with action planning. It uses structured examples to show a LLM how to reason through a problem and decide on actions to take that move it closer to a solution.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/10_ReAct-480.webp 480w,/assets/img/posts/genai_llm_6/10_ReAct-800.webp 800w,/assets/img/posts/genai_llm_6/10_ReAct-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/10_ReAct.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 10.</b> ReAct: synergizing reasoning and action in LLMs. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/11_ReAct-480.webp 480w,/assets/img/posts/genai_llm_6/11_ReAct-800.webp 800w,/assets/img/posts/genai_llm_6/11_ReAct-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/11_ReAct.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 11.</b> ReAct: synergizing reasoning and action in LLMs. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/12_ReAct_instructions-480.webp 480w,/assets/img/posts/genai_llm_6/12_ReAct_instructions-800.webp 800w,/assets/img/posts/genai_llm_6/12_ReAct_instructions-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/12_ReAct_instructions.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 12.</b> ReAct instructions define the action space. Source: course lecture. </div> <p>The <b>LangChain</b> framework provides modular pieces that contain the components necessary to work with LLMs. These components include prompt templates for many different use cases that you can use to format both input examples and model completions, and memory that we can use to store interactions with an LLM. The framework also includes pre-built tools that carry out a variety of tasks, including calls to external datasets and various APIs. Connecting a selection of these individual components together results in a chain.</p> <p>The creators of LangChain have developed a set of predefined chains that have been optimized for different use cases. You can use these off the shelf to quickly get your app up and running. Sometimes your application workflow could take multiple paths depending on the information the user provides. In this case, you can’t use a predetermined chain, but instead we’ll need the flexibility to decide which actions to take as the user moves through the workflow. You can use an <b>agent</b> to interpret the input from the user and determine which tool or tools to use to complete the task. LangChain currently includes agents for both PAL and ReAct, among others. Agents can be incorporated into chains to take an action or plan and execute a series of actions.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/13_LangChain-480.webp 480w,/assets/img/posts/genai_llm_6/13_LangChain-800.webp 800w,/assets/img/posts/genai_llm_6/13_LangChain-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/13_LangChain.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 13.</b> LangChain framework. Source: course lecture. </div> <h2 id="llm-application-architectures">LLM application architectures</h2> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_6/14_llm_architecture-480.webp 480w,/assets/img/posts/genai_llm_6/14_llm_architecture-800.webp 800w,/assets/img/posts/genai_llm_6/14_llm_architecture-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_6/14_llm_architecture.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 14.</b> LLM application architecture of an end-to-end solution. Source: course lecture. </div> <h2 id="references">References</h2> <ul> <li><a href="https://arxiv.org/pdf/2201.11903.pdf">Chain-of-thought Prompting Elicits Reasoning in Large Language Models</a> <ul> <li>Paper by researchers at Google exploring how chain-of-thought prompting improves the ability of LLMs to perform complex reasoning.</li> </ul> </li> <li><a href="https://arxiv.org/abs/2211.10435">PAL: Program-aided Language Models</a> <ul> <li>This paper proposes an approach that uses the LLM to read natural language problems and generate programs as the intermediate reasoning steps.</li> </ul> </li> <li><a href="https://arxiv.org/abs/2210.03629">ReAct: Synergizing Reasoning and Acting in Language Models</a> <ul> <li>This paper presents an advanced prompting technique that allows an LLM to make decisions about how to interact with external applications.</li> </ul> </li> <li><a href="https://github.com/hwchase17/langchain">LangChain Library (GitHub)</a> <ul> <li>This library is aimed at assisting in the development of those types of applications, such as Question Answering, Chatbots and other Agents. You can read the documentation here</li> </ul> </li> <li><a href="https://a16z.com/2023/01/19/who-owns-the-generative-ai-platform/">Who Owns the Generative AI Platform?</a> <ul> <li>The article examines the market dynamics and business models of generative AI.</li> </ul> </li> </ul>]]></content><author><name></name></author><category term="llm"/><summary type="html"><![CDATA[Course summary of Generative AI with Large Language Models. Part Six.]]></summary></entry><entry><title type="html">GenAI with LLMs (5) Reinforcement learning from human feedback</title><link href="https://wenwenkong.github.io/blog/2025/gen-ai-llm-5/" rel="alternate" type="text/html" title="GenAI with LLMs (5) Reinforcement learning from human feedback"/><published>2025-08-06T00:00:00+00:00</published><updated>2025-08-06T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2025/gen-ai-llm-5</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2025/gen-ai-llm-5/"><![CDATA[<p>This post covers reinforcement learning from human feedback (RLHF) from the <strong>Generative AI With LLMs</strong> course offered by DeepLearning.AI.</p> <h2 id="why-we-need-rlhf">Why we need RLHF</h2> <p>RLHF helps to avoid</p> <ul> <li>Toxic language</li> <li>Aggressive responses</li> <li>Providing dangerous information</li> </ul> <p>One potentially exciting application of RLHF is the personalization of LLMs, where models learn the preference of each individual user through a continuous feedback process. Such as individualized learning plans and personalized AI assistant.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/1_RLHF-480.webp 480w,/assets/img/posts/genai_llm_5/1_RLHF-800.webp 800w,/assets/img/posts/genai_llm_5/1_RLHF-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/1_RLHF.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> Fine-tuning with human feedback. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/2_RLHF-480.webp 480w,/assets/img/posts/genai_llm_5/2_RLHF-800.webp 800w,/assets/img/posts/genai_llm_5/2_RLHF-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/2_RLHF.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 2.</b> Reinforcement learning from human feedback. Source: course lecture. </div> <h2 id="reinforcement-learning">Reinforcement learning</h2> <p>Reinforcement learning is a type of machine learning where an agent learns to make decisions related to a specific goal by taking actions in an environment, with the objective of maximizing some notion of a cumulative reward. In this framework, the agent continually learns from its experiences by taking actions, observing the resulting changes in the environment, and receiving rewards or penalties, based on the outcomes of its actions. By iterating through this process, the agent gradually refines its strategy or policy to make better decisions and increase its chances of success.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/3_RL_diagram-480.webp 480w,/assets/img/posts/genai_llm_5/3_RL_diagram-800.webp 800w,/assets/img/posts/genai_llm_5/3_RL_diagram-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/3_RL_diagram.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 3.</b> Reinforcement learning diagram. Source: course lecture. </div> <p>How to determine the reward when fine-tuning LLM with reinforcement learning?</p> <ul> <li>One way is to have a human evaluate all of the completions of the model against some alignment metric, such as determining whether the generated text is toxic or non-toxic. This feedback can be represented as a scalar value, either 0 or 1. The LLM weights are then updated iteratively, to maximize the reward obtained from the human classifier, enabling the model to generate non-toxic completions.</li> <li>A scalable and practical alternative is the <b>reward model</b>: <ul> <li>Start with a smaller number of human examples to train the reward model</li> <li>Once trained, use the reward model to assess the output of the LLM and assign a reward value, which in turn gets used to update the weights of the LLM and train a new human aligned version.</li> <li>Exactly how the weights get updated as the model completions are assessed depends on the algorithm used to optimize the policy.</li> </ul> </li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/4_RL_finetuneLLM-480.webp 480w,/assets/img/posts/genai_llm_5/4_RL_finetuneLLM-800.webp 800w,/assets/img/posts/genai_llm_5/4_RL_finetuneLLM-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/4_RL_finetuneLLM.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 4.</b> Reinforcement learning from human feedback. Source: course lecture. </div> <h2 id="rlhf-preparation">RLHF: preparation</h2> <p>The first step is to <b>select a model to work with and prepare a dataset for human feedback</b>.</p> <p>The model should have some capability to carry out the task of interest, whether it is text summarization, question answering, or something else. In general, recommend to start with an instruct model that has already been fine-tuned across many tasks and has some general capabilities.</p> <h4 id="prepare-dataset-for-human-feedback">Prepare dataset for human feedback</h4> <p>Use the selected instruct LLM with a prompt dataset to generate a number of different responses for each prompt. The prompt dataset is composed of multiple prompts, each of which gets processed by the LLM to produce a set of completions.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/5_prepare_dataset-480.webp 480w,/assets/img/posts/genai_llm_5/5_prepare_dataset-800.webp 800w,/assets/img/posts/genai_llm_5/5_prepare_dataset-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/5_prepare_dataset.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 5.</b> Prepare dataset for human feedback. Source: course lecture. </div> <h4 id="collect-human-feedback">Collect human feedback</h4> <p>The next step is to collect feedback from human labelers on the completions generated by the LLM. This is the <b>human feedback portion</b> of the RLHF.</p> <ul> <li>Decide the <b>criteria</b> for the labelers to assess the completions on. This could be helpfulness, toxicity, etc.</li> <li>Ask the labelers to assess each completion in the dataset based on the criteria.</li> <li>Assign the same task to multiple labelers to dampen the impact of “poor” labelers who may misunderstood the instruction.</li> </ul> <p>Note that the clarify of instructions can make a big difference on the quality of the human feedback.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/6_human_feedback-480.webp 480w,/assets/img/posts/genai_llm_5/6_human_feedback-800.webp 800w,/assets/img/posts/genai_llm_5/6_human_feedback-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/6_human_feedback.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 6.</b> Collect human feedback. Source: course lecture. </div> <h4 id="prepare-labeled-data-for-training">Prepare labeled data for training</h4> <p>Before training the reward model, convert the ranking data into a pairwise comparison of completions. <b>Re-order the pair so the preferred response comes first.</b> This is an important step because the reward model expects the preferred completion \(y_{j}\) first. Once completing this data restructuring, the human responses will be in the correct format for training the reward model.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/7_data_restructuring-480.webp 480w,/assets/img/posts/genai_llm_5/7_data_restructuring-800.webp 800w,/assets/img/posts/genai_llm_5/7_data_restructuring-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/7_data_restructuring.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 7.</b> Prepare labeled data for reward model training. Source: course lecture. </div> <h2 id="rlhf-reward-model">RLHF: reward model</h2> <p>By the time we are done with training the reward model, we won’t need to include any more humans in the loop. Instead, the reward model will effectively take place of the human labeler and automatically choose the preferred completions during the RLHF process.</p> <p>The reward model is also usually a language model which is trained using the supervised learning on the pairwise comparison that we prepared from the human labelers’ assessment of the prmpts.</p> <p>The human preferred completion is always the first one, labeled as \(y_{j}\). For a given prompt \(x\), the reward model learns to favor the human-preferred completion \(y_{j}\), while minimizing the log sigmoid of the reward difference, \(r_{j} - r_{k}\).</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/8_train_reward_model-480.webp 480w,/assets/img/posts/genai_llm_5/8_train_reward_model-800.webp 800w,/assets/img/posts/genai_llm_5/8_train_reward_model-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/8_train_reward_model.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 8.</b> Train the reward model. Source: course lecture. </div> <p>Once the model has been trained on the human ranked prompt-completion pairs, we can use the reward model as a <b>binary classifier</b> to provide a set of <b>logits</b> (i.e. reward values) across the positive and negative classes. The logits are the unnormalized model outputs before applying any activation function. If we apply the softmax function to the logits, we get probabilities. The examples below (Figure 9) show a good and a bad example for the rewards.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/9_use_reward_model-480.webp 480w,/assets/img/posts/genai_llm_5/9_use_reward_model-800.webp 800w,/assets/img/posts/genai_llm_5/9_use_reward_model-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/9_use_reward_model.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 9.</b> Use the reward model. Source: course lecture. </div> <h2 id="rlhf-fine-tuning">RLHF: fine-tuning</h2> <p>Start with a model that already has good performance on the task of interest, i.e. an instruction fine-tuned LLM. A higher reward value represents a more aligned response, vice versa.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/10_fine-tune-480.webp 480w,/assets/img/posts/genai_llm_5/10_fine-tune-800.webp 800w,/assets/img/posts/genai_llm_5/10_fine-tune-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/10_fine-tune.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 10.</b> Use the reward model to fine-tune LLM with RL. Source: course lecture. </div> <p>Proceed the fine-tuning with multiple iterations. In the following example (Figure 11), we can see that the completion generated by the <b>RL-updated LLM</b> receives a higher reward score, indicating that the updates to weights have resulted in a more aligned completion. If the process works well, we will see the reward improving after each iteration as the model produces text that is increasingly aligned with human preferences.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/11_iterations-480.webp 480w,/assets/img/posts/genai_llm_5/11_iterations-800.webp 800w,/assets/img/posts/genai_llm_5/11_iterations-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/11_iterations.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 11.</b> Fine-tuning iterations. Source: course lecture. </div> <p>We continue the iterative process until the model is aligned based on some evaluation criteria. For example, reaching a threshold value for the helpfulness we defined. We can also define a maximum number of steps, for example, 20, 000 as the stopping criteria.</p> <p>At this point, we can refer the fine-tuned model as the <b>human-aligned LLM</b>.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/12_iteration_n-480.webp 480w,/assets/img/posts/genai_llm_5/12_iteration_n-800.webp 800w,/assets/img/posts/genai_llm_5/12_iteration_n-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/12_iteration_n.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 12.</b> Human-aligned LLM. Source: course lecture. </div> <h2 id="proximal-policy-optimization">Proximal policy optimization</h2> <p><b>Proximal policy optimization (PPO)</b> is the most widely used alogirthm for the reinforcement learning step in RLHF pipelines. PPO optimizes a policy, in this case the LLM, to be more aligned with human preferences. So the goal is to update the policy to maximize the reward. Over many iterations, PPO makes updates to the LLM. The updates are small and within a bounded region, resulting in an updated LLM that is close to the previous version. Keeping the changes within the small region results in a more stable learning.</p> <p>At a high level, each cycle of PPO goes over 2 phases.</p> <h4 id="ppo-phase-1-create-completions">PPO Phase 1: Create completions</h4> <p>In phase 1, the LLM is used to carry out a number of experiments to complete the given prompts. These experiments allow us to update the LLM against the reward model in phase 2.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/13_ppo_experiments-480.webp 480w,/assets/img/posts/genai_llm_5/13_ppo_experiments-800.webp 800w,/assets/img/posts/genai_llm_5/13_ppo_experiments-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/13_ppo_experiments.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 13.</b> PPO Phase 1: create completions. Source: course lecture. </div> <p>Recall that the reward model captures human preference. For example, the reward can define how helpful, harmless, and honest the responses are. The expected reward of a completion is an important quantity used in the PPO objective. We estimate this quantity through a separate head of the LLM called the <b>value function</b>.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/14_estimated_future_total_reward-480.webp 480w,/assets/img/posts/genai_llm_5/14_estimated_future_total_reward-800.webp 800w,/assets/img/posts/genai_llm_5/14_estimated_future_total_reward-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/14_estimated_future_total_reward.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 14.</b> Estimated future total reward. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/15_value_loss-480.webp 480w,/assets/img/posts/genai_llm_5/15_value_loss-800.webp 800w,/assets/img/posts/genai_llm_5/15_value_loss-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/15_value_loss.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 15.</b> Calculate value loss. Source: course lecture. </div> <p><b>How to calculate value loss:</b></p> <p>Assume a number of prompts are given, we first generate LLM response to the prompts, then calculate the reward for the prompt completions using the reward model.</p> <ul> <li> <p>The value function estimates the expected total rewards for a given state s. In other words, as the LLM generates each token of a completion, we want to estimate the total future reward based on the current sequence of tokens. Think of this as a baseline to evaluate the quality of completions agains the alignment criteria. In the following example, with the completion of the first token, the total estimated future reward is 0.34; with the next generated token, the estimated future total reward increases to 1.23.</p> </li> <li> <p>The goal is to minimize the value loss, which is the difference between the actual future total reward and the estimation to the value function.</p> </li> </ul> <p>The value loss makes the estimates for future rewards more accurate. The value function is then used in Advantage Estimation in phase 2.</p> <h4 id="ppo-phase-2-model-update">PPO Phase 2: Model update</h4> <p>In phase 2, we make small updates to the model, and evaluate the impact of those updates on the alignment goal. The model weights updates are guided by the prompt completion, losses, and rewards.</p> <p>PPO ensures to keep the model updates within a certain small region called the <b>trust region</b>. This is where the <b>proximal</b> aspect of PPO comes into play. Ideally, this series of small updates will move the model towards higher rewards.</p> <p><b>The policy loss</b> is the main objective that the PPO algorithm tries to optimize during training.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/16_policy_loss-480.webp 480w,/assets/img/posts/genai_llm_5/16_policy_loss-800.webp 800w,/assets/img/posts/genai_llm_5/16_policy_loss-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/16_policy_loss.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 16.</b> Calculate policy loss. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/17_trust_region-480.webp 480w,/assets/img/posts/genai_llm_5/17_trust_region-800.webp 800w,/assets/img/posts/genai_llm_5/17_trust_region-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/17_trust_region.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 17.</b> Trust region. Source: course lecture. </div> <p><b>Calculate policy loss</b></p> <ul> <li>\(a_{t}\) is the next token, \(s_{t}\) is the completed prompt up to the token \(t\).</li> <li>The denominator of the first term is the probability of the next token with the initial version of the LLM which is frozen. The numerator is the probability of the next token, through the updated LLM, which we can change for the better reward. \(\hat{A_{t}}\) is called the <b>estimated advantage</b> of a given choice of action. The advantage term estimates how much better or worse the current action is compared to all possible actions at that state. So we look at the expected future rewards of a completion following the new token, and we estimate how advantageous this completion is compared to the rest. <ul> <li>A positive \(\hat{A_{t}}\) means the suggested token is better than the average. Therefore, increasing the probability of the current token seems like a good strategy that leads to higher rewards. This translates to maximizing the expression we have here. If the suggested token is worse than average, the advantage will be negative. Then maximizing the expression will demote the token, which is the correct strategy.</li> <li>So the overall conclusion is that maximizing this expression results in a better aligned LLM.</li> <li>Directly maximizing the expression would lead to problems because our calculation is reliable under the assumption that our advantage estimations are valid. <b>The advantage estimations are valid only when the old and new policies are close to each other.</b> This is where the rest of the terms come into play.</li> </ul> </li> <li>The second term defines a region where the two policies are near each other. These extra terms are guardrails, and simply define a region in proximity to the LLM, where our estimates have small errors. This is called the <b>trust region</b>. These extra terms ensure that we are unlikely to leave the trust region.</li> <li>In summary, optimizing the PPO policy objective results in a better LLM without overshooting to unreliable regions.</li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/18_entropy_loss_and_objective_function-480.webp 480w,/assets/img/posts/genai_llm_5/18_entropy_loss_and_objective_function-800.webp 800w,/assets/img/posts/genai_llm_5/18_entropy_loss_and_objective_function-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/18_entropy_loss_and_objective_function.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 18.</b> Entropy loss and PPO objective function. Source: course lecture. </div> <p><b>Calculate entropy loss</b></p> <ul> <li>While the policy loss moves the model toward the alignment goal, <b>entropy loss</b> allows the model to maintain creativity. If we keep entropy low, we may end up always completing the prompt in the same way. This is similar to the <b>temperature</b> setting. The difference is that temperature influences model creativity during the inference time, while the entropy influences the model creativity during training.</li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/19_human-aligned_llm-480.webp 480w,/assets/img/posts/genai_llm_5/19_human-aligned_llm-800.webp 800w,/assets/img/posts/genai_llm_5/19_human-aligned_llm-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/19_human-aligned_llm.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 19.</b> Update to human-aligned LLM. Source: course lecture. </div> <p>Once the model weights are updated, PPO starts a new cycle. For the next iteration, the LLM is replaced with the updated LLM, and a new PPO cycle starts. After many iterations, we arrive at the human-aligned LLM.</p> <h2 id="rlhf-reward-hacking">RLHF: reward hacking</h2> <p>As the policy tries to maximize the reward, it can diverge too much from the original language model.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_5/20_avoid_reward_hacking-480.webp 480w,/assets/img/posts/genai_llm_5/20_avoid_reward_hacking-800.webp 800w,/assets/img/posts/genai_llm_5/20_avoid_reward_hacking-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_5/20_avoid_reward_hacking.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 20.</b> Avoid reward hacking. Source: course lecture. </div> <p>To avoid reward hacking, we can use the instruct model as a <b>reference model</b>. The weights of the reference model are frozen, and are not updated during iterations of RLHF. This way, we always maintain a single reference model to compare to.</p> <p>During training, each prompt is passed to both models, generating a completion by the reference LLM and the intermediate LLM updated model. At this point, we can compare the two completions and calculate a value called the <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence"><b>KL divergence</b></a>. KL divergence is a statistical measure of how different two probability distributions are. We can use it to compare the completions of the two models and determine how much the updated model has diverged from the reference model.</p> <p>KL divergence is calculated for each generated token across the whole vocabulary of the LLM. This can easily be tens or hundreds or thousands of tokens. Although softmax gives a probability for every token, in practice, most of the probability mass is concentrated on a small number of likely tokens, making the distribution effectively sparse. This is still a relatively expensive process. So we will always benefit from using GPUs.</p> <p>Once we calculate the KL divergence between the two models, we add it as a term to the reward calculation. This will <b>penalize</b> the RL updated model if it shifts too far from the reference LLM and generates completions that are too different.</p> <p>Note that we need two full copies of the LLM to calculate KL divergence, the frozen reference LLM, and the RL updated PPO LLM. We can benefit from combining RLHF with <b>PEFT</b>. In this case, we only update the weights of a PEFT adapter, not the full weights of the LLM. This means we can reuse the same underlying LLM for both the reference model and the PPO model, which we update with trained PEFT parameters. This reduces the memory footprint during training by approximately half.</p> <h2 id="scaling-human-feedback">Scaling human feedback</h2> <p><b>Constitutional AI</b> is a method for training models using a set of rules and principles that govern the model’s behavior. We train the model to self-critique and revise its response to comply with those principles.</p> <p>Constitutional AI is useful not only for scaling feedback, it can also help to address some unintended consequences of RLHF. For example, depending on how the prompt is structured, an aligned model may end up revealing harmful information as it tries to provide the most helpful response it can. Providing the model with a set of constitutional principles can help the model balance these competing interests and minimize the harm.</p> <h2 id="references">References</h2> <ul> <li><a href="https://arxiv.org/pdf/2203.02155.pdf">Training language models to follow instructions with human feedback</a> <ul> <li>Paper by OpenAI introducing a human-in-the-loop process to create a model that is better at following instructions (InstructGPT).</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2009.01325.pdf">Learning to summarize from human feedback</a> <ul> <li>This paper presents a method for improving language model-generated summaries using a reward-based approach, surpassing human reference summaries.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/1707.06347.pdf">Proximal Policy Optimization Algorithms</a> <ul> <li>The paper from researchers at OpenAI that first proposed the PPO algorithm. The paper discusses the performance of the algorithm on a number of benchmark tasks including robotic locomotion and game play.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2305.18290.pdf">Direct Preference Optimization: Your Language Model is Secretly a Reward Model</a> <ul> <li>This paper presents a simpler and effective method for precise control of large-scale unsupervised language models by aligning them with human preferences.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2212.08073.pdf">Constitutional AI: Harmlessness from AI Feedback</a> <ul> <li>This paper introduces a method for training a harmless AI assistant without human labels, allowing better control of AI behavior with minimal human input.</li> </ul> </li> </ul>]]></content><author><name></name></author><category term="llm"/><summary type="html"><![CDATA[Course summary of Generative AI with Large Language Models. Part Five.]]></summary></entry><entry><title type="html">GenAI with LLMs (4) Parameter-efficient fine-tuning</title><link href="https://wenwenkong.github.io/blog/2025/gen-ai-llm-4/" rel="alternate" type="text/html" title="GenAI with LLMs (4) Parameter-efficient fine-tuning"/><published>2025-06-28T00:00:00+00:00</published><updated>2025-06-28T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2025/gen-ai-llm-4</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2025/gen-ai-llm-4/"><![CDATA[<p>This post covers parameter-efficient fine-tuning from the <strong>Generative AI With LLMs</strong> course offered by DeepLearning.AI.</p> <h2 id="why-parameter-efficient-fine-tuning-peft">Why Parameter efficient fine-tuning (PEFT)</h2> <p><b>Full fine-tuning</b> results in a new version of the original LLM for every task trained on. Each of the new version is the same size as the original model, so it can create an expensive storage problem if fine-funing for multiple tasks.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/1_full_finetuning-480.webp 480w,/assets/img/posts/genai_llm_4/1_full_finetuning-800.webp 800w,/assets/img/posts/genai_llm_4/1_full_finetuning-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/1_full_finetuning.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> Full fine-tuning creates full copy of original LLM per task. Source: course lecture. </div> <p>In contrast to <b>full fine-tuning</b> where every model weight is updated during supervised learning, <b>PEFT</b> only updates a small subset of parameters. Some PEFT techniques freeze most of the model weights and focus on fine-tuning a subset of existing model parameters, for example, particular layers or components. Other techniques don’t touch the model weights at all, and instead add a small number of new parameters or layers and fine-tune only the new components.</p> <p>With PEFT, most if not all of the model weights are kept frozen. As a result, the number of trained parameters is much smaller than the number of parameters in the original LLM. In some cases, just 15-20 % of the original LLM weights. This makes the memory requirements for training much more manageable. In fact, PEFT can often be performed on a single GPU. And because the original LLM is only slightly modified or left unchanged, PEFT is less prone to the catastrophic forgetting problem of full fine-tuning.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/2_PEFT-480.webp 480w,/assets/img/posts/genai_llm_4/2_PEFT-800.webp 800w,/assets/img/posts/genai_llm_4/2_PEFT-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/2_PEFT.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 2.</b> Parameter efficient fine-tuning (PEFT). Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/3_PEFT-480.webp 480w,/assets/img/posts/genai_llm_4/3_PEFT-800.webp 800w,/assets/img/posts/genai_llm_4/3_PEFT-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/3_PEFT.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 3.</b> PEFT fine-tuning saves space and is flexible. Source: course lecture. </div> <h2 id="peft-methods">PEFT methods</h2> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/4_PEFT_methods-480.webp 480w,/assets/img/posts/genai_llm_4/4_PEFT_methods-800.webp 800w,/assets/img/posts/genai_llm_4/4_PEFT_methods-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/4_PEFT_methods.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 4.</b> PEFT methods taxonomy. Source: <a href="https://arxiv.org/pdf/2303.15647" target="_blank">Lialin et al. 2024, Scaling Down to Scale Up: A Guide to Parameter-Efficient Fine-Tuning</a>. </div> <h4 id="selective">Selective</h4> <p><b>Select</b> subset of initial LLM parameters to fine-tune. There are several methods you can take to identify which parameters you want to update. But performance of these methods (i.e., train only certain components, layers, or just individual parameter types) are mixed and there are significant trade-offs between parameter efficiency and compute efficiency.</p> <h4 id="reparameterization">Reparameterization</h4> <p><b>Reparameterize</b> model weights using a low-rank representation. It works with the original LLM parameters, but reduces the number of parameters to train by creating new low rank transformations of the original network weights.</p> <h4 id="additive">Additive</h4> <p><b>Add</b> trainable layers or parameters to model. This fine-tuning method keeps all of the original LLM weights frozen and introducing new trainable components. For example,</p> <ul> <li><b>Adapter</b> adds new trainable layers to the architecture of the model, typically inside the encoder or decoder components after the attention or feed-forward layers.</li> <li><b>Soft prompts</b> keep the model architecture fixed and frozen, and focus on manipulating the input to achieve better performance. This can be done by adding trainable parameters to the prompt embeddings or keeping the input fixed and retraining the embedding weights.</li> </ul> <h2 id="lora">LoRA</h2> <p>LoRA == <a href="https://arxiv.org/abs/2106.09685">Low-Rank Adaptation of Large Language Models</a></p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/5_Transformers_recap-480.webp 480w,/assets/img/posts/genai_llm_4/5_Transformers_recap-800.webp 800w,/assets/img/posts/genai_llm_4/5_Transformers_recap-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/5_Transformers_recap.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 5.</b> Transformers recap. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/6_Transformers_recap-480.webp 480w,/assets/img/posts/genai_llm_4/6_Transformers_recap-800.webp 800w,/assets/img/posts/genai_llm_4/6_Transformers_recap-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/6_Transformers_recap.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 6.</b> Transformers recap. Source: course lecture. </div> <h4 id="lora-workflow">LoRA workflow</h4> <ol> <li> <p>Freeze most of the original LLM weights, i.e. weights applied to embedding vectors</p> </li> <li> <p>Inject 2 rank decomposition matrices</p> <ul> <li>The dimensions of the smaller matrices are set so their product is a matrix with the same dimensions as the weights they are modifying.</li> </ul> </li> <li> <p>Train the weights of the smaller matrices</p> <ul> <li>Keep the original weights of the LLM frozen and train the smaller matrices.</li> </ul> </li> <li> <p>Inference</p> <ul> <li>For inference, the two low-rank matrices are multiplied together to create a matrix with the same dimensions as the frozen weights. Add this to the original weights and replace them in the model with the updated values.</li> </ul> </li> </ol> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/7_LoRA-480.webp 480w,/assets/img/posts/genai_llm_4/7_LoRA-800.webp 800w,/assets/img/posts/genai_llm_4/7_LoRA-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/7_LoRA.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 7.</b> LoRA workflow. Source: course lecture. </div> <p><b>Note:</b></p> <ul> <li>Because the LoRA fine-tuned model has the same number of parameters with the original model, there is little to no impact on inferenc latency.</li> <li>Researchers have found that applying LoRA to just the <b>self-attention</b> layers of the model is often enough to fine-tune for a task and achieve performance gains. In principle, you can also use LoRA on other components like the feed-forward layers. However, since most of the parameters of LLMs are in the attention layers, you get the biggest savings in trainable parameters by applying LoRA to these weights matrices.</li> <li>Because LoRA allows you to significantly reduce the number of trainable parameters, you can often perform this PEFT method with a single GPU and avoid the need for a distributed cluster of GPUs.</li> </ul> <h4 id="lora-math-behind">LoRA: math behind</h4> <p>Use the base Transformer model presented by Vaswani et al. 2017 as an example, consider LoRA wight rank \(r = 8\).</p> <p><strong>Base weight:</strong></p> \[W_0 \in \mathbb{R}^{d \times k} = \mathbb{R}^{512 \times 64} \Rightarrow 32{,}768 \text{ parameters}\] <p><strong>LoRA low-rank matrices:</strong></p> \[A \in \mathbb{R}^{r \times k} = \mathbb{R}^{8 \times 64} \Rightarrow 512 \text{ parameters}\] \[B \in \mathbb{R}^{d \times r} = \mathbb{R}^{512 \times 8} \Rightarrow 4{,}096 \text{ parameters}\] <p><strong>Total LoRA parameters trained:</strong></p> \[512 + 4096 = 4,608\] <p><strong>Parameter reduction:</strong></p> \[1 - \frac{4608}{32768} = 0.859 \Rightarrow \text{~86% reduction}\] <p>Understanding why the total parameters during the inference stays the same.</p> <p><strong>During training:</strong></p> <ul> <li>The original weight matrix \(W_0\) is frozen</li> <li>Two small matrices \(A \in \mathbb{R}^{r \times k}\), \(B \in \mathbb{R}^{d \times r}\) are trained</li> <li>The effective weight becomes \(W = W_0 + \Delta W = W_0 + B \cdot A\)</li> <li>The model learns the low-rank update \(\Delta W\), which is far smaller in size then \(W_0\)</li> </ul> <p><strong>At inference:</strong></p> <ul> <li>Merge the update \(B \cdot A\) into \(W_0\) ahead of time</li> <li>So still using a matrix of size \(d x k\), not adding more layers or extra computations during forward pass</li> <li>Thus, inference speed and memory stay the same as the original model</li> </ul> <h4 id="lora-for-different-tasks">LoRA for different tasks</h4> <p>Since the rank-decomposition matrices are small, you can fine-tune a different set for each task and then switch them out at inference time by updating the weights.</p> <p>Suppose you train a pair of LoRA matrices for a specific task, Task A. To carry out inference on this task, you would multiply these matrices together and then add the resulting matrix to the original frozen weights. You then take this summed weight matrix and replace the original weights where they appear in your model. You can then use this model to carry out inference on Task A. And you can repeat the same process for task B.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/8_different_tasks_A-480.webp 480w,/assets/img/posts/genai_llm_4/8_different_tasks_A-800.webp 800w,/assets/img/posts/genai_llm_4/8_different_tasks_A-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/8_different_tasks_A.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 8.</b> LoRA for different tasks. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/9_different_tasks_B-480.webp 480w,/assets/img/posts/genai_llm_4/9_different_tasks_B-800.webp 800w,/assets/img/posts/genai_llm_4/9_different_tasks_B-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/9_different_tasks_B.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 9.</b> LoRA for different tasks. Source: course lecture. </div> <h4 id="lora-other-notes">LoRA: other notes</h4> <p>ROUGE metrics from LoRA fine-tuning only slightly suffers compared to that from full fine-tuning.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/10_sample_ROUGE-480.webp 480w,/assets/img/posts/genai_llm_4/10_sample_ROUGE-800.webp 800w,/assets/img/posts/genai_llm_4/10_sample_ROUGE-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/10_sample_ROUGE.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 10.</b> Sample ROUGE metrics for full vs. LoRA fine-tuning. Source: course lecture. </div> <p>How to choose the rank?</p> <ul> <li>The smaller the rank, the smaller number of trainable parameters, and the bigger saving on compute.</li> <li>Ranks in the range of 4 to 32 can provide a good trade-off between reducing trainable parameters and preserving performance.</li> <li>Optimizing the choice of rank is an ongoing area of research and best practices may evolve.</li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/11_choosing_rank-480.webp 480w,/assets/img/posts/genai_llm_4/11_choosing_rank-800.webp 800w,/assets/img/posts/genai_llm_4/11_choosing_rank-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/11_choosing_rank.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 11.</b> Metrics from different ranks (<a href="https://arxiv.org/abs/2106.09685" target="_blank">source</a>). </div> <h2 id="soft-prompt">Soft prompt</h2> <p>Prompt tuning is <b>not</b> prompt engineering. With prompt tuning, you add additional trainable tokens to your prompt and leave it up to the supervised learning process to determine their optimal values. The set of trainable tokens is called a <b>soft prompt</b>, and it gets prepended to embedding vectors that represent your input text. The soft prompt vectors have the same length as the embedding vectors of the language tokens. Usually 20-100 tokens can be sufficient for good performance.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/12_prompt_tuning-480.webp 480w,/assets/img/posts/genai_llm_4/12_prompt_tuning-800.webp 800w,/assets/img/posts/genai_llm_4/12_prompt_tuning-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/12_prompt_tuning.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 12.</b> Prompt tuning adds trainable soft prompt to inputs. Source: course lecture. </div> <p>The tokens that represent natural language are hard in the sense that they each correspond to a fixed location in the embedding vector space. However, the soft prompts are not fixed discrete words of natural language. Instead, you can think of them as virtual tokens that can take on any value within the continuous multidimensional embedding space. Through supervised learning, the model learns the values for these virtual tokens that maximize performance for a given task.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/13_soft_prompt-480.webp 480w,/assets/img/posts/genai_llm_4/13_soft_prompt-800.webp 800w,/assets/img/posts/genai_llm_4/13_soft_prompt-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/13_soft_prompt.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 13.</b> Soft prompt tokens are not fixed in the embedding vector space. Source: course lecture. </div> <p>In full fine-tuning, the training data set consists of input prompts and output completions or labels. The weights of the LLM are updated during supervised learning. In contrast, with prompt tuning, the weights of the LLM are <b>frozen</b> and the underlying model does not get updated. Instead, the embedding vectors of the soft prompt gets updated over time optimize the model’s completion of the prompt. Prompt tuning is a very parameter efficient strategy because only a few parameters are being trained. Similar to LoRA, you can train a different set of soft prompts for each task and then easily swap them out at inference time.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/14_full_vs_soft-480.webp 480w,/assets/img/posts/genai_llm_4/14_full_vs_soft-800.webp 800w,/assets/img/posts/genai_llm_4/14_full_vs_soft-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/14_full_vs_soft.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 14.</b> Full fine-tuning vs prompt tuning. Source: course lecture. </div> <p>Prompt tuning doesn’t perform as well as full fine-tuning for smaller LLMs. However, as the model size increases, so does the performance of prompt tuning.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/15_prompt_tuning_performance-480.webp 480w,/assets/img/posts/genai_llm_4/15_prompt_tuning_performance-800.webp 800w,/assets/img/posts/genai_llm_4/15_prompt_tuning_performance-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/15_prompt_tuning_performance.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 15.</b> Performance of prompt tuning. Source: course lecture. </div> <p>Because the soft prompt tokens can take any value within the continuous embedding vector space, the trained tokens don’t correspond to any known token, word, or phrase in the vocabulary of the LLM. Therefore interpretability of the virtual tokens can be a potential issue. An analysis of the nearest neighbor tokens to the soft prompt location shows that they form tight semantic clusters. That is, the words closest to the soft prompt tokens have similar meanings. The words identified usually have some meaning related to the task, suggesting that the prompts are learning word-like representations.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_4/16_interpretability-480.webp 480w,/assets/img/posts/genai_llm_4/16_interpretability-800.webp 800w,/assets/img/posts/genai_llm_4/16_interpretability-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_4/16_interpretability.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 16.</b> Interpretability of soft prompts. </div> <h2 id="references">References</h2> <ul> <li><a href="https://arxiv.org/pdf/2303.15647.pdf">Scaling Down to Scale Up: A Guide to Parameter-Efficient Fine-Tuning</a> <ul> <li>This paper provides a systematic overview of Parameter-Efficient Fine-tuning (PEFT) Methods in all three categories discussed in the lecture videos.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2211.15583.pdf">On the Effectiveness of Parameter-Efficient Fine-Tuning</a> <ul> <li>The paper analyzes sparse fine-tuning methods for pre-trained models in NLP.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2106.09685.pdf">LoRA Low-Rank Adaptation of Large Language Models</a> <ul> <li>This paper proposes a parameter-efficient fine-tuning method that makes use of low-rank decomposition matrices to reduce the number of trainable parameters needed for fine-tuning language models.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2305.14314.pdf">QLoRA: Efficient Finetuning of Quantized LLMs</a> <ul> <li>This paper introduces an efficient method for fine-tuning large language models on a single GPU, based on quantization, achieving impressive results on benchmark tests.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2104.08691.pdf">The Power of Scale for Parameter-Efficient Prompt Tuning</a> <ul> <li>The paper explores “prompt tuning,” a method for conditioning language models with learned soft prompts, achieving competitive performance compared to full fine-tuning and enabling model reuse for many tasks.</li> </ul> </li> </ul>]]></content><author><name></name></author><category term="llm"/><summary type="html"><![CDATA[Course summary of Generative AI with Large Language Models. Part Four.]]></summary></entry><entry><title type="html">GenAI with LLMs (3) Instruction fine-tuning</title><link href="https://wenwenkong.github.io/blog/2025/gen-ai-llm-3/" rel="alternate" type="text/html" title="GenAI with LLMs (3) Instruction fine-tuning"/><published>2025-06-21T00:00:00+00:00</published><updated>2025-06-21T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2025/gen-ai-llm-3</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2025/gen-ai-llm-3/"><![CDATA[<p>This post covers instruction fine-tuning from the <strong>Generative AI With LLMs</strong> course offered by DeepLearning.AI.</p> <h2 id="llm-fine-tuning-at-a-high-level">LLM fine-tuning at a high level</h2> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/1_finetuning_highlevel-480.webp 480w,/assets/img/posts/genai_llm_3/1_finetuning_highlevel-800.webp 800w,/assets/img/posts/genai_llm_3/1_finetuning_highlevel-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/1_finetuning_highlevel.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> LLM fine-tuning at a high level. Source: course lecture. </div> <h4 id="why-we-need-llm-fine-tuning">Why we need LLM fine-tuning</h4> <p>Recall In-context learning: zero-shot, one-shot, and few-shot inference. See <a href="https://wenwenkong.com/blog/2025/gen-ai-llm-1/#prompt-engineering">this note</a> for more details.</p> <p>We need LLM fine-tuning because in-context learning has several drawbacks:</p> <ul> <li>For smaller models, the in-context learning doesn’t always work, even when 5 or 6 examples are included.</li> <li>Any examples you include in your prompt take up valuable space in the context window, reducing the amount of room you have to include other useful information.</li> </ul> <h4 id="what-is-llm-fine-tuning">What is LLM fine-tuning</h4> <p>Fine-tuning is a <b>supervised learning</b> process, where you use a dataset of labeled examples to update the weights of the LLM.</p> <p><b>Instruction fine-tuning</b> trains the model using examples demonstrating how it should respond to a specific instruction. The labeled examples are <b>prompt-completion pairs</b>; the fine-tuning process extends the training of the model to improve its ability to generate good completions for a specific task.</p> <p>Each example in the prompt-completion pairs datasets begins with <b>instructions</b>. For example, if you want to fine-tune your model to improve its summarization ability, you’d build up a dataset of examples that begin with instruction “summarize the following text” or a similar phrase; if you are improving the model’s translation skills, your examples would include instructions like “translate this sentence”. These examples allow the model to learn to generate responses following given responses.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/2_finetuning_highlevel-480.webp 480w,/assets/img/posts/genai_llm_3/2_finetuning_highlevel-800.webp 800w,/assets/img/posts/genai_llm_3/2_finetuning_highlevel-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/2_finetuning_highlevel.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 2.</b> Using prompts to fine-tune LLMs with instruction. Source: course lecture. </div> <p><b>Instruction fine-tuning</b>, where all of the model’s weights are updated, is known as <b>full fine-tuning</b>. The process results in a new version of the model with updated weights. Note that just like pre-training, full fine-tuning requires enough memory and compute budget to store and process all the gradients, optimizers, and other components that are being updated during training.</p> <h2 id="llm-fine-tuning-process">LLM fine-tuning process</h2> <p>First step of instruction fine-tuning is to prepare your training data. There is much publicly available data that has been used to train earlier generations of LLMs, but not all of them are formatted as instructions. Developers have assembled <a href="https://github.com/bigscience-workshop/promptsource/tree/main/promptsource/templates">prompt template libraries</a> that can be used to take existing dataset. For example,turn the large dataset of Amazon product review into instruction prompt datasets for fine-tuning (see <b>Figure 3</b>, <a href="https://github.com/bigscience-workshop/promptsource/blob/main/promptsource/templates/amazon_polarity/templates.yaml">source</a>). In each case, you pass in the original review, here called <code class="language-plaintext highlighter-rouge">review_body</code>, to the template, where it gets inserted into the text that starts with an instruction. The result is a prompt that now contains both an instruction and the example from the dataset.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/3_prompt_instruction_template-480.webp 480w,/assets/img/posts/genai_llm_3/3_prompt_instruction_template-800.webp 800w,/assets/img/posts/genai_llm_3/3_prompt_instruction_template-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/3_prompt_instruction_template.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 3.</b> Sample prompt instruction templates. Source: course lecture. </div> <p>Once the instruction dataset is ready, we divide the dataset into <code class="language-plaintext highlighter-rouge">training</code>, <code class="language-plaintext highlighter-rouge">validation</code>, <code class="language-plaintext highlighter-rouge">test</code> split.</p> <p>During fine-tuning, we select prompts from the training set and pass them to the LLM which then generates completions. Next, we compare LLM completion with the response specified in the training data.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/4_finetuning_process-480.webp 480w,/assets/img/posts/genai_llm_3/4_finetuning_process-800.webp 800w,/assets/img/posts/genai_llm_3/4_finetuning_process-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/4_finetuning_process.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 4.</b> LLM fine-tuning process. Source: course lecture. </div> <p>Recall that the output of an LLM is a probability distribution across tokens. So we can compare the distribution of the completion and that of the training label, and use the standard <a href="https://en.wikipedia.org/wiki/Cross-entropy"><b>cross entropy function</b></a> to calculate <b>loss</b> between the two token distributions. Then use the calculated loss to update model weights in standard <b>backpropagation</b>. Do this for many batches of prompt completion pairs and over several epochs, update the weights so that the model’s performance on the task improves. Then get the <b>validation_accuracy</b> using the holdout validation set, and get the <b>test_accuracy</b> once you apply the model to the test set.</p> <h2 id="single-task-vs-multi-task">Single task vs. Multi-task</h2> <h3 id="single-task-fine-tuning">Single task fine-tuning</h3> <p>Good results can be achieved with relatively few examples (often 500-1000 examples) for single task fine-tuning. However, fine-tuning on a single task can lead to <b>catastrophic forgetting</b>, i.e. fine-tuning significantly improves performance of the model on a specific task but degrades performance on other tasks.</p> <p>How to avoid catastrophic forgetting?</p> <ul> <li>First of all, you might not have to if you only care about the task you fine-tuned for</li> <li>Fine-tune on multiple tasks at the same time</li> <li>Consider Parameter Efficient Fine-tuning (PEFT)</li> </ul> <h3 id="multi-task-fine-tuning">Multi-task fine-tuning</h3> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/5_multitask_finetuning-480.webp 480w,/assets/img/posts/genai_llm_3/5_multitask_finetuning-800.webp 800w,/assets/img/posts/genai_llm_3/5_multitask_finetuning-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/5_multitask_finetuning.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 5.</b> Multi-task fine-tuning. Source: course lecture. </div> <p>Over many epochs of training, the calculated losses across examples are used to update the weights of the model, resulting in an instruction fine-tuned model that learned how to be good at many different tasks simultaneously.</p> <p>Drawback to multi-task fine-tuning: requires a lot of data. However, it can be very worthwhile and worth the effort to assemble this data. The resulting models are often very capable and suitable for use in situations where good performance at many tasks is desirable.</p> <h2 id="instruction-fine-tuning-with-flan">Instruction fine-tuning with FLAN</h2> <p>FLAN == <b>F</b>ine-tuned <b>LA</b>nguage <b>N</b>et. FLAN models refer to a specific set of instructions used to perform instruction fine-tuning. FLAN-T5 (fine-tuned version of pre-trained T5 model) is a great, general purpose, instruct model.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/6_FLAN-480.webp 480w,/assets/img/posts/genai_llm_3/6_FLAN-800.webp 800w,/assets/img/posts/genai_llm_3/6_FLAN-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/6_FLAN.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 6.</b> Datasets and task categories employed in FLAN fine-tuning, <a href="https://arxiv.org/abs/2210.11416" target="_blank">source</a>. </div> <h2 id="llm-evaluation">LLM evaluation</h2> <h4 id="metrics-rouge">Metrics: ROUGE</h4> <p><b>ROUGE</b> is used for text summarization and text generation tasks. Figures in below demonstrate usage of <b>ROUGE-1</b>, <b>ROUGE-2</b>, <b>ROUGE-L</b>, and <b>ROUGE clipping</b>.</p> <p><b>ROUGE-1</b> measures the overlap of <b>unigrams (single words)</b> between the generated and reference texts.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/7_ROUGE_1-480.webp 480w,/assets/img/posts/genai_llm_3/7_ROUGE_1-800.webp 800w,/assets/img/posts/genai_llm_3/7_ROUGE_1-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/7_ROUGE_1.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 7.</b> ROUGE-1. Source: course lecture. </div> <p><b>ROUGE-2</b> measures the overlap of <b>bigrams (two-word sequences)</b> between the generated and reference texts.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/8_ROUGE_2-480.webp 480w,/assets/img/posts/genai_llm_3/8_ROUGE_2-800.webp 800w,/assets/img/posts/genai_llm_3/8_ROUGE_2-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/8_ROUGE_2.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 8.</b> ROUGE-2. Source: course lecture. </div> <p><b>ROUGE-L</b> measures the <b>longest common subsequences (LCS)</b> between the generated and reference texts, capturing setence-level fluency and structure.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/9_ROUGE_L-480.webp 480w,/assets/img/posts/genai_llm_3/9_ROUGE_L-800.webp 800w,/assets/img/posts/genai_llm_3/9_ROUGE_L-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/9_ROUGE_L.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 9.</b> ROUGE-L. Source: course lecture. </div> <p><b>ROUGE clipping</b> limits the count of overlapping n-grams to the maximum number that appears in the reference, preventing the generated text from getting extra credit for repeated words.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_3/10_ROUGE_clipping-480.webp 480w,/assets/img/posts/genai_llm_3/10_ROUGE_clipping-800.webp 800w,/assets/img/posts/genai_llm_3/10_ROUGE_clipping-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_3/10_ROUGE_clipping.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 10.</b> ROUGE clipping. Source: course lecture. </div> <h4 id="metrics-bleu-score">Metrics: BLEU SCORE</h4> <p><b>BLEU SCORE</b> is used for text translation. Below is the core BLEU formula, from <a href="https://aclanthology.org/P02-1040.pdf">Papineni et al. 2002</a>.</p> \[\text{BLEU} = \text{BP} \cdot \exp\left( \sum_{n=1}^{N} w_n \log p_n \right)\] <ul> <li><strong>BLEU</strong>: The final BLEU score (0 to 1), evaluating how closely the generated text matches the reference.</li> <li><strong>BP</strong>: <em>Brevity Penalty</em> — penalizes candidates that are shorter than the reference.</li> <li><strong>\(\exp\)</strong>: Exponential function, used to combine the log-precisions into a geometric mean.</li> <li><strong>\(w_n\)</strong>: Weight for each n-gram order (e.g., 0.25 when using up to 4-grams).</li> <li><strong>\(p_n\)</strong>: <em>Modified precision</em> for n-grams of size \(n\), with clipping to avoid over-counting.</li> <li><strong>\(N\)</strong>: Maximum n-gram order (usually 4 in practice).</li> </ul> <h4 id="benchmarks">Benchmarks</h4> <p>Selecting an evaluating dataset is vital to an accurate evaluation of model performance. Example evaluation benchmarks include <a href="https://gluebenchmark.com/">GLUE</a>, <a href="https://super.gluebenchmark.com/">SuperGLUE</a>, <a href="https://paperswithcode.com/dataset/mmlu">MMLU (Massive Multitask Language Understanding)</a>, <a href="https://crfm.stanford.edu/helm/">HELM</a>, <a href="https://github.com/google/BIG-bench">Big-bench</a>, etc.</p> <h2 id="references">References</h2> <ul> <li><a href="https://arxiv.org/pdf/2210.11416.pdf">Scaling Instruction-Finetuned Language Models</a> <ul> <li>Scaling fine-tuning with a focus on task, model size and chain-of-thought data.</li> </ul> </li> <li><a href="https://ai.googleblog.com/2021/10/introducing-flan-more-generalizable.html">Introducing FLAN: More generalizable Language Models with Instruction Fine-Tuning</a> <ul> <li>This blog (and article) explores instruction fine-tuning, which aims to make language models better at performing NLP tasks with zero-shot inference.</li> </ul> </li> <li><a href="https://crfm.stanford.edu/helm/latest/">HELM - Holistic Evaluation of Language Models</a> <ul> <li>HELM is a living benchmark to evaluate Language Models more transparently.</li> </ul> </li> <li><a href="https://openreview.net/pdf?id=rJ4km2R5t7">General Language Understanding Evaluation (GLUE) benchmark</a> <ul> <li>This paper introduces GLUE, a benchmark for evaluating models on diverse natural language understanding (NLU) tasks and emphasizing the importance of improved general NLU systems.</li> </ul> </li> <li><a href="https://super.gluebenchmark.com/">SuperGLUE</a> <ul> <li>This paper introduces SuperGLUE, a benchmark designed to evaluate the performance of various NLP models on a range of challenging language understanding tasks.</li> </ul> </li> <li><a href="https://aclanthology.org/W04-1013.pdf">ROUGE: A Package for Automatic Evaluation of Summaries</a> <ul> <li>This paper introduces and evaluates four different measures (ROUGE-N, ROUGE-L, ROUGE-W, and ROUGE-S) in the ROUGE summarization evaluation package, which assess the quality of summaries by comparing them to ideal human-generated summaries.</li> </ul> </li> <li><a href="https://aclanthology.org/P02-1040.pdf">BLEU: a Method for Automatic Evaluation of Machine Translation</a></li> <li><a href="https://arxiv.org/pdf/2009.03300.pdf">Measuring Massive Multitask Language Understanding (MMLU)</a> <ul> <li>This paper presents a new test to measure multitask accuracy in text models, highlighting the need for substantial improvements in achieving expert-level accuracy and addressing lopsided performance and low accuracy on socially important subjects.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2206.04615.pdf">BigBench-Hard - Beyond the Imitation Game: Quantifying and Extrapolating the Capabilities of Language Models</a> <ul> <li>The paper introduces BIG-bench, a benchmark for evaluating language models on challenging tasks, providing insights on scale, calibration, and social bias.</li> </ul> </li> </ul>]]></content><author><name></name></author><category term="llm"/><summary type="html"><![CDATA[Course summary of Generative AI with Large Language Models. Part Three.]]></summary></entry><entry><title type="html">GenAI with LLMs (2) Pre-training</title><link href="https://wenwenkong.github.io/blog/2025/gen-ai-llm-2/" rel="alternate" type="text/html" title="GenAI with LLMs (2) Pre-training"/><published>2025-06-16T00:00:00+00:00</published><updated>2025-06-16T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2025/gen-ai-llm-2</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2025/gen-ai-llm-2/"><![CDATA[<p>This post covers LLM pre-training and scaling laws from the <strong>Generative AI With LLMs</strong> course offered by DeepLearning.AI.</p> <h2 id="model-cards">Model cards</h2> <p>Model cards are useful for understanding how a model is trained, its use case, and known limitations. See <a href="https://huggingface.co/docs/hub/en/model-cards">here</a> for a more complete definition from HuggingFace.</p> <p>Figures 1-2 are two example model cards from <a href="https://arxiv.org/abs/1810.03993">Mitchel et al. (2018)</a>. Figure 3 is the model card for T5 Large, captured from the lecture slides.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/1_modelcards_example-480.webp 480w,/assets/img/posts/genai_llm_2/1_modelcards_example-800.webp 800w,/assets/img/posts/genai_llm_2/1_modelcards_example-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/1_modelcards_example.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> Model card example from Mitchell et al. 2018. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/2_modelcards_example-480.webp 480w,/assets/img/posts/genai_llm_2/2_modelcards_example-800.webp 800w,/assets/img/posts/genai_llm_2/2_modelcards_example-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/2_modelcards_example.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 2.</b> Model card example from Mitchell et al. 2018. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/3_modelcards_T5-480.webp 480w,/assets/img/posts/genai_llm_2/3_modelcards_T5-800.webp 800w,/assets/img/posts/genai_llm_2/3_modelcards_T5-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/3_modelcards_T5.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 3.</b> Model card for T5. Source: course lecture. </div> <h2 id="token-filtering">Token filtering</h2> <p>Only 1-3% of original tokens are used to train the LLM. We should consider this when we estimate how much data we need to collect if we decide to pre-train our own model. In other words, data quality control or bias removal is always needed to increase data quality before training. This refers to the <b>token filtering</b> or <b>rejection process</b> during LLM pre-training.</p> <p>LLM developers all start from massive web-scale corpora, then spend huge effort on <b>filtering</b>, <b>deduplicating</b>, <b>scoring for quality</b>, and <b>weighting data by domain or value</b>. See <a href="https://arxiv.org/abs/2303.08774">GPT-4 Technical Report</a>, <a href="https://arxiv.org/abs/2302.13971">LLaMA</a>, and <a href="https://arxiv.org/abs/2203.15556">Chinchilla</a> for details.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/4_token_filtering-480.webp 480w,/assets/img/posts/genai_llm_2/4_token_filtering-800.webp 800w,/assets/img/posts/genai_llm_2/4_token_filtering-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/4_token_filtering.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 4.</b> LLMs pretraining at high level. Source: course lecture. </div> <h2 id="llms-pre-training">LLMs pre-training</h2> <p>Different LLMs pretrain using different objectives - from denoising (such as BERT), to predicting next tokens (such as GPT), to reconstructing corrupted input using a sequence-to-sequence setup (such as T5 and BART). These design choices affect how models behave. For example, BERT is optimized for understanding tasks, GPT excels at generating fluent and coherent outputs. T5 and BART aim to balance both.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/5_llm_pretraining-480.webp 480w,/assets/img/posts/genai_llm_2/5_llm_pretraining-800.webp 800w,/assets/img/posts/genai_llm_2/5_llm_pretraining-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/5_llm_pretraining.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 5.</b> Model architectures and pre-training objectives. Source: course lecture. </div> <h3 id="autoencoding-models">Autoencoding models</h3> <p>Autoencoding models like BERT are pre-trained using <b>masked language modeling</b>. In the context of autoencoding models, the pre-training task is often described as a <b>“denoising” objective</b> because the model learns to reconstruct the original text from a corrupted (noisy) version of it.</p> <p>This setup provides the model with <b>bi-directional context</b>, meaning it can consider both preceding and following words when predicting masked tokens.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/6_autoencoding_pretraining-480.webp 480w,/assets/img/posts/genai_llm_2/6_autoencoding_pretraining-800.webp 800w,/assets/img/posts/genai_llm_2/6_autoencoding_pretraining-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/6_autoencoding_pretraining.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 6.</b> Autoencoding models pre-training. Source: course lecture. </div> <h3 id="autoregressive-models">Autoregressive models</h3> <p>Autoregressive models are pretrained using <b>causal language modeling</b>, where the model learns to predict the next token based solely on the preceding sequence of tokens. Note: predicting the next token is sometimes called <b>full language modeling</b> by researchers.</p> <p>This setup provides <b>unidirectional context</b>, meaning the model has no access to future tokens during training. Autoregressive models mask the input sequence and can only see the input tokens leading up to the token in question. The model has no knowledge of the end of the sequence. The model then iterates over the input sequence one by one to predict the following token.</p> <p>Large decoder-only models, such as GPT, demonstrate strong ability in zero-shot and few-shot inferences, and can generalize well across a wide range of language tasks.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/7_autoregressive_pretraining-480.webp 480w,/assets/img/posts/genai_llm_2/7_autoregressive_pretraining-800.webp 800w,/assets/img/posts/genai_llm_2/7_autoregressive_pretraining-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/7_autoregressive_pretraining.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 7.</b> Autoregressive models pre-training. Source: course lecture. </div> <h3 id="seq2seq-models">Seq2Seq models</h3> <p>Exact detail of pre-training varies from model to model.</p> <ul> <li>A popular Seq2Seq model <a href="https://github.com/google-research/text-to-text-transfer-transformer">T5</a> pretrains the encoder using <b>span corruption</b>, which masks random sequences of input tokens. Those masked sequences are then replaced with a unique sentinel token. <b>Sentinel tokens</b> are special tokens added to the vocabulary, but do not correspond to any actual word from the input text. The decoder is then tasked with reconstructing the masked token sequences auto-regressively. The output is the sentinel token followed by the predicted tokens.</li> <li>BART combines the ideas of masked language modeling and causal language modeling within a seq2seq (encoder-decoder) framework. It corrupts text with various noise functions (e.g., setence shuffling, token masking), then uses a decoder to reconstruct the original text.</li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/8_seq2seq_pretraining-480.webp 480w,/assets/img/posts/genai_llm_2/8_seq2seq_pretraining-800.webp 800w,/assets/img/posts/genai_llm_2/8_seq2seq_pretraining-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/8_seq2seq_pretraining.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 8.</b> Seq2Seq models pre-training. Source: course lecture. </div> <h2 id="model-size">Model size</h2> <p>The growth of model size is powerd by</p> <ul> <li>introduction of transformer</li> <li>access to massive datasets</li> <li>more powerful compute resources</li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/9_model_size-480.webp 480w,/assets/img/posts/genai_llm_2/9_model_size-800.webp 800w,/assets/img/posts/genai_llm_2/9_model_size-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/9_model_size.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 9.</b> Model size evolution with time. Source: <a href="https://informationisbeautiful.net/visualizations/the-rise-of-generative-ai-large-language-models-llms-like-chatgpt/" target="_blank"> Information is beautiful.</a> </div> <h2 id="compute-challenge">Compute challenge</h2> <p><b>CUDA</b>, short for <b>Compute Unified Device Architecture</b>, is a collection of libraries and tools developed for NVIDIA GPUs to boost performance on common deep-learning operations, including matrix multiplication, among many others. Deep-learning libraries such as PyTorch and TensorFlow use CUDA extensively to handle the low-level, hardware-specific details, including data movement between CPU and GPU memory.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/10_cuda-480.webp 480w,/assets/img/posts/genai_llm_2/10_cuda-800.webp 800w,/assets/img/posts/genai_llm_2/10_cuda-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/10_cuda.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 10.</b> CUDA out-of-memory error (<a href="https://www.oreilly.com/library/view/generative-ai-on/9781098159214/ch04.html" target="_blank">source</a>). </div> <p>Quote from <em>Generative AI on AWS: Building Context-Aware Multimodal Reasoning Applications (<a href="https://www.oreilly.com/library/view/generative-ai-on/9781098159214/ch04.html">source</a>)</em>:</p> <blockquote> <p>A single-model parameter, at full 32-bit precision, is represented by 4 bytes. Therefore, a 1-billion-parameter model requires 4GB of GPU RAM just to load the model into GPU RAM at full precision. If you want to also train the model, you need more GPU memory to store the states of the numerical optimizer, gradients, and activations, as well as any temporary variables used by your functions.</p> </blockquote> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/11_gpuram_store_1b-480.webp 480w,/assets/img/posts/genai_llm_2/11_gpuram_store_1b-800.webp 800w,/assets/img/posts/genai_llm_2/11_gpuram_store_1b-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/11_gpuram_store_1b.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 11.</b> Approximate GPU RAM needed to store 1B parameters. Source: course lecture. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/12_gpuram_train_1b-480.webp 480w,/assets/img/posts/genai_llm_2/12_gpuram_train_1b-800.webp 800w,/assets/img/posts/genai_llm_2/12_gpuram_train_1b-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/12_gpuram_train_1b.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 12.</b> Additional GPU RAM needed to train 1B parameters. Source: course lecture </div> <p>Quote from <em>Generative AI on AWS: Building Context-Aware Multimodal Reasoning Applications (<a href="https://www.oreilly.com/library/view/generative-ai-on/9781098159214/ch04.html">source</a>)</em>:</p> <blockquote> <p>When you experiment with training a model, it’s recommended that you start with batch_size=1 to find the memory boundaries of the model with just a single training example. You can then incrementally increase the batch size until you hit the CUDA out-of-memory error. This will determine the maximum batch size for the model and dataset. A larger batch size can often speed up your model training.</p> </blockquote> <blockquote> <p>These additional components lead to approximately 12–20 extra bytes of GPU memory per model parameter. For example, to train a 1-billion-parameter model, you will need approximately 24 GB of GPU RAM at 32-bit full precision, six times the memory compared to just 4 GB of GPU RAM for loading the model</p> </blockquote> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/13_gpuram_load_vs_loadtrain-480.webp 480w,/assets/img/posts/genai_llm_2/13_gpuram_load_vs_loadtrain-800.webp 800w,/assets/img/posts/genai_llm_2/13_gpuram_load_vs_loadtrain-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/13_gpuram_load_vs_loadtrain.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 13.</b> Comparison of approximate GPU RAM needed to load versus load and train a 1-billion-parameter model at 32-bit full precision (<a href="https://www.oreilly.com/library/view/generative-ai-on/9781098159214/ch04.html" target="_blank">source</a>). </div> <p>One technique we can use to reduce memory is called <b>quantization</b>. The idea is to reduce the memory required to store the model weights by reducing their precision from 32-bit floating point numbers to 16-bit (or 8-bit) floating point numbers. Quantization statistically projects the original 32-bit floating point numbers into a lower precision space, using scaling factors calculated based on the range of the original 32-bit floating point numbers.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/14_FP16-480.webp 480w,/assets/img/posts/genai_llm_2/14_FP16-800.webp 800w,/assets/img/posts/genai_llm_2/14_FP16-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/14_FP16.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 14.</b> Quantization: FP16. Source: course lecture </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/15_BFLOAT16-480.webp 480w,/assets/img/posts/genai_llm_2/15_BFLOAT16-800.webp 800w,/assets/img/posts/genai_llm_2/15_BFLOAT16-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/15_BFLOAT16.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 15.</b> Quantization: BFLOAT16. Source: course lecture </div> <p><b>BFLOAT-16</b> (BF16, developed at Google Brain) has recently become a popular alternative to FP16.</p> <ul> <li>BF16 is a hybrid between half precision FP16 and full precision FP32.</li> <li>BF16 significantly helps with training stability and is supported by newer GPUs such as NVIDIA’s A100.</li> <li>BF16 is often described as truncated 32-bit float, as it captures the full dynamic range of the full 32-bit float that uses only 16-bits.</li> <li>BF16 uses the full 8 bits to represent the exponent, but truncates the fraction to just 7 bits.</li> <li>Downside: BF16 is not well suited for integer calculations, but these are relatively rare in deep learning.</li> </ul> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/16_INT8-480.webp 480w,/assets/img/posts/genai_llm_2/16_INT8-800.webp 800w,/assets/img/posts/genai_llm_2/16_INT8-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/16_INT8.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 16.</b> Quantization: INT8. Source: course lecture </div> <h2 id="scalling-law">Scalling law</h2> <p>The <b>Chinchilla scaling law</b> shows that, for a fixed compute budget, language model performance is optimized by using more training data and a smaller model size (<a href="https://arxiv.org/abs/2203.15556">Hoffmann et al., 2022</a>). Undertraining is the bottleneck - large models like GPT-3 were not trained on enough tokens to fully benefit from their size.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/17_optimal_computing-480.webp 480w,/assets/img/posts/genai_llm_2/17_optimal_computing-800.webp 800w,/assets/img/posts/genai_llm_2/17_optimal_computing-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/17_optimal_computing.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 17.</b> Compute optimal models. Source: course lecture </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/18_scalinglaw-480.webp 480w,/assets/img/posts/genai_llm_2/18_scalinglaw-800.webp 800w,/assets/img/posts/genai_llm_2/18_scalinglaw-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/18_scalinglaw.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 18.</b> Chinchilla scaling laws for model and dataset size. Source: course lecture </div> <h2 id="domain-adaptation">Domain adaptation</h2> <p>Example: <a href="https://arxiv.org/abs/2303.17564">BloombergGPT</a></p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_2/19_BloombergGPT-480.webp 480w,/assets/img/posts/genai_llm_2/19_BloombergGPT-800.webp 800w,/assets/img/posts/genai_llm_2/19_BloombergGPT-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_2/19_BloombergGPT.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 19.</b> BloombergGPT: domain adaptation for finance. Source: course lecture </div> <h2 id="references">References</h2> <ul> <li><a href="https://www.amazon.com/Generative-AI-AWS-Multimodal-Applications/dp/1098159225/">Generative AI on AWS: Building Context-Aware, Multimodal Reasoning Applications</a> <ul> <li>Deep dive into all phases of the generative AI Lifecycle</li> </ul> </li> <li><a href="https://arxiv.org/abs/2211.05100">BLOOM: BigScience 176B Model</a> <ul> <li>BLOOM is an open-source LLM with 176B parameters trained in an open and transparent way. In this paper, the authors present a detailed discussion of the dataset and process used to train the model. You can also see a high-level overview of the model <a href="https://bigscience.notion.site/BLOOM-BigScience-176B-Model-ad073ca07cdf479398d5f95d88e218c4">here</a></li> </ul> </li> <li><a href="https://www.coursera.org/learn/classification-vector-spaces-in-nlp/home/week/3">Vector Space Models</a> <ul> <li>Series of lessons from DeepLearning.AI’s Natural Language Processing specialization discussing the basics of vector space models and their use in language modeling.</li> </ul> </li> <li><a href="https://arxiv.org/abs/2001.08361">Scaling Laws for Neural Language Models</a> <ul> <li>Pre-training and scaling laws</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2204.05832.pdf">What Language Model Architecture and Pretraining Objective Work Best for Zero-Shot Generalization?</a> Model architectures and pre-training objectives. The paper examines modeling choices in large pre-trained language models and identifies the optimal approach for zero-shot generalization.</li> <li><a href="https://huggingface.co/tasks">HuggingFace Tasks</a> and <a href="https://huggingface.co/models">Model Hub</a> <ul> <li>Collection of resources to tackle varying machine learning tasks using the HuggingFace library.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2302.13971.pdf">LLaMA: Open and Efficient Foundation Language Models</a> <ul> <li>Article from Meta AI proposing Efficient LLMs (their model with 13B parameters outperform GPT3 with 175B parameters on most benchmarks)</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2005.14165.pdf">Language Models are Few-Shot Learners</a> <ul> <li>Scaling laws and compute-optimal models. This paper investigates the potential of few-shot learning in Large Language Models.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2203.15556.pdf">Training Compute-Optimal Large Language Models</a> <ul> <li>Study from DeepMind to evaluate the optimal model size and number of tokens for training LLMs. Also known as “Chinchilla Paper”.</li> </ul> </li> <li><a href="https://arxiv.org/pdf/2303.17564.pdf">BloombergGPT: A Large Language Model for Finance</a> <ul> <li>LLM trained specifically for the finance domain, a good example that tried to follow chinchilla laws.</li> </ul> </li> </ul>]]></content><author><name></name></author><category term="llm"/><summary type="html"><![CDATA[Course summary of Generative AI with Large Language Models. Part Two.]]></summary></entry><entry><title type="html">GenAI with LLMs (1) Fundamentals</title><link href="https://wenwenkong.github.io/blog/2025/gen-ai-llm-1/" rel="alternate" type="text/html" title="GenAI with LLMs (1) Fundamentals"/><published>2025-05-30T00:00:00+00:00</published><updated>2025-05-30T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2025/gen-ai-llm-1</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2025/gen-ai-llm-1/"><![CDATA[<p>This post covers fundamentals from the <strong>Generative AI With LLMs</strong> course offered by DeepLearning.AI.</p> <h2 id="transformer-variants">Transformer variants</h2> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_1/1_transformer_variants-480.webp 480w,/assets/img/posts/genai_llm_1/1_transformer_variants-800.webp 800w,/assets/img/posts/genai_llm_1/1_transformer_variants-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_1/1_transformer_variants.jpeg" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> Transformer variants. Source: course lectures. </div> <h3 id="encoder-only-models">Encoder only models</h3> <ul> <li> <p>Also known as <strong>Autoencoding models</strong>.</p> </li> <li> <p>Input sequence and output sequence are the same length.</p> </li> <li> <p>Use cases</p> <ul> <li>Sentiment analysis</li> <li>Named entity recognition</li> <li>Word classification</li> </ul> </li> <li> <p>Examples</p> <ul> <li><a href="https://arxiv.org/abs/1810.04805">BERT</a></li> <li><a href="https://arxiv.org/abs/1907.11692">RoBERTa</a></li> </ul> </li> </ul> <h3 id="encoder-decoder-models">Encoder Decoder models</h3> <ul> <li> <p>Also known as <strong>Seq2Seq models</strong>.</p> </li> <li> <p>Input sequence and output sequence can be different lengths.</p> </li> <li> <p>Use cases</p> <ul> <li>Translation</li> <li>Text summarization</li> <li>Question answering</li> </ul> </li> <li> <p>Examples</p> <ul> <li><a href="https://arxiv.org/abs/1910.13461">BART</a></li> <li><a href="https://arxiv.org/pdf/1910.10683">T5</a></li> </ul> </li> </ul> <h3 id="decoder-only-models">Decoder only models</h3> <ul> <li> <p>Also known as <strong>Autoregressive models</strong>.</p> </li> <li> <p>Widely used today. Can generalize to most tasks.</p> </li> <li> <p>Use cases</p> <ul> <li>Text generation</li> </ul> </li> <li> <p>Examples</p> <ul> <li><a href="https://arxiv.org/abs/2005.14165">GPTs</a></li> <li><a href="https://arxiv.org/abs/2211.05100">BLOOM</a></li> <li><a href="https://www.ai21.com/research/jurassic-1-technical-details-evaluation/">Jurassic</a></li> <li><a href="https://arxiv.org/abs/2302.13971">LLaMA</a></li> <li>etc</li> </ul> </li> </ul> <h2 id="prompt-engineering">Prompt engineering</h2> <h3 id="in-context-learning">In-context learning</h3> <p><strong>In-context learning:</strong> including examples of the task that you want the model to carry out inside the prompt can get the model to produce better outcomes. Providing examples inside the context window is called in-context learning.</p> <h3 id="zero-shot-one-shot-few-shot">Zero-shot, one-shot, few-shot</h3> <p><strong>Zero-shot inference:</strong> including zero examples.</p> <p><strong>One-shot inference:</strong> including a single example.</p> <p><strong>Few-shot inference:</strong> including several examples.</p> <p><strong>Note:</strong></p> <ul> <li> <p>Large LLMs can do well with zero-shot inference, smaller LLMs struggle with zero-shot inference and benefit by learning examples of the desired behavior.</p> </li> <li> <p>You have a limit on the amount of in-context learning that you can pass to the model. If you find your model isn’t performing well when including 5 or 6 examples, you should try fine-tuning your model instead.</p> </li> </ul> <h2 id="generative-configuration---inference-parameters">Generative configuration - inference parameters</h2> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_1/2_inference_parameters-480.webp 480w,/assets/img/posts/genai_llm_1/2_inference_parameters-800.webp 800w,/assets/img/posts/genai_llm_1/2_inference_parameters-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_1/2_inference_parameters.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 2.</b> Inference configuration parameters. Source: course lectures. </div> <h3 id="max-new-tokens">Max new tokens</h3> <ul> <li>Used to limit the number of tokens that the model will generate. You can think of this as putting a cap on the number of times the model will go through the selection process (i.e., from computing probability distribution to sampling or selecting the next token).</li> <li>Remember it’s <strong>max</strong> new tokens, not a hard number of new tokens generated.</li> </ul> <h3 id="top-k-and-top-p">Top-k and Top-p</h3> <p>Recall that the output from the transformer’s softmax layer is a probability distribution across the entire dictionary of words that the model uses.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_1/3_greedy_vs_random_sampling-480.webp 480w,/assets/img/posts/genai_llm_1/3_greedy_vs_random_sampling-800.webp 800w,/assets/img/posts/genai_llm_1/3_greedy_vs_random_sampling-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_1/3_greedy_vs_random_sampling.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 3.</b> Greedy decoding and random sampling. Source: course lectures. </div> <p><strong>Greedy decoding</strong></p> <ul> <li>Model chooses the word/token with the highest probability.</li> <li>This method can work very well for short generation but is susceptible to repeated words or repeated sequences of words. If you want to generate texts that’s more natural, more creative, and avoid repeating words, you need to use some other controls.</li> </ul> <p><strong>Random (weighted) sampling</strong></p> <ul> <li>The model chooses the output word at random using the probability distribution to weight the selection.</li> <li>Reduce the likelihood that words will be repeated. However, depending on the setting, there is a possibility that the output may be too creative, producing words that cause the generation to wander off into topics or words that just don’t make sense.</li> </ul> <p>Top-k and top-p are sampling methods we can use to limit the random sampling and increase the chance that the output will be sensible.</p> <p><strong>Top-k</strong></p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_1/4_top-k-480.webp 480w,/assets/img/posts/genai_llm_1/4_top-k-800.webp 800w,/assets/img/posts/genai_llm_1/4_top-k-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_1/4_top-k.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 4.</b> Top-k. Source: course lectures. </div> <ul> <li>The model to choose from only the \(k\) tokens with the highest probability. The model then selects from these options using the probability weighting</li> <li>This method can help the model have some randomness while preventing the selection of highly improbable completion words. This in turn makes your text generation more likely to sound reasonable and to make sense.</li> </ul> <p><strong>Top-p</strong></p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_1/5_top-p-480.webp 480w,/assets/img/posts/genai_llm_1/5_top-p-800.webp 800w,/assets/img/posts/genai_llm_1/5_top-p-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_1/5_top-p.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 5.</b> Top-p. Source: course lectures. </div> <p>Limit the random sampling to the predictions whose combined probabilities do not exceed \(p\).</p> <h3 id="temperature">Temperature</h3> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_1/6_temperature-480.webp 480w,/assets/img/posts/genai_llm_1/6_temperature-800.webp 800w,/assets/img/posts/genai_llm_1/6_temperature-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_1/6_temperature.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 6.</b> Temperature. Source: course lectures. </div> <ul> <li>This parameter influences the shape of the probability distribution that the model calculates for the next token.</li> <li>The temperature is a scaling factor that’s applied within the final softmax layer of the model that impacts the shape of the probability distribution of the next token. In contrast to top-k and top-p, changing temperature actually alters the predictions the model will make.</li> <li>Cooler temperature (\(&lt;1\)) - strongly peaked distribution.</li> <li>Warmer temperature (\(&gt;1\)) - broader, flatter distribution.</li> </ul> <h2 id="genai-lifecycle">GenAI lifecycle</h2> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/genai_llm_1/7_genai_lifecycle-480.webp 480w,/assets/img/posts/genai_llm_1/7_genai_lifecycle-800.webp 800w,/assets/img/posts/genai_llm_1/7_genai_lifecycle-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/genai_llm_1/7_genai_lifecycle.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 7.</b> Generative AI project lifecycle. Source: course lectures. </div> <h2 id="references">References</h2> <ul> <li> <p>Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … &amp; Polosukhin, I. (2017). <a href="https://arxiv.org/pdf/1706.03762">Attention Is All You Need</a>. arXiv preprint arXiv:1706.03762.</p> <ul> <li>The Transformer architecture, with the core “self-attention” mechanism.</li> </ul> </li> <li> <p>Radford, A., Narasimhan, K., Salimans, T., &amp; Sutskever, I. (2018). <a href="https://arxiv.org/abs/1810.04805">Improving Language Understanding by Generative Pre-Training</a>. OpenAI Technical Report.</p> <ul> <li>BERT</li> </ul> </li> <li> <p>Liu, Y., Ott, M., Goyal, N., Du, J., Joshi, M., Chen, D., Levy, O., Lewis, M., Zettlemoyer, L., &amp; Stoyanov, V. (2019). <a href="https://arxiv.org/abs/1907.11692">RoBERTa: A Robustly Optimized BERT Pretraining Approach</a>. arXiv preprint arXiv:1907.11692.</p> <ul> <li>RoBERTa</li> </ul> </li> <li> <p>Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S., Matena, M., … &amp; Liu, P. J. (2020). <a href="https://arxiv.org/abs/1910.10683">Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer</a>. arXiv preprint arXiv:1910.10683.</p> <ul> <li>T5</li> </ul> </li> <li> <p>Lewis, M., Liu, Y., Goyal, N., Ghazvininejad, M., Mohamed, A., Levy, O., … &amp; Zettlemoyer, L. (2020). <a href="https://arxiv.org/abs/1910.13461">BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension</a>. arXiv preprint arXiv:1910.13461.</p> <ul> <li>BART</li> </ul> </li> <li> <p>Brown, T., Mann, B., Ryder, N., Subbiah, M., Kaplan, J., Dhariwal, P., … &amp; Amodei, D. (2020). <a href="https://arxiv.org/abs/2005.14165">Language Models are Few-Shot Learners</a>. arXiv preprint arXiv:2005.14165.</p> <ul> <li>GPT-3</li> </ul> </li> <li> <p>BigScience Workshop. (2022). <a href="https://arxiv.org/abs/2211.05100">BLOOM: A 176B-Parameter Open-Access Multilingual Language Model</a>. arXiv preprint arXiv:2211.05100.</p> <ul> <li>BLOOM</li> </ul> </li> <li> <p>AI21 Labs. (2021). <a href="https://www.ai21.com/research/jurassic-1-technical-details-evaluation/">Jurassic-1: Technical Details and Evaluation</a>. AI21 Labs Blog.</p> <ul> <li>Jurassic</li> </ul> </li> <li> <p>OpenAI. (2023). <a href="https://arxiv.org/abs/2302.13971">Language models can explain neurons in language models</a>. arXiv preprint arXiv:2302.13971.</p> <ul> <li>LLaMA</li> </ul> </li> </ul>]]></content><author><name></name></author><category term="llm"/><summary type="html"><![CDATA[Course summary of Generative AI with Large Language Models. Part One.]]></summary></entry><entry><title type="html">Predicting U.S. Soybean Yield with Climate Data</title><link href="https://wenwenkong.github.io/blog/2025/us-soybean-prediction/" rel="alternate" type="text/html" title="Predicting U.S. Soybean Yield with Climate Data"/><published>2025-03-11T00:00:00+00:00</published><updated>2025-03-11T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2025/us-soybean-prediction</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2025/us-soybean-prediction/"><![CDATA[<h2 id="summary">Summary</h2> <p>This post walks through my end-to-end machine learning project on predicting U.S. soybean annual yield based on local climate conditions. We cover all key steps of a machine learning workflow, including ideation, feature selection, cross validation, baseline modeling, hyperparameter tuning, and model deployment. We employed annual soybean yield data and monthly climate variables during the historical period from 1981 to 2016. The model was trained on annual soybean yield data and monthly climate variables from 1981 to 2015, with 2016 used as the test set. We found that XGBRegressor performed the best among the regression algorithms (including linear and tree-based models) tested in this project. Our model achieved an \(R^2\) of ~0.9, demonstrating a strong ability to predict U.S. soybean annual yield based on climate conditions. Please refer to <a href="https://github.com/wenwenkong/data-science-portfolio/tree/main/US_soybean_yield">this repo</a> for the project’s code.</p> <hr/> <h2 id="introduction">Introduction</h2> <p>Soybean is a vital source of protein for both human and animal nutrition, but its yield is highly sensitive to weather and climate variability. High temperatures and low soil moisture, particularly during the summer reproductive period, can significantly reduce soybean yields (Hamed et al., 2021). Early-season excessive precipitation can also negatively impact soybean yields by restricting root development, causing nutrient leaching, and increasing disease susceptibility (Ortiz-Bobea et al., 2019).</p> <p>This project is motivated by two questions:</p> <ol> <li>Can we build a machine learning model that predicts local annual soybean yield in the United States based on local climate conditions?</li> <li>Which climatic factors contribute most to the soybean yield prediction?</li> </ol> <p><strong>Figure 1</strong> (<a href="https://www.codecademy.com/article/deep-learning-workflow">source</a>) illustrates the life cycle of a typical end-to-end machine learning project, which consists of four main components: data preparation, feature selection, model training, and deployment. We closely followed this framework throughout the project.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_1_ML_Workflow-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_1_ML_Workflow-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_1_ML_Workflow-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_1_ML_Workflow.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 1.</b> Life cycle of an end-to-end machine learning project. </div> <p>The reminder of the post is structured as follows. We first introduce the dataset and conduct an exploratory data analysis to examine the temporal and spatial patterns of the historical U.S. soybean yield. We then describe the feature selection process that constructed the training dataset. The model training section covers key aspects of model development. Finally, we discuss the deployment process and conclude with an overview of caveats and potential directions for future work.</p> <hr/> <h2 id="data">Data</h2> <p>We focused on two datasets: one for soybean yield and the other for climate variables. Historical annual soybean yield was provided by the Global Dataset of Historical Yields (GDHY) (lizumi and Sakai, 2020), where crop yield is defined as production per unit harvested area (\(t\) \(ha^{-1}\)). For climate variables, we used monthly model outputs from the North American Land Data Assimilation System (NLDAS) (Mitchell et al. 2004). The NLDAS dataset provides near-surface climate variables, including surface energy fluxes, surface water flux and storage, soil moisture, temperature, and land surface parameters. Both GDHY and NLDAS are land-based datasets, meaning that values over the ocean appear as NaNs. We focus on the period 1981-2016, covering the spatial domain \(235.25^{\circ} - 292.75^{\circ}E, 25.25^{\circ} - 52.75^{\circ}N\), which encompasses the primary continental regions in the U.S.</p> <hr/> <h2 id="exploratory-data-analysis-eda">Exploratory Data Analysis (EDA)</h2> <p>To better understand U.S. soybean production, we conducted an exploratory data analysis (<strong>Figures 2-5</strong>). The majority of soybean production is concentrated in the eastern and midwestern states, while the Great Plains region has relatively lower production density (<strong>Figure 2</strong>). To complement this spatial view, <strong>Figure 3</strong> presents a boxplot of the interquartile range (IQR) across all soybean production grid points for each year, highlighting spatial variations in yield Both local soybean yield and its spatial spread exhibit year-to-year variability (<strong>Figures 2-3</strong>).</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_2_GDHY_Soybean_4yrs-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_2_GDHY_Soybean_4yrs-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_2_GDHY_Soybean_4yrs-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_2_GDHY_Soybean_4yrs.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 2.</b> Soybean annual yield (unit: \(t\) \(ha^{-1}\)) in the U.S. for four years. </div> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_3_GDHY_Box-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_3_GDHY_Box-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_3_GDHY_Box-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_3_GDHY_Box.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 3.</b> Boxplot of the U.S. soybean annual yield for each year. </div> <p>Statistical analysis reveals that U.S. soybean annual yield follows a bimodal distribution (<strong>Figure 4</strong>), suggesting that not all soybean-producing regions behave uniformly. We hypothesize that this bimodal pattern arises from differences between high-production areas (Midwestern and Eastern states) and lower-production areas (Great Plains) The left mode of the distribution likely corresponds to the Great Plains, while the right mode represents more densely cultivated regions.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_4_GDHY_PDF-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_4_GDHY_PDF-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_4_GDHY_PDF-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_4_GDHY_PDF.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 4.</b> Probability Density Function of the U.S. soybean annual yield from 1981 to 2016. </div> <p>Both climatology and long-term trends display a west-east dipole pattern, further the Great Plains apart from other areas(<strong>Figure 5</strong>). Climatologically, soybean yield is lower in the Great Plains compared to other regions. The long-term trend, however, highlights the Great Plains as a hotspot area that experienced notable increase in soybean yield from 1981 to 2016. The overall increasing trend in the U.S. Soybean yield aligns with what we observed in <strong>Figure 3</strong>.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_5_GDHY_climatology_trend-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_5_GDHY_climatology_trend-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_5_GDHY_climatology_trend-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_5_GDHY_climatology_trend.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 5.</b> (Left) Climatology and (Right) trend of the U.S. soybean annual yield. </div> <p>In this project, we train a unified model for all soybean production regions across the U.S. This approach assumes that the causal relationship between local climate conditions and soybean yield is consistent across all soybean production regions. We acknowledge that this is an oversimplification and we discuss its limitations in the <code class="language-plaintext highlighter-rouge">Caveats and Future Work</code> section.</p> <p>We merged the GDHY and NLDAS datasets by matching the <code class="language-plaintext highlighter-rouge">lat</code>, <code class="language-plaintext highlighter-rouge">lon</code>, and <code class="language-plaintext highlighter-rouge">year</code> features (see <strong>Figure 6</strong> for a screenshot of the merged dataset; see section 4.1 in <a href="https://github.com/wenwenkong/data-science-portfolio/blob/main/US_soybean_yield/1.0_Data_ingestion.ipynb">this notebook</a>). The resulting DataFrame contains over 600 climate features from NLDAS. We will perform feature selection in the next section.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_6_GDHY_NLDAS_merged_head-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_6_GDHY_NLDAS_merged_head-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_6_GDHY_NLDAS_merged_head-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_6_GDHY_NLDAS_merged_head.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 6.</b> Screenshot of the merged DataFrame of the GDHY (i.e. soybean yield) and NLDAS (i.e. climate variables) datasets. </div> <hr/> <h2 id="feature-selection">Feature selection</h2> <p>Feature selection requires critical thinking and iterative analysis, making it the most tedious component of this project. Our goal is to narrow down the climate features to a subset that most likely affect soybean yield. This section outlines our thought process for feature selection. Detailed calculations and reasoning can be found in <a href="https://github.com/wenwenkong/data-science-portfolio/blob/main/US_soybean_yield/2.0_EDA_feature_engineering_selection_OutputsCleared.ipynb">this notebook</a> and <a href="https://github.com/wenwenkong/data-science-portfolio/blob/main/US_soybean_yield/3.0_feature_selection_model_training.ipynb">this notebook</a>.</p> <p><strong>Key considerations for feature selection</strong>:</p> <ul> <li>Feature selection should only be performed using the training dataset to prevent bias in feature and model choice from the test set.</li> <li>Feature selection does not always guarantee improved predictions.</li> <li>Linear and non-linear feature selection methods may yield conflicting results. When this happens, we rely on domain knowledge and our understanding of the problem to make decisions.</li> </ul> <p><strong>Feature selection process</strong></p> <p>We break the feature selection process into two phases:</p> <ul> <li>Phase 1: Initial feature filtering based on correlation analysis and domain knowledge.</li> <li>Phase 2: Further refinement using scikit-learn’s feature selection methods. We used features derived from Phase 1 to build baseline models, and used the refined features from Phase 2 for final model selection (see the <code class="language-plaintext highlighter-rouge">Model Development</code> section).</li> </ul> <p><strong>Phase 1: Initial Filtering</strong></p> <p>We followed these key principles in Phase 1:</p> <ol> <li>Temporal consideration:</li> </ol> <ul> <li>Most U.S. soybeans are planted in May and early June and harvested in late September and October (Source: <a href="https://www.ers.usda.gov/topics/crops/soybeans-oil-crops/oil-crops-sector-at-a-glance/">USDA</a>). Thus, we only consider climate features during months before October, removing November and December variables from the current year.</li> <li>Besides current-year climate, we explored whether past-year climate conditions matter. In particular, we explored past year’s annual total rainfall, past winter’s snowfall, rainfall, and soil moisture.</li> </ul> <ol> <li>Correlation analysis:</li> </ol> <ul> <li>We examined correlation between annual yield and climate features to identify important features. We kept variables with strong correlation with yield, and discarded the rest.</li> <li>Since some relationships between climate and yield are nonlinear, we kept certain features despite weak linear correlations if they were scientifically relevant.</li> </ul> <ol> <li>Redundant feature removal:</li> </ol> <ul> <li>We aggregated (e.g., seasonal averages) climate variables that are highly auto-correlated across months to avoid redundancy.</li> <li>Some climate variables exhibit strong cross-correlations, andi we only kept the most relevant ones.</li> <li>We excluded vegetation and land cover features (such as leaf area index) that directly reflect the yield data during the soybean growing and harvest season.</li> </ul> <ol> <li>Feature engineering: We created new features when necessary. For example, we derived an evaporative fraction using surface energy fluxes and used it instead of latent and sensible heat fluxes to simplify the feature set.</li> </ol> <p><strong>Phase 2: scikit-learn based feature selection methods</strong></p> <p>In Phase 2, we refined the feature set using various scikit-learn methods: <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.VarianceThreshold.html">VarianceThreshold</a>, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.f_regression.html">f_regression</a>, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.mutual_info_regression.html">mutual_info_regression</a>, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html">Lasso</a>, and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectFromModel.html">SelectFromModel</a>. Although typically fewer methods are needed in practical applications, here we experimented with multiple approaches for the sake of practice. More details can be found in <a href="https://github.com/wenwenkong/data-science-portfolio/blob/429f607bb8148e9792c85c149e3f381056ad8346/US_soybean_yield/3.0_feature_selection_model_training.ipynb">this notebook</a>.</p> <hr/> <h2 id="model-development">Model Development</h2> <h3 id="cross-validation">Cross-validation</h3> <p><a href="https://machinelearningmastery.com/k-fold-cross-validation/">Cross-validation</a> helps reduce overfitting in machine learning models. While scikit-learn’s train_test_split` method allows for random splitting of data, it is not suitable for our problem due to the sequential nature of the dataset. Instead, we implemented an expanding window backtesting procedure for cross-validation (<strong>Figure 7</strong>). Using this approach, we created a 5-fold split in the training set, ensuring that the test size remained constant across splits for comparability in their performance statistics:</p> <ul> <li>Split 1: train on 1980-2010, test on 2011</li> <li>Split 2: train on 1980-2011, test on 2012</li> <li>Split 3: train on 1980-2012, test on 2013</li> <li>Split 4: train on 1980-2013, test on 2014</li> <li>Split 5: train on 1980-2014, test on 2015</li> </ul> <p>This method ensures that each model is trained on an expanding historical dataset, reflecting real-world forecasting conditions where future predictions are based only on past information.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_7_Expanding-window-cross-validation-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_7_Expanding-window-cross-validation-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_7_Expanding-window-cross-validation-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_7_Expanding-window-cross-validation.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 7.</b> Illustration of the expanding window backtesting concept. Adopted from Uber blog <a href="https://www.uber.com/blog/omphalos/" target="_blank">here</a>. </div> <h3 id="model-selection">Model selection</h3> <p>We first explored both linear models (OLS, Ridge, Lasso) and tree-based models (Decision Tree, Random Forest, XGBoost) to build baseline models. We used both \(R^2\) and RMSE to evaluate model performance. Not surprisingly, tree-based models outperformed linear models, with XGBoost achieving the best performance among the three tree-based models (<strong>Figure 8</strong>).</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_8_Model_selection-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_8_Model_selection-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_8_Model_selection-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_8_Model_selection.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 8.</b> Box plot of \(R^{2}\) values across cross-validation splits from (left) linear regression models and (right) tree-based regression models. </div> <h3 id="hyperparameter-tuning">Hyperparameter tuning</h3> <p>We focused on tuning the following XGBoost hyperparameters to control overfitting:</p> <ul> <li><code class="language-plaintext highlighter-rouge">n_estimators</code>: Number of rounds for boosting.</li> <li><code class="language-plaintext highlighter-rouge">learning_rate</code>: Step size shrinkage used in update to prevent overfitting.</li> <li><code class="language-plaintext highlighter-rouge">colsample_bytree</code>: Subsample ratio of columns when constructing each tree</li> <li><code class="language-plaintext highlighter-rouge">subsample</code>: Subsample ratio of the training instances.</li> <li><code class="language-plaintext highlighter-rouge">gamma</code>: Minimum loss reduction required to split a leaf node of the tree; higher values make the algorithm more conservative.</li> <li><code class="language-plaintext highlighter-rouge">min_child_weight</code>: Minimum sum of instance weights needed in a child; higher values make the algorithm more conservative. -<code class="language-plaintext highlighter-rouge">max_depth</code>: Maximum depth of a tree; higher values increase model complexity and risk of overfitting.</li> <li><code class="language-plaintext highlighter-rouge">reg_alpha</code>: L1 regularization term on weights; higher values make the model more conservative.</li> </ul> <p>Grid Search, Random Search, and Bayesian Optimization are commonly used hyperparameter tuning methods. We tested both Random Search and Bayesian Optimization (via <a href="https://optuna.readthedocs.io/en/stable/">Optuna</a>). We selected the RandomizedSearchCV-tuned parameters as they produced a slightly higher \(R^2\) value.</p> <h3 id="feature-importance">Feature importance</h3> <p>We used XGBoost’s built-in function to evaluate feature importance (<strong>Figure 9</strong>). Both longitude and year emerge as key features, reflecting the spatial-temporal nature of soybean yield prediction. Longitude serves as a proxy for geographic differences in soybean production, as observed in the EDA, while year likely captures long-term trends affecting yield. Several variables related to soil moisture content also stand out, including spring and summer soil moisture and summertime evaporative fraction. Springtime leaf area index also contributes to yield prediction, likely because it reflects pre-season vegetation health, which could correlate with soil fertility and growing conditions.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_9_XGBoost_feature_importance-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_9_XGBoost_feature_importance-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_9_XGBoost_feature_importance-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_9_XGBoost_feature_importance.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 9.</b> Feature importance chart evaluated based on XGBoost built-in function. </div> <hr/> <h2 id="inference-and-deployment">Inference and Deployment</h2> <p>How well does the model perform in 2016 soybean annual yield? <strong>Figure 10</strong> compares the true versus predicted values, suggesting that the model does a decent job in capturing both the spatial pattern and local magnitude of soybean yield. However, the model overall tends to underestimate annual yield c, while overestimating yield in some localized areas. We did not investigate the cause of this underestimation, which could be an area for future analysis. We deployed the trained XGBoost model on AWS EC2, and built a <a href="http://www.ussoybean-demo.com/">web interface</a> using Flask, basic css and javascript.</p> <div class="row mt-3"> <div class="col-sm mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/posts/us_soybean_yield/fig_10_XGBoost_prediction-480.webp 480w,/assets/img/posts/us_soybean_yield/fig_10_XGBoost_prediction-800.webp 800w,/assets/img/posts/us_soybean_yield/fig_10_XGBoost_prediction-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/posts/us_soybean_yield/fig_10_XGBoost_prediction.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </div> </div> <div class="caption"> <b>Figure 10.</b> (Top) Actual value and (Middle) predicted value of the U.S. soybean annual yield for 2016. The bottom plot shows fractional error between the actual and predicted values. </div> <hr/> <h2 id="caveats-and-future-work">Caveats and Future Work</h2> <p>In this section, we discuss several limitations of the current approach and potential future improvements.</p> <p><strong>Limited predictors</strong></p> <p>Unlike some other crops (e.g. corn) that are strongly influenced by soil type, drainage, population, row width, tillage and other physical and human factors, soybean yield is more dependent on the natural environment (Source: <a href="https://www.agweb.com/news/crops/soybeans/stack-odds-soybeans-spring">Stack the odds for soybeans this spring</a>). Still, additional factors such as genotype, soil type, and seeding experiments could improve our model’s predictability.</p> <p>In this project, we focused solely on the predictive power of local monthly climate due to the lack of suitable datasets for other predictors. This limitation may have constrained our model’s predictability. Even for the climate data, we relied on a single source (NLDAS). Future work could involve testing alternative datasets that provide both atmospheric and land-based variables to validate or refine our findings.</p> <p><strong>Coarse timescale of crop yield</strong></p> <p>The crop yields data used in this project only provide annual yields, thus we lack information on the timing of soybean planting and seasonal growth cycle at each location and year. Several studies (Colet et al., 2023; Vann and Stokes, 2024) suggest that planting timing affects yield. Future work incorporating sub-annual yield estimates or phenological data could help capture these temporal variations.</p> <p><strong>Localized climate perspective</strong></p> <p>This work takes a localized perspective of climate impacts.hat is, we only considered impacts of local climate on local yield. However, large-scale climate patterns can also affect U.S. soybean yield through teleconnections. For example, El Niño-Southern Oscillation (ENSO) events can impact U.S. growing conditions by synchronizing climate risks across major agricultural regions (Anderson et al., 2018). Including remote climate indices as features could improve our understanding of remote climate influences on soybean yield.</p> <p><strong>Spatial variation</strong></p> <p>As shown in the EDA, U.S. soybean yield varies across the Great Plains, Midwest, and Eastern states. We hypothesize that different sub-regions are governed by different climate factors. Even a common set of climate features is relevant across all regions, their importance may vary by location. Future work could explore training separate models for different sub-regions to improve predictions for local areas.</p> <p><strong>LSTM as an alternative model architecture</strong></p> <p>Long Short-Term Memory (LSTM) networks are well-suited for time-series forecasting tasks. Given the temporal nature of our soybean yield prediction problem, incorporating LSTM in future work could provide valuable insights. Several studies have demonstrated the effectiveness of LSTMs in crop yield prediction (Sun et al, 2019; Bhimavarapu et al., 2023). However, while LSTMs excel at capturing sequential dependencies, they require larger datasets and are more computationally intensive than tree-based models like XGBoost.</p> <hr/> <h2 id="references">References</h2> <p><strong>Journal Articles:</strong></p> <ul> <li>Anderson, W., Seager, R., Baethgen, W., &amp; Cane, M. (2018). Trans-Pacific ENSO teleconnections pose a correlated risk to agriculture. Agricultural and Forest Meteorology. <a href="https://doi.org/10.1016/j.agrformet.2018.07.023">https://doi.org/10.1016/j.agrformet.2018.07.023</a></li> <li>Bhimavarapu, U., Battineni, G., &amp; Chintalapudi, N. (2023). Improved optimization algorithm in LSTM to predict crop yield. Computers, 12(1), 10. <a href="https://doi.org/10.3390/computers12010010">https://doi.org/10.3390/computers12010010</a></li> <li>Colet, F., Lindsey, A. J., &amp; Lindsey, L. E. (2023). Soybean planting date and seeding rate effect on grain yield and profitability. Agronomy Journal. <a href="https://doi.org/10.1002/agj2.21434">https://doi.org/10.1002/agj2.21434</a></li> <li>Hamed, M. K., Vogel, M. M., Patricola, C. M., &amp; Seneviratne, S. I. (2021). Impacts of compound hot–dry extremes on US soybean yields. Earth System Dynamics, 12(4), 1371–1386. <a href="https://doi.org/10.5194/esd-12-1371-2021">https://doi.org/10.5194/esd-12-1371-2021</a></li> <li>Iizumi, T., &amp; Sakai, T. (2020). The global dataset of historical yields for major crops 1981–2016. Scientific Data, 7(1), 97. <a href="https://doi.org/10.1038/s41597-020-0433-7">https://doi.org/10.1038/s41597-020-0433-7</a></li> <li>Mitchell, K. E., Lohmann, D., Houser, P. R., Wood, E. F., Schaake, J. C., Robock, A., … &amp; Cosgrove, B. A. (2004). The multi-institution North American Land Data Assimilation System (NLDAS): Utilizing multiple GCIP products and partners in a continental distributed hydrological modeling system. Journal of Geophysical Research: Atmospheres, 109(D7), D07S90. <a href="https://doi.org/10.1029/2003JD003823">https://doi.org/10.1029/2003JD003823</a></li> <li>Ortiz-Bobea, A., Wang, H., Carrillo, C. M., &amp; Ault, T. R. (2019). Unpacking the climatic drivers of U.S. agricultural yields. Environmental Research Letters, 14(6), 064003. <a href="https://doi.org/10.1088/1748-9326/ab1e75">https://doi.org/10.1088/1748-9326/ab1e75</a></li> <li>Sun, J., Di, L., Sun, Z., Shen, Y., &amp; Lai, Z. (2019). County-level soybean yield prediction using deep CNN-LSTM model. Sensors, 19(20), 4363. <a href="https://doi.org/10.3390/s19204363">https://doi.org/10.3390/s19204363</a></li> </ul> <p><strong>Online Tutorials &amp; Blog Posts:</strong></p> <ul> <li>Vann, R., &amp; Stokes, D. J. (2024, January). How does soybean planting date impact plant height and soybean yield? NC State Extension. <a href="https://soybeans.ces.ncsu.edu/2024/01/how-does-soybean-planting-date-impact-plant-height-and-soybean-yield/">https://soybeans.ces.ncsu.edu/2024/01/how-does-soybean-planting-date-impact-plant-height-and-soybean-yield/</a></li> <li>AgWeb. (2024, February). Stack the odds for soybeans this spring. <a href="https://www.agweb.com/news/crops/soybeans/stack-odds-soybeans-spring">https://www.agweb.com/news/crops/soybeans/stack-odds-soybeans-spring</a></li> <li>XGBoost. (n.d.). XGBoost hyperparameter tuning guide. XGBoost Documentation. <a href="https://xgboost.readthedocs.io/en/stable/tutorials/param_tuning.html">https://xgboost.readthedocs.io/en/stable/tutorials/param_tuning.html</a></li> <li>XGBoost. (n.d.). XGBoost parameters. XGBoost Documentation. <a href="https://xgboost.readthedocs.io/en/stable/parameter.html">https://xgboost.readthedocs.io/en/stable/parameter.html</a></li> <li>Amazon Web Services. (n.d.). Tune an XGBoost model in Amazon SageMaker. AWS Documentation. <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost-tuning.html">https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost-tuning.html</a></li> <li>Uber. (n.d.). Omphalos: Uber’s point of interest engine for better user experiences. Uber Blog. <a href="https://www.uber.com/blog/omphalos/">https://www.uber.com/blog/omphalos/</a></li> <li>Towards Data Science. (2020, April). Grid search vs. random search vs. Bayesian optimization. <a href="https://towardsdatascience.com/grid-search-vs-random-search-vs-bayesian-optimization-2e68f57c3c46">https://towardsdatascience.com/grid-search-vs-random-search-vs-bayesian-optimization-2e68f57c3c46</a></li> <li>Practical Data Science. (n.d.). How to tune an XGBRegressor model with Optuna. <a href="https://practicaldatascience.co.uk/machine-learning/how-to-tune-an-xgbregressor-model-with-optuna">https://practicaldatascience.co.uk/machine-learning/how-to-tune-an-xgbregressor-model-with-optuna</a></li> </ul> <p><strong>GitHub Repository:</strong></p> <ul> <li>Kong, W. (2022). U.S. soybean yield prediction [GitHub repository]. <a href="https://github.com/wenwenkong/data-science-portfolio/tree/main/US_soybean_yield">https://github.com/wenwenkong/data-science-portfolio/tree/main/US_soybean_yield</a></li> </ul>]]></content><author><name>Wenwen Kong</name></author><category term="machine-learning"/><category term="climate"/><summary type="html"><![CDATA[An end-to-end machine learning project on U.S. soybean yield prediction]]></summary></entry><entry><title type="html">Statistical Learning Notes Outline</title><link href="https://wenwenkong.github.io/blog/2023/sl-notes-outline/" rel="alternate" type="text/html" title="Statistical Learning Notes Outline"/><published>2023-07-27T00:00:00+00:00</published><updated>2023-07-27T00:00:00+00:00</updated><id>https://wenwenkong.github.io/blog/2023/sl-notes-outline</id><content type="html" xml:base="https://wenwenkong.github.io/blog/2023/sl-notes-outline/"><![CDATA[<p>This note outlies topics about statistical learning that I want to update. Each note serves as a summary of my learnings, including concepts, R/Python methods, and use cases. Though ISLR2 will be the main reference, readings and learnings from other resources (such as blog posts or papers) will be cited when necessary.</p> <hr/> <h3 id="topics">Topics</h3> <ol> <li> <p>Fundamentals</p> </li> <li> <p>Linear Regression</p> </li> <li> <p>Lasso, Ridge, and ElasticNet</p> </li> <li> <p>Logistic Regression</p> </li> <li> <p>Tree-based models (Decision Trees, Random Forests, Bagging, Boosting)</p> </li> <li> <p>XGBoost</p> </li> <li> <p>Regression and Classification Metrics</p> </li> <li> <p>Support Vector Machine</p> </li> <li> <p>Unsupervised Learning</p> </li> </ol> <p>… …</p>]]></content><author><name></name></author><category term="stats-learning"/><category term="statistics"/><summary type="html"><![CDATA[Outline of notes about statistical learning.]]></summary></entry></feed>