<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ritwik's blog]]></title><description><![CDATA[This publication is about making deep learning research more accessible, distilling complex topics, and developing poc solutions in the fields of deep learning,]]></description><link>https://blog.ritwikraha.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1731341082178/abad5cb2-e64b-40cc-a2f8-8f371c8a1d56.png</url><title>Ritwik&apos;s blog</title><link>https://blog.ritwikraha.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 08 Nov 2026 22:44:16 GMT</lastBuildDate><atom:link href="https://blog.ritwikraha.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Can we really scale RL?]]></title><description><![CDATA[Yes and No. LLM reasoning research is just a big pile of math. We stir the math every once in a while, and it starts doing crazy stuff. For months the…]]></description><link>https://blog.ritwikraha.dev/can-we-really-scale-rl</link><guid isPermaLink="true">https://blog.ritwikraha.dev/can-we-really-scale-rl</guid><category><![CDATA[Reinforcement Learning]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[llm]]></category><category><![CDATA[large language models]]></category><category><![CDATA[claude.ai]]></category><category><![CDATA[gpt]]></category><category><![CDATA[RLHF]]></category><dc:creator><![CDATA[Ritwik Raha]]></dc:creator><pubDate>Sun, 08 Jun 2025 10:50:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749379209306/457dbf1e-1f2c-4495-a6eb-478208e2b516.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Yes and No. LLM reasoning research is just a big pile of math. We stir the math every once in a while, and it starts doing crazy stuff. For months the community has argued that RL post-training just <em>polishes</em> ideas an LLM already had. ProRL politely says:</p>
<blockquote>
<p>“Give me 2k RL steps and a truck-load of tasks and I’ll <strong>invent</strong> <strong>new</strong> reasoning strategies.”</p>
</blockquote>
<p>The authors(from Nvidia) back that up with the strongest 1.5 B reasoning model to date, <code>Nemotron-Research-Reasoning-Qwen-1.5B</code>, beating its own 7B parameter big brother on several benchmarks.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749378437797/f9375771-ad89-414a-b937-63218fc7000f.png" alt="ProRL is a recent paper from Nvidia that shows benefits of scaling RL for prolonged duration" class="image--center mx-auto" /></p>
<h2 id="heading-tldr-prolonged-rl-is-prolonged-rl">TL;DR: Prolonged RL is Prolonged RL!</h2>
<p>ProRL is designed to extend RL training over a long duration, incorporating several innovative techniques to ensure stability and exploration. The methodology includes:</p>
<ul>
<li><strong>KL Divergence Control</strong>: This technique maintains policy entropy to prevent drift, using a penalty term in the loss function:</li>
</ul>
<p>$$L_{KL-RL}(\theta) = L_{GRPO}(\theta) - \beta D_{KL}(\pi_\theta || \pi_{ref}).$$</p><ul>
<li><p>This ensures the policy doesn’t deviate too far from the reference, preserving natural language coherence.</p>
</li>
<li><p><strong>Reference Policy Resetting</strong>: Periodic resets are applied to avoid premature convergence, ensuring the model continues to explore new reasoning strategies throughout training. This is crucial for long-horizon RL, where models might otherwise get stuck in local optima.</p>
</li>
</ul>
<p><strong>Diverse Task Suite</strong>: ProRL leverages a comprehensive dataset of 136K problems across domains such as math, code, STEM, logical puzzles, and instruction following. The training dataset details are outlined in Table 1 below, showcasing the variety and quantity of tasks:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Data Type</strong></td><td><strong>Reward Type</strong></td><td><strong>Quantity</strong></td><td><strong>Data Source</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Math</td><td>Binary</td><td><code>40k</code></td><td>DeepScaleR Dataset</td></tr>
<tr>
<td>Code</td><td>Continuous</td><td><code>24k</code></td><td>Eurus-2-RL Dataset</td></tr>
<tr>
<td>STEM</td><td>Binary</td><td><code>25k</code></td><td>SCP-116K Dataset</td></tr>
<tr>
<td>Logical Puzzles</td><td>Continuous</td><td><code>37k</code></td><td>Reasoning Gym</td></tr>
<tr>
<td>Instruction Following</td><td>Continuous</td><td><code>10k</code></td><td>Llama-Nemotron</td></tr>
</tbody>
</table>
</div><p>Does it help? Apparently the results speak for themselves</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749378543339/85d29895-23f4-48e2-a968-5b4aa25fb944.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-what-is-rl-again">What is RL again?</h2>
<p>The fundamental RL objective in language models is to maximise the expected reward while maintaining proximity to a reference policy. Mathematically, this is expressed as:</p>
<p>$$J(\theta) = \mathbb{E}{\tau \sim \pi\theta}[R(\tau)] - \beta \cdot D_{KL}[\pi_\theta || \pi_{ref}]$$</p><p>Where:</p>
<ul>
<li><p>$$\pi_\theta \text{ is the current policy (language model) with parameters } \theta$$</p></li>
<li><p>$$\tau \text{ represents a trajectory (prompt + generated response)}$$</p></li>
<li><p>$$R(\tau) \text{ is the reward function}$$</p></li>
<li><p>$$\pi_{ref} \text{ is the reference policy (typically the initial supervised fine-tuned model)}$$</p></li>
<li><p>$$\beta \text{ is the KL penalty coefficient}$$</p></li>
<li><p>$${KL} \text{ is the Kullback-Leibler divergence}$$</p></li>
</ul>
<p>Great now that we have recapped, what is RL, let us focus on the algorithm the Nvidia folks use.</p>
<h3 id="heading-group-relative-policy-optimisation-grpo">Group Relative Policy Optimisation (GRPO)</h3>
<p>ProRL uses GRPO as its core algorithm. As does every other paper in 2025. Thanks Chinese hedge fund team. The GRPO objective is:</p>
<p>$$L_{GRPO}(\theta) = \mathbb{E}{\tau \sim \pi\theta}\left[\min\left(r_\theta(\tau)A(\tau), \text{clip}(r_\theta(\tau), 1-\epsilon, 1+\epsilon)A(\tau)\right)\right]$$</p><p>Where the probability ratio is:</p>
<p>$$r_\theta(\tau) = \frac{\pi_\theta(\tau)}{\pi_{old}(\tau)}$$</p><p><code>Imagine the model is solving "What is 15 × 7?"</code></p>
<ul>
<li><p>Old policy might generate <code>"15 × 7 = 105"</code> with probability <code>0.3</code></p>
</li>
<li><p>New policy generates the same response with probability <code>0.45</code></p>
</li>
<li><p>Then <code>rθ = 0.45/0.3 = 1.5</code></p>
</li>
</ul>
<p>This ratio tells us the new policy is <code>1.5×</code> more likely to generate this response than the old policy.</p>
<h3 id="heading-the-advantage-function-at">The Advantage Function A(τ)</h3>
<p>$$A(\tau) = \frac{R_\tau - \text{mean}({R_i}{i \in G(\tau)})}{\text{std}({R_i}{i \in G(\tau)})}$$</p><p>Here, <code>G(</code>τ<code>)</code> represents a group of trajectories sampled together, typically 16 in this implementation.</p>
<p>‘This is GRPO's key innovation. Instead of comparing against a learned value function, it compares against other responses in the same batch.</p>
<p><code>Let us assume there are 4 responses to the same math problem:</code></p>
<ul>
<li><p>Response 1: Correct answer, clear steps → <code>R₁ = 1.0</code></p>
</li>
<li><p>Response 2: Correct answer, messy work → <code>R₂ = 0.8</code></p>
</li>
<li><p>Response 3: Wrong answer → <code>R₃ = 0.0</code></p>
</li>
<li><p>Response 4: Partially correct → <code>R₄ = 0.4</code></p>
</li>
</ul>
<p><code>Mean reward = (1.0 + 0.8 + 0.0 + 0.4) / 4 = 0.55</code> <code>Standard deviation ≈ 0.41</code></p>
<ul>
<li><p>For Response 1: <code>A(τ₁) = (1.0 - 0.55) / 0.41 ≈ 1.10</code> (positive advantage) ✅</p>
</li>
<li><p>For Response 3: <code>A(τ₃) = (0.0 - 0.55) / 0.41 ≈ -1.34</code> (negative advantage)❌</p>
</li>
</ul>
<h3 id="heading-the-clipping-mechanism">The Clipping Mechanism</h3>
<p>ProRL also uses asymmetric clipping:</p>
<p>$$\text{clip}(r_\theta(\tau), 1-\epsilon_{low}, 1+\epsilon_{high})$$</p><p>With <code>ϵlow=0.2</code> and <code>ϵhigh=0.4</code></p>
<ul>
<li><p>If advantage is positive: ratio clipped to [0.8, 1.4]</p>
</li>
<li><p>If advantage is negative: ratio clipped to [0.6, 1.2]</p>
</li>
</ul>
<p>This asymmetry encourages exploration. We will discuss more on this later. In a nutshell, when the model finds a good response (positive advantage), it can increase its probability by up to <code>40%</code>. But when penalizing bad responses, it's more consertvative.</p>
<h2 id="heading-scaling-is-hard-in-rl">Scaling is hard in RL</h2>
<p>Yeah, you cant just throw truckloads of compute and expect it to work. Why? A couple of reasons:</p>
<ol>
<li><h3 id="heading-entropy-collapse">Entropy Collapse</h3>
</li>
</ol>
<p>Entropy measures how "spread out" the model's predictions are.</p>
<p>A critical challenge in prolonged RL training is entropy collapse. The entropy of a policy is defined as:</p>
<p>$$H(\pi_\theta) = -\mathbb{E}{a \sim \pi\theta}[\log \pi_\theta(a|s)]$$</p><p>As training progresses, the policy tends to become increasingly deterministic, leading to:</p>
<p>$$\lim_{t \to \infty} H(\pi_\theta^t) \to 0$$</p><p><code>Early in training, for the prompt "What is 2+2?", the model might output</code>:</p>
<ul>
<li><p><code>"4"</code> with probability <code>0.3</code></p>
</li>
<li><p><code>"The answer is 4"</code> with probability <code>0.25</code></p>
</li>
<li><p><code>"2+2 equals 4"</code> with probability <code>0.25</code></p>
</li>
<li><p>Other variations with probability <code>0.2</code></p>
</li>
</ul>
<p><code>High entropy ≈ 1.95</code> (lots of diversity)</p>
<p>After extensive training without entropy control:</p>
<ul>
<li><p><code>"The answer is 4"</code> with probability <code>0.95</code></p>
</li>
<li><p>Everything else with probability <code>0.05</code></p>
</li>
</ul>
<p><code>Low entropy ≈ 0.20</code> (almost deterministic)</p>
<p>This collapse means the model stops exploring new ways to solve problems, getting stuck in local optima. This collapse severely limits exploration and learning of new strategies.</p>
<ol start="2">
<li><h3 id="heading-kl-divergence-growth">KL Divergence Growth</h3>
</li>
</ol>
<p>Without constraints, the KL divergence between the current and reference policies grows unbounded:</p>
<p>$$D_{KL}(\pi_\theta || \pi_{ref}) = \mathbb{E}{s \sim \rho^{\pi\theta}}\left[\sum_a \pi_\theta(a|s) \log \frac{\pi_\theta(a|s)}{\pi_{ref}(a|s)}\right]$$</p><p>This drift can lead to:</p>
<ol>
<li><p>Loss of linguistic coherence</p>
</li>
<li><p>Reward hacking</p>
</li>
<li><p>Catastrophic forgetting of pre-trained capabilities</p>
</li>
</ol>
<h2 id="heading-gimme-solutions-man">Gimme, solutions man!</h2>
<p>So yeah, we have established why scaling RL is not that easy. So what do we do? Or what have the authors done?</p>
<ol>
<li><h3 id="heading-modified-loss-function-with-kl-regularization">Modified Loss Function with KL Regularization</h3>
</li>
</ol>
<p>ProRL modifies the GRPO loss to include explicit KL regularization:</p>
<p>$$L_{KL-RL}(\theta) = L_{GRPO}(\theta) - \beta D_{KL}(\pi_\theta || \pi_{ref})$$</p><p>The KL divergence term expands to:</p>
<p>$$D_{KL}(\pi_\theta || \pi_{ref}) = \mathbb{E}{s \sim \rho^{\pi\theta}}\left[\sum_a \pi_\theta(a|s) \log \frac{\pi_\theta(a|s)}{\pi_{ref}(a|s)}\right]$$</p><p><code>For the prompt "Explain gravity", suppose at a particular generation step</code>:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Tokens</strong></td><td><strong>Reference model's next token probabilities:</strong></td><td><strong>Current model's probabilities</strong>:</td></tr>
</thead>
<tbody>
<tr>
<td><code>“Gravity”</code></td><td><code>0.4</code></td><td><code>0.1</code> (much lower!)</td></tr>
<tr>
<td><code>“The”</code></td><td><code>0.3</code></td><td><code>0.7</code> (much higher!)</td></tr>
<tr>
<td><code>"Newton's"</code></td><td><code>0.2</code></td><td><code>0.15</code></td></tr>
<tr>
<td><code>“Others”</code></td><td><code>0.1</code></td><td><code>0.05</code></td></tr>
</tbody>
</table>
</div><p>The KL contribution from just these tokens:</p>
<p>$$D_{KL} = 0.1 \log(0.1/0.4) + 0.7 \log(0.7/0.3) + 0.15 \log(0.15/0.2) + ...$$</p><p>$$≈0.1(−1.39)+0.7(0.85)+0.15(−0.29)+...≈0.41$$</p><p>With <code>β = 0.1</code> this adds a penalty of <code>0.041</code> to the loss, discouraging the model from drifting too far from sensible language patterns. This maintains a balance between reward optimisation and staying close to the reference distribution.</p>
<ol start="2">
<li><h3 id="heading-decoupled-clipping-dapo-integration">Decoupled Clipping (DAPO Integration)</h3>
</li>
</ol>
<p>ProRL incorporates asymmetric clipping bounds.</p>
<p>$$\text{clip}(r_\theta(\tau), 1-\epsilon_{low}, 1+\epsilon_{high})$$</p><p>With <code>ϵlow=0.2</code> and <code>ϵhigh=0.4</code>, this encourages exploration by allowing larger upward movements in probability space for previously unlikely actions.</p>
<p>We discussed this previously but lets look at a more illustrative example now:</p>
<p><code>"Find the derivative of f(x) = x³ + 2x² - 5x + 3"</code></p>
<p>One way to think of DAPO's asymmetric clipping is like teaching a student:</p>
<ul>
<li><p>When they discover a brilliant solution → Celebrate enthusiastically! (larger positive updates) 🥳</p>
</li>
<li><p>When they make mistakes → Correct gently (conservative negative updates) 🤔</p>
</li>
</ul>
<p>This asymmetry prevents the model from becoming overly cautious while still maintaining stability.</p>
<p>Okay enough analogies, let us take a look at the example at hand:</p>
<p><code>"Find the derivative of f(x) = x³ + 2x² - 5x + 3"</code></p>
<h3 id="heading-scenario-1-excellent-response-positive-advantage"><code>Scenario 1: Excellent Response (Positive Advantage)</code>✅</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Details</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Model's Response</strong></td><td><code>"To find f'(x), I'll differentiate term by term: f'(x) = 3x² + 4x - 5"</code></td></tr>
<tr>
<td><strong>Quality Assessment</strong></td><td>✅ Correct answer ✅ Clear step-by-step explanation ✅ Proper mathematical notation</td></tr>
<tr>
<td><strong>Reward</strong></td><td><code>1.0</code> (perfect score)</td></tr>
<tr>
<td><strong>Group Context</strong></td><td>Other responses in batch averaged 0.4 reward</td></tr>
<tr>
<td><strong>Advantage Score</strong></td><td>A(τ) = +1.46 (this response is much better than average)</td></tr>
</tbody>
</table>
</div><div class="hn-table">
<table>
<thead>
<tr>
<td>Probability Update Process</td><td>Standard PPO</td><td>DAPO</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Current probability (π_old)</strong></td><td>15%</td><td>15%</td></tr>
<tr>
<td><strong>Desired probability (π_new)</strong></td><td>30% (model wants to double it)</td><td>30% (same desire)</td></tr>
<tr>
<td><strong>Probability ratio (r)</strong></td><td>30% ÷ 15% = 2.0</td><td>30% ÷ 15% = 2.0</td></tr>
<tr>
<td><strong>Clipping bound</strong></td><td>[0.8, 1.2]</td><td>[0.8, 1.4]</td></tr>
<tr>
<td><strong>Actual ratio after clipping</strong></td><td>1.2 (capped)</td><td>1.4 (more room)</td></tr>
<tr>
<td><strong>Final probability</strong></td><td>15% × 1.2 = <strong>18%</strong></td><td>15% × 1.4 = <strong>21%</strong></td></tr>
<tr>
<td><strong>Improvement allowed</strong></td><td>+20% max</td><td>+40% max</td></tr>
</tbody>
</table>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">DAPO allows 2× more aggressive learning for good solutions (40% vs 20% increase)</div>
</div>

