<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://namesarnav.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://namesarnav.com/" rel="alternate" type="text/html" /><updated>2026-11-21T05:57:21+00:00</updated><id>https://namesarnav.com/feed.xml</id><title type="html">Arnav Verma</title><subtitle>Arnav Verma — AI engineering and research. M.S. Computer Science at NYU Courant.</subtitle><author><name>Arnav Verma</name><email>av4445@nyu.edu</email></author><entry><title type="html">Kubernetes Pods Explained</title><link href="https://namesarnav.com/blog/k8s-pods/" rel="alternate" type="text/html" title="Kubernetes Pods Explained" /><published>2026-08-02T00:00:00+00:00</published><updated>2026-08-02T00:00:00+00:00</updated><id>https://namesarnav.com/blog/k8s-pods</id><content type="html" xml:base="https://namesarnav.com/blog/k8s-pods/"><![CDATA[<p><em>Also published on <a href="https://arnavverma.hashnode.dev/kubernetes-pods">arnavverma.hashnode.dev</a>.</em></p>

<h2 id="1-understanding-pods-as-the-smallest-deployable-unit"><a href="#1-understanding-pods-as-the-smallest-deployable-unit"></a>1. Understanding Pods as the Smallest Deployable Unit</h2>

<h3 id="what-exactly-is-a-pod"><a href="#what-exactly-is-a-pod"></a>What Exactly Is a Pod?</h3>

<p>A Pod is Kubernetes’ atomic unit of deployment. You cannot deploy anything smaller than a Pod. While you might think of containers as the fundamental building block (since that’s what actually runs your code), Kubernetes wraps containers in Pods for important architectural reasons.</p>

<p><strong>The Technical Reality:</strong></p>

<p>When you create a Pod, Kubernetes actually creates something called a <strong>pause container</strong> (also called the infrastructure container) first. This hidden container:</p>

<ol>
  <li>
    <p>Holds the network namespace for the Pod</p>
  </li>
  <li>
    <p>Acquires the Pod’s IP address</p>
  </li>
  <li>
    <p>Stays running for the Pod’s entire lifetime</p>
  </li>
  <li>
    <p>Allows your application containers to restart without losing network identity</p>
  </li>
</ol>

<p>Your application containers then join this pause container’s namespaces. This is why all containers in a Pod share the same IP address and network stack.</p>

<pre><code class="language-mermaid">flowchart TB
    subgraph POD["POD"]
        NS["Shared Network Namespace&lt;br/&gt;(pause container)&lt;br/&gt;IP: 10.244.1.5"]
        NS --&gt; A["Container A&lt;br/&gt;:8080"]
        NS --&gt; B["Container B&lt;br/&gt;:9090"]
        NS --&gt; C["Container C&lt;br/&gt;:3000"]
        A --- VOL["Shared Volumes"]
        B --- VOL
        C --- VOL
    end
</code></pre>

<h3 id="what-does-smallest-deployable-unit-actually-mean"><a href="#what-does-smallest-deployable-unit-actually-mean"></a>What Does “Smallest Deployable Unit” Actually Mean?</h3>

<p>It means:</p>

<ol>
  <li>
    <p><strong>Scheduling granularity</strong> — The Kubernetes scheduler places entire Pods on nodes, never individual containers. If you have 3 containers in a Pod, they all go to the same node together.</p>
  </li>
  <li>
    <p><strong>Scaling granularity</strong> — When you scale up, you add more Pods, not more containers within a Pod. If you need 5 replicas of your web server, you get 5 Pods, each with its own web server container.</p>
  </li>
  <li>
    <p><strong>Failure granularity</strong> — If a node fails, the entire Pod fails. Kubernetes doesn’t try to relocate individual containers from a Pod to different nodes.</p>
  </li>
</ol>

<h3 id="why-not-deploy-containers-directly"><a href="#why-not-deploy-containers-directly"></a>Why Not Deploy Containers Directly?</h3>

<p>Consider what you’d need to manage if Kubernetes deployed raw containers:</p>

<ul>
  <li>
    <p><strong>Networking:</strong> How would containers find each other? How would they share <a href="http://localhost">localhost</a>?</p>
  </li>
  <li>
    <p><strong>Storage:</strong> How would you share files between containers?</p>
  </li>
  <li>
    <p><strong>Lifecycle:</strong> What happens when one container depends on another?</p>
  </li>
  <li>
    <p><strong>Identity:</strong> How do you refer to a group of related containers as one thing?</p>
  </li>
</ul>

<p>The Pod abstraction solves all of these:</p>

<table>
  <thead>
    <tr>
      <th>Problem</th>
      <th>Pod Solution</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Containers need same IP</td>
      <td>Pod provides shared network namespace</td>
    </tr>
    <tr>
      <td>Containers need shared files</td>
      <td>Pod provides shared volume mounts</td>
    </tr>
    <tr>
      <td>Containers have dependencies</td>
      <td>Init containers and lifecycle hooks</td>
    </tr>
    <tr>
      <td>Need atomic deployment</td>
      <td>Pod is scheduled/deployed as one unit</td>
    </tr>
    <tr>
      <td>Need health tracking</td>
      <td>Pod-level status and conditions</td>
    </tr>
  </tbody>
</table>

<h3 id="the-pod-to-container-relationship-real-world-analogy"><a href="#the-pod-to-container-relationship-real-world-analogy"></a>The Pod-to-Container Relationship: Real-World Analogy</h3>

<p>Imagine shipping containers (the metal boxes on cargo ships). A Pod is like a shipping container, and application containers are like the packages inside it.</p>

<ul>
  <li>
    <p>The shipping container (Pod) provides the outer boundary and tracking number</p>
  </li>
  <li>
    <p>The packages (containers) inside share the same journey</p>
  </li>
  <li>
    <p>When the shipping container moves, everything inside moves together</p>
  </li>
  <li>
    <p>The shipping manifest (Pod spec) lists all packages inside</p>
  </li>
  <li>
    <p>Customs (Kubernetes) deals with shipping containers, not individual packages</p>
  </li>
</ul>

<p><strong>When to Use Single-Container Pods:</strong></p>

<p>Most Pods contain exactly one container. Use single-container Pods when:</p>

<ul>
  <li>
    <p>The container is self-sufficient</p>
  </li>
  <li>
    <p>It doesn’t need to share files or network with a helper</p>
  </li>
  <li>
    <p>Scaling means running more instances of the same thing</p>
  </li>
</ul>

<p><strong>When to Use Multi-Container Pods:</strong></p>

<p>Use multi-container Pods only when containers are <strong>tightly coupled</strong>:</p>

<ul>
  <li>
    <p>They must run on the same machine</p>
  </li>
  <li>
    <p>They must share files</p>
  </li>
  <li>
    <p>They communicate over <a href="http://localhost">localhost</a></p>
  </li>
  <li>
    <p>They scale together as a unit</p>
  </li>
</ul>

<hr />

<h2 id="2-pod-lifecycle-and-phases"><a href="#2-pod-lifecycle-and-phases"></a>2. Pod Lifecycle and Phases</h2>

<h3 id="the-complete-pod-lifecycle-journey"><a href="#the-complete-pod-lifecycle-journey"></a>The Complete Pod Lifecycle Journey</h3>

<p>When you create a Pod, it goes through a predictable sequence of events. Understanding this deeply helps you debug problems.</p>

<pre><code class="language-mermaid">---
title: Pod Lifecycle Phases
---
flowchart TD
    PC["Pod Created (via API call)"] --&gt; PENDING

    subgraph PENDING["PENDING PHASE"]
        P1["1. Pod stored in etcd"]
        P2["2. Scheduler assigns Pod to Node"]
        P3["3. Kubelet receives Pod spec"]
        P4["4. Kubelet pulls container images"]
        P5["5. Init containers run (if any)"]
        P1 --&gt; P2 --&gt; P3 --&gt; P4 --&gt; P5
    end

    PENDING --&gt;|"All init containers complete&lt;br/&gt;Main containers starting"| RUNNING

    subgraph RUNNING["RUNNING PHASE"]
        R1["At least one container running"]
        R2["Pod bound to node"]
        R3["Container States: Running, Waiting, or Terminated"]
    end

    RUNNING --&gt;|"All containers exit&lt;br/&gt;with code 0"| SUCCEEDED
    RUNNING --&gt;|"At least one container&lt;br/&gt;exits with non-zero"| FAILED

    subgraph SUCCEEDED["SUCCEEDED"]
        S1["All containers terminated"]
        S2["All exit code 0"]
        S3["Won't restart"]
        S4["Common for: Jobs"]
    end

    subgraph FAILED["FAILED"]
        F1["All containers terminated"]
        F2["At least one exit code != 0"]
        F3["Won't restart (unless policy)"]
    end
</code></pre>

<h3 id="deep-dive-into-each-phase"><a href="#deep-dive-into-each-phase"></a>Deep Dive into Each Phase</h3>

<h4 id="pending-phase"><a href="#pending-phase"></a>PENDING Phase</h4>

<p>A Pod enters Pending immediately after creation and stays there until containers start running. Many things happen in this phase:</p>

<p><strong>Step 1: API Server Processing</strong></p>

<pre><code class="language-mermaid">flowchart TD
    CMD["kubectl apply -f pod.yaml"] --&gt; API

    subgraph API["API Server"]
        A1["Authenticates"]
        A2["Authorizes"]
        A3["Validates"]
        A4["Stores in etcd"]
        A1 --&gt; A2 --&gt; A3 --&gt; A4
    end

    API --&gt; RESULT["Pod exists in cluster&lt;br/&gt;(but not scheduled yet)"]
</code></pre>

<p><strong>Step 2: Scheduling</strong></p>

<pre><code class="language-mermaid">flowchart TD
    subgraph SCHED["Scheduler"]
        direction TB
        E["Evaluates:"]
        E1["Resource requests"]
        E2["Node selectors"]
        E3["Affinity rules"]
        E4["Taints/tolerations"]
        E5["Available nodes"]
        E --&gt; E1 --&gt; E2 --&gt; E3 --&gt; E4 --&gt; E5
    end

    SCHED --&gt; RESULT["Pod assigned to Node&lt;br/&gt;(nodeName field set)"]
</code></pre>

<p><strong>What Can Cause Prolonged Pending:</strong></p>

<table>
  <thead>
    <tr>
      <th>Symptom</th>
      <th>Cause</th>
      <th>How to Debug</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>No node assigned</td>
      <td>No node has enough resources</td>
      <td><code class="language-plaintext highlighter-rouge">kubectl describe pod</code> shows “Insufficient cpu/memory”</td>
    </tr>
    <tr>
      <td>No node assigned</td>
      <td>No node matches node selector</td>
      <td>Check node labels vs pod’s nodeSelector</td>
    </tr>
    <tr>
      <td>No node assigned</td>
      <td>Taints blocking all nodes</td>
      <td>Check tolerations</td>
    </tr>
    <tr>
      <td>Image pull stuck</td>
      <td>Wrong image name or tag</td>
      <td><code class="language-plaintext highlighter-rouge">kubectl describe pod</code> shows ImagePullBackOff</td>
    </tr>
    <tr>
      <td>Image pull stuck</td>
      <td>Private registry, no credentials</td>
      <td>Check imagePullSecrets</td>
    </tr>
    <tr>
      <td>Init container running</td>
      <td>Init containers taking time</td>
      <td>Normal if init does real work</td>
    </tr>
  </tbody>
</table>

<p><strong>Example Pending Debugging:</strong></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>kubectl get pods
NAME      READY   STATUS    RESTARTS   AGE
my-pod    0/1     Pending   0          5m

<span class="nv">$ </span>kubectl describe pod my-pod
...
Events:
  Type     Reason            Age   From               Message
  <span class="nt">----</span>     <span class="nt">------</span>            <span class="nt">----</span>  <span class="nt">----</span>               <span class="nt">-------</span>
  Warning  FailedScheduling  5m    default-scheduler  0/3 nodes are available: 
                                                       3 Insufficient memory.
</code></pre></div></div>

<p>This tells you: No node has enough memory for this Pod’s requests.</p>

<h4 id="running-phase"><a href="#running-phase"></a>RUNNING Phase</h4>

<p>Once at least one main container is running, the Pod transitions to Running. But “Running” doesn’t mean “working correctly” — your app could be crashing in a loop.</p>

<p><strong>Container States Within Running Pod:</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># kubectl get pod my-pod -o yaml (simplified)</span>
<span class="na">status</span><span class="pi">:</span>
  <span class="na">phase</span><span class="pi">:</span> <span class="s">Running</span>
  <span class="na">containerStatuses</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">nginx</span>
    <span class="na">state</span><span class="pi">:</span>
      <span class="na">running</span><span class="pi">:</span>
        <span class="na">startedAt</span><span class="pi">:</span> <span class="s2">"</span><span class="s">2024-01-15T10:00:00Z"</span>
    <span class="na">ready</span><span class="pi">:</span> <span class="kc">true</span>
    <span class="na">restartCount</span><span class="pi">:</span> <span class="m">0</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">sidecar</span>
    <span class="na">state</span><span class="pi">:</span>
      <span class="na">waiting</span><span class="pi">:</span>
        <span class="na">reason</span><span class="pi">:</span> <span class="s">CrashLoopBackOff</span>
        <span class="na">message</span><span class="pi">:</span> <span class="s2">"</span><span class="s">back-off</span><span class="nv"> </span><span class="s">5m0s</span><span class="nv"> </span><span class="s">restarting</span><span class="nv"> </span><span class="s">failed</span><span class="nv"> </span><span class="s">container"</span>
    <span class="na">ready</span><span class="pi">:</span> <span class="kc">false</span>
    <span class="na">restartCount</span><span class="pi">:</span> <span class="m">5</span>
</code></pre></div></div>

<p>This Pod is “Running” but has a problem — the sidecar container keeps crashing.</p>

<p><strong>Container State Details:</strong></p>

<table>
  <thead>
    <tr>
      <th>State</th>
      <th>Fields</th>
      <th>Meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">waiting</code></td>
      <td>reason, message</td>
      <td>Container not running yet. Reasons: ContainerCreating, ImagePullBackOff, CrashLoopBackOff</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">running</code></td>
      <td>startedAt</td>
      <td>Container executing. Has timestamp of start</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">terminated</code></td>
      <td>exitCode, reason, startedAt, finishedAt</td>
      <td>Container finished. exitCode 0 = success, else failure</td>
    </tr>
  </tbody>
</table>

<h4 id="succeeded-phase"><a href="#succeeded-phase"></a>SUCCEEDED Phase</h4>

<p>Pods reach Succeeded when:</p>

<ul>
  <li>
    <p>All containers have terminated</p>
  </li>
  <li>
    <p>All containers exited with code 0</p>
  </li>
  <li>
    <p>The Pod won’t be restarted</p>
  </li>
</ul>

<p>This is normal for <strong>Jobs</strong> — workloads designed to run to completion:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>kubectl get pods
NAME              READY   STATUS      RESTARTS   AGE
backup-job-xyz    0/1     Completed   0          1h
</code></pre></div></div>

<h4 id="failed-phase"><a href="#failed-phase"></a>FAILED Phase</h4>

<p>Pods reach Failed when:</p>

<ul>
  <li>
    <p>All containers have terminated</p>
  </li>
  <li>
    <p>At least one container exited with non-zero code</p>
  </li>
  <li>
    <p>restartPolicy prevents restart (Never or OnFailure with Succeeded)</p>
  </li>
</ul>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>kubectl get pods
NAME            READY   STATUS   RESTARTS   AGE
broken-job-abc  0/1     Error    0          5m

<span class="nv">$ </span>kubectl logs broken-job-abc
Error: database connection failed
</code></pre></div></div>

<h3 id="restart-policies"><a href="#restart-policies"></a>Restart Policies</h3>

<p>The <code class="language-plaintext highlighter-rouge">restartPolicy</code> field determines what happens when containers exit:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">spec</span><span class="pi">:</span>
  <span class="na">restartPolicy</span><span class="pi">:</span> <span class="s">Always</span>  <span class="c1"># Options: Always, OnFailure, Never</span>
</code></pre></div></div>

<table>
  <thead>
    <tr>
      <th>Policy</th>
      <th>Behavior</th>
      <th>Use Case</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Always</code></td>
      <td>Always restart containers, regardless of exit code</td>
      <td>Long-running services (web servers, daemons)</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">OnFailure</code></td>
      <td>Restart only if exit code is non-zero</td>
      <td>Jobs that should retry on failure</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Never</code></td>
      <td>Never restart containers</td>
      <td>Jobs where failure should not retry</td>
    </tr>
  </tbody>
</table>

<p><strong>How Restart Backoff Works:</strong></p>

<p>When a container keeps failing, Kubernetes doesn’t just hammer restarts. It uses exponential backoff:</p>

<pre><code class="language-mermaid">flowchart LR
    F1["First failure:&lt;br/&gt;restart immediately"] --&gt; F2["Second failure:&lt;br/&gt;wait 10s, then restart"]
    F2 --&gt; F3["Third failure:&lt;br/&gt;wait 20s, then restart"]
    F3 --&gt; F4["Fourth failure:&lt;br/&gt;wait 40s, then restart"]
    F4 --&gt; F5["Fifth failure:&lt;br/&gt;wait 80s, then restart"]
    F5 --&gt; F6["...continues...&lt;br/&gt;up to 5 minutes max"]
</code></pre>

<p>This is why you see “CrashLoopBackOff” — Kubernetes is backing off between restart attempts.</p>

<h3 id="pod-conditions"><a href="#pod-conditions"></a>Pod Conditions</h3>

<p>Beyond the simple phase, Pods have detailed <strong>conditions</strong>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>kubectl describe pod my-pod
Conditions:
  Type              Status
  Initialized       True    <span class="c"># All init containers completed</span>
  Ready             True    <span class="c"># Pod is ready to serve traffic</span>
  ContainersReady   True    <span class="c"># All containers are ready</span>
  PodScheduled      True    <span class="c"># Pod has been scheduled to a node</span>
</code></pre></div></div>

<table>
  <thead>
    <tr>
      <th>Condition</th>
      <th>True Means</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">PodScheduled</code></td>
      <td>Pod assigned to a node</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Initialized</code></td>
      <td>All init containers completed successfully</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ContainersReady</code></td>
      <td>All containers have passed readiness probes</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Ready</code></td>
      <td>Pod can receive traffic (used by Services)</td>
    </tr>
  </tbody>
</table>

<hr />

<h2 id="3-creating-pods-imperative-vs-declarative"><a href="#3-creating-pods-imperative-vs-declarative"></a>3. Creating Pods: Imperative vs Declarative</h2>

<p>These represent two fundamentally different approaches to managing infrastructure.</p>

<h3 id="imperative-approach-telling-kubernetes-what-to-do"><a href="#imperative-approach-telling-kubernetes-what-to-do"></a>Imperative Approach: Telling Kubernetes What To Do</h3>

<p>With imperative commands, you issue direct orders to Kubernetes: “Run this container,” “Delete this Pod,” “Scale this deployment.”</p>

<p><strong>The Imperative Mindset:</strong></p>

<ul>
  <li>
    <p>You are the operator</p>
  </li>
  <li>
    <p>You execute commands in sequence</p>
  </li>
  <li>
    <p>The cluster state is the result of your actions</p>
  </li>
  <li>
    <p>No record exists of how you got to current state</p>
  </li>
</ul>

<p><strong>Basic Pod Creation:</strong></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kubectl run nginx-pod <span class="nt">--image</span><span class="o">=</span>nginx
</code></pre></div></div>

<p>This single command:</p>

<ol>
  <li>
    <p>Creates a Pod resource</p>
  </li>
  <li>
    <p>Names it “nginx-pod”</p>
  </li>
  <li>
    <p>Uses the nginx image</p>
  </li>
  <li>
    <p>Applies default settings for everything else</p>
  </li>
</ol>

<p><strong>Adding More Options:</strong></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kubectl run nginx-pod <span class="se">\</span>
  <span class="nt">--image</span><span class="o">=</span>nginx:1.19 <span class="se">\</span>
  <span class="nt">--port</span><span class="o">=</span>80 <span class="se">\</span>
  <span class="nt">--labels</span><span class="o">=</span><span class="s2">"app=web,env=prod"</span> <span class="se">\</span>
  <span class="nt">--env</span><span class="o">=</span><span class="s2">"ENV=production"</span> <span class="se">\</span>
  <span class="nt">--restart</span><span class="o">=</span>Never
</code></pre></div></div>

<p><strong>Common Imperative Commands:</strong></p>

<table>
  <thead>
    <tr>
      <th>Command</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">kubectl run NAME --image=IMAGE</code></td>
      <td>Create a Pod</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">kubectl create deployment NAME --image=IMAGE</code></td>
      <td>Create a Deployment</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">kubectl expose pod NAME --port=80</code></td>
      <td>Create a Service</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">kubectl delete pod NAME</code></td>
      <td>Delete a Pod</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">kubectl edit pod NAME</code></td>
      <td>Edit live resource</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">kubectl scale deployment NAME --replicas=3</code></td>
      <td>Scale deployment</td>
    </tr>
  </tbody>
</table>

<p><strong>Imperative Object Configuration:</strong></p>

<p>There’s a middle ground — using imperative verbs with files:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kubectl create <span class="nt">-f</span> pod.yaml    <span class="c"># Create (fails if exists)</span>
kubectl delete <span class="nt">-f</span> pod.yaml    <span class="c"># Delete</span>
kubectl replace <span class="nt">-f</span> pod.yaml   <span class="c"># Replace (must exist)</span>
</code></pre></div></div>

<p>This is still imperative because you’re telling Kubernetes what to do, but you’re using files to define the objects.</p>

<h3 id="declarative-approach-telling-kubernetes-what-you-want"><a href="#declarative-approach-telling-kubernetes-what-you-want"></a>Declarative Approach: Telling Kubernetes What You Want</h3>

<p>With declarative configuration, you describe the desired state, and Kubernetes figures out how to achieve it.</p>

<p><strong>The Declarative Mindset:</strong></p>

<ul>
  <li>
    <p>You define the target state</p>
  </li>
  <li>
    <p>Kubernetes continuously works toward that state</p>
  </li>
  <li>
    <p>The definition IS the documentation</p>
  </li>
  <li>
    <p>Changes are tracked through version control</p>
  </li>
</ul>

<p><strong>The Core Command:</strong></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kubectl apply <span class="nt">-f</span> pod.yaml
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">apply</code> is intelligent:</p>

<ul>
  <li>
    <p>If resource doesn’t exist → create it</p>
  </li>
  <li>
    <p>If resource exists → update it to match the file</p>
  </li>
  <li>
    <p>If resource is unchanged → do nothing</p>
  </li>
</ul>

<p><strong>Declarative Workflow:</strong></p>

<pre><code class="language-mermaid">flowchart TD
    V1["pod.yaml (v1)&lt;br/&gt;Version controlled in Git"] --&gt; APPLY1["kubectl apply -f pod.yaml"]
    APPLY1 --&gt; K1["Kubernetes Cluster&lt;br/&gt;Creates Pod"]
    K1 -.-&gt;|"time passes...&lt;br/&gt;you need to make changes"| V2
    V2["pod.yaml (v2)&lt;br/&gt;Edit the file, commit to Git"] --&gt; APPLY2["kubectl apply -f pod.yaml"]
    APPLY2 --&gt; K2["Kubernetes Cluster&lt;br/&gt;Updates Pod to match new spec"]
</code></pre>

<h3 id="comparison-table"><a href="#comparison-table"></a>Comparison Table</h3>

<table>
  <thead>
    <tr>
      <th>Aspect</th>
      <th>Imperative</th>
      <th>Declarative</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Command</strong></td>
      <td><code class="language-plaintext highlighter-rouge">kubectl run</code>, <code class="language-plaintext highlighter-rouge">create</code>, <code class="language-plaintext highlighter-rouge">delete</code></td>
      <td><code class="language-plaintext highlighter-rouge">kubectl apply</code></td>
    </tr>
    <tr>
      <td><strong>State tracking</strong></td>
      <td>None (you remember)</td>
      <td>Git history</td>
    </tr>
    <tr>
      <td><strong>Repeatability</strong></td>
      <td>Run same commands</td>
      <td>Apply same files</td>
    </tr>
    <tr>
      <td><strong>Collaboration</strong></td>
      <td>Share commands (error-prone)</td>
      <td>Share files (reliable)</td>
    </tr>
    <tr>
      <td><strong>Audit trail</strong></td>
      <td>None</td>
      <td>Git commits</td>
    </tr>
    <tr>
      <td><strong>Rollback</strong></td>
      <td>Remember previous commands</td>
      <td>Revert Git commit</td>
    </tr>
    <tr>
      <td><strong>Partial updates</strong></td>
      <td>Tricky</td>
      <td>Automatic</td>
    </tr>
    <tr>
      <td><strong>Learning curve</strong></td>
      <td>Lower</td>
      <td>Higher</td>
    </tr>
    <tr>
      <td><strong>CKAD exams</strong></td>
      <td>Essential for speed</td>
      <td>Required for complex tasks</td>
    </tr>
  </tbody>
</table>

<h3 id="the-secret-weapon-generating-yaml-from-imperative-commands"><a href="#the-secret-weapon-generating-yaml-from-imperative-commands"></a>The Secret Weapon: Generating YAML from Imperative Commands</h3>

<p>Here’s the technique that makes you fast in CKAD:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kubectl run nginx <span class="nt">--image</span><span class="o">=</span>nginx <span class="nt">--dry-run</span><span class="o">=</span>client <span class="nt">-o</span> yaml <span class="o">&gt;</span> pod.yaml
</code></pre></div></div>

<p><strong>Breaking this down:</strong></p>

<table>
  <thead>
    <tr>
      <th>Flag</th>
      <th>Meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--dry-run=client</code></td>
      <td>Don’t actually create anything; just simulate</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">-o yaml</code></td>
      <td>Output the would-be resource as YAML</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">&gt; pod.yaml</code></td>
      <td>Redirect output to a file</td>
    </tr>
  </tbody>
</table>

<p><strong>Generated output:</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Pod</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">creationTimestamp</span><span class="pi">:</span> <span class="kc">null</span>
  <span class="na">labels</span><span class="pi">:</span>
    <span class="na">run</span><span class="pi">:</span> <span class="s">nginx</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">nginx</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="na">containers</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">image</span><span class="pi">:</span> <span class="s">nginx</span>
    <span class="na">name</span><span class="pi">:</span> <span class="s">nginx</span>
    <span class="na">resources</span><span class="pi">:</span> <span class="pi">{}</span>
  <span class="na">dnsPolicy</span><span class="pi">:</span> <span class="s">ClusterFirst</span>
  <span class="na">restartPolicy</span><span class="pi">:</span> <span class="s">Always</span>
<span class="na">status</span><span class="pi">:</span> <span class="pi">{}</span>
</code></pre></div></div>

<p>Now you can edit this file to add anything you need (environment variables, volumes, etc.) and apply it.</p>

<p><strong>More Examples:</strong></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Generate Pod with port exposed</span>
kubectl run nginx <span class="nt">--image</span><span class="o">=</span>nginx <span class="nt">--port</span><span class="o">=</span>80 <span class="nt">--dry-run</span><span class="o">=</span>client <span class="nt">-o</span> yaml

<span class="c"># Generate Pod with environment variable</span>
kubectl run nginx <span class="nt">--image</span><span class="o">=</span>nginx <span class="nt">--env</span><span class="o">=</span><span class="s2">"DB_HOST=mysql"</span> <span class="nt">--dry-run</span><span class="o">=</span>client <span class="nt">-o</span> yaml

