<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Waleed Esmail on Medium]]></title>
        <description><![CDATA[Stories by Waleed Esmail on Medium]]></description>
        <link>https://medium.com/@waleed.physics?source=rss-8d4542253634------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WQPkJwVNN1WDJiYIgZDXqw.jpeg</url>
            <title>Stories by Waleed Esmail on Medium</title>
            <link>https://medium.com/@waleed.physics?source=rss-8d4542253634------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:12:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@waleed.physics/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Installed PyTorch, Cursor and a Full Debian Desktop on a 450 Grams Android Tablet]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@waleed.physics/i-installed-pytorch-cursor-and-a-full-debian-desktop-on-a-450-grams-android-tablet-17d2881869d0?source=rss-8d4542253634------2"><img src="https://cdn-images-1.medium.com/max/1672/1*kRt-wQDeODEASNgJ08cXXw.png" width="1672"></a></p><p class="medium-feed-snippet">How the Honor MagicPad 4&#x2019;s LinuxLab turns a 450-gram tablet into a genuine, if limited, research machine and the dozen things that go&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@waleed.physics/i-installed-pytorch-cursor-and-a-full-debian-desktop-on-a-450-grams-android-tablet-17d2881869d0?source=rss-8d4542253634------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@waleed.physics/i-installed-pytorch-cursor-and-a-full-debian-desktop-on-a-450-grams-android-tablet-17d2881869d0?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/17d2881869d0</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[linux-lab]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[cursor-ai]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 21:41:14 GMT</pubDate>
            <atom:updated>2026-09-18T21:41:14.061Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Your Model’s MSE Is Lying to You]]></title>
            <link>https://medium.com/@waleed.physics/your-models-mse-is-lying-to-you-9481fc86054f?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/9481fc86054f</guid>
            <category><![CDATA[uncertainty]]></category>
            <category><![CDATA[maximum-likelihood]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[probabilistic-forecasting]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 08:51:19 GMT</pubDate>
            <atom:updated>2026-09-17T08:51:19.298Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two forecasters with nearly identical MSE can completely disagree on when you should trust them.</h4><p>New on Towards Data Science: <strong>Your Model’s MSE Is Lying to You</strong><br> 👉 <a href="https://towardsdatascience.com/your-models-mse-is-lying-to-you/">https://towardsdatascience.com/your-models-mse-is-lying-to-you/</a></p><p>Two forecasting models. Same transformer backbone, same training budget, same data. On the held-out set they score almost identical MSE:</p><pre>Test MSE — point model:         0.1211<br>Test MSE — probabilistic model: 0.1154</pre><p>By that number they’re interchangeable. They are not, one of them quietly lies to you about how sure it is.</p><p>The only difference is the loss. Model A minimizes plain MSE and outputs a single number per step. Model B minimizes Gaussian negative log likelihood, it outputs a mean <em>and</em> a standard deviation:</p><pre>def gaussian_nll(mu, log_sigma, target):<br>    # fit term wants sigma small; log_sigma term punishes overconfidence<br>    sigma = torch.exp(log_sigma)<br>    return (log_sigma + 0.5 * ((target - mu) / sigma) ** 2).mean()</pre><p>That extra σ is the whole story. Split the test set into calm and noisy stretches and ask the honest question, does a <strong>90% interval</strong> actually contain the <strong>truth 90% of the time</strong>, <em>in each regime</em>?</p><pre>                          quiet regime   noisy regime<br>probabilistic model           87.7%          83.3%<br>point model (fixed band)      95.0%          63.1%</pre><p>The point model has only one number for uncertainty, a single <em>residual std</em> from training, so its band is the same width everywhere. It over-covers when things are calm and badly under-covers when they’re noisy (63%!): silently overconfident exactly where you most need caution. The probabilistic model’s band adapts, and it was never told where the regimes are, <strong><em>it learned that from the data</em></strong>.</p><figure><img alt="Point vs. probabilistic forecasts on held-out data. The true signal, both models’ predictions, and the probabilistic model’s 90% band are plotted over 400 test steps. The shaded band widens in noisy stretches and narrows in calm ones, tracking the signal’s changing uncertainty, while both models’ point predictions stay nearly on top of each other." src="https://cdn-images-1.medium.com/max/1024/1*DHKBXwQK2fwtxJ8LOQIHcQ.png" /><figcaption>The shaded band visibly widens in noisy stretches and tightens in calm ones.</figcaption></figure><blockquote>Same MSE. Very different reliability.</blockquote><p>Full walkthrough, the <strong><em>heteroscedastic </em></strong>signal, both models end-to-end, calibration by regime, and a decision use-case (probability of crossing a threshold), is on <strong><em>Towards Data Science, with all the code</em></strong>:</p><p>👉 <a href="https://towardsdatascience.com/your-models-mse-is-lying-to-you/">https://towardsdatascience.com/your-models-mse-is-lying-to-you/</a><br> <strong>Code </strong>👉: <a href="https://github.com/wesmail/probabilistic-forecasting">https://github.com/wesmail/probabilistic-forecasting</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9481fc86054f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From χ² to Normalising Flows: A Series in Review]]></title>
            <link>https://medium.com/@waleed.physics/from-%CF%87%C2%B2-to-normalising-flows-a-series-in-review-46b8aa0c4f71?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/46b8aa0c4f71</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[gravitational-waves]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[normalizing-flow]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 11:12:00 GMT</pubDate>
            <atom:updated>2026-05-08T14:26:41.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rzv7wiJcxig4V4RAdKDFZg.png" /></figure><h3>What this series was about ?</h3><p>Last week, I set out to write the tutorial I wish had existed when I first encountered machine learning as a physicist. Not a general introduction to neural networks, not a collection of Keras snippets, but a single coherent argument: one that starts from something every physicist already knows: fitting a model to data by minimizing an error and follows that idea, without interruption, all the way to the generative models now running inside gravitational-wave observatories and particle physics experiments.</p><p>The result is eight articles and eight companion Jupyter notebooks, covering <strong>linear regression</strong>, <strong>classification</strong>, <strong>neural networks</strong>, <strong>overfitting </strong>and <strong>regularization</strong>, <strong>density estimation</strong>, <strong>autoencoders</strong>, <strong>variational autoencoders</strong>, and <strong>normalizing flows</strong>. Every step builds on the one before it. No step requires anything the previous steps did not already establish.</p><h3>The one idea behind all eight steps</h3><p>If you take away one thing from the series, it should be this. Every model in every step was trained by solving the same optimization problem:</p><figure><img alt="Minimization: argument minimum of the loss function" src="https://cdn-images-1.medium.com/max/353/1*DdaKbrkpUp1Ewwsds9lTTA.png" /></figure><p>The loss function L(θ) changed at each step as we asked more sophisticated statistical questions. The model family changed as we needed more expressive function approximators. But the algorithm compute the gradient of the loss with respect to the parameters, take a small step downhill, repeat <em>never changed once from Step 1 to Step 8</em>.</p><p>In section 1, minimizing MSE turned out to be identical to minimizing χ2 under Gaussian noise — something every physicist has done. In section 2, minimizing cross-entropy turned out to be Bernoulli maximum likelihood. In section 5, the negative log-likelihood became the universal training objective that unified all the previous cases. By section 8, that same objective, applied to an invertible neural network with a triangular Jacobian, gave us exact probability densities in high dimensions with no approximation.</p><p>The physicist’s summary: machine learning is maximum likelihood estimation, applied to increasingly expressive model families, optimized by gradient descent. You were already doing it.</p><h3>What each step contributed</h3><p><strong>Section 1: Linear regression</strong> established the vocabulary: <em>model</em>, <em>loss</em>, <em>parameters</em>, <em>gradient descen</em>t, loss surface. The χ² connection was made explicit.</p><p><strong>Section 2: Classification</strong> introduced the <em>sigmoid </em>and <em>cross-entropy</em>, explained via <em>entropy </em>and <em>information theory</em>. The ROC curve and detection efficiency were connected to real GW trigger ranking pipelines.</p><p><strong>Section 3: Neural networks</strong> showed why linear boundaries fail for real physics data, derived the forward pass and <em>backpropagation </em>from the chain rule, and introduced <em>ReLU </em>as the solution to the vanishing gradient problem.</p><p><strong>Section 4: Regularization</strong> introduced the <em>train/validation/test split</em>, the ML equivalent of blinding an analysis and showed that <em>L2 regularization</em> is Tikhonov regularization, familiar from inverse problems in geophysics and detector calibration.</p><p><strong>Section 5: Density estimation</strong> made the shift from discriminative to generative modelling, derived the <em>negative log-likelihood from first principles</em>, and showed why <em>KDE </em>and GMMs collapse above ten dimensions. The <em>curse of dimensionality </em>was made concrete.</p><p><strong>Section 6: Autoencoders</strong> introduced <em>PyTorch</em>, the bottleneck architecture, and the latent space. Anomaly detection without labels followed naturally. The hole problem was diagnosed precisely as a consequence of the reconstruction loss placing no constraint on the latent distribution.</p><p><strong>Section 7: Variational autoencoders</strong> built the <em>KL divergence</em> from entropy and cross-entropy, derived the closed form for Gaussians step by step, assembled the <em>ELBO </em>from Jensen’s inequality, and explained the reparameterization trick as the solution to a specific gradient flow problem.</p><p><strong>Section 8: Normalizing flows</strong> started from the rubber-band intuition for probability conservation, derived the <em>change-of-variables formula</em>, showed why <em>coupling layers</em> produce a triangular Jacobian with an O(D) determinant, and connected the result to <a href="https://arxiv.org/abs/2106.12594">DINGO</a>, <a href="https://arxiv.org/abs/2106.05285">CaloFlow</a>, <a href="https://arxiv.org/abs/2211.06397">FlowMC</a>, and the sbi <a href="https://github.com/sbi-dev/sbi">library</a>.</p><h3>The companion code</h3><p>Every article is accompanied by a self-contained Python code that generates its own data, trains a model, prints a step-by-step explanation to the terminal, and saves publication-quality figures. The scripts are written as annotated tutorials, not as software every non-trivial line has a comment explaining what it does and why. Running them in order, reading the terminal output alongside the figures, is the fastest way to make the mathematics visceral rather than abstract.</p><p>The code is available at <a href="https://github.com/wesmail/PhysML"><strong>github.com/wesmail/Ph</strong>ysML</a> under the MIT licence. The articles are available at <a href="https://wesmail.github.io/"><strong>wesmail.github.io</strong></a> under CC BY 4.0. Both are free to use, share, and adapt with attribution.</p><p>Feedback, corrections, and suggestions regarding both the articles and the accompanying code are warmly welcomed. Hope it helps 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46b8aa0c4f71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of Time-Series Modeling: Tokenization Through Vector Quantization]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@waleed.physics/the-future-of-time-series-modeling-tokenization-through-vector-quantization-77ed3bc745d8?source=rss-8d4542253634------2"><img src="https://cdn-images-1.medium.com/max/1536/1*_VkvHHh0n2niJMWPrDMbvA.png" width="1536"></a></p><p class="medium-feed-snippet">Time series are everywhere: shaking beneath our feet in seismic recordings &#x1FAE8;, humming through gravitational-wave detectors &#x3030;&#xFE0F;&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@waleed.physics/the-future-of-time-series-modeling-tokenization-through-vector-quantization-77ed3bc745d8?source=rss-8d4542253634------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@waleed.physics/the-future-of-time-series-modeling-tokenization-through-vector-quantization-77ed3bc745d8?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ed3bc745d8</guid>
            <category><![CDATA[vector-quantization]]></category>
            <category><![CDATA[totem]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[autoencoder]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 17:03:03 GMT</pubDate>
            <atom:updated>2025-11-14T17:03:03.105Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why Light Bends and Planets Dance: The Least Action Story]]></title>
            <link>https://medium.com/@waleed.physics/why-light-bends-and-planets-dance-the-least-action-story-e2a8359d8dd4?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2a8359d8dd4</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[principle-of-least-action]]></category>
            <category><![CDATA[nash-equilibrium]]></category>
            <category><![CDATA[lagrangian]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 21:29:36 GMT</pubDate>
            <atom:updated>2025-10-26T21:29:36.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOmwC30vP4vHIq6oeiqlBQ.png" /></figure><p>Imagine you’re a lifeguard on the beach. Far ahead in the water, someone is struggling and every second matters. You can sprint quickly on sand 🏃‍➡️, but once you dive into the waves 🌊, your speed slows dramatically. So what do you do? Run straight toward the swimmer? Or sprint farther along the beach to minimize your time in the water? Without thinking about the math, your brain instinctively finds the <strong>fastest</strong> route, that one that saves a life. <a href="https://en.wikipedia.org/wiki/Richard_Feynman">Richard Feynman</a> loved this story because it reveals a remarkable truth:</p><blockquote><strong>all of nature behaves like that lifeguard</strong>.</blockquote><p>Whether it’s a ray of light bending through glass or a planet curving through space, the universe always “chooses” the path that requires the least possible effort or time. This profound idea has a name the</p><blockquote><strong>Principle of Least Action</strong></blockquote><p>and it turns out to be one of the most beautiful and unifying laws in all of physics.</p><figure><img alt="A lifeguard stands on a sandy beach looking toward a swimmer in the water, with three possible rescue paths illustrated: a straight path labeled “Least distance,” a path that stays along the beach longer labeled “Least water,” and a middle path highlighted as “Least time,” showing the fastest rescue route." src="https://cdn-images-1.medium.com/max/544/1*DcAs-jFObfMDUtelbwGceg.png" /><figcaption>The lifeguard’s dilemma: The shortest route isn’t the fastest. Running farther along the beach reduces the slow part of the journey in water, leading to the path of least time. Nature, like this lifeguard, always finds the most efficient path.</figcaption></figure><p>What you’ve just seen is not just a clever beach story — it’s a scene straight out of Richard Feynman’s legendary <em>Lectures on Physics</em>. Feynman used this simple rescue scenario to reveal something astonishing: <strong>the same logic that guides a lifeguard also guides the entire universe</strong>. And this isn’t an exaggeration. The <em>Principle of Least Action</em> is one of the most profound, beautiful, and unifying ideas ever discovered in physics, a principle so powerful that from it we can derive almost every law of motion we know.</p><h3>From Beaches to Beams: Snell’s Law via Least Time</h3><p>Think back to the lifeguard story. Light faces the same dilemma at the boundary between air and water: it “moves” fast in air and slower in water. Of all the possible routes from point A (in air) to point B (underwater), which arrives soonest? The winning path balances two competing urges, go more directly toward the target, or stay longer in the fast medium to reduce time in the slow medium. If we compute the <strong>total travel time</strong> for any path that hits the surface at some point x, it’s</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*hZcKqICauJ961Omb8jOjgQ.png" /></figure><p>where v_1 and v_2​ are light’s speeds in air and water. When you minimize this time (the calculus step sets dT/dx=0), a beautiful relation pops out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*KhXoz8HcUAKBwWNrtDABtg.png" /></figure><p>Since light slows down in water. Physicists came up with a name for how much a material slows down light, it is called the <strong>refractive index</strong>. Think of it as a <em>“speed limit for light in the material”</em>:</p><ul><li>A <strong>low refractive index</strong> → light moves fast (air, outer space)</li><li>A <strong>high refractive index</strong> → light slows down (water, glass, diamond)</li></ul><p>And here’s the amazing part:</p><blockquote><strong>light doesn’t just plow ahead but it adjusts its path to get to its destination as fast as possible</strong>.</blockquote><p>This compromise found by minimizing travel time leads directly to the famous <strong>Snell’s Law</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*RGsF4bcypizvsbQtRDtxEg.png" /></figure><figure><img alt="A side-by-side image comparing a diagram and a real demonstration of light refraction. On the left, a red ray of light travels from air into water, bending at the boundary. Angles θ1 and θ2 ​ are shown relative to a dashed normal line, with labels indicating different refractive indices and speeds of light in each medium. On the right, a photo shows a laser beam entering a clear container of water and bending toward the normal inside, illustrating the same effect in real life." src="https://cdn-images-1.medium.com/max/734/1*Fe0LxThGTgjJvKLQrSt7FA.png" /><figcaption><strong>Light’s Shortcut:</strong> When a laser beam enters water from air, it bends toward the vertical “normal” line because it slows down in water. This bending follows Snell’s Law — a precise mathematical rule that comes directly from nature choosing the fastest path for the light to travel. Left figure source: <a href="https://en.wikipedia.org/wiki/Snell%27s_law">https://en.wikipedia.org/wiki/Snell’s_law</a></figcaption></figure><p>This simple equation predicts exactly <strong>how much</strong> light bends at any boundary. It’s why:</p><ul><li>a straw in a glass of water looks bent 🍹</li><li>a prism spreads white light into a rainbow 🌈</li><li>lenses can focus sunlight into a burning beam 🔥</li></ul><h3><strong>The Master Equation of Nature</strong></h3><p>So far we’ve seen that light cleverly bends to reach its destination faster, but this fascinating behavior isn’t unique to light. <strong>Everything in the universe</strong>, from apples falling off trees to planets orbiting stars, and even electrons flickering through atoms, follows a single, powerful rule. This rule or principle can be written in one compact line:</p><blockquote>The Principle of Least Action</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*KhB9NzSFC6kNONCZSEUXWA.png" /></figure><p>Don’t panic! This isn’t a complicated formula you need to memorize. What matters is what it <em>means</em>.</p><ul><li>S is called the <strong>action</strong>, a kind of score the universe assigns to each possible path something could take.</li><li>L is called the <strong>Lagrangian</strong>, named after the brilliant mathematician and physicist <strong>Joseph-Louis Lagrange</strong> (1736–1813), who helped turn classical mechanics into a precise science. The <strong>Lagrangian </strong>is a quantity that generally depends on the position (and it’s time derivative) and time.</li></ul><p>And here’s the magic:</p><blockquote><strong><em>Out of all possible paths between two points, nature always picks the one that makes S as small as possible, the path of least action.</em></strong></blockquote><p>Still not impressed? Here’s the real punchline:</p><blockquote><strong>this one formula silently contains nearly all of physics inside it</strong>. Newton, Einstein, quantum theory they all fall out of the action S.</blockquote><p>Even <strong>Snell’s law of refraction</strong>, the law that tells us how light bends when it enters water, can be derived from this same principle.</p><p>So what does this look like in practice? Let’s See the <strong>Action </strong>in Action 😄. Let’s derive the famous Newton 2nd law — the famous <em>apple law </em>🍎<em>.</em></p><h3><strong>The Action Behind Falling Apples </strong>🍎</h3><p>Newton’s second law tells us that:</p><blockquote><em>Force = mass × acceleration (F = ma)</em></blockquote><figure><img alt="A semi-realistic painting of Isaac Newton sitting under an apple tree in a garden, looking surprised as an apple falls toward his head, representing the inspiration behind his theory of gravity." src="https://cdn-images-1.medium.com/max/1024/1*_m2_x5jq5fz02V8W4nPfYQ.png" /><figcaption>Sir Isaac Newton beneath an apple tree, moments before the falling apple sparks his curiosity about gravity. A symbolic depiction of scientific discovery.</figcaption></figure><p>But in the least action world, we don’t start with force. We start with the <strong>action</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*vVOwaYAODQid9aU2IVQdqg.png" /></figure><p>Before we jump in, we should take one quick moment to appreciate a key player here: the <strong>Lagrangian</strong>, L, which in this case has a very special combination of energies: L = T — V</p><ul><li>T = kinetic energy → <strong>energy of motion</strong></li><li>V = potential energy → <strong>energy of position</strong> (like gravity pulling on an apple)</li></ul><p>Why <strong>this</strong> particular combination? Why not T+V or T×V?</p><p>Here’s the beautiful answer:</p><blockquote><em>The universe respects certain </em><strong><em>symmetries</em></strong><em>, and those symmetries </em>force<em> the Lagrangian to take this form.</em></blockquote><p>These aren’t coincidences, they are linked by a deep result in physics called <strong>Noether’s Theorem</strong> named after the brilliant mathematician Emmy Noether (1882–1935).</p><p>That exact recipe yields motions that match <strong>the real world</strong>.<br> So when we write L=T−V, we’re not guessing<strong>, we’re respecting the symmetries of the universe.</strong></p><p>So far, so good, let’s take one step further, the kinetic energy is the energy of motion. Therefore, it depends on the velocity of the object. So, for a moving particle, the kinetic energy is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*t_vHuBc3gbh_UHTdaQi7QA.png" /></figure><p>The small dot above x in physics means “time derivative”, which is just a fancy way of saying <strong>“how fast something changes in time”. Simply</strong>, the velocity of the moving object.</p><p>The potential energy on the other hand, depends on the position and it’s exact form depends on the <em>situation</em>!. For example, if you are moving near the earth’s surface you <em>gravitational potential energy </em>takes the form <em>mgx, </em>where g, is the gravitational acceleration, which is a constant 9.8 m/s2. Since, the exact form of potential energy depends on the situation, we will <em>refer to it as just V(x)</em>, which means a function of<em> x.</em></p><p>Now, go back to the action equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*novhHWZ0v3uULVZ_lKCqJg.png" /></figure><p>Now comes the fun part<strong>, we need to minimize the action</strong>, make it as small as possible. Remember: <em>least</em> action 😉.</p><p>When we ask for the path that makes S smallest, we’re stepping into a powerful branch of mathematics called the <strong>calculus of variations</strong>. Instead of finding the lowest point on a curve (like in normal calculus), this math finds the <em>best path out of infinitely many possibilities</em>. It’s like comparing every possible movie of a particle’s motion — past, present, future — and picking the one nature actually uses. Using this mathematical super-tool, the <strong>Euler–Lagrange equations</strong>, we can turn the vague idea of “the most efficient path” into a precise law of motion.</p><p>So, using this mathematical tool, the Euler–Lagrange equations, something magical happens 🪄:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*qSi-YNKo5a4IBCTf4EQF2A.png" /></figure><p>The right-hand side is exactly the <strong>force</strong> calculated from the potential:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*rb7PULJN0cCpvVo2qZxbgQ.png" /></figure><p>➡️ Rearranging gives the iconic result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*IH9mUPthbAdIDWOa0u46SQ.png" /></figure><p>In summary, Newton discovered F=ma by studying apples. But, Lagrange showed that <strong>apples simply obey the universe’s efficiency rule</strong>.</p><h3><strong>The Action That Curves Spacetime</strong></h3><p>We’ve just seen how Newton’s famous law F=ma <strong>falls out of the action</strong>, nature picking the most efficient path in space and time. But Newton made one assumption that eventually cracks: <em>Space and time themselves are fixed, absolute, and flat.</em></p><p>Fast-forward to 1905: Albert Einstein (1879–1955) arrives with <strong>Special Relativity</strong>, showing that:</p><ul><li>Space and time are woven together into <strong>spacetime</strong></li><li>Motion stretches time and shrinks space</li><li>The speed of light is the ultimate speed limit</li></ul><figure><img alt="A semi-realistic painting of Albert Einstein sitting at a desk, writing the general relativity field equations, while behind him a cosmic scene shows the Sun warping a grid of spacetime to represent gravity as curvature." src="https://cdn-images-1.medium.com/max/1024/1*qy-AgJaFShEelscilRnx8Q.png" /><figcaption>Albert Einstein writing the General Relativity (GR) field equations , which are derived by applying the principle of least action to the Einstein–Hilbert action!</figcaption></figure><p>So now, instead of an object minimizing <strong>action in space</strong>, a free particle in relativity moves along the path that <strong>maximizes proper time</strong>, its personal time. That naturally leads to a new action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*Er_aKu4kO5fwLyb-9Y170A.png" /></figure><p>This alone already gives us the <strong>relativistic equation of motion</strong>, derived again by minimizing the action.</p><p>Pretty cool. But Einstein wasn’t done. He generalized his special theory of relativity by asking What if objects simply <strong>follow straight paths</strong>, but in a <strong>curved</strong> spacetime?</p><p>This is Einstein’s insight in <strong>General Relativity</strong>:</p><blockquote><em>Mass and energy tell spacetime how to curve.<br>Curved spacetime tells matter how to move.</em></blockquote><p>So how does least action fit here?</p><blockquote>A free-falling object (like an astronaut orbiting Earth) moves along the <strong>straightest possible path</strong> but in curved spacetime. These straightest paths are called <strong>geodesics.</strong></blockquote><p><em>Mathematically</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*5KOO7f4FfA1Bfuyr_2k9tQ.png" /></figure><p>Don’t panic! The message is simple:</p><ul><li>gμν​ is the “shape” of spacetime</li><li>Minimizing this action picks the <strong>geodesic</strong></li><li>A geodesic <em>looks like</em> a straight line to the traveler, i.e., no force felt!</li></ul><p>This gives <strong>the geodesic equation</strong> — the “F=ma” of GR — telling us how objects move in curved spacetime.</p><blockquote>That’s how GPS satellites, light near the Sun, and black hole orbits are predicted.</blockquote><p>Einstein answered with the most powerful action ever written:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*-L0IYbSxv_SAiLSDYXwztw.png" /></figure><p>This is the <strong>Einstein–Hilbert Action</strong>, the master formula for gravity. Extremizing this action gives you the <strong>Einstein Field Equations</strong>, the equations that shape the <strong>entire universe</strong>.</p><blockquote><strong>Same idea. Bigger stage. </strong>The principle of least action didn’t break <strong>it <em>expanded</em> into the shape of the cosmos.</strong></blockquote><h3>All Paths Allowed: Welcome to Quantum Reality</h3><p>In our everyday world, objects take one path, the path of <strong>least action</strong>.<br>That’s why a lifeguard runs a smart shortcut and a ball arcs smoothly through the air.</p><p>But zoom all the way down to quantum particles, and nature gets playful 😏.</p><p>This is where <strong>Richard Feynman</strong> enters the stage again, not with a beach story this time, but with one of the greatest ideas in physics:</p><blockquote>A quantum particle does not take one path. It explores <strong>all possible paths</strong> at once.</blockquote><p>Every wiggly, zig-zaggy, looping path from point A to point B the particle tries them all.</p><p>Light doesn’t just bend in a neat line into water. It tries a trillion trillion different route<strong>s but most cancel out. </strong>Only paths near the <em>least-action</em> route reinforce each other and survive.🎩 That’s the quantum magic.</p><figure><img alt="Diagram showing many thin red paths from point A in air to point B in water, representing all possible trajectories a particle or light ray can take. A single blue path is emphasized as the least-action path that dominates the contribution." src="https://cdn-images-1.medium.com/max/359/1*3BdBpia9YgmxPwGzSTOU0w.png" /><figcaption><strong>A laser beam traveling from point A to point B in a system with two media (air above and water below). Quantum mechanically, the particle explores <em>all</em> possible paths between A and B (thin red rays). The dominant path — highlighted (blue) — is the one that makes the action stationary, corresponding to the path of least action according to the principle of least action and Fermat’s principle of least time.</strong></figcaption></figure><p>Instead of action choosing the <em>one</em> winning movie a particle stars in, quantum mechanics <strong>screens every movie ever filmed</strong>. Feynman called this the <strong>Path Integral</strong> formulation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*s5RVex5St0bccOWrLo19aA.png" /></figure><p>Once again, S is the action here. Each path contributes a little “vote” in the form of a wave:</p><ul><li>If neighboring paths have <strong>similar action</strong>, their waves line up → <strong>constructive</strong> addition → observable path</li><li>If actions differ a lot, the waves cancel → <strong>destructive</strong> interference → path disappears</li></ul><p>The classical path, Newton’s orbits, laser beams, falling apples, is simply the path where <strong>all votes add up most strongly</strong>.</p><p>So classical physics isn’t wrong, it’s just the <strong>shadow</strong> of quantum physics in the limit where a zillion paths cancel out except the least-action ones.</p><p>Think of it this way:</p><blockquote><em>A quantum particle samples every possible universe…<br> and reality becomes the one with the most constructive interference.</em></blockquote><p>We started with a lifeguard. Then we soared to planets and curved spacetime. Now we see down to the quantum foam. And all along, one idea ruled them all:</p><blockquote><strong><em>Everywhere and everywhen in the universe, reality is shaped by extremizing the action.</em></strong></blockquote><h3>Economics and Games: The Least-Action Whisper Behind Decisions</h3><p>You might think that the principle of least action is just a physics rule, a beautiful secret whispered by falling apples, spinning planets, and curious photons. But it is <strong>much more than that</strong>. In economics and finance, something very similar happens, albeit in different language, different variables, and with human agents instead of falling apples. But the underlying theme remains: <strong>efficiency, optimization, and equilibrium</strong>.</p><p>In markets, firms, or national economies, every decision, producing, investing, consuming, saving, can be thought of as an <em>action</em> in the sense of “what sequence of steps will minimize cost or maximize return given time and resources”. Researchers have explored applying variational‐principle ideas to economics.</p><p>In simple terms:</p><blockquote><em>Whether it’s a firm choosing how much to produce, or a government deciding how much to invest, the </em>sequence of actions over time<em> matters. The best sequence often minimizes some “cost functional” or maximizes a “utility functional” subject to constraints. That’s analogous to minimizing an action in physics.</em></blockquote><p>In addition, in game theory, the concept of a Nash equilibrium, named after John Nash (1928–2015) describes a situation where <strong>no player can improve their outcome by unilaterally changing their strategy</strong>.</p><p>Here’s how the action‐thinking enters:</p><ul><li>Each player chooses a “path” (a strategy or sequence of moves) over time.</li><li>The “action functional” becomes something like a player’s cumulative payoff (or cost) over time, given the interplay with other players.</li><li>A Nash equilibrium is a profile of strategies such that <strong>no one can reduce their “action” (cost) or increase their “utility” by deviating</strong> — in other words, the “path” each player follows is (locally) optimal given the others.</li><li>Sophisticated mathematical work shows that Nash equilibria can be studied through <strong>variational inequalities</strong> and variational analysis, branches of mathematics deeply related to calculus of variations.</li></ul><p>So just like particles and light “choose” paths of stationary action, human agents in competition choose strategy paths where their personal “action” is (in some sense) optimized relative to others.</p><h3>🤖 The AI Connection: Machines Learn Like the Universe Acts</h3><p>Now jump to modern AI. Inside a neural network, whether it’s recognizing cats, translating languages, or forecasting earthquakes, something eerily familiar is happening.</p><p>At its core, <strong>AI is also minimizing something</strong>: a <em>loss function</em>.</p><p>Every training step adjusts millions or even billions of parameters in a direction that <strong>reduces</strong> that loss. That journey, guided by <strong>gradient descent</strong>, is a search for:</p><blockquote><em>The path of least “computational action” in parameter space.</em></blockquote><p>Physicists minimize action over <em>time</em>. AI minimizes loss over <em>learning</em>.</p><blockquote>Euler–Lagrange equations → best physical path<br>Gradient descent → best learning path</blockquote><p>Same idea. Different universe.</p><p>Push the analogy a bit further and it gets richer. In information-theoretic terms, popular losses (cross-entropy, KL) measure <strong>information discrepancy</strong>; minimizing them is like following the path of <strong>least informational effort</strong>. And just as symmetries of a physical Lagrangian yield conservation laws, <strong>invariances in data and architectures</strong> (translation in CNNs, permutation in Deep Sets, rotation in equivariant GNNs) shape the loss landscape and produce <strong>stable, generalizable behavior</strong>. You can even add “kinetic” style regularizers that penalize rapid weight changes, encouraging smoother, lower-action training paths that often generalize better. So while AI isn’t literally solving classical mechanics, the guiding philosophy is shared: <strong>choose the right action (loss + symmetries), and the right behavior emerges from extremizing it</strong>.</p><p>I hope you enjoyed this journey into one of the most beautiful and unifying ideas in science, and that the Principle of Least Action now feels like a secret thread connecting everything from falling apples to artificial intelligence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2a8359d8dd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Graphs Learn: From Message Passing to Attention]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@waleed.physics/how-graphs-learn-from-message-passing-to-attention-1854b777288b?source=rss-8d4542253634------2"><img src="https://cdn-images-1.medium.com/max/1024/1*t9hQyXhqP2_EJm3rP6z9Ug.png" width="1024"></a></p><p class="medium-feed-snippet">Do you know that 2024 Nobel Prize in Chemistry celebrated a landmark moment for artificial intelligence in science &#x1F973;. It is awarded&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@waleed.physics/how-graphs-learn-from-message-passing-to-attention-1854b777288b?source=rss-8d4542253634------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@waleed.physics/how-graphs-learn-from-message-passing-to-attention-1854b777288b?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/1854b777288b</guid>
            <category><![CDATA[graph-attention-networks]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[message-passing-networks]]></category>
            <category><![CDATA[pytorch-geometric]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 18:20:08 GMT</pubDate>
            <atom:updated>2025-10-19T18:53:35.409Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Demystifying GNNs: Implementing a Graph Neural Network from Scratch]]></title>
            <link>https://medium.com/@waleed.physics/demystifying-gnns-implementing-a-graph-neural-network-from-scratch-27759d262b70?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/27759d262b70</guid>
            <category><![CDATA[pytorch-geometric]]></category>
            <category><![CDATA[geometric-deep-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[graph-convolution-network]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 08:13:46 GMT</pubDate>
            <atom:updated>2025-10-19T19:07:59.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Implementation of Graph Neural Networks from scratch article banner" src="https://cdn-images-1.medium.com/max/1024/1*9Be4q5CQ1If-UtKCluh_5g.png" /></figure><p>As an Egyptian I was living the time during the <strong>Egyptian revolution</strong> in <strong>January 2011 </strong>and witness the reasons for this great and inspiring revolution 😍which is mainly lead by corruption and police brutality😥. The important thing here is that people were mainly using <strong>Facebook </strong>and <strong>twitter </strong>(now X) to communicate and organize demonstrations. <em>You can see already the importance of social media in making the revolution success</em>.</p><p>Another example of the importance and influence of <strong>social media </strong>on people’s lives and the history is <strong>Cambridge Analytica </strong>in the <strong>USA elections </strong>where personal data belonging to millions of Facebook users was collected without their consent 👺 by British consulting firm Cambridge Analytica, predominantly to be used for political advertising.</p><p>These two examples demonstrate the importance of social media, but <strong>the question </strong>is<strong> how extract and deal with such data</strong>. The answer is simply <strong>graphs</strong>! Dealing with graph dataset is under the umbrella of what is known as <strong>Geometric deep learning</strong> (<strong>GDL</strong>) 😵‍💫. The term geometric deep learning was first coined by <a href="https://en.wikipedia.org/wiki/Michael_Bronstein"><strong>Michael Bronstein</strong></a>. Fundamentally, geometric deep learning involves encoding a geometric understanding of data as an inductive bias in deep learning models to give them a helping hand.</p><h3>The Language of Graphs:</h3><p>In simple terms, a <strong>graph </strong>is a collection of points, called <strong>nodes </strong>or <strong>vertices</strong>, <strong>connected </strong>by <strong>lines </strong>known as <strong>edges </strong>mathematically represented as <strong>G(V,E)</strong>, where V is the set of vertices and E is the set of edges.</p><blockquote>GDL uses this idea to apply deep learning techniques to graph data.</blockquote><p>To better understand this, let’s look at some everyday examples of graph data:</p><ol><li><strong>Chemistry</strong>⚗️: Think of molecules as tiny structures made of atoms connected by bonds. We can picture these structures as graphs, where each atom is a node and each bond between atoms is an edge.</li><li><strong>Citation Networks </strong>🌐: When scientists write research papers, they often refer to other scientists’ work. Imagine each paper as a point (node) and every reference to another paper as a connection (edge) between them. This forms a network of citations, much like a graph.</li><li><strong>Social Networks </strong>#️⃣: This is what we’ve been talking about. Imagine a social network where each person is a point (node) and their friendships or connections are lines (edges) between them. This helps us study how people interact as a group.</li><li><strong>Traffic </strong>🚥: Surprisingly, traffic can also be represented as a graph. Think of each intersection as a node and the roads connecting them as edges. This helps in understanding and managing traffic flow.</li></ol><figure><img alt="Examples of Graph Data" src="https://cdn-images-1.medium.com/max/1024/1*77xFGIWX_lBU266fR7HwWg.png" /><figcaption>Examples of Graph Data</figcaption></figure><p>Graph data comes in different forms, including <strong>directed </strong>and <strong>undirected</strong> graphs. Imagine directed graphs like one-way streets: they have arrows on the edges, showing the direction of connection. For instance, if there’s an edge from node A to node B, it’s not the same as one from node B to node A, the direction matters. On the other hand, undirected graphs are like two-way streets. There’s no distinction in direction between nodes. An edge is simply a connection without any directional arrow. Additionally, graphs can have <strong>loops</strong>. This means a node can link back to itself, creating a loop. It’s like a road that starts and ends at the same place. Let’s write some code to visualize different kinds of graphs, we will use the famous <a href="https://networkx.org/"><strong>networkx</strong></a> library to create graphs.</p><p>Before you run the following code, please make sure that you have the <strong>networkx</strong> library already installed:</p><pre>pip install networkx[default]</pre><pre># import networkx and matplotlib to plot the graphs<br>import networkx as nx<br>import matplotlib.pyplot as plt<br><br># Create an undirected graph with 4 nodes <br># and we will connect the nodes by hand using<br># add_edges_from() method<br>undirected_graph = nx.Graph()<br>undirected_graph.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (4, 2)])<br><br># Create a directed graph<br>directed_graph = nx.DiGraph()<br>directed_graph.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (4, 3), (1, 4)])<br><br># Create an undirected graph with loops<br>undirected_graph_loops = nx.Graph()<br>undirected_graph_loops.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 1), (3, 3)])<br><br># Drawing the graphs<br>plt.figure(figsize=(12, 4))<br><br># Draw the undirected graph<br>plt.subplot(131)<br>nx.draw(undirected_graph, with_labels=True, node_color=&#39;lightblue&#39;, node_size=200, font_size=10)<br>plt.title(&quot;Undirected Graph&quot;)<br><br># Draw the directed graph<br>plt.subplot(132)<br>nx.draw(directed_graph, with_labels=True, node_color=&#39;lightgreen&#39;, node_size=200, font_size=10, arrows=True)<br>plt.title(&quot;Directed Graph&quot;)<br><br># Draw the undirected graph with loops<br>plt.subplot(133)<br>nx.draw(undirected_graph_loops, with_labels=True, node_color=&#39;salmon&#39;, node_size=200, font_size=10, arrows=True)<br>plt.title(&quot;Undirected Graph with Loops&quot;)<br><br># Display the graphs<br>plt.tight_layout()<br>plt.show()</pre><p>When you run the previous block of code, it will generate an image that demonstrates directed and undirected graphs, as well as graphs containing loops</p><figure><img alt="Undirected graph (left), directed (middle) and graph with loops (right)." src="https://cdn-images-1.medium.com/max/1024/1*A7s6k9DmTlf158bpMZUQZw.png" /><figcaption>Undirected graph (left), directed (middle) and graph with loops (right).</figcaption></figure><p>So far so good, but now, let’s think about how we can turn a graph into something <em>a computer can understand</em>. After all, computers really just understand <strong>numbers </strong>♾️. The field of <strong>graph theory</strong> offers some answers, but it’s a broad topic beyond the scope of this article. So, we’ll just focus on the basics of how graphs are represented mathematically. One common way to represent a graph is through an <strong>adjacency matrix</strong>.</p><p>The <strong>adjacency matrix </strong>(<strong>A</strong>) is a <strong>grid </strong>(or matrix) where each <strong>row </strong>and <strong>column</strong> represent a <strong>node</strong>. In this matrix, we use <strong>0s and 1s</strong> to <strong>show connections</strong>: a <em>‘0’ means no connection between two nodes</em>, and a ‘<em>1’ means there is a connection</em>.</p><figure><img alt="The Adjacency Matrix (A) definition" src="https://cdn-images-1.medium.com/max/1024/1*k786skEanRyX4poy3udNfw.png" /><figcaption>The Adjacency Matrix (A) definition</figcaption></figure><p>Another key representation is the <strong>degree matrix </strong>(<strong>D</strong>). This is also a grid, but it shows how many connections each node has.</p><p>In deep learning, we often use a third type of representation called the <strong>feature matrix</strong>. This is a table where each <em>row represents a node</em>, and <em>each column represents a feature of that node</em>, like <em>age </em>or <em>gender </em>in a social network. So, if we’re talking about people on social media, each person (node) would have features like age, gender, etc., listed in this matrix. By translating graphs into these numerical formats, we make it possible for computers to process and learn from complex graph data.</p><p>The next code block takes the undirected graph from above and prints its mathematical form, including the <strong>adjacency matrix</strong> and the <strong>degree matrix</strong>.</p><pre>import networkx as nx<br>import numpy as np<br><br># Create an undirected graph<br>undirected_graph = nx.Graph()<br><br># ----------------------------<br># 1️⃣ Adjacency Matrix<br># ----------------------------<br># The adjacency matrix A[i][j] = 1 if there is an edge between nodes i and j, otherwise 0.<br>A = nx.to_numpy_array(undirected_graph, nodelist=sorted(undirected_graph.nodes()))<br>print(&quot;Adjacency Matrix (A):&quot;)<br>print(A)<br><br># ----------------------------<br># 2️⃣ Degree Matrix<br># ----------------------------<br># The degree matrix D is a diagonal matrix where D[i][i] is the degree of node i.<br>degrees = [val for (node, val) in undirected_graph.degree()]<br>D = np.diag(degrees)<br>print(&quot;\nDegree Matrix (D):&quot;)<br>print(D)<br><br># ----------------------------<br># 3️⃣ (Optional) Check results<br># ----------------------------<br># You can also verify the Laplacian: L = D - A<br>L = D - A<br>print(&quot;\nGraph Laplacian (L = D - A):&quot;)<br>print(L)</pre><p>The output should be:</p><figure><img alt="An example of adjacency matrix and degree matrix of an undirected graph." src="https://cdn-images-1.medium.com/max/1024/1*CkgXd9764qEbqhhuXeUR4w.png" /></figure><h3>The Art of GNN Implementation:</h3><p>Let’s dive into the most exciting part: how do we learn from graph data? The answer is with something called a <strong>Graph Neural Network (GNN)</strong>.</p><blockquote>A GNN is a special kind of neural network designed to work with graph data.</blockquote><p><em>But how exactly is a GNN built?</em> It might get a bit technical, but the <em>key is to design it is in a way that keeps the structure of the graph data intact</em>. Just like in Convolutional Neural Networks (CNNs) if you design a layer that shuffles the pixels you would simply destroy the input image. <em>In GNNs, we need operations that respect the graph’s structure</em>. Here’s how this is done in GNNs:</p><ol><li><strong><em>Symmetric Aggregation</em></strong><em>: This involves using functions like sum, mean, or max to combine information from a node’s neighbors. These functions don’t care about the order of the nodes, making them perfect for keeping the graph structure.</em></li><li><strong><em>Parameter Sharing</em></strong><em>: In GNNs, the same parameters are used across all nodes. This way, every node is treated equally, no matter where it is in the graph.</em></li><li><strong><em>Readout Function</em></strong><em>: If the goal is to understand the whole graph (like classifying the graph into categories), we use a special function that treats the entire graph as a single entity. This function doesn’t change based on the order of the nodes.</em></li></ol><p>By sticking to these principles, a GNN can effectively learn from graph data, regardless of how the nodes in the graph are ordered. This makes the GNN versatile and able to handle different graphs and different arrangements of the same graph.</p><p>Now that we understand the basics for designing a layer in a GNN, let’s look at how we use the different graph data representations we talked about earlier. Remember, we have two types of representations for graph connectivity (how the graph is connected) and one for node features (the properties of each node).</p><p>We can use the <strong>adjacency matrix</strong> to show the connections in the graph. In addition, we also have the <strong>feature matrix</strong> that describes the characteristics or the features of each node.</p><p>In a <strong>simple graph layer</strong>, we might use a formula like <strong><em>h = WAX</em></strong>, which combines node features (X) with graph connectivity (A), where (W) are the weights of the layer. <em>Multiplying by the adjacency matrix ensures that we include the features of neighboring nodes as it encodes the graph connectivity</em>.</p><p>But there’s a catch: <strong>this method doesn’t include the features of the central node itself</strong>, where the central node in this context refers to a specific node that is the focus of analysis or computation at a given moment. To fix this, we add what’s called <strong>self loops</strong> to the adjacency matrix. This means we adjust the matrix to include connections from nodes to themselves.</p><p>We do this by adding the identity matrix (I) to (A), creating a new matrix (Ã). So, our updated formula becomes <strong><em>h = WÃX</em></strong>, once again (W) is simply the weights of the layer or the learnable parameters. <em>By doing this, our GNN layer can now consider both the features of a node and its neighbors, giving us a more complete picture</em>.</p><h3>Coding your first GNN:</h3><p>Now, let’s proceed to implement our GNN layer and put it to the test on a real-world graph dataset. We’ll compare our GNN with a simple <strong>Multi-Layer Perceptron</strong> (<strong>MLP</strong>) to see how well it does. We’ll use <a href="https://pytorch.org/"><strong>PyTorch</strong> </a>to build our GNN.</p><p>For the data we’ll use, there’s a dataset called the <strong>Cora dataset</strong>. The Cora dataset comprises <strong>2708 scientific publications</strong>, each classified into one of <strong>seven distinct classes</strong>. It features a citation network with <strong>5429 links</strong>. Every publication in the dataset is characterized by a binary word vector, which represents the absence (0) or presence (1) of certain words from a dictionary of 1433 unique terms. Our goal is to <strong>classify</strong> each node (publication) into one of these <strong>seven classes</strong>.</p><p>While the Cora dataset can be accessed directly from its official website, we’ll use <a href="https://pytorch-geometric.readthedocs.io/en/latest/"><strong>PyTorch Geometric</strong></a><strong> (PyG) </strong>to download it. PyG is a library built upon PyTorch to easily write and train GNNs.</p><blockquote>Please, first make sure you have <strong>PyTorch</strong> and <strong>PyG</strong> installed.</blockquote><blockquote>You can follow the official installation guide at 👉 <a href="https://pytorch.org/">https://pytorch.org/</a>. For most users, installing via pip looks like this:</blockquote><pre># For GPU (CUDA 12.x)<br>pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121<br><br># OR for CPU-only version<br>pip install torch torchvision torchaudio</pre><blockquote>Next, install <strong>PyG </strong>and its dependencies. Follow the official guide here: 👉 <a href="https://pytorch-geometric.readthedocs.io/en/latest/install/installation.html">https://pytorch-geometric.readthedocs.io/en/latest/install/installation.html</a>. For most setups (PyTorch ≥ 2.0), you can install PyG as follows:</blockquote><pre># Install core PyG packages<br>pip install torch-geometric<br><br># (Optional) Install additional operators if needed<br>pip install torch-scatter torch-sparse torch-cluster torch-spline-conv -f https://data.pyg.org/whl/torch-2.4.0+cu121.html</pre><p>Let’s dive into this task!</p><p>This code 📦 downloads the <strong>Cora citation network dataset</strong> using the <strong>Planetoid</strong> class from <strong>PyG</strong>, stores it in the current directory, and accesses its single graph. It then prints key information about the dataset — including the number of graphs, nodes (<strong>papers</strong>), features (<strong>attributes per paper</strong>), and classes (<strong>research topics</strong>) — giving you a quick overview of the dataset’s structure 🧠📊.</p><pre># Import the Planetoid class from PyG<br>from torch_geometric.datasets import Planetoid<br><br># Then download the Cora dataset using this class<br># We will donwload it in this directory (.)<br>dataset = Planetoid(root=&quot;.&quot;, name=&quot;Cora&quot;)<br><br># Cora only has one graph, can be accessed as follows<br>cora = dataset[0]<br><br>print(f&#39;Dataset: {dataset.name}&#39;)<br>print(&#39;---------------&#39;)<br>print(f&#39;Number of graphs: {len(dataset)}&#39;) # how many graphs in this dataset<br>print(f&#39;Number of nodes: {cora.x.shape[0]}&#39;) # here, x, is the feature matrix<br>print(f&#39;Number of features: {dataset.num_features}&#39;) # how many features, how many columns are in x<br>print(f&#39;Number of classes: {dataset.num_classes}&#39;) # how many classes</pre><p>Now let’s train a very simple MLP for the task of node classification! First, the MLP implementation:</p><pre># PyTorch imports<br>import torch<br>import torch.nn.functional as F<br><br># A simple feed forward network for multiclass classification<br>class MLP(torch.nn.Module):<br>    def __init__(self, in_features, hidden_features, out_features, activation=torch.nn.ReLU):<br>        super().__init__()<br>        self.layer1 = torch.nn.Linear(in_features, hidden_features)<br>        self.layer2 = torch.nn.Linear(hidden_features, out_features)<br><br>        self.activation = activation()<br><br>    def forward(self, x):<br>        h = self.layer1(x)<br>        h = self.activation(h)<br>        h = self.layer2(h)<br>        out = F.log_softmax(h, dim=1)<br><br>        return out   </pre><p>And then, we split the graph into train (80%) and test (20%) datasets using the famous scikit-learn package:</p><pre>from sklearn.model_selection import train_test_split<br><br># Extract the node features and the labels<br>X, y = cora.x.numpy(), cora.y.numpy()<br><br># Split the data into train and test sets (80%, 20%)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Convert to PyTorch tensors<br>train_data = {&quot;X&quot;: torch.tensor(X_train, dtype=torch.float32), &quot;y&quot;:torch.tensor(y_train, dtype=torch.long)}<br>test_data = {&quot;X&quot;: torch.tensor(X_test, dtype=torch.float32), &quot;y&quot;:torch.tensor(y_test, dtype=torch.long)}</pre><p>Now, we define a simple training and testing functions 😉 to train our MLP model 🧠on the Cora dataset and evaluate its performance!</p><pre>import torch<br>import numpy as np<br>from tqdm import trange<br><br># ============================================<br># Training Function<br># ============================================<br>def fit(model, data, criterion, config):<br>    &quot;&quot;&quot;<br>    Train a PyTorch model on the given dataset.<br>    <br>    Args:<br>        model: The neural network model (PyTorch module)<br>        data:  Dictionary containing input features &#39;X&#39; and labels &#39;y&#39;<br>        criterion: Loss function<br>        config: Object or dict containing hyperparameters like:<br>                - device (e.g. &#39;cuda&#39; or &#39;cpu&#39;)<br>                - lr (learning rate)<br>                - max_epochs (number of training epochs)<br>                <br>    Returns:<br>        Dictionary containing lists of training loss, accuracy, and epoch indices.<br>    &quot;&quot;&quot;<br><br>    # Move model to the specified device (CPU or GPU)<br>    device = config.device<br>    model = model.to(device)<br><br>    # Define optimizer (AdamW is a good default choice)<br>    optimizer = torch.optim.AdamW(model.parameters(), lr=config.lr, weight_decay=0.0)<br><br>    # ------------------------------------------------<br>    # 📦 Prepare data and move tensors to the device<br>    # ------------------------------------------------<br>    X = None<br>    if isinstance(data[&quot;X&quot;], torch.Tensor):<br>        X = data[&quot;X&quot;].to(device)<br>    elif isinstance(data[&quot;X&quot;], dict):<br>        # Handle case where X is a dictionary of tensors<br>        for key, value in data[&quot;X&quot;].items():<br>            if isinstance(value, torch.Tensor):<br>                data[&quot;X&quot;][key] = value.to(device)<br>        X = data[&quot;X&quot;]<br>    <br>    y = data[&quot;y&quot;].to(device)<br><br>    # Lists to store loss and accuracy values per epoch<br>    train_loss, train_acc = [], []<br><br>    # ------------------------------------------------<br>    # 🔁 Training loop<br>    # ------------------------------------------------<br>    pbar = trange(config.max_epochs, unit=&quot; epochs&quot;)<br>    for epoch in pbar:<br>        pbar.set_description(f&quot;Epoch {epoch+1}&quot;)<br><br>        # Reset gradients before each iteration<br>        optimizer.zero_grad()<br><br>        # Forward pass: compute predictions<br>        y_pred = model(X)<br><br>        # Compute the loss between prediction and target<br>        loss = criterion(y_pred, y)<br><br>        # Backpropagation: compute gradients<br>        loss.backward()<br><br>        # Update model weights<br>        optimizer.step()<br><br>        # ------------------------------------------------<br>        # 📊 Compute accuracy for this epoch<br>        # ------------------------------------------------<br>        _, predicted = torch.max(y_pred.data, 1)  # Get class with highest score<br>        total = y.size(0)<br>        correct = (predicted == y).sum().item()<br>        accuracy = 100 * correct / total<br><br>        # Store metrics<br>        train_loss.append(loss.item())<br>        train_acc.append(accuracy)<br><br>        # Display metrics in progress bar<br>        pbar.set_postfix(loss=loss.item(), accuracy=f&quot;{accuracy:.2f}%&quot;)<br><br>    # Return results for plotting or analysis<br>    return {<br>        &quot;train_loss&quot;: train_loss,<br>        &quot;train_acc&quot;: train_acc,<br>        &quot;iterations&quot;: np.arange(1, config.max_epochs + 1)<br>    }<br><br># ============================================<br># 🧪 Testing Function<br># ============================================<br>def test(model, data):<br>    &quot;&quot;&quot;<br>    Evaluate a trained model on test data.<br>    <br>    Args:<br>        model: Trained PyTorch model<br>        data:  Dictionary with &#39;X&#39; and &#39;y&#39; tensors for testing<br>    &quot;&quot;&quot;<br>    model.eval()  # Set model to evaluation mode (no dropout, etc.)<br>    model = model.cpu()<br><br>    # Move data to CPU<br>    X = None<br>    if isinstance(data[&quot;X&quot;], torch.Tensor):<br>        X = data[&quot;X&quot;].cpu()<br>    elif isinstance(data[&quot;X&quot;], dict):<br>        for key, value in data[&quot;X&quot;].items():<br>            if isinstance(value, torch.Tensor):<br>                data[&quot;X&quot;][key] = value.cpu()<br>        X = data[&quot;X&quot;]<br><br>    y = data[&quot;y&quot;].cpu()<br><br>    # Forward pass (no gradient computation needed)<br>    with torch.no_grad():<br>        yhat = model(X)<br><br>    # Compute accuracy<br>    _, predicted = torch.max(yhat.data, 1)<br>    total = y.size(0)<br>    correct = (predicted == y).sum().item()<br>    test_acc = 100 * correct / total<br><br>    print(f&quot;✅ Testing accuracy: {test_acc:.2f}%&quot;)</pre><p>Next, we define a simple configuration class to set the training parameters and then train the MLP model 🙂‍↕️using the following code block:</p><pre>class Config:<br>    pass<br><br>config = Config()<br>config.device     = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>config.max_epochs = 100<br>config.lr         = 1e-3<br><br>mlp = MLP(in_features=X.shape[1], hidden_features=32, out_features=dataset.num_classes)<br><br># Train the MLP<br>history = fit(model=mlp, data=train_data, criterion=torch.nn.CrossEntropyLoss(), config=config)</pre><figure><img alt="Showing the Test Accuracy" src="https://cdn-images-1.medium.com/max/1024/1*c1caUj4Zx3uyQW28g_0X7Q.png" /><figcaption>MLP Test Accuracy</figcaption></figure><p>Fantastic! 🥳. Our basic MLP model achieved a 73% accuracy on the test data.</p><p>Now comes the <strong>thrilling part </strong>🤓: training our custom-built GNN. The first thing we need is the <strong>adjacency matrix</strong>. In the Cora dataset, this information is stored as an <strong>edge index</strong>, which is a way to store graph edges. The <em>edge index is a 2-row matrix</em>, where<em> each column represents an edge</em>. We’ll convert this into a dense matrix using <strong>PyG</strong>. Once we have our adjacency matrix ready, we’ll be all set to start building our own GNN:</p><pre>from torch_geometric.utils import to_dense_adj<br><br># The adjacency matrix as a dense (square) matrix<br>A = to_dense_adj(cora.edge_index)[0]<br><br># Now we should add the self-loops (the Identity Matrix)<br>I = torch.eye(len(A))<br>A += I<br>print(A, A.shape)</pre><blockquote>Now, let’s define a simple, handwritten-from-scratch GNN model to perform node classification on graph data.</blockquote><pre># A simple Graph Neural Network (GNN) built from scratch for multiclass node classification<br>class GNN(torch.nn.Module):<br>    def __init__(self, in_features, hidden_features, out_features, activation=torch.nn.ReLU):<br>        super().__init__()<br>        # Linear layer to transform input node features (acts like weight matrix W in h = WAX)<br>        self.W = torch.nn.Linear(in_features, hidden_features)<br>        <br>        # Classifier layer to map hidden representations to class scores<br>        self.classifier = torch.nn.Linear(hidden_features, out_features)<br><br>        # Non-linear activation function (default: ReLU)<br>        self.activation = activation()<br><br>    def forward(self, inputs):<br>        # Unpack node features (X) and adjacency matrix (A)<br>        X, A = inputs[&quot;node_features&quot;], inputs[&quot;adjacency_matrix&quot;]<br><br>        # Message passing: aggregate neighbor features using A, then apply learnable weights<br>        h = self.W(A @ X)<br>        <br>        # Apply non-linearity<br>        h = self.activation(h)<br>        <br>        # Map to class logits<br>        h = self.classifier(h)<br>        <br>        # Compute log probabilities for classification<br>        out = F.log_softmax(h, dim=1)<br><br>        return out</pre><p>Please note, that this line of code self.W(A@X) is exactly the equation (<strong><em>h = WÃX</em></strong>) we constructed above 😎.</p><p>Let’s train our hand crafted GNN 🫡:</p><pre># Inputs to our GNN model<br>gnn_inputs = {&quot;X&quot;: {&quot;node_features&quot;:cora.x, &quot;adjacency_matrix&quot;:A}, &quot;y&quot;:cora.y}<br><br>gnn = GNN(in_features=cora.x.shape[1], hidden_features=32, out_features=7)<br><br># Train the GNN<br>history = fit(model=gnn, data=gnn_inputs, criterion=torch.nn.CrossEntropyLoss(), config=config)</pre><figure><img alt="GNN Test Accuracy" src="https://cdn-images-1.medium.com/max/1024/1*UV_feLAuoes3gXz_NC_vug.png" /><figcaption>GNN Test Accuracy</figcaption></figure><p>Congratulations! You’ve successfully implemented your very first GNN from scratch — a remarkable achievement that demonstrates both your curiosity and technical skill in understanding the foundations of graph-based deep learning. 🚀</p><p>Your journey so far has built a solid foundation for exploring more advanced architectures — and one of the most influential next steps is the <strong>Graph Convolutional Network (GCN)</strong> by <em>Thomas Kipf and Max Welling.</em></p><p>The GCN introduced a <strong>powerful yet elegant way to generalize convolutions to graphs</strong>, enabling efficient feature aggregation from neighboring nodes and achieving state-of-the-art performance on benchmark datasets like Cora. Studying and implementing GCNs will help you move from a “handcrafted” GNN to a <strong>principled, mathematically grounded model</strong> that captures the true potential of graph learning.</p><p>As you continue, remember — this is just the beginning. I hope the skills you’ve gained through reading this article open doors to exciting directions like Graph Attention Networks (GATs), Graph Transformers, and even foundation graph models! 🌟</p><p>In the 👉 <a href="https://medium.com/@waleed.physics/how-graphs-learn-from-message-passing-to-attention-1854b777288b">next article</a>, we’ll take a big step forward by implementing the <strong>GCN</strong> and <strong>compare it to our handcrafted GNN</strong> to see how theory and practice come together in real-world performance. 🔍✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27759d262b70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Local Coding Assistant: Fine-Tuning Big Models on a Budget (QLoRA Edition)]]></title>
            <link>https://medium.com/@waleed.physics/your-local-coding-assistant-fine-tuning-big-models-on-a-budget-qlora-edition-6ed91e25edd8?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ed91e25edd8</guid>
            <category><![CDATA[parameter-efficient-ft]]></category>
            <category><![CDATA[qwen3-coder]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-coding-assistant]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 11:21:23 GMT</pubDate>
            <atom:updated>2025-10-12T11:21:23.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmU2oVawfad6ZZvk_nyMMQ.jpeg" /></figure><p>In a previous article, we discussed how to train a Large Language Model (LLM) from scratch using Hugging Face on your dataset. The model trained was GPT-2 because it is relatively small and can be trained on a local machine or Google Colab. If you haven’t read that article yet, be sure to check it out! 👉 [<a href="https://medium.com/@waleed.physics/llms-101-training-an-llm-from-scratch-f4012f562d98">Previous Article</a>]</p><p>🔮 Behind the impressive capabilities of an LLM lies a two-stage development process: pretraining and fine-tuning. These phases are critical to building models that are both broadly knowledgeable and task-specific.</p><p>⚡ <strong>Pretraining </strong>is the first and most resource-intensive stage in training an LLM, which we discussed previously. It equips the model with a general understanding of language (known as language modeling) by exposing it to vast amounts of text data. The goal is to teach the model fundamental language skills — such as grammar, syntax, factual knowledge, and even reasoning abilities. Pretraining relies on self-supervised learning, where the model learns by predicting parts of its input data. This stage provides a strong linguistic foundation but does not tailor the model to specific tasks.</p><p>🎉 <strong>Fine-tuning</strong> is the second phase, where the pretrained model is adapted to excel at specific tasks or domains. This is where the model transitions from broad knowledge to practical utility. The goal is to refine the model’s abilities for applications like language translation, answering medical questions, or generating code. For example, a pretrained model might be fine-tuned on legal documents to assist with contract analysis.</p><p>🔄 How does fine-tuning work?</p><p>Fine-tuning typically involves training the model on a labeled dataset relevant to the target application. Unlike pretraining, which requires vast computational resources, fine-tuning can often be performed on more modest hardware, depending on the dataset size and model architecture. During this process, techniques such as supervised learning, reinforcement learning, and transfer learning may be used to enhance the model’s performance and align it with specific objectives.</p><p>✍️ Why is fine-tuning necessary?</p><p>For example, if you ask a <em>pretrained LLM a question</em>, do not expect it to answer it correctly — <em>it will essentially continue the question rather than providing a meaningful response</em>. This happens because it is trained to generate or predict the next word rather than to comprehend and answer queries. And here comes the fine-tuning step!</p><p>⚙️ Two Fine-Tuning Schemes:</p><p><strong>1️⃣ Full Fine-Tuning</strong>: This involves updating all the weights of the model. However, this approach can be as resource-intensive as the pretraining phase itself.</p><p><strong>2️⃣ Parameter-Efficient Fine-Tuning (PEFT)</strong>: Instead of updating the entire model, this method modifies only some of the parameters. It uses significantly fewer resources while maintaining high computational efficiency.</p><p>🚀 What’s Next?</p><p>In this article, we will discuss Parameter-Efficient Fine-Tuning, with a focus on a technique called <strong>Quantized Low-Rank Adaptation (QLoRA)</strong>. Let’s start of what is <strong>LoRA</strong>! 🔥</p><p>🔎 What is <strong>LoRA </strong>and Why is it Useful?</p><p><strong>LoRA (Low-Rank Adaptation)</strong> is a technique that helps adapt large language models to specific tasks without modifying all of their parameters. Instead of updating the entire model (which is computationally expensive), <em>LoRA introduces low rank (small) trainable matrices that are added to the layers of the model</em>.<em> These adapters capture task-specific knowledge while keeping most of the original model frozen, significantly reducing the number of parameters that need to be trained</em>.</p><blockquote>✅<strong> Reduces Memory Usage</strong>: Since LoRA updates only a small fraction of the model, it requires much less VRAM compared to full fine-tuning.</blockquote><blockquote>✅ <strong>Improves Efficiency</strong>: It enables fine-tuning on large models using consumer-grade GPUs.</blockquote><blockquote>✅<strong> Maintains Model Performance</strong>: Despite training fewer parameters, LoRA achieves comparable performance to full fine-tuning.</blockquote><blockquote>✅ <strong>Modularity</strong>: LoRA adapters can be swapped out for different tasks without retraining the entire model.</blockquote><figure><img alt="LoRA introduce two smaller matrices A and B that are trained during model fine-tuning, while the BIG model weights are frozen. Adapted from LLM fine tuning with LoRA by Kedar Naik" src="https://cdn-images-1.medium.com/max/1024/1*Y3_T1TBEL679FDXkXqe_Cw.png" /><figcaption>LoRA introduce two smaller matrices A and B that are trained during model fine-tuning, while the BIG model weights are frozen. Adapted from <a href="https://kednaik.medium.com/llm-fine-tuning-with-lora-8e06f2227183">LLM fine tuning with LoRA</a></figcaption></figure><p>LoRA enables fine-tuning of LLMs by injecting small trainable matrices into the model while keeping the original weights frozen. This dramatically reduces the number of trainable parameters while still achieving competitive performance.</p><p>🔢 What is <strong>Quantization </strong>and Why is it Important?</p><p>Now comes the <strong>Q</strong> in <strong>QLoRA</strong>. <strong>Q</strong> stands for <strong>Quantization</strong>, which is a clever <em>technique that reduces the precision of a model’s weights </em>(and sometimes activations) <em>from high precision (like 32-bit floats) to lower precision (like 8-bit or even 4-bit)</em>. Why does this matter? Because it drastically cuts down the memory footprint and speeds up computation, without a huge loss in accuracy! 🚀 For example, the GPT-2-XL model in full FP32 precision takes up ~6.4 GB of memory. After applying 4-bit quantization, it can shrink to less than 2 GB 🤯. This means you can now run GPT-2-XL on a single consumer GPU that otherwise couldn’t even load it.</p><p>And here comes the magic with QLoRA: <strong>quantization always comes first </strong>🥇. <em>We first compress and freeze the large pretrained model into low-bit form, saving VRAM and making it lightweight. Then, LoRA adapters are added on top to fine-tune task-specific knowledge</em>. If we did it the other way around (LoRA first, then quantization), the adapters themselves would get distorted and lose effectiveness. So the order is: Quantization → Adapters. Think of it like shrinking a big textbook into a pocket-sized version (quantization), and then adding colorful sticky notes for your own insights (LoRA). Together, they unlock efficient fine-tuning of massive LLMs on everyday hardware! 💡🔥.</p><p>A very intuitive in-detail <strong>explanation of Quantization</strong> is given by <strong>Maarten Grootendorst</strong>, please check his <a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-quantization">article</a>.</p><p>💥 Now Let’s put <strong>QLoRA into action</strong>!</p><p>In this article, we will <strong>fine-tune</strong> the <strong>Qwen3 </strong>model (<em>4B version</em>) using the <strong>Python code dataset</strong> 🧠💻 — specifically, <a href="https://huggingface.co/datasets/jtatman/python-code-dataset-500k">jtatman/python-code-dataset-500k</a> from 🤗datasets. <br>And as before, we’ll use the trusted 🤗Transformers library to make the process clean, modular, and elegant. ⚙️✨</p><p>The <strong>Qwen3 family</strong> (by Alibaba) represents the cutting edge of efficient, multilingual, and code-capable large language models. <br>The <strong>4B version</strong> strikes the perfect balance between <em>power and accessibility</em> — large enough to understand complex Python syntax and logic, yet small enough to run on consumer GPUs when paired with QLoRA! 💪</p><p><strong>Let’s get hands-on!</strong></p><h3>🧩 Step 1: Install the Essentials</h3><p>Make sure you have the right libraries installed. <br>We’ll use <a href="https://huggingface.co/docs/transformers/en/installation">transformers</a>, <a href="https://huggingface.co/docs/datasets/en/installation">datasets</a>, <a href="https://huggingface.co/docs/bitsandbytes/main/en/installation">bitsandbytes</a>, and <a href="https://huggingface.co/docs/peft/en/index">peft</a>, the magic ingredients for QLoRA fine-tuning. But before that, <strong>please make sure that you have </strong><a href="https://pytorch.org/"><strong>PyTorch </strong></a><strong>already installed</strong>.</p><pre><br>pip install transformers datasets bitsandbytes peft accelerate</pre><p>If you prefer using <strong>micromamba </strong>instead of pip (for faster, cleaner environment management), <br>you can create a new environment and install all dependencies in one go:</p><pre><br>micromamba create -n qlora -y<br>micromamba activate qlora</pre><pre>micromamba install -c conda-forge -c pytorch -c huggingface \<br> transformers datasets bitsandbytes peft accelerate -y</pre><h3>🧠 Step 2: Loading the Qwen3–4B Model and Tokenizer</h3><p>Let’s now load the <strong>Qwen3–4B</strong> model and its tokenizer from <a href="https://huggingface.co/Qwen/Qwen3-4B">🤗transformers</a>.</p><p>⚠️ <strong>Note:</strong> Since this is a large model (~4 billion parameters), downloading it for the first time may take several minutes depending on your internet speed and disk space. Be patient — it’s worth it! ⏳🚀</p><pre># Load pretrained Qwen3-4b and its tokenizer<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br>model_name = &quot;Qwen/Qwen3-4B&quot;<br><br># Load tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br><br># Load model<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_name,<br>    device_map=&quot;auto&quot;<br>)</pre><blockquote>The <strong>device_map=”auto”</strong> argument automatically distributes the model across available hardware (e.g., GPU if detected, otherwise CPU). This helps efficiently manage large models without manual configuration.</blockquote><p><strong>Let’s Prepare a Test Prompt!</strong></p><p>We’ll give the model a coding problem and inspect how the tokenizer processes it into numerical tensors (tokens and attention masks).</p><p>These are what the model actually “sees” under the hood 👀</p><pre># prepare the model input<br>prompt = &quot;&quot;&quot;You are given a list of integers. <br>Write a Python function that returns a new list containing only the numbers that are prime and appear more than once in the input list.<br><br>Example:<br>```python<br>nums = [2, 3, 5, 3, 7, 11, 2, 13, 13, 4]<br>```<br>Expected output:<br>```python<br>[2, 3, 13]<br>```<br>The solution should be efficient and written in clean, readable code. Include a few test cases to verify your function.<br>&quot;&quot;&quot;<br><br>messages = [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>]<br>text = tokenizer.apply_chat_template(<br>    messages,<br>    tokenize=False,<br>    add_generation_prompt=False,<br>    enable_thinking=False, # Switches between thinking and non-thinking modes. Default is True.<br>)<br>model_inputs = tokenizer([text], return_tensors=&quot;pt&quot;).to(model.device)<br># Let&#39;s check this structure<br>print(model_inputs)</pre><p>The output of this should be like this:</p><pre>{&#39;input_ids&#39;: tensor([[151644,    872,    198,   2610,    525,   2661,    264,   1140,    315,<br>          25780,     13,    715,   7985,    264,  13027,    729,    429,   4675,<br>            264,    501,   1140,   8482,   1172,    279,   5109,    429,    525,<br>          10250,    323,   4994,    803,   1091,   3055,    304,    279,   1946,<br>           1140,    382,  13314,    510,  73594,  12669,    198,  26350,    284,<br>            508,     17,     11,    220,     18,     11,    220,     20,     11,<br>            220,     18,     11,    220,     22,     11,    220,     16,     16,<br>             11,    220,     17,     11,    220,     16,     18,     11,    220,<br>             16,     18,     11,    220,     19,    921,  13874,   3989,  18896,<br>           2550,    510,  73594,  12669,    198,     58,     17,     11,    220,<br>             18,     11,    220,     16,     18,    921,  13874,   3989,    785,<br>           6291,   1265,    387,  11050,    323,   5326,    304,   4240,     11,<br>          33798,   2038,     13,  29734,    264,   2421,   1273,   5048,    311,<br>          10146,    697,    729,    624, 151645,    198]], device=&#39;cuda:0&#39;), &#39;attention_mask&#39;: tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,<br>         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,<br>         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,<br>         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,<br>         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,<br>         1, 1, 1]], device=&#39;cuda:0&#39;)}</pre><p><strong>💬 What is apply_chat_template?</strong></p><p>The Qwen3 model, like many modern LLMs, is chat-optimized, meaning it expects messages in a conversational format — a list of messages from roles such as user, assistant, and system.</p><p>The method <strong>tokenizer.apply_chat_template()</strong> automatically formats these messages into the correct prompt structure expected by the model. It handles things like inserting role tokens and separators so that the model can correctly interpret who’s speaking.</p><p><strong>A Note on the “Thinking” Mode in Qwen3 🧠</strong></p><p>According to the <a href="https://huggingface.co/Qwen/Qwen3-4B">official documentation</a>. Qwen3 introduces an optional “thinking mode”, where the model explicitly reasons step-by-step before producing its final answer.</p><p>This is designed to improve factual accuracy and reasoning ability.</p><p>When <strong>enable_thinking=False</strong>, the model responds directly (faster, concise).</p><p>When <strong>enable_thinking=True</strong>, it activates a reasoning mode — like an inner monologue — which may generate intermediate thoughts before the final output.</p><p><strong>🧮 Let’s Ask Qwen3 a Simple Python Question!</strong></p><p>Now that we’ve loaded and tokenized our input, let’s <strong>see Qwen3–4B in action</strong> by asking it to solve a Python coding problem! ⚡🐍</p><p>We’ll use the <strong>generate()</strong> method from the Hugging Face Transformers library to let the model produce text (in this case, Python code).</p><p>To make the output smooth and interactive, we’ll use a <strong>TextStreamer</strong>, which displays tokens as they are generated — giving you real-time feedback! ⏳✨</p><p>&gt; ⚠️ <strong>Please Note</strong> that generating with a 4B model requires a GPU with at least ~8–12 GB VRAM (e.g., RTX 3060 or higher).</p><p>The first generation might take a few seconds as weights are moved to memory.</p><pre># Optimized text generation<br>from transformers import TextStreamer<br>import torch<br><br># Load model once (if not already loaded)<br>if &#39;model&#39; not in globals():<br>    model = AutoModelForCausalLM.from_pretrained(model_name, device_map=&quot;auto&quot;)<br><br># Stream tokens for real-time feedback<br>streamer = TextStreamer(tokenizer, skip_special_tokens=True)<br><br># Generate with optimized parameters<br>inputs = tokenizer(text, return_tensors=&quot;pt&quot;).to(model.device)<br><br>with torch.no_grad():<br>    outputs = model.generate(<br>        **inputs,<br>        max_new_tokens=256,  # Use max_new_tokens instead of max_length<br>        # Note: max_length = prompt length + max_new_tokens. <br>        # If both `max_length` and `max_new_tokens` are set, `max_new_tokens` takes precedence in most pipelines.        <br>        temperature=0.3,    # Sampling temperature (higher = more creative)<br>        do_sample=True,     # Enable sampling (introduces randomness)<br>        use_cache=True,      # Enable KV cache<br>        pad_token_id=tokenizer.eos_token_id,<br>        streamer=streamer,   # Stream tokens, which means that we can see the generated text in real-time<br>        num_beams=1,         # Single beam for speed, which means that we are not using beam search<br>    )<br><br># The code below uses IPython&#39;s display and Markdown to render the generated text output as formatted Markdown in the notebook.<br># This makes the output more readable and visually appealing, especially for code or structured text.<br>from IPython.display import display, Markdown<br>display(Markdown(tokenizer.decode(outputs[0], skip_special_tokens=True)))</pre><p>I omit the output of previous cell for brevity. When you run the previous code cell, you will see that the model understood the problem description, correctly parsed the example, and produced:</p><ul><li>A helper function <strong>is_prime()</strong> to check primality.</li><li>A main function that filters numbers based on frequency and primality.</li><li><em>Clean</em>, <em>readable </em>code with <em>docstrings </em>and even an example test case.</li></ul><p>This shows that <em>even without fine-tuning</em>, the <strong>pretrained Qwen3–4B</strong> model:</p><ul><li>Handles structured reasoning over instructions,</li><li>Maintains logical consistency,</li><li>And follows Python best practices like clean code and modular design.</li></ul><p>⚠️ You might have noticed that the model <strong>didn’t finish its full answer</strong>, it stopped partway through the function or after the code block. That’s totally normal 🧠, that because we <strong>explicitly</strong> the <strong>max_new_tokens = 256</strong>, which limits how many new tokens the model can generate.</p><h3>🧠 Step3: Now Let’s Load and Explore Our Dataset!</h3><p>Before we can fine-tune the model, we need data — and not just any data, but a <strong>high-quality Python code dataset</strong> that will teach our model to write, understand, and reason about code effectively.</p><p>For this tutorial, we’ll use <a href="https://huggingface.co/datasets/jtatman/python-code-dataset-500k"><strong>jtatman/python-code-dataset-500k</strong></a>, a massive collection of <strong>500K Python code snippets</strong> paired with natural language instructions.</p><p>This dataset is perfect for fine-tuning a language model like <strong>Qwen3–4B</strong>, since it combines <em>programming logic</em> with <em>textual reasoning</em>.</p><p>Let’s load it using the 🤗 datasets library:</p><pre>from datasets import load_dataset<br># Load the python code dataset<br>dataset = load_dataset(&quot;jtatman/python-code-dataset-500k&quot;, split=&quot;train&quot;)</pre><p>Once loaded, let’s inspect its structure:</p><p>You should see details like:</p><ul><li>The total number of examples.</li><li>The available fields (e.g., instruction, system, output).</li><li>The data format (usually a list of Python dictionaries).</li></ul><p>Each example is a mini chat between a user and a coding assistant:</p><ul><li>system: background context or system prompt.</li><li>instruction: what the user asked for.</li><li>output: the assistant’s answer (usually a Python solution).</li></ul><pre># Let&#39;s inspect the dataset<br>print(dataset)</pre><p>You can also visualize it nicely in your notebook:</p><pre>from IPython.display import display, Markdown<br># Let&#39;s print the first example<br>print(&quot;Instruction:&quot;)<br>display(Markdown(dataset[0][&quot;instruction&quot;]))<br>print(&quot;System:&quot;)    <br>display(Markdown(dataset[0][&quot;system&quot;]))<br>print(&quot;Output:&quot;)<br>display(Markdown(dataset[0][&quot;output&quot;]))</pre><p><strong>🗨️ Visualizing the Chat Template</strong></p><p>Now that we’ve peeked at a raw example, let’s understand how Qwen3 interpret it internally. Each sample is turned into a structured conversation using the <strong>apply_chat_template() </strong>method, which formats the messages in the same style used by real chat models (with roles like system, user, and assistant)</p><pre># The following code selects the first example from the training split of the loaded dataset,<br># and constructs a list of messages in the format expected by chat-based language models.<br># Each message is a dictionary with a &quot;role&quot; (such as &quot;system&quot;, &quot;user&quot;, or &quot;assistant&quot;) and its corresponding &quot;content&quot;.<br># The &quot;system&quot; message provides context or instructions for the assistant, the &quot;user&quot; message contains the user&#39;s prompt,<br># and the &quot;assistant&quot; message contains the expected response.<br># The code then uses the tokenizer&#39;s `apply_chat_template` method to convert this list of messages into a single formatted string,<br># which is rendered as Markdown in the notebook for better readability.<br># This approach is useful for visualizing how the chat template structures the conversation and for preparing data for model training or inference.<br><br>example = dataset[0]<br>messages = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: example[&quot;system&quot;]},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: example[&quot;instruction&quot;]},<br>    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: example[&quot;output&quot;]},<br>]<br><br>display(Markdown(tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)))</pre><h3>Step 4: 🚀 Finally We’re Ready for Fine-Tuning!</h3><p>🎉 So far We’ve loaded our dataset, explored its structure, and even formatted it to match Qwen3’s chat-based input style.</p><p>Now it’s time for the <em>fun part </em><strong>preparing the model for fine-tuning!</strong> 🧠💪</p><p>But before we start updating any weights, we need to make sure our model is <strong>efficiently quantized</strong>, remember, we’re using <strong>QLoRA</strong>, which combines <strong>Quantization + Low-Rank Adaptation</strong> to make fine-tuning large models like <strong>Qwen3–4B</strong> possible even on a single consumer GPU. ⚡</p><p><strong>💡 Step 1: Quantize the Model (The “Q” in QLoRA)</strong></p><blockquote>Quantization reduces the model’s precision from 16-bit or 32-bit floats down to <strong>4-bit</strong> — massively shrinking memory usage while keeping performance almost the same.</blockquote><blockquote>This lets us load Qwen3–4B (a multi-billion-parameter model!) right on your GPU without hitting that dreaded <strong><em>Out of Memory</em></strong> error <em>😅</em>.</blockquote><blockquote>Let’s do it 👇</blockquote><pre>from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig<br><br>model_name = &quot;Qwen/Qwen3-4B&quot;<br><br># Load tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br><br># This configuration is used to quantize the model to 4-bit precision.<br># The Q in QLoRA, where Q stands for Quantization.<br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,                 # This means that the model will be loaded in 4-bit precision.<br>    bnb_4bit_quant_type=&quot;nf4&quot;,         # This is the type of quantization to use, which means that the model will be quantized using the NF4 algorithm.<br>    bnb_4bit_compute_dtype=&quot;bfloat16&quot;, # The quantized adapter weights will be stored in bfloat16 precision.<br>    bnb_4bit_use_double_quant=True,    # Apply double quantization to the quantized adapter weights.<br>)<br><br># Load the model to train on the GPU<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_name,                     # Our Qwen3-4B model<br>    quantization_config=bnb_config, # The quantization configuration we defined earlier<br>    device_map=&quot;auto&quot;,              # The device to train on, which is the GPU in this case.<br>)<br><br># The following two lines modify the model&#39;s configuration:<br># Setting `use_cache` to False disables the use of past key values during training,<br># which is necessary for some training setups (like using gradient checkpointing) to save memory.<br># Setting `pretraining_tp` to 1 ensures that the model uses a single tensor parallelism group,<br># which is important for compatibility and efficiency when training on a single GPU or with certain quantization settings.<br>model.config.use_cache = False<br>model.config.pretraining_tp = 1</pre><p><strong>🧠 What’s Happening Here?</strong></p><p><a href="https://huggingface.co/docs/bitsandbytes/main/en/index"><strong>BitsAndBytesConfig</strong></a> tells the model to load in 4-bit precision using <a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes"><strong>NF4 quantization</strong></a>, one of the most accurate low-bit representations available.</p><ul><li><strong>bfloat16 </strong>compute <strong>dtype </strong>ensures that while storage is compact, computation stays stable — the best of both worlds!</li><li><strong>use_cache=False </strong>is a small but crucial tweak that prevents memory conflicts during training when gradients are backpropagated.</li><li><strong>pretraining_tp=1 </strong>guarantees smooth training on a single GPU or limited compute setups.</li></ul><p><strong>🎯 In short</strong>: We’ve just transformed <em>a massive model</em> into a finetuning-friendly version <em>that fits comfortably</em> in memory without losing its brilliance!</p><p>Our <strong>Qwen3–4B </strong>is now <em>lightweight</em>, efficient, and ready to learn from our Python code dataset. 🧑‍💻💬</p><p>Next up, we’ll attach the LoRA adapters, the “LORA” part of QLoRA — so we can train efficiently without touching the full model weights.</p><p>So far, we’ve handled the “Q” in QLoRA. Now it’s time for the really cool part: setting up the Low-Rank Adaptation or “LoRA”. This is where we tell our model how to learn without having to update all 4 billion of its parameters! Instead of changing the original model, we’re going to cleverly inject tiny, trainable “adapter” layers into it. Think of it like giving our giant, wise model a small, fresh notebook to jot down new information about our Python code dataset. 📝</p><p><strong>💡 Step 2: Configure the LoRA Layers!</strong></p><blockquote>This is where we define the blueprint for our LoRA adapters. We’re using the <a href="https://huggingface.co/docs/peft/en/index"><strong>peft library</strong></a> from 🤗, which makes this super easy. Let’s look at the code!</blockquote><pre>from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model<br># Prepare LoRA Configuration<br>peft_config = LoraConfig(<br>    lora_alpha=32, # LoRA Scaling<br>    lora_dropout=0.1, # Dropout for LoRA Layers<br>    r=64, # Rank<br>    bias=&quot;none&quot;,<br>    task_type=&quot;CAUSAL_LM&quot;,<br>    target_modules= # Layers to target<br>    [&quot;k_proj&quot;, &quot;gate_proj&quot;, &quot;v_proj&quot;, &quot;up_proj&quot;, &quot;q_proj&quot;, &quot;o_proj&quot;,<br>    &quot;down_proj&quot;]<br>)</pre><p>Whoa, that’s a few parameters! Don’t worry, they’re not as scary as they look. Let’s break them down:</p><ul><li><strong>r=64</strong>: This is the rank, or the “size” of our new adapter layers. It controls how many new parameters we’re adding. A higher r means more expressive power for the adapter, but also more memory. 64 is a great starting point! 💪</li><li><strong>lora_alpha=32</strong>: Think of this as a scaling factor for our new LoRA weights. It controls how much importance we give to the new notebook compared to the model’s original knowledge. A common rule of thumb is to set alpha to half of the r value.</li><li><strong>lora_dropout=0.1</strong>: This is a standard technique to prevent our model from overfitting (aka just memorizing the training data). During training, it will randomly “turn off” 10% of the LoRA neurons, forcing the model to learn more robustly. 🧠</li><li><strong>target_modules</strong>: This is the most important part! 🎯 We’re telling the model exactly which of its original layers we want to attach our adapters to. The names like <strong>q_proj </strong>and <strong>v_proj </strong>refer to key components of the model’s attention mechanism. By targeting all of these, we’re giving our adapters the best possible chance to influence the model’s output.</li></ul><blockquote>P.S. This little code snippet is a super handy trick to see all the possible layers you can target!</blockquote><pre># Temporarily print modules<br>for name, module in model.named_modules():<br>    print(name)</pre><ul><li><strong>task_type=”CAUSAL_LM”</strong>: We’re just telling it our goal: Causal Language Modeling. In simple terms, we want the model to get really good at predicting the next word in a sequence. Perfect for a chat or code-generation model!</li></ul><p><strong>🔧 Step 3: Plug in the Adapters!</strong></p><blockquote>Now that we have our configuration, we just need to apply it to our quantized model. It’s just two lines of code, but this is where the magic happens! ✨</blockquote><pre># Prepare model for training<br>model = prepare_model_for_kbit_training(model)<br>model = get_peft_model(model, peft_config)</pre><p>And… that’s it! The <strong>get_peft_model </strong>function takes our base model and our peft_config and seamlessly “plugs in” our tiny, trainable LoRA adapters.</p><p>Our model is now officially ready for training! I<em>t’s still the powerful 4-billion-parameter Qwen3 model</em>, but we only have <em>to train a tiny fraction</em> of weights, all while fitting it on a single GPU. How cool is that?! 😎</p><p>The stage is set! 🎭 Now, we need to write the script for our model’s training performance. This means setting up the training arguments, which are basically the “rules of the road” for the fine-tuning process. Think of this as setting up your workout plan at the gym. How many reps? How much weight? How many sets? Let’s define our model’s training routine! 🏋️‍♂️</p><h3>📜 Step 4: Define the Training Arguments</h3><p>We use the handy <strong>TrainingArguments </strong>class from the 🤗 transformers library to bundle all our hyperparameters together. It looks like a lot, but each setting plays a crucial role in making this process smooth and memory-efficient.</p><pre>from transformers import TrainingArguments<br>output_dir = &quot;./results&quot;<br># Training arguments<br>training_arguments = TrainingArguments(<br>    output_dir=output_dir, # The directory where the model checkpoints and logs will be saved.<br>    per_device_train_batch_size=2, # The batch size for training.<br>    gradient_accumulation_steps=4, # The number of steps to accumulate gradients over.<br>    optim=&quot;paged_adamw_32bit&quot;, # The optimizer to use.<br>    learning_rate=2e-4, # The learning rate for the optimizer.<br>    lr_scheduler_type=&quot;cosine&quot;, # The learning rate scheduler to use.<br>    num_train_epochs=1, # The number of training epochs.<br>    logging_steps=10, # The number of steps to log the training progress.<br>    fp16=True, # Whether to use 16-bit floating point precision.<br>    gradient_checkpointing=True # Whether to use gradient checkpointing.<br>)</pre><h3>🍽️ Step 5: Prepare the Data for the Model!</h3><p>Our dataset, has columns <strong>instruction</strong>, <strong>system </strong>and <strong>output</strong>. We need to structure this into a proper chat format before fine-tuning.</p><p><strong>Part 1: Formatting the Prompt</strong></p><blockquote>First, we’ll create a function to arrange each row of our dataset into a sequence of messages (System, User, Assistant). Again, we’ll use <strong>apply_chat_template </strong>that does all the hard work of adding the special tokens and formatting for us! 🪄</blockquote><blockquote>With this function, we’re telling the model: “Here’s the context (system), here’s the user’s request (instruction), and here’s the perfect response you should learn (output).” We then <strong>.map() </strong>this function across our entire dataset. Easy peasy!</blockquote><p><strong>Part 2: Tokenization (The Final Translation)</strong></p><blockquote>Now that our data is beautifully formatted as text, we need to convert it into numbers, or tokens, which is the only thing a model can actually read. We’ll also handle a few housekeeping items here.</blockquote><pre># Let&#39;s create a function to format the prompt for the dataset<br>def format_prompt(example):<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: example[&quot;system&quot;]},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: example[&quot;instruction&quot;]},<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: example[&quot;output&quot;]},<br>    ]<br>    prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)<br>    return {&quot;text&quot;: prompt}<br><br># Format the dataset<br>dataset = dataset.map(format_prompt)<br><br># Tokenize the dataset<br>def tokenize_function(examples):<br>    # Tokenize the text<br>    tokenized = tokenizer(<br>        examples[&quot;text&quot;], # The text to tokenize.<br>        truncation=True, # Whether to truncate the text to a maximum length.<br>        padding=True, # Whether to pad the text to a maximum length.<br>        max_length=512, # The maximum length of the text.<br>        return_tensors=None  # Don&#39;t return tensors, let the trainer handle it<br>    )<br>    # Add labels for causal language modeling (same as input_ids)<br>    tokenized[&quot;labels&quot;] = tokenized[&quot;input_ids&quot;].copy()<br>    return tokenized<br><br># Apply tokenization<br>tokenized_dataset = dataset.map(tokenize_function, batched=True)</pre><p>Let’s zoom in on what’s happening here:</p><ul><li><strong>tokenizer(…)</strong>: This is the main workhorse. It takes our text and chops it up into tokens. We set a max_length of 512 to ensure all our sequences are the same size, truncating or padding them as needed.</li><li><strong>tokenized[“labels”] = tokenized[“input_ids”].copy()</strong>: This is the secret sauce for training! 🧙‍♂️ For Causal Language Modeling, the model learns by trying to predict the next token in the sequence. By setting the labels (what it needs to predict) to be the same as the input_ids (what it’s given), we’re teaching it exactly that. It will read the sequence of tokens and learn to predict the very next one at every single step.</li></ul><p>Finally, we .map() this tokenization function across the entire dataset, using batched=True to process many rows at once for a massive speed boost! ⚡</p><p>And with that… our data is prepped, our model is configured, and our training plan is set. The kitchen is clean and the ingredients are ready. It’s time to start cooking! 🔥</p><p>The moment of truth has arrived! 🎉. All the pieces are on the board. All that’s left to do is to bring them all together and start the fine-tuning process.</p><p>This is the part that feels like magic. We’ve done a lot of setup, but the actual training is kicked off with just a few lines of code, thanks to the powerful SFTTrainer from the trl (Transformer Reinforcement Learning) library.</p><h3>🚀 Step 6: Launch the Training!</h3><p>The <a href="https://huggingface.co/docs/trl/en/sft_trainer"><strong>SFTTrainer </strong></a>is like the head coach of our operation. It takes our model, our dataset, and our training rules and manages the entire fine-tuning process from start to finish.</p><p>We simply pass all the components we’ve built into the <strong>SFTTrainer</strong>:</p><p>It’s that clean! We’re handing our coach:</p><ul><li><strong>model</strong>: Our <em>quantized Qwen3 model</em>, now equipped with <em>tiny LoRA adapters</em>.</li><li><strong>train_dataset</strong>: Our Python code dataset, all formatted and tokenized.</li><li><strong>args</strong>: The detailed training plan we created.</li><li><strong>peft_config</strong>: The blueprint for our LoRA adapters, so the trainer knows which parts of the model to train.</li></ul><p>That’s it! 🤯. When you run this cell, you’ll see your GPU spring to life. A <em>progress bar will appear</em>, and you’ll see the training loss start to go down — a <em>beautiful sign that your model is learning</em>!</p><pre>from trl import SFTTrainer<br># Set supervised fine-tuning parameters<br>trainer = SFTTrainer(<br>    model=model, # Our Qwen3-4B model with LoRA adapters.<br>    train_dataset=tokenized_dataset, # Our formatted and tokenized Python code dataset.<br>    args=training_arguments, # The detailed training plan we created.<br>    # Leave this out for regular SFT<br>    peft_config=peft_config, # The blueprint for our LoRA adapters, so the trainer knows which parts of the model to train.<br>)</pre><p>And train it 🏃‍➡️</p><pre>trainer.train()</pre><p>Hopefully you will see a training progress bar like mines 😉</p><figure><img alt="Qwen3–4B training progress bar" src="https://cdn-images-1.medium.com/max/1024/1*zU0ejyaYb-caIJZBItWI_A.png" /><figcaption>Finetuning Qwen3–4B locally</figcaption></figure><p>Amazing 🫣 , you’ve <strong>fine-tuned your Qwen3–4B with QLoRA</strong>! Now we’ll save the adapter, load the base model, merge the LoRA adapters back into the base weights, and run a test generation on a real example from the Python dataset. This is the moment you see your model <em>behave like your custom coding assistant</em> — exciting! 😄🔥</p><h3>🧩 Step 7: Inference Time: Merge LoRA into weights</h3><p>Now we load the original base model, load the LoRA adapter, merge them into a single set of weights, and prepare for efficient inference.</p><blockquote>👉 Why merge?</blockquote><blockquote>Merging produces a single standard model (no PEFT wrapper), which is simpler and faster for pure inference and easier to save/export for production.</blockquote><p>Finally 👨‍🦳, let’s pick an example from the Python dataset, format it with <strong>apply_chat_template</strong>, <strong>tokenize</strong>, and <strong>generate</strong>. Once again, we use <strong>max_new_tokens </strong>to control how much the model generates.</p><pre>from IPython.display import display, Markdown<br>import torch<br>from transformers import AutoTokenizer, AutoModelForCausalLM<br>from peft import PeftModel<br><br># === Paths ===<br>base_id = &quot;Qwen/Qwen3-4B&quot;<br>lora_dir = &quot;./qwen3-4b-qlora&quot;   # fine-tuned adapter directory<br><br># === Load tokenizer ===<br>tokenizer = AutoTokenizer.from_pretrained(base_id, use_fast=True, trust_remote_code=True)<br><br># === Load and merge LoRA ===<br>base = AutoModelForCausalLM.from_pretrained(<br>    base_id,<br>    device_map=&quot;auto&quot;,<br>    dtype=torch.bfloat16,            # or torch.float16<br>    attn_implementation=&quot;flash_attention_2&quot;, # Use the flash attention implementation for better performance.<br>    trust_remote_code=True,<br>)<br># After training our QLoRA model, we should combine it with the<br># original weights of the model. This is done using the `merge_and_unload` method.<br># This method merges the LoRA weights with the original weights of the model,<br># and then unloads the LoRA weights from the model.<br># This is done because the LoRA weights are not needed after training, and<br># we want to keep the original weights of the model.<br>model = PeftModel.from_pretrained(base, lora_dir).merge_and_unload()<br>model.eval()<br># Set the precision to high for better performance. <br># This is used to ensure that the model is using the highest precision for the calculations.<br>torch.set_float32_matmul_precision(&quot;high&quot;)<br><br># === Generate text ===<br>from datasets import load_dataset<br># Load the python code dataset<br>dataset = load_dataset(&quot;jtatman/python-code-dataset-500k&quot;, split=&quot;train&quot;).select(range(1000))<br>example = dataset[19]<br>messages = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: example[&quot;system&quot;]},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: example[&quot;instruction&quot;]},<br>    #{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: example[&quot;output&quot;]},<br>]<br>prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)<br><br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(model.device)<br><br>with torch.inference_mode():<br>    output_ids = model.generate(<br>        **inputs,<br>        max_new_tokens=1000,                # use max_new_tokens, not max_length<br>        do_sample=False,                    # greedy decode = faster<br>        use_cache=True,                     # KV cache speeds up generation<br>        eos_token_id=tokenizer.eos_token_id,<br>        pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id,<br>    )<br><br># === Decode and display nicely ===<br>text = tokenizer.decode(output_ids[0], skip_special_tokens=True)<br>display(Markdown(f&quot;**🧠 Model output:**\n\n{text}&quot;))</pre><p><strong>💬 Wrapping up — You Did It! 🎉</strong></p><p>I hope you liked this article! 🙌</p><p>We’ve fine-tuned <strong>Qwen3–4B</strong> using <strong>QLoRA</strong>, explored how <strong>parameter-efficient fine-tuning (PEFT) </strong>works, and saw how <strong>quantization</strong> makes it possible to train big models on smaller GPUs. 🧠⚡</p><p>Now, you have your very own <strong>coding assistant</strong>, compact, smart, and customized for your tasks. 💻✨</p><p>It’ll be really fun to compare its performance with proprietary models like <strong>ChatGPT</strong>, <strong>Claude</strong>, or <strong>Gemini</strong>, and see how close your open-source model can get. 🚀</p><p>If you enjoyed this tutorial and found it useful, I’d be thrilled if you <strong>leave a comment</strong> or <strong>clap</strong> 👏 that keeps me motivated to write more hands-on AI content like this! ❤️.</p><p>Stay tuned for the next post, we’ll explore <strong>evaluating and benchmarking </strong>your fine-tuned model, and maybe even deploy it as a local code assistant! ⚙️💬</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ed91e25edd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs 101: Training an LLM from Scratch]]></title>
            <link>https://medium.com/@waleed.physics/llms-101-training-an-llm-from-scratch-f4012f562d98?source=rss-8d4542253634------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4012f562d98</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt-2]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Waleed Esmail]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 12:02:55 GMT</pubDate>
            <atom:updated>2025-10-20T10:35:32.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGYfbnIf4i31Ipd7ttn1Fg.png" /></figure><p>Large Language Models (LLMs) are everywhere nowadays. They can perform a wide range of tasks, such as answering questions on various topics, summarizing long articles, and, more interestingly, reasoning and generating project ideas. In this article, I will guide you through training a simple LLM — specifically, the GPT-2 model.</p><p>Today, most LLMs on the market are based on the transformer architecture, first introduced in the seminal paper <em>“Attention Is All You Need.”</em> Although I won’t dive into the detailed workings of transformers — since there are many excellent tutorials covering the nitty-gritty aspects — I will show you how to select a transformer-based model off the shelf and train it on your own dataset.</p><p>For this tutorial, I will use Hugging Face, a central hub for the machine learning and natural language processing (NLP) community. Hugging Face provides essential tools, models, datasets, and libraries that simplify and accelerate the development of AI applications, particularly those involving transformers and LLMs.</p><p>The goal of this article is to keep things simple and concise. So, let’s jump right in!</p><h3><strong>🛠️ Step 0: Installing the Required Packages</strong></h3><p>Before we dive into training our LLM, let’s set up our environment by installing the necessary packages. You have a couple of options for installation, depending on your preferred workflow.</p><h4>💡 Which Package Manager Should You Use?</h4><p>You can choose between two popular tools for managing your Python environment and packages:</p><ul><li>🐍 <strong>micromamba</strong>: A lightweight, fast, and minimal package and environment manager for Python. It’s an excellent alternative to Conda and ideal for managing isolated environments.</li><li>🚀 <strong>pip</strong>: The official package manager for Python, suitable for quick installations and virtual environments.</li></ul><h4>📦 Required Packages:</h4><p>We’ll need the following libraries:</p><p>✅ <strong>NumPy</strong> — <a href="https://numpy.org/install/">https://numpy.org/install/</a><br>✅ <strong>pandas</strong> — <a href="https://pandas.pydata.org/docs/getting_started/install.html">https://pandas.pydata.org/docs/getting_started/install.html</a><br>✅ <strong>matplotlib</strong> — <a href="https://matplotlib.org/stable/install/index.html">https://matplotlib.org/stable/install/index.html</a><br>✅ <strong>Hugging Face Transformers</strong> — <a href="https://huggingface.co/docs/transformers/en/installation">https://huggingface.co/docs/transformers/en/installation</a></p><h3>📊 Step 1: Obtaining the Dataset</h3><p>The choice of the dataset is entirely up to you! With over <strong>300,000 datasets</strong> available on <a href="https://huggingface.co/datasets">Hugging Face Datasets</a>, you can find one that suits your interests and goals. Whether you’re interested in literature, science, or social trends, Hugging Face has you covered!</p><p>Since my background is in physics, I’ll use a physics-related dataset available on Hugging Face. Specifically, I’ve chosen:</p><p>📚 <a href="https://huggingface.co/datasets/enesxgrahovac/the-feynman-lectures-on-physics"><strong>The Feynman Lectures on Physics</strong></a> by @enesxgrahovac</p><p>This dataset contains excerpts from one of the most iconic physics textbook ever written.</p><p>To get the dataset, go to the <a href="https://huggingface.co/datasets/enesxgrahovac/the-feynman-lectures-on-physics">Feynman Lectures on Physics dataset page</a>. On the dataset page, click the <strong>“Use this dataset”</strong> button and choose the <strong>pandas</strong> option. Then copy the link and use <strong>pandas </strong>to load the dataset:</p><pre>import pandas as pd<br>df = pd.read_parquet(&quot;hf://datasets/enesxgrahovac/the-feynman-lectures-on-physics/data/train-00000-of-00001-d61a336a5c880eb1.parquet&quot;)</pre><p>The dataset contains <strong>7 columns</strong>, capturing excerpts from the renowned physics textbook 📚 <em>Feynman Lectures on Physics</em> (though it doesn’t include the entire book).</p><p>Among these columns, the most valuable for our LLM training is:</p><ul><li>📝 <strong>section_text</strong>: This column contains segments of text from the lectures, which we will use as training data for our language model.</li></ul><p>To count the total number of words in the <strong>section_text </strong>column, we can use the following code:</p><pre># Count total words in the &#39;section_text&#39; column<br>total_words = df[&quot;section_text&quot;].apply(lambda x: len(str(x).split())).sum()<br># Print the result<br>print(f&quot;Text size: {total_words} words&quot;)</pre><h3>📖 Step 2: Tokenization</h3><p>This dataset contains more than <strong>724,000 words</strong>, which is a good amount of text to train our “little” LLM! 🚀 Now, it’s time for <strong>tokenization</strong>, a crucial step in transforming raw text into a format that the model can understand.</p><p>Tokenization is simply the process of <strong>converting text into numbers</strong>, breaking down sentences into smaller units (tokens) that the model can process.</p><h4>🤖 Choosing the Right Tokenizer</h4><p>Since we’re using <strong>GPT-2</strong>, we’ll use the <strong>GPT2Tokenizer</strong> from Hugging Face’s transformers library. Hugging Face provides a convenient interface to load either:</p><ol><li>✅ <strong>A pre-trained tokenizer</strong> — Already trained on massive datasets and optimized for GPT-2.</li><li>✅ <strong>An untrained tokenizer</strong> — Can be trained from scratch if you want a completely custom tokenization strategy.</li></ol><p>For simplicity, we will start with the <strong>pre-trained tokenizer</strong>.</p><p>🚀 <strong>Loading the GPT-2 Tokenizer</strong></p><pre>from transformers import GPT2Tokenizer<br><br># Load the GPT-2 tokenizer<br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;openai-community/gpt2&quot;)<br># Print tokenizer details<br>print(tokenizer)</pre><p>The tokenizer outputs key details about its configuration:</p><ul><li>🧩 <strong>Vocabulary Size:</strong> 50,257 tokens (unique token IDs)</li><li>🧠 <strong>Maximum Context Length:</strong> 1,024 tokens. This is the maximum input size for GPT-2.</li><li>🏷️ <strong>Special Tokens:</strong></li><li><strong>&lt;|endoftext|&gt;</strong> – Used as:</li><li><strong>bos_token </strong>(Beginning of Sequence)</li><li><strong>eos_token </strong>(End of Sequence)</li><li><strong>unk_token </strong>(Unknown Token)</li><li>📌 All special tokens are set to the same identifier: &#39;<strong>&lt;|endoftext|&gt;</strong>&#39;.</li></ul><p>Let’s see how the tokenizer processes our dataset by tokenizing the first row of <strong>section_text</strong>:</p><pre># Tokenize the first section without truncation<br>tokenized_output = tokenizer(df[&quot;section_text&quot;].iloc[0])<br>print(tokenized_output)</pre><p>The tokenizer returns a <strong>dictionary</strong> containing:</p><ul><li>📊 <strong>input_ids</strong>: A list of token IDs representing the text.</li><li>💡 <strong>attention_mask</strong>: Can you guess what is this ?</li></ul><p>Did you notice something? 🧐</p><p>The <strong>text length exceeds the tokenizer’s context window</strong> of <strong>1,024 tokens</strong>, which means the model cannot process the entire text at once. This could cause:</p><ul><li>❌ <strong>Indexing errors (out-of-bounds errors):</strong> When the model tries to access tokens beyond the maximum input length.</li></ul><p>To address this, we can instruct the tokenizer to automatically truncate any input that exceeds the context size using the <strong>truncation=True</strong> argument:</p><pre># Tokenize with truncation enabled<br>tokenized_truncated = tokenizer(df[&quot;section_text&quot;].iloc[0], truncation=True)<br><br># Print the truncated tokenized output<br>print(tokenized_truncated)</pre><p>📊 The histogram below displays the distribution of section lengths based on word count and the red 🚨 vertical line marks the <strong>GPT-2 context limit (1,024 tokens)</strong>. You’ll likely notice a <strong>significant portion of the text exceeds the context window</strong>, meaning some sections are too long for the model to handle in a single pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSCrRxFromnyu8JRxYymrw.png" /></figure><p>Since many sections exceed the model’s input limit, we will split longer texts into smaller chunks before training. For example, we can split the text by periods (&quot;.&quot;) or newline characters (&quot;\n&quot;) to create manageable chunks. This is how it is done:</p><pre># Splitting thelong section by sentences based on &quot;.&quot;<br>df[&quot;section_text_split&quot;] = df[&quot;section_text&quot;].str.split(&quot;.&quot;)<br>df_exploded = df.explode(&quot;section_text_split&quot;)</pre><h3>🚀 Step 3: Initializing the GPT-2 Model for Training</h3><p>We are now ready to train our Large Language Model (LLM)! 🎉 As mentioned earlier, we will use the <strong>GPT-2 model</strong>, but I won’t dive into the model’s internals here, as there are many excellent resources that explain its architecture in detail. If you’d like to understand the theory and inner workings of GPT-2, I highly recommend this excellent tutorial:</p><p><em>👉 📖 </em><a href="https://medium.com/@vipul.koti333/from-theory-to-code-step-by-step-implementation-and-code-breakdown-of-gpt-2-model-7bde8d5cecda"><em>From Theory to Code: Step-by-Step Implementation and Code Breakdown of GPT-2 model</em></a><em> by Vipul Koti</em></p><h4>🧠 Want to Train a Different LLM?</h4><p>Hugging Face offers a vast collection of LLM models. Feel free to explore and experiment! 🚀</p><p>👉 🔗 <strong>Browse available models:</strong> <a href="https://huggingface.co/models">Hugging Face Models</a></p><p>We will use the <strong>GPT2LMHeadModel</strong>, which is the <strong>GPT-2 model with a language modeling head</strong>. The <strong>LM </strong>(Language Modeling) head is a linear layer that outputs a tensor of the same shape as the tokenized input, allowing the model to predict the next token in a sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCbnljYyeYZgHIRdEF5Vuw.png" /><figcaption>GPT-2 Model with the LM head. Taken from: <a href="https://medium.com/@vipul.koti333/from-theory-to-code-step-by-step-implementation-and-code-breakdown-of-gpt-2-model-7bde8d5cecda">From Theory to Code: Step-by-Step Implementation and Code Breakdown of GPT-2 model.</a></figcaption></figure><p>Let’s start by importing the necessary modules from Hugging Face’s <strong>transformers </strong>library:</p><pre># Importing Hugging Face Transformers modules<br>from transformers import GPT2Config, GPT2LMHeadModel, TrainingArguments, Trainer</pre><p>Next, we will create a <strong>GPT2LMHeadModel</strong> from scratch using the GPT2Config class and move it to the <strong>GPU</strong> if available:</p><pre># Initialize GPT-2 model from scratch<br>model = GPT2LMHeadModel(GPT2Config())<br><br># Move the model to GPU if available<br>device = &quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>model = model.to(device)<br><br>print(f&quot;Model loaded on: {device}&quot;)</pre><p>✅ Here, <strong>GPT2Config()</strong> – Initializes the model with default GPT-2 configurations (12 layers, 768 hidden dimensions, 12 attention heads). You can simply <strong>print(GPT2Config()) </strong>to investigate the contents.</p><h4>⚠️ Note on Using a Pre-Trained Model:</h4><p>If you want to fine-tune a <strong>pre-trained GPT-2</strong> instead of training from scratch, simply use:</p><pre>from transformers import GPT2LMHeadModel<br><br># Load a pre-trained GPT-2 model from Hugging Face<br>model = GPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;)<br># Move model to GPU if available<br>model = model.to(device)</pre><h3>🚀 <strong>Step 4: Training Setup — Defining Arguments, Tokenizing the Dataset, and Preparing for Training</strong></h3><p>First, we define the <strong>hyperparameters</strong> for the training process using <strong>TrainingArguments </strong>from Hugging Face.</p><pre>from transformers import TrainingArguments<br><br># Define training arguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;./gpt2_pretrained&quot;,  # Directory to save model checkpoints<br>    overwrite_output_dir=True,       # Overwrite old checkpoints<br>    per_device_train_batch_size=8,   # Number of samples per batch per GPU<br>    num_train_epochs=5,              # Number of times the model will see the full dataset<br>    logging_dir=&quot;./logs&quot;,            # Directory for logs<br>    save_strategy=&quot;epoch&quot;,           # Save model after each epoch<br>    report_to=&quot;none&quot;,                # Disable logging to Weights &amp; Biases<br>    fp16=True,                       # Enable mixed-precision training (faster on modern GPUs)<br>)</pre><h4>📝 Explanation of Training Arguments:</h4><ul><li>📁 <strong>output_dir=&quot;./gpt2_pretrained&quot;</strong> – The directory where trained model checkpoints will be saved.</li><li>📝 <strong>overwrite_output_dir=True</strong> – If enabled, overwrites previous checkpoints (useful for experiments).</li><li>🚀 <strong>per_device_train_batch_size=8</strong> – Number of training samples processed per GPU. (Adjust based on your VRAM)</li><li>🔁 <strong>num_train_epochs=5</strong> – Number of passes through the full dataset.</li><li>📊 <strong>logging_dir=&quot;./logs&quot;</strong> – Saves logs for tracking training progress.</li><li>💾 <strong>save_strategy=&quot;epoch&quot;</strong> – Saves model checkpoints at the end of every epoch.</li><li>🛑 <strong>report_to=&quot;none&quot;</strong> – Prevents logging to third-party services like Weights &amp; Biases.</li><li>⚡ <strong>fp16=True</strong> – Enables <strong>mixed-precision training</strong>, which speeds up training and reduces memory usage on GPUs that support it (e.g., NVIDIA 4090).</li></ul><p>Now, let’s convert our <strong>DataFrame</strong> into a Hugging Face<strong> </strong><strong>Dataset</strong>, tokenize it, and prepare it for training.</p><pre>from transformers import AutoTokenizer<br>from datasets import Dataset<br><br># Convert DataFrame to Hugging Face Dataset. I use only 1000 rows for simplicity<br>dataset = Dataset.from_pandas(df_exploded[[&#39;section_text_split&#39;]].iloc[0:1000])<br># Rename the column to &#39;text&#39; to match model expectations<br>dataset = dataset.rename_column(&quot;section_text_split&quot;, &quot;text&quot;)</pre><p>By default, GPT-2 does not use a<strong> </strong><strong>pad_token</strong>, as it was originally trained without one. However, during training and batching, <strong>padding is essential</strong> to ensure that all input sequences are of the same length. Without proper padding, we cannot efficiently stack multiple samples into a batch. o resolve this, we assign a custom padding token. Since GPT-2 already uses &quot;<strong>&lt;|endoftext|&gt;</strong>&quot; (<strong>eos_token</strong>) to mark the end of a sequence, we can set it as the padding token to avoid expanding the model&#39;s vocabulary.</p><pre>from transformers import GPT2Tokenizer<br><br># Define the tokenizer<br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;openai-community/gpt2&quot;)<br># Set EOS token as PAD token to avoid vocabulary resizing<br>new_pad_token = &quot;&lt;|pad|&gt;&quot;<br>tokenizer.add_special_tokens({&#39;pad_token&#39;: new_pad_token})<br># Ensure the tokenizer uses EOS token as PAD token<br>tokenizer.pad_token = tokenizer.eos_token<br><br># Tokenization function<br>def tokenize_function(examples):<br>    return tokenizer(<br>        examples[&quot;text&quot;],                # Tokenize the &#39;text&#39; column<br>        padding=&quot;max_length&quot;,            # Pad all sequences to the same length<br>        truncation=True,                 # Truncate texts longer than max length<br>        max_length=1024,                 # Set maximum input length<br>        return_tensors=&quot;pt&quot;              # Return PyTorch tensors<br>    )</pre><p>In <em>causal language modeling</em> (like GPT-2), <strong>input_ids </strong>are used as <strong>labels</strong> because the model predicts the next token from previous tokens.</p><pre># Function to copy input IDs as labels (for causal language modeling)<br>def add_labels(example):<br>    example[&quot;labels&quot;] = example[&quot;input_ids&quot;].copy()  # Labels match input tokens<br>    return example</pre><p>Now, let’s apply our functions to the dataset:</p><pre># Tokenize the dataset<br>tokenized_datasets = dataset.map(<br>    tokenize_function,<br>    batched=True,                 # Tokenizes multiple examples at once (faster)<br>    remove_columns=[&quot;text&quot;],      # Removes original text column (not needed)<br>)<br><br># Add labels to the tokenized dataset<br>tokenized_datasets = tokenized_datasets.map(<br>    add_labels,<br>    batched=True                  # Adds labels for multiple examples<br>)</pre><h3>🚀 <strong>Step 5: Training the GPT-2 Model with Hugging Face </strong><strong>Trainer</strong></h3><p>To train our GPT-2 model, we will use the <strong>Hugging Face </strong><strong>Trainer API</strong>, which is:</p><ul><li>✅ <strong>Simple and Convenient:</strong> Abstracts away boilerplate code.</li><li>⚙️ <strong>Optimized for Transformer Models:</strong> Built specifically for models like GPT-2.</li><li>🚀 <strong>Efficient:</strong> Supports distributed training, mixed-precision, and logging out-of-the-box.</li></ul><p>However, you can always choose to <strong>train using plain PyTorch</strong> if you prefer full control over the training loop.</p><pre>from transformers import Trainer<br><br># Initialize the Trainer<br>trainer = Trainer(<br>    model=model,                      # Our GPT-2 model<br>    args=training_args,              # Training arguments (defined previously)<br>    train_dataset=tokenized_datasets,  # Tokenized dataset for training<br>    processing_class=tokenizer        # Tokenizer for data preprocessing<br>)</pre><p>With everything set up, we can now <strong>start training</strong> the model:</p><pre># Start the training process<br>trainer.train()</pre><p>Once training is complete, let’s <strong>save the trained model and tokenizer</strong> for future use:</p><pre># Save the trained model<br>trainer.save_model(&quot;./gpt2_pretrained&quot;)<br># Save the tokenizer with its special tokens<br>tokenizer.save_pretrained(&quot;./gpt2_pretrained&quot;)</pre><h3>🚀 <strong>Step 6: Testing the Trained GPT-2 Model — Generating Text</strong></h3><p>Now that we’ve finished training the GPT-2 model, it’s time to <strong>test it by generating text</strong>! We will use Hugging Face’s<strong> </strong><strong>pipeline </strong>API, which provides an easy interface for model inference.</p><pre>from transformers import pipeline<br><br># Load fine-tuned model and tokenizer from saved directory<br>generator = pipeline(<br>    &quot;text-generation&quot;,                # Task: Generate text<br>    model=&quot;./gpt2_pretrained&quot;,        # Path to fine-tuned model<br>    tokenizer=&quot;./gpt2_pretrained&quot;     # Path to saved tokenizer<br>)</pre><p>📦 Here, <strong>pipeline</strong> is a high-level API from Hugging Face that simplifies model inference. And, finally, generating some text:</p><pre># Generate text with the fine-tuned model<br>output = generator(<br>    &quot;The equations of motion are&quot;,  # Prompt to start generating text<br>    max_length=50,                 # Maximum length of the generated sequence<br>    do_sample=True,                # Enable sampling (introduces randomness)<br>    temperature=1.0                # Sampling temperature (higher = more creative)<br>)</pre><p>📝 <strong>Explanation of Generation Parameters:</strong></p><ul><li>📝 <strong>Prompt:</strong> &quot;The equations of motion are&quot; – The starting point (also known as a <strong>seed</strong> or <strong>prompt</strong>).</li><li>📏 <strong>max_length=50</strong> – Limits the output to 50 tokens (including the prompt).</li><li>🎲 <strong>do_sample=True</strong> – Enables <strong>sampling</strong>, making the output <strong>less deterministic</strong> (randomness).</li><li>🌡️ <strong>temperature=1.0</strong> – Controls the randomness:</li><li><strong>Higher (&gt;1)</strong> = More creative and diverse output.</li><li><strong>Lower (&lt;1)</strong> = More focused and conservative output.</li></ul><h3>🎉 Conclusion: Building and Testing a Custom GPT-2 Model</h3><p>Congratulations on training your own GPT-2 model! You’ve come a long way — from preparing your dataset and fine-tuning your model to generating meaningful text. 💪📊</p><p>But the journey doesn’t stop here! 🚀 Now, it’s time to <strong>showcase your model’s creativity and knowledge</strong>.</p><blockquote>Don’t miss <a href="https://medium.com/p/6ed91e25edd8">part 2 of this article</a>, it dives into how to fine-tune a pretrained LLM.</blockquote><p>I’d love to see what your model has learned! Feel free to:<br>📝 <strong>Drop your generated outputs</strong> in the comments — whether they are insightful, technical, or even hilariously off-topic! 🤖🎉<br>💡 <strong>Tell us your favorite prompt</strong> and the most surprising result your model produced! 💬✨<br>🚀 <strong>Share your experiments:</strong> Did you tweak the temperature or try different prompts? Let us know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4012f562d98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>