<h3 id="heading-scenario-2-incorrect-response-negative-advantage"><code>Scenario 2: Incorrect Response (Negative Advantage)</code></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Details</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Model's Response</strong></td><td><code>"The derivative is x² + 2x - 5"</code></td></tr>
<tr>
<td><strong>Quality Assessment</strong></td><td>❌ Wrong answer (missed coefficient 3) ❌ Incomplete differentiation ✅ At least attempted the problem</td></tr>
<tr>
<td><strong>Reward</strong></td><td><code>0.0</code> (incorrect)</td></tr>
<tr>
<td><strong>Group Context</strong></td><td>Other responses averaged <code>0.4</code> reward</td></tr>
<tr>
<td><strong>Advantage Score</strong></td><td><code>A(τ) = -0.97</code> (this response is worse than average)</td></tr>
</tbody>
</table>
</div><div class="hn-table">
<table>
<thead>
<tr>
<td>Probability Update Process</td><td>Standard PPO</td><td>DAPO</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Current probability (π_old)</strong></td><td>20%</td><td>20%</td></tr>
<tr>
<td><strong>Desired probability (π_new)</strong></td><td>5% (model wants to reduce it significantly)</td><td>5% (same desire)</td></tr>
<tr>
<td><strong>Probability ratio (r)</strong></td><td>5% ÷ 20% = 0.25</td><td>5% ÷ 20% = 0.25</td></tr>
<tr>
<td><strong>Clipping bound</strong></td><td>[0.8, 1.2]</td><td>[0.8, 1.4]</td></tr>
<tr>
<td><strong>Actual ratio after clipping</strong></td><td>0.8 (capped)</td><td>0.8 (same cap for negative)</td></tr>
<tr>
<td><strong>Final probability</strong></td><td>20% × 0.8 = <strong>16%</strong></td><td>20% × 0.8 = <strong>16%</strong></td></tr>
<tr>
<td><strong>Reduction allowed</strong></td><td>-20% max</td><td>-20% max (conservative)</td></tr>
</tbody>
</table>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">DAPO remains equally conservative for bad solutions to prevent catastrophic forgetting</div>
</div>

<ol start="3">
<li><h3 id="heading-reference-policy-resetting">Reference Policy Resetting</h3>
</li>
</ol>
<p>Periodically, ProRL resets the reference policy:</p>
<p>$$\pi_{ref}^{(k+1)} \leftarrow \pi_\theta^{(k)}$$</p><p><code>Before Reset (Run 3)</code><strong>:</strong></p>
<ul>
<li><p>Current model has learned good math strategies</p>
</li>
<li><p>KL divergence has grown to 0.15 (getting large)</p>
</li>
<li><p>Model wants to explore new approaches but is held back</p>
</li>
</ul>
<p><code>After Reset (Run 4)</code><strong>:</strong></p>
<ul>
<li><p>Reference model now includes all learned improvements</p>
</li>
<li><p>KL divergence resets to 0.</p>
</li>
<li><p>Model can freely explore from this new baseline</p>
</li>
</ul>
<p>It's like a rock climber establishing a new base camp at a higher altitude before continuing the ascent.</p>
<p>This prevents the KL term from dominating the loss and allows continued improvement. The reset points are strategically chosen based on validation performance.</p>
<ol start="4">
<li><h2 id="heading-training-dynamics-and-scaling-laws">Training Dynamics and Scaling Laws</h2>
</li>
</ol>
<h3 id="heading-performance-scaling">Performance Scaling</h3>
<p>The paper demonstrates that both pass@1 and pass@k scale with training steps. The relationship can be approximated as:</p>
<p>$$\text{Pass@k}(t) = 1 - (1 - p_0)e^{-\alpha t}$$</p><p>Where:</p>
<ul>
<li><p>$$t \text{ is the training step}$$</p></li>
<li><p>$$p_0 \text{ is the initial performance}$$</p></li>
<li><p>$$\alpha \text{ is the learning rate coefficient}$$</p></li>
</ul>
<p><strong>Example with actual numbers:</strong></p>
<ul>
<li><p>Initial pass@1 for AIME problems: p0=0.285(28.5%)</p>
</li>
<li><p>Learning rate coefficient: α ≈ 0.0003</p>
</li>
<li><p>After 1000 steps: Pass@1 ≈ 1 - (1-0.285)e^{-0.3} ≈ 0.481 (48.1%)</p>
</li>
<li><p>After 2000 steps: Pass@1 ≈ 1 - (1-0.285)e^{-0.6} ≈ 0.602 (60.2%)</p>
</li>
</ul>
<p>This shows sustained improvement rather than quick saturation.</p>
<h3 id="heading-42-reasoning-boundary-expansion">4.2 Reasoning Boundary Expansion</h3>
<p>The paper introduces the concept of reasoning boundary, measured by pass@k metrics. For a task <code>x</code>, the upper bound is:</p>
<p>$$\mathbb{E}{x,y \sim D}[\text{pass@k}] \leq 1 - \frac{(1 - \mathbb{E}{x,y \sim D}[\rho_x])^2 + \text{Var}(\rho_x)}{k/2}$$</p><p>Where:</p>
<p>$$\rho_x \text{ is the pass@1 accuracy for task }x$$</p><ol start="5">
<li><h2 id="heading-got-any-code">Got any code?</h2>
</li>
</ol>
<p>Let us look at a <em>minimal</em> sketch of the ProRL loop—GRPO loss, KL penalty, and periodic reference resets.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">⚠</div>
<div data-node-type="callout-text">Warning: Boilerplate code. Wouldn’t run! Try to understand not blindly copy paste!</div>
</div>

<p>Replace the stubbed reward with your verifier of choice.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> torch, copy, random
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer
<span class="hljs-keyword">from</span> torch.distributions <span class="hljs-keyword">import</span> Categorical

MODEL_ID = <span class="hljs-string">"Qwen/Qwen-1.5B"</span> <span class="hljs-comment"># &lt;-- yes its qwen, deal with it</span>
EPS_LOW, EPS_HIGH = <span class="hljs-number">0.2</span>, <span class="hljs-number">0.4</span>
KL_BETA = <span class="hljs-number">0.1</span>

model = AutoModelForCausalLM.from_pretrained(MODEL_ID).cuda()
ref_model = copy.deepcopy(model).cuda()
tok = AutoTokenizer.from_pretrained(MODEL_ID)

opt = torch.optim.AdamW(model.parameters(), lr=<span class="hljs-number">2e-6</span>)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">grpo_loss</span>(<span class="hljs-params">logits, old_logits, adv</span>):</span>
    dist, old = Categorical(logits=logits), Categorical(logits=old_logits)
    ratio = torch.exp(dist.logits - old.logits)
    clipped = torch.clamp(ratio, <span class="hljs-number">1</span>-EPS_LOW, <span class="hljs-number">1</span>+EPS_HIGH)
    <span class="hljs-keyword">return</span> -(torch.min(ratio*adv, clipped*adv).mean())

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">kl_penalty</span>(<span class="hljs-params">logits, ref_logits</span>):</span>  <span class="hljs-comment"># symmetric KL is fine here</span>
    p, q = Categorical(logits=logits), Categorical(logits=ref_logits)
    <span class="hljs-keyword">return</span> KL_BETA * torch.distributions.kl_divergence(p, q).mean()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">rollout</span>(<span class="hljs-params">prompt, temp=<span class="hljs-number">1.2</span></span>):</span>
    <span class="hljs-string">"""Sample a single response &amp; a mock scalar reward."""</span>
    input_ids = tok(prompt, return_tensors=<span class="hljs-string">"pt"</span>).to(<span class="hljs-string">'cuda'</span>)
    out = model.generate(**input_ids, do_sample=<span class="hljs-literal">True</span>, temperature=temp,
                         max_new_tokens=<span class="hljs-number">128</span>, return_dict_in_generate=<span class="hljs-literal">True</span>,
                         output_scores=<span class="hljs-literal">True</span>)
    <span class="hljs-comment"># take logits for sampled tokens</span>
    logits = torch.stack(out.scores, dim=<span class="hljs-number">1</span>).squeeze(<span class="hljs-number">0</span>)
    reward = torch.tensor([random.random()], device=<span class="hljs-string">'cuda'</span>)  <span class="hljs-comment"># &lt;-- Pls replace reward here</span>
    <span class="hljs-keyword">return</span> logits, reward

prompts = [<span class="hljs-string">"Integrate x^2 * sin(x)."</span>, <span class="hljs-string">"Write a BFS in brainfuck."</span>, <span class="hljs-string">"Color this 12-node graph."</span>]

<span class="hljs-keyword">for</span> step <span class="hljs-keyword">in</span> range(<span class="hljs-number">2000</span>):            <span class="hljs-comment"># pretend-marathon</span>
    batch_logits, batch_old, rewards = [], [], []
    <span class="hljs-keyword">for</span> p <span class="hljs-keyword">in</span> prompts:
        logits, r = rollout(p)
        batch_logits.append(logits); rewards.append(r)
        batch_old.append(logits.detach())               <span class="hljs-comment"># store old logits</span>

    adv = torch.cat(rewards) - torch.mean(torch.cat(rewards))  <span class="hljs-comment"># simple baseline</span>
    logits = torch.cat(batch_logits)
    old_logits = torch.cat(batch_old)

    loss = grpo_loss(logits, old_logits, adv) + \
           kl_penalty(logits, ref_model(**tok(prompts, return_tensors=<span class="hljs-string">"pt"</span>).to(<span class="hljs-string">'cuda'</span>)).logits)

    opt.zero_grad(); loss.backward(); opt.step()

    <span class="hljs-comment"># hard reset every 250 or so steps</span>
    <span class="hljs-keyword">if</span> (step + <span class="hljs-number">1</span>) % <span class="hljs-number">250</span> == <span class="hljs-number">0</span>:
        ref_model = copy.deepcopy(model).cuda()
        print(<span class="hljs-string">f"Reset ref @ step <span class="hljs-subst">{step+<span class="hljs-number">1</span>}</span>, loss <span class="hljs-subst">{loss.item():<span class="hljs-number">.4</span>f}</span>"</span>)