<span class="c"># Generate Pod that runs a command</span>
kubectl run busybox <span class="nt">--image</span><span class="o">=</span>busybox <span class="nt">--dry-run</span><span class="o">=</span>client <span class="nt">-o</span> yaml <span class="se">\</span>
  <span class="nt">--command</span> <span class="nt">--</span> <span class="nb">sleep </span>3600

<span class="c"># Generate Pod with resource limits</span>
kubectl run nginx <span class="nt">--image</span><span class="o">=</span>nginx <span class="nt">--dry-run</span><span class="o">=</span>client <span class="nt">-o</span> yaml <span class="se">\</span>
  <span class="nt">--requests</span><span class="o">=</span><span class="s1">'cpu=100m,memory=128Mi'</span> <span class="se">\</span>
  <span class="nt">--limits</span><span class="o">=</span><span class="s1">'cpu=200m,memory=256Mi'</span>
</code></pre></div></div>

<hr />

<h2 id="4-yaml-manifest-structure"><a href="#4-yaml-manifest-structure"></a>4. YAML Manifest Structure</h2>

<h3 id="the-four-required-top-level-fields"><a href="#the-four-required-top-level-fields"></a>The Four Required Top-Level Fields</h3>

<p>Every Kubernetes resource YAML follows this structure:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">&lt;api-version&gt;</span>   <span class="c1"># 1. Which API version</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">&lt;resource-type&gt;</span>       <span class="c1"># 2. What kind of resource</span>
<span class="na">metadata</span><span class="pi">:</span>                   <span class="c1"># 3. Resource identification</span>
  <span class="c1"># ...</span>
<span class="na">spec</span><span class="pi">:</span>                       <span class="c1"># 4. Desired state</span>
  <span class="c1"># ...</span>
</code></pre></div></div>

<p>Let’s examine each in detail.</p>

<h3 id="field-1-apiversion"><a href="#field-1-apiversion"></a>Field 1: apiVersion</h3>

<p>This tells Kubernetes which schema to use for parsing this resource. Different resources live in different API groups.</p>

<p><strong>How to find the right apiVersion:</strong></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># List all API resources and their versions</span>
kubectl api-resources

<span class="c"># Output (partial):</span>
NAME          SHORTNAMES   APIVERSION   NAMESPACED   KIND
pods          po           v1           <span class="nb">true         </span>Pod
deployments   deploy       apps/v1      <span class="nb">true         </span>Deployment
services      svc          v1           <span class="nb">true         </span>Service
configmaps    cm           v1           <span class="nb">true         </span>ConfigMap
secrets                    v1           <span class="nb">true         </span>Secret
<span class="nb">jobs                       </span>batch/v1     <span class="nb">true         </span>Job
cronjobs      cj           batch/v1     <span class="nb">true         </span>CronJob
</code></pre></div></div>

<p><strong>API Version Patterns:</strong></p>

<table>
  <thead>
    <tr>
      <th>Pattern</th>
      <th>Example</th>
      <th>Meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">v1</code></td>
      <td><code class="language-plaintext highlighter-rouge">v1</code></td>
      <td>Core API group, stable</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">GROUP/VERSION</code></td>
      <td><code class="language-plaintext highlighter-rouge">apps/v1</code></td>
      <td>Named group, stable</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">GROUP/v1beta1</code></td>
      <td><a href="http://networking.k8s.io/v1beta1"><code class="language-plaintext highlighter-rouge">networking.k8s.io/v1beta1</code></a></td>
      <td>Beta, may change</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">GROUP/v1alpha1</code></td>
      <td><a href="http://example.io/v1alpha1"><code class="language-plaintext highlighter-rouge">example.io/v1alpha1</code></a></td>
      <td>Alpha, experimental</td>
    </tr>
  </tbody>
</table>

<p><strong>Common apiVersions for CKAD:</strong></p>

<table>
  <thead>
    <tr>
      <th>Resource</th>
      <th>apiVersion</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Pod, Service, ConfigMap, Secret, PersistentVolume, PersistentVolumeClaim</td>
      <td><code class="language-plaintext highlighter-rouge">v1</code></td>
    </tr>
    <tr>
      <td>Deployment, ReplicaSet, DaemonSet, StatefulSet</td>
      <td><code class="language-plaintext highlighter-rouge">apps/v1</code></td>
    </tr>
    <tr>
      <td>Job, CronJob</td>
      <td><code class="language-plaintext highlighter-rouge">batch/v1</code></td>
    </tr>
    <tr>
      <td>Ingress</td>
      <td><a href="http://networking.k8s.io/v1"><code class="language-plaintext highlighter-rouge">networking.k8s.io/v1</code></a></td>
    </tr>
    <tr>
      <td>NetworkPolicy</td>
      <td><a href="http://networking.k8s.io/v1"><code class="language-plaintext highlighter-rouge">networking.k8s.io/v1</code></a></td>
    </tr>
  </tbody>
</table>

<h3 id="field-2-kind"><a href="#field-2-kind"></a>Field 2: kind</h3>

<p>The type of resource you’re creating. This must match one of Kubernetes’ registered resource types.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">kind</span><span class="pi">:</span> <span class="s">Pod</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Deployment</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Service</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">ConfigMap</span>
</code></pre></div></div>

<p>The kind determines what fields are valid in the spec section.</p>

<h3 id="field-3-metadata"><a href="#field-3-metadata"></a>Field 3: metadata</h3>

<p>This section provides the resource’s identity and organizational information.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">my-pod</span>                    <span class="c1"># Required: unique name within namespace</span>
  <span class="na">namespace</span><span class="pi">:</span> <span class="s">default</span>              <span class="c1"># Optional: which namespace (default if omitted)</span>
  <span class="na">labels</span><span class="pi">:</span>                         <span class="c1"># Optional: key-value pairs for organization</span>
    <span class="na">app</span><span class="pi">:</span> <span class="s">myapp</span>
    <span class="na">environment</span><span class="pi">:</span> <span class="s">production</span>
    <span class="na">version</span><span class="pi">:</span> <span class="s">v1.2.3</span>
  <span class="na">annotations</span><span class="pi">:</span>                    <span class="c1"># Optional: non-identifying metadata</span>
    <span class="na">description</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Main</span><span class="nv"> </span><span class="s">application</span><span class="nv"> </span><span class="s">pod"</span>
    <span class="na">owner</span><span class="pi">:</span> <span class="s2">"</span><span class="s">platform-team@company.com"</span>
    <span class="na">git-commit</span><span class="pi">:</span> <span class="s2">"</span><span class="s">abc123def456"</span>
</code></pre></div></div>

<p><strong>Understanding Labels:</strong></p>

<p>Labels are key-value pairs that identify resources. They’re used for:</p>

<ol>
  <li>
    <p><strong>Selection</strong> — Find resources matching criteria</p>
  </li>
  <li>
    <p><strong>Grouping</strong> — Organize resources logically</p>
  </li>
  <li>
    <p><strong>Service routing</strong> — Services use label selectors to find Pods</p>
  </li>
</ol>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Find all pods with label app=myapp</span>
kubectl get pods <span class="nt">-l</span> <span class="nv">app</span><span class="o">=</span>myapp

<span class="c"># Find pods matching multiple labels</span>
kubectl get pods <span class="nt">-l</span> <span class="nv">app</span><span class="o">=</span>myapp,environment<span class="o">=</span>production

<span class="c"># Find pods where version is NOT v1</span>
kubectl get pods <span class="nt">-l</span> <span class="s1">'version!=v1'</span>
</code></pre></div></div>

<p><strong>Label Best Practices:</strong></p>

<table>
  <thead>
    <tr>
      <th>Label Key</th>
      <th>Purpose</th>
      <th>Example</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">app</code></td>
      <td>Application name</td>
      <td><code class="language-plaintext highlighter-rouge">app: frontend</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">environment</code></td>
      <td>Deployment environment</td>
      <td><code class="language-plaintext highlighter-rouge">environment: production</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">version</code></td>
      <td>Application version</td>
      <td><code class="language-plaintext highlighter-rouge">version: v2.1.0</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">tier</code></td>
      <td>Architectural tier</td>
      <td><code class="language-plaintext highlighter-rouge">tier: backend</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">team</code></td>
      <td>Owning team</td>
      <td><code class="language-plaintext highlighter-rouge">team: payments</code></td>
    </tr>
  </tbody>
</table>

<p><strong>Understanding Annotations:</strong></p>

<p>Annotations are for non-identifying information:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">annotations</span><span class="pi">:</span>
  <span class="c1"># Documentation</span>
  <span class="na">description</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Handles</span><span class="nv"> </span><span class="s">user</span><span class="nv"> </span><span class="s">authentication"</span>
  
  <span class="c1"># Tooling</span>
  <span class="na">prometheus.io/scrape</span><span class="pi">:</span> <span class="s2">"</span><span class="s">true"</span>
  <span class="na">prometheus.io/port</span><span class="pi">:</span> <span class="s2">"</span><span class="s">9090"</span>
  
  <span class="c1"># Audit trail</span>
  <span class="na">kubernetes.io/change-cause</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Update</span><span class="nv"> </span><span class="s">to</span><span class="nv"> </span><span class="s">fix</span><span class="nv"> </span><span class="s">CVE-2024-1234"</span>
  
  <span class="c1"># Build information</span>
  <span class="na">build.company.com/git-sha</span><span class="pi">:</span> <span class="s2">"</span><span class="s">abc123"</span>
  <span class="na">build.company.com/pipeline</span><span class="pi">:</span> <span class="s2">"</span><span class="s">main-123"</span>
</code></pre></div></div>

<p><strong>Labels vs Annotations:</strong></p>

<table>
  <thead>
    <tr>
      <th>Aspect</th>
      <th>Labels</th>
      <th>Annotations</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Used for selection</td>
      <td>Yes</td>
      <td>No</td>
    </tr>
    <tr>
      <td>Character limits</td>
      <td>Key: 63, Value: 63</td>
      <td>Key: 253, Value: 256KB</td>
    </tr>
    <tr>
      <td>Purpose</td>
      <td>Identify and group</td>
      <td>Store metadata</td>
    </tr>
    <tr>
      <td>Example use</td>
      <td><code class="language-plaintext highlighter-rouge">app=nginx</code></td>
      <td>Long JSON config</td>
    </tr>
  </tbody>
</table>

<h3 id="field-4-spec"><a href="#field-4-spec"></a>Field 4: spec</h3>

<p>This is where you define what you actually want. The structure depends on the <code class="language-plaintext highlighter-rouge">kind</code> of resource.</p>

<p><strong>Pod spec structure:</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">spec</span><span class="pi">:</span>
  <span class="c1"># Container definitions (required)</span>
  <span class="na">containers</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">main</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">nginx</span>
    <span class="c1"># ... container-specific settings</span>
  
  <span class="c1"># Init containers (optional)</span>
  <span class="na">initContainers</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">init</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">busybox</span>
  
  <span class="c1"># Volume definitions (optional)</span>
  <span class="na">volumes</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">data</span>
    <span class="na">emptyDir</span><span class="pi">:</span> <span class="pi">{}</span>
  
  <span class="c1"># Pod-level settings</span>
  <span class="na">restartPolicy</span><span class="pi">:</span> <span class="s">Always</span>
  <span class="na">serviceAccountName</span><span class="pi">:</span> <span class="s">default</span>
  <span class="na">nodeName</span><span class="pi">:</span> <span class="s">specific-node</span>  <span class="c1"># Manual scheduling</span>
  <span class="na">nodeSelector</span><span class="pi">:</span>            <span class="c1"># Node selection by labels</span>
    <span class="na">disktype</span><span class="pi">:</span> <span class="s">ssd</span>
</code></pre></div></div>

<h3 id="container-spec-deep-dive"><a href="#container-spec-deep-dive"></a>Container Spec Deep Dive</h3>

<p>The container definition is the heart of a Pod spec:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">containers</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">nginx</span>                        <span class="c1"># Required: container name</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">nginx:1.19</span>                  <span class="c1"># Required: image to run</span>
  
  <span class="c1"># Command and arguments</span>
  <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">/bin/sh"</span><span class="pi">]</span>               <span class="c1"># Override ENTRYPOINT</span>
  <span class="na">args</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">-c"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">echo</span><span class="nv"> </span><span class="s">hello"</span><span class="pi">]</span>         <span class="c1"># Override CMD</span>
  
  <span class="c1"># Environment variables</span>
  <span class="na">env</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">DB_HOST</span>
    <span class="na">value</span><span class="pi">:</span> <span class="s2">"</span><span class="s">mysql.default.svc"</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">DB_PASSWORD</span>
    <span class="na">valueFrom</span><span class="pi">:</span>
      <span class="na">secretKeyRef</span><span class="pi">:</span>
        <span class="na">name</span><span class="pi">:</span> <span class="s">db-secret</span>
        <span class="na">key</span><span class="pi">:</span> <span class="s">password</span>
  
  <span class="c1"># Port definitions</span>
  <span class="na">ports</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">http</span>
    <span class="na">containerPort</span><span class="pi">:</span> <span class="m">80</span>
    <span class="na">protocol</span><span class="pi">:</span> <span class="s">TCP</span>
  
  <span class="c1"># Resource management</span>
  <span class="na">resources</span><span class="pi">:</span>
    <span class="na">requests</span><span class="pi">:</span>                        <span class="c1"># Minimum guaranteed</span>
      <span class="na">memory</span><span class="pi">:</span> <span class="s2">"</span><span class="s">128Mi"</span>
      <span class="na">cpu</span><span class="pi">:</span> <span class="s2">"</span><span class="s">100m"</span>
    <span class="na">limits</span><span class="pi">:</span>                          <span class="c1"># Maximum allowed</span>
      <span class="na">memory</span><span class="pi">:</span> <span class="s2">"</span><span class="s">256Mi"</span>
      <span class="na">cpu</span><span class="pi">:</span> <span class="s2">"</span><span class="s">200m"</span>
  
  <span class="c1"># Volume mounts</span>
  <span class="na">volumeMounts</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">data</span>
    <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/var/data</span>
    <span class="na">readOnly</span><span class="pi">:</span> <span class="kc">false</span>
  
  <span class="c1"># Health checks</span>
  <span class="na">livenessProbe</span><span class="pi">:</span>
    <span class="na">httpGet</span><span class="pi">:</span>
      <span class="na">path</span><span class="pi">:</span> <span class="s">/health</span>
      <span class="na">port</span><span class="pi">:</span> <span class="m">80</span>
    <span class="na">initialDelaySeconds</span><span class="pi">:</span> <span class="m">10</span>
    <span class="na">periodSeconds</span><span class="pi">:</span> <span class="m">5</span>
  
  <span class="na">readinessProbe</span><span class="pi">:</span>
    <span class="na">httpGet</span><span class="pi">:</span>
      <span class="na">path</span><span class="pi">:</span> <span class="s">/ready</span>
      <span class="na">port</span><span class="pi">:</span> <span class="m">80</span>
    <span class="na">initialDelaySeconds</span><span class="pi">:</span> <span class="m">5</span>
    <span class="na">periodSeconds</span><span class="pi">:</span> <span class="m">3</span>
  
  <span class="c1"># Security settings</span>
  <span class="na">securityContext</span><span class="pi">:</span>
    <span class="na">runAsUser</span><span class="pi">:</span> <span class="m">1000</span>
    <span class="na">runAsNonRoot</span><span class="pi">:</span> <span class="kc">true</span>
    <span class="na">readOnlyRootFilesystem</span><span class="pi">:</span> <span class="kc">true</span>
</code></pre></div></div>

<hr />

<h2 id="5-multi-container-pods"><a href="#5-multi-container-pods"></a>5. Multi-Container Pods</h2>

<h3 id="when-and-why-to-use-multi-container-pods"><a href="#when-and-why-to-use-multi-container-pods"></a>When and Why to Use Multi-Container Pods</h3>

<p>The general rule is: <strong>one container per Pod</strong>. But there are legitimate cases for multiple containers:</p>

<p><strong>Use Multi-Container Pods When:</strong></p>

<ul>
  <li>
    <p>Containers are tightly coupled and must share resources</p>
  </li>
  <li>
    <p>One container enhances/supports another</p>
  </li>
  <li>
    <p>Containers must run on the same node</p>
  </li>
  <li>
    <p>They need to communicate via <a href="http://localhost">localhost</a></p>
  </li>
  <li>
    <p>They share the same lifecycle</p>
  </li>
</ul>

<p><strong>Don’t Use Multi-Container Pods When:</strong></p>

<ul>
  <li>
    <p>Containers scale independently</p>
  </li>
  <li>
    <p>Containers have different lifecycle needs</p>
  </li>
  <li>
    <p>They could run on different nodes</p>
  </li>
  <li>
    <p>Communication can happen over the network</p>
  </li>
</ul>

<h3 id="how-multi-container-pods-work"><a href="#how-multi-container-pods-work"></a>How Multi-Container Pods Work</h3>

<p>All containers in a Pod share:</p>

<p><strong>1. Network Namespace</strong></p>

<pre><code class="language-mermaid">flowchart TB
    subgraph POD["Pod: my-app  —  IP: 10.244.1.15"]
        A["Container A&lt;br/&gt;Listens on :8080"]
        B["Container B&lt;br/&gt;Listens on :9090"]
        A &lt;--&gt;|"A reaches B at localhost:9090&lt;br/&gt;B reaches A at localhost:8080"| B
    end
    EXT["External communication"] --&gt;|"to either container&lt;br/&gt;uses 10.244.1.15"| POD
</code></pre>

<p><strong>2. Shared Volumes</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Pod</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">shared-volume-pod</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="na">containers</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">writer</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">busybox</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">while</span><span class="nv"> </span><span class="s">true;</span><span class="nv"> </span><span class="s">do</span><span class="nv"> </span><span class="s">date</span><span class="nv"> </span><span class="s">&gt;&gt;</span><span class="nv"> </span><span class="s">/shared/log.txt;</span><span class="nv"> </span><span class="s">sleep</span><span class="nv"> </span><span class="s">5;</span><span class="nv"> </span><span class="s">done'</span><span class="pi">]</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">shared-data</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/shared</span>
  
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">reader</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">busybox</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">tail</span><span class="nv"> </span><span class="s">-f</span><span class="nv"> </span><span class="s">/shared/log.txt'</span><span class="pi">]</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">shared-data</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/shared</span>
  
  <span class="na">volumes</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">shared-data</span>
    <span class="na">emptyDir</span><span class="pi">:</span> <span class="pi">{}</span>
</code></pre></div></div>

<p>In this example:</p>

<ul>
  <li>
    <p><code class="language-plaintext highlighter-rouge">writer</code> appends timestamps to <code class="language-plaintext highlighter-rouge">/shared/log.txt</code></p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">reader</code> continuously reads from the same file</p>
  </li>
  <li>
    <p>Both see the same filesystem at <code class="language-plaintext highlighter-rouge">/shared</code></p>
  </li>
</ul>

<p><strong>3. Same Node</strong></p>

<p>The scheduler places the entire Pod on one node. You’re guaranteed both containers run on the same machine.</p>

<h3 id="lifecycle-behavior"><a href="#lifecycle-behavior"></a>Lifecycle Behavior</h3>

<p><strong>Startup Order:</strong></p>

<ol>
  <li>
    <p>All init containers run first (sequentially)</p>
  </li>
  <li>
    <p>All main containers start simultaneously</p>
  </li>
  <li>
    <p>There’s no guaranteed order among main containers</p>
  </li>
</ol>

<p><strong>If One Container Crashes:</strong></p>

<ul>
  <li>
    <p>The crashed container is restarted (based on restartPolicy)</p>
  </li>
  <li>
    <p>Other containers keep running</p>
  </li>
  <li>
    <p>The Pod status reflects the issue</p>
  </li>
  <li>
    <p>If crashes continue, you see CrashLoopBackOff</p>
  </li>
</ul>

<p><strong>Example: Handling Container Dependencies</strong></p>

<p>If container B depends on container A being ready, use readiness probes:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">containers</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">database</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">postgres</span>
  <span class="na">readinessProbe</span><span class="pi">:</span>
    <span class="na">tcpSocket</span><span class="pi">:</span>
      <span class="na">port</span><span class="pi">:</span> <span class="m">5432</span>
    <span class="na">initialDelaySeconds</span><span class="pi">:</span> <span class="m">5</span>
    <span class="na">periodSeconds</span><span class="pi">:</span> <span class="m">5</span>

<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">app</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">myapp</span>
  <span class="c1"># App should handle DB not being ready initially</span>
  <span class="c1"># or use an init container to wait</span>
</code></pre></div></div>

<h3 id="practical-multi-container-example"><a href="#practical-multi-container-example"></a>Practical Multi-Container Example</h3>

<p><strong>Log shipping pattern:</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Pod</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">app-with-logging</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="na">containers</span><span class="pi">:</span>
  <span class="c1"># Main application</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">app</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">myapp:latest</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">logs</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/var/log/app</span>
  
  <span class="c1"># Sidecar that ships logs</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">log-shipper</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">fluentd:latest</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">logs</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/var/log/app</span>
      <span class="na">readOnly</span><span class="pi">:</span> <span class="kc">true</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">fluentd-config</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/fluentd/etc</span>
  
  <span class="na">volumes</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">logs</span>
    <span class="na">emptyDir</span><span class="pi">:</span> <span class="pi">{}</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">fluentd-config</span>
    <span class="na">configMap</span><span class="pi">:</span>
      <span class="na">name</span><span class="pi">:</span> <span class="s">fluentd-config</span>
</code></pre></div></div>

<hr />

<h2 id="6-init-containers"><a href="#6-init-containers"></a>6. Init Containers</h2>

<h3 id="what-are-init-containers"><a href="#what-are-init-containers"></a>What Are Init Containers?</h3>

<p>Init containers are specialized containers that run <strong>before</strong> your main application containers start. They run to completion, one at a time, in order.</p>

<p><strong>Key Characteristics:</strong></p>

<ul>
  <li>
    <p>Run sequentially, not in parallel</p>
  </li>
  <li>
    <p>Each must complete successfully before the next starts</p>
  </li>
  <li>
    <p>If any fails, the Pod restarts (based on restartPolicy)</p>
  </li>
  <li>
    <p>Only after ALL init containers succeed do main containers start</p>
  </li>
  <li>
    <p>Can have different images than main containers</p>
  </li>
  <li>
    <p>Don’t support readiness probes (they’re not long-running)</p>
  </li>
</ul>

<h3 id="init-container-lifecycle"><a href="#init-container-lifecycle"></a>Init Container Lifecycle</h3>

<pre><code class="language-mermaid">flowchart TD
    PC["Pod Created"] --&gt; I1

    subgraph I1["Init Container 1 — Running"]
    end
    I1 --&gt;|"Exit 0"| I2

    subgraph I2["Init Container 2 — Running"]
    end
    I2 --&gt;|"Exit 0"| I3

    subgraph I3["Init Container 3 — Running"]
    end
    I3 --&gt;|"Exit 0"| MAIN

    subgraph MAIN["Main Containers&lt;br/&gt;(all start simultaneously)"]
    end
</code></pre>

<h3 id="common-use-cases"><a href="#common-use-cases"></a>Common Use Cases</h3>

<p><strong>1. Wait for a Dependency</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">initContainers</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">wait-for-database</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">busybox</span>
  <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> 
    <span class="s1">'</span><span class="s">until</span><span class="nv"> </span><span class="s">nc</span><span class="nv"> </span><span class="s">-z</span><span class="nv"> </span><span class="s">database-service</span><span class="nv"> </span><span class="s">5432;</span><span class="nv"> </span><span class="s">do</span> 
       <span class="s">echo</span><span class="nv"> </span><span class="s">"Waiting</span><span class="nv"> </span><span class="s">for</span><span class="nv"> </span><span class="s">database...";</span> 
       <span class="s">sleep</span><span class="nv"> </span><span class="s">2;</span> 
     <span class="s">done;</span> 
     <span class="s">echo</span><span class="nv"> </span><span class="s">"Database</span><span class="nv"> </span><span class="s">is</span><span class="nv"> </span><span class="s">ready"'</span><span class="pi">]</span>
</code></pre></div></div>

<p>This ensures your app doesn’t start until the database is reachable.</p>

<p><strong>2. Clone Code or Configuration</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">initContainers</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">clone-repo</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">alpine/git</span>
  <span class="na">command</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="s">git</span>
  <span class="pi">-</span> <span class="s">clone</span>
  <span class="pi">-</span> <span class="s">--depth=1</span>
  <span class="pi">-</span> <span class="s">https://github.com/company/config.git</span>
  <span class="pi">-</span> <span class="s">/config</span>
  <span class="na">volumeMounts</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">config</span>
    <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/config</span>
<span class="na">containers</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">app</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">myapp</span>
  <span class="na">volumeMounts</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">config</span>
    <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/app/config</span>
<span class="na">volumes</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">config</span>
  <span class="na">emptyDir</span><span class="pi">:</span> <span class="pi">{}</span>
</code></pre></div></div>

<p><strong>3. Setup File Permissions</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">initContainers</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">fix-permissions</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">busybox</span>
  <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">chown</span><span class="nv"> </span><span class="s">-R</span><span class="nv"> </span><span class="s">1000:1000</span><span class="nv"> </span><span class="s">/data'</span><span class="pi">]</span>
  <span class="na">volumeMounts</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">data</span>
    <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/data</span>
  <span class="na">securityContext</span><span class="pi">:</span>
    <span class="na">runAsUser</span><span class="pi">:</span> <span class="m">0</span>  <span class="c1"># Run as root to change ownership</span>
</code></pre></div></div>

<p><strong>4. Generate Configuration</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">initContainers</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">generate-config</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">busybox</span>
  <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">echo</span><span class="nv"> </span><span class="s">"server_id=$(hostname)"</span><span class="nv"> </span><span class="s">&gt;</span><span class="nv"> </span><span class="s">/config/server.conf'</span><span class="pi">]</span>
  <span class="na">volumeMounts</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">config</span>
    <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/config</span>
</code></pre></div></div>

<p><strong>5. Database Migrations</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">initContainers</span><span class="pi">:</span>
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">db-migrate</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">myapp:latest</span>
  <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">./migrate.sh'</span><span class="pi">]</span>
  <span class="na">env</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">DATABASE_URL</span>
    <span class="na">valueFrom</span><span class="pi">:</span>
      <span class="na">secretKeyRef</span><span class="pi">:</span>
        <span class="na">name</span><span class="pi">:</span> <span class="s">db-credentials</span>
        <span class="na">key</span><span class="pi">:</span> <span class="s">url</span>
</code></pre></div></div>

