<?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 Vicki Y Mu on Medium]]></title>
        <description><![CDATA[Stories by Vicki Y Mu on Medium]]></description>
        <link>https://medium.com/@vicki.y.mu?source=rss-19e8d15be833------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8SlGq2TrFOcLjrXf8GC2KA.jpeg</url>
            <title>Stories by Vicki Y Mu on Medium</title>
            <link>https://medium.com/@vicki.y.mu?source=rss-19e8d15be833------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:45:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vicki.y.mu/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[From Noise to Structure: Building a Flow Matching Model from Scratch]]></title>
            <link>https://aiadvances.org/from-noise-to-structure-building-a-flow-matching-model-from-scratch-f1ca12b31602?source=rss-19e8d15be833------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1ca12b31602</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Vicki Y Mu]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 13:31:57 GMT</pubDate>
            <atom:updated>2025-07-05T13:31:57.847Z</atom:updated>
            <content:encoded><![CDATA[<h4>An MIT sophomore’s walkthrough of Flow Matching, training dynamics, and 2D generative toy datasets.</h4><h3>1. Introduction</h3><p>Diffusion models are everywhere. They generate stunning images, videos, and even music. But they’re <em>extremely slow.</em> Hundreds of denoising steps just to create one image.</p><p>I’m an undergrad student at MIT interested in deep learning and generative models. Recently, I came across another approach to the generative modeling problem: F<strong>low Matching</strong>. This method learns to generate new data by solving an ODE, not by reversing the diffusion process.</p><p>So I built it from scratch — the math, model, training loop, velocity fields. <em>This post is a distilled walkthrough of that process: a hands-on exploration of the theory, code, and visual intuition behind Flow Matching.</em></p><p>I’ll walk through the math behind Flow Matching, how I implemented the training and sampling pipelines, and what makes this approach so fundamentally different from diffusion. By the end of this post, you’ll have a working Flow Matching model in PyTorch and a much clearer picture of how generative models can expand beyond noise schedules and scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDug21EDQ7sLcR6aIcrd-Q.png" /><figcaption><strong>Figure 1. </strong>Image generation using Flow Matching. The model learns a smooth trajectory from Gaussian noise to complex data distributions. Source: Flow Matching for Generative Modeling (<a href="https://arxiv.org/pdf/2210.02747">arXiv:2210.02747</a>)</figcaption></figure><h3>2. Why Not Just Use Diffusion?</h3><p>Let’s start with the popular generative models you’ve probably heard of: <strong>diffusion models, </strong>especially <strong>DDPMs </strong>(Denoising Diffusion Probabilistic Models). These models generate images by gradually reversing a process that turns clean images into noise.</p><p>You train the model by adding noise to data in small steps until it becomes pure Gaussian noice — literally watching the image get blurred into static. The model then learns how to <strong>denoise</strong> that static step-by-step, which is what we call learning the <strong>score function, </strong>which is just the gradient of the data distribution. All of this is just a fancy way of saying it learns to predict the direction that points back to the original clean image.</p><p>But here’s the problem: when you want to <em>generate</em> a new image, you have to start with noise and go through that same process in reverse, step-by-step denoising each one. The score function has to be plugged into a <strong>stochastic differential equation (SDE), </strong>a mathematical description of noise should be reversed over time. So even with a fully trained model, sampling requires you to follow that SDE by taking many, many denoising steps guided by the score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D25Kfic3X0jcE6QljFF9Fw.png" /><figcaption><strong>Equation 1.</strong> The stochastic reverse process used for sampling in score-based diffusion models like DDPM.</figcaption></figure><p>Some approaches try to speed this process up. For example, <strong>DDIM </strong>(Denoising Diffusion Implicit Models) is a non-stochastic version of diffusion that gets rid of the randomness in the differential equation. These <strong>diffusion ODEs<em> </em></strong>use deterministic solvers to go backwards faster. But even these models still need dozens of steps to denoise and dozens of forward passes through the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fi5faRGQs-CszhD01-wmWQ.png" /><figcaption><strong>Equation 2.</strong> The deterministic reverse process that generates the same marginals as the SDE, but requires no randomness.</figcaption></figure><p>What if we skipped <em>all</em> of that? What if instead of learning how to <em>denoise</em>, you directly learned a <strong>velocity field</strong> that tells us how to push particles from noise to data in one smooth path?</p><p>Thats exactly what <strong>Flow Matching</strong> does — instead of training a model to <em>reverse noise</em>, you train it to move samples along a continuous path towards the data distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LpbWnSA4ubg8kaEDJjP1w.png" /></figure><h3>3. How Flow Matching Works</h3><h4>3.1 The Problem</h4><p>In order to generate images, we need to model how samples move from an easy initial distribution (like Gaussian noise) to a complex data distribution (like natural images). Unlike denoising based methods that learn to reverse the noise gradually, <strong>Flow Matching</strong> models how a sample <em>flows</em> between the two distributions.</p><p>intuition callout</p><p>The Flow Matching model learns a path — a smooth, time-dependent transform that connects noise to data. This interpretation lets us treat image generation as a transport problem. How can we move a point from where we started to where we want it to go?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPoLnuBKa3lF-MnmjVWHbQ.png" /><figcaption><strong>Figure 2. </strong>Flow matching learns a smooth path from noise to data by modeling a time-dependent velocity field. Source: adapted from <a href="https://github.com/facebookresearch/flow_matching/tree/main?tab=readme-ov-file">Facebook AI Research Github</a></figcaption></figure><h4>3.2 The Flow Matching Objective</h4><p>Let’s start with two distributions:</p><ul><li><em>p₀​:</em> a simple prior (e.g. standard Gaussian noise)</li><li><em>p₁: </em>the complex end distribution (e.g. natural images)</li></ul><p>We sample a point from each distribution, and connect the them with a path. The most common way is to just connect them with a straight line: <em>x(t) </em>= (<em>1 </em>− <em>t)x₀ + tx₁.</em></p><p>This is called a linear interpolation between <em>x₀</em> and <em>x₁.</em> (Note that it’s also possible to use other interpolations (e.g. spherical), but linear is the easiest and works well in practice — so we’ll stick with this one.)</p><p>The goal is to learn a time-dependent velocity field <strong>f</strong>(<em>x, t</em>) that describes the velocity at each point along a trajectory. Since we know the ground truth velocity already from the path, the neural network is trying to approximate <em>x’(t) = x₁ </em>− <em>x₀.</em></p><p>So, we just train the model to match the predicted velocity to the true one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvVWgHo8ILz-aNd6r5J2pQ.png" /><figcaption><strong>Equation 3.</strong> The supervised loss for flow matching, comparing predicted and true velocity along the path from noise to data.</figcaption></figure><h4>3.3 Sampling with Flow Matching</h4><p>Recall that the network learned a velocity field <strong>f</strong>(<em>x, t</em>) that moves a point from noise to data. During the training loop, we had access to both <em>x₀</em> and <em>x₁, </em>but during generation, we only have <em>x₀. </em>The goal at sampling time is to take a point of noise and push it towards the <em>p₁ </em>distribution, and reach something that looks like a natural image.</p><p>We start with a sample <em>x₀ ~ p₀​ </em>(e.g. standard Gaussian noise). From there we define a time grid from <em>t = </em>0 → 1, split evenly into a series of steps. At each of these time steps, we solve an ODE forward in time to update the sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67xKLDY5Fh2EPME1y_tBwA.png" /><figcaption><strong>Equation 4. </strong>The update rule used for sampling with flow matching.</figcaption></figure><p>The vector field <strong>f</strong>(<em>x, t</em>) is used at each step with the current <em>x</em> and <em>t</em> to get an estimate for <em>x’(t). </em>Once you reach <em>t = </em>1, you’ll end up with a sample that hopefully looks like a natural image. This process is similar to following a flow field — we’re “pushing” the sample along the learned velocity path towards the data.</p><h3>4. Implementation Walkthrough</h3><h4>4.0 Setup</h4><p>Before we dive into Flow Matching, we need a pair of distributions to map between. You can start with any two noise and data distributions you want, but for our purposes, we’ll choose two easy distributions.</p><ul><li><em>p₀​: </em>2D standard Gaussian</li></ul><pre>def sample_source(batch_size):<br>    # Sample from a 2D standard Gaussian (mean=0, std=1)<br>    return torch.randn(batch_size, 2)</pre><ul><li><em>p₁: </em>2D<em> c</em>heckerboard dataset — a toy dataset made of Gaussian clusters in a checkerboard grid</li></ul><pre>def sample_target(batch_size):<br>    # Sample the x-coordinate uniformly in the range [-2, 2)<br>    x1 = torch.rand(batch_size) * 4 - 2<br><br>    # Sample the y-coordinate:<br>    # Step 1: draw from uniform [0, 1)<br>    # Step 2: subtract either 0 or 2, randomly (via torch.randint)<br>    # Result: values centered roughly around -2 or -1<br>    x2_ = torch.rand(batch_size) - torch.randint(high=2, size=(batch_size, )) * 2<br><br>    # Add a vertical shift depending on whether the x1 bin is even or odd<br>    # This creates the alternating row offset of the checkerboard<br>    x2 = x2_ + (torch.floor(x1) % 2)<br><br>    # Stack x1 and x2 into (batch_size, 2) vectors, and scale the whole grid<br>    data = 1.0 * torch.cat([x1[:, None], x2[:, None]], dim=1) / 0.45<br><br>    return torch.tensor(data, dtype=torch.float32)</pre><p><strong>4.1 Model Definition</strong></p><p>We build a small neural network to learn the time-dependent velocity field <strong>f</strong>(<em>x, t</em>). Since our dataset isn’t too complicated, we create a small MLP that takes (<em>x, t</em>) as an input and outputs a vector with the same dimensions as <em>x.</em></p><p>But because <em>t</em> is just a scalar, we first map it to a higher dimension using two fully connected layers. Then we concatenate this time-embedding with <em>x, </em>and pass the result through a few fully connected layers with SiLU activations.</p><pre>class FlowModel(nn.Module):  # Neural network to learn the time-dependent velocity field f(x, t)<br>  def __init__(self, input_dim=2, time_embed_dim=64):<br>    super().__init__()<br>    <br>    # Small MLP to embed the time scalar t into a higher-dimensional space<br>    self.time_embed = nn.Sequential(<br>        nn.Linear(1, time_embed_dim),<br>        nn.SiLU(),                     # Activation function: Sigmoid Linear Unit<br>        nn.Linear(time_embed_dim, time_embed_dim)<br>    )<br><br>    # Main network to predict velocity, given (x, embedded t)<br>    self.net = nn.Sequential(<br>        nn.Linear(input_dim + time_embed_dim, 128),  # Input: concatenated x and t embedding<br>        nn.SiLU(),<br>        nn.Linear(128, 128),<br>        nn.SiLU(),<br>        nn.Linear(128, 128),<br>        nn.SiLU(),<br>        nn.Linear(128, 128),<br>        nn.SiLU(),<br>        nn.Linear(128, 128),<br>        nn.SiLU(),<br>        nn.Linear(128, 128),<br>        nn.SiLU(),<br>        nn.Linear(128, input_dim)  # Output: predicted velocity (same dimension as x)<br>    )<br><br>  def forward(self, x, t):<br>    # Embed time t (shape: [batch_size, 1]) into a higher-dimensional vector<br>    t_embed = self.time_embed(t)<br><br>    # Concatenate position x and time embedding along the last dimension<br>    xt = torch.cat([x, t_embed], dim=-1)<br><br>    # Pass through the network to predict the velocity at (x, t)<br>    return self.net(xt)</pre><p>As explained in section 3.2, the goal is to train the model to match the true velocity along the paths. Since the ground truth velocity is just <em>x₁ </em>− <em>x₀, </em>we can enforce this constraint by minimizing squared error between the true and predicted velocity.</p><pre>def flow_matching_loss(model, x0, x1, t):<br>  # Compute the interpolated point along the trajectory for each t<br>  xt = (1 - t) * x0 + t * x1<br><br>  # Compute the ground truth velocity vector (constant across trajectory)<br>  v_target = x1 - x0<br><br>  # Predict the velocity at point (x(t), t) using the model<br>  v_pred = model(xt, t)<br><br>  # Compute squared error between predicted and true velocity at each sample<br>  # Then average over the entire batch<br>  return ((v_pred - v_target) ** 2).mean()</pre><h4>4.2 Training</h4><p>To train the model, we sample noise and data points from <em>p₀ </em>and <em>p₁</em>. At each step, we pick a random time in the range [0, 1], compute the Flow Matching loss, and update the parameters using Adam. Over time, the model learns a velocity field connecting the two distributions.</p><pre>num_steps = 10000<br>batch_size = 512<br>losses = []<br><br>model = FlowModel().to(device)<br>optimizer = torch.optim.Adam(model.parameters(), lr=5e-4)<br><br>for step in tqdm(range(num_steps)):<br>  x0 = sample_source(batch_size).to(device)<br>  x1 = sample_target(batch_size).to(device)<br>  t = torch.rand(batch_size, 1).to(device)  # Random interpolation time ∈ [0, 1]<br><br>  loss = flow_matching_loss(model, x0, x1, t)<br><br>  optimizer.zero_grad()<br>  loss.backward()<br>  optimizer.step()<br><br>  losses.append(loss.item())<br><br>  if step % 100 == 0:<br>    print(f&quot;Step {step} | Loss: {loss.item():.4f}&quot;)</pre><h4>4.3 Sampling</h4><p>To generate new samples from our trained model, we start from a point in the noise distribution and push it forwards using the learned velocity field <strong>f</strong>(<em>x, t</em>). This is done by solving the ODE from <em>t = </em>0 to <em>t = </em>1, like we described in section 3.3. We use scipy.integrate.solve_ivp, a standard ODE solver, to numerically integrate the learned velocity field and produce an output that lies in the target distribution.</p><pre>def sample_flow(model, x0, t_span=(0, 1)):<br>    &quot;&quot;&quot;<br>    Evolve x0 through the learned flow to produce a sample from p1.<br>    &quot;&quot;&quot;<br>    def ode_func(t, x):<br>        # Convert input x and time t into proper torch tensors<br>        x_tensor = torch.tensor(x, dtype=torch.float32).unsqueeze(0).to(device)<br>        t_tensor = torch.tensor([[t]], dtype=torch.float32).to(device)<br><br>        # Predict velocity without tracking gradients<br>        with torch.no_grad():<br>            v = model(x_tensor, t_tensor)<br><br>        # Return velocity as NumPy array (shape: [2])<br>        return v.squeeze(0).cpu().numpy()<br><br>    # Solve ODE from t=0 to t=1 using the learned velocity field<br>    sol = solve_ivp(ode_func, t_span, x0.cpu().numpy(), t_eval=[t_span[1]])<br><br>    # Return the final state at t=1 (i.e. predicted x1)<br>    return sol.y[:, -1]</pre><h3>5. Results &amp; Visualizations</h3><h4>5.1 Source and Target Distributions</h4><p>We defined a simple synthetic toy problem for Flow Matching, where <em>p₀​ </em>is a 2D Gaussian and <em>p₁</em> is a checkerboard pattern. This setup allows us to easily visualize the learned flow and intermediate diagnostics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MO7PKjk-nlprq6ifEwfew.png" /><figcaption><strong>Figure 3.</strong> Source samples drawn from a 2D standard Gaussian (left) and target samples drawn from the synthetic checkerboard distribution (right).</figcaption></figure><h4>5.2 Training Loss Curve</h4><p>The loss quickly drops in early iterations and then oscillates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*IgFa1CLMHYK94xum2uW2ig.png" /><figcaption><strong>Figure 4.</strong> Training loss curve over 10,000 optimization steps.</figcaption></figure><h4>5.3 Learned Velocity Field</h4><p>The vector field evolves smoothly over time. At <em>t</em> = 0, the flow is directed outwards from the center, reflecting movement towards a Gaussian distribution. At later <em>t</em>, the flow starts to exhibit a more checkerboard-like structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9O1g4CwurGkXoQ5hZBD2qQ.png" /><figcaption><strong>Figure 5. </strong>Snapshots of the learned velocity field at various times t∈{0.0,0.25,0.5,0.75,1.0}</figcaption></figure><h4>5.4 Generated vs Target Samples</h4><p>To generate new samples, we integrate the learned velocity field from <em>t</em> = 0 to <em>t = </em>1, using scipy.integrate.solve_ivp. Qualitatively, the generated samples closely match the shape and structure of the target checkerboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*gGlAcXNH-7mRCJ-Ri3Lfiw.png" /><figcaption><strong>Figure 6. </strong>True samples from the checkerboard target distribution (left), and samples generated by integrating the learned flow (right)</figcaption></figure><h3>6. Limitations and Extensions</h3><h4>6.1 Limitations</h4><p>While Flow Matching is a simple and elegant alternative to score-matching, it does face some limitations.</p><ul><li><strong>No Sampling Guarantee </strong><br>Flow Matching bypasses log-likelihood and instead fits a model to the velocity field. While this method simplifies training, it no longer guarantees that our generated samples are in the target distribution.</li><li><strong>Integration Cost at Inference</strong><br>To generate new samples with this method, it requires solving an ODE at inference time for each input sample. This can be computationally expensive compared to feedforward models or diffusion sampling with fewer steps.</li><li><strong>Requires Velocity Supervision</strong><br>Flow Matching requires access to a ground truth velocity. While this is easy with simply synthetic datasets, it becomes extremely nontrivial for real-world data.</li></ul><h4>6.2 Extensions and Improvements</h4><p>To address these limitations, researchers have developed several improvements.</p><ul><li><strong>Flow Matching with Score Models</strong><br>Some approaches have begun to combine the two models — using score-based objectives to train a Flow Matching model. This combines the best of both worlds.</li><li><strong>Neural ODE Solvers</strong><br>More cutting edge ODE solvers or even neural approximators can reduce inference time by learning efficient solutions through the flow field, which allows for faster sampling at inference time.</li></ul><h3>7. GitHub + Colab</h3><h4>View the <a href="https://github.com/vickiiimu/checkerboard-FM-tutorial.git">GitHub Repo</a></h4><p>Includes a clean folder structure with:</p><ul><li>checkerboard_flow_matching.ipynb notebook</li><li>images/ folder for visualizations</li><li>requirements.txt for easy installation</li></ul><h4>Installation</h4><pre>git clone https://github.com/vickiiimu/checkerboard-FM-tutorial.git<br>cd flow_matching<br>pip install -r requirements.txt</pre><h4>Open in <a href="https://colab.research.google.com/drive/1_-IDm8OVhZwNHZhStS7oONvTj7pyTODe?usp=sharing">Colab</a></h4><p>Readers can fork and run the notebook directly in the browser.</p><h3>7. Conclusion</h3><p>Congratulations — you’ve just built Flow Matching from scratch!</p><p>Along the way, we covered the <strong>core ideas behind Flow Matching</strong>, explored how it differed from traditional diffusion models, and reimplemented <strong>core components</strong> like toy 2D datasets, vector field estimation, and ODE integration. If you followed the walkthrough, you now have a functioning Flow Matching model you fully understand.</p><p>Whether you’re here to <em>learn the internals, prototype your own vision ideas, or just scratch the itch of curiosity</em> — this is your sandbox.</p><h3>Feedback welcome</h3><p>If you spot bugs, have suggestions, or build something cool on top of this, feel free to open an <a href="https://github.com/vickiiimu/checkerboard-FM-tutorial.git/issues">issue</a> or <a href="https://github.com/vickiiimu/checkerboard-FM-tutorial.git/pulls">pull request</a> on GitHub.</p><h3>Further reading</h3><ul><li><a href="https://arxiv.org/abs/2210.02747">Flow Matching for Generative Modeling (Lipman et al., 2023)</a></li><li><a href="https://arxiv.org/abs/2006.11239">Denoising Diffusion Probabilistic Models (Ho et al., 2020)</a></li><li><a href="https://arxiv.org/abs/2011.13456">Score-Based Generative Modeling through SDEs (Song et al., 2020)</a></li></ul><p>Thanks for reading! 👋<br>See you in the next post.</p><h3>About Me</h3><p>I’m a sophomore at MIT studying physics and artificial intelligence. This post is part of a series —<em> </em><a href="https://pub.towardsai.net/from-pixels-to-predictions-building-a-transformer-for-images-fea5a4f64816"><em>Recreated from Scratch</em></a> — where I reimplement foundational AI papers to learn them inside and out. I’ll be posting new walkthroughs every few of weeks, diving into a different model or paper each time.</p><p>If you enjoyed this walkthrough, feel free to <a href="https://github.com/vickiiimu">follow me on GitHub</a>, <a href="https://medium.com/@vicki.y.mu">Medium</a>, <a href="https://twitter.com/vickiiimu">Twitter</a>, or even <a href="/service/mailto:vymu@mit.edu">reach out</a>. I love chatting about research, open-source projects, and all things deep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1ca12b31602" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/from-noise-to-structure-building-a-flow-matching-model-from-scratch-f1ca12b31602">From Noise to Structure: Building a Flow Matching Model from Scratch</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginning on the Leaderboard: My First Kaggle Challenge in 7 Days]]></title>
            <link>https://medium.com/@vicki.y.mu/beginning-on-the-leaderboard-my-first-kaggle-challenge-in-7-days-0749ceebc825?source=rss-19e8d15be833------2</link>
            <guid isPermaLink="false">https://medium.com/p/0749ceebc825</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vicki Y Mu]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 15:10:30 GMT</pubDate>
            <atom:updated>2025-07-01T00:42:56.162Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I participated in the Image Matching Challenge with no prior Kaggle experience, just one week, and a lot of stubborn debugging.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*2moKfEQTx7mpEdhEgdNmiQ.png" /><figcaption>Source: Kaggle IMC 2025</figcaption></figure><h3>1. Opening: Why I Joined So Late</h3><p>I first saw the Image Matching Challenge pop up on Kaggle sometime in early May. I bookmarked it out of curiosity — the problem sounded cool, and I’d been meaning to get into competitions for a while — but between MIT finals, end-of-semester deadlines, and packing up to move out, it got buried under everything else.</p><p>It wasn’t until a week before the deadline that I remembered it again. I was finally free, finally bored, and finally curious enough to open the starter notebook. One baseline submission later, I was hooked.</p><p>This was my first-ever Kaggle competition. I had no leaderboard expectations — just a vague goal to build something functional, learn as much as possible in seven days, and see how far I could push it.</p><blockquote><em>“It was a bit of a reckless decision. I had a week, a little familiarity with vision models, and zero competition experience. I wanted to see how far I could get.”</em></blockquote><h3>2. Understanding the Challenge</h3><p>The Image Matching Challenge (IMC) is an annual computer vision competition hosted by CVPR and Kaggle. At its core, the goal sounds simple: match local features between image pairs to estimate the relative pose of the cameras that captured them. In other words, given two images of the same scene — possibly from wildly different angles or lighting — can you determine how those cameras were positioned relative to each other?</p><p>But 2025’s edition took that basic setup and made it <em>brutal</em>.</p><p>Unlike past IMC competitions, where the organizers provided pre-segmented scenes, <strong>this year you had to segment the scenes yourself</strong>. That meant reverse-engineering the scene structure from hundreds of loosely grouped image pairs before you could even begin estimating poses. It added an extra layer of uncertainty — you weren’t just solving the matching problem, you were solving the <em>context</em> problem, too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*3uh_XWcwsjHfspExDLsbeA.png" /><figcaption>These are two completely different stairwells — but my pipeline lumped them into the same scene more than once. Turns out ‘gray steps in a hallway’ isn’t a very unique visual signature. Source: Kaggle IMC 2025</figcaption></figure><p>What really separated IMC 2025 from class projects or standard CV pipelines was the real-world messiness of it all:</p><ul><li>Images weren’t neatly aligned or staged — they were taken from inconsistent angles, sometimes under drastically different lighting conditions, or even at different times of day</li><li>Generalization mattered more than precision — your pipeline had to work across architecture, nature, objects, stairs, ET statues, and more</li><li>And finally, compute was a bottleneck: every submission was a tradeoff between quality and runtime, with timeout risks looming</li></ul><h3>3. Days 1–2: Getting the Baseline Running</h3><p>I kicked things off with a pipeline based on <strong>ALIKED + LightGlue</strong> — a lightweight but effective combo I’d seen mentioned in previous IMC discussions. ALIKED gave me reliable keypoints and descriptors, and LightGlue handled the matching with impressive robustness, especially in low-texture scenes. It was a solid starting point — but far from plug-and-play.</p><p>The real curveball in IMC 2025 was <strong>scene segmentation</strong>. Unlike in previous years, the dataset didn’t come pre-organized into scenes. That meant before I could even estimate poses, I had to figure out which image pairs belonged to the same physical environment.</p><p>To tackle that, I used <strong>DINOv2 as a global image descriptor</strong>. For each image, I extracted global embeddings using a pretrained DINOv2 backbone, then clustered the embeddings using KMeans to group images into scenes. It wasn’t perfect — and I definitely tuned it more by vibe than theory — but it was good enough to avoid total chaos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CXzH6zDSLlnw90qVmdUOA.png" /><figcaption>Clustering results on the ET dataset using DINOv2 + KMeans. Two main clusters, with 3 outliers flagged. Source: Kaggle IMC 2025</figcaption></figure><p>Still, some scenes like <strong>vineyard</strong> and <strong>stairs</strong> were incredibly brittle. These environments had so much <strong>repetition and structural symmetry</strong> that even small mistakes in clustering led to <strong>completely incorrect pose estimates</strong>. Multiple rows of grapevines or similar staircases taken at slightly different angles or lighting conditions could easily be grouped together, even when they came from different physical spaces. Those mistakes hit hard — the mAA metric punishes wrong matches aggressively, and once scene segmentation goes wrong, everything downstream follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*wiGLGdAe5HqaL6djraWLkQ.png" /><figcaption>Three different vineyard scenes — visually similar enough to confuse DINOv2 and cluster them together, despite coming from completely different locations. These kinds of mistakes wrecked downstream pose estimates. Source: Kaggle IMC 2025</figcaption></figure><p>Because I had joined the competition so late, I leaned heavily on the <strong>Kaggle discussion boards</strong> to stay afloat. Reading through others’ pain points and quick wins helped me shortcut a lot of early confusion — especially around runtime optimization and evaluating failure cases like ET, stairs, and the infamous castle towers. I also saw a few people visualizing keypoint matches and inlier ratios, which helped me trust (or distrust) my pipeline more quickly.</p><p>By the end of Day 2, I had something functional. Not amazing — but stable, reproducible, and ready to start iterating on. The real experimentation was still ahead.</p><h3>4. Days 3–4: Idea Flood (and Reality Check)</h3><p>By day three, I had a working baseline — which, naturally, meant I started throwing every half-baked idea I had at the wall to see what might stick. At one point, my notebook was a graveyard of TODOs: local SfM pipelines, GNN-based outlier rejection, even patch-wise attention reranking. Some of these I partially implemented. Others I just mocked up enough to convince myself I didn’t have the time.</p><p>But a few things <em>did</em> make it into the actual pipeline:</p><ul><li><strong>Cluster refinement via match graph connectivity</strong>: I built a scene graph where each node was an image, and edges were weighted by LightGlue match confidence and number of inliers. Then I ran connected component analysis to recover tightly linked subgraphs — effectively letting the data self-organize the scene clusters. This was especially useful in ambiguous environments like vineyards and stairs, where DINOv2 global embeddings alone tended to over-group visually similar but spatially unrelated scenes.</li><li><strong>Targeted COLMAP reruns with pre-filtered matches:</strong> I selectively reran COLMAP on scenes with low estimated mAA, injecting LightGlue matches with custom outlier filtering. This worked well for scenes with harsh lighting changes or wide baselines — particularly the ET statue and several of the indoor staircases, where vanilla matching often produced degenerate poses.</li><li><strong>Pose-aware pair filtering</strong>: For a brief window, I experimented with using pairwise match consistency — essentially a simplified geometric verification — to discard scene pairs that weren’t consistent with the rest of their cluster. It was light-touch, but reduced false positives in scenes with high symmetry.</li></ul><p>A few other ideas didn’t make the cut, but might in a future comp:</p><ul><li>Learning a <strong>per-scene descriptor weighting</strong> strategy (foreground vs. background emphasis)</li><li>Filtering match graphs using <strong>spectral clustering</strong> on pose residuals</li><li>Using <strong>CLIP</strong> embeddings as a second-pass sanity check for scene consistency</li></ul><p>Ultimately, I realized I wasn’t going to outbuild the top teams — not in a week — but I could be thoughtful about what <em>not</em> to waste time on. That became my mini-strategy: solve what’s fragile, trust what’s robust, and don’t touch anything on Friday night.</p><h3>5. Days 5–6: Patch, Tune, Pray</h3><p>By this point, it wasn’t about adding features — it was about <strong>pipeline triage</strong>.</p><p>Days 5 and 6 were a blur of last-minute patches, scene-level debugging, and running the full dataset through my pipeline <em>without it catching fire</em>. I knew I was running out of time, and the priority shifted from “can I improve this?” to “can I trust this?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2ANPEvMJKpMyIW62mn3nQ.png" /><figcaption>The real MVPs were all the print statements. Source: author</figcaption></figure><p>I focused on final structure: stitching together my best scene clustering logic (DINOv2 + match-graph analysis), a couple custom COLMAP reruns for the weird scenes (looking at you, <strong>ET</strong>), and a filtering layer for pruning obviously bad pairs. <strong>Stairs</strong> remained one of the hardest — visually repetitive, sometimes indoor, sometimes outdoor, and prone to degeneracy in pose estimation. My only move there was to hand-check a few sample scenes and hope the outlier filter was doing its job.</p><p>Meanwhile, <strong>compute became a bottleneck</strong>. I was trying to test full runs locally, monitor GPU usage on Kaggle notebooks, and avoid timeout errors — all while juggling submission caps. At one point I split inference across multiple notebooks just to stay under the limit. It felt duct-taped together, but at least it was running.</p><blockquote><em>My notebook was a Frankenstein of late-night hacks, quick sanity checks, and a few very strategic </em><em>print()s. Honestly, it had no right to work as well as it did.</em></blockquote><h3>6. Day 7: Submitting + The Final Rank</h3><p>Submission day felt like holding my breath for 12 hours straight.</p><p>I queued up my final pipeline the night before the deadline — patched, filtered, clustered, and barely tested end-to-end. It wasn’t clean, and it definitely wasn’t elegant, but it ran. And at that point, that was all I needed.</p><p>When the results came in, I landed at <strong>Rank 260 out of 943</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Po6IaRMicwRqv0ph8bYncA.png" /><figcaption>Final leaderboard rank: 260 out of 943 — not a medal, but a 501-place climb in seven days, and my first ever Kaggle comp. I’ll take it. Source: author</figcaption></figure><p>No medal, no spotlight — but for a <strong>first competition</strong> done in <strong>seven days</strong>, while figuring out scene segmentation, pose estimation, LightGlue, COLMAP, and Kaggle notebooks on the fly… I was proud of that number.</p><p>It wasn’t about beating anyone else. It was about proving to myself that I could build something from scratch, debug under pressure, and ship a real submission. And I did.</p><p>I didn’t expect a medal — but seeing my name halfway up the leaderboard felt like proof of concept: I could do this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXSkSCcNzvxCDhRQu1fY_w.png" /><figcaption>What one week of late nights, weird bugs, and unexpected breakthroughs looked like. The timeline of how I (barely) held it all together. Source: author</figcaption></figure><h3>7. What I Learned in 7 Days</h3><p>This competition condensed months of learning into a single week. I came in with some computer vision experience — but matching, clustering, and pose estimation under pressure taught me things no lecture or tutorial ever could.</p><h4>Reproducibility is non-negotiable</h4><p>When you’re iterating fast, the ability to rerun the exact same pipeline is everything. I lost hours to silent mismatches between intermediate files, cache conflicts, and half-tested logic blocks. By day 3, I was versioning configs and scene outputs like my life depended on it — because it kind of did.</p><h4>Visual matching is way harder than it looks</h4><p>On paper, it’s just keypoints and descriptors. In reality, it’s everything from occlusions to lighting variation, repeating structures, degenerate geometry, and weird edge cases that no tutorial prepares you for. Robustness mattered more than elegance.</p><h4>The leaderboard can help — or totally distract</h4><p>Seeing your name rise is addictive, but chasing short-term gains made me overfit to specific scenes more than once. Some of my lowest mAA scores came from over-optimized fixes that broke generalization. In the end, the most helpful metric was just <strong>consistency across scene types</strong>.</p><h4>Competitions make you a faster, better debugger</h4><p>I had no choice but to figure things out quickly: mismatched pose outputs, LightGlue breaking silently, scenes clustering wrong, COLMAP throwing obscure errors… All of it sharpened my instincts. I now write defensive code by default — with checks, asserts, and visualizations built-in.</p><p>More than anything, I learned that these comps are a perfect training ground for research-style thinking: you pick your assumptions, fail fast, validate hard, and trust nothing until it works on the leaderboard.</p><h3>8. What I’d Do Differently</h3><p>Looking back, there’s a lot I’m proud of — but also a lot I’d change if I had more time (or a time machine).</p><h4>Start earlier. Seriously.</h4><p>One week was barely enough to get a stable pipeline running, let alone explore the frontier of matching models. I spent more time fixing data issues than testing ideas — and missed out on the deep modeling work that could’ve made a real difference.</p><h4>Get more aggressive with bad pairs</h4><p>Some of my lowest-scoring scenes were due to noisy matches that should’ve been filtered out earlier — either by geometric inconsistency, low keypoint density, or scene confusion. A stronger outlier rejection module (maybe even learned) would’ve saved me a lot of leaderboard pain.</p><h4>Explore beyond the baseline</h4><p>I stuck with ALIKED + LightGlue for speed and familiarity, but next time I’d love to seriously try:</p><ul><li><strong>LoFTR</strong> for its dense, global attention-driven matching</li><li><strong>GNN-based match filtering</strong> to reason about match confidence beyond pairwise similarity</li><li>And maybe even <strong>pose refinement modules</strong> post-COLMAP, built to adapt to challenging camera configurations</li></ul><p>If I’d had two more weeks, I would’ve focused on generalization: building a model-aware filtering stage and validating it across clusters, rather than hand-tuning scenes one-by-one. That’s the kind of robustness that separates mid-tier submissions from gold medals.</p><h3>9. What’s Next</h3><p>I’m not entirely sure what my next competition will be — but I know this sprint wasn’t a one-off.</p><p>I’m currently deciding between a few very different challenges:</p><ul><li><strong>CMI — Detect Behavior with Sensor Data</strong>, to sharpen temporal modeling and classification robustness</li><li><strong>NeurIPS — Open Polymer Prediction</strong>, for a deep dive into scientific ML and graph-based modeling</li><li>Or <strong>DRW — Crypto Market Prediction</strong>, a fast-paced signal extraction challenge that forces you to think like a quant</li></ul><p>Whichever I choose, the goal is clear: <strong>medal in my second comp</strong>, and keep moving toward true mastery.</p><p>This sprint was a turning point. It reminded me why I do this — not just to rank, but to <strong>build</strong>, to <strong>learn fast</strong>, and to <strong>get pushed beyond the comfort zone of lectures and controlled assignments</strong>. I learned more in one week of hacking together a real pipeline than I have in some entire semesters. I learned what to prioritize, what to throw away, how to debug under pressure, and how to focus only on what matters when time is short.</p><p>Kaggle has become part of my larger AI journey — a place where I can stay sharp, stay uncomfortable, and build the kind of intuition that only comes from doing. It’s not always pretty. But it’s real.</p><h3>About Me</h3><p>I’m a sophomore at MIT studying physics and artificial intelligence. This post is part of my <em>Projects in the Wild</em> series — where I document personal experiments, Kaggle challenges, physics-ML crossovers, and anything else that pushes me outside the classroom.</p><p>My goal is to learn by building: fast, messy, sometimes late, but always real. Whether it’s reimplementing papers or racing the Kaggle deadline, I use these projects to sharpen my instincts and stay uncomfortable — the kind of learning that doesn’t come from lectures alone.</p><p>If you enjoyed this post, feel free to <a href="https://github.com/vickiiimu">follow me on GitHub</a>, <a href="https://medium.com/@vicki.y.mu">Medium</a>, <a href="https://x.com/vickiiimu">Twitter</a>, or <a href="/service/mailto: vymu@mit.edu">reach out</a>. I love talking about AI, open-source, and anything that blends math, vision, or modeling under pressure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0749ceebc825" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Pixels to Predictions: Building a Transformer for Images]]></title>
            <link>https://pub.towardsai.net/from-pixels-to-predictions-building-a-transformer-for-images-fea5a4f64816?source=rss-19e8d15be833------2</link>
            <guid isPermaLink="false">https://medium.com/p/fea5a4f64816</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vicki Y Mu]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 13:01:57 GMT</pubDate>
            <atom:updated>2025-06-24T13:01:57.850Z</atom:updated>
            <content:encoded><![CDATA[<h4>An MIT sophomore’s walkthrough of ViTs, training, and results on CIFAR-10.</h4><p>Convolutional neural networks have been the driving force behind almost every major breakthrough in computer vision — <strong>but what if they’ve been holding us back all along?</strong></p><p>In 2020, a team of researchers at Google asked the bold question: <em>Can we throw out convolutions entirely and still build world-class image models?</em> Their answer — <a href="https://arxiv.org/abs/2010.11929"><strong>the Vision Transformer (ViT)</strong></a> — sparked a new era in deep learning.</p><figure><img alt="Diagram showing the architecture of a Vision Transformer (ViT). An input image is divided into patches, linearly embedded with positional information, and passed through a stack of transformer encoder blocks. The encoder includes multi-head self-attention, normalization, and MLP layers, with output passed to a classification head." src="https://cdn-images-1.medium.com/max/1024/1*DQUENgS19YmLkUA-v9COSQ.png" /><figcaption><strong>Figure 1:</strong> Vision Transformer (ViT) architecture. Source: Dosovitskiy et al., 2020 (<a href="https://arxiv.org/abs/2010.11929">arXiv:2010.11929</a>)</figcaption></figure><p>I’m an undergraduate student at MIT with an interest in computer vision and generative models, and I recently implemented a Vision Transformer from scratch to better understand its architecture. <em>This post is a distilled guide to that process, blending theory, visuals and code.</em></p><p>We’ll walk through how ViT’s turn images into sequences, how attention works in this context, and how it compares to the CNNs you’re used to. By the end, you’ll have <strong>a working ViT in PyTorch</strong> and <strong>a much deeper understanding of how it all fits together</strong>.</p><h3>1. Background and Intuition</h3><h4><strong>1.1 From Recurrent Models to the Rise of Transformers (in NLP)</strong></h4><p>Before 2017, NLP was ruled by <strong>RNNs</strong> and <strong>LSTMs</strong>: models that powered everything from <em>machine translation</em> to <em>language modeling</em>. But despite their early success, they had fundamental limitations. Because they processed sequences one token at a time, training couldn’t be parallelized. And as sequences got longer, they struggled to retain information from earlier tokens. These bottlenecks made it difficult to scale up, especially for tasks that required a deep, global understanding of language.</p><p>In 2017, researchers at Google made a breakthrough in their paper <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em></a>. It proposed a new architecture — <strong>the Transformer</strong> — built around a simple but powerful idea: <strong>self-attention</strong>. Instead of processing tokens one at a time, self-attention allows each token to directly consider every other token in the sequence.</p><blockquote>Put simply, each word learns to ask questions (<strong>queries</strong>), decide what to listen to (<strong>keys</strong>), and gather relevant information(<strong>values</strong>).</blockquote><p>This mechanism eliminated the need for recurrence and fixed step order, sidestepping the main weaknesses of RNNs.</p><figure><img alt="Diagram comparing RNNs and Transformers. On the left, RNNs process inputs sequentially from left to right, passing hidden states forward through time steps. On the right, a Transformer encoder processes all inputs simultaneously, with each input connected to all others using weighted attention lines of varying thickness. Arrows and labels highlight the difference in processing order and parallelism." src="https://cdn-images-1.medium.com/max/1024/1*S4B_d4qFqSnYJJ1i3gxfyQ.jpeg" /><figcaption><strong>Figure 2: </strong>RNNs handle inputs sequentially, while Transformers attend to all tokens in parallel. Line thickness represents attention strength. <em>Source: author</em></figcaption></figure><p>Within just two years, <strong>Transformer architecture</strong> completely took over NLP. It proved more efficient, easier to scale, and better at modeling long-range dependencies than any of its predecessors. Transformers quickly became the backbone of major breakthrough models: <strong>BERT</strong> (for bi-directional context), <strong>GPT</strong> (for generative, causal language modeling), and <strong>T5</strong> (for sequence to sequence tasks).</p><p><strong>RNNs were replaced by attention in NLP — but what about computer vision? </strong>At the time, <strong>CNNs</strong> dominated the field, but they came with their own set of limitations. Convolutions are inherently local, making it difficult for CNNs to capture long-range dependencies. They also rely heavily on spatial prior and careful feature engineering.</p><p>So the natural next question emerged:<em> if attention could replace recurrence…could it replace convolution too?</em></p><h4><strong>1.2 Can Attention Replace Convolution? The Shift to Vision</strong></h4><p>In 2020, Dosovitskiy et al. introduced the <strong>Vision Transformer (ViT)</strong> in their paper <a href="https://arxiv.org/abs/2010.11929"><em>An Image Is Worth 16×16 Words</em></a>. They proposed a bold idea: <em>what if we treated an image like a sentence?</em></p><p>Instead of relying on convolutional filters, they divided images into patches and fed them into a standard transformer. While early ViTs needed massive datasets to compete with CNNs, <strong>the approach proved that attention-based models could work for vision </strong>— not just language.</p><p>Since its release, the Vision Transformer has sparked a wave of improvements:</p><ul><li><strong>DeiT</strong> introduced smarter training strategies to reduce ViT’s reliance on huge datasets</li><li><strong>Swin Transformer</strong> added hierarchical structure to better handle local spatial patterns</li><li><strong>DINO</strong> and <strong>DINOv2</strong> showed that ViTs could learn rich visual representations <em>without any labels at all — </em>unlocking powerful self-supervised features for downstream tasks.</li></ul><p>What began as a bold experiment has now become a core building block in modern computer vision.</p><h3>2. How Vision Transformers Work</h3><h4>2.1 Patch Embedding</h4><p>Transformers were originally designed to process sequences, like sentences made out of word tokens. But images are 2D grids of pixels, not 1D sequences. So how do we feed an image into a transformer?</p><p>The Vision Transformer solves this by dividing the image into <strong>non-overlapping</strong> <strong>square patches</strong> (e.g. 16x16 pixels). Each patch is then flattened into a 1D vector and linearly projected into a fixed-size embedding — just like token embeddings in NLP.</p><p>For example:</p><ul><li>A 224x224 image with 16x16 patches produces (224/16)² = 196 patches.</li><li>Each patch is of shape 3x16x16 (RGB).</li><li>Each flattened patch becomes a 768-dim vector (common for ViT-Base).</li></ul><p>Instead of a sentence of words, ViT sees a sequence of image patch embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSnwn8KjHySrV3HWHVcfyg.jpeg" /><figcaption><strong>Figure 3:</strong> Patch embedding. Source: Dosovitskiy et al., 2020 (<a href="https://arxiv.org/abs/2010.11929">arXiv:2010.11929</a>)</figcaption></figure><blockquote><strong><em>Analogy:</em></strong><em> Just like a tokenizer turns a sentence into a sequence of word embeddings, the ViT turns an image into a sequence of patch embeddings.</em></blockquote><h4>2.2 Class Token and Positional Embeddings</h4><p>Transformers need two extra ingredients to work properly with image sequences:</p><ol><li>a <strong>[CLS] token</strong> to aggregate global information, and</li><li><strong>positional embeddings</strong> to encode spatial structure.</li></ol><p>In ViT, a special learnable token is prepended to the input sequence. During self-attention, this token attends to every patch — and becomes the representation used for final classification.</p><p>Transformers are <strong>permutation-invariant</strong> — they don’t inherently understand order. To give the model spatial awareness, we add a unique positional embedding to each token in the sequence.</p><p>Both the [CLS] token and positional embeddings are <strong>learned parameters</strong>, updated during training.</p><h4>2.3 Multi-Head Self-Attention (MHSA)</h4><p>At the heart of the Vision Transformer is the <strong>multi-head self-attention mechanism</strong> — the part that allows the model to understand how image patches relate to each other, regardless of spatial distance.</p><p>Instead of using one attention function, MHSA splits the input into <strong>multiple “heads”</strong>. Each head learns to focus on different aspects of the input — some might focus on edges, others on texture, others on spatial layout. Their outputs are then concatenated and projected back into the original embedding space.</p><h4>How it works, step by step:</h4><ul><li>The input sequence of tokens (shape [B, N, D]) is linearly projected into: <strong>Queries</strong> Q, <strong>Keys</strong> K, and <strong>Values</strong> V.</li><li>Each attention head computes:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLfU5lr38mOfp1J5Ge-oKQ.png" /><figcaption><strong>Equation 1:</strong> Scaled Dot-Product Attention</figcaption></figure><ul><li>Multiple heads run in parallel, and their outputs are concatenated and linearly projected back.</li></ul><blockquote><strong><em>Why “multi-head”?</em></strong><em><br> Each head attends to different parts of the sequence. This allows the model to understand complex relationships in parallel — not just spatial proximity, but also semantic structure.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Dlu_463Q8XMsZWBtFZ6sA.png" /><figcaption><strong>Figure 4: </strong>The left shows how attention scores are computed using queries (Q), keys (K), and values (V). The right illustrates how multiple attention “heads” capture diverse representations in parallel. Source: Vaswani et al. (<a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a>)</figcaption></figure><h4>2.4 Transformer Encoder</h4><p>Once we have self-attention, we wrap it inside a larger unit: the <strong>Transformer block</strong>. This block is the fundamental building unit of ViTs (and NLP Transformers too). It combines:</p><ul><li><strong>LayerNorm → Multi-Head Attention → Residual Connection</strong></li><li><strong>LayerNorm → MLP (Feedforward Network) → Residual Connection</strong></li></ul><p>Each block enables the model to <strong>attend globally</strong> and <strong>transform features</strong> across layers while maintaining stability with normalization and residuals.</p><p><strong>What’s inside a ViT Transformer block:</strong></p><ol><li><strong>LayerNorm</strong> before attention (called <em>pre-norm</em>).</li><li><strong>Multi-head self-attention</strong> applied to the normalized input.</li><li>A <strong>residual connection</strong> adds the attention output back.</li><li>Another <strong>LayerNorm</strong>, followed by a small <strong>MLP</strong>.</li><li>Another <strong>residual connection</strong> adds the MLP output.</li></ol><figure><img alt="Diagram of a Vision Transformer encoder block. It shows the flow from embedded patches through LayerNorm, multi-head attention, another LayerNorm, and an MLP. Residual connections are applied after the attention and MLP steps. The entire sequence is enclosed in a “Transformer Encoder” box." src="https://cdn-images-1.medium.com/max/1024/1*ZyoyZUrv6OekphSc90ta2w.png" /><figcaption><strong>Figure 5:</strong> ViT encoder block with attention, MLP, and residuals. Source: author</figcaption></figure><p>This structure repeats across all transformer layers (e.g., 12 layers in ViT-Base).</p><h4>2.5 Classification Head</h4><p>After processing the input through multiple Transformer blocks, the model needs a way to produce a final prediction. In Vision Transformers, this is handled by the <strong>classification head</strong>.</p><p>During the embedding step, we added a special <strong>[CLS] token</strong> at the beginning of the sequence. Just like in BERT, this token is intended to <strong>aggregate information</strong> from all the image patches through self-attention. After passing through all Transformer layers, the <strong>final embedding of the [CLS] token</strong> is used as a summary representation of the entire image.</p><p>This vector is then passed through a simple <strong>linear layer</strong> to output class logits.</p><h3>3. Implementation Walkthrough</h3><p>All core modules — patch embedding, MHSA, encoder blocks — are implemented from scratch. No timm shortcuts.</p><h4>3.1 Patch Embedding</h4><p>To convert image patches into a sequence of embeddings, we use a clever trick. Instead of writing a manual for-loop to extract and flatten patches, we can use a Conv2dlayer<strong> </strong>with:</p><ul><li>kernel_size = patch_size</li><li>stride = patch_size</li></ul><p>This extracts <strong>non-overlapping patches</strong> and applies a <strong>learned linear projection</strong> — all in a single operation. It’s clean, efficient, and easy to backpropagate through.</p><pre>class PatchEmbed(nn.Module):<br>    def __init__(self, img_size = 224, patch_size = 16, in_chans = 3, embed_dim = 768):<br>        super().__init__()<br>        self.img_size = img_size<br>        self.patch_size = patch_size<br>        self.num_patches = (img_size // patch_size) ** 2<br>        <br>        self.proj = nn.Conv2d(<br>            in_chans, <br>            embed_dim, <br>            kernel_size = patch_size, <br>            stride = patch_size)<br>  <br>    def forward(self, x):<br>        # x shape: [B, 3, 224, 224]<br>        x = self.proj(x) # [B, emdbed_dim, H/patch, W/patch]<br>        x = x.flatten(2) # [B, emdbed_dim, num_patches]<br>        x = x.transpose(1, 2) # [B, num_patches, embed_dim]<br>        return x</pre><h4>3.2 Class Token and Positional Embeddings</h4><p>Here we define a ViTEmbed module that:</p><ul><li>Prepends a learnable [CLS] token to the sequence</li><li>Adds a learnable positional embedding to each token (including [CLS])</li></ul><p>This produces a sequence shaped [B, num_patches + 1, embed_dim] — ready for the transformer encoder.</p><pre>class ViTEmbed(nn.Module):<br>    def __init__(self, num_patches, embed_dim):<br>        super().__init__()<br>        <br>        # Learnable [CLS] token (1 per model)<br>        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))  # [1, 1, D]<br><br>        # Learnable positional embeddings (1 per token, including CLS)<br>        self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))  # [1, N+1, D]<br><br>    def forward(self, x):<br>        batch_size = x.shape[0]<br><br>        # Expand [CLS] token to match batch size<br>        cls_tokens = self.cls_token.expand(batch_size, -1, -1)  # [B, 1, D]<br><br>        # Prepend CLS token to patch embeddings<br>        x = torch.cat((cls_tokens, x), dim=1)  # [B, N+1, D]<br><br>        # Add positional embeddings<br>        x = x + self.pos_embed  # [B, N+1, D]<br><br>        return x</pre><h4>3.3 Multi-Head Self-Attention</h4><p>Let’s implement one of the most important parts of the Vision Transformer: <strong>multi-head self-attention</strong>.</p><p>Each input token is linearly projected into a <strong>query (Q)</strong>, <strong>key (K)</strong>, and <strong>value (V)</strong> vector. Attention is computed in parallel across multiple heads, then concatenated and projected back to the original embedding dimension.</p><pre>class MyMultiheadAttention(nn.Module):<br>    def __init__(self, embed_dim, num_heads):<br>        super().__init__()<br>        assert embed_dim % num_heads == 0, &quot;embed_dim must be divisible by num_heads&quot;<br><br>        self.embed_dim = embed_dim<br>        self.num_heads = num_heads<br>        self.head_dim = embed_dim // num_heads<br><br>        # Learnable projections for Q, K, V<br>        self.q_proj = nn.Linear(embed_dim, embed_dim)<br>        self.k_proj = nn.Linear(embed_dim, embed_dim)<br>        self.v_proj = nn.Linear(embed_dim, embed_dim)<br><br>        # Final output projection<br>        self.out_proj = nn.Linear(embed_dim, embed_dim)<br><br>    def forward(self, x):<br>        B, T, C = x.shape  # [batch, seq_len, embed_dim]<br><br>        # Project input into Q, K, V<br>        Q = self.q_proj(x)<br>        K = self.k_proj(x)<br>        V = self.v_proj(x)<br><br>        # Reshape into heads: [B, num_heads, T, head_dim]<br>        def split_heads(tensor):<br>            return tensor.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)<br><br>        Q = split_heads(Q)<br>        K = split_heads(K)<br>        V = split_heads(V)<br><br>        # Scaled dot-product attention<br>        scores = torch.matmul(Q, K.transpose(-2, -1))  # [B, heads, T, T]<br>        scores /= self.head_dim ** 0.5<br>        attn = torch.softmax(scores, dim=-1)<br><br>        # Apply attention to values<br>        out = torch.matmul(attn, V)  # [B, heads, T, head_dim]<br><br>        # Recombine heads<br>        out = out.transpose(1, 2).contiguous().view(B, T, C)<br><br>        # Final linear projection<br>        return self.out_proj(out)</pre><h4>3.4 Transformer Encoder</h4><p>We now wrap everything together in a <strong>Transformer block</strong> — a modular unit that stacks self-attention and MLP layers with residual connections. This design lets the model reason globally (through self-attention) and then transform those representations (through the MLP), all while preserving stability via skip connections.</p><p>In this implementation:</p><ul><li>We use our <strong>own </strong>MyMultiheadAttention<strong> class</strong> from earlier to demystify how attention works under the hood.</li><li>In practice, you can use PyTorch’s built-in nn.MultiheadAttention for convenience and efficiency.</li><li>We apply <strong>LayerNorm before</strong> both the attention and MLP layers (a “pre-norm” design).</li><li>The mlp_ratio controls the width of the MLP’s hidden layer (usually 3–4× wider than the embedding dimension).</li></ul><p>Let’s build the full Transformer block:</p><pre>class TransformerBlock(nn.Module):<br>    def __init__(self, embed_dim, num_heads, mlp_ratio=4.0):<br>        super().__init__()<br>        self.norm1 = nn.LayerNorm(embed_dim)<br>        self.attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)<br><br>        self.norm2 = nn.LayerNorm(embed_dim)<br>        self.mlp = nn.Sequential(<br>            nn.Linear(embed_dim, int(embed_dim * mlp_ratio)),<br>            nn.GELU(),<br>            nn.Linear(int(embed_dim * mlp_ratio), embed_dim)<br>        )<br><br>    def forward(self, x):<br>        # Self-attention with residual connection<br>        x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0]<br><br>        # MLP with residual connection<br>        x = x + self.mlp(self.norm2(x))<br>        return x</pre><h4>3.5 Putting It All Together</h4><p>Now that we’ve built all the key components of a Vision Transformer — patch embedding, positional encoding, multi-head self-attention, Transformer blocks, and the [CLS] token — it’s time to assemble everything into a full model.</p><p>In the code below:</p><ul><li>We use our PatchEmbed, ViTEmbed, and TransformerBlock classes from earlier.</li><li>The [CLS] token is passed through all transformer layers and then <strong>normalized</strong>.</li><li>We add a <strong>classification head</strong>: a single nn.Linear layer that maps the [CLS] token embedding to class logits.</li><li>This architecture mirrors the original <strong>ViT-Base</strong> (12 layers, 12 heads, 768-dim embeddings), but it’s easy to scale.</li></ul><pre>class SimpleViT(nn.Module):<br>    def __init__(<br>        self, img_size=224, patch_size=16, in_chans=3,<br>        embed_dim=768, depth=12, num_heads=12, num_classes=1000<br>    ):<br>        super().__init__()<br>        self.patch_embed = PatchEmbed(img_size, patch_size, in_chans, embed_dim)<br>        num_patches = (img_size // patch_size) ** 2<br>        self.vit_embed = ViTEmbed(num_patches, embed_dim)<br><br>        # Stack transformer blocks<br>        self.blocks = nn.Sequential(*[<br>            TransformerBlock(embed_dim, num_heads) for _ in range(depth)<br>        ])<br><br>        # Final normalization before classification<br>        self.norm = nn.LayerNorm(embed_dim)<br><br>        # Linear classification head (using the CLS token)<br>        self.head = nn.Linear(embed_dim, num_classes)<br><br>    def forward(self, x):  # [batch_size, channels, height, width]<br>        x = self.patch_embed(x)         # -&gt; [B, N, D]<br>        x = self.vit_embed(x)           # add CLS token + pos embed<br>        x = self.blocks(x)              # transformer layers<br>        x = self.norm(x)                # normalize CLS token<br>        return self.head(x[:, 0])       # classification using CLS token</pre><h3>4. Training the ViT</h3><h4>4.1 Dataset: CIFAR-10</h4><p>We trained our Vision Transformer (ViT) on <strong>CIFAR-10</strong>, a well-known benchmark dataset with 60,000 images across 10 classes (e.g., airplanes, cats, ships). Each image is only 32×32 pixels, which makes CIFAR-10:</p><ul><li><em>Lightweight</em> and quick to train on</li><li><em>Challenging enough</em> to evaluate small models</li><li><em>Easy to visualize</em>, which helps interpret what the model is learning</li></ul><h4>4.2 Model Setup: Adapting ViT for CIFAR-10</h4><p>ViTs were originally designed for large-scale datasets like ImageNet, so we made several adjustments to make training feasible on CIFAR-10 with limited compute:</p><ul><li><strong>Input size</strong>: Resized to 32×32 to match CIFAR-10</li><li><strong>Patch size</strong>: 4×4 → yields 64 tokens per image</li><li><strong>Embedding dimension</strong>: 192 (smaller than ImageNet-scale ViTs)</li><li><strong>Depth</strong>: 6 transformer blocks</li><li><strong>Heads</strong>: 3 attention heads (192 ÷ 3 = 64 dim per head)</li><li><strong>Positional embeddings</strong>: Recomputed for 64+1 tokens</li><li><strong>Batch size</strong>: 80 — balances speed and memory on Colab</li></ul><pre># Refactored SimpleViT config for CIFAR-10<br>model = SimpleViT(<br>    img_size=32,         # CIFAR-10 images are 32x32<br>    patch_size=4,        # 4x4 patches → 64 tokens<br>    in_chans=3,<br>    embed_dim=192,       # Smaller embedding size<br>    depth=6,             # Fewer transformer blocks<br>    num_heads=3,         # Divides evenly into 192<br>    num_classes=10       # For CIFAR-10<br>).to(device)</pre><h4>4.3 Training Setup</h4><p>The model was trained using:</p><ul><li><strong>Optimizer</strong>: Adam (lr = 3e-4)</li><li><strong>Loss</strong>: CrossEntropyLoss</li><li><strong>Hardware</strong>: Google Colab T4 GPU</li></ul><p>Training was efficient — about <strong>30 seconds per epoch</strong>, thanks to:</p><ul><li>Fewer transformer blocks and tokens</li><li>Larger batch size (80)</li><li>Explicit use of CUDA (to(device))</li></ul><h4>4.3 Results</h4><p>We trained our Vision Transformer for <strong>30 epochs</strong>, totaling ~15 minutes on a GPU. By the end of training, the model achieved approximately <strong>60% accuracy</strong> on the CIFAR-10 test set — a solid baseline given the model’s simplicity and the relatively small dataset size.Learning Progress</p><p>As shown in the training plots below:</p><ul><li><strong>Training loss</strong> steadily decreased, indicating that the model was effectively minimizing prediction error on the training set.</li><li><strong>Test accuracy</strong> improved rapidly within the first 10 epochs, plateauing around 60% thereafter. This suggests the model learned quickly but struggled to generalize further without additional techniques like data augmentation or regularization.</li></ul><figure><img alt="Side-by-side line charts showing decreasing training loss and increasing test accuracy for a Vision Transformer trained on CIFAR-10 over 30 epochs." src="https://cdn-images-1.medium.com/max/1024/1*4lgjT4l6QGa9FUkJz4ZCKg.png" /><figcaption><strong>Figure 6: </strong>Training loss and test accuracy over 30 epochs. Source: author</figcaption></figure><p>Here are a few <strong>example outputs</strong> from the model. While it correctly identified many samples (like cats and frogs), it struggled with visually similar classes (e.g., misclassifying a ship as an airplane).</p><figure><img alt="Six CIFAR-10 images with model predictions and ground truth labels. Four predictions are correct (cat, airplane, frog, frog), two are incorrect (automobile vs. ship, airplane vs. ship)." src="https://cdn-images-1.medium.com/max/1024/1*FN0pWEVlY_kxE5auwSjvzg.png" /><figcaption><strong>Figure 7: </strong>Example predictions on CIFAR-10 images. Source: author</figcaption></figure><p>The bar chart below shows how well the model performed <strong>across all 10 classes</strong>. Notably:</p><ul><li>The model performed best on <em>ship</em>, <em>automobile</em>, and <em>frog</em> classes — likely due to more distinctive visual features.</li><li>Performance lagged on <em>cat</em> and <em>bird</em>, which may be harder to distinguish due to higher intra-class variation and similar textures or shapes shared with other animals.</li></ul><figure><img alt="Bar chart showing classification accuracy for each CIFAR-10 class. Highest accuracy is for “ship” (~75%), lowest for “cat” (~39%). Other classes vary between ~48% and ~71%." src="https://cdn-images-1.medium.com/max/841/1*ogL74NHb6TnAXRg9PEiDaA.png" /><figcaption><strong>Figure 8:</strong> Accuracy by class. Source: author</figcaption></figure><h3>5. Limitations and Extensions</h3><p>Despite their success, Vision Transformers (ViTs) come with trade-offs. Here’s a summary of what to keep in mind:</p><h4><strong>5.1 Limitations</strong></h4><ul><li><strong>Data-Hungry by Design</strong><br>ViTs lack the strong inductive biases of CNNs (like locality and translation invariance), which means they <em>typically require large datasets</em> to perform well.<br> → <em>This is why the original ViT was pretrained on massive private datasets.</em></li><li><strong>Quadratic Time Complexity</strong><br>The self-attention mechanism scales with the square of the number of input tokens — making ViTs <em>computationally expensive</em> for high-resolution images. For an image split into N patches, attention scales as <strong>O(N²)</strong>.</li></ul><h4>5.2 Extensions and Improvements</h4><p>Researchers have developed several workarounds and improvements to address these issues:</p><ul><li><strong>DeiT (Data-efficient Image Transformer)</strong><br>A version of ViT trained <em>without large private datasets</em>, using <em>knowledge distillation</em> from a CNN teacher to improve performance on smaller datasets like ImageNet.</li><li><strong>Pretrained Backbones + Fine-Tuning</strong><br>Instead of training ViTs from scratch, most modern pipelines use <em>pretrained ViTs</em> and then fine-tune them on downstream tasks with fewer samples.</li><li><strong>Swin Transformer</strong><br>Introduces a <em>hierarchical</em> structure similar to CNNs by using local window-based attention that shifts across layers — making it <em>efficient</em> and <em>scalable</em> for high-resolution inputs.</li><li><strong>🛠 Fine-tuning on Small Datasets</strong><br>Techniques like freezing early layers, adding task-specific heads, or leveraging self-supervised pretraining (e.g., DINO, MAE) can help ViTs adapt well to limited data.</li></ul><p>In short, while ViTs opened the door to attention-based vision modeling, their full potential is best realized when paired with large-scale pretraining, architectural tweaks, or smart training tricks.</p><h3>6. GitHub + Colab</h3><h4><strong>View the </strong><a href="https://github.com/vickiiimu/vit-cifar10-tutorial"><strong>GitHub Repo</strong></a></h4><p>Includes a clean folder structure with:</p><ul><li>vit_cifar10.ipynb notebook</li><li>images/ folder for visualizations</li><li>requirements.txt for easy installation</li></ul><h4><strong>Open in </strong><a href="https://colab.research.google.com/drive/1vn57VeLHweWZCiEiJoc39q_NYUKuSXrc?usp=sharing"><strong>Colab</strong></a></h4><p>Readers can fork and run the notebook directly in the browser.</p><h4><strong>Installation</strong></h4><pre>git clone https://github.com/vickiiimu/vit-cifar10-tutorial.git<br>cd vit-cifar10-tutorial<br>pip install -r requirements.txt</pre><h3>7. Conclusion</h3><p>Congratulations — you’ve just built a Vision Transformer from scratch!</p><p>Along the way, we covered the <strong>intuitions behind attention</strong>, walked through <strong>ViT’s architecture block-by-block</strong>, and reimplemented <strong>core components</strong> like patch embedding, positional encoding, and multi-head self-attention. If you followed the walkthrough, you now have a functioning ViT model you fully understand.</p><p>Whether you’re here to <em>learn the internals, prototype your own vision ideas, or just scratch the itch of curiosity</em> — this is your sandbox.</p><h4><strong>Feedback welcome</strong></h4><p>If you spot bugs, have suggestions, or build something cool on top of this, feel free to open an <a href="https://github.com/vickiiimu/vit-cifar10-tutorial/issues">issue</a> or <a href="https://github.com/vickiiimu/vit-cifar10-tutorial/pulls">pull request</a> on GitHub.</p><h4><strong>Further reading</strong></h4><ul><li><a href="https://arxiv.org/abs/2010.11929">An Image is Worth 16x16 Words (ViT paper)</a></li><li><a href="https://arxiv.org/abs/1706.03762">Attention is All You Need (Transformer paper)</a></li><li><a href="https://arxiv.org/abs/2012.12877">DeiT: Data-efficient training of ViTs</a></li></ul><p>Thanks for reading! 👋<br>See you in the next post.</p><h4><strong>About Me</strong></h4><p>I’m a sophomore at MIT studying physics and artificial intelligence. This post is part of a series — <strong>Recreated from Scratch</strong> — where I reimplement foundational AI papers to learn them inside and out. I’ll be posting new walkthroughs every few of weeks, diving into a different model or paper each time.</p><p>If you enjoyed this walkthrough, feel free to <a href="https://github.com/vickiiimu">follow me on GitHub</a>, <a href="https://medium.com/@vicki.y.mu">follow me on Medium</a>, or even <a href="/service/mailto:vymu@mit.edu">reach out</a>. I love chatting about research, open-source projects, and all things deep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fea5a4f64816" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/from-pixels-to-predictions-building-a-transformer-for-images-fea5a4f64816">From Pixels to Predictions: Building a Transformer for Images</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>