</code></pre>
<p><em>What does this mean?</em></p>
<ol>
<li><p><strong>GRPO</strong> uses only log-probabilities—no value network headaches.</p>
</li>
<li><p><strong>KL penalty</strong> tethers the policy to a moving reference.</p>
</li>
<li><p>Every 250 steps we “cut the rope” and start a new KL leash, mimicking the paper’s resets.</p>
</li>
</ol>
<h2 id="heading-so-can-we-really-scale-rl">So, can we really scale RL?</h2>
<p>ProRL’s key insight is refreshingly old-school: <strong>keep training longer AND keep it stable.</strong> With the right guard-rails (KL + resets) and a buffet of varied tasks, even a tiny 1.5B model can punch far above its weight, inventing answer trajectories its base version and frankly other dinosaur models (looking at you Llama) had never dreamed of.</p>
<p>That’s both inspiring and a sobering reminder that <em>compute is still king</em>. Happy experimenting :)</p>
<p>Key Citations</p>
<ul>
<li><p><a target="_blank" href="https://arxiv.org/abs/2505.24864">ProRL Paper Abstract</a></p>
</li>
<li><p><a target="_blank" href="https://huggingface.co/papers/2505.24864">ProRL on Hugging Face</a></p>
</li>
<li><p><a target="_blank" href="https://huggingface.co/blog/rlhf">RLHF Blog</a></p>
</li>
<li><p><a target="_blank" href="https://magazine.sebastianraschka.com/p/the-state-of-llm-reasoning-model-training">PPO Paper</a></p>
</li>
<li><p><a target="_blank" href="https://huggingface.co/nvidia/Nemotron-Research-Reasoning-Qwen-1.5B">Hugging Face Model Weights</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[DDPM Explained for Dummies!]]></title><description><![CDATA[Learn DDPM with Simple Steps for Beginners]]></description><link>https://blog.ritwikraha.dev/ddpm-explained-for-dummies</link><guid isPermaLink="true">https://blog.ritwikraha.dev/ddpm-explained-for-dummies</guid><category><![CDATA[ddpm]]></category><category><![CDATA[Diffusion Models ]]></category><category><![CDATA[generative ai]]></category><category><![CDATA[AI]]></category><category><![CDATA[ML]]></category><dc:creator><![CDATA[Ritwik Raha]]></dc:creator><pubDate>Mon, 16 Dec 2024 05:50:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731340769098/5a7f2b24-e10e-40be-a8a7-7bec352db1ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The following blog post is meant to be a companion post for understanding the math of the paper: <a target="_blank" href="https://arxiv.org/abs/2006.11239">Denoising Diffusion Probabilistic Models</a>. There are a lof of other blogposts that tackle this in a more elegant and structured manner. Most of them are listed in the reference section. This post is meant to be a Hitchhiker’s Guide to the Math of DDPM Models.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">🙏</div>
<div data-node-type="callout-text">The Dummy in the title is meant as humour. It is not in any way referring to the readers of this blogpost or anyone else as ‘Dummies’.</div>
</div>

<h2 id="heading-what-is-a-diffusion-process">What is a Diffusion Process?</h2>
<p>Think of dropping a bottle of ink in a cup of water—first, drop by drop, then all at once. Pretty soon, the cup will be the same color as the ink. Now, think about removing each drop of ink from the cup to get the clear water back. Impossible, right?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731317369350/c6ca11fa-e36b-4614-8518-4074ba8f1267.gif" alt class="image--center mx-auto" /></p>
<p>But imagine for a second you can do this. How does that help you? Well, it doesn’t until you realize that the cup of clear water you started with is not the same one you end up with. The two cups will resemble each other, but their minute properties will differ.</p>
<p><strong>Diffusion Models</strong> work the same way.</p>
<ol>
<li><p>You take an image (your clear cup of water)</p>
</li>
<li><p>And then add noise to it (drops of ink)</p>
</li>
<li><p>Till the image is just noise (fully inked cup of water)</p>
</li>
<li><p>Now remove the noise from the image (remove the drops of ink)</p>
</li>
<li><p>Till you get the same image back (original cup of clear water)</p>
</li>
</ol>
<p>Now, if you close your eyes and think of a way to diagrammatically express this, you will most likely arrive at the following figure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731305641964/be884f2b-ca8c-4d8d-80d7-1ac318935a27.png" alt /></p>
<p>This looks an awful lot like a VAE (Variational Auto Encoder).</p>
<details><summary>Variational Auto Encoders</summary><div data-type="detailsContent">Variational Autoencoders (VAEs) are a type of generative model that learns a latent representation of data. They use an encoder to map input data to a latent space, and a decoder to reconstruct the original data from the latent representation. The latent space is a continuous space, which allows VAEs to generate new data points that are similar to the training data. VAEs are trained to minimize the reconstruction error between the original data and the reconstructed data, as well as the Kullback-Leibler divergence between the latent distribution and a prior distribution.</div></details>

<p>In a way, Diffusion models can be seen as latent variable models. Latent refers to a hidden continuous feature space.</p>
<details><summary>What is that continuous feature space?</summary><div data-type="detailsContent">The point at which the Noise Level is 100% or all of the information in the original image has been lost, and only the noise remains.</div></details>

<p>In practice, they are formulated using a Markov chain of T steps.</p>
<details><summary>What is a Markov Chain?</summary><div data-type="detailsContent">It is a fancy way of saying that each step depends on the previous step, and the process goes on for T steps.</div></details>