<h3 id="complete-init-container-example"><a href="#complete-init-container-example"></a>Complete Init Container Example</h3>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Pod</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">myapp-pod</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="na">initContainers</span><span class="pi">:</span>
  <span class="c1"># First: wait for database</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">wait-db</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">busybox:1.35</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">until</span><span class="nv"> </span><span class="s">nc</span><span class="nv"> </span><span class="s">-z</span><span class="nv"> </span><span class="s">db-service</span><span class="nv"> </span><span class="s">3306;</span><span class="nv"> </span><span class="s">do</span><span class="nv"> </span><span class="s">sleep</span><span class="nv"> </span><span class="s">2;</span><span class="nv"> </span><span class="s">done'</span><span class="pi">]</span>
  
  <span class="c1"># Second: wait for cache</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">wait-cache</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">busybox:1.35</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">until</span><span class="nv"> </span><span class="s">nc</span><span class="nv"> </span><span class="s">-z</span><span class="nv"> </span><span class="s">redis-service</span><span class="nv"> </span><span class="s">6379;</span><span class="nv"> </span><span class="s">do</span><span class="nv"> </span><span class="s">sleep</span><span class="nv"> </span><span class="s">2;</span><span class="nv"> </span><span class="s">done'</span><span class="pi">]</span>
  
  <span class="c1"># Third: download configuration</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">download-config</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">curlimages/curl:latest</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">curl</span><span class="nv"> </span><span class="s">-o</span><span class="nv"> </span><span class="s">/config/app.json</span><span class="nv"> </span><span class="s">http://config-service/config'</span><span class="pi">]</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">config</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/config</span>
  
  <span class="na">containers</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">app</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">myapp:v2</span>
    <span class="na">ports</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">containerPort</span><span class="pi">:</span> <span class="m">8080</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">config</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/app/config</span>
    <span class="na">env</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">CONFIG_PATH</span>
      <span class="na">value</span><span class="pi">:</span> <span class="s2">"</span><span class="s">/app/config/app.json"</span>
  
  <span class="na">volumes</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">config</span>
    <span class="na">emptyDir</span><span class="pi">:</span> <span class="pi">{}</span>
</code></pre></div></div>

<h3 id="debugging-init-containers"><a href="#debugging-init-containers"></a>Debugging Init Containers</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># See init container status</span>
kubectl get pod myapp-pod

<span class="c"># Output might show:</span>
<span class="c"># NAME        READY   STATUS     RESTARTS   AGE</span>
<span class="c"># myapp-pod   0/1     Init:1/3   0          30s</span>

<span class="c"># This means: 1 of 3 init containers completed</span>

<span class="c"># Get logs from specific init container</span>
kubectl logs myapp-pod <span class="nt">-c</span> wait-db

<span class="c"># If init container is currently running:</span>
kubectl logs myapp-pod <span class="nt">-c</span> wait-cache

<span class="c"># Describe pod to see init container details</span>
kubectl describe pod myapp-pod
</code></pre></div></div>

<p><strong>Init Status Meanings:</strong></p>

<table>
  <thead>
    <tr>
      <th>Status</th>
      <th>Meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Init:0/3</code></td>
      <td>0 of 3 init containers completed</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Init:1/3</code></td>
      <td>1 of 3 completed, second running</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Init:Error</code></td>
      <td>Current init container failed</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Init:CrashLoopBackOff</code></td>
      <td>Init container keeps crashing</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">PodInitializing</code></td>
      <td>All init containers done, main starting</td>
    </tr>
  </tbody>
</table>

<hr />

<h2 id="7-static-pods"><a href="#7-static-pods"></a>7. Static Pods</h2>

<h3 id="what-are-static-pods"><a href="#what-are-static-pods"></a>What Are Static Pods?</h3>

<p>Static Pods are managed directly by the kubelet on a specific node, without any involvement from the Kubernetes API server, scheduler, or controller manager.</p>

<p><strong>The key difference:</strong></p>

<ul>
  <li>
    <p>Normal Pods: API server → Scheduler → Kubelet</p>
  </li>
  <li>
    <p>Static Pods: Kubelet watches a directory → Creates Pod directly</p>
  </li>
</ul>

<h3 id="how-static-pods-work"><a href="#how-static-pods-work"></a>How Static Pods Work</h3>

<pre><code class="language-mermaid">flowchart LR
    subgraph NORMAL["Normal Pod Flow"]
        direction LR
        N1["kubectl apply"] --&gt; N2["API Server (etcd)"] --&gt; N3["Scheduler"] --&gt; N4["Kubelet"]
    end
</code></pre>

<pre><code class="language-mermaid">flowchart TD
    subgraph NODE["Node"]
        MAN["/etc/kubernetes/manifests/&lt;br/&gt;├── etcd.yaml&lt;br/&gt;├── kube-apiserver.yaml&lt;br/&gt;└── kube-scheduler.yaml&lt;br/&gt;&lt;i&gt;(You put files here)&lt;/i&gt;"]
        MAN --&gt;|"Kubelet watches&lt;br/&gt;this directory"| KUBELET["Kubelet&lt;br/&gt;&lt;br/&gt;Automatically creates and&lt;br/&gt;manages Pods from manifests"]
    end
</code></pre>

<h3 id="why-do-static-pods-exist"><a href="#why-do-static-pods-exist"></a>Why Do Static Pods Exist?</h3>

<p><strong>The Bootstrap Problem:</strong></p>

<p>When a Kubernetes cluster starts, you face a chicken-and-egg problem:</p>

<ul>
  <li>
    <p>The API server is a container that needs to be scheduled</p>
  </li>
  <li>
    <p>But the scheduler is also a container that needs the API server</p>
  </li>
  <li>
    <p>And etcd (the database) is also a container</p>
  </li>
</ul>

<p>Static Pods solve this. The control plane components run as static Pods managed by kubelet directly, without needing the full cluster to be running.</p>

<p><strong>On a master node, you typically find:</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/etc/kubernetes/manifests/
├── etcd.yaml
├── kube-apiserver.yaml
├── kube-controller-manager.yaml
└── kube-scheduler.yaml
</code></pre></div></div>

<h3 id="characteristics-of-static-pods"><a href="#characteristics-of-static-pods"></a>Characteristics of Static Pods</h3>

<table>
  <thead>
    <tr>
      <th>Aspect</th>
      <th>Static Pod Behavior</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Creation</td>
      <td>Kubelet creates when manifest appears in watched directory</td>
    </tr>
    <tr>
      <td>Deletion</td>
      <td>Kubelet deletes when manifest is removed</td>
    </tr>
    <tr>
      <td>Updates</td>
      <td>Kubelet updates when manifest file changes</td>
    </tr>
    <tr>
      <td>API visibility</td>
      <td>A mirror Pod appears in API (read-only)</td>
    </tr>
    <tr>
      <td>Scheduling</td>
      <td>No scheduling—runs on the node where manifest exists</td>
    </tr>
    <tr>
      <td>Pod naming</td>
      <td>Node name is appended: <code class="language-plaintext highlighter-rouge">my-pod-node01</code></td>
    </tr>
    <tr>
      <td>Control via kubectl</td>
      <td>Cannot delete via API (recreates immediately)</td>
    </tr>
  </tbody>
</table>

<h3 id="finding-the-static-pod-directory"><a href="#finding-the-static-pod-directory"></a>Finding the Static Pod Directory</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Check kubelet configuration</span>
<span class="nb">cat</span> /var/lib/kubelet/config.yaml | <span class="nb">grep </span>staticPodPath

<span class="c"># Or</span>
ps aux | <span class="nb">grep </span>kubelet | <span class="nb">grep</span> <span class="nt">--</span> <span class="nt">--pod-manifest-path</span>

<span class="c"># Common locations:</span>
<span class="c"># /etc/kubernetes/manifests/</span>
<span class="c"># /etc/kubelet.d/</span>
</code></pre></div></div>

<h3 id="creating-a-static-pod"><a href="#creating-a-static-pod"></a>Creating a Static Pod</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># 1. Create a manifest file</span>
<span class="nb">cat</span> <span class="o">&lt;&lt;</span><span class="no">EOF</span><span class="sh"> &gt; /etc/kubernetes/manifests/static-nginx.yaml
apiVersion: v1
kind: Pod
metadata:
  name: static-nginx
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 80
</span><span class="no">EOF

</span><span class="c"># 2. Kubelet automatically creates it</span>
<span class="c"># Wait a few seconds...</span>

<span class="c"># 3. Verify</span>
kubectl get pods
<span class="c"># Shows: static-nginx-&lt;node-name&gt;</span>

<span class="c"># 4. Try to delete it</span>
kubectl delete pod static-nginx-&lt;node-name&gt;
<span class="c"># Pod immediately recreates!</span>

<span class="c"># 5. Actually delete it by removing the file</span>
<span class="nb">rm</span> /etc/kubernetes/manifests/static-nginx.yaml
<span class="c"># Now it's gone</span>
</code></pre></div></div>

<h3 id="mirror-pods"><a href="#mirror-pods"></a>Mirror Pods</h3>

<p>When kubelet creates a static Pod, it also creates a “mirror Pod” in the API server. This is read-only and lets you see the static Pod via <code class="language-plaintext highlighter-rouge">kubectl get pods</code>.</p>

<p><strong>Mirror Pod characteristics:</strong></p>

<ul>
  <li>
    <p>Has annotation: <a href="http://kubernetes.io/config.mirror"><code class="language-plaintext highlighter-rouge">kubernetes.io/config.mirror</code></a></p>
  </li>
  <li>
    <p>Cannot be modified via API</p>
  </li>
  <li>
    <p>Deleting it via kubectl does nothing (kubelet recreates)</p>
  </li>
  <li>
    <p>Reflects the real Pod’s status</p>
  </li>
</ul>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Identify a mirror pod</span>
kubectl get pod static-nginx-node01 <span class="nt">-o</span> yaml | <span class="nb">grep</span> <span class="nt">-A2</span> annotations
<span class="c"># annotations:</span>
<span class="c">#   kubernetes.io/config.mirror: "..."</span>
</code></pre></div></div>

<h3 id="ckad-relevance"><a href="#ckad-relevance"></a>CKAD Relevance</h3>

<p>For CKAD, you need to know:</p>

<ul>
  <li>
    <p>What static Pods are</p>
  </li>
  <li>
    <p>How to identify them</p>
  </li>
  <li>
    <p>Where manifests are stored</p>
  </li>
  <li>
    <p>That you can’t manage them via kubectl</p>
  </li>
</ul>

<p>You probably won’t create static Pods in the exam, but you might be asked to identify them or understand why a Pod keeps recreating after deletion.</p>

<hr />

<h2 id="8-pod-design-patterns"><a href="#8-pod-design-patterns"></a>8. Pod Design Patterns</h2>

<p>These patterns describe standard ways to structure multi-container Pods. They come from distributed systems design and solve common problems.</p>

<h3 id="pattern-1-sidecar"><a href="#pattern-1-sidecar"></a>Pattern 1: Sidecar</h3>

<p><strong>Purpose:</strong> Extend or enhance the main container’s functionality without modifying it.</p>

<p><strong>The Sidecar Analogy:</strong></p>

<p>Think of a motorcycle with a sidecar. The motorcycle (main container) does the primary work—driving. The sidecar (sidecar container) adds capability—carrying a passenger or cargo. They move together, share the journey, but have different jobs.</p>

<pre><code class="language-mermaid">flowchart LR
    subgraph POD["POD"]
        MAIN["Main Container&lt;br/&gt;- Business logic&lt;br/&gt;- Writes logs to&lt;br/&gt;&amp;nbsp;&amp;nbsp;/logs volume"]
        SIDE["Sidecar Container&lt;br/&gt;- Log shipping&lt;br/&gt;- Watches /logs&lt;br/&gt;- Ships to ELK"]
        MAIN --&gt;|writes| VOL["Shared Volume&lt;br/&gt;(/logs)"]
        VOL --&gt;|reads| SIDE
    end
</code></pre>

<p><strong>Common Sidecar Use Cases:</strong></p>

<table>
  <thead>
    <tr>
      <th>Use Case</th>
      <th>Main Container</th>
      <th>Sidecar</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Logging</td>
      <td>App writes logs</td>
      <td>Fluentd ships logs</td>
    </tr>
    <tr>
      <td>Monitoring</td>
      <td>App runs</td>
      <td>Prometheus exporter</td>
    </tr>
    <tr>
      <td>Security</td>
      <td>App serves traffic</td>
      <td>mTLS proxy (Istio)</td>
    </tr>
    <tr>
      <td>Sync</td>
      <td>App uses config</td>
      <td>Git-sync updates config</td>
    </tr>
    <tr>
      <td>Compression</td>
      <td>App serves files</td>
      <td>Compressor processes uploads</td>
    </tr>
  </tbody>
</table>

<p><strong>Complete Sidecar Example: Log Collection</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Pod</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">app-with-log-sidecar</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="na">containers</span><span class="pi">:</span>
  <span class="c1"># Main application</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">app</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">myapp:latest</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">while</span><span class="nv"> </span><span class="s">true;</span><span class="nv"> </span><span class="s">do</span><span class="nv"> </span><span class="s">echo</span><span class="nv"> </span><span class="s">"$(date)</span><span class="nv"> </span><span class="s">-</span><span class="nv"> </span><span class="s">App</span><span class="nv"> </span><span class="s">running"</span><span class="nv"> </span><span class="s">&gt;&gt;</span><span class="nv"> </span><span class="s">/var/log/app/app.log;</span><span class="nv"> </span><span class="s">sleep</span><span class="nv"> </span><span class="s">5;</span><span class="nv"> </span><span class="s">done'</span><span class="pi">]</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">log-volume</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/var/log/app</span>
  
  <span class="c1"># Sidecar: ships logs to external system</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">log-shipper</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">busybox</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s1">'</span><span class="s">sh'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">-c'</span><span class="pi">,</span> <span class="s1">'</span><span class="s">tail</span><span class="nv"> </span><span class="s">-f</span><span class="nv"> </span><span class="s">/var/log/app/app.log'</span><span class="pi">]</span>  <span class="c1"># Simplified; real would send to logging system</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">log-volume</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/var/log/app</span>
      <span class="na">readOnly</span><span class="pi">:</span> <span class="kc">true</span>
  
  <span class="na">volumes</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">log-volume</span>
    <span class="na">emptyDir</span><span class="pi">:</span> <span class="pi">{}</span>
</code></pre></div></div>

<p><strong>Real-World Sidecar: Service Mesh (Istio)</strong></p>

<p>In Istio, every Pod gets an Envoy proxy sidecar automatically:</p>

<pre><code class="language-mermaid">flowchart LR
    subgraph POD["POD"]
        APP["Your App&lt;br/&gt;Listens on&lt;br/&gt;localhost:8080&lt;br/&gt;&lt;br/&gt;No security&lt;br/&gt;code needed!"]
        ENVOY["Envoy Sidecar&lt;br/&gt;- mTLS encryption&lt;br/&gt;- Traffic management&lt;br/&gt;- Observability&lt;br/&gt;- Circuit breaking"]
        APP &lt;--&gt; ENVOY
    end
    ENVOY --&gt;|"All external traffic&lt;br/&gt;goes through Envoy"| EXT["External Traffic"]
</code></pre>

<h3 id="pattern-2-ambassador"><a href="#pattern-2-ambassador"></a>Pattern 2: Ambassador</h3>

<p><strong>Purpose:</strong> Proxy outbound connections from the main container, simplifying how the app connects to external services.</p>

<p><strong>The Ambassador Analogy:</strong></p>

<p>An ambassador represents you in a foreign country. They handle the complexity of diplomacy, translation, and protocol. Your main container just talks to the ambassador (<a href="http://localhost">localhost</a>), and the ambassador handles the complex external communication.</p>

<pre><code class="language-mermaid">flowchart LR
    subgraph POD["POD"]
        MAIN["Main Container&lt;br/&gt;Connects to&lt;br/&gt;localhost:5432&lt;br/&gt;&lt;br/&gt;Simple config:&lt;br/&gt;DB_HOST=localhost&lt;br/&gt;DB_PORT=5432"]
        AMB["Ambassador&lt;br/&gt;localhost:5432&lt;br/&gt;&lt;br/&gt;Handles:&lt;br/&gt;- Service discovery&lt;br/&gt;- Load balancing&lt;br/&gt;- Failover&lt;br/&gt;- Connection pooling"]
        MAIN --&gt; AMB
    end
    AMB --&gt; DB["Database Cluster&lt;br/&gt;- Primary&lt;br/&gt;- Replica 1&lt;br/&gt;- Replica 2"]
</code></pre>

<p><strong>Why Use Ambassador Pattern:</strong></p>

<p>Without ambassador:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># App needs complex logic
</span><span class="n">db</span> <span class="o">=</span> <span class="nf">connect_with_retry</span><span class="p">(</span>
    <span class="n">hosts</span><span class="o">=</span><span class="p">[</span><span class="sh">'</span><span class="s">db-1.prod</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">db-2.prod</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">db-3.prod</span><span class="sh">'</span><span class="p">],</span>
    <span class="n">load_balance</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">ssl</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="bp">...</span>
<span class="p">)</span>
</code></pre></div></div>

<p>With ambassador:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># App has simple logic
</span><span class="n">db</span> <span class="o">=</span> <span class="nf">connect</span><span class="p">(</span><span class="sh">'</span><span class="s">localhost:5432</span><span class="sh">'</span><span class="p">)</span>  <span class="c1"># Ambassador handles everything
</span></code></pre></div></div>

<p><strong>Ambassador Example: Database Proxy</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Pod</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">app-with-ambassador</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="na">containers</span><span class="pi">:</span>
  <span class="c1"># Main app - connects to localhost</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">app</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">myapp:latest</span>
    <span class="na">env</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">DATABASE_HOST</span>
      <span class="na">value</span><span class="pi">:</span> <span class="s2">"</span><span class="s">localhost"</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">DATABASE_PORT</span>
      <span class="na">value</span><span class="pi">:</span> <span class="s2">"</span><span class="s">5432"</span>
  
  <span class="c1"># Ambassador - proxies to real database</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">db-ambassador</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">haproxy:latest</span>
    <span class="na">ports</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">containerPort</span><span class="pi">:</span> <span class="m">5432</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">haproxy-config</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/usr/local/etc/haproxy</span>
  
  <span class="na">volumes</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">haproxy-config</span>
    <span class="na">configMap</span><span class="pi">:</span>
      <span class="na">name</span><span class="pi">:</span> <span class="s">db-proxy-config</span>
</code></pre></div></div>

<p><strong>Common Ambassador Use Cases:</strong></p>

<table>
  <thead>
    <tr>
      <th>Scenario</th>
      <th>Ambassador Does</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Database cluster</td>
      <td>Routes to correct shard, handles failover</td>
    </tr>
    <tr>
      <td>Redis cluster</td>
      <td>Manages cluster topology, routes by key</td>
    </tr>
    <tr>
      <td>External APIs</td>
      <td>Handles retries, rate limiting, auth</td>
    </tr>
    <tr>
      <td>Legacy systems</td>
      <td>Protocol translation</td>
    </tr>
  </tbody>
</table>

<h3 id="pattern-3-adapter"><a href="#pattern-3-adapter"></a>Pattern 3: Adapter</h3>

<p><strong>Purpose:</strong> Transform the main container’s output into a format that external systems expect.</p>

<p><strong>The Adapter Analogy:</strong></p>

<p>Think of a power adapter. Your laptop (main container) outputs one type of power/data. The adapter transforms it to what the wall socket (external system) expects. The main container doesn’t need to know about the external system’s requirements.</p>

<pre><code class="language-mermaid">flowchart LR
    subgraph POD["POD"]
        MAIN["Main Container&lt;br/&gt;Outputs custom&lt;br/&gt;log format&lt;br/&gt;&lt;br/&gt;2024-01-15 ERROR&lt;br/&gt;User login failed"]
        ADAPT["Adapter&lt;br/&gt;Reads custom format&lt;br/&gt;Converts to JSON&lt;br/&gt;&lt;br/&gt;{'time':'2024...',&lt;br/&gt;&amp;nbsp;'level':'ERROR',&lt;br/&gt;&amp;nbsp;'msg':'User...'}"]
        MAIN --&gt;|writes to| VOL["Shared Volume"]
        VOL --&gt;|reads from| ADAPT
    end
    ADAPT --&gt;|JSON| LOG["Logging System&lt;br/&gt;(expects JSON)"]
</code></pre>

<p><strong>Common Adapter Use Cases:</strong></p>

<table>
  <thead>
    <tr>
      <th>Input (Main Container)</th>
      <th>Output (Adapter)</th>
      <th>Consumer</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Custom log format</td>
      <td>JSON logs</td>
      <td>ELK Stack</td>
    </tr>
    <tr>
      <td>Application metrics</td>
      <td>Prometheus format</td>
      <td>Prometheus</td>
    </tr>
    <tr>
      <td>Custom health check</td>
      <td>HTTP endpoint</td>
      <td>Kubernetes probes</td>
    </tr>
    <tr>
      <td>XML data</td>
      <td>JSON data</td>
      <td>Modern APIs</td>
    </tr>
  </tbody>
</table>

<p><strong>Adapter Example: Prometheus Exporter</strong></p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Pod</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">app-with-metrics-adapter</span>
  <span class="na">annotations</span><span class="pi">:</span>
    <span class="na">prometheus.io/scrape</span><span class="pi">:</span> <span class="s2">"</span><span class="s">true"</span>
    <span class="na">prometheus.io/port</span><span class="pi">:</span> <span class="s2">"</span><span class="s">9090"</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="na">containers</span><span class="pi">:</span>
  <span class="c1"># Main app - writes metrics in custom format</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">app</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">legacy-app:latest</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">metrics</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/var/metrics</span>
  
  <span class="c1"># Adapter - converts to Prometheus format</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">metrics-adapter</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">prom/statsd-exporter:latest</span>
    <span class="na">ports</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">containerPort</span><span class="pi">:</span> <span class="m">9090</span>
      <span class="na">name</span><span class="pi">:</span> <span class="s">metrics</span>
    <span class="na">volumeMounts</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">metrics</span>
      <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/var/metrics</span>
      <span class="na">readOnly</span><span class="pi">:</span> <span class="kc">true</span>
  
  <span class="na">volumes</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">metrics</span>
    <span class="na">emptyDir</span><span class="pi">:</span> <span class="pi">{}</span>
</code></pre></div></div>

<h3 id="comparing-the-patterns"><a href="#comparing-the-patterns"></a>Comparing the Patterns</h3>

<table>
  <thead>
    <tr>
      <th>Pattern</th>
      <th>Direction</th>
      <th>Purpose</th>
      <th>Example</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Sidecar</strong></td>
      <td>Same direction as main</td>
      <td>Enhance/extend main container</td>
      <td>Log shipping, config reload</td>
    </tr>
    <tr>
      <td><strong>Ambassador</strong></td>
      <td>Outbound</td>
      <td>Simplify external connections</td>
      <td>DB proxy, API gateway</td>
    </tr>
    <tr>
      <td><strong>Adapter</strong></td>
      <td>Outbound</td>
      <td>Transform output format</td>
      <td>Metrics conversion</td>
    </tr>
  </tbody>
</table>

<p><strong>Visual Comparison:</strong></p>

<pre><code class="language-mermaid">flowchart LR
    subgraph SC["SIDECAR (enhances)"]
        direction LR
        SM["Main"] --&gt; SS["Sidecar (helps)"] --&gt; SE1["External"]
        SM --&gt; SE2["External"]
    end
</code></pre>

<pre><code class="language-mermaid">flowchart LR
    subgraph AM["AMBASSADOR (proxies outbound)"]
        direction LR
        AMain["Main"] --&gt; AAmb["Ambassador (proxies)"] --&gt; AExt["External"]
    end
</code></pre>

<pre><code class="language-mermaid">flowchart LR
    subgraph AD["ADAPTER (transforms output)"]
        direction LR
        DMain["Main"] --&gt; DAdapt["Adapter (transforms)"] --&gt; DExt["External"]
    end
</code></pre>

<hr />

<h2 id="summary"><a href="#summary"></a>Summary</h2>

<table>
  <thead>
    <tr>
      <th>Topic</th>
      <th>Key Takeaways</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Pod basics</strong></td>
      <td>Smallest deployable unit; wraps containers; provides shared network/storage</td>
    </tr>
    <tr>
      <td><strong>Lifecycle</strong></td>
      <td>Pending → Running → Succeeded/Failed; containers have Waiting/Running/Terminated states</td>
    </tr>
    <tr>
      <td><strong>Restart policies</strong></td>
      <td>Always (services), OnFailure (jobs with retry), Never (one-shot jobs)</td>
    </tr>
    <tr>
      <td><strong>Imperative</strong></td>
      <td><code class="language-plaintext highlighter-rouge">kubectl run</code> — fast, no audit trail, good for quick tasks</td>
    </tr>
    <tr>
      <td><strong>Declarative</strong></td>
      <td>YAML + <code class="language-plaintext highlighter-rouge">kubectl apply</code> — reproducible, version-controlled, production standard</td>
    </tr>
    <tr>
      <td><strong>YAML structure</strong></td>
      <td>apiVersion, kind, metadata, spec — every resource follows this</td>
    </tr>
    <tr>
      <td><strong>Multi-container</strong></td>
      <td>Shared network (<a href="http://localhost">localhost</a>), shared volumes, same lifecycle</td>
    </tr>
    <tr>
      <td><strong>Init containers</strong></td>
      <td>Run before main containers, sequential, must succeed</td>
    </tr>
    <tr>
      <td><strong>Static Pods</strong></td>
      <td>Managed by kubelet directly, used for control plane, mirror pods in API</td>
    </tr>
    <tr>
      <td><strong>Sidecar</strong></td>
      <td>Helper that enhances main container (logs, mesh proxy)</td>
    </tr>
    <tr>
      <td><strong>Ambassador</strong></td>
      <td>Proxy for outbound connections (DB proxy)</td>
    </tr>
    <tr>
      <td><strong>Adapter</strong></td>
      <td>Transforms output format (metrics exporter)</td>
    </tr>
  </tbody>
</table>]]></content><author><name>Arnav Verma</name><email>av4445@nyu.edu</email></author><category term="Kubernetes" /><category term="Containers" /><category term="DevOps" /><category term="Infrastructure" /><summary type="html"><![CDATA[What a Pod actually is, starting from the pause container nobody mentions: the lifecycle and its phases, imperative versus declarative creation, the manifest field by field, and the multi-container patterns worth knowing.]]></summary></entry><entry><title type="html">Building a Semantic Video Search Engine</title><link href="https://namesarnav.com/blog/sv-engine/" rel="alternate" type="text/html" title="Building a Semantic Video Search Engine" /><published>2026-08-02T00:00:00+00:00</published><updated>2026-08-02T00:00:00+00:00</updated><id>https://namesarnav.com/blog/sv-engine</id><content type="html" xml:base="https://namesarnav.com/blog/sv-engine/"><![CDATA[<p><em>Also published on <a href="https://arnavverma.hashnode.dev/building-a-semantic-video-search-engine">arnavverma.hashnode.dev</a>.</em></p>

<p>This is a write-up of <code class="language-plaintext highlighter-rouge">sv-engine</code> , what it does, how it is built, which decisions were made by measurement rather than by argument, and the bugs that were only found because something was measured. It is a small system, roughly 3,000 lines of Python and 1,500 lines of TypeScript, but almost every piece of it exists because a simpler version of it broke in a specific way.</p>

<p>Link for Code: https://github.com/namesarnav/semantic-video-search-engine</p>

<h2 id="1-the-problem"><a href="#1-the-problem"></a>1. The problem</h2>

<p>Video is the least searchable data most people own. A folder of 200 clips is a folder of 200 opaque blobs. The tools that exist mostly search <em>around</em> the video , the filename, the transcript, the description someone typed , not the picture itself.</p>

<p>The question I wanted to answer was the one you actually ask yourself when hunting through footage:</p>

<blockquote>
  <p><em>Where is the bit where someone opens a laptop?</em></p>
</blockquote>

<p>Not “which file is called laptop.mp4”. Not “where does someone say the word laptop”. Where is the <strong>moment that looks like that</strong>.</p>

<p>So the scope was drawn tightly and deliberately:</p>

