<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Umang Jain on Medium]]></title>
        <description><![CDATA[Stories by Umang Jain on Medium]]></description>
        <link>https://medium.com/@umangjain18211821?source=rss-5ac13d1a41aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nG4Wkr353uLSQXxtLPPY4w.jpeg</url>
            <title>Stories by Umang Jain on Medium</title>
            <link>https://medium.com/@umangjain18211821?source=rss-5ac13d1a41aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:25:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umangjain18211821/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Energy Based Models Explained: Scores, Training and Sampling. With Code!]]></title>
            <link>https://medium.com/@umangjain18211821/energy-based-models-explained-scores-training-and-sampling-with-code-74fbc610f4a7?source=rss-5ac13d1a41aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/74fbc610f4a7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Umang Jain]]></dc:creator>
            <pubDate>Sun, 10 May 2026 19:59:49 GMT</pubDate>
            <atom:updated>2026-05-10T20:27:18.757Z</atom:updated>
            <content:encoded><![CDATA[<p>Most generative models directly learn normalized probability distributions. Energy Based Models take a completely different route.</p><p>Instead of explicitly modeling probabilities, they assign an energy to every configuration of data. Low energy means “more likely.”</p><p>This simple idea turns out to be incredibly powerful — and leads directly to score matching, Langevin dynamics, and even modern diffusion models.</p><p>In this blog, we’ll build EBMs from first principles, train one on the Two Moons dataset, visualize its learned energy landscape, and generate samples using Langevin dynamics.</p><h3>Building Probability Distributions</h3><p>To build a generative model, we need to define a valid probability distribution p(x).</p><p>There are only two conditions for any function to be a valid probability distribution:</p><ul><li>p(x) &gt; 0 → Non-negativity</li><li>Sum (or integral in case of continuous x) of p(x) for all values of x should be 1 → Normalization</li></ul><p>Enforcing non-negativity is easy. For any function f(x) we can take square, exponent, etc. to make it always non-negative. The real challenge arises in the second condition.</p><p>Lets say we have a function f(x) (parameterized by theta parameters) which we want to convert into a valid probability distribution. f can be considered as a neural network, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*dlYJyLjyEq5KwVTfvX9Dtw.png" /></figure><p>The exponent of f(x) ensure that p(x) is always non-negative (satisfy first condition). Now to make p(x) satisfy the second condition, we divide by the integral (or sum) for exponent of f(x) across all x’s. This will help us satisfy the second condition.</p><p>The denominator in the above equation (normalization constant) Z is also called the <strong>partition function.</strong></p><p>The above equation arises under fairly general assumptions in statistical physics (maximum entropy, second law of thermodynamics):</p><ul><li>-f(x) is called the <strong>energy</strong>, hence the name.</li><li>Intuitively, configurations x with low energy (high f(x)) are more likely.</li></ul><p>If we were to plot this “energy”, we would get peaks (region with high energy, less likely) and valleys (region with low energy, more likely). Take a look at the energy contour below for two moons dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*_DMFrcPSiT2H0qpVPeuVJA.png" /></figure><p>In the above image, the blue region is the region of our actual data. The places where the contour lines are closeby are regions with higher energy (lower probability, observe the corners), while the regions where contours lines are far apart are the regions with lower energy (higher probability).</p><p>So now, the only thing to figure out in EBMs is the partition function (Z). But it turns out that finding Z is not easy. Assume you want to calculate Z for the distribution of all the face images. There are many-many face images possible, and including all of those in the integral would blow up due to computation expenses. Computing Z numerically (when no analytic solution is available) scales exponentially in the number of dimensions of x.</p><p>Without being able to sample, or estimate the probability of a point x (in other words, without Z), training a neural network will be hard, since standard losses (like MSE, BCE, etc.) depend on the likelihood of a point.</p><p>So,</p><p>Pros of Energy Based Models:</p><ul><li>extreme flexibility: can use pretty much any function f(x) you want</li></ul><p>Cons of Energy Based Models:</p><ul><li>Sampling from p(x) is hard</li><li>Evaluation and optimizing likelihood p(x) is hard (learning is hard)</li><li>No feature learning (but can add latent variables)</li></ul><h3>Two Places Where the Partition Function Disappears:</h3><p>We have already established that Z is very difficult to calculate. Surprisingly, there are two operations where the partition function vanishes completely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*dlYJyLjyEq5KwVTfvX9Dtw.png" /></figure><ol><li>Comparing two samples:</li></ol><ul><li>If we take two sample, x and y, and try to calculate the ratio of their probability:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*gOfmum80Roi5lMzgv3YbOg.png" /></figure><ul><li>This means that even though we cannot compute exact probabilities, we can still compare which configuration (x or y) is more likely.</li><li>This technique can be used in applications like Anomaly Detection, where we just care about comparing the probability of current event to previous ones, to identify an anomly.</li><li>We will use this result while creating a sampling algorithm for EBMs.</li><li>An even more important simplification appears when we differentiate the log-density with respect to the input.</li></ul><p>2. Differentiation p(x) w.r.t x:</p><ul><li>If we try and differentiate log(p(x)) with respect to x, we get the following:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*Y255zeyOfwTHfGz7GXJPDQ.png" /></figure><ul><li>The last equation comes from the fact that Z does not depend on x (since Z is the sum of p(x) for all possible x), and hence its derivative w.r.t x will be 0</li><li>The variable s(x) which we obtained in the last equation is called as the “<strong>score function</strong>”.</li><li>This single identity becomes the foundation of score matching and diffusion models.</li><li>Upon observing closely, score function is nothing but derivative of our energy. Hence, score function just tells the direction in which we need to move to reach less energy regions (or more energy regions). If we take the above two moons dataset and calculate the score, we get something like below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*ARBixw8V6ZgKwH6R9ERyXg.png" /><figcaption>Visualization of Score Vector Field for Two Moons Dataset</figcaption></figure><pre>score = torch.autograd.grad(<br>    energy.sum(), x<br>)[0]</pre><h3>Training Energy Based Models</h3><p>As observed above, the score function is independent of partition function, and hence we naturally feel to use it in someway to train our EBM.</p><p>The score function is used to define a divergence, known as <strong>Fisher Divergence</strong>, defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*uro7WO4-YGgVR70jAyuCJg.png" /></figure><p>The intuition behind the divergence is that if probability distributions p and q are similar, then their score vector fields (like the one shown in the above image) should also be close to each other at all points, thereby giving the Fisher Divergence.</p><p>If we minimize this Fisher Divergence between p_data and p_theta (p_theta is the distribution by EBM, which is proportional to the exponential of negative energy function), then ideally upon convergence p_theta should be close to p_data. So we can define the minimized Fisher Divergence as our loss function!!</p><p>This is powerful because it allows us to train EBMs without ever computing the partition function or sampling from the model during training.</p><p>After doing some calculus on Fisher Divergence, and substituting p_theta’s form, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*q71F-m-BjZ5KQSQ0QV50XA.png" /></figure><p><em>If you are interested in knowing the full derivation of this loss function from Fisher Divergence, do checkout this </em><a href="https://youtu.be/Nci1Bepcy0g?si=f6f9rkhZwDe-U_uG&amp;t=2240"><em>awesome video</em></a><em> from Stanford CS236 Course.</em></p><p>Some key observations from this loss function:</p><ul><li>The score matching loss depends on the second-derivative of our parameterized function (ie, neural network)</li><li>Since second-derivative w.r.t vector x will result in an Hessian of size (dim_x, dim_x), we can observe that the loss computation will become quadratic in the dimension of x</li><li>Curse of dimensionality will hit, and computing this will not be scalable for higher dimensions (like images, audio, etc.)</li><li>Also note that since the loss depends on second-derivative w.r.t x, if we use activation functions like ReLU in our neural network, we will face issues since the second-derivative of ReLU is 0 almost everywhere. Hence while training with the above loss, we will need to use other activation functions (like GELU) whose second-derivative is non-zero.</li><li>The score matching loss doesn’t require us to sample from the network during training</li></ul><p>Score Matching Algorithm:</p><ul><li>Sample a mini-batch of datapoints (x_1, x_2, …, x_n) from the training data points</li><li>Estimate the score matching loss with the empirical mean</li><li>Stochastic Gradient Descent</li></ul><h3>Sampling from EBMs:</h3><p>We saw that how will we be able to train a generative model using Score Matching Loss, but still one problem remains. Sampling!</p><p>We don’t want to just train a model to produce images, but we would also like to produce some images once the model is trained. That’s the key purpose of training the model.</p><p>But how do we produce images when we can’t compute the likelihood of a point.</p><h4>Langevin Dynamics Sampling:</h4><p>Let’s assume we know a prior distribution n(x) which is easy to sample from (like a Gaussian, Uniform, etc.)</p><p>The intuition behind Langevin Sampling is derived from the fact that from a point, we would like to go towards the direction of the steepest slope of the energy function (similar to gradient descent), and that would give us our sample.</p><p>The Langevin Sampling algorithm is as follows:</p><ul><li>Sample x_0 from n(x)</li><li>At any step t, we update our sample as follows:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_Avuyy-uafUg0d58M--Gg.jpeg" /></figure><p>In the above equation, epsilon is a small constant which controls how much we are moving in direction of the score function, and also controls how much noise is added at each step (think epsilon to be similar to learning rate in gradient descent)</p><p>So in Langevin Sampling, we start with random points, and then at each iteration try to follow the score vector field and go in the direction of the descent. We add some noise in each step, so that all the sampled points dont get stuck in the same minima, and we get more exploratory-ish behaviour. A visual image to understand this can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBZLRKMdBmruX_NJmS3lQg.png" /><figcaption>Langevin Sampling at step 0, 10, 20 and 100</figcaption></figure><h3>Full Experiment Walkthrough:</h3><h4>Dataset:</h4><p>We will use the two moons dataset from sklearn in this experiment.</p><pre>from sklearn.datasets import make_moons<br>import matplotlib.pyplot as plt<br><br>X, y = make_moons(<br>    n_samples=10000,<br>    noise=0.05<br>)<br><br># Shape of X = [10000, 2]<br><br># Visualise the samples<br>plt.scatter(<br>    x=[point[0] for point in X],<br>    y=[point[1] for point in X],<br>    s=10,<br>    alpha = 0.5<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*521A495goxRdWUKwRxh6vA.png" /><figcaption>Visualization of the two moons dataset</figcaption></figure><h4>Model Architecture:</h4><p>Lets define our EBM model.</p><pre>from torch import nn<br><br>class EBM(nn.Module):<br>    def __init__(self, input_dim):<br>        super().__init__()<br>        self.linear_1 = nn.Linear(in_features=input_dim, out_features=64)<br>        self.linear_2 = nn.Linear(in_features=64, out_features=64)<br>        self.linear_3 = nn.Linear(in_features=64, out_features=1)<br>        # self.relu = nn.ReLU() # Cannot use RELU in EBM since the loss requires second-derivative of the model, and second-derivative of relu will almost always become 0<br>        self.gelu = nn.GELU()<br><br>    def forward(self, x):<br>        out_1 = self.gelu(self.linear_1(x))<br>        out_2 = self.gelu(self.linear_2(out_1))<br>        out_3 = self.linear_3(out_2)<br><br>        # This scaler here is our f_theta(x)<br>        return out_3</pre><p>Note that this EBM outputs a scaler value, which will be our negative energy function.</p><h4>Visualizing Initial Energy and Score Fields</h4><p>Since our model is currently randomly initialized, the energy and score-vector fields will also be random.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*WmjrMaUUbYhKsMZeqW8OUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*BxZxN2Y44SMwxnVVFh6VGQ.png" /></figure><h4>Score Matching Loss:</h4><pre>import torch<br><br>def score_matching_loss(x):<br><br>    x.requires_grad_(True)<br>    output = model(x)<br><br>    # Calculate Score<br>    grad_x = torch.autograd.grad(<br>        outputs=output, <br>        inputs=x, <br>        grad_outputs=torch.ones_like(output),<br>        create_graph=True  # Required if you need higher-order derivatives<br>    )[0]<br><br>    score = -grad_x<br><br>    # Calculate Trace of Hessian<br>    trace = torch.zeros(x.shape[0], device=x.device)<br>    dim = x.shape[1]<br>    for i in range(dim):<br>        grad_i = torch.autograd.grad(<br>            outputs=score[:,i].sum(),<br>            inputs=x,<br>            create_graph=True,<br>            retain_graph=True<br>        )[0]<br><br>        trace += grad_i[:,i]<br><br>    # Take norm and combine<br>    score_norm_sq = (score**2).sum(dim=1)<br>    score_loss_part = 0.5 * score_norm_sq<br>    <br>    loss_per_element = score_loss_part + trace<br>    loss = loss_per_element.mean()<br><br>    return output, loss, score, trace</pre><h4>Train:</h4><p>The training function for EBM is pretty straight forward, since the loss itself takes care of everything.</p><pre>from torch.utils.data import DataLoader<br><br>input_dim = 2<br>dataset = torch.tensor(X, dtype=torch.float32)<br>data_loader = DataLoader(dataset, batch_size=64, shuffle=True)<br>model = EBM(input_dim=input_dim)<br>optimizer = torch.optim.Adam(params=model.parameters(), lr=2e-4, weight_decay=1e-4)<br>EPOCHS = 100</pre><pre>loss_history = []<br><br>for i in range(EPOCHS):<br><br>    epoch_loss = 0<br><br>    for batch_idx, data in enumerate(data_loader):<br>        <br>        output, loss, score, trace = score_matching_loss(data)<br>        <br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br><br>        epoch_loss += loss.item()<br><br>    <br>    epoch_loss = epoch_loss/len(data_loader)<br>    loss_history.append(epoch_loss)<br><br>    print(f&quot;Completed epoch: {i+1}/{EPOCHS} | Loss: {epoch_loss}&quot;)</pre><p>The energy contour and score vector field progression can be seen below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvJ1ST8zd4F3-mbyncsAhQ.png" /><figcaption>Energy Contour Progression in Epochs 0, 20, 80 and 100</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2vRyRhcGScILwtYs9hHKFw.png" /><figcaption>Score Vector Field Progression in Epochs 0, 20, 80 and 100</figcaption></figure><p>Observe here that initially we have random energy contour, but as the training progress, valley has started to form near the centre, and the valley is trying to take the shape of the moons.</p><p>Similarly in the Score Vector Fields, the score vectors are initially random, but quickly they start to align themselves to point towards the two moons. The vector near to our data points have low magnitude, while the ones far are bigger (higher magnitude).</p><h4>Langevin Sampling:</h4><p>Now that we have trained our model, lets implement langevin sampling and produce some samples.</p><pre>def langevin_sampling(sample_steps=1000, epislon=0.01, num_samples=1):<br><br>    # Start with a normal random vector<br>    x_i = torch.randn(num_samples,2)<br><br>    trajectory = []<br><br>    # Iteratively update the initial_tensor<br>    for _ in range(sample_steps):<br><br>        # Store trajectory<br>        trajectory.append(x_i.detach().cpu().numpy())<br><br>        # Detach to control computation graph<br>        x_i = x_i.detach()<br>        x_i.requires_grad_(True)<br><br>        # Get score<br>        output_i = model(x_i)<br>        grad_i = torch.autograd.grad(<br>            outputs=output_i,<br>            inputs=x_i,<br>            grad_outputs=torch.ones_like(output_i)<br>        )[0]<br>        score_i = -grad_i<br><br>        # Sample normal random<br>        normal_random = torch.randn_like(x_i)<br><br>        # Calculate the next sample:<br>        x_i = x_i + epislon*score_i + normal_random*((2*epislon)**0.5)<br><br>    trajectory.append(x_i.detach().cpu().numpy())<br><br>    trajectory = np.array(trajectory).reshape(sample_steps+1, -1, 2)<br>    <br>    return x_i.detach().cpu().numpy(), trajectory<br><br># Lets visualize some samples<br>samples, trajectories = langevin_sampling(num_samples=5000, epislon=0.001, sample_steps=2000)<br><br># Plot true moon data<br>plt.scatter(<br>    X[:, 0],<br>    X[:, 1],<br>    s=10,<br>    alpha=0.3,<br>    label=&quot;Real Data&quot;<br>)<br><br># Plot generated samples<br>plt.scatter(<br>    samples[:, 0],<br>    samples[:, 1],<br>    s=10,<br>    label=f&quot;EBM generated samples&quot;<br>)<br><br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*TJjKFRsxW8xMKYXUytboqQ.png" /></figure><p>Let’s also see the trajectory of the generated samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBZLRKMdBmruX_NJmS3lQg.png" /><figcaption>Langevin Sampling at step 0, 10, 20 and 100</figcaption></figure><h3>Connection to Diffusion Models:</h3><p>Energy Based Models are deeply connected to modern diffusion models through the concept of the <strong>score function</strong>.</p><p>Instead of learning exact probabilities, diffusion models learn these score functions at different noise levels.</p><p>During training, noise is gradually added to data samples, and the model learns how to predict directions that move noisy samples back toward the data distribution. This process is called <strong>Denoising Score Matching</strong>.</p><p>During generation, diffusion models start from pure noise and iteratively refine samples using the learned score field. This process is conceptually very similar to Langevin dynamics.</p><p>Both approaches:</p><ul><li>start from random noise</li><li>use score information</li><li>iteratively move toward high-density regions</li></ul><p>This makes diffusion models a powerful large-scale extension of ideas that naturally emerge from Energy Based Models.</p><h3>Final Takeaways:</h3><p>In this blog, we explored how Energy Based Models define probability distributions through energy functions instead of normalized likelihoods.</p><p>Some key takeaways are:</p><ul><li>EBMs model probabilities using energy functions</li><li>The partition function is usually intractable</li><li>Score functions eliminate dependence on the partition function</li><li>Langevin dynamics enables iterative sampling</li><li>Score matching allows training without explicit likelihood computation</li><li>Diffusion models build upon these same score-based ideas</li></ul><p>One of the most elegant ideas behind EBMs is that instead of directly modeling probabilities, we can learn the geometry of the data distribution through score functions.</p><p>These ideas ultimately form the foundation of many modern generative models, including diffusion models.</p><h3>Appendix:</h3><ul><li>The full code of my experimentation can be found here: <a href="https://github.com/Umang1815/learning/blob/main/EBMs/two_moons_ebm.ipynb">https://github.com/Umang1815/learning/blob/main/EBMs/two_moons_ebm.ipynb</a></li><li>Do checkout this awesome playlist from Stanford CS236 if you are interested in the theory of deep generative models: <a href="https://www.youtube.com/playlist?list=PLoROMvodv4rPOWA-omMM6STXaWW4FvJT8">https://www.youtube.com/playlist?list=PLoROMvodv4rPOWA-omMM6STXaWW4FvJT8</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74fbc610f4a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding KL Divergence in VAEs, GANs, and Diffusion Models]]></title>
            <link>https://medium.com/@umangjain18211821/understanding-kl-divergence-in-vaes-gans-and-diffusion-models-e9680d7697f8?source=rss-5ac13d1a41aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9680d7697f8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[generative-model]]></category>
            <dc:creator><![CDATA[Umang Jain]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 16:55:25 GMT</pubDate>
            <atom:updated>2026-04-26T15:46:21.674Z</atom:updated>
            <content:encoded><![CDATA[<p>Why do VAEs produce blurry images, GANs collapse modes, but diffusion models just… work?</p><p>The answer lies in a subtle detail: how we use KL divergence, and more importantly, which direction we use it in.</p><h3>What is KL Divergence?</h3><p>KL Divergence is a information theory concept, which tries to measure distance between two distributions (how “far apart” are two distributions from each other).</p><p>Lets say we have two distributions p(x) and q(x), the KL Divergence between them is defined in two ways:</p><ol><li>How far is p(x) from q(x):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*WTFJjE3DM9jgG4m88Jx8Sg.png" /></figure><p>2. How far is q(x) from p(x):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*aWhMDivK5Yu-c3t3xsHswg.png" /></figure><blockquote>Note: As observed above, KL Divergence is not symmetric, ie, KL(p||q) ≠ KL(q||p)</blockquote><h3>Forward vs Reverse KL</h3><p>Let&#39;s assume p(x) is the actual distribution of data, while q(x) is the distribution which we are trying to learn using some model. The loss function which we are using is KL Divergence.</p><p>As seen above, there are two ways to define KL between these two quantities:</p><ol><li>How far is p(x) from q(x):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*WTFJjE3DM9jgG4m88Jx8Sg.png" /></figure><ul><li>If for a point x, q(x) → 0 while p(x) ≠ 0, then the KL here becomes infinity</li><li>In other words, this heavily penalizes missing regions where the true data has probability mass. q(x) will try to have high value wherever p(x) is non-zero. Hence q(x) will try and cover the whole distribution of p(x)</li><li>This is called a “<strong>mode-covering</strong>” behaviour, and this kind of KL Loss is called as “<strong>Forward KL</strong>”</li><li>Example: Suppose p(x) is mixture of two Gaussians. q(x) is also a Gaussian, whose parameters ( mu, sigma ) are getting learned using this loss.</li><li>As observed above, q(x) will try to cover p(x) as much as possible, but since q(x) is only one Gaussian, we will get very high variance, making q(x) too “spread out” to cover full p(x).</li><li>This will result in features getting “<strong>averaged out</strong>” in q(x).</li><li>Think if we model each pixel in a binary MNIST image in this way, the image which will be formed will be too blurry, since each pixel is getting average between its ideal values.</li></ul><p>2. How far is q(x) from p(x):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*aWhMDivK5Yu-c3t3xsHswg.png" /></figure><ul><li>If for a point x, p(x) → 0 where q(x) ≠ 0, then KL here becomes infinity.</li><li>In other words, our model q(x) will try to find a region with high p(x) and try to stay there itself, since going outside it will result in high KL.</li><li>This is called as “<strong>mode-seeking</strong>” behaviour, and this kind of KL is called as “<strong>Reverse KL</strong>”. Reverse KL does not penalize missing modes, only penalizes assigning probability where p(x) is low.</li><li>Example: In the above example of p(x) being a mixture of two Gaussians and q(x) being a Gaussian with learnable parameters, we will observe that q(x) will go and settle at one of the Gaussians.</li><li>This will result in what is called as “<strong>mode-collapse</strong>” as q(x) settled for one of the optima, due to how the loss function is.</li><li>In case of MNIST, this will result in sharp images since we are very close to one of the Gaussians, but the variety of images will be absent, since q(x) never explored the other Gaussian.</li></ul><p>To build intuition, I ran a simple experiment where I trained a model q(x) to predict a target distribution p(x) using both forward and reverse KL.</p><h3>Understanding Using Code:</h3><h4>Setup:</h4><p>Let p(x) be our ideal distribution and q(x) be the modelled distribution, trying to be similar to p(x)</p><p>For both these experiments, we will use p(x) to be mixture of two gaussians, while q(x) being only a Gaussian with learnable mean and variance.</p><pre>import torch<br>from torch.nn import Module, Parameter<br><br># Create a mixture of gaussians as the target distribution<br><br>mu_1, var_1 = -10, 0.5<br>mu_2, var_2 = 10, 0.5<br><br>def target_distribution(size=2):<br>    std_1 = var_1**0.5<br>    gauss_1 = mu_1 + std_1*torch.randn(size)<br><br>    std_2 = var_2**0.5<br>    gauss_2 = mu_2 + std_2*torch.randn(size)<br><br>    mask = torch.rand(size) &lt; 0.5<br>    samples = torch.where(mask, gauss_1, gauss_2)<br>    return samples<br><br>def model_distribution(mu: float, var: float, size=2):<br>    std = var**0.5<br>    return mu + std * torch.randn(size)<br>    <br># Lets create a pytorch style Module for q(x) so that it can be learned<br>class ModelTargetDistribution(Module):<br>    def __init__(self, mu_init=0.0):<br>        super().__init__()<br><br>        self.mu = Parameter(torch.tensor(mu_init)) # initial mu=mu_init<br>        self.log_sigma = Parameter(torch.tensor(0.0)) # initial sigma=1<br>    <br>    def forward(self):<br>        return self.mu, torch.exp(self.log_sigma)</pre><p>Visualising some samples from both of these distributions:</p><pre>import matplotlib.pyplot as plt<br><br>def plot_sample_from_distributions(mu, std, sample_size):<br>    target_samples = [target_distribution() for x in range(sample_size)]<br>    model_samples = [model_distribution(mu, std**2) for x in range(sample_size)]<br><br>    plt.figure(figsize=(8,6))<br><br>    # Plot target distribution<br>    plt.scatter(<br>        x=[point[0] for point in target_samples],<br>        y=[point[1] for point in target_samples],<br>        c=&#39;red&#39;,<br>        label=&#39;Target&#39;,<br>        s=5,<br>        alpha=0.6<br>    )<br><br>    # Plot model distribution<br>    plt.scatter(<br>        x=[point[0] for point in model_samples],<br>        y=[point[1] for point in model_samples],<br>        c=&#39;blue&#39;,<br>        label=&#39;Model&#39;,<br>        s=5,<br>        alpha=0.6<br>    )<br>    <br>    plt.legend()<br>    plt.title(&quot;Data Distribution for Model vs Target&quot;)<br>    <br># For mu=2 and sigma=1 as model parameters, the sample distribution should be like below:<br>plot_sample_from_distributions(2, 1, 5000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*cTjxALwcOrrKWdaqNcRXFA.png" /></figure><h4>Forward KL:</h4><p>We will now try to model p(x) with q(x) using forward KL loss. As noted above, the forward KL loss is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*WTFJjE3DM9jgG4m88Jx8Sg.png" /></figure><p>Another way to write the above equation is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22n9oWp972hgM2oD6hsbuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ejv5GCHeWpDwLdXNY5LE9g.png" /></figure><p>This means if we sample our training data from p(x), we can make the first term as constant, and the loss will only require the second term. So finally,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7_SJ1REqtHMmvNvXiqcxg.png" /></figure><p>So the steps to train become:</p><ul><li>Sample dataset from p(x)</li><li>For those points, calculate -log q(x).</li><li>Use this loss to update the parameters in q(x)</li><li>Repeat until convergence.</li></ul><blockquote>Note: Since q(x) is a gaussian, log q(x) is a very well-defined quantity. This can be easily derived using basic maths</blockquote><p>Dataset:</p><pre>from torch import Tensor<br>from torch.utils.data import DataLoader<br><br>DATASET_SIZE = 5000<br>BATCH_SIZE = 256<br><br>def sample_from_target_distribution():<br>    sampled_points_in_list = [Tensor(target_distribution()) for x in range(DATASET_SIZE)]<br>    dataloader = DataLoader(sampled_points_in_list, batch_size=BATCH_SIZE, shuffle=True)<br>    return dataloader</pre><p>Loss:</p><pre># Calculate log q(x)<br>def log_model_distribution(samples, mu, logvar):<br>    return -0.5 * ((samples - mu)**2/torch.exp(logvar) + logvar)</pre><p>Defining model and training loop:</p><pre>prediction_model = ModelTargetDistribution()<br>optimizer = Adam(params=prediction_model.parameters(), lr=0.001)<br><br>def forward_kl_training_per_epoch():<br>    # sample from p(x)<br>    data = sample_from_target_distribution()<br>    total_loss_of_sample = []<br>    for sample in data:<br>        mu, sigma = prediction_model()<br>        logvar = torch.log(sigma**2)<br>        # compute log q(x)<br>        # loss = -log q(x)  <br>        loss = torch.mean(-1*log_model_distribution(sample, mu, logvar))<br>        # optimize<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br>        total_loss_of_sample.append(loss.item())<br>    <br>    avg_loss = sum(total_loss_of_sample) / len(data)<br>    print(f&quot;Loss for This Epoch: {avg_loss}&quot;)<br>    return avg_loss</pre><p>Train the model:</p><pre>EPOCHS = 50<br>loss_history = []<br>for epoch in range(EPOCHS):<br>    avg_loss = forward_kl_training_per_epoch()<br>    loss_history.append(avg_loss)</pre><p>Check the final trained values:</p><pre>mu, sigma = prediction_model()<br>print(mu, sigma) # mu=-0.0048, sigma=2.0136</pre><p>Visualizing the trained and actual values:</p><pre>plot_sample_from_distributions(mu.detach(), sigma.detach(), 5000)<br># Mode Covering Behaviour</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*JAmYiwH06AjJo7h7EV0OtQ.png" /></figure><p>Observations:</p><ul><li>As observed above, the model distribution is trying to cover the full target distribution.</li><li>q(x) learned to give probability mass wherever there is non-zero probability mass in p(x). Otherwise, the loss will become very high, penalizing the model</li><li>This is what is called as “<strong>mode-covering</strong>” behaviour, since the model learned to capture everything in a complex distribution p(x) using a simpler distribution q(x).</li><li>Hence the generated samples q(x) are “average” of p(x), resulting in blurry-image (if this loss is used in image generation task)</li></ul><h4>Reverse KL:</h4><p>We will now try to model p(x) with q(x) using reverse KL loss. As noted above, the reverse KL loss is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*aWhMDivK5Yu-c3t3xsHswg.png" /></figure><p>This can also be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qX8VXAuX41hc9X2Ai9hfIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnZk6sBEAde9LpA61sJT7Q.png" /></figure><p>Steps to train:</p><ul><li>Get the current mu and sigma from model</li><li>Use that to create a Gaussian distribution, and take samples from it</li><li>For each of those sample, calculate log q(x) and log p(x)</li><li>Estimate the loss</li><li>Backprop to update mu and sigma from model</li><li>Repeat</li></ul><p>We have already defined log q(x) above. log p(x) is as follows:</p><pre># log p(X) for reverse KL<br>def mixture_log_prob(x):<br><br>    sigma1 = var_1**0.5<br>    sigma2 = var_2**0.5<br><br>    log_pi1 = torch.log(torch.tensor(0.5))<br>    log_pi2 = torch.log(torch.tensor(0.5))<br><br>    log_p1 = log_pi1 + log_model_distribution(x, mu_1, torch.log(torch.tensor(sigma1**2)))<br>    log_p2 = log_pi2 + log_model_distribution(x, mu_2, torch.log(torch.tensor(sigma2**2)))<br><br>    stacked = torch.stack([log_p1, log_p2], dim=0)<br><br>    return torch.logsumexp(stacked, dim=0)</pre><p>Dataset:</p><pre>def sample_from_model_distribution(mu, var, size=DATASET_SIZE):<br>    sampled_points_in_list = [Tensor(model_distribution(mu, var)) for x in range(size)]<br><br>  # Keep everything in one batch for ease<br>    dataloader = DataLoader(sampled_points_in_list, batch_size=len(sampled_points_in_list), shuffle=True)<br><br>    return dataloader</pre><p>Training loop:</p><pre>reverse_prediction_model = ModelTargetDistribution(mu_init=0.0)<br>optimizer = Adam(params=reverse_prediction_model.parameters(), lr=0.01)<br><br>def reverse_kl_training_per_epoch(step_per_epoch = 100):<br>    <br>    epoch_loss = 0<br>    for step in range(step_per_epoch):<br>        <br>        # Get current mu and sigma<br>        mu, sigma = reverse_prediction_model()<br>        # Sample from q(x)<br>        data = sample_from_model_distribution(mu, sigma**2, size=1024)<br>        sample = next(iter(data))<br><br>    # Calculate log p(x) and log q(x) for those samples<br>        log_q = log_model_distribution(sample, mu, torch.log(torch.tensor(sigma**2)))<br>        log_p = mixture_log_prob(sample)<br><br>    # Calculate the loss<br>        loss = (log_q - log_p).mean()     <br>           <br>        # optimize<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br><br>        epoch_loss += loss.item()<br><br>    print(mu.item(), sigma.item())<br>    print(f&quot;Loss for This Epoch: {epoch_loss / step_per_epoch}&quot;)<br><br>    return epoch_loss / step_per_epoch</pre><p>Train:</p><pre>EPOCHS = 50<br>reverse_loss_history = []<br>for epoch in range(EPOCHS):<br>    avg_loss = reverse_kl_training_per_epoch()<br>    reverse_loss_history.append(avg_loss)</pre><p>Visualize:</p><pre>mu, sigma = reverse_prediction_model()<br>print(mu, sigma) # mu=9.9995, sigma=0.707<br>plot_sample_from_distributions(mu.detach(), sigma.detach(), 5000)<br># Mode Seeking Behaviour</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*i5I0T3cOuPrIf6oxrSVUrg.png" /></figure><p>Observation:</p><ul><li>As we can see here, our model converged to a mean of ~10 with variance ~0.5</li><li>If you note above, our actual target distribution is a mixture of two gaussians, one with mean 10 and variance 0.5, and other with mean -10 and variance 0.5</li><li>So our model settled on one of the distributions of the target, thereby completely ignoring the other distribution</li><li>Hence the samples from our model will be of good quality, since they are very close to the actual p(x), but the range of samples will not be complete since we will only get contribution from one gaussian of p(x)</li><li>This is called as “<strong>mode seeking</strong>” behaviour.</li></ul><h3>Problems in Generative Modelling:</h3><p>Forward KL is used in generative models like Variational Autoencoders (VAE). As observed above, forward KL rewards covering behaviour, VAE’s latent spaces is very smooth, and hence the images become blurry.</p><p>Reverse KL is used in generative models like Generative Adversarial Networks (GANs). Since Reverse KL rewards a stable non-zero distribution, GANs produce very clear images, but suffer with what we call “mode-collapse”, ie, they have a hard time generating something new, something which is not similar to the training set, since they have settled on a good p(x) which is the training data itself.</p><blockquote>Note: GANs do not explicitly optimize KL, but their training dynamics behave similar to reverse KL, leading to mode-seeking behavior.</blockquote><p>What we want is:</p><ul><li>Fully cover the input distribution (diversity)</li><li>Produce sharp samples (quality)</li></ul><p>But KL gives tradeoff:</p><ul><li>Forward KL → coverage</li><li>Reverse KL → sharpness</li></ul><p>The root cause here is: We are trying to fit a simple model to a complex multi-modal distribution in one step</p><h3>How Diffusion Solves This Problem?</h3><p>Diffusion doesn’t try to model the whole complex distribution in one-go. Instead, it breaks the problem down into many simple problems.</p><p>Diffusion Intuition:</p><ul><li>Start with pure noise.</li><li>At each step, diffusion models learn to reverse a small Gaussian corruption process. This reduces the problem to learning simple, near-Gaussian transitions instead of a complex multi-modal distribution.</li><li>Repeat this step for a many times.</li></ul><p>Instead of learning one-hard KL, diffusion learns many easy Gaussians using KLs. Since we are trying to learn a simple Gaussian, the problem of mode-collapse vanishes.</p><p>And since we are starting from pure noise every time, we naturally cover whole possible space, thereby solving the coverage problem</p><p>Diffusion also gives high-quality images, since we are making small improvements in each denoise step, allowing us to make finer improvements with each step, thereby improving the image quality.</p><p><strong>To summarize:</strong></p><p>Diffusion models succeed because they avoid fitting a complex multi-modal distribution in one step. Instead, they learn many small, simple distributions where KL behaves well.</p><h3>A Deeper Insight: Why KL Fails for Multi-Modal Distributions</h3><p>The behaviour we observed (mode-covering vs mode-seeking) is not just a property of KL divergence, but a consequence of how the expectations are computed.</p><p>In both cases, KL is defined as an expectation:</p><p>Forward KL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ejv5GCHeWpDwLdXNY5LE9g.png" /></figure><p>Reverse KL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnZk6sBEAde9LpA61sJT7Q.png" /></figure><p>The key difference lies in where we sample from.</p><h4>Forward KL: “Data-Driven” Learning</h4><p>In forward KL, samples come from the true distribution p(x) itself.</p><p>This means every region where data exists will be seen during training. So if the model misses any mode, it gets penalized heavily.</p><p>This leads to <strong>mode covering</strong>, but also forces the model to spread probability mass, often resulting in <strong>averaging effects (blur)</strong>.</p><h4>Reverse KL: “Model-Driven” learning</h4><p>In reverse KL, samples come from the model q(x).</p><p>This means, the model only learns from regions it already believes are likely. If the model ignores a mode early in training, it will <strong>never see it again</strong>. There is no penalty for missing modes, only for assigning probability to unlikely regions.</p><p>This leads to <strong>mode seeking</strong>, where the model collapses to a single high-density region.</p><h4>The Deeper Problem</h4><p>Both divergences struggle because they try to match a <strong>multi-modal distribution using a simpler distribution in one step</strong>.</p><p>This creates an inherent conflict:</p><ul><li>Covering all modes requires spreading probability mass</li><li>Producing sharp samples requires concentrating probability mass</li></ul><p>KL divergence forces the model to choose between these two.</p><h4>Why Diffusion Avoids This</h4><p>Diffusion models avoid this issue entirely by <strong>changing the problem</strong>.</p><p>Instead of matching a complex multi-modal distribution directly, they learn a sequence of simple, near-Gaussian transitions.</p><p>Each step is easy to learn, unimodal and well-behaved under KL</p><p>This removes the need to choose between mode covering and mode seeking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9680d7697f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>