<h2 id="heading-forward-diffusion-process-noise-addition">Forward Diffusion Process - Noise Addition</h2>
<p>Given a data point sampled from the real data distribution, we can define the forward diffusion process by adding noise to it.</p>
<div class="hn-embed-widget" id="noise-1"></div><p> </p>
<p>$$q(x) = \text{Data Distribution}$$</p><p>$$x_0 = \text{Original Image}$$</p><p>$$x_T= \text{Image at time step T}$$</p><p>Here <code>x_T</code> is the Image at time step T(with noise added), initially, T was set to <code>1000</code>.</p>
<p>Note: <code>x_T</code> will always be an image with a little bit more noise than <code>x_(T-1)</code></p>
<p>$$q(x_t | x_{t-1}) = \text{The forward process}$$</p><p>This takes in an image and returns an image with a little bit more noise added.</p>
<p>Specifically, at each step of the Markov chain, we add Gaussian noise with variance t to xt-1, producing a new latent variable xt with distribution q(xt | xt-1). The diffusion process can be formulated as below:</p>
<p>$$q(x_t | x_{t-1}) = N(x_t, \sqrt{1 - \beta_t} x_{t-1}, \beta_t I)$$</p><p>If you are frightened by the formula, don’t worry; it is just scary-looking notations and we will learn the notations in a second.</p>
<hr />
<h3 id="heading-list-of-notations-and-their-meaning">List of Notations and their meaning</h3>
<p>$$x_t= \text{Output}$$</p><p>Here this can mean the output or a more noisy image</p>
<p>$$q(x_t | x_{t-1}) = \text{The forward process}$$</p><p>This represents the probability distribution of the noisy image <code>x_t</code> at a specific step <code>t</code></p>
<p>$$\beta_t = \text{Variance}$$</p><p>$$\sqrt{1 - \beta_t} =\text{Mean of Noise}$$</p><p>$$I = \text{Identity Matrix}$$</p><blockquote>
<h3 id="heading-what-is-happening-with-betat">What is happening with Beta_t?</h3>
</blockquote>
<p>Let us try to break that down in the most simple way:</p>
<p>$$\sqrt{1 - \beta_t x_{t-1}}$$</p><p>This term scales the previous image <code>x_(t-1)</code>by a factor slightly less than 1.</p>
<p>This factor is:</p>
<ul>
<li><p>$$\sqrt{1 - \beta_t }$$</p><p>  The value of <code>t</code> is between <code>0</code> and <code>1</code> and controls the amount of noise added at each step.</p>
</li>
<li><p>As t increases (more steps), t gets larger, so this term gets smaller, pushing the image towards zero.</p>
</li>
</ul>
<p>The original paper (2020 -DDPM) had the following range for</p>
<p><code>beta_start = 0.0001</code> and <code>beta_end = 0.02</code></p>
<p>This works to keep the variance in a lower bound. In simpler terms, this formula gradually injects noise into an image by:</p>
<ul>
<li><p>Slightly weakening the previous version of the image at each step.</p>
</li>
<li><p>Adding random noise scaled by a factor that increases with each step.</p>
</li>
</ul>
<p>By repeating this process for many steps (increasing t), the image becomes increasingly noisy, essentially losing its details</p>
<p>This gives us an idea of what to do to apply a forward step:</p>
<ul>
<li><p>Pass the image from the previous step</p>
</li>
<li><p>Add noise of a particular mean and variance (determined by )</p>
</li>
<li><p>Keep increasing the as per a schedule thus scaling down the image</p>
</li>
<li><p>Obtain a progressively noisier image</p>
</li>
</ul>
<p>So now, what do we do to apply this forward process for <code>1000</code> steps (remember <code>T=1000</code></p>
<p>One answer is to do this for a thousand steps, which might seem tempting, but exploring math gives us a better (read easier) way to do this.</p>
<p>Let us revisit the equation first:</p>
<p>$$q(x_t | x_{t-1}) = N(x_t, \sqrt{1 - \beta_t x_{t-1}}, \beta_t I)$$</p><p>Now let's substitute the following</p>
<p>$$\sqrt{\beta_t} \rightarrow \alpha_t$$</p><p>Let us also define a cumulative product of all alphas</p>
<p>For the following:</p>
<p>$$t = N; \quad \alpha_N = \alpha_1. \alpha_2. \alpha_3. \alpha_4 \ldots \alpha_N$$</p><p>The mathematical way to write this is:</p>
<p>$$\bar{\alpha}t = \prod{N=1}^{t} \alpha_N$$</p><p>Now let us rewrite the above formula as follows using the reparameterization trick.</p>
<p>$$N(\mu, \sigma^2) = \mu + \sigma \cdot \varepsilon$$</p><details><summary>A Mathematical Note on Reparameterization</summary><div data-type="detailsContent">This specific formula N(μ, σ²)  represents the probability density function of the normal distribution with mean μ and standard deviation σ. It cannot be derived from a single theorem or concept but rather arises from the central limit theorem, which states that the sum of a large number of independent random variables, each with a finite mean and variance, will be approximately normally distributed.</div></details>

<p>Back to the formula at hand</p>
<p>$$q(x_t | x_{t-1}) = N(x_t, \sqrt{1 - \beta_t x_{t-1}}, \beta_t I)$$</p><p>$$= \sqrt{1 - \beta_t x_{t-1}} + \sqrt{\beta_t} \varepsilon$$</p><p>Here is sampled from a Normal distribution with Mean = 0 and Standard Deviation = 1. We can view a Normal Distribution in the diagram below.</p>
<iframe src="https://www.desmos.com/calculator/7hezaxhokf?embed" width="500" height="500" style="border:1px solid #ccc"></iframe>

<p>Now, we can rewrite the above equation with</p>
<p>$$= \sqrt{1 - \beta_t x_{t-1}} + \sqrt{\beta_t} \varepsilon_t$$</p><p>$$= \sqrt{\alpha_t x_{t-1}} + \sqrt{1 - \alpha_t} \varepsilon_t$$</p><p>We can directly go from time step <code>t-1</code> to <code>t-2</code> , all the way to <code>t=0</code>, by chaining the alphas.</p>
<p>$$= \sqrt{\alpha_t \cdot \alpha_{t-1} \cdot x_{t-2}} + \sqrt{1 - \alpha_t \cdot \alpha_{t-1}} \cdot \varepsilon_{t-1}$$</p><p>$$= \sqrt{\alpha_t \cdot \alpha_{t-1} \cdot \alpha_0} \cdot x_0 + \sqrt{1 - \alpha_t \cdot \alpha_{t-1} \cdot \alpha_0} \cdot \varepsilon$$</p><p>If only we had a way to collapse the alphas into a cumulative term, but wait, we do have that:</p>
<p>$$= \sqrt{\bar{\alpha}_t} x_0 + \sqrt{1 - \bar{\alpha}_t} \varepsilon_t$$</p><hr />
<h2 id="heading-reverse-diffusion-process-noise-removal">Reverse Diffusion Process - Noise Removal</h2>
<p><code>p(xt-1|xt)</code> = The reverse process, where a more noisy image is passed to the function and out comes a less noisy image. In this case, the function is a model (specifically a U-Net model, but we can learn about that later)</p>
<div class="hn-embed-widget" id="noise-2"></div><p> </p>
<p>We can express the formula in the following way:</p>
<p>$$p(x_{t-1}|x_t) = N(x_{t-1}; \mu_{\theta}(x_t, t), \Sigma_{\phi}(x_t, t))$$</p><h3 id="heading-list-of-notations-and-their-meaning-1">List of Notations and their Meaning</h3>
<p>$$x_t = \text{More Noisy Image}$$</p><p>$$x_{t-1} = \text{Less Noisy Image}$$</p><p>$$p(x_{t-1}|x_t) = \text{The Reverse Process}$$</p><p>In this case, we will have two neural networks (μ and Σ) that parameterize the normal distribution which we can sample from to get <code>x_t-1</code>, the more</p>
<p>$$\mu_\theta(x_t,t)=\text{Mean of the normal distribution, parameterized by neural network θ}$$</p><p>$$\Sigma_\phi(x_t,t)= \text{Variance of the normal distribution, parameterized by neural network} \phi$$</p><p>In practice, the variance term <code>Σφ(x_t, t)</code> is often set to a fixed schedule, simplifying the model.</p>
<p>The ultimate goal is to train a neural network to accurately predict the noise difference between two-time steps, enabling the effective denoising process.</p>
<h3 id="heading-arriving-at-a-formula">Arriving at a Formula</h3>
<div data-node-type="callout">
<div data-node-type="callout-emoji">🎯</div>
<div data-node-type="callout-text"><strong>AIM</strong>: Arriving at a formula that uses a neural network to predict the noise between two time steps.</div>
</div>

<p>Let us begin with the core structure that connects the entire process. The Loss Function of the Diffusion Model. But before we do, here is a short mathematical note that might come in handy</p>
<p><strong>ELBO Formulation</strong></p>
<p>The variational lower bound or Evidence Lower Bound (ELBO)  can be expressed as follows:</p>
<p>$$\mathcal{L} = \mathbb{E}_{q(z)}[\log q(z) - \log p(z, x)]$$</p><p>Here's a breakdown of the equation:</p>
<ul>
<li><p><code>L</code>: This represents the variational lower bound itself.</p>
</li>
<li><p><code>Eq(z)[...]</code>: This denotes the expectation over the variational distribution <code>q(z)</code>. Expectation refers to the average value of a function evaluated for each possible outcome of a random variable.</p>
</li>
<li><p><code>q(z)</code>: This is the variational distribution, which approximates the true intractable posterior distribution <code>p(z|x)</code>.</p>
</li>
<li><p><code>log q(z)</code>: This is the logarithm of the variational distribution.</p>
</li>
<li><p><code>log p(z,x)</code>: This is the logarithm of the joint probability distribution <code>p(z,x)</code>, where <code>z</code> is the latent variable and <code>x</code> is the data point.</p>
</li>
</ul>
<details><summary>A Mathematical Note on ELBO</summary><div data-type="detailsContent">The ELBO aims to find a variational distribution <code>q(z)</code> that is close to the true posterior <code>p(z|x)</code>. It does this by maximizing the difference between two terms: The logarithm of the variational distribution <code>log q(z)</code>: This term encourages the variational distribution to assign high probability to regions where the true posterior is also high. The logarithm of the joint distribution<code> log p(z,x)</code>: This term penalizes the variational distribution for assigning probability to regions with low joint distribution. Maximizing the ELBO forces the variational distribution to become a good approximation of the true posterior.</div></details>

<h4 id="heading-loss-function">Loss Function</h4>
<p>Loss Function = negative Log Likelihood of the following term:</p>
<p>$$-log(p(x_0))$$</p><p>But remember this is the reverse process and we must start at <code>x_T</code> and move back to <code>x_0</code>, so the probability of <code>x_0</code> will depend on all previous terms such as <code>x_1, x_2, x_3,..., x_T-1,x_T</code>. This makes it incredibly complex to predict the probability.</p>
<p>To solve this problem, we can compute the Variational Lower Bound for this objective and arrive at a more reasonable formula.</p>
<p>How does the reasonable formula look? Well, a little bit like this:</p>
<p>$$-\log(p_{\theta}(x_0)) \leq -\log(q(x_0)) + D_{KL}(q(x_{1:T}|x_0)||p_{\theta}(x_{1:T}|x_0))$$</p><p>Now if you are thinking about giving up, at this point, don’t. Because this is just scary-looking syntax and soon we will simplify it to simpler-looking syntax.</p>
<p>Now all this equation is saying is:</p>
<p><code>-p -p + DKL(something)</code></p>
<p>This seems reasonable, it means the negative log-likelihood of <code>x_0</code> will always be less than the negative log-likelihood of <code>x_0</code> added with a certain term called <code>DKL</code>.</p>
<p>So the first thing we need to learn about is <code>DKL</code>. It is the symbol for expressing something called KL Divergence.</p>
<p>Before that let us digress a bit:</p>
<ul>
<li><p>Let's say we have a function <code>f(x)</code> that we can’t compute.</p>
</li>
<li><p>If we can prove that some function <code>g(x)</code> is always smaller than <code>f(x)</code></p>
</li>
<li><p>Then theoretically by maximizing <code>g(x)</code>, we can be certain that <code>f(x)</code> also increases.</p>
</li>
</ul>
<p>Let us look at two distributions in the following Figure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731317638673/ab41a141-e2b6-4b91-9823-12e7dda987c3.jpeg" alt class="image--center mx-auto" /></p>
<p>Two distributions <code>f(x)</code> and <code>g(x)</code> where <code>g(x) &lt; f(x)</code> always</p>
<p>In this case, this is ensured by subtracting the KL divergence. So what exactly is KL Divergence?</p>
<hr />
<p><strong>KL Divergence Formulation</strong></p>
<p>$$D_{KL}(p||q) = \int_x p(x) \log \frac{p(x)}{q(x)} dx$$</p><details><summary>A Mathematical Note on KL Divergence</summary><div data-type="detailsContent">It is a measure of similarity between two distributions, given by the following expression. In short, if you always subtract the similarity between two distributions from the original distribution, you will end up maximizing it. But we have added the DKL term, because our goal is to minimize the negative log-likelihood. Why? Because remember that it is also our loss, and we would want the loss to go down.</div></details>

<hr />
<h3 id="heading-removing-uncomputable-terms">Removing uncomputable terms</h3>
<p>But we have a problem, we have the same term that we previously mentioned is uncomputable for us</p>
<p>$$-\log(p_{\theta}(x_0)) \leq -\log(q(x_0)) + D_{KL}(q(x_{1:T}|x_0)||p_{\theta}(x_{1:T}|x_0))$$</p><p>So let’s start with the other term</p>
<p>$$-\log(p_{\theta}(x_0)) \leq -\log(q(x_0)) + D_{KL}(q(x_{1:T}|x_0)||p_{\theta}(x_{1:T}|x_0))$$</p><p>$$= \log(\frac{q(x_{1:T}|x_0)}{p_\theta(x_{1:T}|x_0)})$$</p><p>Applying the Bayesian Rule to just the denominator:</p>
<p>$$p_{\theta}(x_{1:T}|x_0) = \frac{p_{\theta}(x_{1:T}, x_0)}{p_{\theta}(x_0)} = \frac{p_{\theta}(x_{1:T}, x_0)}{p_{\theta}(x_0)} = \frac{p_{\theta}(x_{1:T}, x_0)}{p_{\theta}(x_0)}$$</p><p>Substituting this back into the denominator of the log term we get</p>
<p>$$\log(\frac{q(x_{1:T}|x_0)}{p_\theta(x_{0:T})/p_\theta(x_0)})$$</p><p>Now we can pull the bottom quantity to the top using the fraction rules and split the logarithm to get:</p>
<p>$$\log(\frac{q(x_{1:T}|x_0)}{p_{\theta}(x_{0:T})}) + \log(p_{\theta}(x_0))$$</p><p>Now let us remember where we started, we wanted to simplify the <code>D_KL</code> term, so we have:</p>
<p>$$D_{KL}(q(x_{1:T}|x_0)||p_{\theta}(x_{1:T}|x_0)) = \log(\frac{q(x_{1:T}|x_0)}{p_\theta(x_{0:T})}) + \log(p_{\theta}(x_0))$$</p><p>Now let us plug this back into this expression:</p>
<p>$$-\log(p_{\theta}(x_0)) \leq -\log(q(x_0)) + D_{KL}(q(x_{1:T}|x_0)||p_{\theta}(x_{1:T}|x_0))$$</p><p>This gives us</p>
<p>$$-\log(p_{\theta}(x_0)) \leq \log(\frac{q(x_{1:T}|x_0)}{p_\theta(x_{0:T})})$$</p><hr />
<h3 id="heading-variational-lower-bound">Variational Lower Bound</h3>
<p>This is the Variational Lower Bound that we want to minimize.</p>
<p>Now look closely at the following expression</p>
<p>$$\log(\frac{q(x_{1:T}|x_0)}{p_\theta(x_{0:T})})$$</p><p>The term in the numerator is just the forward process.</p>
<p>The term in the denominator can be rewritten as the following:</p>
<p>$$p_{\theta}(x_{0:T}) = p_{\theta}(x_T) \prod_{t=1}^T p_{\theta}(x_{t-1}|x_t)$$</p><p>So let's take the current lower bound and rewrite it</p>
<p>$$\log(\frac{q(x_{1:T}|x_0)}{p_\theta(x_{0:T})}) = \log(\frac{\prod_{t=1}^{T}q(x_t|x_{t-1})}{p(x_T)\prod_{t=1}^{T}p_\theta(x_{t-1}|x_t)}) \\$$</p><p>$$= -\log(p(x_T)) + \log(\frac{\prod_{t=1}^{T}q(x_t|x_{t-1})}{\prod_{t=1}^{T}p_\theta(x_{t-1}|x_t)}) \\$$</p><p>$$= \log(p(x_T)) + \sum_{t=1}^{T}\log(\frac{q(x_t|x_{t-1})}{p_\theta(x_{t-1}|x_t)})$$</p><p>Next, we take out the first term or <code>t=0</code></p>
<p>$$-\log(p(x_T)) + \sum_{t=2}^{T} \log \frac{q(x_t|x_{t-1})}{p_{\theta}(x_{t-1}|x_t)} + \log \frac{q(x_1|x_0)}{p_{\theta}(x_0|x_1)}$$</p><p>Now applying Baye’s rule to the numerator of this</p>
<p>$$\log \frac{q(x_t|x_{t-1})}{p_{\theta}(x_{t-1}|x_t)}$$</p><p>term we get:</p>
<p>$$q(x_{t-1}|x_t) = \frac{q(x_{t-1}|x_t)q(x_t)}{q(x_{t-1})}$$</p><hr />
<h3 id="heading-conditioning-on-the-original-image">Conditioning on the original Image</h3>
<p>Now imagine looking at a noisy image, being shown a less noisy image, and being asked whether it is logically the image at the next step.</p>
<p>You can’t tell, right? This is because the two images you are shown have a high variance. This is true for <code>x_t-1</code> and <code>x_t</code></p>
<p>One way this can be remedied is by showing the original picture, each time you are shown the two noisy images. In math language, we say this as conditioning with the original term <code>x_0</code>.</p>
<p>$$q(x_{t-1}|x_t) = \frac{q(x_{t-1}|x_t, x_0) q(x_t|x_0)}{q(x_{t-1}|x_0)}$$</p><p>Now plugging this into the equation of the lower bound we get:</p>
<p>$$= -\log(p(x_T)) + \sum_{t=2}^T \log \frac{q(x_t|x_{t-1})}{p_{\theta}(x_{t-1}|x_t)} + \log \frac{q(x_1)}{p_{\theta}(x_1)}$$</p><p>$$= -\log(p(x_T)) + \sum_{t=2}^T \log \frac{q(x_t|x_{t-1}) q(x_{t-1})}{p_{\theta}(x_{t-1}|x_t) q(x_{t-1})} + \log \frac{q(x_1)}{p_{\theta}(x_1)}$$</p><p>Next, we split up the summation term into two parts because it helps us in the simplification process:</p>
<p>$$= -\log(p(x_T)) + \sum_{t=2}^T \log \frac{q(x_t|x_{t-1}, x_{t-2})}{p_{\theta}(x_{t-1}|x_t)} + \sum_{t=2}^T \log \frac{q(x_t|x_{t-1})}{q(x_{t-1}|x_{t-1})} + \log \frac{q(x_1|x_0)}{p_{\theta}(x_0|x_1)}$$</p><p>Let us zoom into the second summation term and set <code>T=4</code></p>
<p>$$\sum_{t=2}^4 \log \frac{q(x_t|x_{t-1}, x_0) q(x_{t-1}|x_{t-2}, x_0) q(x_{t-2}|x_{t-3}, x_0)}{q(x_{t-1}|x_{t-2}, x_0) q(x_{t-2}|x_{t-3}, x_0) q(x_{t-3}|x_{t-4}, x_0)} = \sum_{t=2}^4 \log \frac{q(x_t|x_{t-1}, x_0)}{q(x_{t-1}|x_{t-2}, x_0)}$$</p><p>Half of these terms cancel each other out leaving the above-simplified expression, for the sake of simplification the authors wanted the second summation term to be</p>
<p>$$\sum_{t=2}^T \log \frac{q(x_t|x_0)}{q(x_{t-1}|x_0)} = \log \frac{q(x_T|x_0)}{q(x_1|x_0)}$$</p><p>Again plugging that into the variational lower bound formula we get:</p>
<p>$$E = -\log(p(x_T)) + \sum_{t=2}^T \log \frac{q(x_t|x_{t-1}, x_0)}{p_\theta(x_{t-1}|x_t)} + \log \frac{q(x_T|x_0)}{q(x_1|x_0)} + \log \frac{q(x_1|x_0)}{p_\theta(x_0|x_1)}$$</p><p>Expanding the last two log terms:</p>
<p>$$= -\log(p(x_T)) + \sum_{t=2}^T \log \frac{q(x_t|x_{t-1}, x_0)}{p_\theta(x_{t-1}|x_t)} + \log q(x_T|x_0) - \log q(x_1|x_0) + \log q(x_1|x_0) - \log p_\theta(x_0|x_1)$$</p><p>$$= -\log(p(x_T)) + \sum_{t=2}^T \log \frac{q(x_t|x_{t-1}, x_0)}{p_\theta(x_{t-1}|x_t)} + \log q(x_T|x_0) - \log p_\theta(x_0|x_1)$$</p><p>$$= \frac{\log q(x_T|x_0)}{\log p(x_T)} + \sum_{t=2}^T \log \frac{q(x_t|x_{t-1}, x_0)}{p_\theta(x_{t-1}|x_t)} - \log p_\theta(x_0|x_1)$$</p><p>Rewriting this as a <strong>KL Divergence</strong> we get:</p>
<p>$$= D_{KL}(q(x_T|x_0)||p(x_T)) + \sum_{t=2}^T D_{KL}(q(x_t|x_{t-1}, x_0)||p_{\theta}(x_{t-1}|x_t)) - \log(p_{\theta}(x_0|x_1))$$</p><h3 id="heading-arriving-at-the-objective-function">Arriving at the Objective Function</h3>
<p>And that is our objective that we want to minimize, yes this feels like a step backward in terms of simplification, but let us zoom in and see which terms we can minimize or ignore for the sake of simplicity.</p>
<p>For example, the first term</p>
<p>$$D_{KL}(q(x_T|x_0)||p(x_T))$$</p><p>will always be low and can be ignored as far as finding the objective function for the loss is concerned because:</p>
<ul>
<li><p><code>q(x_T|x_0)</code> is just the forward process with no learnable parameters and will eventually converge to  random noise</p>
</li>
<li><p><code>p(x_T)</code> is random noise sampled from a Gaussian distribution</p>
</li>
</ul>
<p>Thus reformulating we have the following:</p>
<p>$$= \sum_{t=2}^T D_{KL}(q(x_t|x_{t-1}, x_0)||p_{\theta}(x_{t-1}|x_t)) - \log(p_{\theta}(x_0|x_1))$$</p><h3 id="heading-substituting-the-mean-in-the-kl-divergence">Substituting the Mean in the KL Divergence</h3>
<p>At this stage, it is good to recalibrate how this expression connects to the individual expressions of the forward and reverse processes, shown in the following figure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731305626923/f6e6c619-9e38-43f2-aea1-ae26b69a00a3.png" alt /></p>
<h5 id="heading-analytically-arriving-at-the-mean-of-the-reverse-process">Analytically arriving at the Mean of the Reverse Process</h5>
<p>Now let's look at the reverse process at <code>p(x_t-1|x_t)</code>, We already know that</p>
<p>$$p(x_{t-1}|x_t) = N(x_{t-1}; \mu_{\theta}(x_t), \Sigma_{\phi}(x_t))$$</p><p>We can ignore the variance term since it has a fixed schedule, so we can rewrite this as:</p>
<p>$$p(x_{t-1}|x_t) = N(x_{t-1}; \mu_{\theta}(x_t), \beta I)$$</p><p>So this means we need a neural network to predict the mean of the noise. Now let us express the forward process in a similar style.</p>
<h5 id="heading-analytically-arriving-at-the-mean-of-the-forward-process">Analytically arriving at the Mean of the Forward Process</h5>
<p>We also know that the forward process <code>q(x_t|x_t-1, x_0)</code> has an expression like the following:</p>
<p>$$q(x_t|x_{t-1}) = N(x_t, \sqrt{1-\beta_t}x_{t-1}, \beta_t I)$$</p><p>For the sake of making this similar, let us rewrite the above expression while conditioning on <code>x_0</code> and using a function like <code>µ_t</code></p>
<p>$$q(x_t|x_{t-1}, x_0) = N(x_t; \overline{\mu}_{\phi}(x_t, x_0), \overline{\beta}_t I)$$</p><p>Deriving the terms <code>µ_t</code>, and <code>β_t</code> will make this unnecessarily stretched out, so let us leave them as they are:</p>
<p>$$\overline{\mu}t(x_t, x_0) = \frac{\sqrt{\alpha_t(1-\overline{\alpha}{t-1})}}{1-\overline{\alpha}t}x_t + \frac{\sqrt{\overline{\alpha}{t-1}\beta_t}}{1-\overline{\alpha}_t}x_0$$</p><p>$$\overline{\beta}t = \frac{1-\overline{\alpha}{t-1}}{1-\overline{\alpha}_t}\beta_t$$</p><p>We can safely ignore the <code>β_t</code> term since it is fixed, let us instead focus on <code>µ_t(X_t,X_0)</code></p>
<p>We know that</p>
<p>$$\log(\frac{q(x_{1:T}|x_0)}{p_\theta(x_{1:T}|x_0)})$$</p><p>So,</p>
<p>$$x_0 = \frac{1}{\sqrt{\alpha_t}}(x_t - \sqrt{1-\overline{\alpha_t}}\epsilon)$$</p><p>Plugging this into <code>µ_t</code> we have:</p>
<p>$$\overline{\mu}_t(x_t, x_0) = \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\alpha_t}}\epsilon)(\frac{1}{\sqrt{\alpha_t}}(x_t - \sqrt{1-\overline{\alpha}_t}\epsilon))$$</p><p>$$\overline{\mu}t(x_t, x_0) = \frac{\sqrt{\alpha_t(1-\overline{\alpha}{t-1})}}{1-\overline{\alpha}t}x_t + \frac{\sqrt{\overline{\alpha}{t-1}\beta_t}}{1-\overline{\alpha}_t}(x_t - \sqrt{1-\overline{\alpha}_t}\epsilon)$$</p><p>$$\overline{\mu}_t(x_t, x_0) = \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\alpha_t}}\epsilon)$$</p><p>Essentially this means we are just subtracting random scaled noise from <code>x_t</code></p>
<h3 id="heading-expressing-the-mean-of-the-reverse-process-as-a-similar-expression">Expressing the Mean of the Reverse Process as a similar expression</h3>
<p>Now let us again go back to how the forward and reverse diffusion process connects to the variational lower bound expression. But this time let us also look at the Figure and try to figure out what is in the respective equations.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731305601289/a4401069-cb1e-4986-830f-5e39c4eec996.png" alt /></p>
<p>Now something funny happens here, in the reverse process:</p>
<p>$$p(x_{t-1}|x_t) = N(x_{t-1}; \mu_{\theta}(x_t, t), \beta I)$$</p><p>We realize that must predict the noise at time step <code>t</code>, given the <code>x_t</code> as an input to the model</p>
<p>Now do we have a formula where we can plug in the time step <code>t</code> and <code>x_t</code> as an input to the model. Yes, we do!</p>
<p>Remember for the forward process we have derived:</p>
<p>$$\overline{\mu}_t(x_t, x_0) = \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\overline{\alpha}_t}}\epsilon)$$</p><p>So we can write as:</p>
<p>$$\mu_{\theta}(x_t, t) = \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\overline{\alpha}t}}\epsilon{\theta}(x_t, t))$$</p><p>Here we just need a parameterized neural network <code>ε_(x_t,t)</code> that takes in the noisy image and the time step t and gives us the noise.</p>
<h4 id="heading-deriving-xt-1">Deriving <code>x_t-1</code></h4>
<p>Now from our previous formula for the reverse process, we have:</p>
<p>$$p(x_{t-1}|x_t) = N(x_{t-1}; \mu_{\theta}(x_t, t), \beta I)$$</p><p>Since we already have the formula for substituting we get:</p>
<p>$$= N(x_{t-1}; \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\overline{\alpha}t}}\epsilon{\theta}(x_t, t)), \beta I)$$</p><p>Now we can apply the <strong>reparametrization</strong> trick again and get the following value for:</p>
<p>$$x_{t-1} = \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\overline{\alpha}t}}\epsilon{\theta}(x_t, t)) + \sqrt{\beta_t}\epsilon$$</p><hr />
<h3 id="heading-further-simplifying-the-objective-function">Further Simplifying the Objective Function</h3>
<p>Now focusing back on our objective function:</p>
<p>$$\sum_{t=2}^T D_{KL}(q(x_t|x_{t-1}, x_0)||p_{\theta}(x_{t-1}|x_t)) - \log(p_{\theta}(x_0|x_1))$$</p><p>Let us single out the KL Divergence part, the authors resolved to simplify this into a simple mean squared error as shown in the following Figure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731318006023/a25933ce-111d-46ab-becf-459c17e2ac18.png" alt /></p>
<p>So we can write <strong>KL Divergence</strong> term as:</p>
<p>$$\frac{1}{2\sigma_t^2}\lVert \overline{\mu}t(x_t, x_0) - \mu{\theta}(x_t, x_0) \rVert^2$$</p><p>This simplifies matters a lot, again we can plug the values here to get:</p>
<p>$$\frac{1}{2\sigma_t^2}\lVert \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\overline{\alpha}_t}}\epsilon) - \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\overline{\alpha}t}}\epsilon{\theta}(x_t, t)) \rVert^2$$</p><p>Which can be simplified further into:</p>
<p>$$\frac{\beta_t^2}{2\sigma_t^2 \alpha_t(1-\overline{\alpha}t)}\lVert \epsilon - \epsilon{\theta}(x_t, t) \rVert^2$$</p><p>So the final expression becomes:</p>
<p>$$\frac{\beta_t^2}{2\sigma_t^2 \alpha_t(1-\overline{\alpha}t)}\lVert \epsilon - \epsilon{\theta}(x_t, t) \rVert^2 - \log(p_{\theta}(x_0|x_1))$$</p><p>The authors also considered the <code>-log(p(x_0|x_1)</code> to be a component of the prediction from the model rather than deriving its expression.</p>
<p>So the final objective function is:</p>
<p>$$\frac{\beta_t^2}{2\sigma_t^2 \alpha_t(1-\overline{\alpha}t)}\lVert \epsilon - \epsilon{\theta}(x_t, t) \rVert^2$$</p><p>Formally in the paper, this is expressed as:</p>
<p>$$L_{obj} = E_{t, x, \epsilon} [\frac{\beta_t^2}{2\sigma_t^2\alpha_t(1-\overline{\alpha}t)}\lVert \epsilon - \epsilon{\theta}(\sqrt{\alpha_t}x_t + \sqrt{1-\overline{\alpha}_t}\epsilon, t) \rVert^2]$$</p><p>Now you already know that the scary-looking <code>E</code> is simply the expectation of the random variable. That is just a fancy way of saying what the expected value of the objective function or loss would be at each time step, given the initial image and the noise.</p>
<p>Oh and also if you are afraid of the scary-looking alphas, remember earlier where we got:</p>
<p>$$x_t = \sqrt{\overline{\alpha}_t}x_0 + \sqrt{1-\overline{\alpha}_t}\epsilon$$</p><h2 id="heading-summing-up-literally">Summing Up (Literally)</h2>
<p>At this juncture, it is probably best to revisit our original goal:</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">🎯</div>
<div data-node-type="callout-text"><strong>AIM</strong>: Arriving at a formula that uses a neural network to predict the noise between two time steps.</div>
</div>

<p>At the end of this entire math circus what we have with us are two very important formulas:</p>
<p>$$L_{obj} = E_{t, x, \epsilon} [\frac{\beta_t^2}{2\sigma_t^2\alpha_t(1-\overline{\alpha}t)}\lVert \epsilon - \epsilon{\theta}(\sqrt{\alpha_t}x_t + \sqrt{1-\overline{\alpha}_t}\epsilon, t) \rVert^2]$$</p><p>The objective function allows the use of a neural network to predict the noise at each time step.</p>
<p>$$x_{t-1} = \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\overline{\alpha}t}}\epsilon{\theta}(x_t, t)) + \sqrt{\beta_t}\epsilon$$</p><p>Another formula that allows us to create the image for the subsequent time steps from the current time steps.</p>
<p>Congratulations! 🎉</p>
<details><summary>A Request 🙏</summary><div data-type="detailsContent">If you liked this blog and it helped you on your mathematical journey toward understanding the riddle of diffusion, please consider subscribing to the newsletter.</div></details>