<ul>
  <li>
    <p><strong>In scope:</strong> visual semantic search. Natural-language query in, ranked (video, timestamp) pairs out, with a thumbnail and a seekable player.</p>
  </li>
  <li>
    <p><strong>Explicitly out of scope:</strong> OCR / text-in-frame, transcript or speech search, audio of any kind. If a change starts pulling toward Whisper, that is a different project.</p>
  </li>
</ul>

<p>That second list matters more than it looks. “Semantic video search” is a phrase that expands to fill any amount of engineering time. Writing down what it is <em>not</em> was what kept the project finishable.</p>

<h3 id="the-targets"><a href="#the-targets"></a>The targets</h3>

<p>Three numbers, agreed before any code:</p>

<table>
  <thead>
    <tr>
      <th>Target</th>
      <th>Value</th>
      <th>Why this one</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Correctness</strong></td>
      <td>a distinctive moment lands in the <strong>top 5</strong></td>
      <td>This is the real metric. Top-50 is not a search engine, it is a haystack.</td>
    </tr>
    <tr>
      <td><strong>Latency</strong></td>
      <td>search p95 &lt; 500ms over hundreds of videos</td>
      <td>Fast enough to feel interactive.</td>
    </tr>
    <tr>
      <td><strong>Storage</strong></td>
      <td>never store every raw frame</td>
      <td>A minute of 30fps 4K is 1,800 frames. That does not scale and mostly stores duplicates.</td>
    </tr>
  </tbody>
</table>

<p>Ingestion throughput was explicitly <em>not</em> a target. A “few videos a day” workflow was the bar. Correctness was the thing worth optimising, and every time those two competed, correctness won.</p>

<hr />

<h2 id="2-the-core-idea-one-shared-embedding-space"><a href="#2-the-core-idea-one-shared-embedding-space"></a>2. The core idea: one shared embedding space</h2>

<p>The whole system rests on a single property of CLIP.</p>

<p>CLIP is trained on image–caption pairs with a contrastive objective, so it learns <strong>two encoders that land in the same vector space</strong>: an image encoder and a text encoder. A picture of a sunset and the string <code class="language-plaintext highlighter-rouge">"a sunset"</code> end up as nearby vectors. That is not a coincidence of the architecture, it is the training objective.</p>

<p>Which means the entire search engine is this:</p>

<p><strong>Ingest path</strong></p>

<p><img src="https://cdn.hashnode.com/uploads/covers/6557ff28afe2c15e65f8d100/52b66d87-7a89-4018-b7c0-52677f03defd.png align=&quot;center&quot;" alt="" /></p>

<p><strong>Query path</strong></p>

<p><img src="https://cdn.hashnode.com/uploads/covers/6557ff28afe2c15e65f8d100/0bc2b7f9-68ca-46fc-aac5-e43ef5d53acb.png align=&quot;center&quot;" alt="" /></p>

<p>Two pipelines, one vector space, and the space is what makes comparing words to pictures meaningful at all. Everything else in this document is plumbing around that one idea , but the plumbing is where all the interesting failures live.</p>

<p>One implementation detail that saves a step: every vector is <strong>L2-normalised on the way out of the embedder</strong>. That makes FAISS inner-product search exactly equivalent to cosine similarity, so <code class="language-plaintext highlighter-rouge">IndexFlatIP</code> does the right thing with no extra work at query time.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">_normalize</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">tensor</span><span class="p">:</span> <span class="n">torch</span><span class="p">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">np</span><span class="p">.</span><span class="n">ndarray</span><span class="p">:</span>
    <span class="n">tensor</span> <span class="o">=</span> <span class="n">tensor</span> <span class="o">/</span> <span class="n">tensor</span><span class="p">.</span><span class="nf">norm</span><span class="p">(</span><span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">,</span> <span class="n">keepdim</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">tensor</span><span class="p">.</span><span class="nf">cpu</span><span class="p">().</span><span class="nf">numpy</span><span class="p">().</span><span class="nf">astype</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">float32</span><span class="p">)</span>
</code></pre></div></div>

<hr />

<h2 id="3-the-stack-and-why-each-piece"><a href="#3-the-stack-and-why-each-piece"></a>3. The stack, and why each piece</h2>

<table>
  <thead>
    <tr>
      <th>Component</th>
      <th>Choice</th>
      <th>Why</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Embedding</td>
      <td>CLIP ViT-B/32 via <code class="language-plaintext highlighter-rouge">open_clip</code></td>
      <td>joint image/text space; the whole trick</td>
    </tr>
    <tr>
      <td>Vector index</td>
      <td>FAISS, flat (<code class="language-plaintext highlighter-rouge">IndexFlatIP</code>)</td>
      <td>in-process, no extra service, exact search</td>
    </tr>
    <tr>
      <td>Metadata</td>
      <td>SQLite</td>
      <td>zero-ops, genuinely fine at this scale, transactional</td>
    </tr>
    <tr>
      <td>API</td>
      <td>FastAPI</td>
      <td>background tasks, automatic docs, thread-pool semantics I could reason about</td>
    </tr>
    <tr>
      <td>Frame extraction</td>
      <td>OpenCV</td>
      <td>standard, and the histogram tooling is right there</td>
    </tr>
    <tr>
      <td>Frontend</td>
      <td>React + TypeScript + Tailwind + Vite</td>
      <td>small client, no state library needed</td>
    </tr>
    <tr>
      <td>Packaging</td>
      <td>Docker, single container</td>
      <td><code class="language-plaintext highlighter-rouge">docker compose up --build</code> is the only setup step</td>
    </tr>
    <tr>
      <td>Python tooling</td>
      <td><code class="language-plaintext highlighter-rouge">uv</code>, pinned to 3.12</td>
      <td>fast, lockfile-truthful; <code class="language-plaintext highlighter-rouge">faiss-cpu</code> wheels for macOS arm64 are unreliable on 3.13</td>
    </tr>
  </tbody>
</table>

<h3 id="things-deliberately-not-used"><a href="#things-deliberately-not-used"></a>Things deliberately <em>not</em> used</h3>

<ul>
  <li>
    <p><strong>Sentence Transformers.</strong> CLIP already ships its own text encoder, in the same space as the images. Adding a second text model would mean two spaces that cannot be compared.</p>
  </li>
  <li>
    <p><strong>ONNX Runtime.</strong> Pre-optimising before measuring. Latency turned out to be ~40× under target, so this never became justified.</p>
  </li>
  <li>
    <p><strong>Postgres / Chroma / any vector service.</strong> FAISS in-process with SQLite beside it has no operational cost at all. The escape hatch is written down , FAISS → Chroma if metadata filtering ever gets painful , but taking it requires a measured reason, not a feeling.</p>
  </li>
  <li>
    <p><strong>IVF/HNSW approximate indexes.</strong> A flat index is exhaustive and exact. It measured p50 11ms / p95 12ms at 4,415 vectors. Trading recall for speed the system does not need would be a strict loss.</p>
  </li>
</ul>

<p>Every one of these is a decision <em>not</em> to add a moving part. At this scale the boring choice is the right one, and the cost of the boring choice is zero.</p>

<hr />

<h2 id="4-architecture"><a href="#4-architecture"></a>4. Architecture</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>src/sv_engine/
  sampler.py      video → frames worth embedding
  embedder.py     frames/text → normalised CLIP vectors
  index.py        FAISS: vectors and nothing else
  db.py           SQLite: everything else, source of truth
  ingest.py       glues sampler → embedder → index + db
  search.py       text → vectors → FAISS → join back to metadata
  recovery.py     repairs a store left inconsistent by a crash
  compaction.py   removes a video without corrupting every id after it
  evaluation.py   Recall@K against hand-labelled ground truth
  cli.py  api.py  two front ends over the same core

web/              React client; knows nothing but the HTTP API

eval/             labels + methodology

scripts/          corpus builders, A/B runners, report comparison
</code></pre></div></div>

<p>The shape that matters: <code class="language-plaintext highlighter-rouge">cli.py</code> <strong>and</strong> <code class="language-plaintext highlighter-rouge">api.py</code> <strong>are peers</strong>, both thin, and the core modules know about neither. <code class="language-plaintext highlighter-rouge">web/</code> is a client over the HTTP API and knows nothing beyond it. Every layer can be tested without the one above it.</p>

<h3 id="the-single-sharpest-failure-mode"><a href="#the-single-sharpest-failure-mode"></a>The single sharpest failure mode</h3>

<p>FAISS holds vectors. SQLite holds everything needed to turn a vector back into something meaningful. They are joined on one column:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">frames</span><span class="p">.</span><span class="n">vector_index_id</span>   <span class="c1">-- the vector's *position* in the FAISS index</span>
</code></pre></div></div>

<p>A flat FAISS index assigns positions implicitly. First vector added is 0, next is 1, and so on. Which means:</p>

<blockquote>
  <p><strong>Any code that rebuilds or mutates the index must keep that mapping consistent , or search returns the wrong video at the wrong timestamp, with full confidence, and never raises.</strong></p>
</blockquote>

<p>This is the thing that shaped most of the system’s design. A crash that <em>errors</em> is fine. A desync that silently answers wrong is not, because nothing in the system or the UI can tell you it happened. Two whole modules (<code class="language-plaintext highlighter-rouge">recovery.py</code>, <code class="language-plaintext highlighter-rouge">compaction.py</code>) exist only to make that failure impossible, and <code class="language-plaintext highlighter-rouge">index.py</code> deliberately has <strong>no</strong> “remove vector at position i” method, because there is no safe implementation of one.</p>

<hr />

<h2 id="5-frame-sampling-the-first-real-design-decision"><a href="#5-frame-sampling-the-first-real-design-decision"></a>5. Frame sampling: the first real design decision</h2>

<p>Naive options, both bad:</p>

<ul>
  <li>
    <p><strong>Every frame.</strong> 30fps means 1,800 embeddings a minute, mostly near-identical. Wasted storage, wasted index, wasted search time.</p>
  </li>
  <li>
    <p><strong>Every N seconds.</strong> Cheap, but misses short distinct moments entirely. A 0.6-second shot in a fast-cut sequence simply does not exist to the index.</p>
  </li>
</ul>

<p>The strategy used is <strong>scene-change-aware sampling</strong>: a fixed baseline rate of ~1 frame/sec, <em>plus</em> extra samples at points where the picture actually changes.</p>

<p>Cut detection compares <strong>downscaled HSV histograms</strong> using <strong>Bhattacharyya distance</strong>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">scene_distance</span><span class="p">(</span><span class="n">prev</span><span class="p">,</span> <span class="n">curr</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">float</span><span class="p">:</span>
    <span class="sh">"""</span><span class="s">Bhattacharyya distance between two frame histograms, in [0, 1].</span><span class="sh">"""</span>
    <span class="k">return</span> <span class="nf">float</span><span class="p">(</span><span class="n">cv2</span><span class="p">.</span><span class="nf">compareHist</span><span class="p">(</span><span class="nf">_histogram</span><span class="p">(</span><span class="n">prev</span><span class="p">),</span> <span class="nf">_histogram</span><span class="p">(</span><span class="n">curr</span><span class="p">),</span>
                                 <span class="n">cv2</span><span class="p">.</span><span class="n">HISTCMP_BHATTACHARYYA</span><span class="p">))</span>
</code></pre></div></div>

<p>Three choices inside that one function:</p>

<ol>
  <li>
    <p><strong>Frames are downscaled to 160px wide first.</strong> A scene cut is a global property of the picture. Comparing 4K pixels buys nothing and costs a lot.</p>
  </li>
  <li>
    <p><strong>HSV, not BGR.</strong> Hue/saturation is more robust to lighting drift than raw channel intensity.</p>
  </li>
  <li>
    <p><strong>Bhattacharyya, not correlation.</strong> Bhattacharyya is already bounded to [0, 1], so the threshold is interpretable and needs no per-video calibration. Correlation would have meant tuning per clip, which is not a threshold, it is a chore.</p>
  </li>
</ol>

<h3 id="the-threshold-is-measured-not-guessed"><a href="#the-threshold-is-measured-not-guessed"></a>The threshold is measured, not guessed</h3>

<p>On 4-shot test footage:</p>

<table>
  <thead>
    <tr>
      <th>threshold</th>
      <th>result</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0.10</td>
      <td>26 false positives , triggered by camera motion</td>
    </tr>
    <tr>
      <td><strong>0.20 – 0.60</strong></td>
      <td><strong>all cuts found, zero false positives</strong></td>
    </tr>
    <tr>
      <td>0.75</td>
      <td>starts missing real cuts</td>
    </tr>
  </tbody>
</table>

<p>0.35 sits in the middle of a wide plateau. That plateau is the point: a threshold that only works at exactly one value is a threshold that will break on the next video.</p>

<h3 id="the-bug-that-only-a-test-found"><a href="#the-bug-that-only-a-test-found"></a>The bug that only a test found</h3>

<p>There is a <code class="language-plaintext highlighter-rouge">min_gap_sec</code> throttle so a shaky or fast-cutting sequence cannot emit a burst of samples. The first version throttled a candidate cut against <em>any</em> previous sample.</p>

<p>That is wrong, and wrong in the worst direction. A cut landing just after a baseline tick is the <strong>least</strong> duplicative frame available , the picture just changed, which is the entire reason it was flagged. Throttling against baseline left the opening of every new scene unrepresented until the next tick, silently dropping exactly the frames the whole feature exists to capture.</p>

<p>The fix is one word in a condition. Finding it required writing a test that asserted the expected frame count on footage with known cuts:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Throttle cuts against the previous *cut* only.
</span><span class="nf">if </span><span class="p">(</span><span class="nf">scene_distance</span><span class="p">(</span><span class="n">prev_frame</span><span class="p">,</span> <span class="n">frame</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="n">scene_threshold</span>
        <span class="ow">and</span> <span class="n">timestamp</span> <span class="o">-</span> <span class="n">last_cut_ts</span> <span class="o">&gt;=</span> <span class="n">min_gap_sec</span><span class="p">):</span>
    <span class="n">reason</span> <span class="o">=</span> <span class="sh">"</span><span class="s">scene_cut</span><span class="sh">"</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">min_gap_sec</code> throttles <strong>cut-against-cut only, never cut-against-baseline</strong>. There are regression tests pinning this in <code class="language-plaintext highlighter-rouge">test_sampler.py</code>, because the code looked completely reasonable while being wrong.</p>

<p>One more subtlety in the same loop: <code class="language-plaintext highlighter-rouge">prev_frame</code> updates on <strong>every</strong> iteration, not only when a frame is emitted. Cut detection compares against the previous <em>compared</em> frame, not the previous <em>sampled</em> one. Getting that backwards turns a cut detector into a slow-drift detector.</p>

<hr />

<h2 id="6-idempotency-content-hash-not-filename"><a href="#6-idempotency-content-hash-not-filename"></a>6. Idempotency: content hash, not filename</h2>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">content_hash</span><span class="p">(</span><span class="n">path</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="sh">"""</span><span class="s">SHA-256 of the file</span><span class="sh">'</span><span class="s">s bytes, truncated to 16 hex chars.</span><span class="sh">"""</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">videos.id</code> <strong>is</strong> the hash. Re-ingesting the same file is a no-op or a clean overwrite, never a duplicate set of frames. Rename a file and it is still the same video. Copy it into a second folder and it does not double.</p>

<p>Files are hashed in 1MB chunks , these are hundreds of megabytes and do not belong in memory.</p>

<p>The trade-off is honest and worth stating: re-encoding a video changes its hash, so it re-ingests as a new video. That is the correct behaviour for a <em>visual</em> search engine (re-encoded pixels really are different pixels), but it is a choice, not a law.</p>

<hr />

<h2 id="7-status-is-persisted-not-in-memory"><a href="#7-status-is-persisted-not-in-memory"></a>7. Status is persisted, not in-memory</h2>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">videos</span><span class="p">.</span><span class="n">status</span> <span class="err">∈</span> <span class="n">queued</span> <span class="o">|</span> <span class="n">processing</span> <span class="o">|</span> <span class="n">done</span> <span class="o">|</span> <span class="n">failed</span>
<span class="n">videos</span><span class="p">.</span><span class="n">error</span>                        <span class="c1">-- so a failure says *why*</span>
</code></pre></div></div>

<p>The temptation with a background-task API is to hold job state in a dict. That dict does not survive a restart, and the failure it produces is the invisible kind: a video that is silently stuck forever with no way to notice.</p>

<p>So status is a column. <code class="language-plaintext highlighter-rouge">sv-engine videos</code> lists it. <code class="language-plaintext highlighter-rouge">GET /videos/{id}/status</code> serves it. And a video that fails records the reason next to the status, because “failed” with no explanation is only marginally better than silence.</p>

<p>Two real bugs on this project were caught only by tests written <em>after</em> the code was already called “working”: the <code class="language-plaintext highlighter-rouge">min_gap_sec</code> cut-suppression bug above, and a missing <code class="language-plaintext highlighter-rouge">failed</code> row for unreadable files. Both were invisible failures. Both are now pinned by tests.</p>

<hr />

<h2 id="8-crash-recovery-the-part-im-most-pleased-with"><a href="#8-crash-recovery-the-part-im-most-pleased-with"></a>8. Crash recovery: the part I’m most pleased with</h2>

<p><code class="language-plaintext highlighter-rouge">kill -9</code> runs no <code class="language-plaintext highlighter-rouge">except</code> block. Neither does an OOM kill, nor a power cut. So nothing the ingest path does <em>on the way down</em> can be relied on. What survives on disk has to be repairable <strong>from the disk alone</strong>.</p>

<p>The approach: rather than try to handle every crash window, <strong>order the writes so the damage always takes one repairable shape.</strong></p>

<h3 id="the-write-order"><a href="#the-write-order"></a>The write order</h3>

<ol>
  <li>
    <p>A writer holds <code class="language-plaintext highlighter-rouge">index.appending()</code> across <strong>add → persist → commit</strong>, so no second ingest can interleave its vectors. (Embedding stays <em>outside</em> that lock , it is the slow part, and holding a lock across it would make one ingest block every other. Searches take a different, finer lock and are never held up.)</p>
  </li>
  <li>
    <p>The index is <strong>saved before the rows are committed</strong>, and the save is atomic , temp file plus <code class="language-plaintext highlighter-rouge">os.replace</code> , so a half-written index can never replace a good one. Recovery can repair a <em>stale</em> index; it cannot repair an unreadable one.</p>
  </li>
  <li>
    <p>The frame rows and the <code class="language-plaintext highlighter-rouge">done</code> status are <strong>one SQLite transaction</strong>. Otherwise a crash between them leaves a complete frame set on a <code class="language-plaintext highlighter-rouge">processing</code> video, and recovery would re-ingest it and double every frame.</p>
  </li>
</ol>

<h3 id="the-invariant-those-three-buy"><a href="#the-invariant-those-three-buy"></a>The invariant those three buy</h3>

<blockquote>
  <p>A crash leaves <strong>at most surplus vectors at the tail of the index.</strong></p>
</blockquote>

<p>And a tail is the one thing that can be dropped without shifting a single surviving <code class="language-plaintext highlighter-rouge">vector_index_id</code>. Hence the only removal primitive on the index:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">truncate</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">size</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="bp">None</span><span class="p">:</span>
    <span class="sh">"""</span><span class="s">Drop every vector from `size` onwards.

    The only safe way to remove vectors from a flat index: positions below the
    cut keep their ids. Removing from the middle would shift ids and silently
    mis-answer every later query, which is why there is no such method.
    </span><span class="sh">"""</span>
</code></pre></div></div>

<h3 id="what-recovery-does-at-startup"><a href="#what-recovery-does-at-startup"></a>What recovery does at startup</h3>

<ol>
  <li>
    <p><strong>Sweep.</strong> Every video left in <code class="language-plaintext highlighter-rouge">processing</code> or <code class="language-plaintext highlighter-rouge">queued</code> is marked <code class="language-plaintext highlighter-rouge">failed</code>, with the reason recorded. After a restart neither status is true any more , the worker died with the process and nothing re-queues it.</p>
  </li>
  <li>
    <p><strong>Reconcile.</strong> Rows whose vectors are past the end of the index are unrecoverable, so that video is failed <em>wholesale</em> and its rows dropped. Then vectors no row points at are truncated away.</p>
  </li>
</ol>

<p>That “wholesale” is deliberate. <strong>Half a video in the index is worse than none</strong> , it answers queries confidently using whichever frames happened to survive. A partial result that looks complete is the failure mode this entire subsystem exists to prevent.</p>

<p>Recovery runs before the CLI ingests anything, in the API’s lifespan hook, and on demand via <code class="language-plaintext highlighter-rouge">sv-engine recover</code>. It is startup-only and assumes it is the only process running , sweeping while another process ingests would fail a live job.</p>

<hr />

<h2 id="9-compacting-removal-the-operation-with-no-safe-write-order"><a href="#9-compacting-removal-the-operation-with-no-safe-write-order"></a>9. Compacting removal: the operation with no safe write order</h2>

<p><code class="language-plaintext highlighter-rouge">--force</code> on a video that still has frames used to just raise an error. Making it work was the hardest correctness problem in the project.</p>

<p>The issue: <strong>a flat FAISS index cannot delete a vector.</strong> Removing position 3 shifts 4, 5, 6 down by one, and every stored <code class="language-plaintext highlighter-rouge">vector_index_id</code> above it then points at the wrong frame. So removal means rebuilding the index <em>and</em> rewriting the mapping, together.</p>

<p>Unlike an append, <strong>a compaction has no safe write order</strong>:</p>

<ul>
  <li>
    <p>Save the index first → a compacted index against stale ids.</p>
  </li>
  <li>
    <p>Commit the rows first → new ids against the old index.</p>
  </li>
</ul>

<p>Both are silent corruption. And neither is the shape M4’s recovery repairs , <code class="language-plaintext highlighter-rouge">truncate</code> drops from the <em>end</em>, compaction renumbers from the <em>middle</em>.</p>

<p>The solution is a <strong>write-ahead marker</strong>: the operation announces its intent before it swaps.</p>

<ol>
  <li>
    <p>Build the compacted index and <strong>stage</strong> it beside the live one.</p>
  </li>
  <li>
    <p>In <strong>one</strong> SQLite transaction: renumber the survivors, delete the video, and record that a swap is owed.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">os.replace</code> the staged file over the live one.</p>
  </li>
  <li>
    <p>Clear the marker.</p>
  </li>
</ol>

<p>Every interruption then lands somewhere repairable, and <code class="language-plaintext highlighter-rouge">recovery.repair</code> finishes the job at startup:</p>

<table>
  <thead>
    <tr>
      <th>crash point</th>
      <th>state on disk</th>
      <th>repair</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>before (2)</td>
      <td>marker absent, staged file present</td>
      <td>staged file is an orphan , delete it, old store intact</td>
    </tr>
    <tr>
      <td>between (2) and (3)</td>
      <td>marker set, staged file present</td>
      <td>the DB already describes the compacted index , <strong>complete the swap</strong></td>
    </tr>
    <tr>
      <td>between (3) and (4)</td>
      <td>marker set, staged file gone</td>
      <td>swap already happened , clear the marker. Idempotent.</td>
    </tr>
  </tbody>
</table>

<p>The marker stores the <em>staged filename</em> rather than a boolean, precisely so repair can tell those last two cases apart by asking whether the file exists.</p>

<p>Compaction repair also runs <strong>first</strong> in the recovery pass, before reconcile , it decides which file is the live index, so reconciling before it would compare the database against a file that is about to be replaced, and conclude (correctly but uselessly) that they disagree.</p>

<h3 id="two-small-details-with-big-consequences"><a href="#two-small-details-with-big-consequences"></a>Two small details with big consequences</h3>

<p><strong>Renumbering passes through negative ids.</strong> <code class="language-plaintext highlighter-rouge">vector_index_id</code> has a <code class="language-plaintext highlighter-rouge">UNIQUE</code> constraint, so assigning final values directly would collide with rows that have not moved yet. Two passes , write <code class="language-plaintext highlighter-rouge">-(new+1)</code>, then flip the sign , cannot collide, because negatives and positives are disjoint.</p>

<p><code class="language-plaintext highlighter-rouge">drop_video</code> <strong>takes a required</strong> <code class="language-plaintext highlighter-rouge">index_dir</code> <strong>with no default.</strong> It briefly defaulted to <code class="language-plaintext highlighter-rouge">config.INDEX_DIR</code>. A unit test that omitted the argument then compacted my real 205-video index out from under me. The lesson is written into the code and pinned by a test:</p>

<blockquote>
  <p>A destructive file operation must never be able to reach a global path because a caller left an argument off.</p>
</blockquote>

<hr />

<h2 id="10-the-api-layer-and-two-rules-that-break-silently"><a href="#10-the-api-layer-and-two-rules-that-break-silently"></a>10. The API layer, and two rules that break silently</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>POST   /videos                # {"path": "..."} -&gt; 202 queued; ingests in background
POST   /videos/upload         # multipart file -&gt; 202 queued
GET    /videos[?status=...]   # list with per-video frame counts
GET    /videos/{id}/status    # ingestion status
POST   /search                # {query, top_k, collapse_window_sec} -&gt; ranked results
GET    /videos/{id}/file      # streams the source video, with byte ranges
GET    /thumbnails/{frame_id} # serves the JPEG
GET    /health                # corpus size + device
</code></pre></div></div>

<p><strong>Rule 1: every handler that can reach CLIP is a plain</strong> <code class="language-plaintext highlighter-rouge">def</code><strong>, never</strong> <code class="language-plaintext highlighter-rouge">async def</code><strong>.</strong></p>

<p>FastAPI runs <code class="language-plaintext highlighter-rouge">async def</code> handlers on the single event-loop thread and plain <code class="language-plaintext highlighter-rouge">def</code> handlers in a worker thread. CLIP inference is CPU-bound and never yields. An <code class="language-plaintext highlighter-rouge">async def</code> search handler would stall the <em>entire server</em> for the length of an ingest. Measured with the rule in place: searches held ~13ms while a 40-second video ingested.</p>

<p>This is the kind of bug that does not show up in development, where you are the only user, and shows up immediately in a demo.</p>

<p><strong>Rule 2:</strong> <code class="language-plaintext highlighter-rouge">VectorIndex</code> <strong>locks internally, around the FAISS call only.</strong></p>

<p>The lock lives inside the index rather than in callers, so it cannot be forgotten. It is held for the microseconds of the FAISS call , never around sampling or embedding, which would freeze search for the whole of an ingest.</p>

<p>There is a second, coarser writer lock (<code class="language-plaintext highlighter-rouge">appending()</code>) held across an entire add-persist-commit unit. It blocks other <em>writers</em> only. Searches take the fine lock and are never held up by it, so rule 2 still holds.</p>

<p>And a constraint that falls out of threading: <strong>SQLite connections cannot cross threads</strong>, so each request and each background task opens its own.</p>

<h3 id="byte-ranges-by-hand"><a href="#byte-ranges-by-hand"></a>Byte ranges, by hand</h3>

<p><code class="language-plaintext highlighter-rouge">GET /videos/{id}/file</code> implements HTTP range requests manually rather than delegating to <code class="language-plaintext highlighter-rouge">FileResponse</code>, for two reasons:</p>

<ol>
  <li>
    <p><strong>Seeking is the entire point.</strong> A result is a moment <em>inside</em> a video. Without a 206 response the browser must download the whole file before it can jump to 4:32.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">FileResponse</code> answers <strong>400</strong> for a range unit it does not recognise, where RFC 9110 §14.2 requires an unknown unit to be <em>ignored</em> and the full representation sent.</p>
  </li>
</ol>

<p>Ranges are streamed in 256KB blocks: a seek into a 120MB 4K clip should not cost 120MB of RSS per viewer. Only paths recorded in <code class="language-plaintext highlighter-rouge">videos.path</code> are reachable, and the id is a content hash rather than a caller-supplied filename, so there is no path-traversal surface.</p>

<h3 id="urls-not-paths"><a href="#urls-not-paths"></a>URLs, not paths</h3>

<p>Results return <code class="language-plaintext highlighter-rouge">thumbnail_url</code> and <code class="language-plaintext highlighter-rouge">video_url</code>, never a filesystem path. A server path is useless to a browser and leaks the server’s layout.</p>

<hr />

<h2 id="11-the-web-ui-and-one-opinionated-call"><a href="#11-the-web-ui-and-one-opinionated-call"></a>11. The web UI, and one opinionated call</h2>

<p>Vite + React + TypeScript + Tailwind, with shadcn-style components vendored into <code class="language-plaintext highlighter-rouge">components/ui/</code> (shadcn ships source, not a runtime dependency). Four tabs: Search, Library, How to use, About. Tested with Vitest and Testing Library , no browser needed.</p>

<p><strong>Results are grouped by video, not listed as frames.</strong></p>

<p>The engine ranks <em>frames</em>, because frames are what get embedded, and <code class="language-plaintext highlighter-rouge">/search</code> still returns that flat ranked list , the honest shape of what the index computed. But a frame is <strong>evidence</strong>, not the answer. The answer is “this video, at these times.”</p>

<p>So <code class="language-plaintext highlighter-rouge">lib/group.ts</code> folds hits into one card per video: filename at the head, the video itself playable, and its matched moments beneath as a strip of seek targets. A video is ranked by its <strong>best</strong> moment rather than by how many it has , one strong match should beat five weak ones, and counting would only reward long videos.</p>

<p>Grouping is a presentation concern and stays in the client. The API keeps returning frames.</p>

<h3 id="the-client-holds-no-api-base-url-and-must-not-grow-one"><a href="#the-client-holds-no-api-base-url-and-must-not-grow-one"></a>The client holds no API base URL, and must not grow one</h3>

<p><code class="language-plaintext highlighter-rouge">/search</code> returns <code class="language-plaintext highlighter-rouge">thumbnail_url</code> as a <em>relative</em> path, so every URL the app touches is relative. In development the Vite proxy forwards <code class="language-plaintext highlighter-rouge">/search</code>, <code class="language-plaintext highlighter-rouge">/videos</code>, <code class="language-plaintext highlighter-rouge">/thumbnails</code> and <code class="language-plaintext highlighter-rouge">/health</code> to <code class="language-plaintext highlighter-rouge">:8000</code>; in production FastAPI serves the built files itself, so they are same-origin.</p>

<p>Introducing a <code class="language-plaintext highlighter-rouge">VITE_API_URL</code> would trade that for a setting that can be wrong in two environments instead of a thing that cannot be wrong in either.</p>

<h3 id="one-route-ordering-trap"><a href="#one-route-ordering-trap"></a>One route-ordering trap</h3>

<p><code class="language-plaintext highlighter-rouge">create_app</code> mounts <code class="language-plaintext highlighter-rouge">web/dist</code> at <code class="language-plaintext highlighter-rouge">/</code> <strong>last, and nowhere else</strong>. A mount at <code class="language-plaintext highlighter-rouge">/</code> matches every path, and Starlette resolves routes in registration order , so anything registered after it becomes unreachable, while everything before it (every API route, plus <code class="language-plaintext highlighter-rouge">/docs</code>) still wins. Move that block and you get a page that loads and whose every request 404s. <code class="language-plaintext highlighter-rouge">test_web.py</code> pins it.</p>

<p>An absent build is not an error, either. A headless deployment is legitimate, so <code class="language-plaintext highlighter-rouge">/</code> returns a 404 with the command to build the UI rather than failing at startup.</p>

<hr />

<h2 id="12-evaluation-the-part-that-made-everything-else-decidable"><a href="#12-evaluation-the-part-that-made-everything-else-decidable"></a>12. Evaluation: the part that made everything else decidable</h2>

<p>This is the piece I would keep if I had to throw the rest away.</p>

<p>Everything above is an <em>opinion</em> until it is measured. <code class="language-plaintext highlighter-rouge">sv-engine eval</code> scores the store against hand-labelled ground truth and reports <strong>Recall@1 / @5 / @10</strong> plus latency p50/p95. Every design decision in this project was settled by A/B against it.</p>

<h3 id="recall-over-queries-not-relevant-items"><a href="#recall-over-queries-not-relevant-items"></a>Recall over <em>queries</em>, not relevant items</h3>

<p>Each label names the moments that answer a query. A query counts as found if <strong>any</strong> of them lands in the top K. Finding two is worth no more than finding one.</p>

<p>That is <strong>known-item retrieval</strong>, which is the actual shape of this product: a person hunting one moment they remember. It is deliberately not the mean-average-precision framing , there is no notion of “all relevant frames” to be complete against, and inventing one would mean labelling every frame of every video.</p>

<h3 id="three-design-points-each-because-the-alternative-silently-corrupts-the-metric"><a href="#three-design-points-each-because-the-alternative-silently-corrupts-the-metric"></a>Three design points, each because the alternative silently corrupts the metric</h3>

<ol>
  <li>
    <p><strong>A label carries a <em>list</em> of targets.</strong> The test corpus includes <code class="language-plaintext highlighter-rouge">multishot_4cuts_720p.mp4</code>, a concatenation of four other clips , so most footage has two correct answers. A single-target schema would score a perfect retrieval as a miss and cap Recall@1 for reasons unrelated to retrieval.</p>
  </li>
  <li>
    <p><strong>Labels key on filename, and an unknown filename is an error, not a miss.</strong> A typo’d or un-ingested video would score zero, which looks <em>exactly</em> like a broken retriever. The same reasoning drives the strict loader: unknown keys, backwards ranges and empty label sets all raise, because each would otherwise surface only as a lower score.</p>
  </li>
  <li>
    <p><strong>A tolerance (default 1.0s = one baseline interval) widens each range.</strong> Sampling is ~1 frame/sec, so the nearest sampled frame can sit that far from the moment a human read off the clock. Scoring strictly charges the retriever for the sampler’s grid.</p>
  </li>
</ol>

<p>Every report also records <strong>which sampling arm built the store it measured</strong>, inferred from whether any frame has <code class="language-plaintext highlighter-rouge">reason = scene_cut</code>. Two A/B reports without that are two numbers with no record of what they compare.</p>

<p>And the labels are <strong>committed to git</strong>, anchored to the checkout rather than the gitignored data directory. A metric whose ground truth is not version-controlled cannot be re-derived, and a metric that cannot be re-derived is not a metric.</p>

<h3 id="two-eval-sets-for-two-different-questions"><a href="#two-eval-sets-for-two-different-questions"></a>Two eval sets, for two different questions</h3>

<table>
  <thead>
    <tr>
      <th>set</th>
      <th>size</th>
      <th>how made</th>
      <th>what it measures</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">eval/labels.json</code></td>
      <td>12 queries</td>
      <td>hand-authored, someone looked at the frames</td>
      <td><strong>moment precision</strong> , narrow timestamp targets. The headline number, and the only one supporting an absolute claim.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">eval/labels-corpus.json</code></td>
      <td>187 queries</td>
      <td>generated from the corpus manifest; the query is the uploader’s own description</td>
      <td><strong>video selection</strong> , whole-video targets. Weak supervision; use for <em>comparison</em>, never as a quality claim.</td>
    </tr>
  </tbody>
</table>

<p>The corpus set’s absolute number understates quality badly, and it is worth understanding why: with ~20 near-identical clips per category, returning a <em>different</em> cat video than the labelled one scores zero while being a perfectly good answer. Its value is that a <strong>paired</strong> comparison over identical queries cancels per-query noise , which is exactly what an A/B needs.</p>

<h3 id="current-baseline"><a href="#current-baseline"></a>Current baseline</h3>

<p><strong>205 videos, 4,415 frames, ~70 minutes of footage, scene-aware, ViT-B/32:</strong></p>

<table>
  <thead>
    <tr>
      <th>set</th>
      <th>R@1</th>
      <th>R@5</th>
      <th>R@10</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>hand-labelled (12)</td>
      <td>66.7%</td>
      <td>75.0%</td>
      <td>83.3%</td>
    </tr>
    <tr>
      <td>corpus (187, weak)</td>
      <td>38.0%</td>
      <td>52.4%</td>
      <td>58.8%</td>
    </tr>
  </tbody>
</table>

<p>Latency <strong>p50 11ms / p95 12ms</strong> against a 500ms target , roughly 40× headroom. The flat index is nowhere near being the bottleneck, so IVF/HNSW stays unjustified.</p>

<p>One number worth reporting honestly: the hand-labelled R@5 <strong>fell from 91.7% to 75.0%</strong> when the corpus grew from 5 videos to 205. That is not a regression. It is the honest effect of 200 distractors; the earlier figure was measured against a corpus with almost nothing to confuse it. A benchmark that only ever improves is usually a benchmark that is being gamed.</p>

<hr />

<h2 id="13-what-the-measurements-settled"><a href="#13-what-the-measurements-settled"></a>13. What the measurements settled</h2>

<h3 id="a-scene-aware-sampling-beats-fixed-interval--and-the-corpus-problem"><a href="#a-scene-aware-sampling-beats-fixed-interval--and-the-corpus-problem"></a>A. Scene-aware sampling beats fixed-interval , and the corpus problem</h3>

<p><strong>Result: Recall@5 100% vs 85.7%, +14.3 points.</strong></p>

<p>But the interesting part is that <strong>this could not be measured on the real corpus.</strong> Scene-aware sampling contributes exactly 3 frames out of 87 there, because four of the five original videos are single continuous shots. Both arms tied , and the tie says nothing whatsoever about the design.</p>

<blockquote>
  <p><strong>A corpus that cannot exhibit the phenomenon cannot measure it.</strong></p>
</blockquote>

<p>So <code class="language-plaintext highlighter-rouge">scripts/make_cut_dense_corpus.py</code> builds one that can: 16 shots (8 sub-second, 8 sustained) cut from four source clips crossed with four visual treatments, so every shot is uniquely addressable by one query. Boundaries are known by construction.</p>

<table>
  <thead>
    <tr>
      <th>arm</th>
      <th>frames</th>
      <th>shot coverage</th>
      <th>R@1</th>
      <th>R@5</th>
      <th>R@10</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>scene-aware</strong></td>
      <td>43</td>
      <td><strong>100.0%</strong></td>
      <td>81.2%</td>
      <td><strong>93.8%</strong></td>
      <td>100.0%</td>
    </tr>
    <tr>
      <td>fixed-interval</td>
      <td>28</td>
      <td>81.2%</td>
      <td>68.8%</td>
      <td>81.2%</td>
      <td>81.2%</td>
    </tr>
    <tr>
      <td>dense control (10fps)</td>
      <td>277</td>
      <td>100.0%</td>
      <td>68.8%</td>
      <td>87.5%</td>
      <td>87.5%</td>
    </tr>
  </tbody>
</table>

<p>Two queries changed outcome, both sub-second shots (0.63s and 0.57s), findable <em>only</em> by the scene-aware arm. Fixed-interval put no frame inside them at all.</p>

<p><strong>Three things hold that result up</strong>, and each exists because its absence silently corrupts the answer:</p>

<ol>
  <li>
    <p><strong>Coverage is reported next to recall.</strong> Recall alone cannot distinguish “captured shots that were missed, and retrieval improved” from “captured them and retrieval didn’t improve” , the second is a finding about CLIP, not about sampling. Here they agree, and that agreement is the actual evidence.</p>
  </li>
  <li>
    <p><strong>A dense 10fps control arm decides which labels are answerable.</strong> Some queries fail because CLIP simply cannot see “sepia”. Filtering with either test arm’s own successes would bias the comparison toward it.</p>
  </li>
  <li>
    <p><strong>Shot boundaries are quantised to whole frames.</strong> The first version rounded durations to 1/100s while the renderer wrote whole frames. The declared boundaries drifted from the rendered ones, ground truth pointed at the <em>neighbouring</em> shot, and the run produced a coherent-looking, wholly false result , 100% coverage with <em>worse</em> recall. <strong>Generated ground truth still has to be verified against the artefact it describes.</strong> That one cost a day and was the most valuable mistake in the project.</p>
  </li>
</ol>

<h3 id="b-near-duplicate-collapsing-helps-and-the-safe-window-is-35s"><a href="#b-near-duplicate-collapsing-helps-and-the-safe-window-is-35s"></a>B. Near-duplicate collapsing helps, and the safe window is 3–5s</h3>

<p>A long static shot floods the results with near-identical entries. Collapsing merges hits from the same video within N seconds, keeping the best-scoring one. (The search over-fetches <code class="language-plaintext highlighter-rouge">top_k * 5</code> when collapsing, so <code class="language-plaintext highlighter-rouge">top_k</code> distinct moments still come back.)</p>

<table>
  <thead>
    <tr>
      <th>collapse</th>
      <th>hand R@5</th>
      <th>hand R@10</th>
      <th>corpus R@5</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>off</td>
      <td>75.0%</td>
      <td>83.3%</td>
      <td>52.4%</td>
    </tr>
    <tr>
      <td><strong>3s</strong></td>
      <td><strong>83.3%</strong></td>
      <td><strong>91.7%</strong></td>
      <td>56.7%</td>
    </tr>
    <tr>
      <td><strong>5s</strong></td>
      <td><strong>83.3%</strong></td>
      <td><strong>91.7%</strong></td>
      <td>63.1%</td>
    </tr>
    <tr>
      <td>20s</td>
      <td>75.0%</td>
      <td>75.0%</td>
      <td><strong>71.7%</strong></td>
    </tr>
  </tbody>
</table>

<p><strong>The two sets disagree above ~5s, and the disagreement is the finding, not a problem.</strong> The corpus set improves monotonically because its targets are <em>whole videos</em> , collapsing frees top-K slots for distinct videos, so it can only help a video-selection task. The hand-labelled set degrades past 10s because aggressive merging deletes the correct <em>moment</em> inside the right video.</p>

<p>So: collapse hard if you only care which video; keep it at 3–5s if timestamps matter. The 3s default sits in that plateau.</p>

<h3 id="c-vit-l14-beats-vit-b32-by-7-points--and-the-default-did-not-change"><a href="#c-vit-l14-beats-vit-b32-by-7-points--and-the-default-did-not-change"></a>C. ViT-L/14 beats ViT-B/32 by ~7 points , and the default did not change</h3>

<p>Measured at 205 videos on both eval sets. The comparison is clean: <code class="language-plaintext highlighter-rouge">laion2b_s32b_b82k</code> is the LAION-2B counterpart to B/32’s <code class="language-plaintext highlighter-rouge">laion2b_s34b_b79k</code>, so this isolates <strong>model capacity</strong> rather than confounding it with training data , and both arms indexed the identical 4,415 frames, with only the embedder differing.</p>

<table>
  <thead>
    <tr>
      <th>set</th>
      <th>arm</th>
      <th>R@1</th>
      <th>R@5</th>
      <th>R@10</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>corpus (187, weak)</td>
      <td>ViT-B/32</td>
      <td>38.0%</td>
      <td>52.4%</td>
      <td>58.8%</td>
    </tr>
    <tr>
      <td>corpus (187, weak)</td>
      <td><strong>ViT-L/14</strong></td>
      <td>43.9%</td>
      <td><strong>59.4%</strong></td>
      <td>65.8%</td>
    </tr>
    <tr>
      <td>hand-labelled (12)</td>
      <td>ViT-B/32</td>
      <td>66.7%</td>
      <td>75.0%</td>
      <td>83.3%</td>
    </tr>
    <tr>
      <td>hand-labelled (12)</td>
      <td><strong>ViT-L/14</strong></td>
      <td>75.0%</td>
      <td><strong>83.3%</strong></td>
      <td>91.7%</td>
    </tr>
  </tbody>
</table>

<p><strong>Read the churn, not just the delta.</strong> At R@5 on the 187-query set, ViT-L/14 <strong>gained 26 queries and lost 13</strong>. A net +13 built from a 2:1 win ratio is a real effect rather than noise , but a model swap is <em>not</em> a strict improvement, and thirteen queries genuinely got worse. The 12-query set moves +8.3 everywhere, which is one query each: corroboration, not evidence.</p>

<p>Costs: search p50 11ms → 22ms (still ~20× under target), ingest 198s → 370s for 70 minutes of footage, index 8.6MB → 13MB (768-d vs 512-d), and the Docker image would grow ~1.1GB.</p>

<p><strong>Why the default did not change:</strong> the vector dimension changes with the checkpoint, so <strong>every existing index becomes unreadable</strong> and needs a full <code class="language-plaintext highlighter-rouge">--rebuild</code>. That is an operational decision, not a tuning knob. The mismatch is caught loudly rather than silently mis-served:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>existing index has dim 512, embedder produces 768.
The checkpoint changed -- rebuild the index.
</code></pre></div></div>

<p>Switching is one env var away (<code class="language-plaintext highlighter-rouge">SV_CLIP_MODEL=ViT-L-14</code>), and the measurement says it is worth it , it is just not something that should happen to someone by surprise.</p>

<p><code class="language-plaintext highlighter-rouge">scripts/compare_reports.py</code> reproduces the comparison, pairing two <code class="language-plaintext highlighter-rouge">eval --json</code> reports by query text and reporting <strong>wins and losses separately</strong>. It refuses to compare reports scored against different label sets rather than silently intersecting them.</p>

<hr />

<h2 id="14-packaging"><a href="#14-packaging"></a>14. Packaging</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose up <span class="nt">--build</span>      <span class="c"># API + UI on :8000</span>
</code></pre></div></div>

<p>A <strong>four-stage build</strong>: the React UI (so the image does not depend on a host <code class="language-plaintext highlighter-rouge">npm run build</code>), Python deps from <code class="language-plaintext highlighter-rouge">uv.lock</code> with <code class="language-plaintext highlighter-rouge">--frozen</code>, the CLIP checkpoint baked in, then a slim runtime. Verified in-container: identical Recall to the host, UI at <code class="language-plaintext highlighter-rouge">/</code>, <code class="language-plaintext highlighter-rouge">/docs</code> still 200, thumbnails served. Latency is ~3× the host (p50 34ms vs 11ms) , CPU-only, as designed.</p>

<p>Five things turned out to be load-bearing, each found by the container failing without it:</p>

<ol>
  <li>
    <p><code class="language-plaintext highlighter-rouge">pyproject.toml</code> <strong>pins torch to the CPU index on linux.</strong> The default wheels drag in the entire CUDA toolkit , gigabytes, for hardware the container cannot reach. Scoped by a <code class="language-plaintext highlighter-rouge">sys_platform</code> marker so macOS resolution is untouched; <code class="language-plaintext highlighter-rouge">uv.lock</code> carries both.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">/data</code> <strong>is created and chowned in the image <em>before</em></strong> <code class="language-plaintext highlighter-rouge">VOLUME</code><strong>.</strong> Docker seeds a fresh named volume from the image path, ownership included. Without it the volume arrives root-owned and the unprivileged process dies in <code class="language-plaintext highlighter-rouge">ensure_dirs()</code>.</p>
  </li>
  <li>
    <p><strong>Host footage mounts at</strong> <code class="language-plaintext highlighter-rouge">/videos</code><strong>, not over</strong> <code class="language-plaintext highlighter-rouge">/data/videos</code><strong>.</strong> That directory must stay writable , <code class="language-plaintext highlighter-rouge">POST /videos/upload</code> saves into it, so a read-only bind there breaks the endpoint at <em>runtime</em> rather than at startup.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">SV_WEB_DIST</code> <strong>and</strong> <code class="language-plaintext highlighter-rouge">SV_DEVICE</code> <strong>are set explicitly.</strong> <code class="language-plaintext highlighter-rouge">config.py</code> derives the UI path from the source-tree layout, which is not a safe assumption inside an image; and there is no MPS or CUDA in the container, so say so rather than letting device selection fall through and look like a choice.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">.dockerignore</code> <strong>is not optional.</strong> The build context is 1.2GB without it , 258MB of source videos plus a macOS-built <code class="language-plaintext highlighter-rouge">.venv</code> that must never enter a linux image.</p>
  </li>
</ol>

<p>One known wrinkle, documented rather than hidden: <code class="language-plaintext highlighter-rouge">docker compose run ... index</code> writes to the shared volume immediately, but the already-running server loaded its index at startup and will not see the new vectors until a restart. Ingesting through <code class="language-plaintext highlighter-rouge">POST /videos</code> avoids it entirely.</p>

<h3 id="local-dev-vs-docker"><a href="#local-dev-vs-docker"></a>Local dev vs Docker</h3>

<p>Develop natively with <code class="language-plaintext highlighter-rouge">uv</code>. <strong>Docker on macOS has no MPS/GPU passthrough</strong>, so CLIP inference in a container is CPU-only and dramatically slower , fine for correctness and for the <code class="language-plaintext highlighter-rouge">docker compose up</code> done-criterion, painful for iterating on ingestion. Device selection is <code class="language-plaintext highlighter-rouge">mps → cuda → cpu</code>, overridable by <code class="language-plaintext highlighter-rouge">SV_DEVICE</code> so containers and tests can force <code class="language-plaintext highlighter-rouge">cpu</code>.</p>

<hr />

<h2 id="15-the-stupidest-bug-two-openmp-runtimes"><a href="#15-the-stupidest-bug-two-openmp-runtimes"></a>15. The stupidest bug: two OpenMP runtimes</h2>

<p><code class="language-plaintext highlighter-rouge">faiss</code> and <code class="language-plaintext highlighter-rouge">torch</code> each bundle their own <code class="language-plaintext highlighter-rouge">libomp.dylib</code>. Loading both in one process on macOS aborts with <code class="language-plaintext highlighter-rouge">OMP: Error #15</code>. Import order does not fix it.</p>

<p>The internet’s answer is <code class="language-plaintext highlighter-rouge">KMP_DUPLICATE_LIB_OK=TRUE</code>. <strong>That was not acceptable here.</strong> OpenMP’s own documentation says it can silently produce incorrect results , which is disqualifying for a retrieval system, where “silently incorrect” is the exact failure class the entire architecture is built to avoid.</p>

<p>The fix is <code class="language-plaintext highlighter-rouge">scripts/fix_openmp.py</code>: it repoints faiss’s copy at torch’s (same LLVM libomp, ABI 5.0.0), and <strong>refuses to link if the ABI versions ever diverge</strong>. It must be re-run after any <code class="language-plaintext highlighter-rouge">uv sync</code>.</p>

<p>This does not arise on linux , there is one system <code class="language-plaintext highlighter-rouge">libgomp</code> and both libraries use it , so the script is macOS-only.</p>

<p>Not an interesting bug. But a good illustration: the <em>convenient</em> workaround traded a loud crash for possible silent wrongness, which is always the wrong trade in this project.</p>

<hr />

<h2 id="16-how-it-was-built"><a href="#16-how-it-was-built"></a>16. How it was built</h2>

<p>Six milestones, each independently demoable , the rule was <strong>never leave a half-built pile.</strong></p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>milestone</th>
      <th> </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>M1</td>
      <td>CLI only: extract, embed, index, query one video</td>
      <td>Done</td>
    </tr>
    <tr>
      <td>M2</td>
      <td>Multi-video + SQLite; cross-video results map to the right video/timestamp</td>
      <td>Done</td>
    </tr>
    <tr>
      <td>M3</td>
      <td>FastAPI wrapper; background ingestion with status tracking</td>
      <td>Done</td>
    </tr>
    <tr>
      <td>M4</td>
      <td>Content-hash idempotency, persisted status, crash handling</td>
      <td>Done</td>
    </tr>
    <tr>
      <td>M5</td>
      <td>React search UI</td>
      <td>Done</td>
    </tr>
    <tr>
      <td>M6</td>
      <td>Near-duplicate collapsing, sampling refinement, latency work</td>
      <td>Done (gated on the eval harness)</td>
    </tr>
  </tbody>
</table>

<p>31 commits over roughly two months of evenings.</p>

<h3 id="test-first-and-why-it-stopped-being-optional"><a href="#test-first-and-why-it-stopped-being-optional"></a>Test-first, and why it stopped being optional</h3>

<p>The rule: <strong>write the tests that define the behaviour before the implementation</strong>, run them to confirm they fail for the right reason, then make them pass.</p>

<p>This started as discipline and became non-negotiable after two bugs , the <code class="language-plaintext highlighter-rouge">min_gap_sec</code> cut suppression and the missing <code class="language-plaintext highlighter-rouge">failed</code> row for unreadable files , were found <em>only</em> by tests written after the code had already been called “working.” Both were silent. Neither would have been noticed in normal use.</p>

<p>The suite is 225 tests. The fast suite (<code class="language-plaintext highlighter-rouge">pytest -m "not slow"</code>) is 217 of them and runs in <strong>~2 seconds</strong>, because it is kept free of CLIP loads. End-to-end tests that load the checkpoint are marked <code class="language-plaintext highlighter-rouge">slow</code>. A test suite you avoid running is a test suite you do not have.</p>

<hr />

<h2 id="17-what-id-take-from-this"><a href="#17-what-id-take-from-this"></a>17. What I’d take from this</h2>

<p><strong>Measure the thing you are arguing about, or stop arguing.</strong> Sampling strategy, collapse window, and checkpoint choice were all live debates that took ten minutes each to settle once there was a Recall@K number. The eval harness was the highest-leverage code in the project and it was written <em>after</em> M5 , which is later than it should have been.</p>

<p><strong>A corpus that cannot exhibit the phenomenon cannot measure it.</strong> The sampling A/B tied on real footage and the tie meant nothing. Recognising that a null result was <em>uninformative</em> rather than <em>negative</em> was the difference between shipping the right default and shipping a coin flip.</p>

<p><strong>Generated ground truth is not ground truth until you check it.</strong> A rounding mismatch of one hundredth of a second produced a completely coherent, completely false experimental result.</p>

<p><strong>Order writes so failure has one shape.</strong> Trying to handle every crash window is unbounded work. Constraining the damage to “surplus vectors at the tail” made recovery a dozen lines instead of a subsystem , and where a single shape was impossible (compaction), a write-ahead marker made the three remaining shapes enumerable, and the table of what to do in each fits in a paragraph.</p>

<p><strong>The worst bug is the one that does not raise.</strong> Almost every hard decision here , failing a video wholesale rather than half-serving it, refusing <code class="language-plaintext highlighter-rouge">KMP_DUPLICATE_LIB_OK</code>, making <code class="language-plaintext highlighter-rouge">index_dir</code> a required argument, treating an unknown label filename as an error rather than a miss, erroring loudly on a dimension mismatch , is the same decision made repeatedly: <strong>prefer a loud failure to a quiet wrong answer.</strong> In a retrieval system, a confident wrong answer is indistinguishable from a right one, and that is the only failure mode the user can never catch for you.</p>

<hr />

<h2 id="appendix-running-it"><a href="#appendix-running-it"></a>Appendix: running it</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose up <span class="nt">--build</span>          <span class="c"># everything, on :8000</span>
</code></pre></div></div>

<p>Or natively:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>uv <span class="nb">sync
</span>uv run python scripts/fix_openmp.py       <span class="c"># macOS only</span>

uv run python <span class="nt">-m</span> sv_engine.cli index data/videos      <span class="c"># ingest a file or folder</span>
uv run python <span class="nt">-m</span> sv_engine.cli search <span class="s2">"a red car at night"</span> <span class="nt">-k</span> 10
uv run python <span class="nt">-m</span> sv_engine.cli videos                 <span class="c"># status per video</span>
uv run python <span class="nt">-m</span> sv_engine.cli recover                <span class="c"># repair after a crash</span>
uv run python <span class="nt">-m</span> sv_engine.cli <span class="nb">eval</span>                   <span class="c"># Recall@K</span>
uv run python <span class="nt">-m</span> sv_engine.cli serve <span class="nt">--port</span> 8000      <span class="c"># API + UI, docs at /docs</span>
</code></pre></div></div>

<p>Useful flags: <code class="language-plaintext highlighter-rouge">--rebuild</code> (drop index, database <strong>and</strong> thumbnails together , a rebuilt index against a stale database is exactly the desync that produces confident wrong answers), <code class="language-plaintext highlighter-rouge">--force</code> (re-ingest a <code class="language-plaintext highlighter-rouge">done</code> video, compacting the old frames out), <code class="language-plaintext highlighter-rouge">--fixed-interval</code> (the sampling control arm), <code class="language-plaintext highlighter-rouge">--collapse 3.0</code>.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>uv run pytest <span class="nt">-m</span> <span class="s2">"not slow"</span>      <span class="c"># 217 tests, ~2s, no CLIP</span>
uv run pytest <span class="nt">-m</span> slow            <span class="c"># end-to-end, loads the checkpoint</span>
npm <span class="nt">--prefix</span> web <span class="nb">test</span>            <span class="c"># UI tests, no browser needed</span>
</code></pre></div></div>]]></content><author><name>Arnav Verma</name><email>av4445@nyu.edu</email></author><category term="CLIP" /><category term="FAISS" /><category term="Vector Search" /><category term="Python" /><category term="TypeScript" /><summary type="html"><![CDATA[Point it at a folder of videos, type "a red car driving at night", and get back exact timestamps across every video you own — each one playable at the moment it matched.]]></summary></entry><entry><title type="html">Language Model Distillation</title><link href="https://namesarnav.com/blog/lm-distill/" rel="alternate" type="text/html" title="Language Model Distillation" /><published>2026-03-18T00:00:00+00:00</published><updated>2026-03-18T00:00:00+00:00</updated><id>https://namesarnav.com/blog/lm-distill</id><content type="html" xml:base="https://namesarnav.com/blog/lm-distill/"><![CDATA[<p><em>Also published on <a href="https://arnavverma.hashnode.dev/model-distillation">arnavverma.hashnode.dev</a>.</em></p>