<h2 id="heading-references">References:</h2>
<ul>
<li><p><a class="user-mention" href="https://hashnode.com/@ariG23498">Aritra Roy Gosthipaty</a> ‘s <a target="_blank" href="https://x.com/ariG23498">work on Explaining DDPM Models</a></p>
</li>
<li><p><a target="_blank" href="https://pyimagesearch.com/">PyImageSearch Course</a> on Build an AI Image Generator</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=HoKDTa5jHvg">https://www.youtube.com/watch?v=HoKDTa5jHvg</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=a4Yfz2FxXiY&amp;t=1195s">https://www.youtube.com/watch?v=a4Yfz2FxXiY&amp;t=1195s</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=HxQ94L8n0vU&amp;t=290s">https://www.youtube.com/watch?v=HxQ94L8n0vU&amp;t=290s</a></p>
</li>
<li><p><a target="_blank" href="https://theaisummer.com/diffusion-models/#approximating-the-reverse-process-with-a-neural-network">https://theaisummer.com/diffusion-models/#approximating-the-reverse-process-with-a-neural-network</a></p>
</li>
<li><p><a target="_blank" href="https://magic-with-latents.github.io/latent/posts/ddpms/part3/">https://magic-with-latents.github.io/latent/posts/ddpms/part3/</a></p>
</li>
<li><p><a target="_blank" href="https://mr-easy.github.io/2020-04-16-kl-divergence-between-2-gaussian-distributions/">https://mr-easy.github.io/2020-04-16-kl-divergence-between-2-gaussian-distributions/</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Choosing Between SigLIP and CLIP for Language Image Pretraining]]></title><description><![CDATA[Understand the changes from CLIP to SigLIP in vision-language models, highlighting the advantages of contrastive learning and how they enhances efficiency]]></description><link>https://blog.ritwikraha.dev/choosing-between-siglip-and-clip-for-language-image-pretraining</link><guid isPermaLink="true">https://blog.ritwikraha.dev/choosing-between-siglip-and-clip-for-language-image-pretraining</guid><category><![CDATA[Google gemma]]></category><category><![CDATA[paligemma]]></category><category><![CDATA[siglip]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[machine learning models]]></category><category><![CDATA[Computer Vision]]></category><category><![CDATA[openai]]></category><category><![CDATA[CLIP ]]></category><category><![CDATA[image processing]]></category><category><![CDATA[generative ai]]></category><category><![CDATA[loss functions]]></category><category><![CDATA[multimodal]]></category><category><![CDATA[Google]]></category><dc:creator><![CDATA[Ritwik Raha]]></dc:creator><pubDate>Fri, 02 Aug 2024 15:00:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722610590907/78964915-948b-44cf-9019-15a9e1dd3067.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="hn-table">
<table>
<thead>
<tr>
<td><a class="user-mention" href="https://hashnode.com/@ritwikraha">Ritwik Raha</a></td><td><a class="user-mention" href="https://hashnode.com/@ariG23498">Aritra Roy Gosthipaty</a></td></tr>
</thead>
<tbody>
<tr>
<td>Machine Learning Engineer</td><td>Machine Learning Engineer</td></tr>
<tr>
<td><a target="_blank" href="https://x.com/ritwik_raha">ritwik_raha</a></td><td><a target="_blank" href="https://x.com/ariG23498">arig23498</a></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-introduction">Introduction</h2>
<p>Suppose are given an image and three different captions. One of the captions correctly describes the image. How would you, as a human, choose the correct caption?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722527379950/1c1b08bf-76ed-49df-b088-315a72b93b4e.jpeg" alt class="image--center mx-auto" /></p>
<ul>
<li><p>You first look at the image and understand what is in it.</p>
</li>
<li><p>See the captions and grasp what is written.</p>
</li>
<li><p>Compare the representation of the image with the captions.</p>
</li>
<li><p>The caption which corresponds most to the image is your choice.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722527414898/7edcd367-341b-4dc2-9e93-f3971c0fbd01.jpeg" alt class="image--center mx-auto" /></p>
<blockquote>
<p>How can we use a deep learning model to achieve this</p>
</blockquote>
<p>To make our deep learning model choose from the caption, we need <strong>two</strong> models one for the image and one for the text. The image model takes the image as an input and outputs the <em>visual representation</em> in terms of image embeddings. The text model takes the captions as input and outputs the <em>textual representation</em> in terms of text embeddings.</p>
<p>We know that embeddings are vectors in a higher dimensional space. To compute the <strong>similarity</strong> between vectors, we compute the <strong>cosine similarity</strong> between them. Similarly to compute the similarity between the text and image embeddings, we compute the cosine similarity between them.</p>
<p>This task (choosing the correct text and image pairs) is a great pre-training objective for vision and language models. To simplify, the image and text embeddings for the correct pair should be similar, while that of the incorrect pair should be dissimilar.</p>
<p>We can formulate the task in a couple of ways. In this blog post, we talk about two prominent ways introduced in CLIP and SigLIP, and understand which is better (here there is a clear winner).</p>
<hr />
<h2 id="heading-how-does-clip-do-it">How does CLIP do it?</h2>
<p>The figure below is what a mini-batch of data for our task (choose the correct pair) looks like. A collection of image-text pairs. We denote images with <code>I</code> and text with <code>T</code>.</p>
<p>$$\text{Mini Batch } \mathcal{B} = \{(I_1, T_1), (I_2, T_2) \dots\}$$</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722527444435/1e75f4bc-9f70-4240-9635-236b139e91da.jpeg" alt class="image--center mx-auto" /></p>
<p><a target="_blank" href="https://openai.com/index/clip/">CLIP</a> (Connecting Text and Images by OpenAI) devises two models, an image encoder and a text encoder.</p>
<p>$$\text{Image Encoder: } f(I)=x$$</p><p>$$\text{Text Encoder: }g(T)=y$$</p><p>The encoder, as the name suggests, takes the input and encodes it into a latent representation (denoted by <code>x</code> for image latent, and <code>y</code> for text latent).</p>
<p>Now that we have the embeddings (the latent representations) from the encoders, we need a way to compute the similarity score. We delegate this to our friendly neighborhood function "the dot product".</p>
<p>$$\text{Dot product: }x.y$$</p><p>The similarity score gives us a measure of how similar the image and the text embeddings are. We would need to figure out a way to transform the similarity score into a likelihood measure.</p>
<blockquote>
<p>Why a likelihood measure? We want to predict (deep learning models are tasked to predict) how likely a text and an image pair are.</p>
</blockquote>
<p>To get the likelihood measure we use the soft-max function.</p>
<p>$$\frac{e^{\text{similarity score of a correct pair}}}{\sum_{\text{all incorrect pairs}}e^{\text{similarity score of pairs}}}$$</p><p>The numerator only deals with the correct pairs, while the denominator deals with everything except the correct pair. Intuitively the denominator is the normalization term, which makes the equation transform a similarity score into a likelihood measure.</p>
<p>Now that we have our likelihood measure, we can apply a log to it and then turn the product of likelihood into a summation (a trick deep learning engineers use quite often).</p>
<p>To condense this section into a mathematical statement we can write:</p>
<p>$$\sum_{i=1}^{|\mathcal{B}|}\left(\log\frac{e^{x_{i}y_{i}}}{\sum_{j=1}^{|\mathcal{B}|}e_{x_{i}.\boxed{y_{j}}}}\right)$$</p><p>If you look closely you will know that the image is static while we loop over the text in the mini-batch (the boxed section).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722527469586/ee8d8a20-a887-4a12-b1e1-5d0393ca7304.jpeg" alt class="image--center mx-auto" /></p>
<p>In CLIP we also keep the text static and loop over the image, to build the complete loss function.</p>
<p>$$\sum_{i=1}^{|\mathcal{B}|}\left(\log\frac{e^{x_{i}y_{i}}}{\sum_{j=1}^{|\mathcal{B}|}e_{\boxed{x_{j}}.y_{i}}}\right)$$</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722527489131/f87370fc-87cd-461a-a218-6aded0b3f75b.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-is-soft-max-bad">Is soft-max bad?</h2>
<p>We now know that the loss function used in CLIP from OpenAI is similar to a soft-max function. We needed soft-max to convert our similarity scores into likelihood estimates. The main reason for this transformation is the normalization term (the denominator).</p>
<p>Let's now take a different mini-batch of our dataset as shown in the Figure below. If you were to think of a problem with this mini-batch, what would that be?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722527520930/3543f159-63a4-4bcf-b199-03b506dff114.jpeg" alt class="image--center mx-auto" /></p>
<p>The data at index 2 and 3 (dog and corgi) are very similar to each other. This will harm the normalization term in the soft-max, which in turn harms our mini-batch loss. Here we uncover a very important assumption that needs to be in place to use the CLIP loss:</p>
<blockquote>
<p>The mini batch should not have similar data points.</p>
</blockquote>
<p><strong>Problem 1:</strong> This is genuinely a very difficult problem to solve. We have to get into our dataset, apply a filter (semantic filter of sorts), and prune the dataset before training our model.</p>
<p><strong>Problem 2:</strong> Let us now focus on a different problem. The soft-max loss is batch dependent. Even if you prune the dataset very well, you would need a big (in orders of thousands) batch size to train the model. The batch size problem directly stems from the normalization term. The more varied data present in a mini-batch, the better likelihood term we get!</p>
<p><strong>Problem 3:</strong> Notice that the loss function of CLIP runs twice in the training loop. Once where the image is static we iterate over the text, and the other time when we keep the text static and iterate over the images.</p>
<p>The three major cons:</p>
<ol>
<li><p>Pruning dataset is a must</p>
</li>
<li><p>Large batch size is a must</p>
</li>
<li><p>Running the loss function twice is a must</p>
</li>
</ol>
<p>All of these problems motivated researchers to devise a better (more data and batch-agnostic way) to compute the loss.</p>
<h2 id="heading-enter-siglip">Enter SigLIP</h2>
<p>If you think about the root cause of all the cons of soft-max loss, you will quickly notice that it is the <strong>normalization term</strong> (the denominator).</p>
<p>The denominator is a sum of the exponential similarity score of all the other pairs except the correct one.</p>
<blockquote>
<p>How do we get rid of the normalization term?</p>
</blockquote>
<p>SigLIP (Sigmoid Loss for Language Image Pre-Training) a 2023 paper from Google DeepMind aims to solve this problem with the <strong>sigmoid loss</strong> expression.</p>
<h3 id="heading-the-sigmoid-loss">The Sigmoid Loss</h3>
<p>Let's first check out how the sigmoid function looks like:</p>
<p>$$y=\frac{1}{1+e^{-x}}$$</p><p>Note, here <code>x</code> and <code>y</code> are the coordinates of a 2D plane. If we plot the graph we get something like this:</p>
<iframe src="https://www.desmos.com/calculator/usclqdpsjn?embed" width="500" height="500" style="border:1px solid #ccc"></iframe>