<p>Knowledge distillation is a technique for training smaller neural networks to perform like larger ones. The basic idea is simple: train a small “student” model to copy the behavior of a large “teacher” model. This lets you compress years of training and billions of parameters into something you can actually deploy. But making this work well requires understanding probability matching, intermediate representations, and training dynamics.</p>

<h2 id="how-distillation-works"><a href="#how-distillation-works"></a>How Distillation Works</h2>

<p>Hinton and his colleagues created knowledge distillation after noticing something useful: when a trained model makes predictions, it outputs a probability distribution that contains more information than just the final answer. Say a teacher model assigns 80% probability to the correct class, 15% to a similar class, and 5% to an unrelated class. This distribution tells you about relationships between classes that a simple correct/incorrect label throws away. The student learns not just what to predict, but how the teacher thinks about alternatives.</p>

<p><img src="https://cdn.hashnode.com/uploads/covers/6557ff28afe2c15e65f8d100/631d3b3b-6893-47ed-b796-2d6df04cb5b5.png align=&quot;center&quot;" alt="" /></p>

<p>The distillation loss function combines two parts. First, it measures how well the student matches the teacher’s soft predictions using KL divergence. Second, it makes sure the student still learns from the actual labels using cross-entropy loss. You control the balance between these with a parameter called alpha.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">torch</span>
<span class="kn">import</span> <span class="n">torch.nn</span> <span class="k">as</span> <span class="n">nn</span>
<span class="kn">import</span> <span class="n">torch.nn.functional</span> <span class="k">as</span> <span class="n">F</span>

<span class="k">class</span> <span class="nc">DistillationLoss</span><span class="p">(</span><span class="n">nn</span><span class="p">.</span><span class="n">Module</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">temperature</span><span class="o">=</span><span class="mf">3.0</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="mf">0.7</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Args:
            temperature: Controls softness of probability distributions
            alpha: Weight balancing distillation vs hard label loss
        </span><span class="sh">"""</span>
        <span class="nf">super</span><span class="p">().</span><span class="nf">__init__</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">temperature</span> <span class="o">=</span> <span class="n">temperature</span>
        <span class="n">self</span><span class="p">.</span><span class="n">alpha</span> <span class="o">=</span> <span class="n">alpha</span>
        <span class="n">self</span><span class="p">.</span><span class="n">kl_div</span> <span class="o">=</span> <span class="n">nn</span><span class="p">.</span><span class="nc">KLDivLoss</span><span class="p">(</span><span class="n">reduction</span><span class="o">=</span><span class="sh">'</span><span class="s">batchmean</span><span class="sh">'</span><span class="p">)</span>
        <span class="n">self</span><span class="p">.</span><span class="n">ce_loss</span> <span class="o">=</span> <span class="n">nn</span><span class="p">.</span><span class="nc">CrossEntropyLoss</span><span class="p">()</span>
    
    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">student_logits</span><span class="p">,</span> <span class="n">teacher_logits</span><span class="p">,</span> <span class="n">labels</span><span class="p">):</span>
        <span class="c1"># Soften distributions with temperature scaling
</span>        <span class="n">student_soft</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">log_softmax</span><span class="p">(</span><span class="n">student_logits</span> <span class="o">/</span> <span class="n">self</span><span class="p">.</span><span class="n">temperature</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">teacher_soft</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">softmax</span><span class="p">(</span><span class="n">teacher_logits</span> <span class="o">/</span> <span class="n">self</span><span class="p">.</span><span class="n">temperature</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        
        <span class="c1"># Distillation loss (KL divergence between soft distributions)
</span>        <span class="n">distillation_loss</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">kl_div</span><span class="p">(</span><span class="n">student_soft</span><span class="p">,</span> <span class="n">teacher_soft</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">temperature</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span>
        
        <span class="c1"># Standard cross-entropy with hard labels
</span>        <span class="n">student_loss</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">ce_loss</span><span class="p">(</span><span class="n">student_logits</span><span class="p">,</span> <span class="n">labels</span><span class="p">)</span>
        
        <span class="c1"># Combined objective
</span>        <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="n">alpha</span> <span class="o">*</span> <span class="n">distillation_loss</span> <span class="o">+</span> <span class="p">(</span><span class="mi">1</span> <span class="o">-</span> <span class="n">self</span><span class="p">.</span><span class="n">alpha</span><span class="p">)</span> <span class="o">*</span> <span class="n">student_loss</span>
</code></pre></div></div>

<p>Temperature is important here. Higher temperature makes the probability distribution “softer,” revealing more about class relationships. At temperature 1, you get normal softmax. As temperature goes up, the distribution gets more uniform. The best temperature is usually between 2 and 5. The temperature squared term in the loss keeps gradients consistent across different temperature settings.</p>

<h2 id="dealing-with-size-differences"><a href="#dealing-with-size-differences"></a>Dealing with Size Differences</h2>

<p>The gap between teacher and student size fundamentally limits how well distillation works. If the student is too small, it can’t capture what the teacher knows. If it’s too large, you’re not getting much compression. You need to find the point where the student is small enough to be useful but large enough to learn the important patterns.</p>

<p><img src="https://cdn.hashnode.com/uploads/covers/6557ff28afe2c15e65f8d100/7d4c0360-082d-4015-b94f-87ae27b00cb1.png align=&quot;center&quot;" alt="" /></p>

<p>Different approaches handle this gap in different ways. Basic distillation just matches output distributions. Intermediate distillation also aligns hidden layer representations. This works better for transformers where intermediate attention patterns encode important linguistic knowledge. Patient Knowledge Distillation goes further by matching relationships between layers, not just individual layers.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">IntermediateDistillation</span><span class="p">(</span><span class="n">nn</span><span class="p">.</span><span class="n">Module</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">student_dim</span><span class="p">,</span> <span class="n">teacher_dim</span><span class="p">,</span> <span class="n">num_student_layers</span><span class="p">,</span> <span class="n">num_teacher_layers</span><span class="p">):</span>
        <span class="nf">super</span><span class="p">().</span><span class="nf">__init__</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">num_student_layers</span> <span class="o">=</span> <span class="n">num_student_layers</span>
        <span class="n">self</span><span class="p">.</span><span class="n">num_teacher_layers</span> <span class="o">=</span> <span class="n">num_teacher_layers</span>
        
        <span class="c1"># Layer mapping strategy: map student layers to teacher layers
</span>        <span class="n">self</span><span class="p">.</span><span class="n">layer_mapping</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">_create_layer_mapping</span><span class="p">()</span>
        
        <span class="c1"># Projection layers if dimensions don't match
</span>        <span class="k">if</span> <span class="n">student_dim</span> <span class="o">!=</span> <span class="n">teacher_dim</span><span class="p">:</span>
            <span class="n">self</span><span class="p">.</span><span class="n">projections</span> <span class="o">=</span> <span class="n">nn</span><span class="p">.</span><span class="nc">ModuleList</span><span class="p">([</span>
                <span class="n">nn</span><span class="p">.</span><span class="nc">Linear</span><span class="p">(</span><span class="n">student_dim</span><span class="p">,</span> <span class="n">teacher_dim</span><span class="p">)</span> 
                <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="n">num_student_layers</span><span class="p">)</span>
            <span class="p">])</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">self</span><span class="p">.</span><span class="n">projections</span> <span class="o">=</span> <span class="bp">None</span>
    
    <span class="k">def</span> <span class="nf">_create_layer_mapping</span><span class="p">(</span><span class="n">self</span><span class="p">):</span>
        <span class="c1"># Map student layers uniformly across teacher layers
</span>        <span class="c1"># For 6 student, 12 teacher: [1, 3, 5, 7, 9, 11]
</span>        <span class="n">step</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">num_teacher_layers</span> <span class="o">/</span> <span class="n">self</span><span class="p">.</span><span class="n">num_student_layers</span>
        <span class="k">return</span> <span class="p">[</span><span class="nf">int</span><span class="p">(</span><span class="n">i</span> <span class="o">*</span> <span class="n">step</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">num_student_layers</span><span class="p">)]</span>
    
    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">student_hidden_states</span><span class="p">,</span> <span class="n">teacher_hidden_states</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Args:
            student_hidden_states: List of tensors [batch, seq_len, student_dim]
            teacher_hidden_states: List of tensors [batch, seq_len, teacher_dim]
        </span><span class="sh">"""</span>
        <span class="n">total_loss</span> <span class="o">=</span> <span class="mi">0</span>
        
        <span class="k">for</span> <span class="n">student_idx</span><span class="p">,</span> <span class="n">teacher_idx</span> <span class="ow">in</span> <span class="nf">enumerate</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">layer_mapping</span><span class="p">):</span>
            <span class="n">student_hidden</span> <span class="o">=</span> <span class="n">student_hidden_states</span><span class="p">[</span><span class="n">student_idx</span><span class="p">]</span>
            <span class="n">teacher_hidden</span> <span class="o">=</span> <span class="n">teacher_hidden_states</span><span class="p">[</span><span class="n">teacher_idx</span><span class="p">]</span>
            
            <span class="c1"># Project student to teacher dimension if needed
</span>            <span class="k">if</span> <span class="n">self</span><span class="p">.</span><span class="n">projections</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                <span class="n">student_hidden</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">projections</span><span class="p">[</span><span class="n">student_idx</span><span class="p">](</span><span class="n">student_hidden</span><span class="p">)</span>
            
            <span class="c1"># MSE loss between intermediate representations
</span>            <span class="n">layer_loss</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">mse_loss</span><span class="p">(</span><span class="n">student_hidden</span><span class="p">,</span> <span class="n">teacher_hidden</span><span class="p">.</span><span class="nf">detach</span><span class="p">())</span>
            <span class="n">total_loss</span> <span class="o">+=</span> <span class="n">layer_loss</span>
        
        <span class="k">return</span> <span class="n">total_loss</span> <span class="o">/</span> <span class="nf">len</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">layer_mapping</span><span class="p">)</span>
</code></pre></div></div>

<h2 id="transferring-attention-patterns"><a href="#transferring-attention-patterns"></a>Transferring Attention Patterns</h2>

<p>Attention mechanisms in transformers capture complex dependencies between input tokens, encoding structure, relationships, and context. Distilling these attention patterns is harder than distilling outputs because attention matrices are large and sensitive to architectural differences. Attention transfer methods usually focus on preserving the structure of attention rather than exact weights.</p>

<p><img src="https://cdn.hashnode.com/uploads/covers/6557ff28afe2c15e65f8d100/157caed2-04ab-4ab7-932b-1b9cdcb17287.png align=&quot;center&quot;" alt="" /></p>

<p>The attention transfer loss measures the distance between teacher and student attention distributions, typically using mean squared error or KL divergence. You need to handle different numbers of attention heads. Some approaches average attention across heads before computing loss. Others maintain head-specific alignments, which preserves more detail but requires careful mapping.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">AttentionTransfer</span><span class="p">(</span><span class="n">nn</span><span class="p">.</span><span class="n">Module</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">student_heads</span><span class="p">,</span> <span class="n">teacher_heads</span><span class="p">,</span> <span class="n">use_head_mapping</span><span class="o">=</span><span class="bp">True</span><span class="p">):</span>
        <span class="nf">super</span><span class="p">().</span><span class="nf">__init__</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student_heads</span> <span class="o">=</span> <span class="n">student_heads</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teacher_heads</span> <span class="o">=</span> <span class="n">teacher_heads</span>
        <span class="n">self</span><span class="p">.</span><span class="n">use_head_mapping</span> <span class="o">=</span> <span class="n">use_head_mapping</span>
        
        <span class="k">if</span> <span class="n">use_head_mapping</span> <span class="ow">and</span> <span class="n">student_heads</span> <span class="o">!=</span> <span class="n">teacher_heads</span><span class="p">:</span>
            <span class="c1"># Learn which teacher heads to map to which student heads
</span>            <span class="n">self</span><span class="p">.</span><span class="n">head_mapping</span> <span class="o">=</span> <span class="n">nn</span><span class="p">.</span><span class="nc">Parameter</span><span class="p">(</span>
                <span class="n">torch</span><span class="p">.</span><span class="nf">randn</span><span class="p">(</span><span class="n">student_heads</span><span class="p">,</span> <span class="n">teacher_heads</span><span class="p">)</span>
            <span class="p">)</span>
    
    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">student_attentions</span><span class="p">,</span> <span class="n">teacher_attentions</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Args:
            student_attentions: [batch, num_heads, seq_len, seq_len]
            teacher_attentions: [batch, num_heads, seq_len, seq_len]
        </span><span class="sh">"""</span>
        <span class="n">batch_size</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">seq_len</span><span class="p">,</span> <span class="n">_</span> <span class="o">=</span> <span class="n">student_attentions</span><span class="p">.</span><span class="n">shape</span>
        
        <span class="k">if</span> <span class="n">self</span><span class="p">.</span><span class="n">use_head_mapping</span> <span class="ow">and</span> <span class="nf">hasattr</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="sh">'</span><span class="s">head_mapping</span><span class="sh">'</span><span class="p">):</span>
            <span class="c1"># Apply learned head mapping
</span>            <span class="n">mapping_weights</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">softmax</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">head_mapping</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
            <span class="c1"># [student_heads, teacher_heads] × [batch, teacher_heads, seq, seq]
</span>            <span class="n">teacher_mapped</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="nf">einsum</span><span class="p">(</span>
                <span class="sh">'</span><span class="s">st,bthw-&gt;bshw</span><span class="sh">'</span><span class="p">,</span> 
                <span class="n">mapping_weights</span><span class="p">,</span> 
                <span class="n">teacher_attentions</span>
            <span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c1"># Simple averaging if heads match or no mapping desired
</span>            <span class="k">if</span> <span class="n">self</span><span class="p">.</span><span class="n">student_heads</span> <span class="o">==</span> <span class="n">self</span><span class="p">.</span><span class="n">teacher_heads</span><span class="p">:</span>
                <span class="n">teacher_mapped</span> <span class="o">=</span> <span class="n">teacher_attentions</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="c1"># Average teacher heads to match student count
</span>                <span class="n">teacher_mapped</span> <span class="o">=</span> <span class="n">teacher_attentions</span><span class="p">.</span><span class="nf">reshape</span><span class="p">(</span>
                    <span class="n">batch_size</span><span class="p">,</span> <span class="n">self</span><span class="p">.</span><span class="n">student_heads</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="n">seq_len</span><span class="p">,</span> <span class="n">seq_len</span>
                <span class="p">).</span><span class="nf">mean</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
        
        <span class="c1"># MSE between attention distributions
</span>        <span class="n">attention_loss</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">mse_loss</span><span class="p">(</span><span class="n">student_attentions</span><span class="p">,</span> <span class="n">teacher_mapped</span><span class="p">.</span><span class="nf">detach</span><span class="p">())</span>
        
        <span class="k">return</span> <span class="n">attention_loss</span>
</code></pre></div></div>

<h2 id="progressive-distillation"><a href="#progressive-distillation"></a>Progressive Distillation</h2>

<p>Progressive distillation solves the problem of distilling very large teachers into very small students by using intermediate teachers. Instead of going straight from a GPT-3 scale model to a mobile-friendly size, you create a series of progressively smaller teachers, each distilled from the previous one. This staged approach lets each student learn from a teacher closer to its own capacity, which reduces the knowledge gap and improves final performance.</p>

<p><img src="https://cdn.hashnode.com/uploads/covers/6557ff28afe2c15e65f8d100/e04e6415-d051-4d47-b391-927771aafd5b.png align=&quot;center&quot;" alt="" /></p>

<p>Curriculum learning in distillation means carefully ordering training examples. Early on, the student learns from easier examples where the teacher is more confident. As training goes on, you introduce more ambiguous cases where the teacher’s soft labels provide maximum information. You can define this curriculum based on prediction entropy, loss magnitude, or example complexity.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ProgressiveDistillationTrainer</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">teachers</span><span class="p">,</span> <span class="n">student</span><span class="p">,</span> <span class="n">device</span><span class="o">=</span><span class="sh">'</span><span class="s">cuda</span><span class="sh">'</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Args:
            teachers: List of teacher models ordered from largest to smallest
            student: Student model to train
        </span><span class="sh">"""</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teachers</span> <span class="o">=</span> <span class="n">teachers</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span> <span class="o">=</span> <span class="n">student</span>
        <span class="n">self</span><span class="p">.</span><span class="n">device</span> <span class="o">=</span> <span class="n">device</span>
        
        <span class="c1"># Move all models to device and set teachers to eval
</span>        <span class="k">for</span> <span class="n">teacher</span> <span class="ow">in</span> <span class="n">self</span><span class="p">.</span><span class="n">teachers</span><span class="p">:</span>
            <span class="n">teacher</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="n">device</span><span class="p">)</span>
            <span class="n">teacher</span><span class="p">.</span><span class="nf">eval</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="n">device</span><span class="p">)</span>
    
    <span class="k">def</span> <span class="nf">get_curriculum_weight</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">epoch</span><span class="p">,</span> <span class="n">total_epochs</span><span class="p">):</span>
        <span class="c1"># Linearly increase difficulty over training
</span>        <span class="k">return</span> <span class="nf">min</span><span class="p">(</span><span class="mf">1.0</span><span class="p">,</span> <span class="n">epoch</span> <span class="o">/</span> <span class="p">(</span><span class="n">total_epochs</span> <span class="o">*</span> <span class="mf">0.7</span><span class="p">))</span>
    
    <span class="k">def</span> <span class="nf">compute_example_difficulty</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">teacher_logits</span><span class="p">):</span>
        <span class="c1"># Use entropy of teacher predictions as difficulty measure