<blockquote>
<p>What if we just used <strong>sigmoid</strong> instead of <strong>softmax</strong>?</p>
</blockquote>
<p>That is exactly what the authors of <a target="_blank" href="https://arxiv.org/abs/2303.15343">SigLIP</a> did, formulate the language-image pretraining objective as a sigmoid loss function.</p>
<p>The sigmoid loss used in SigLIP can be represented as follows:</p>
<p>$$L = -\frac{1}{|B|} \sum_{i=1}^{|B|} \sum_{j=1}^{|B|} \log \frac{1}{1 + e^{z_{ij}(-tx_i \cdot y_j + b)}}$$</p><p>Instead of the softmax, SigLIP uses a sigmoid-based loss that operates independently on each image-text pair. The pseudocode from the Google Deepmind paper is presented below:</p>
<pre><code class="lang-python"><span class="hljs-comment"># img_emb </span>
<span class="hljs-comment"># txt_emb : image model embedding [n, dim] : text model embedding [n, dim]  </span>
<span class="hljs-comment"># t_prime, b : learnable temperature and bias </span>
<span class="hljs-comment"># n : mini-batch size</span>

t = exp(t_prime) 
zimg = l2_normalize(img_emb) 
ztxt = l2_normalize(txt_emb) 
logits = dot(zimg, ztxt.T) * t + b 
labels = <span class="hljs-number">2</span> * eye(n)- ones(n) <span class="hljs-comment">#-1 with diagonal 1 </span>
l =-sum(log_sigmoid(labels * logits)) / n
</code></pre>
<p>Let us understand the design of this loss function in detail:</p>
<ul>
<li><p><code>-1/|B|</code> : Scales the loss by the inverse of the batch size, ensuring the loss is comparable across different batch sizes.</p>
</li>
<li><p><code>Σ(i=1 to |B|) Σ(j=1 to |B|)</code> : Computes the loss over all possible image-text pairs in the batch, including both positive and negative pairs.</p>
</li>
<li><p><code>log(·)</code> : Converts the probability from the sigmoid function into a loss value. It helps in numerical stability and makes the optimization landscape smoother.</p>
</li>
<li><p><code>1 / (1 + e^(·))</code> : Maps the input to a probability between 0 and 1. For positive pairs, we want this probability to be high (close to 1), and for negative pairs, we want it to be low (close to 0).</p>
</li>
<li><p><code>z_ij</code> : Determines whether the pair is positive (1) or negative (-1). It flips the sign of the similarity for negative pairs.</p>
</li>
<li><p><code>t</code> : Controls the steepness of the sigmoid. Higher values make the model more confident but potentially less stable. Lower values make it less confident but more stable.</p>
</li>
<li><p><code>x_i · y_j</code> : Measures how similar the image and text embeddings are. Higher values indicate more similar pairs.</p>
</li>
<li><p><code>b</code> : Shifts the decision boundary of the sigmoid. It helps to counteract the imbalance between positive and negative pairs, especially at the start of training.</p>
</li>
</ul>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/DvMbgpyeWZ8">https://youtu.be/DvMbgpyeWZ8</a></div>
<p> </p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sigmoid_loss</span>(<span class="hljs-params">image_emb, text_emb, temperature, bias</span>):</span>
    similarity = dot_product(image_emb, text_emb) 
    logits = temperature * similarity + bias
    labels = <span class="hljs-number">2</span> * eye(batch_size) - <span class="hljs-number">1</span>  <span class="hljs-comment"># 1 for positives, -1 for negatives</span>
    loss = -mean(log_sigmoid(labels * logits))
    <span class="hljs-keyword">return</span> loss