</span>        <span class="n">probs</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">softmax</span><span class="p">(</span><span class="n">teacher_logits</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">entropy</span> <span class="o">=</span> <span class="o">-</span><span class="p">(</span><span class="n">probs</span> <span class="o">*</span> <span class="n">torch</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="n">probs</span> <span class="o">+</span> <span class="mf">1e-10</span><span class="p">)).</span><span class="nf">sum</span><span class="p">(</span><span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">entropy</span>
    
    <span class="k">def</span> <span class="nf">progressive_distill</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">dataloader</span><span class="p">,</span> <span class="n">stage</span><span class="p">,</span> <span class="n">optimizer</span><span class="p">,</span> 
                           <span class="n">temperature</span><span class="o">=</span><span class="mf">3.0</span><span class="p">,</span> <span class="n">epochs</span><span class="o">=</span><span class="mi">10</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Distill from teachers[stage] into student or next teacher
        </span><span class="sh">"""</span>
        <span class="n">current_teacher</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">teachers</span><span class="p">[</span><span class="n">stage</span><span class="p">]</span>
        <span class="n">criterion</span> <span class="o">=</span> <span class="nc">DistillationLoss</span><span class="p">(</span><span class="n">temperature</span><span class="o">=</span><span class="n">temperature</span><span class="p">)</span>
        
        <span class="k">for</span> <span class="n">epoch</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="n">epochs</span><span class="p">):</span>
            <span class="n">curriculum_weight</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">get_curriculum_weight</span><span class="p">(</span><span class="n">epoch</span><span class="p">,</span> <span class="n">epochs</span><span class="p">)</span>
            
            <span class="k">for</span> <span class="n">batch</span> <span class="ow">in</span> <span class="n">dataloader</span><span class="p">:</span>
                <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span> <span class="o">=</span> <span class="n">batch</span>
                <span class="n">inputs</span> <span class="o">=</span> <span class="n">inputs</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">device</span><span class="p">)</span>
                <span class="n">labels</span> <span class="o">=</span> <span class="n">labels</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">device</span><span class="p">)</span>
                
                <span class="c1"># Get teacher predictions
</span>                <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="nf">no_grad</span><span class="p">():</span>
                    <span class="n">teacher_logits</span> <span class="o">=</span> <span class="nf">current_teacher</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
                    <span class="n">difficulties</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">compute_example_difficulty</span><span class="p">(</span><span class="n">teacher_logits</span><span class="p">)</span>
                
                <span class="c1"># Filter or weight examples based on curriculum
</span>                <span class="n">difficulty_threshold</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="nf">quantile</span><span class="p">(</span>
                    <span class="n">difficulties</span><span class="p">,</span> <span class="n">curriculum_weight</span>
                <span class="p">)</span>
                <span class="n">example_weights</span> <span class="o">=</span> <span class="p">(</span><span class="n">difficulties</span> <span class="o">&lt;=</span> <span class="n">difficulty_threshold</span><span class="p">).</span><span class="nf">float</span><span class="p">()</span>
                
                <span class="c1"># Student forward pass
</span>                <span class="n">student_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">student</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
                
                <span class="c1"># Compute weighted distillation loss
</span>                <span class="n">loss</span> <span class="o">=</span> <span class="nf">criterion</span><span class="p">(</span><span class="n">student_logits</span><span class="p">,</span> <span class="n">teacher_logits</span><span class="p">,</span> <span class="n">labels</span><span class="p">)</span>
                <span class="n">weighted_loss</span> <span class="o">=</span> <span class="p">(</span><span class="n">loss</span> <span class="o">*</span> <span class="n">example_weights</span><span class="p">.</span><span class="nf">mean</span><span class="p">())</span>
                
                <span class="c1"># Optimization step
</span>                <span class="n">optimizer</span><span class="p">.</span><span class="nf">zero_grad</span><span class="p">()</span>
                <span class="n">weighted_loss</span><span class="p">.</span><span class="nf">backward</span><span class="p">()</span>
                <span class="n">optimizer</span><span class="p">.</span><span class="nf">step</span><span class="p">()</span>
    
    <span class="k">def</span> <span class="nf">train_all_stages</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">dataloader</span><span class="p">,</span> <span class="n">optimizer</span><span class="p">,</span> <span class="n">epochs_per_stage</span><span class="o">=</span><span class="mi">10</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Execute progressive distillation through all teacher stages
        </span><span class="sh">"""</span>
        <span class="k">for</span> <span class="n">stage</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="nf">len</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">teachers</span><span class="p">)):</span>
            <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Stage </span><span class="si">{</span><span class="n">stage</span><span class="si">}</span><span class="s">: Distilling from teacher </span><span class="si">{</span><span class="n">stage</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
            <span class="n">self</span><span class="p">.</span><span class="nf">progressive_distill</span><span class="p">(</span>
                <span class="n">dataloader</span><span class="p">,</span> <span class="n">stage</span><span class="p">,</span> <span class="n">optimizer</span><span class="p">,</span> <span class="n">epochs</span><span class="o">=</span><span class="n">epochs_per_stage</span>
            <span class="p">)</span>
        
        <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="n">student</span>
</code></pre></div></div>

<h2 id="task-specific-and-multi-task-distillation"><a href="#task-specific-and-multi-task-distillation"></a>Task-Specific and Multi-Task Distillation</h2>

<p>General distillation trains students to match teacher behavior across all tasks. Task-specific distillation optimizes for particular applications. This lets you compress more aggressively because the student only needs knowledge relevant to the target task. For example, distilling a general language model into a sentiment classifier can achieve much higher compression while maintaining or exceeding task performance.</p>

<p>Multi-task distillation extends this by training the student on multiple related tasks at once. The teacher might be an ensemble of task-specific expert models, and the student learns to handle all tasks in one architecture. This works well when tasks share underlying patterns, letting the student develop shared representations that generalize across tasks.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">MultiTaskDistillation</span><span class="p">(</span><span class="n">nn</span><span class="p">.</span><span class="n">Module</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">task_weights</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="nf">super</span><span class="p">().</span><span class="nf">__init__</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">task_weights</span> <span class="o">=</span> <span class="n">task_weights</span> <span class="ow">or</span> <span class="p">{}</span>
    
    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">student_outputs</span><span class="p">,</span> <span class="n">teacher_outputs</span><span class="p">,</span> <span class="n">task_names</span><span class="p">,</span> <span class="n">labels</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Args:
            student_outputs: Dict mapping task names to student logits
            teacher_outputs: Dict mapping task names to teacher logits
            task_names: List of tasks in current batch
            labels: Dict mapping task names to ground truth labels
        </span><span class="sh">"""</span>
        <span class="n">total_loss</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">task_losses</span> <span class="o">=</span> <span class="p">{}</span>
        
        <span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">task_names</span><span class="p">:</span>
            <span class="c1"># Task-specific distillation loss
</span>            <span class="n">criterion</span> <span class="o">=</span> <span class="nc">DistillationLoss</span><span class="p">(</span>
                <span class="n">temperature</span><span class="o">=</span><span class="n">self</span><span class="p">.</span><span class="nf">get_task_temperature</span><span class="p">(</span><span class="n">task</span><span class="p">),</span>
                <span class="n">alpha</span><span class="o">=</span><span class="n">self</span><span class="p">.</span><span class="nf">get_task_alpha</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
            <span class="p">)</span>
            
            <span class="n">task_loss</span> <span class="o">=</span> <span class="nf">criterion</span><span class="p">(</span>
                <span class="n">student_outputs</span><span class="p">[</span><span class="n">task</span><span class="p">],</span>
                <span class="n">teacher_outputs</span><span class="p">[</span><span class="n">task</span><span class="p">],</span>
                <span class="n">labels</span><span class="p">[</span><span class="n">task</span><span class="p">]</span>
            <span class="p">)</span>
            
            <span class="c1"># Weight by task importance
</span>            <span class="n">weight</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">task_weights</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="n">task</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">)</span>
            <span class="n">total_loss</span> <span class="o">+=</span> <span class="n">weight</span> <span class="o">*</span> <span class="n">task_loss</span>
            <span class="n">task_losses</span><span class="p">[</span><span class="n">task</span><span class="p">]</span> <span class="o">=</span> <span class="n">task_loss</span><span class="p">.</span><span class="nf">item</span><span class="p">()</span>
        
        <span class="k">return</span> <span class="n">total_loss</span><span class="p">,</span> <span class="n">task_losses</span>
    
    <span class="k">def</span> <span class="nf">get_task_temperature</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">task</span><span class="p">):</span>
        <span class="c1"># Different tasks may benefit from different temperatures
</span>        <span class="n">temperature_map</span> <span class="o">=</span> <span class="p">{</span>
            <span class="sh">'</span><span class="s">sentiment</span><span class="sh">'</span><span class="p">:</span> <span class="mf">2.0</span><span class="p">,</span>      <span class="c1"># Lower for classification
</span>            <span class="sh">'</span><span class="s">nli</span><span class="sh">'</span><span class="p">:</span> <span class="mf">3.0</span><span class="p">,</span>            <span class="c1"># Higher for complex reasoning
</span>            <span class="sh">'</span><span class="s">qa</span><span class="sh">'</span><span class="p">:</span> <span class="mf">4.0</span><span class="p">,</span>             <span class="c1"># Highest for generation tasks
</span>        <span class="p">}</span>
        <span class="k">return</span> <span class="n">temperature_map</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="n">task</span><span class="p">,</span> <span class="mf">3.0</span><span class="p">)</span>
    
    <span class="k">def</span> <span class="nf">get_task_alpha</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">task</span><span class="p">):</span>
        <span class="c1"># Balance between distillation and hard labels per task
</span>        <span class="n">alpha_map</span> <span class="o">=</span> <span class="p">{</span>
            <span class="sh">'</span><span class="s">sentiment</span><span class="sh">'</span><span class="p">:</span> <span class="mf">0.5</span><span class="p">,</span>      <span class="c1"># More weight on hard labels
</span>            <span class="sh">'</span><span class="s">nli</span><span class="sh">'</span><span class="p">:</span> <span class="mf">0.7</span><span class="p">,</span>            <span class="c1"># Balanced
</span>            <span class="sh">'</span><span class="s">qa</span><span class="sh">'</span><span class="p">:</span> <span class="mf">0.9</span><span class="p">,</span>             <span class="c1"># Heavy distillation weight
</span>        <span class="p">}</span>
        <span class="k">return</span> <span class="n">alpha_map</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="n">task</span><span class="p">,</span> <span class="mf">0.7</span><span class="p">)</span>
</code></pre></div></div>

<h2 id="data-augmentation-and-synthetic-data"><a href="#data-augmentation-and-synthetic-data"></a>Data Augmentation and Synthetic Data</h2>

<p>How well distillation works depends heavily on the diversity and quality of training data. Basic distillation uses the same dataset that trained the teacher. Augmented distillation generates synthetic examples to expose the student to more teacher behaviors. The teacher generates labels for unlabeled data, greatly expanding the training set. This works especially well with task-specific augmentation strategies that target challenging cases or underrepresented patterns.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">DataAugmentedDistillation</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">teacher</span><span class="p">,</span> <span class="n">student</span><span class="p">,</span> <span class="n">base_dataset</span><span class="p">):</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teacher</span> <span class="o">=</span> <span class="n">teacher</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span> <span class="o">=</span> <span class="n">student</span>
        <span class="n">self</span><span class="p">.</span><span class="n">base_dataset</span> <span class="o">=</span> <span class="n">base_dataset</span>
        
    <span class="k">def</span> <span class="nf">generate_synthetic_examples</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">num_examples</span><span class="p">,</span> <span class="n">augmentation_fn</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Generate synthetic training examples using the teacher
        </span><span class="sh">"""</span>
        <span class="n">synthetic_data</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teacher</span><span class="p">.</span><span class="nf">eval</span><span class="p">()</span>
        
        <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="nf">no_grad</span><span class="p">():</span>
            <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="n">num_examples</span><span class="p">):</span>
                <span class="c1"># Sample from base dataset and augment
</span>                <span class="n">base_example</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">base_dataset</span><span class="p">[</span>
                    <span class="n">torch</span><span class="p">.</span><span class="nf">randint</span><span class="p">(</span><span class="nf">len</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">base_dataset</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,)).</span><span class="nf">item</span><span class="p">()</span>
                <span class="p">]</span>
                <span class="n">augmented_input</span> <span class="o">=</span> <span class="nf">augmentation_fn</span><span class="p">(</span><span class="n">base_example</span><span class="p">)</span>
                
                <span class="c1"># Generate teacher predictions
</span>                <span class="n">teacher_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">teacher</span><span class="p">(</span><span class="n">augmented_input</span><span class="p">)</span>
                
                <span class="n">synthetic_data</span><span class="p">.</span><span class="nf">append</span><span class="p">({</span>
                    <span class="sh">'</span><span class="s">input</span><span class="sh">'</span><span class="p">:</span> <span class="n">augmented_input</span><span class="p">,</span>
                    <span class="sh">'</span><span class="s">teacher_logits</span><span class="sh">'</span><span class="p">:</span> <span class="n">teacher_logits</span><span class="p">.</span><span class="nf">cpu</span><span class="p">(),</span>
                    <span class="sh">'</span><span class="s">source</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">synthetic</span><span class="sh">'</span>
                <span class="p">})</span>
        
        <span class="k">return</span> <span class="n">synthetic_data</span>
    
    <span class="k">def</span> <span class="nf">hard_example_mining</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">dataloader</span><span class="p">,</span> <span class="n">percentile</span><span class="o">=</span><span class="mi">90</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Identify examples where student struggles most
        </span><span class="sh">"""</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span><span class="p">.</span><span class="nf">eval</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teacher</span><span class="p">.</span><span class="nf">eval</span><span class="p">()</span>
        
        <span class="n">example_difficulties</span> <span class="o">=</span> <span class="p">[]</span>
        
        <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="nf">no_grad</span><span class="p">():</span>
            <span class="k">for</span> <span class="n">batch</span> <span class="ow">in</span> <span class="n">dataloader</span><span class="p">:</span>
                <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span> <span class="o">=</span> <span class="n">batch</span>
                
                <span class="n">student_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">student</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
                <span class="n">teacher_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">teacher</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
                
                <span class="c1"># Measure disagreement as difficulty proxy
</span>                <span class="n">disagreement</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">kl_div</span><span class="p">(</span>
                    <span class="n">F</span><span class="p">.</span><span class="nf">log_softmax</span><span class="p">(</span><span class="n">student_logits</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">),</span>
                    <span class="n">F</span><span class="p">.</span><span class="nf">softmax</span><span class="p">(</span><span class="n">teacher_logits</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">),</span>
                    <span class="n">reduction</span><span class="o">=</span><span class="sh">'</span><span class="s">none</span><span class="sh">'</span>
                <span class="p">).</span><span class="nf">sum</span><span class="p">(</span><span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
                
                <span class="n">example_difficulties</span><span class="p">.</span><span class="nf">extend</span><span class="p">(</span><span class="n">disagreement</span><span class="p">.</span><span class="nf">cpu</span><span class="p">().</span><span class="nf">numpy</span><span class="p">())</span>
        
        <span class="c1"># Return indices of hardest examples
</span>        <span class="n">threshold</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">percentile</span><span class="p">(</span><span class="n">example_difficulties</span><span class="p">,</span> <span class="n">percentile</span><span class="p">)</span>
        <span class="n">hard_indices</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span>
            <span class="n">np</span><span class="p">.</span><span class="nf">array</span><span class="p">(</span><span class="n">example_difficulties</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="n">threshold</span>
        <span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
        
        <span class="k">return</span> <span class="n">hard_indices</span>
</code></pre></div></div>

<h2 id="training-stability-and-optimization"><a href="#training-stability-and-optimization"></a>Training Stability and Optimization</h2>

<p>The optimization landscape for distillation differs from standard supervised learning. The teacher’s soft labels provide a smoother training signal than one-hot labels, which can speed up convergence but also cause instability if not managed carefully. Temperature directly affects gradient magnitudes, and improper tuning can lead to gradient explosion or vanishing gradients.</p>

<p><img src="https://cdn.hashnode.com/uploads/covers/6557ff28afe2c15e65f8d100/4ae39610-097f-4ebb-8dce-874d5c5544dc.png align=&quot;center&quot;" alt="" /></p>

<p>Learning rate scheduling is critical for success. A common strategy uses a warmup phase where the learning rate gradually increases, letting the student stabilize before full distillation. During main training, maintain a moderate learning rate with high temperature. Finally, a fine-tuning phase with reduced temperature and learning rate polishes performance.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">DistillationOptimizer</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">student</span><span class="p">,</span> <span class="n">initial_lr</span><span class="o">=</span><span class="mf">1e-4</span><span class="p">,</span> <span class="n">warmup_steps</span><span class="o">=</span><span class="mi">1000</span><span class="p">):</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span> <span class="o">=</span> <span class="n">student</span>
        <span class="n">self</span><span class="p">.</span><span class="n">initial_lr</span> <span class="o">=</span> <span class="n">initial_lr</span>
        <span class="n">self</span><span class="p">.</span><span class="n">warmup_steps</span> <span class="o">=</span> <span class="n">warmup_steps</span>
        <span class="n">self</span><span class="p">.</span><span class="n">global_step</span> <span class="o">=</span> <span class="mi">0</span>
        
        <span class="c1"># Use AdamW with weight decay for better generalization
</span>        <span class="n">self</span><span class="p">.</span><span class="n">optimizer</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">optim</span><span class="p">.</span><span class="nc">AdamW</span><span class="p">(</span>
            <span class="n">student</span><span class="p">.</span><span class="nf">parameters</span><span class="p">(),</span>
            <span class="n">lr</span><span class="o">=</span><span class="n">initial_lr</span><span class="p">,</span>
            <span class="n">betas</span><span class="o">=</span><span class="p">(</span><span class="mf">0.9</span><span class="p">,</span> <span class="mf">0.999</span><span class="p">),</span>
            <span class="n">weight_decay</span><span class="o">=</span><span class="mf">0.01</span>
        <span class="p">)</span>
        
        <span class="n">self</span><span class="p">.</span><span class="n">scheduler</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">_create_scheduler</span><span class="p">()</span>
    
    <span class="k">def</span> <span class="nf">_create_scheduler</span><span class="p">(</span><span class="n">self</span><span class="p">):</span>
        <span class="c1"># Cosine schedule with warmup
</span>        <span class="kn">from</span> <span class="n">torch.optim.lr_scheduler</span> <span class="kn">import</span> <span class="n">LambdaLR</span>
        
        <span class="k">def</span> <span class="nf">lr_lambda</span><span class="p">(</span><span class="n">step</span><span class="p">):</span>
            <span class="k">if</span> <span class="n">step</span> <span class="o">&lt;</span> <span class="n">self</span><span class="p">.</span><span class="n">warmup_steps</span><span class="p">:</span>
                <span class="c1"># Linear warmup
</span>                <span class="k">return</span> <span class="n">step</span> <span class="o">/</span> <span class="n">self</span><span class="p">.</span><span class="n">warmup_steps</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="c1"># Cosine decay
</span>                <span class="n">progress</span> <span class="o">=</span> <span class="p">(</span><span class="n">step</span> <span class="o">-</span> <span class="n">self</span><span class="p">.</span><span class="n">warmup_steps</span><span class="p">)</span> <span class="o">/</span> <span class="p">(</span><span class="mi">10000</span> <span class="o">-</span> <span class="n">self</span><span class="p">.</span><span class="n">warmup_steps</span><span class="p">)</span>
                <span class="k">return</span> <span class="mf">0.5</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</span> <span class="o">+</span> <span class="n">np</span><span class="p">.</span><span class="nf">cos</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">pi</span> <span class="o">*</span> <span class="n">progress</span><span class="p">))</span>
        
        <span class="k">return</span> <span class="nc">LambdaLR</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">optimizer</span><span class="p">,</span> <span class="n">lr_lambda</span><span class="p">)</span>
    
    <span class="k">def</span> <span class="nf">step</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">loss</span><span class="p">):</span>
        <span class="c1"># Gradient clipping for stability
</span>        <span class="n">torch</span><span class="p">.</span><span class="n">nn</span><span class="p">.</span><span class="n">utils</span><span class="p">.</span><span class="nf">clip_grad_norm_</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">student</span><span class="p">.</span><span class="nf">parameters</span><span class="p">(),</span> <span class="n">max_norm</span><span class="o">=</span><span class="mf">1.0</span><span class="p">)</span>
        
        <span class="n">self</span><span class="p">.</span><span class="n">optimizer</span><span class="p">.</span><span class="nf">step</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">scheduler</span><span class="p">.</span><span class="nf">step</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">global_step</span> <span class="o">+=</span> <span class="mi">1</span>
        
        <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="n">scheduler</span><span class="p">.</span><span class="nf">get_last_lr</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
    
    <span class="k">def</span> <span class="nf">get_temperature_schedule</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">max_steps</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Dynamic temperature scheduling during training
        </span><span class="sh">"""</span>
        <span class="k">if</span> <span class="n">self</span><span class="p">.</span><span class="n">global_step</span> <span class="o">&lt;</span> <span class="n">self</span><span class="p">.</span><span class="n">warmup_steps</span><span class="p">:</span>
            <span class="c1"># Start with lower temperature during warmup
</span>            <span class="k">return</span> <span class="mf">2.0</span>
        <span class="k">elif</span> <span class="n">self</span><span class="p">.</span><span class="n">global_step</span> <span class="o">&lt;</span> <span class="n">max_steps</span> <span class="o">*</span> <span class="mf">0.8</span><span class="p">:</span>
            <span class="c1"># Higher temperature for main distillation
</span>            <span class="k">return</span> <span class="mf">4.0</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c1"># Reduce temperature for fine-tuning
</span>            <span class="k">return</span> <span class="mf">2.0</span>
</code></pre></div></div>

<h2 id="evaluation-metrics"><a href="#evaluation-metrics"></a>Evaluation Metrics</h2>

<p>Evaluating distilled models requires more than just accuracy. You need to assess compression ratio, inference latency, memory footprint, and energy consumption. The distillation efficiency metric captures the trade-off between size reduction and performance retention, typically computed as the ratio of accuracy preservation to compression ratio.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">DistillationEvaluator</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">teacher</span><span class="p">,</span> <span class="n">student</span><span class="p">,</span> <span class="n">test_loader</span><span class="p">,</span> <span class="n">device</span><span class="o">=</span><span class="sh">'</span><span class="s">cuda</span><span class="sh">'</span><span class="p">):</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teacher</span> <span class="o">=</span> <span class="n">teacher</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span> <span class="o">=</span> <span class="n">student</span>
        <span class="n">self</span><span class="p">.</span><span class="n">test_loader</span> <span class="o">=</span> <span class="n">test_loader</span>
        <span class="n">self</span><span class="p">.</span><span class="n">device</span> <span class="o">=</span> <span class="n">device</span>
    
    <span class="k">def</span> <span class="nf">compute_compression_metrics</span><span class="p">(</span><span class="n">self</span><span class="p">):</span>
        <span class="n">teacher_params</span> <span class="o">=</span> <span class="nf">sum</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="nf">numel</span><span class="p">()</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">self</span><span class="p">.</span><span class="n">teacher</span><span class="p">.</span><span class="nf">parameters</span><span class="p">())</span>
        <span class="n">student_params</span> <span class="o">=</span> <span class="nf">sum</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="nf">numel</span><span class="p">()</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">self</span><span class="p">.</span><span class="n">student</span><span class="p">.</span><span class="nf">parameters</span><span class="p">())</span>
        
        <span class="n">compression_ratio</span> <span class="o">=</span> <span class="n">teacher_params</span> <span class="o">/</span> <span class="n">student_params</span>
        
        <span class="k">return</span> <span class="p">{</span>
            <span class="sh">'</span><span class="s">teacher_parameters</span><span class="sh">'</span><span class="p">:</span> <span class="n">teacher_params</span><span class="p">,</span>
            <span class="sh">'</span><span class="s">student_parameters</span><span class="sh">'</span><span class="p">:</span> <span class="n">student_params</span><span class="p">,</span>
            <span class="sh">'</span><span class="s">compression_ratio</span><span class="sh">'</span><span class="p">:</span> <span class="n">compression_ratio</span>
        <span class="p">}</span>
    
    <span class="k">def</span> <span class="nf">measure_inference_speed</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">num_samples</span><span class="o">=</span><span class="mi">100</span><span class="p">):</span>
        <span class="kn">import</span> <span class="n">time</span>
        
        <span class="n">self</span><span class="p">.</span><span class="n">teacher</span><span class="p">.</span><span class="nf">eval</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span><span class="p">.</span><span class="nf">eval</span><span class="p">()</span>
        
        <span class="c1"># Sample random inputs
</span>        <span class="n">sample_inputs</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">batch</span> <span class="ow">in</span> <span class="n">self</span><span class="p">.</span><span class="n">test_loader</span><span class="p">:</span>
            <span class="n">sample_inputs</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">batch</span><span class="p">[</span><span class="mi">0</span><span class="p">][:</span><span class="mi">1</span><span class="p">].</span><span class="nf">to</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">device</span><span class="p">))</span>
            <span class="k">if</span> <span class="nf">len</span><span class="p">(</span><span class="n">sample_inputs</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="n">num_samples</span><span class="p">:</span>
                <span class="k">break</span>
        
        <span class="c1"># Teacher inference time
</span>        <span class="n">teacher_times</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="nf">no_grad</span><span class="p">():</span>
            <span class="k">for</span> <span class="n">inputs</span> <span class="ow">in</span> <span class="n">sample_inputs</span><span class="p">:</span>
                <span class="n">start</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="nf">perf_counter</span><span class="p">()</span>
                <span class="n">_</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">teacher</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
                <span class="n">teacher_times</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">time</span><span class="p">.</span><span class="nf">perf_counter</span><span class="p">()</span> <span class="o">-</span> <span class="n">start</span><span class="p">)</span>
        
        <span class="c1"># Student inference time
</span>        <span class="n">student_times</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="nf">no_grad</span><span class="p">():</span>
            <span class="k">for</span> <span class="n">inputs</span> <span class="ow">in</span> <span class="n">sample_inputs</span><span class="p">:</span>
                <span class="n">start</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="nf">perf_counter</span><span class="p">()</span>
                <span class="n">_</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">student</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
                <span class="n">student_times</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">time</span><span class="p">.</span><span class="nf">perf_counter</span><span class="p">()</span> <span class="o">-</span> <span class="n">start</span><span class="p">)</span>
        
        <span class="n">speedup</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">mean</span><span class="p">(</span><span class="n">teacher_times</span><span class="p">)</span> <span class="o">/</span> <span class="n">np</span><span class="p">.</span><span class="nf">mean</span><span class="p">(</span><span class="n">student_times</span><span class="p">)</span>
        
        <span class="k">return</span> <span class="p">{</span>
            <span class="sh">'</span><span class="s">teacher_latency_ms</span><span class="sh">'</span><span class="p">:</span> <span class="n">np</span><span class="p">.</span><span class="nf">mean</span><span class="p">(</span><span class="n">teacher_times</span><span class="p">)</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">,</span>
            <span class="sh">'</span><span class="s">student_latency_ms</span><span class="sh">'</span><span class="p">:</span> <span class="n">np</span><span class="p">.</span><span class="nf">mean</span><span class="p">(</span><span class="n">student_times</span><span class="p">)</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">,</span>
            <span class="sh">'</span><span class="s">speedup_factor</span><span class="sh">'</span><span class="p">:</span> <span class="n">speedup</span>
        <span class="p">}</span>
    
    <span class="k">def</span> <span class="nf">compute_agreement_metrics</span><span class="p">(</span><span class="n">self</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Measure how well student predictions agree with teacher
        </span><span class="sh">"""</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teacher</span><span class="p">.</span><span class="nf">eval</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span><span class="p">.</span><span class="nf">eval</span><span class="p">()</span>
        
        <span class="n">total_kl</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">total_top1_agreement</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">total_samples</span> <span class="o">=</span> <span class="mi">0</span>
        
        <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="nf">no_grad</span><span class="p">():</span>
            <span class="k">for</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span> <span class="ow">in</span> <span class="n">self</span><span class="p">.</span><span class="n">test_loader</span><span class="p">:</span>
                <span class="n">inputs</span> <span class="o">=</span> <span class="n">inputs</span><span class="p">.</span><span class="nf">to</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">device</span><span class="p">)</span>
                
                <span class="n">teacher_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">teacher</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
                <span class="n">student_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">student</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
                
                <span class="c1"># KL divergence
</span>                <span class="n">kl</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">kl_div</span><span class="p">(</span>
                    <span class="n">F</span><span class="p">.</span><span class="nf">log_softmax</span><span class="p">(</span><span class="n">student_logits</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">),</span>
                    <span class="n">F</span><span class="p">.</span><span class="nf">softmax</span><span class="p">(</span><span class="n">teacher_logits</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">),</span>
                    <span class="n">reduction</span><span class="o">=</span><span class="sh">'</span><span class="s">batchmean</span><span class="sh">'</span>
                <span class="p">)</span>
                <span class="n">total_kl</span> <span class="o">+=</span> <span class="n">kl</span><span class="p">.</span><span class="nf">item</span><span class="p">()</span> <span class="o">*</span> <span class="n">inputs</span><span class="p">.</span><span class="nf">size</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
                
                <span class="c1"># Top-1 agreement
</span>                <span class="n">teacher_preds</span> <span class="o">=</span> <span class="n">teacher_logits</span><span class="p">.</span><span class="nf">argmax</span><span class="p">(</span><span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
                <span class="n">student_preds</span> <span class="o">=</span> <span class="n">student_logits</span><span class="p">.</span><span class="nf">argmax</span><span class="p">(</span><span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
                <span class="n">agreement</span> <span class="o">=</span> <span class="p">(</span><span class="n">teacher_preds</span> <span class="o">==</span> <span class="n">student_preds</span><span class="p">).</span><span class="nf">float</span><span class="p">().</span><span class="nf">mean</span><span class="p">()</span>
                <span class="n">total_top1_agreement</span> <span class="o">+=</span> <span class="n">agreement</span><span class="p">.</span><span class="nf">item</span><span class="p">()</span> <span class="o">*</span> <span class="n">inputs</span><span class="p">.</span><span class="nf">size</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
                
                <span class="n">total_samples</span> <span class="o">+=</span> <span class="n">inputs</span><span class="p">.</span><span class="nf">size</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
        
        <span class="k">return</span> <span class="p">{</span>
            <span class="sh">'</span><span class="s">average_kl_divergence</span><span class="sh">'</span><span class="p">:</span> <span class="n">total_kl</span> <span class="o">/</span> <span class="n">total_samples</span><span class="p">,</span>
            <span class="sh">'</span><span class="s">top1_agreement</span><span class="sh">'</span><span class="p">:</span> <span class="n">total_top1_agreement</span> <span class="o">/</span> <span class="n">total_samples</span>
        <span class="p">}</span>
    
    <span class="k">def</span> <span class="nf">full_evaluation</span><span class="p">(</span><span class="n">self</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Comprehensive evaluation of distillation quality
        </span><span class="sh">"""</span>
        <span class="n">metrics</span> <span class="o">=</span> <span class="p">{}</span>
        
        <span class="c1"># Compression metrics
</span>        <span class="n">metrics</span><span class="p">.</span><span class="nf">update</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="nf">compute_compression_metrics</span><span class="p">())</span>
        
        <span class="c1"># Speed metrics
</span>        <span class="n">metrics</span><span class="p">.</span><span class="nf">update</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="nf">measure_inference_speed</span><span class="p">())</span>
        
        <span class="c1"># Agreement metrics
</span>        <span class="n">metrics</span><span class="p">.</span><span class="nf">update</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="nf">compute_agreement_metrics</span><span class="p">())</span>
        
        <span class="c1"># Efficiency score: accuracy preservation per unit compression
</span>        <span class="n">metrics</span><span class="p">[</span><span class="sh">'</span><span class="s">efficiency_score</span><span class="sh">'</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span>
            <span class="n">metrics</span><span class="p">[</span><span class="sh">'</span><span class="s">top1_agreement</span><span class="sh">'</span><span class="p">]</span> <span class="o">*</span> <span class="n">metrics</span><span class="p">[</span><span class="sh">'</span><span class="s">compression_ratio</span><span class="sh">'</span><span class="p">]</span>
        <span class="p">)</span>
        
        <span class="k">return</span> <span class="n">metrics</span>
</code></pre></div></div>

<h2 id="advanced-techniques"><a href="#advanced-techniques"></a>Advanced Techniques</h2>

<p>Recent advances have introduced several techniques that go beyond traditional knowledge transfer. Online distillation trains teacher and student simultaneously, with the teacher continuously updating rather than staying frozen. This co-evolution can lead to mutually beneficial learning where the student’s progress informs teacher updates. Self-distillation applies distillation to the same architecture, using ensemble predictions or differently initialized models as teachers, which can improve performance even without compression.</p>

<p>Born-again networks are an extreme form of self-distillation where a student with the same architecture as the teacher often beats the teacher’s performance. This suggests distillation provides more than just compression—it offers an improved optimization landscape and implicit regularization. Applying born-again distillation iteratively, where each generation serves as the teacher for the next, can progressively improve performance until it converges.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">OnlineDistillation</span><span class="p">(</span><span class="n">nn</span><span class="p">.</span><span class="n">Module</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">teacher</span><span class="p">,</span> <span class="n">student</span><span class="p">,</span> <span class="n">teacher_update_freq</span><span class="o">=</span><span class="mi">10</span><span class="p">):</span>
        <span class="nf">super</span><span class="p">().</span><span class="nf">__init__</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teacher</span> <span class="o">=</span> <span class="n">teacher</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student</span> <span class="o">=</span> <span class="n">student</span>
        <span class="n">self</span><span class="p">.</span><span class="n">teacher_update_freq</span> <span class="o">=</span> <span class="n">teacher_update_freq</span>
        <span class="n">self</span><span class="p">.</span><span class="n">step_count</span> <span class="o">=</span> <span class="mi">0</span>
        
        <span class="c1"># Initialize teacher with student parameters
</span>        <span class="n">self</span><span class="p">.</span><span class="n">teacher</span><span class="p">.</span><span class="nf">load_state_dict</span><span class="p">(</span><span class="n">student</span><span class="p">.</span><span class="nf">state_dict</span><span class="p">())</span>
        
        <span class="c1"># Separate optimizers for teacher and student
</span>        <span class="n">self</span><span class="p">.</span><span class="n">teacher_optimizer</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">optim</span><span class="p">.</span><span class="nc">AdamW</span><span class="p">(</span>
            <span class="n">teacher</span><span class="p">.</span><span class="nf">parameters</span><span class="p">(),</span> <span class="n">lr</span><span class="o">=</span><span class="mf">1e-5</span>
        <span class="p">)</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student_optimizer</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">optim</span><span class="p">.</span><span class="nc">AdamW</span><span class="p">(</span>
            <span class="n">student</span><span class="p">.</span><span class="nf">parameters</span><span class="p">(),</span> <span class="n">lr</span><span class="o">=</span><span class="mf">1e-4</span>
        <span class="p">)</span>
    
    <span class="k">def</span> <span class="nf">train_step</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span><span class="p">,</span> <span class="n">temperature</span><span class="o">=</span><span class="mf">3.0</span><span class="p">):</span>
        <span class="c1"># Student learning from current teacher
</span>        <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="nf">no_grad</span><span class="p">():</span>
            <span class="n">teacher_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">teacher</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
        
        <span class="n">student_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">student</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
        
        <span class="n">criterion</span> <span class="o">=</span> <span class="nc">DistillationLoss</span><span class="p">(</span><span class="n">temperature</span><span class="o">=</span><span class="n">temperature</span><span class="p">)</span>
        <span class="n">student_loss</span> <span class="o">=</span> <span class="nf">criterion</span><span class="p">(</span><span class="n">student_logits</span><span class="p">,</span> <span class="n">teacher_logits</span><span class="p">,</span> <span class="n">labels</span><span class="p">)</span>
        
        <span class="n">self</span><span class="p">.</span><span class="n">student_optimizer</span><span class="p">.</span><span class="nf">zero_grad</span><span class="p">()</span>
        <span class="n">student_loss</span><span class="p">.</span><span class="nf">backward</span><span class="p">()</span>
        <span class="n">self</span><span class="p">.</span><span class="n">student_optimizer</span><span class="p">.</span><span class="nf">step</span><span class="p">()</span>
        
        <span class="c1"># Periodically update teacher
</span>        <span class="n">self</span><span class="p">.</span><span class="n">step_count</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="k">if</span> <span class="n">self</span><span class="p">.</span><span class="n">step_count</span> <span class="o">%</span> <span class="n">self</span><span class="p">.</span><span class="n">teacher_update_freq</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="c1"># Teacher learns from student's predictions
</span>            <span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="nf">no_grad</span><span class="p">():</span>
                <span class="n">student_logits_detached</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">student</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
            
            <span class="n">teacher_logits</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">teacher</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
            <span class="n">teacher_loss</span> <span class="o">=</span> <span class="nf">criterion</span><span class="p">(</span><span class="n">teacher_logits</span><span class="p">,</span> <span class="n">student_logits_detached</span><span class="p">,</span> <span class="n">labels</span><span class="p">)</span>
            
            <span class="n">self</span><span class="p">.</span><span class="n">teacher_optimizer</span><span class="p">.</span><span class="nf">zero_grad</span><span class="p">()</span>
            <span class="n">teacher_loss</span><span class="p">.</span><span class="nf">backward</span><span class="p">()</span>
            <span class="n">self</span><span class="p">.</span><span class="n">teacher_optimizer</span><span class="p">.</span><span class="nf">step</span><span class="p">()</span>
        
        <span class="k">return</span> <span class="n">student_loss</span><span class="p">.</span><span class="nf">item</span><span class="p">()</span>
</code></pre></div></div>

<h2 id="summary"><a href="#summary"></a>Summary</h2>

<p>Language model distillation enables knowledge transfer from large, expensive teachers to efficient students. The techniques include output distribution matching, intermediate representation alignment, attention transfer, and progressive multi-stage distillation. Success depends on temperature scaling, curriculum learning, optimization dynamics, and architecture mapping.</p>

<p>The field continues to develop with innovations in online distillation, cross-modal knowledge transfer, and task-specific compression. As language models grow larger, distillation becomes necessary for making state-of-the-art natural language understanding accessible to more people. The core insight is straightforward: knowledge encoded in billions of parameters can be compressed into millions while preserving the essential patterns that drive intelligent behavior.</p>]]></content><author><name>Arnav Verma</name><email>av4445@nyu.edu</email></author><category term="Knowledge Distillation" /><category term="LLM" /><category term="Model Compression" /><category term="PyTorch" /><summary type="html"><![CDATA[Training a small student model to behave like a large teacher: what the soft probabilities actually carry, how to transfer attention patterns when the two models are different sizes, and how to tell whether it worked.]]></summary></entry><entry><title type="html">Adapting LLaMA for NER Tasks</title><link href="https://namesarnav.com/blog/adapting-llama-for-ner-tasks/" rel="alternate" type="text/html" title="Adapting LLaMA for NER Tasks" /><published>2025-09-24T00:00:00+00:00</published><updated>2025-09-24T00:00:00+00:00</updated><id>https://namesarnav.com/blog/adapting-llama-for-ner-tasks</id><content type="html" xml:base="https://namesarnav.com/blog/adapting-llama-for-ner-tasks/"><![CDATA[<p>Named Entity Recognition (NER) is the task of finding and labeling entities like
dates, names, places and organizations in text. Most people use encoder models
such as BERT for this, but I wanted to try something different: training a LLaMA
model for token classification. To make training efficient, I used LoRA adapters
and 4-bit quantization.</p>

<p>I worked with a CoNLL-style dataset of about 90k samples, with just three labels:
<code class="language-plaintext highlighter-rouge">O</code>, <code class="language-plaintext highlighter-rouge">B-T</code>, and <code class="language-plaintext highlighter-rouge">I-T</code>. <code class="language-plaintext highlighter-rouge">T</code> stands for time — I wanted the model to recognize
temporal entities.</p>

<p>In this post I’ll go through how I prepared the dataset, set up the LLaMA model
for a PEFT config, prepared it for NER, handled the errors that came up, and
pushed the final model to Hugging Face for inference.</p>

<h2 id="preparing-the-dataset"><a href="#preparing-the-dataset"></a>Preparing the dataset</h2>

<p>The dataset was in <code class="language-plaintext highlighter-rouge">.conll</code> format, where each line has a word and its
corresponding tag, and sentences are separated by blank lines. To train the
model, I first wrote a <code class="language-plaintext highlighter-rouge">data_loader.py</code> that reads through the CoNLL file and
collects everything into words, tags, sentences and labels. Here’s a small peek
at the data:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>AFP_ENG_19970409 O
. O
0547 O
NEW O
YORK O
, O
April B-T
9 I-T
, I-T
1997 I-T
( O
AFP O
) O
</code></pre></div></div>

<p>Tokens and their tags are separated by whitespace; sentences are separated by a
newline. Below is the code I wrote to pull this into Python and build the
trainable dataset.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">datasets</span> <span class="kn">import</span> <span class="n">Dataset</span>

<span class="k">def</span> <span class="nf">load_data</span><span class="p">(</span><span class="n">filepath</span><span class="p">):</span>
    <span class="n">sentences</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">labels</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">words</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">tags</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="k">with</span> <span class="nf">open</span><span class="p">(</span><span class="n">filepath</span><span class="p">,</span> <span class="sh">"</span><span class="s">r</span><span class="sh">"</span><span class="p">)</span> <span class="k">as</span> <span class="n">dataset</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">dataset</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">line</span> <span class="o">!=</span> <span class="sh">"</span><span class="se">\n</span><span class="sh">"</span><span class="p">:</span>
                <span class="n">sample</span> <span class="o">=</span> <span class="n">line</span><span class="p">.</span><span class="nf">strip</span><span class="p">().</span><span class="nf">split</span><span class="p">()</span>
                <span class="n">words</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">sample</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
                <span class="n">tags</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">sample</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">sentences</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">words</span><span class="p">)</span>
                <span class="n">labels</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">tags</span><span class="p">)</span>
                <span class="n">words</span><span class="p">,</span> <span class="n">tags</span> <span class="o">=</span> <span class="p">[],</span> <span class="p">[]</span>

    <span class="n">data</span> <span class="o">=</span> <span class="n">Dataset</span><span class="p">.</span><span class="nf">from_dict</span><span class="p">({</span><span class="sh">"</span><span class="s">inputs</span><span class="sh">"</span><span class="p">:</span> <span class="n">sentences</span><span class="p">,</span> <span class="sh">"</span><span class="s">tags</span><span class="sh">"</span><span class="p">:</span> <span class="n">labels</span><span class="p">})</span>
    <span class="k">return</span> <span class="n">data</span>
</code></pre></div></div>

<p>After building the dataset dictionary, the next step was converting the string
labels into numbers so the model could work with them. I used <code class="language-plaintext highlighter-rouge">LabelEncoder</code> from
scikit-learn to map the tags:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>B-T --&gt; 0
I-T --&gt; 1
O   --&gt; 2
</code></pre></div></div>

<p>Now the dataset looked like this:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
  <span class="sh">"</span><span class="s">tokens</span><span class="sh">"</span><span class="p">:</span> <span class="p">[[</span><span class="sh">"</span><span class="s">NEW</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">YORK</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">,</span><span class="sh">"</span> <span class="p">,</span> <span class="sh">"</span><span class="s">April</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">9</span><span class="sh">"</span><span class="p">],</span> <span class="p">...],</span>
  <span class="sh">"</span><span class="s">labels</span><span class="sh">"</span><span class="p">:</span> <span class="p">[[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="p">...]</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Since LLaMA uses subword tokenization, I also had to align the labels with the
tokenized outputs. That meant repeating a label for every subword and marking
padding with <code class="language-plaintext highlighter-rouge">-100</code> so it wouldn’t affect training.</p>

<p>With this step done, the dataset was ready for training.</p>

<h2 id="model-setup"><a href="#model-setup"></a>Model setup</h2>

<p>For the model I started with <code class="language-plaintext highlighter-rouge">LlamaForTokenClassification</code> from the Hugging Face
transformers library, using the base checkpoint <code class="language-plaintext highlighter-rouge">meta-llama/llama-3.2-1b</code>. This
gave me a LLaMA backbone with a token classification head on top, which is what I
needed for NER.</p>

<p>Since the model has a billion parameters, training all of it would be too slow
and would not fit in my small GPU’s memory. So I used LoRA (Low-Rank Adaptation)
to fine-tune only a small set of parameters, and added bitsandbytes 4-bit
quantization. With bitsandbytes the weights are stored in 4-bit instead of the
usual 16 or 32, which cuts memory usage enough to make training possible on a
single GPU. You can also do 8-bit or mixed-precision 16-bit.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">bnb_config</span> <span class="o">=</span> <span class="nc">BitsAndBytesConfig</span><span class="p">(</span>
    <span class="n">load_in_4bit</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">bnb_4bit_use_double_quant</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">bnb_4bit_quant_type</span><span class="o">=</span><span class="sh">"</span><span class="s">nf4</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">bnb_4bit_compute_dtype</span><span class="o">=</span><span class="n">torch</span><span class="p">.</span><span class="n">bfloat16</span> <span class="k">if</span> <span class="n">torch</span><span class="p">.</span><span class="n">cuda</span><span class="p">.</span><span class="nf">is_available</span><span class="p">()</span> <span class="k">else</span> <span class="n">torch</span><span class="p">.</span><span class="n">float16</span><span class="p">,</span>
<span class="p">)</span>

<span class="n">model</span> <span class="o">=</span> <span class="n">AutoModelForTokenClassification</span><span class="p">.</span><span class="nf">from_pretrained</span><span class="p">(</span>
    <span class="n">model_id</span><span class="p">,</span>
    <span class="n">num_labels</span><span class="o">=</span><span class="n">num_labels</span><span class="p">,</span>
    <span class="n">torch_dtype</span><span class="o">=</span><span class="n">torch</span><span class="p">.</span><span class="n">bfloat16</span> <span class="k">if</span> <span class="n">torch</span><span class="p">.</span><span class="n">cuda</span><span class="p">.</span><span class="nf">is_available</span><span class="p">()</span> <span class="k">else</span> <span class="n">torch</span><span class="p">.</span><span class="n">float16</span><span class="p">,</span>
    <span class="n">quantization_config</span><span class="o">=</span><span class="n">bnb_config</span><span class="p">,</span>
    <span class="n">device_map</span><span class="o">=</span><span class="sh">"</span><span class="s">auto</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">token</span><span class="o">=</span><span class="n">hf_token</span>
<span class="p">)</span>
</code></pre></div></div>

<p>For the tokenizer I load <code class="language-plaintext highlighter-rouge">LlamaTokenizer</code> directly. Since LLaMA does not define a
pad token by default, I add my own <code class="language-plaintext highlighter-rouge">[PAD]</code> token and set it as the pad token ID.
Padding is set to the right side, which is standard for training.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">tokenizer</span> <span class="o">=</span> <span class="n">LlamaTokenizer</span><span class="p">.</span><span class="nf">from_pretrained</span><span class="p">(</span><span class="n">model_id</span><span class="p">,</span> <span class="n">token</span><span class="o">=</span><span class="n">hf_token</span><span class="p">)</span>

<span class="k">if</span> <span class="n">tokenizer</span><span class="p">.</span><span class="n">pad_token</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>  <span class="c1"># true in the case of llama models
</span>    <span class="n">tokenizer</span><span class="p">.</span><span class="nf">add_special_tokens</span><span class="p">({</span><span class="sh">'</span><span class="s">pad_token</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">[PAD]</span><span class="sh">'</span><span class="p">})</span>
    <span class="n">tokenizer</span><span class="p">.</span><span class="n">pad_token</span> <span class="o">=</span> <span class="sh">'</span><span class="s">[PAD]</span><span class="sh">'</span>

<span class="n">tokenizer</span><span class="p">.</span><span class="n">padding_side</span> <span class="o">=</span> <span class="sh">"</span><span class="s">right</span><span class="sh">"</span>
<span class="n">tokenizer</span><span class="p">.</span><span class="n">pad_token_id</span> <span class="o">=</span> <span class="n">tokenizer</span><span class="p">.</span><span class="nf">convert_tokens_to_ids</span><span class="p">(</span><span class="n">tokenizer</span><span class="p">.</span><span class="n">pad_token</span><span class="p">)</span>
</code></pre></div></div>

<p>This keeps the tokenizer and model consistent: the pad token exists in the
vocabulary, sequences are padded correctly, and the embeddings match the vocab
size.</p>

<p>It is important that the tokenizer and the model’s embedding matrix always match.
When I added a new <code class="language-plaintext highlighter-rouge">[PAD]</code> token the tokenizer’s vocabulary grew by one. If you
don’t update the model embeddings to match, you get the common error:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>RuntimeError: size mismatch for
model.embed_tokens.weight: [128257, 2048] vs [128256, 2048]
</code></pre></div></div>

<p>The fix:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">model</span><span class="p">.</span><span class="nf">resize_token_embeddings</span><span class="p">(</span><span class="nf">len</span><span class="p">(</span><span class="n">tokenizer</span><span class="p">))</span>
</code></pre></div></div>

<h3 id="peft-parameter-efficient-fine-tuning"><a href="#peft-parameter-efficient-fine-tuning"></a>PEFT (parameter-efficient fine-tuning)</h3>

<p>I mentioned this above, but it’s worth elaborating. LoRA trains a small number of
additional parameters on top of the frozen model weights, which makes training
faster and lighter. You pass your base model to the PEFT config:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">peft</span> <span class="kn">import</span> <span class="n">prepare_model_for_kbit_training</span><span class="p">,</span> <span class="n">LoraConfig</span><span class="p">,</span> <span class="n">get_peft_model</span><span class="p">,</span> <span class="n">TaskType</span>

<span class="c1"># prepare model for k-bit training (freeze some layers, enable gradient checkpointing)
</span><span class="n">model</span> <span class="o">=</span> <span class="nf">prepare_model_for_kbit_training</span><span class="p">(</span><span class="n">model</span><span class="p">)</span>

<span class="c1"># LoRA configuration
</span><span class="n">lora_cfg</span> <span class="o">=</span> <span class="nc">LoraConfig</span><span class="p">(</span>
    <span class="n">r</span><span class="o">=</span><span class="mi">16</span><span class="p">,</span>
    <span class="n">lora_alpha</span><span class="o">=</span><span class="mi">32</span><span class="p">,</span>
    <span class="n">lora_dropout</span><span class="o">=</span><span class="mf">0.05</span><span class="p">,</span>
    <span class="n">bias</span><span class="o">=</span><span class="sh">"</span><span class="s">none</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">task_type</span><span class="o">=</span><span class="n">TaskType</span><span class="p">.</span><span class="n">TOKEN_CLS</span><span class="p">,</span>
    <span class="n">target_modules</span><span class="o">=</span><span class="p">[</span>
        <span class="sh">"</span><span class="s">q_proj</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">k_proj</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">v_proj</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">o_proj</span><span class="sh">"</span><span class="p">,</span>
        <span class="sh">"</span><span class="s">gate_proj</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">up_proj</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">down_proj</span><span class="sh">"</span><span class="p">,</span>
    <span class="p">],</span>
<span class="p">)</span>

<span class="c1"># wrap model with LoRA
</span><span class="n">model</span> <span class="o">=</span> <span class="nf">get_peft_model</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">lora_cfg</span><span class="p">)</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">target_modules</code> list tells LoRA which parts of the model to adapt. In LLaMA
the main places where information flows are the attention projections (<code class="language-plaintext highlighter-rouge">q_proj</code>,
<code class="language-plaintext highlighter-rouge">k_proj</code>, <code class="language-plaintext highlighter-rouge">v_proj</code>, <code class="language-plaintext highlighter-rouge">o_proj</code>) and the feed-forward network layers (<code class="language-plaintext highlighter-rouge">gate_proj</code>,
<code class="language-plaintext highlighter-rouge">up_proj</code>, <code class="language-plaintext highlighter-rouge">down_proj</code>).</p>

<p>By applying LoRA only to these modules, I could capture most of the model’s
expressive power while training only a fraction of the parameters.</p>

<h2 id="training"><a href="#training"></a>Training</h2>

<p>With the model and tokenizer ready, I set up the training loop using Hugging
Face’s <code class="language-plaintext highlighter-rouge">Trainer</code>. I loaded my training and test datasets, made sure the tokenizer
and model embeddings were aligned, and defined the training arguments.</p>

<p>Some of the important settings:</p>

<ul>
  <li><strong>Batch size:</strong> 32, with gradient accumulation of 2</li>
  <li><strong>Epochs:</strong> 5</li>
  <li><strong>Learning rate:</strong> 3e-5 with a cosine scheduler</li>
  <li><strong>Warmup ratio:</strong> 0.05</li>
  <li><strong>Evaluation:</strong> every 256 steps, with early stopping (patience 3)</li>
  <li><strong>Metrics:</strong> F1 as the main metric for tracking the best model</li>
  <li><strong>Logging:</strong> Weights &amp; Biases</li>
</ul>

<p>Here’s the core of the script:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">training_args</span> <span class="o">=</span> <span class="nc">TrainingArguments</span><span class="p">(</span>
    <span class="n">output_dir</span><span class="o">=</span><span class="sh">"</span><span class="s">./results</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">logging_dir</span><span class="o">=</span><span class="sh">"</span><span class="s">./logs</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">logging_steps</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span>
    <span class="n">save_steps</span><span class="o">=</span><span class="mi">512</span><span class="p">,</span>
    <span class="n">save_total_limit</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span>
    <span class="n">num_train_epochs</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span>
    <span class="n">per_device_train_batch_size</span><span class="o">=</span><span class="mi">32</span><span class="p">,</span>
    <span class="n">per_device_eval_batch_size</span><span class="o">=</span><span class="mi">32</span><span class="p">,</span>
    <span class="n">gradient_accumulation_steps</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span>
    <span class="n">learning_rate</span><span class="o">=</span><span class="mf">3e-5</span><span class="p">,</span>
    <span class="n">warmup_ratio</span><span class="o">=</span><span class="mf">0.05</span><span class="p">,</span>
    <span class="n">lr_scheduler_type</span><span class="o">=</span><span class="sh">"</span><span class="s">cosine</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">weight_decay</span><span class="o">=</span><span class="mf">0.01</span><span class="p">,</span>
    <span class="n">eval_strategy</span><span class="o">=</span><span class="sh">"</span><span class="s">steps</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">eval_steps</span><span class="o">=</span><span class="mi">256</span><span class="p">,</span>
    <span class="n">load_best_model_at_end</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">report_to</span><span class="o">=</span><span class="sh">"</span><span class="s">wandb</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">metric_for_best_model</span><span class="o">=</span><span class="sh">"</span><span class="s">f1</span><span class="sh">"</span><span class="p">,</span>
<span class="p">)</span>

<span class="n">trainer</span> <span class="o">=</span> <span class="nc">Trainer</span><span class="p">(</span>
    <span class="n">model</span><span class="o">=</span><span class="n">model</span><span class="p">,</span>
    <span class="n">args</span><span class="o">=</span><span class="n">training_args</span><span class="p">,</span>
    <span class="n">train_dataset</span><span class="o">=</span><span class="n">train_dataset</span><span class="p">,</span>
    <span class="n">eval_dataset</span><span class="o">=</span><span class="n">test_dataset</span><span class="p">,</span>
    <span class="n">tokenizer</span><span class="o">=</span><span class="n">tokenizer</span><span class="p">,</span>
    <span class="n">callbacks</span><span class="o">=</span><span class="p">[</span><span class="nc">EarlyStoppingCallback</span><span class="p">(</span><span class="n">early_stopping_patience</span><span class="o">=</span><span class="mi">3</span><span class="p">)],</span>
    <span class="n">compute_metrics</span><span class="o">=</span><span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="nf">compute_metrics</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">le</span><span class="p">.</span><span class="n">classes_</span><span class="p">,</span> <span class="n">tokenizer</span><span class="p">),</span>
<span class="p">)</span>

<span class="n">trainer</span><span class="p">.</span><span class="nf">train</span><span class="p">()</span>
</code></pre></div></div>

<h2 id="evaluation-results"><a href="#evaluation-results"></a>Evaluation results</h2>

<p>After training for about 4–5 epochs on the 90k-sample dataset, the model reached
strong performance:</p>

<table>
  <thead>
    <tr>
      <th>Metric</th>
      <th>Value</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Eval loss</td>
      <td>~0.03</td>
    </tr>
    <tr>
      <td>Accuracy</td>
      <td>~99%</td>
    </tr>
    <tr>
      <td>Precision</td>
      <td>~0.93</td>
    </tr>
    <tr>
      <td>Recall</td>
      <td>~0.91</td>
    </tr>
    <tr>
      <td>F1</td>
      <td>~0.92</td>
    </tr>
  </tbody>
</table>

<p>The F1 score is the most useful number here, since the dataset is imbalanced —
most tokens are just <code class="language-plaintext highlighter-rouge">O</code>. An F1 above 0.9 means the model learned to identify
entity spans reliably instead of predicting everything as <code class="language-plaintext highlighter-rouge">O</code>.</p>

<p>Training loss also stayed low (~0.08), which shows the model generalized well and
didn’t just memorize the training set.</p>

<h2 id="merging-lora-into-the-base-model"><a href="#merging-lora-into-the-base-model"></a>Merging LoRA into the base model</h2>

<p>After training with LoRA, the weights are stored as adapters on top of the base
LLaMA model. If you want to use the model directly for inference, without loading
PEFT every time, you need to merge the LoRA weights into the base model.</p>

<p>I first resized the base model embeddings so they matched the tokenizer, then
loaded the LoRA adapter and merged it back in:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">base_model</span><span class="p">.</span><span class="nf">resize_token_embeddings</span><span class="p">(</span><span class="nf">len</span><span class="p">(</span><span class="n">tokenizer</span><span class="p">))</span>

<span class="kn">from</span> <span class="n">peft</span> <span class="kn">import</span> <span class="n">PeftModel</span>

<span class="n">model</span> <span class="o">=</span> <span class="n">PeftModel</span><span class="p">.</span><span class="nf">from_pretrained</span><span class="p">(</span><span class="n">base_model</span><span class="p">,</span> <span class="n">adapter_dir</span><span class="p">)</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="nf">merge_and_unload</span><span class="p">()</span>
</code></pre></div></div>

<p>Finally, I saved the merged model and tokenizer:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">model</span><span class="p">.</span><span class="nf">save_pretrained</span><span class="p">(</span><span class="sh">"</span><span class="s">./final-model</span><span class="sh">"</span><span class="p">)</span>
<span class="n">tokenizer</span><span class="p">.</span><span class="nf">save_pretrained</span><span class="p">(</span><span class="sh">"</span><span class="s">./final-model</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div>

<p>With this step the model becomes fully standalone. I could then push it to the
Hugging Face Hub and load it anywhere with a single pipeline call.</p>

<h2 id="deployment-on-hugging-face"><a href="#deployment-on-hugging-face"></a>Deployment on Hugging Face</h2>

<p>Once the LoRA adapters were merged and the tokenizer was saved correctly, I
pushed the model to the Hugging Face Hub:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">model</span><span class="p">.</span><span class="nf">push_to_hub</span><span class="p">(</span><span class="sh">"</span><span class="s">namesarnav/llama-3.2-1b-NER-timex</span><span class="sh">"</span><span class="p">)</span>
<span class="n">tokenizer</span><span class="p">.</span><span class="nf">push_to_hub</span><span class="p">(</span><span class="sh">"</span><span class="s">namesarnav/llama-3.2-1b-NER-timex</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div>

<p>After that, using the model is a few lines of code:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">transformers</span> <span class="kn">import</span> <span class="n">pipeline</span>

<span class="n">ner</span> <span class="o">=</span> <span class="nf">pipeline</span><span class="p">(</span>
    <span class="sh">"</span><span class="s">token-classification</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">namesarnav/llama-3.2-1b-NER-timex</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">tokenizer</span><span class="o">=</span><span class="sh">"</span><span class="s">namesarnav/llama-3.2-1b-NER-timex</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">aggregation_strategy</span><span class="o">=</span><span class="sh">"</span><span class="s">simple</span><span class="sh">"</span>
<span class="p">)</span>

<span class="n">text</span> <span class="o">=</span> <span class="sh">"</span><span class="s">NEW YORK, April 9, 1997 (AFP).</span><span class="sh">"</span>
<span class="nf">print</span><span class="p">(</span><span class="nf">ner</span><span class="p">(</span><span class="n">text</span><span class="p">))</span>
</code></pre></div></div>

<p>This runs inference directly and outputs the entities recognized in the text. No
PEFT setup is needed once the LoRA weights are merged.</p>

<h2 id="conclusion"><a href="#conclusion"></a>Conclusion</h2>

<p>Using a LLaMA model for NER wasn’t as straightforward as reaching for an encoder
model like BERT, but it worked well once the setup was right. With LoRA and 4-bit
quantization I was able to fine-tune a billion-parameter model on a single GPU.</p>

<p>A few lessons along the way:</p>

<ul>
  <li>Always keep the tokenizer and model embeddings in sync.</li>
  <li>Set <code class="language-plaintext highlighter-rouge">num_labels</code> correctly before saving, to avoid head mismatches.</li>
  <li>Flatten labels and ignore padding when computing metrics.</li>
  <li>Merge LoRA weights if you want a clean, standalone model for inference.</li>
</ul>

<p>The final model reached an F1 above 0.9 on my dataset, showing that decoder-only
models like LLaMA can handle token classification effectively with the right
adjustments.</p>

<p>Pushing the model to Hugging Face made it easy to share and run inference with
just a pipeline call. That step turned the project from an experiment into
something reusable.</p>

<p>The full source code for this project is on
<a href="https://github.com/namesarnav">my GitHub</a>.</p>

<p>Thanks for reading — please share if you found it helpful.</p>]]></content><author><name>Arnav Verma</name><email>av4445@nyu.edu</email></author><category term="Large Language Models" /><category term="LLM Finetuning" /><category term="NLP" /><category term="AI" /><category term="Llama 3" /><summary type="html"><![CDATA[Customize your models using PEFT. Fine-tuning LLaMA 3.2 1B for token classification with LoRA adapters and 4-bit quantization, on a single GPU.]]></summary></entry></feed>