</code></pre>
<h3 id="heading-architecture-of-siglip">Architecture of SigLIP</h3>
<p>Here's a high-level view of how data flows through the SigLIP model:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722583708806/ca1896d5-9637-4746-a07b-169f42e24fc8.png" alt class="image--center mx-auto" /></p>
<p>The authors of the Google DeepMind paper pre-trained their SigLIP models on the <a target="_blank" href="https://sites.research.google/pali/">WebLI</a> dataset, using only English image and text pairs.</p>
<ul>
<li><p>The authors used moderately-sized models: B/16 ViT for image embeddings and B-sized transformer for text embeddings.</p>
</li>
<li><p>The input images were resized to 224×224 resolution.</p>
</li>
<li><p>The text was tokenized by a 32k vocabulary sentence-piece tokenizer trained on the English C4 dataset, and a maximum of 16 text tokens were kept. Figure 2 middle plot shows SigLIP results.</p>
</li>
<li><p>With less than 32k batch size, SigLIP outperformed CLIP (WebLI) baselines.</p>
</li>
<li><p>On the other end of the scale, the memory efficiency of the sigmoid loss enabled much larger batch sizes.</p>
</li>
<li><p>For example, with four TPU-v4 chips, they could fit a batch size of 4096 with a Base SigLIP but only 2048 with a corresponding CLIP model.</p>
</li>
</ul>
<h3 id="heading-analysis-of-batch-size-effects">Analysis of Batch Size Effects</h3>
<p>One of the most intriguing aspects of the research was a comprehensive study on the impact of batch size in contrastive learning. This study challenges some common assumptions and provides valuable insights for practitioners.</p>
<p>The authors followed the setup from the Locked-image Tuning (LiT) paper. The DeepMind authors explored an unprecedented range of batch sizes, from 512 to 1 million, to thoroughly investigate the relationship between batch size and model performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722584398268/39c6c996-abb2-49cf-a2e1-05f49ad3b9e5.png" alt="Fig X: Source: https://arxiv.org/abs/2303.15343" class="image--center mx-auto" /></p>
<h3 id="heading-observations">Observations</h3>
<p>SigLIP performs well with smaller batch sizes, both losses stabilize around 32k, and very large batch sizes (&gt;256k) can reduce performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722584327416/301c4962-51dd-45d8-82c8-a379b14b1bd6.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p><strong>Sigmoid</strong> vs <strong>Softmax</strong> Performance</p>
<ul>
<li><p>For batch sizes &lt; 16k: Sigmoid loss significantly outperforms softmax</p>
</li>
<li><p>For batch sizes &gt; 16k: Softmax catches up, with sigmoid slightly ahead</p>
</li>
</ul>
</li>
<li><p><strong>Performance Saturation</strong></p>
<ul>
<li><p>Surprisingly, performance saturates around 32k batch size</p>
</li>
<li><p>Further increases yield only minor improvements</p>
</li>
<li><p>Peak performance observed at 256k batch size</p>
</li>
</ul>
</li>
<li><p><strong>Large Batch Training</strong></p>
<ul>
<li><p>Successfully trained a SigLiT model with a 1 million batch size</p>
</li>
<li><p>This is far beyond previous studies, which typically stopped at 64k</p>
</li>
</ul>
</li>
<li><p><strong>Best Performance</strong></p>
<ul>
<li><p>The authors mention their best SigLiT model (B-sized text encoder) achieved 84.7% zero-shot ImageNet accuracy</p>
</li>
<li><p>The original LiT paper reported 85.2% with a 10x larger text model</p>
</li>
</ul>
</li>
</ul>
<p>The batch size study reveals that the relationship between batch size and performance in contrastive learning is more nuanced than previously thought. While larger batch sizes can yield better results, there's a point of diminishing returns (around 32k in our experiments).</p>
<p>The sigmoid loss consistently performs well across batch sizes and enables efficient training with limited resources. This makes SigLIP a versatile choice for various research and production scenarios.</p>
<h2 id="heading-future-directions-and-open-questions">Future Directions and Open Questions</h2>
<ol>
<li><p>How can we further improve efficiency for multilingual training?</p>
</li>
<li><p>Are there ways to combine the benefits of sigmoid and softmax losses?</p>
</li>
<li><p>Can we design more effective negative sampling strategies for the sigmoid loss?</p>
</li>
<li><p>How does SigLIP perform on other modalities beyond images and text?</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So clearly SigLIP is better and we must strive to "find-and-replace" CLIP with SigLIP across all code bases and all researches right?</p>
<p>We must replace CLIP with SigLIP right?</p>
<p>Well, the answer is not so simple. As illustrated above batch size, compute resources and pretraining strategy play a massive role in the choice of the loss function.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://x.com/giffmana/status/1692641733459267713">https://x.com/giffmana/status/1692641733459267713</a></div>
<p> </p>
<h3 id="heading-contrastive-losses-in-vision-language-models">Contrastive Losses in Vision Language Models</h3>
<p>Contrastive loss functions are crucial in training vision-language models because they help the model learn to distinguish between correct and incorrect image-text pairs. By maximizing the similarity of correct pairs and minimizing the similarity of incorrect pairs, the model can better understand and match images and text.</p>
<ul>
<li><p><strong>Use CLIP:</strong> When you have access to large computational resources and can handle the need for large batch sizes and dataset pruning.</p>
</li>
<li><p><strong>Use SigLIP:</strong> When you want a more efficient training process, especially with limited computational resources. SigLIP is also preferable when you need to train with smaller batch sizes.</p>
</li>
<li><p><strong>Use Custom Loss:</strong> When you have specific requirements or constraints that neither CLIP nor SigLIP can address, designing a custom loss function tailored to your needs might be the best approach.</p>
</li>
</ul>
<p>SigLIP demonstrates that sometimes, simpler is better. We can achieve impressive results with improved efficiency by rethinking the fundamental loss function for contrastive learning. This work opens up new possibilities for scaling language-image pre-training and making it more accessible to researchers with limited computational resources.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://openai.com/index/clip/">CLIP: Connecting text and images</a></p>
</li>
<li><p><a target="_blank" href="https://arxiv.org/abs/2303.15343">SigLIP: Sigmoid Loss for Language Image Pre-Training</a></p>
</li>
<li><p><a target="_blank" href="https://sites.research.google/pali/">PaLI: Pathways Language Image Model</a></p>
</li>
<li><p><a target="_blank" href="https://blog.ritwikraha.dev/understanding-paligemma-in-50-minutes-or-less">PaliGemma Report</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Understanding PaliGemma in 50 minutes  or less]]></title><description><![CDATA[Understand PaliGemma: a versatile vision-language model for image captioning, visual question answering, and object detection in under 50 minutes]]></description><link>https://blog.ritwikraha.dev/understanding-paligemma-in-50-minutes-or-less</link><guid isPermaLink="true">https://blog.ritwikraha.dev/understanding-paligemma-in-50-minutes-or-less</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[transformers]]></category><category><![CDATA[huggingface]]></category><category><![CDATA[AI]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[Google]]></category><category><![CDATA[gemma]]></category><category><![CDATA[Gemma AI]]></category><category><![CDATA[gemini]]></category><category><![CDATA[Computer Vision]]></category><dc:creator><![CDATA[Ritwik Raha]]></dc:creator><pubDate>Fri, 24 May 2024 18:51:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1716576227391/18576908-1fb3-4719-ba00-2d1a9e1ce917.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>PaliGemma is designed as a versatile model for transfer to a wide range of vision-language tasks such as image and short video caption, visual question answering, text reading, object detection, and object segmentation.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716574313229/6b4d62db-951a-448e-95bc-9fa134ef39bd.gif" alt class="image--center mx-auto" /></p>
<details><summary>Note of some importance</summary><div data-type="detailsContent">A note of thanks, acknowledgment, and warning: This post is a collation of wonderful resources from the <a target="_blank" href="https://developers.googleblog.com/id/gemma-family-and-toolkit-expansion-io-2024/">PaliGemma</a> model card, the <a target="_blank" href="https://huggingface.co/blog/paligemma">HuggingFace Blogpost</a>, and the <a target="_blank" href="https://github.com/google-research/big_vision">BigVision</a> repository. The point of this post is to simplify and show it from my perspective. I am open to constructive criticism and</div></details>

<h2 id="heading-what-is-paligemma">What is PaliGemma?</h2>
<p>PaliGemma is a new family of vision-language models from Google. These models can process both images and text to produce text outputs.</p>
<p>Google has released three types of PaliGemma models:</p>
<ul>
<li><p><strong>Pretrained (pt) models</strong>: Trained on large datasets without task-specific tuning.</p>
</li>
<li><p><strong>Mix models</strong>: A combination of pre-trained and fine-tuned elements.</p>
</li>
<li><p><strong>Fine-tuned (ft) models</strong>: Optimized for specific tasks with additional training.</p>
</li>
</ul>
<p>Each type comes in different resolutions and multiple precisions for convenience. All models are available on the Hugging Face Hub with model cards, licenses, and integration with transformers.</p>
<h2 id="heading-how-do-i-get-it-running">"How do I get it running?"</h2>
<p>The model comes with simple out-of-the-box usage with Huggingface Transformers. A simple colab notebook is linked <a target="_blank" href="https://github.com/ritwikraha/Talks-and-Lessons/blob/main/notebooks/paligemma_inference.ipynb">here</a>.</p>
<pre><code class="lang-python">
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, PaliGemmaForConditionalGeneration, PaliGemmaProcessor
<span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> notebook_login
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image
<span class="hljs-keyword">from</span> matplotlib <span class="hljs-keyword">import</span> pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-keyword">import</span> requests

input_text = <span class="hljs-string">"Who is this person?"</span>
img_url = <span class="hljs-string">"https://huggingface.co/datasets/ritwikraha/random-storage/resolve/main/cohen.jpeg"</span>
input_image = Image.open(requests.get(img_url, stream=<span class="hljs-literal">True</span>).raw)


device = torch.device(<span class="hljs-string">"cuda"</span> <span class="hljs-keyword">if</span> torch.cuda.is_available() <span class="hljs-keyword">else</span> <span class="hljs-string">"cpu"</span>)
model_id = <span class="hljs-string">"google/paligemma-3b-mix-224"</span>
model = PaliGemmaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.bfloat16)
processor = PaliGemmaProcessor.from_pretrained(model_id)

inputs = processor(text=input_text, images=input_image,
                  padding=<span class="hljs-string">"longest"</span>, do_convert_rgb=<span class="hljs-literal">True</span>, return_tensors=<span class="hljs-string">"pt"</span>).to(<span class="hljs-string">"cuda"</span>)
model.to(device)
inputs = inputs.to(dtype=model.dtype)

<span class="hljs-keyword">with</span> torch.no_grad():
  output = model.generate(**inputs, max_length=<span class="hljs-number">496</span>)
print(processor.decode(output[<span class="hljs-number">0</span>], skip_special_tokens=<span class="hljs-literal">True</span>)
)
</code></pre>
<h2 id="heading-what-is-the-architecture-like"><strong>"What is the architecture like?"</strong></h2>
<p>PaliGemma (GitHub) is a family of vision-language models with an architecture featuring SigLIP-So400m as the image encoder and Gemma-2B as the text decoder.</p>
<ul>
<li><p><strong>SigLIP</strong> is a state-of-the-art model capable of understanding both images and text. Similar to CLIP, it includes an image and text encoder trained together.</p>
</li>
<li><p><strong>Gemma</strong> is a decoder-only model designed for text generation.</p>
</li>
</ul>
<h3 id="heading-but-what-is-siglip">But what is SigLIP?</h3>
<p>SigLIP introduces a straightforward modification to the widely-used CLIP architecture, as detailed in the paper <a target="_blank" href="https://arxiv.org/abs/2303.15343">https://arxiv.org/abs/2303.15343</a>. CLIP's architecture includes an image encoder and a text encoder, both utilizing Transformer-based models.</p>
<p>The pre-training of CLIP employs a contrastive approach to ensure that embeddings of corresponding images and texts are close in the embedding space, while non-matching pairs are positioned far apart. Traditionally, CLIP is trained with a softmax loss function, which necessitates a global view of all pairwise similarities for probability normalization.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716661503131/850b71f2-0c3b-4564-81d2-ad61a67443c1.png" alt class="image--center mx-auto" /></p>
<p>SigLIP simplifies this process by substituting the softmax loss with a sigmoid loss. Unlike softmax, the sigmoid loss does not require a global perspective on pairwise similarities. This modification converts the task into a binary classification problem: determining whether a given image and text pair belong together, with a straightforward yes or no.</p>
<h3 id="heading-but-what-is-gemma">But what is Gemma?</h3>
<p>Gemma is a family of lightweight, state-of-the-art open models derived from the research and technology that underpinned the creation of Gemini models. These models exhibit robust performance across various academic benchmarks, particularly in language understanding, reasoning, and safety. The Gemma models are available in two sizes, featuring 2 billion and 7 billion parameters, with both pretrained and fine-tuned checkpoints provided.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716661686222/0517ac7b-fa76-4f4a-b163-e198ca2d8e11.png" alt class="image--center mx-auto" /></p>
<p>PaliGemma combines these two components: the image encoder from SigLIP and the text decoder from Gemma, connected through a linear adapter. This combination creates a powerful vision-language model that can be pre-trained on image-text data and fine-tuned for tasks like captioning and referring segmentation.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716573006637/22bef36d-1b58-4413-b122-bbd9022f06ad.png" alt class="image--center mx-auto" /></p>
<p>Let us look at the boilerplate code of what this might look like. The actual code is present in the <code>bigvision</code> <a target="_blank" href="https://github.com/google-research/big_vision/tree/main/big_vision/trainers/proj/paligemma">repository</a> and this is simply a reduced version of that code.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Model</span>(<span class="hljs-params">nn.Module</span>):</span>
    <span class="hljs-string">"""Two towers transformer for image and text."""</span>
    img_model: str = <span class="hljs-string">"vit"</span>
    img: Optional[ConfigDict] = <span class="hljs-literal">None</span>
    llm_model: str = <span class="hljs-string">"proj.paligemma.gemma_bv"</span>
    llm: Optional[ConfigDict] = <span class="hljs-literal">None</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment"># Initialize LLM and image models</span>
        self._llm = importlib.import_module(<span class="hljs-string">f"big_vision.models.<span class="hljs-subst">{self.llm_model}</span>"</span>).Model(**(self.llm <span class="hljs-keyword">or</span> {}), name=<span class="hljs-string">"llm"</span>)
        img_config = {<span class="hljs-string">"num_classes"</span>: self._llm.embdim, **(self.img <span class="hljs-keyword">or</span> {})}
        self._img_model = importlib.import_module(<span class="hljs-string">f"big_vision.models.<span class="hljs-subst">{self.img_model}</span>"</span>).Model(**img_config, name=<span class="hljs-string">"img"</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">embed_image</span>(<span class="hljs-params">self, image, train=False</span>):</span>
        <span class="hljs-string">"""Embeds the input image."""</span>
        <span class="hljs-comment"># Preprocess image and call image model</span>
        <span class="hljs-comment"># Return image embeddings and any auxiliary outputs</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">embed_text</span>(<span class="hljs-params">self, tokens, train=False</span>):</span>
        <span class="hljs-string">"""Embeds the input text tokens."""</span>
        <span class="hljs-comment"># Call LLM to embed text tokens</span>
        <span class="hljs-comment"># Return text embeddings and any auxiliary outputs</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">embed_image_and_text</span>(<span class="hljs-params">self, image, text, input_mask=None, mask_ar=None, train=False</span>):</span>
        <span class="hljs-string">"""Concatenates image and text embeddings."""</span>
        <span class="hljs-comment"># Embed image and text separately</span>
        <span class="hljs-comment"># Combine embeddings into a single sequence</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, image, text, mask_ar, train=False</span>):</span>
        <span class="hljs-string">"""Processes input image and text and returns logits."""</span>
        <span class="hljs-comment"># Embed image and text</span>
        <span class="hljs-comment"># Create attention mask and call transformer</span>
        <span class="hljs-comment"># Extract and return logits</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">prefill_cache</span>(<span class="hljs-params">self, x, input_mask, mask_ar, cache_size</span>):</span>
        <span class="hljs-string">"""Initializes decoding cache with prompt."""</span>
        <span class="hljs-comment"># Initialize cache for decoding</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">extend_cache</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-string">"""Advances decoding cache with new input."""</span>
        <span class="hljs-comment"># Extend cache for decoding</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_fallback_prefill_cache</span>(<span class="hljs-params">self, x, input_mask, mask_ar, cache_size</span>):</span>
        <span class="hljs-comment"># Fallback method for initializing cache</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_fallback_extend_cache</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-comment"># Fallback method for extending cache</span>
        <span class="hljs-keyword">pass</span>
</code></pre>
<p>The above boilerplate code defines a <code>Model</code> class in a PyTorch-like framework, designed to implement a two-tower transformer architecture for vision-language models (VLMs). The model consists of two primary components: an image model (using ViT) and a language model (using a variant of the Gemma model).</p>
<p>The <code>Model</code> class includes methods for embedding images and text, concatenating these embeddings, and processing them together to generate output logits.</p>
<h3 id="heading-two-tower-transformer-architecture-for-vlms">Two-Tower Transformer Architecture for VLMs</h3>
<p>The two-tower transformer architecture in vision-language models (VLMs) involves separate towers (or networks) for processing images and text, which are later combined for joint tasks. Here's how it works:</p>
<ol>
<li><p><strong>Image Embedding Tower</strong>:</p>
<ul>
<li><p>The image model, specified by <code>img_model</code> (e.g., ViT), processes input images.</p>
</li>
<li><p>The model is initialized with parameters specified in the <code>img</code> configuration.</p>
</li>
<li><p>The <code>embed_image</code> method preprocesses the image and generates embeddings using the image model.</p>
</li>
</ul>
</li>
<li><p><strong>Text Embedding Tower</strong>:</p>
<ul>
<li><p>The language model, specified by <code>llm_model</code> (e.g., Gemma variant), processes input text tokens.</p>
</li>
<li><p>The model is initialized with parameters specified in the <code>llm</code> configuration.</p>
</li>
<li><p>The <code>embed_text</code> method generates embeddings for text tokens using the language model.</p>
</li>
</ul>
</li>
<li><p><strong>Combining Embeddings</strong>:</p>
<ul>
<li><p>The <code>embed_image_and_text</code> method separately embeds images and text, then concatenates these embeddings into a single sequence.</p>
</li>
<li><p>This combined sequence is used for tasks that require joint image-text understanding.</p>
</li>
</ul>
</li>
<li><p><strong>Processing Inputs</strong>:</p>
<ul>
<li>The <code>__call__</code> method processes input images and text, creates an attention mask, and passes the combined embeddings through a transformer to generate output logits.</li>
</ul>
</li>
</ol>
<p>By leveraging this two-tower approach, the PaliGemma model can effectively learn and utilize the relationships between visual and textual information, which is not wholly indifferent from how a Vision language Model is pre-trained.</p>
<p>As mentioned before the PaliGemma release includes three types of models:</p>
<ul>
<li><p><strong>PT checkpoints</strong> are pre-trained models that can be further fine-tuned for specific downstream tasks.</p>
</li>
<li><p><strong>Mix checkpoints</strong>: These models are pre-trained and then fine-tuned on a mixture of tasks. They are suitable for general-purpose inference with free-text prompts and are intended for research purposes only.</p>
</li>
<li><p><strong>FT checkpoints</strong>: These are specialized fine-tuned models, each optimized for a different academic benchmark. They come in various resolutions and are also intended for research purposes only.</p>
</li>
</ul>
<details><summary>PaliGemma Model Sizes</summary><div data-type="detailsContent">The PaliGemma models come in three different resolutions: <code>224x224</code>, <code>448x448</code>, and <code>896x896</code>. They are also available in three different precisions: <code>bfloat16</code>, <code>float16</code>, and <code>float32</code>. Each model repository contains checkpoints for a specific resolution and task, with three revisions corresponding to the available precisions. The main branch of each repository contains <code>float32</code> checkpoints, while the <code>bfloat16</code> and <code>float16</code> revisions contain the respective precision models.</div></details>

<p>There are separate repositories for models compatible with HuggingFace Transformers and those using the original JAX implementation.</p>
<h2 id="heading-what-was-the-pretraining-like">What was the Pretraining like?</h2>
<p>PaliGemma is pre-trained on the following mixture of datasets:</p>
<h3 id="heading-datasets">Datasets</h3>
<ul>
<li><p><strong>WebLI (Web Language Image)</strong>:</p>
<p>  <img src="https://www.researchgate.net/publication/363564241/figure/fig2/AS:11431281084502540@1663211858376/The-WebLI-dataset-Top-Sampled-images-4-associated-with-multilingual-alt-text.png" alt="The WebLI dataset. Top: Sampled images 4 associated with multilingual... |  Download Scientific Diagram" class="image--center mx-auto" /></p>
<p>  A web-scale multilingual image-text dataset sourced from the public web. Various splits of WebLI are used to develop versatile model capabilities such as visual semantic understanding, object localization, visually situated text understanding, and multilingual proficiency.</p>
</li>
<li><p><strong>CC3M-35L</strong>:</p>
<p>  <img src="https://www.researchgate.net/publication/369655531/figure/fig1/AS:11431281132722392@1680233052185/a-Three-image-text-pairs-randomly-sampled-from-CC3M-dataset-have-some-local.png" alt="a) Three image-text pairs randomly sampled from CC3M dataset have some... |  Download Scientific Diagram" /></p>
<p>  Curated English image-alt_text pairs from webpages (Sharma et al., 2018). Translated into 34 additional languages using the Google Cloud Translation API.</p>
</li>
<li><p><strong>VQ²A-CC3M-35L/VQG-CC3M-35L</strong>:<br />  A subset of VQ2A-CC3M (Changpinyo et al., 2022a), translated into the same 34 languages as CC3M-35L, using the Google Cloud Translation API.</p>
</li>
<li><p><strong>OpenImages</strong>:</p>
<p>  <img src="https://storage.googleapis.com/openimages/web/images/oidv7_all-in-one_example_ab.jpg" alt="Open Images V7 - Description" /></p>
<p>  Detection and object-aware questions and answers (Piergiovanni et al. 2022) generated by handcrafted rules on the OpenImages dataset.</p>
</li>
<li><p><strong>WIT</strong>:<br />  Images and texts collected from Wikipedia (Srinivasan et al., 2021).</p>
</li>
</ul>
<h2 id="heading-wait-can-i-finetune-it">"Wait can I finetune it?"</h2>
<h3 id="heading-fine-tuning-methods">Fine-Tuning Methods</h3>
<p><strong>1. JAX Fine-Tuning Script:</strong></p>
<ul>
<li><p>PaliGemma was trained in the <code>big_vision</code> codebase, which has also been used for models like BiT, ViT, LiT, CapPa, and SigLIP.</p>
</li>
<li><p>The project configuration folder <code>configs/proj/paligemma/</code> contains a <a target="_blank" href="http://README.md"><code>README.md</code></a>.</p>
</li>
<li><p>Pretrained models can be transferred using configuration files in the <code>transfers/</code> subfolder.</p>
</li>
<li><p>To transfer your own model, fork <code>transfers/</code><a target="_blank" href="http://forkme.py"><code>forkme.py</code></a> and follow the instructions in the comments to adapt it to your use case.</p>
</li>
<li><p>A Colab notebook, <code>finetune_paligemma.ipynb</code>, provides a simplified fine-tuning process on a free T4 GPU runtime, updating only the weights in the attention layers (170M parameters) and using SGD instead of Adam.</p>
</li>
</ul>
<p><strong>2. Fine-Tuning with Hugging Face Transformers:</strong></p>
<ul>
<li><p>Fine-tuning PaliGemma is straightforward using the <code>transformers</code> library.</p>
</li>
<li><p>Methods such as QLoRA or LoRA fine-tuning can be employed.</p>
</li>
<li><p>An example process involves briefly fine-tuning the decoder, followed by switching to QLoRA fine-tuning.</p>
</li>
<li><p>Ensure to install the latest version of the <code>transformers</code> library.</p>
</li>
</ul>
<p><strong>3. Fine-Tuning with Vanilla Pytorch script</strong></p>
<ul>
<li><p>A small and lean PyTorch script to fine-tune the PaliGemma model</p>
</li>
<li><p>Developed by <a class="user-mention" href="https://hashnode.com/@ariG23498">Aritra Roy Gosthipaty</a> in this <a target="_blank" href="https://github.com/ariG23498/ft-pali-gemma">repository</a>.</p>
</li>
<li><p>Fine-tune on any dataset containing images and caption pairs.</p>
</li>
</ul>
<h3 id="heading-training-and-model-information">Training and Model Information</h3>
<ul>
<li><p>PaliGemma models have been released in various fine-tuned versions by Google.</p>
</li>
<li><p>These models were trained using the <code>big_vision</code> codebase, with a history of developing models like BiT, ViT, LiT, CapPa, SigLIP, and more.</p>
</li>
</ul>
<h3 id="heading-model-performance-table-on-fine-tuned-checkpoints">Model Performance Table on Fine-tuned Checkpoints</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Model Name</td><td>Dataset/Task</td><td>Score in Transferred Task</td></tr>
</thead>
<tbody>
<tr>
<td>paligemma-3b-ft-vqav2-448</td><td>Diagram Understanding</td><td>85.64 Accuracy on VQAV2</td></tr>
<tr>
<td>paligemma-3b-ft-cococap-448</td><td>COCO Captions</td><td>144.6 CIDEr</td></tr>
<tr>
<td>paligemma-3b-ft-science-qa-448</td><td>Science Question Answering</td><td>95.93 Accuracy on ScienceQA Img subset with no CoT</td></tr>
<tr>
<td>paligemma-3b-ft-refcoco-seg-896</td><td>Understanding References to Specific Objects in Images</td><td>76.94 Mean IoU on refcoco</td></tr>
<tr>
<td>paligemma-3b-ft-rsvqa-hr-224</td><td>Remote Sensing Visual Question Answering</td><td>92.61 Accuracy on test</td></tr>
</tbody>
</table>
</div><h2 id="heading-why-paligemma">Why PaliGemma?</h2>
<p>Changing the pretraining strategy and utilizing larger datasets like LAION can significantly enhance PaliGemma's capabilities as a multimodal model for various tasks. Pretraining on vast and diverse datasets improves the model's understanding and generation of nuanced and contextually rich outputs. By scaling the architecture, such as replacing the autoregressive decoder with a more advanced model like Gemini, and training the SigLIP processor on higher-quality, finer-grained images, PaliGemma can achieve superior performance in tasks requiring detailed visual-semantic understanding, precise object localization, and robust multilingual text generation. This will eventually lead to the model becoming more versatile and powerful for a wide range of multimodal applications.</p>
]]></content:encoded></item></channel></rss>