<?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 Matheus Ramos Parracho on Medium]]></title>
        <description><![CDATA[Stories by Matheus Ramos Parracho on Medium]]></description>
        <link>https://medium.com/@mathparracho?source=rss-a26c71ab99ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ge91Dky33nLciuIK6NWPNw.jpeg</url>
            <title>Stories by Matheus Ramos Parracho on Medium</title>
            <link>https://medium.com/@mathparracho?source=rss-a26c71ab99ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:55:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mathparracho/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[Volumetric Rendering with NeRF: Mathematical Foundations]]></title>
            <link>https://medium.com/@mathparracho/volumetric-rendering-with-nerf-mathematical-foundations-d7b170acbd1b?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7b170acbd1b</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 02:58:23 GMT</pubDate>
            <atom:updated>2026-03-17T03:44:58.303Z</atom:updated>
            <content:encoded><![CDATA[<p>In 2020, a paper named “NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis” revolutionized the way we define volumetric images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*zn7cXKU9HxgpMhHsADbyHA.png" /><figcaption>Overall Pipeline of NeRF. Source: Official paper</figcaption></figure><p>Instead of explicitly storing surfaces, meshes, or voxels, it learns a continuous representation of the world directly inside the weights of a neural network. That is what makes this idea very elegant and powerful in my opinion.</p><p>In 2023, things have changed <strong>again </strong>with the use of Gaussian Splatting for describing 3D images (will be the focus of another future article).</p><p>In this article, we are going to focus on the mathematical foundations of NeRF.</p><h3>Some Ways of Representing 3D images</h3><p>There are several ways to represent 3D scenes, but the most common are:</p><ul><li><strong>Voxel Grids</strong>: simply 3D pixels. The idea is to discretize space into a regular 3D grid where each voxel stores information such as occupancy, density, or intensity. It is very intuitive but <strong>very </strong>memory intensive. It is explicit and volumetric.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*9EBWQfcKLfyKzoLzSE2mGw.png" /><figcaption>3D grid of voxels. Source: <a href="https://www.researchgate.net/figure/D-binary-voxel-grid-left-and-TDF-encoded-3D-voxel-grid-right-Smaller-and-darker_fig4_339059333">https://www.researchgate.net/figure/D-binary-voxel-grid-left-and-TDF-encoded-3D-voxel-grid-right-Smaller-and-darker_fig4_339059333</a></figcaption></figure><ul><li><strong>Point clouds</strong>: The idea here is to represent a scene with discrete points in 3D space. It is common to obtain data from LiDAR, depth sensors, or multi-view reconstruction. They are lightweight but lack explicit surface connectivity (we don’t have explicit connection between the points). It is explicit and sparse.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SA-yds-MTTu_xt2_" /><figcaption>Source: <a href="https://www.bricsys.com/de-at/blog/point-clouds-6-scan-to-bim?srsltid=AfmBOoofOWRYaPzT5JPjtMt4JpSTi_R0xsKTKersQJ48_aHBxXGlrHZi">https://www.bricsys.com/de-at/blog/point-clouds-6-scan-to-bim?srsltid=AfmBOoofOWRYaPzT5JPjtMt4JpSTi_R0xsKTKersQJ48_aHBxXGlrHZi</a></figcaption></figure><ul><li><strong>Meshes: </strong>One of the most common ways of representing 3D images in any computer graphics software. It describes surfaces using vertices, edges, and faces (typically triangles). Meshes are efficient for rendering but require reliable surface reconstruction. It is explicit and discrete.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*KOLoG_ubKJQNd4X1J9ZnzQ.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Polygon_mesh#/media/File:Dolphin_triangle_mesh.png">https://en.wikipedia.org/wiki/Polygon_mesh#/media/File:Dolphin_triangle_mesh.png</a></figcaption></figure><ul><li><strong>Implicit representations: </strong>the geometry here is defined as the zero-level set of a continuous function (e.g., signed distance functions or radiance fields). <em>Here is where we are going to work on this article.</em></li></ul><h3>The NeRF Idea</h3><p>The core idea of NeRF is: using only a few 2D images of our scene, how can we interpolate and generate a whole 3D scene using some implicit representation?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*bx2IVSl6QSIILxyb58T4IQ.png" /><figcaption>Using different 2D images of our scene, how can we interpolate between them? Source: <a href="https://theaisummer.com/nerf/">https://theaisummer.com/nerf/</a></figcaption></figure><p>The NeRF model uses a neural network to approximate a continuous function that maps via supervised learning these features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*JmSiwz6rKLOXP_h2lYI0TQ.png" /></figure><ul><li><strong>x: (x,y,z)</strong> the continuous position in absolute space;</li><li><strong>d: (θ,ϕ)</strong> the direction of vision;</li><li><strong>σ</strong>: volumetric density;</li><li><strong>c</strong>: (r,g,b) RGB color.</li></ul><p>But… with only some 2D images, how can we extract these features to explicitly train our neural network? And what do these features actually mean?</p><p>Now that enters a lot of computer vision theory. Let’s go step by step and understand how we can extract these features.</p><h3>The Pinhole Model: Representing Camera in Space</h3><p>The pinhole model is the simplest model used to describe the mathematical relationship of the projection of points in 3D space onto an image plane.</p><p>In this model, light rays emitted from 3D points pass through an idealized pinhole (the camera center) and intersect an image plane, producing a 2D projection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jG9yr-HQxacGdnJ1.jpg" /><figcaption>Source: <a href="https://hedivision.github.io/Pinhole.html">https://hedivision.github.io/Pinhole.html</a></figcaption></figure><p>In this model, we divide the projection into 2 systems:</p><ol><li>The world coordinate (global): A fixed reference frame that describes the absolute position of points in the environment.</li><li>Camera Coordinate System (local): A coordinate frame attached to the camera, with the origin at the camera center and axes aligned with the camera’s orientation.</li></ol><p><strong>The Camera Extrinsics</strong></p><p>The transformation between these systems is handled by the camera extrinsics, which consist of a rotation matrix <strong>R</strong> and a translation vector <strong>t</strong>. These parameters map points from the world coordinate system into the camera coordinate system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*7bwAVSNEowV3ncrh2pGNrQ.png" /></figure><p><strong>The Camera Intrinsics</strong></p><p>This part answers the question, “How does the camera transform 3D coordinates into 2D pixels?”</p><p>While the extrinsics describe where the camera is and how it is oriented, the camera intrinsics explain how the camera projects 3D points onto the 2D image plane.</p><p>This projection is modeled by the intrinsic matrix K, defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*lL5KiwRGa5DPyjfG4adrvg.png" /></figure><ul><li>fx​ and fy​ represent the focal lengths of the camera along the horizontal and vertical axes (expressed in pixels)</li><li>cx​ and cy correspond to the coordinates of the principal point, typically located near the center of the image.</li></ul><p><strong>The Algorithm Pipeline</strong></p><p>So, what exactly is the step-by-step?</p><ol><li><strong><em>World Coordinates -&gt; Camera Coordinates (Extrinsics):</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*CcCIj7FAg2u-nCOITQMeCw.png" /></figure><p>And apply the extrinsic transformation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*udVWof8ZJJiqtCv_7rgryQ.png" /></figure><p><strong><em>2. Perspective projection</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*eQ1LMcJnm4gGGPoxyi1eWg.png" /></figure><p>to get the homogeneous</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*5HAOH_xPkSD3Bps0hokwxA.png" /></figure><p><strong><em>3. Normalized projection -&gt; Pixel (Intrinsics)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*HKeCl_CAwYY4zcmQEjMdlg.png" /></figure><p>Where (u,v) are the pixel coordinates.</p><p>Okay, so the Pinhole Model tells us how the real-world scenario is mapped into a 2D plane (image). However, this idea is not invertible. This means that the model tells us how we convert 3D to 2D but not how we can undo this operation: estimate the 3D using 2D (and this is what we need for NeRF).</p><p>For this, we are going to use the <strong><em>Structure-From-Motion Algorithm</em></strong><em> </em>(I am not going to focus on this article) that makes this estimation for us. These algorithms and implementations can be found in a “framework” named <strong><em>COLMAP.</em></strong></p><h3>The 5D Input</h3><p>This SFM algorithm converts the several pictures into camera pose extrinsics (matrices <strong>R </strong>and <strong>t</strong>) and the intrinsic matrix <strong>K. </strong>These parameters are estimated per image (camera) and are shared across all pixels of that image.</p><p><strong><em>1. Pixel to 3D Ray (Ray Casting)</em></strong></p><p>Given the intrinsic matrix K and the camera extrinsics (R,t), each pixel (u,v) in the image can be associated with a unique 3D ray originating from the camera center and passing through the image plane.</p><p>First, the pixel coordinates are mapped to normalized camera coordinates by inverting the intrinsic transformation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*5RX1D1ZOtv5wHVtDUvh2mg.png" /></figure><p>making us with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*vTj5AE_hrts1TAhgl1e_bQ.png" /></figure><p>This point lies on the normalized image plane at z=1 in the camera coordinate system.</p><p>In the camera reference frame, the ray is defined by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*5NcB1ZLK4tCD4YTTRKFdjg.png" /></figure><p>with the direction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*Zj-A1nYQilrPRbYA1Dmd-w.png" /></figure><p>To express the ray in the world coordinate system, both its origin and direction are transformed using the camera extrinsics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*gExFj2sAff7OJb-yDpYYCw.png" /></figure><p>Finally, we get the resulting 3D ray associated with the pixel (u,v):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*0niuihc5h1i9UE5IAkm8Gw.png" /></figure><p>Each value of <strong><em>t</em></strong> corresponds to a point in 3D space along the ray.</p><p><strong>2. Sampling points along the ray</strong></p><p>To render the pixel color, NeRF does not evaluate a single point along the ray. Instead, it samples multiple points within a predefined depth interval:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*_Nlse7hctuFbftoXtyvZ9w.png" /></figure><p>Generating a set of samples along the ray:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*vae3ALKAz8EgkCCQtnUmQQ.png" /></figure><p>Now each point can be represented as</p><ul><li>its 3D position <strong>xi ​= (x,y,z)</strong></li></ul><p>And changing to spherical coordinates (azimuth and polar angles):</p><ul><li><strong>d ​= (θ,ϕ)</strong></li></ul><p>and together, they form our 5D input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*zhga04nOr51pWxLCLkeorg.png" /></figure><h3>The 4D Output</h3><p>For each sampled point, the network predicts two physical quantities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*DmwB3-DM5fIqAYYYJ6S3Vg.png" /></figure><p>where</p><ul><li><strong>σ</strong> ∈ R+ represents the volumetric density at location <strong>x</strong></li><li><strong>c</strong> ∈ R3 corresponds to the emitted RGB color in the viewing direction <strong>d</strong>.</li></ul><p>However, these quantities are not directly supervised during training.</p><p>Instead of comparing the predicted density and color values themselves, they are used to synthesize a 2D image through the volumetric rendering process. The rendered image is then compared against the corresponding ground-truth image, and the discrepancy between the two serves as the supervisory signal for learning.</p><blockquote>And this is the key and what makes the formulation so beautiful in my opinion.</blockquote><ol><li><strong>Volumetric Rendering</strong></li></ol><p>The color of a pixel is defined as the continuous integration of radiance along the ray, weighted by the accumulated transmittance of the medium:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*u_C3mB4zs7mz4siXtdyNmA.png" /></figure><p>where</p><ul><li>σ(r(t)) is the volume density at point r(t)</li><li>c(r(t),d) is the emitted color in direction d</li><li>T(t) is the <strong>transmittance</strong>, representing the probability that the ray reaches depth <strong><em>t</em></strong> without being absorbed.</li></ul><p>And the transmittance is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*tkKZbsV6sECQt1q-HkAM2w.png" /></figure><p>We can view this model as</p><ul><li>The transmittance encodes the light absorption along the ray</li><li>Regions with high density contribute more strongly and occlude farther points</li><li>The formulation naturally enforces visibility and depth ordering without explicit surface geometry</li></ul><p>Discretizing this formulation, the continuous integral is approximated using a finite number of samples​ along the ray. Each sample corresponds to a point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*nwJE3XDNrPUp6Qq6e0a8Mw.png" /></figure><p>and using numerical quadrature, the integral becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*ZE_yLacxsYIAJTeEjPaAQw.png" /></figure><p>Perfect, now this color value is going to be compared with the ground truth!</p><h3>The Supervised Learning</h3><p>Now we have everything for our supervised learning!</p><p>For each training iteration, a set of camera rays is sampled from the available views. Given a ray r corresponding to a pixel (u,v), the network predicts its color C^(r) through volumetric rendering. This prediction is then compared to the observed pixel color C∗(r).</p><p>Now, we simply use the MSE loss to compare both:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*CVHAQQ7psNElspyHILnByg.png" /></figure><p>where <strong><em>R </em></strong>denotes the set of sampled rays in the current minibatch.</p><p>It is interesting to notice that the loss is not applied to the 3D geometry directly but only to the final rendered pixel colors. And even so, the network is able to learn two important features:</p><ul><li>accurate scene geometry (encoded in σ(x))</li><li>view-dependent appearance (encoded in c(x,d))</li></ul><p>And we can backpropagate because the rendering equation is fully differentiable.</p><h3>Implementing in Pytorch</h3><p>In this section, we are going to implement NeRF using the concepts studied</p><p><strong>The 5D Inputs</strong></p><p>Here, we are going to use the official dataset used in the original paper. The download link can be found here: “<a href="https://drive.google.com/drive/folders/1cK3UDIJqKAAm7zyrxRYVFJ0BRMgrwhh4">NeRF_Data — Google Drive</a>” or simply on Kaggle “<a href="https://www.kaggle.com/datasets/sauravmaheshkar/nerf-dataset">NeRF Dataset</a>”.</p><p>For each image in the dataset, we have the respective frame matrices. For example, let’s see for the image r_0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*9YG0IWhZFB5MBLM_ng8Epg.png" /><figcaption>Image r_0 in the lego dataset</figcaption></figure><p>its camera definitions:</p><pre>{<br>    &quot;camera_angle_x&quot;: 0.6911112070083618,<br>    &quot;frames&quot;: [<br>        {<br>            &quot;file_path&quot;: &quot;./train/r_0&quot;,<br>            &quot;rotation&quot;: 0.012566370614359171,<br>            &quot;transform_matrix&quot;: [<br>                [<br>                    -0.9999021887779236,<br>                    0.004192245192825794,<br>                    -0.013345719315111637,<br>                    -0.05379832163453102<br>                ],<br>                [<br>                    -0.013988681137561798,<br>                    -0.2996590733528137,<br>                    0.95394366979599,<br>                    3.845470428466797<br>                ],<br>                [<br>                    -4.656612873077393e-10,<br>                    0.9540371894836426,<br>                    0.29968830943107605,<br>                    1.2080823183059692<br>                ],<br>                [<br>                    0.0,<br>                    0.0,<br>                    0.0,<br>                    1.0<br>                ]<br>            ]<br>        },</pre><p>camera_angle_x defines the FOV (it is the same for all images):</p><pre>&quot;camera_angle_x&quot;: 0.6911112070083618</pre><p>and it is used to calculate the intrinsic matrix of the camera:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*R1sX9ptu8E1RxsHz4GgCdA.png" /></figure><p>And naturally, we assume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*K9CQjMS2WBFqSkmwH9fMQw.png" /></figure><p>For each frame, we have the transform matrix: the 4x4 matrix that describes the camera pose (also called “Camera-to-World matrix (c2w)”)</p><pre>&quot;transform_matrix&quot;: [<br>  [-0.9999,  0.0041, -0.0133, -0.0538],<br>  [-0.0139, -0.2996,  0.9539,  3.8454],<br>  [ 0.0000,  0.9540,  0.2996,  1.2080],<br>  [ 0.0,     0.0,     0.0,     1.0]<br>]</pre><p>And it is defined in this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*T-NDCbR6wjEmEEMow9wIdQ.png" /></figure><p>The rotation matrix (R) is</p><pre>[-0.9999,  0.0041, -0.0133]<br>[-0.0139, -0.2996,  0.9539]<br>[ 0.0000,  0.9540,  0.2996]</pre><p>And the translation</p><pre>[-0.0538]<br>[ 3.8454]<br>[ 1.2080]</pre><p>that represents the camera’s position in the 3D world:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*HQruacrhGJVRelNSMfYSNQ.png" /></figure><p>Let’s start step by step:</p><ol><li><strong>Load the images, pose (transform_matrix or c2w), and focal (formula).</strong></li></ol><pre>def load_blender_split(data_dir, split): # images were generated in Blender<br><br>    meta_path = Path(data_dir) / f&quot;transforms_{split}.json&quot;<br>    with open(meta_path, &quot;r&quot;) as f:<br>        meta = json.load(f)<br><br>    frames = meta[&quot;frames&quot;]<br>    imgs, poses = [], []<br>    for fr in frames:<br>        fp = Path(data_dir) / (fr[&quot;file_path&quot;] + &quot;.png&quot;)<br>        img = imageio.imread(fp)<br>        img = (img / 255.0).astype(np.float32)<br>        imgs.append(img)<br>        poses.append(np.array(fr[&quot;transform_matrix&quot;], dtype=np.float32))<br><br>    imgs = np.stack(imgs, axis=0)<br>    poses = np.stack(poses, axis=0)<br><br>    H, W = imgs.shape[1], imgs.shape[2]<br>    camera_angle_x = float(meta[&quot;camera_angle_x&quot;])<br>    focal = 0.5 * W / np.tan(0.5 * camera_angle_x)<br>    return imgs, poses, H, W, focal #everything we need to build</pre><p>With this we can create the intrinsic matrix of the camera:</p><pre>K = torch.tensor([[focal, 0.0, 0.5 * W],<br>                  [0.0, focal, 0.5 * H],<br>                  [0.0, 0.0, 1.0]], dtype=torch.float32, device=device)<br># with K and c2w, we transform pixels into 3D rays</pre><p>Now that we have K and c2w, we should:</p><p><strong>2. Choose a random image and random pixels to generate 3D rays.</strong></p><pre>img_idx = torch.randint(0, self.images.shape[0], (1,)).item()<br>rgba = self.images[img_idx]<br>c2w = self.poses[img_idx]<br><br>ys = torch.randint(0, self.H, (self.n_rays,))<br>xs = torch.randint(0, self.W, (self.n_rays,))</pre><p>and then generate the 3D rays:</p><pre>dirs = torch.stack([<br>    (xs.float() - K[0, 2]) / K[0, 0],<br>    -(ys.float() - K[1, 2]) / K[1, 1],<br>    -torch.ones_like(xs, dtype=torch.float32)<br>], dim=-1)  # (N,3)<br><br>R = c2w[:3, :3]<br>t = c2w[:3, 3]<br>rays_d = (dirs[:, None, :] @ R.T[None, :, :]).squeeze(1)<br>rays_o = t.expand_as(rays_d)</pre><p><strong>3. Get the ground-truth RGB values of the sampled pixels</strong></p><pre>rgb = gt_rgba[..., :3]<br>a = gt_rgba[..., 3:4]<br>gt_rgb = rgb * a + (1.0 - a) * 1.0   #white background</pre><p><strong>4. Sample 3D points along each ray</strong></p><pre>#now that we have the rays, <br># we sample several 3D points along each one, between near and far<br><br>def sample_stratified(rays_o, rays_d, near, far, n_samples, perturb=True):<br>    device = rays_o.device<br>    t_vals = torch.linspace(0.0, 1.0, n_samples, device=device)<br>    z_vals = near * (1.0 - t_vals) + far * t_vals<br>    z_vals = z_vals.expand(rays_o.shape[0], n_samples)<br><br>    if perturb:<br>        mids = 0.5 * (z_vals[:, 1:] + z_vals[:, :-1])<br>        upper = torch.cat([mids, z_vals[:, -1:]], dim=-1)<br>        lower = torch.cat([z_vals[:, :1], mids], dim=-1)<br>        t_rand = torch.rand_like(z_vals)<br>        z_vals = lower + (upper - lower) * t_rand<br><br>    pts = rays_o[:, None, :] + rays_d[:, None, :] * z_vals[..., None]<br>    return pts, z_vals</pre><p>And inside training:</p><pre>pts, z_vals = sample_stratified(rays_o, rays_d, near, far, n_samples, perturb=True)</pre><p><strong>6. Apply positional encoding to points and directions</strong></p><p>Using the same idea as the Transformer, NeRF also uses sine positional encoding:</p><pre>class PositionalEncoding(nn.Module):<br>    def __init__(self, num_freqs: int, include_input: bool = True, log_sampling: bool = True):<br>        super().__init__()<br>        self.num_freqs = num_freqs<br>        self.include_input = include_input<br><br>        if log_sampling:<br>            self.freq_bands = 2.0 ** torch.linspace(0.0, num_freqs - 1, num_freqs)<br>        else:<br>            self.freq_bands = torch.linspace(1.0, 2.0 ** (num_freqs - 1), num_freqs)<br><br>    def forward(self, x):<br>        out = []<br>        if self.include_input:<br>            out.append(x)<br>        for f in self.freq_bands.to(x.device):<br>            out.append(torch.sin(f * x))<br>            out.append(torch.cos(f * x))<br>        return torch.cat(out, dim=-1)</pre><p><strong>7. Building the MLP</strong></p><p>Here, the idea is to create a MLP in this format. Using (x,d) as our inputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*af22W6turIMGr7mv7XWdAg.png" /><figcaption>Source: Author</figcaption></figure><p>Where we have a skip connection after layer 4, and two different sections for the output: one for <strong>σ</strong>, other for <strong>rgb</strong></p><pre>class NeRF(nn.Module):<br>    def __init__(self, d_in=3, d_dir=3, n_hidden=256):<br>        super().__init__()<br>        self.n_hidden = n_hidden<br><br>        self.pts_linears = nn.ModuleList([nn.Linear(d_in, n_hidden)] + \<br>                                        [nn.Linear(n_hidden, n_hidden) for _ in range(7)])<br><br>        self.skip_layer = 4<br>        self.pts_linears[self.skip_layer] = nn.Linear(n_hidden + d_in, n_hidden)<br><br>        self.sigma_linear = nn.Linear(n_hidden, 1)<br>        self.feature_linear = nn.Linear(n_hidden, n_hidden)<br><br>        self.dir_linear = nn.Linear(n_hidden + d_dir, n_hidden // 2)<br>        self.rgb_linear = nn.Linear(n_hidden // 2, 3)<br><br>    def forward(self, x, d):<br>        h = x<br>        for i, layer in enumerate(self.pts_linears):<br>            if i == self.skip_layer:<br>                h = torch.cat([h, x], dim=-1)<br>            h = F.relu(layer(h))<br><br>        sigma = F.relu(self.sigma_linear(h))<br>        feat = self.feature_linear(h)<br><br>        h_dir = torch.cat([feat, d], dim=-1)<br>        h_dir = F.relu(self.dir_linear(h_dir))<br>        rgb = torch.sigmoid(self.rgb_linear(h_dir))<br><br>        return sigma, rgb</pre><p>And with that we already have everyting we need to train using the usual Pytorch training pipeline.</p><p>If you want to check the detailed full code (to be updated): <a href="https://www.kaggle.com/code/matheusparracho/nerf-pytorch">https://www.kaggle.com/code/matheusparracho/nerf-pytorch</a></p><p>Observing the rendering after some iterations, we can clearly see an advance regarding the details from each ray:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*upPYrUqGsHIsRmAPSIUT4Q.png" /><figcaption>2k iterations on the left X 20k iterations on the right. Source: author</figcaption></figure><p>And, in the end, we can create images from new angles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*shsgzdWcPm4FeFZZ-EhOtw.png" /><figcaption>Some viewing examples. Source: Author</figcaption></figure><h3>Conclusion</h3><p>NeRF can look kind scary at first, especially because it brings together geometry, camera modeling, neural networks, and volumetric rendering all at once.</p><p>But once we break it down step by step, the idea becomes intuitive: start from images and camera poses, turn pixels into rays, sample points in 3D space, let a neural network predict color and density, and then combine everything into a final rendered image.</p><p>Instead of explicitly storing surfaces, meshes, or voxels, it learns a continuous representation of the world directly inside the weights of a neural network. That shift in perspective is what makes the method feel so elegant and powerful.</p><p>Thank you for reading! Feel free to comment. See you next time!</p><h3>References</h3><p><a href="https://arxiv.org/pdf/2003.08934">https://arxiv.org/pdf/2003.08934</a></p><p><a href="https://hedivision.github.io/Pinhole.html">https://hedivision.github.io/Pinhole.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7b170acbd1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spiking Neural Networks: Towards Biologically Plausible Brain Models]]></title>
            <link>https://medium.com/@mathparracho/spiking-neural-networks-towards-biologically-plausible-brain-models-113cf2262204?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/113cf2262204</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[neural-science]]></category>
            <category><![CDATA[spiking-neural-network]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 05:17:34 GMT</pubDate>
            <atom:updated>2025-12-28T04:32:37.255Z</atom:updated>
            <content:encoded><![CDATA[<p>Neural networks are extremely powerful function approximators, and their design takes inspiration from the human brain.</p><p>But can we use these systems to genuinely capture how our brain operates? The way we create regression, or generative models… Is it <strong><em>biologically plausible</em></strong>? Can we recreate the behavior of our understanding using these structures? In a nutshell, can we model our brain via common artificial neural networks?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*nFnQvw5U0zLZPtULkxXDrg.png" /><figcaption>LIF model: one mathematical description of the conduction of electrical signals in neurons. Source: <a href="https://www.researchgate.net/publication/339574089_Enabling_Spike-Based_Backpropagation_for_Training_Deep_Neural_Network_Architectures">https://www.researchgate.net/publication/339574089_Enabling_Spike-Based_Backpropagation_for_Training_Deep_Neural_Network_Architectures</a></figcaption></figure><p>These are some of the questions we are going to discuss in this article! We are going to understand the bridge that connects neural networks (the way we usually do in computational modeling) with some of the neural science concepts.</p><blockquote>Keep in mind that I am not a neuroscientist. The goal of this article is study how the brain process the information and try to model the basic principles using neural networks. Also, this article is just a simple introduction and exploration!</blockquote><p>And, as usual, all code from this article is on this Kaggle link: <a href="https://www.kaggle.com/code/matheusparracho/spiking-neural-networks-snns">https://www.kaggle.com/code/matheusparracho/spiking-neural-networks-snns</a></p><p>Let’s start!</p><h3>Some characteristics of our brain</h3><p>Neural networks are inspired by the way our brain communicates, so you may expect that they work similarly. Indeed, it is true! However, some constraints are important to notice:</p><ol><li><strong>Spikes</strong>: Continuous X Discrete</li></ol><p>The brain does not work using continuous values, just as we usually do in artificial neural networks. Instead, the neuron is activated by the membrane electric potential. When its membrane potential (approx. 100 mV) reaches a threshold, it fires a <strong>spike</strong> (or <em>action potential</em>).</p><p>Each spike is a discrete event in time (a pulse with a duration of approximately 1 ms).</p><p><strong>2. Sparsity</strong></p><p>Most of the time, our neurons are at rest. This means the majority of activations are 0. Most of the time, our neuron activations are just like that:<em> [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1] (just for demonstration).</em></p><p><strong>3. Static Suppression (Event-Driven Processing)</strong></p><p>The sensory system is more responsive to changes than to static input. So, instead of storing 30 frames per second in a camera, for instance, the brain only stores “changes” in scenes.</p><p>These 3 characteristics have the name of “<em>The Three S’s.</em>”</p><p>Fundamentally, applying these constraints makes our structures more biologically plausible in comparison to vanilla ANNs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*TJ7fgKMH9yn6Sek9.png" /><figcaption>Comparison of the architectures&#39; biological “spectrum”. Source: <a href="https://www.sciencedirect.com/science/article/abs/pii/S0893608020300563?via%3Dihub">https://www.sciencedirect.com/science/article/abs/pii/S0893608020300563?via%3Dihub</a></figcaption></figure><p>With these S’s in mind, we have to carefully study how we are going to adapt from the “practical” and “common” way of modeling neural networks to the closer biological spiking networks:</p><ol><li><strong>Input Encoding</strong></li><li><strong>Output Decoding</strong></li><li><strong>Activation Functions</strong></li><li><strong>Training Rules</strong></li><li><strong>Objective functions</strong></li></ol><p>And we are going to see why.</p><h3>Input Encoding</h3><p>Starting with our inputs: now that we understand some constraints of our brain, how can we reflect them in our input data?</p><p>There are three encoding mechanisms that have been popularized with respect to input data:</p><ol><li><strong>Rate Coding: </strong>spiking frequency</li></ol><p>Rate coding uses input features to determine <strong>spiking frequency</strong>. There are many ways we can think of rate coding.</p><p>One way to use this idea is to sample from the Bernoulli distribution:</p><p>Each normalized feature value <em>X_ij</em>​ is interpreted as the probability that a spike occurs at a given time step. Based on this probability, we generate a binary output <em>R_ij</em>​.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*_NQC5ekAjDzAii9cDgyiIQ.png" /></figure><p>where there is only one trial (n=1), and the probability of “success” (meaning that a spike happens) is simply <em>X_ij</em>​.</p><p>Therefore, the probability of emitting a spike is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*kpiK3tBz4AMcbnc4kCqPNA.png" /></figure><p>and the probability of <em>not</em> emitting a spike is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*x8Q2pKYV6jMnIcvg8YTo0w.png" /></figure><p>In code, we can do it simply:</p><pre>#size of the temporal dynamics (we are going to understand later)<br>num_steps = 10<br>raw_vector = torch.ones(num_steps)*0.5 # [0.5 * 10]<br><br>#pass each sample through a Bernoulli trial<br>rate_coded_vector = torch.bernoulli(raw_vector)<br><br>#each of the elements of the vector will be passing through the bernoulli trial:<br># output: [1., 1., 1., 0., 0., 1., 1., 0., 1., 0.]</pre><p>Another way to use rate encoding is to think deterministically.<br>For instance, if our feature is normalized [0,1], we can simply determine that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*R8o_Oi37ZLpglBEsosI6Lw.png" /></figure><p>for a fixed period of time T.</p><p>And, therefore,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*JuvIH7N1U8KlpSEGrbmHJQ.png" /></figure><p>determining an Inter-Spike Interval (ISI).</p><p>This deterministic approach leads to a more stable behavior but is <em>less biological</em> because our neurons spike in a non-regular way.</p><p>2. <strong>Latency Coding: </strong>spike timing</p><p>Latency coding uses input features to determine spike timing.</p><p>In latency coding, each input feature produces <strong>exactly one spike</strong>.<br>The value of the feature is converted into a spike delay: higher values fire earlier, and lower values fire later within a fixed time window.</p><p>Different mapping functions can be used (e.g., linear, logarithmic), but the idea is always the same: the information is carried in <em>when</em> the spike happens, not in how many spikes occur.</p><pre>def latency_encode(features, T=20.0, t_min=1.0, mode=&quot;linear&quot;):<br><br>    if mode == &quot;linear&quot;:<br>        # linear: value 1.0 -&gt; t_min | value 0.0 -&gt; T<br>        spike_times = t_min + (1 - f) * (T - t_min)<br><br>    elif mode == &quot;log&quot;:<br>        # logarithmic latency coding<br>        eps = 1e-4<br>        f = np.clip(f, eps, 1)<br>        spike_times = t_min + (np.log(1/f) / np.log(1/eps)) * (T - t_min)<br><br>    return spike_times<br><br><br>features = np.array([0.0, 0.3, 0.7, 1.0]) #considering normalized features<br><br>print(&quot;Features:&quot;, features)<br>print(&quot;Linear latency spike times:&quot;, latency_encode(features, mode=&quot;linear&quot;))<br>print(&quot;Log latency spike times:&quot;, latency_encode(features, mode=&quot;log&quot;))<br><br>&quot;&quot;&quot;&quot;<br>OUTPUT:<br><br>Features: [0.  0.3 0.7 1. ]<br>Linear:  [20.   14.3   7.6   1. ]<br>Log:     [20.   16.9   4.8   1. ]<br>&quot;&quot;&quot;</pre><p>3.<strong> Delta Modulation: </strong>temporal change</p><p>Delta modulation uses the temporal change of input features to generate spikes. This concept is very used in other domains like telecom.</p><p>A spike is generated whenever the signal increases or decreases beyond a small threshold, so the spikes represent the temporal differences rather than the absolute values.</p><p>For instance, implementing DM to track a sinusoid (code on Kaggle):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcTp2g5AYFkr-UFz7fmYYg.png" /></figure><p>We will have their binary output as</p><pre>First Bits: [0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 0.<br> 1. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 0.]</pre><p>Bits: 1 -&gt; Sinusoid increasing; 0 -&gt; Sinusoid decreasing.</p><p>There are more advanced delta modulations, like the Adaptive Delta Modulation (ADM) to avoid slope overload and granular noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RDKh6tZW3onS7cf3.png" /><figcaption>Input encoding comparison. Source: <a href="https://snntorch.readthedocs.io/">https://snntorch.readthedocs.io/</a></figcaption></figure><h3>Output Decoding</h3><p>Now we are going to see how to transform the internal activity of a SNN into a meaningful continuous variable, class label, or decision.</p><p>And, as you may expect, just like the input encoding, there are different decoding strategies. And each one captures different aspects of neural activity, trading off temporal precision, robustness, and computational cost.</p><ol><li><strong>Rate Decoding</strong></li></ol><p>Here, we just do the inverse of the rate encoding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*xdNH0sYHP2kkPNArq7IqNw.png" /></figure><p>It interprets the output based on the firing rate of a neuron within a time window T. And y’s range is [0,1].</p><p>The highest probability neuron is the one with the highest firing rate, or spike count, as the predicted class.</p><p>2. <strong>Latency (or temporal) Decoding</strong></p><p>The highest probability neuron is the one with the output neuron that fires first as the predicted class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*PhdPbTzHZExr85Ob210DYw.png" /></figure><p>It carries the same idea as the input encoding</p><p>3. <strong>Population Decoding</strong></p><p>Instead of relying on a single neuron, a population of neurons jointly encodes the output. Examples:</p><ul><li><strong>Population Rate Code: </strong>average firing rate across a population</li><li><strong>Winner-Take-All (WTA): </strong>the population with the highest overall activation wins</li><li><strong>Weighted Population Code: </strong>neurons contribute with different weights depending on preferences</li></ul><h3>Activation Models for Biological Neurons</h3><p>In ANNs, we commonly use ReLU or Tanh as activation functions for each neuron. But for biological neurons, we have two main ways to model the neuron behavior, named <strong>Leaky Integrate-and-Fire (LIF)</strong> and the<strong> Hodgkin-Huxley Model</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MQTHMhSjAnBu_ri5.png" /><figcaption>Neuron Models Comparison. Source: <a href="https://snntorch.readthedocs.io/">https://snntorch.readthedocs.io/</a></figcaption></figure><p>The Hodgkin-Huxley model brings a lot of complexity in terms of computation, so in this article, we are going to focus on the LIF model.</p><p>The LIF model states that the activation for a neuron can be modeled as an RC low-pass filter circuit. Let’s understand its behavior:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*ZrjIAQl7J2oN6Tf9.gif" /><figcaption>Source: <a href="https://lcnwww.epfl.ch/gerstner/SPNM/node26.html">https://lcnwww.epfl.ch/gerstner/SPNM/node26.html</a></figcaption></figure><p>If we make the nodal equation (I) for the RC circuit and transform via Laplace, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*BfS-88_hGaD3pChul2VA8w.png" /></figure><p>and isolating U(s):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*M05nwAW6eb_eGvDchdA0OQ.png" /></figure><p>multiplying by R/R:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*k0CAhMGwvq4oda1QurT-Bg.png" /></figure><p>We can see that the transfer function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*FW03bHoB4GEefGEJ1a0QDQ.png" /></figure><p>is indeed a low-pass filter with a zero at infinity and a pole in (-1/RC). The time constant τ = RC has a typical order of 1–100 ms.</p><p>Let’s go back to the time domain analysis. Applying the inverse Laplace transform in equation (I), rearranging, and using that τ = RC, we can express the nodal equation as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*7ZCSNHF0c9MVuMVEnhpRqA.png" /></figure><p>This is the continuous form of LIF (without threshold/reset).</p><p>To make this time-varying solution compatible with a sequence-based neural network, the forward Euler method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*lPUb9T4BIfrEvFxBhxgCTg.png" /></figure><p>is used in the simplest case to find an approximate solution to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*7NE7NFcgQxB4x3FZkynJsQ.png" /></figure><p>where time is explicitly discretized, β = exp(−1/τ) is the decay rate (or “inverse time constant”) of U [t].</p><p>Until now, we have only a low-pass filter. To fully model the neuron, we need the decay (we already have at βU[t-1]), the synaptic entrance, and a reset after the spike.</p><p>The synaptic entrance we can make</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*97ASoIZFxPsG9Zr-jJUejQ.png" /></figure><p>Where X[t] is the spike inputs, W is the learnable weights for our spike neural network, and there is no normalization (1-β) because, for a deep learning approach, it does not take any effect.</p><p>For the reset, we add:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*oEusQYPJybCgX7l2LEsbZA.png" /></figure><p>where Sout[t] ∈ {0, 1} is the output spike generated by the neuron, where, if activated (Sout = 1), the reset term subtracts the threshold θ from the membrane potential. Otherwise, the reset term has no effect (Sout = 0).</p><p>In the end, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*6muziOBSktvP5MHew68aGQ.png" /></figure><p>For further highlights and reasons for taking some modeling decisions, I highly recommend checking this <a href="https://ieeexplore.ieee.org/abstract/document/10242251">IEEE overview</a>.</p><p>Implementing this mechanism, we have:</p><pre>#LIF w/Reset mechanism<br>def leaky_integrate_and_fire(mem, cur=0, threshold=1, time_step=1e-3, R=5.1, C=5e-3):<br>  tau_mem = R*C<br>  spk = (mem &gt; threshold)<br>  mem = mem + (time_step/tau_mem)*(-mem + cur*R) - spk*threshold  # every time spk=1, subtract the threhsold<br>  return mem, spk</pre><p>The behavior we get is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*eM1eULd_tCPns-ZE.png" /><figcaption>LIF behavior with constant current. Source: <a href="https://snntorch.readthedocs.io/">https://snntorch.readthedocs.io/</a></figcaption></figure><p>And the learning parameter (the weight) is expressed in how much current we should input to that neuron.</p><blockquote>Excellent! By now, we understood some ways to adapt the input, output, and to model our activation function! Still, there are two things we have to pay attention to: the training and the objective function.</blockquote><h3>The problem of Backpropagation</h3><p>We noticed that there are a few concepts explained by <strong><em>the three S’s </em></strong>that we should pay attention to by the time we create a biologically plausible neural network.</p><p>But there is something even more problematic: backpropagation.</p><p>Backpropagation depends on global, synchronous, and non-local information, while our brain works via local signals and event-driven operations, and it does not have access to a “global error.”</p><p>Furthermore, as we noticed, our brain encodes information via spikes (pulses), and, by their definition, they are not differentiable.</p><p>So, we simply cannot use our common backpropagation when “training” our brain model. We have to find something different or some kind of trick.</p><h3>Training Strategies</h3><p>Researchers developed some ways to train these networks:</p><ol><li><strong><em>Shadow </em>Training</strong></li></ol><p>The first and most used way to train SNNs is to simply train a common ANN and convert it, after, to a SNN.</p><p>The ANN serves as a <em>shadow model</em>: it learns the mapping using continuous activations, and the SNN later inherits its weights and structure.</p><p><strong><em>2. Backpropagation using Spikes</em></strong></p><p>Here we do use backpropagation, but with some tricks. We explore an adaptation to solve the <em>dead neuron problem</em> (we are going to see it in detail).</p><p><strong><em>3. Local Learning Rules</em></strong></p><p>Weight updates are a function of signals that are spatially and temporally local to the weight, rather than from a global signal as in error backpropagation. This one is the closest we can get to the biological constraints of the brain.</p><p>There are a whole lot of studies on each of these techniques. Here in this article, I am going to focus on how we can backpropagate using spikes. And again, if you want to get details on each of these techniques, I strongly recommend checking the IEEE article.</p><h3><strong><em>Backpropagation using Spikes</em></strong></h3><p>The spike occurs when the neuron’s membrane achieves a specific threshold. This can be described in this manner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*wHALrAKQ8oHeH_Ec6GwGkQ.png" /></figure><p>So, in this case, it is basically the description of the Heaviside function Θ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*4s1uYlRU6FgRtP_x9cyyGg.png" /></figure><p>Described in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CL03ayaKjOXvv0VY.png" /><figcaption>Source: <a href="https://snntorch.readthedocs.io/">https://snntorch.readthedocs.io/</a></figcaption></figure><p>This spike will further communicate with other neurons and achieve some objective function. But let’s first consider a single neuron with its loss function:</p><p>The forward pass for our neuron model (in a time step <em>t</em>) is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*mTodjhFRCnovuUMp0BWrag.png" /></figure><p>An input (X) is mapped to the current (<strong>I</strong> = <strong>W</strong>*X) that will be applied to the neuron. This current is mapped to the voltage (<strong>U</strong>) via the Leaky Integrate-and-Fire model. This voltage is mapped to the spike (<strong>S</strong>) via the Heaviside function. This spike is then evaluated by the loss function (<strong>L</strong>).</p><p>And, therefore, its backward pass will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*9ZCmXdI6QhKm4pOYT95-yw.png" /></figure><p>Did you notice something problematic in this backpropagation? Exactly, the ∂S/∂U term. Deriving a Heaviside function in terms of its domain gets us 0 in all domains except for 1, which is not defined (infinity).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*sMmn5b8fiy9OiDLTW3At6A.png" /><figcaption>Source: IEEE article.</figcaption></figure><p>The gradient of the Heaviside function is 0 almost every time. And if this gradient is 0, there is no weight update and, therefore, no learning. This is known as the <strong><em>dead neuron problem</em></strong>.</p><p>And how can we solve this issue? One trick is to approximate Heaviside to a smoother function with the same characteristics: Sigmoid, or Arctan, for instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*7Moxy5GVmnXFwM_41gtsnA.png" /><figcaption>Source: IEEE article.</figcaption></figure><p>This is commonly known as the <strong><em>surrogate gradient</em> </strong>approach.</p><h3>Backpropagation Through Time</h3><p>​Until now, our model has been described only for a specific time <em>t</em>. This means we only calculate the gradient for one single time step (referred to as the <em>immediate influence).</em></p><p>However, as we have noticed, our brain stores information through different population activations over time. And how can we backpropagate through time? We use the<em> backpropagation through time (BPTT)</em> algorithm. It calculates the gradient from the loss to <em>all</em> descendants and sums them together.</p><p>We can get the total loss by adding the loss at every time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*WdMOfEcZhIxsGN5_SNr5cw.png" /></figure><p>Since the weights <strong><em>W</em></strong> are the same at all time steps<strong> </strong>(the formulation states temporal invariance), when we differentiate the total loss with respect to <strong><em>W</em></strong>, the derivative of the sum is just the sum of the derivatives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*9bCBSaU9yUQ7xfCaB7xhDw.png" /></figure><p>Each <strong><em>L[t]</em></strong> does not depend on <strong><em>W</em></strong> only directly, but also through all hidden states up to time <strong><em>t</em></strong>. If we call the hidden state at time <strong><em>s </em></strong>by <em>h[s]</em>, then, by the chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*vv9x6A1ROKMCQ7rPTLrxkA.png" /></figure><blockquote>If you come from a computational background instead of pure mathematics (just like me), it is easier to think this double sum as just 2 nested for loops.</blockquote><pre>g = {<br>    1: {1: 10},<br>    2: {1: 5,  2: 20},<br>    3: {1: 2,  2: 3, 3: 7}<br>}<br><br>total_grad = 0<br><br>for t in [1, 2, 3]:      #first sum<br>    for s in range(1, t+1): #nested sum<br>        total_grad += g[t][s]<br><br>print(&quot;total gradient dL/dW =&quot;, total_grad)</pre><p>Let’s see make an example with<strong><em> T=3</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*5upxPqfEoew2rc9ERlP0AA.png" /></figure><p>For t=1 (the first time step only depends on h[1]):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*VMVj92nxm1NmmGD71zFkEA.png" /></figure><p>For t=2 (the loss at time 2 depends on both h[1] and h[2]):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*ICNPUpX62Ke4Hb3o6Z5xug.png" /></figure><p>For t=3 (the loss at time 3 depends on h[1],h[2] and h[3]):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*6WH-RrMWzzJoTApff6NJrw.png" /></figure><p>Putting everything together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*0TxjpXxfK1aBMCKqzjZyjA.png" /></figure><p>See? Basically, two nested <em>for</em> loops!</p><p>This algorithm is used in many recurrent architectures, such as RNNs and LSTMs.</p><p>But let’s come back to our SNN formulation. Remember the loss for a certain time t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*9ZCmXdI6QhKm4pOYT95-yw.png" /></figure><p>In the LIF model, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*oPHXnwSbDnvpyTEXnjboqw.png" /></figure><p>So, strictly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*kF9ylO84Srzr4VOTKo3J2A.png" /></figure><p>Analysing each term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/63/1*WYsHUkBHjLKZjQuCaTQBiw.png" /></figure><p>comes from the loss function itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*lU8_Zu5qtyrzBU93ch0GYA.png" /></figure><p>comes from the surrogate gradient (smoothed activation function).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*qPZCemiNMzTxoLFQsg7IYQ.png" /></figure><p>It&#39;s just beta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*iSfpxispSJqGkACMo7FiPA.png" /></figure><p>equals 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*4xXhfC6uMnbFjf6LFkSNNA.png" /></figure><p>Finally, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*B2t8i55wBo8-KIF-9jYhWw.png" /></figure><p>Unrolling this, we visually have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZVnqn0HsQeTxZIhw" /><figcaption>Source: <a href="https://snntorch.readthedocs.io/">https://snntorch.readthedocs.io/</a></figcaption></figure><p>SNNs trained via BPTT are formally an RNN. But instead of a tanh/LSTM, we have a physical dynamics (LIF):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*-vcf5sZlo3xAZK28AaEvrA.png" /><figcaption>RNN block</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*bT7G7mgF58IKuXlcnjCKCw.png" /><figcaption>Discrete LIF dynamic</figcaption></figure><p>Thankfully, PyTorch’s autodiff takes care of that in the background for us.</p><h3>Loss Functions</h3><p>We can think of many different ways of optimization techniques. In this article, I will focus on <strong>spike rate objective functions</strong>.</p><ol><li><strong>Spike rate objective function</strong></li></ol><p>Let’s think about a simple multi-class classification problem.</p><p>When thinking about a classification model, it is common for us to think of a function (black box) that will map a series of inputs X into their respective probability density functions Y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*Met0h63-xtw8CNxff3pUAA.png" /><figcaption>In this specific application, n=m.</figcaption></figure><p>To map the input into their respective probability density function, we first want to make sure all logits are positive (e^z), and then, we simply normalize them by dividing by the sum of all e^z. This is commonly known as the softmax function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*EFgEUwWSWvjtF1tVpwiv3A.png" /></figure><p>To optimize our weights, we use the cross-entropy loss.</p><p>But we have a problem: SNNs do not generate logits. Their outputs are spikes throughout time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*0YmafxddsKCY-CEKRlHz_A.png" /></figure><p>Then, how can we make a classification? We are going to explicitly use the rate encoding.</p><p>For each class<em> c</em>, we sum the spikes throughout time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*2zfCZvlLWpLyGszIz5j4bQ.png" /></figure><p>This turns into a “continuous activation proxy”.</p><p>Therefore, we apply the spike rate to the softmax function, and we have each specific logit. After this, we can use the cross-entropy loss function to optimize our weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*bjCCzH5VAcJ4th86sugeIw.png" /></figure><p>We can also use spiking time objectives just as the same way we used for rate coding.</p><blockquote>Spike-based classification is not limited to rate-based objective functions. Alternative formulations can be built using spike-timing objectives, where the precise timing of spikes carries the discriminative information and directly defines the loss function.</blockquote><blockquote>In addition, there is an increasingly interesting line of research focused on <em>local</em> loss optimization, often inspired by predictive coding principles, where learning emerges from local error signals rather than global backpropagation (more biollogical fidelity). These approaches offer both biological plausibility and potential computational advantages. However, since they involve fundamentally different learning paradigms, I am going to leave their detailed discussion for a dedicated article.</blockquote><h3>Training a SNN</h3><p>Now that we have discussed the main principles behind the construction and operation of SNNs, we can move on to a concrete example that applies the techniques introduced so far.</p><p>In this example, we rely on <strong>SNNTorch</strong>, a library that provides practical implementations of the concepts we discussed. This allows us to focus on the modeling and training aspects without reimplementing low-level spiking mechanisms from scratch.</p><p>Using a simple pipeline to import and create dataloaders for the MNIST:</p><pre>batch_size = 256<br>data_path=&#39;/tmp/data/mnist&#39;<br><br>dtype = torch.float<br>device = torch.device(&quot;cuda&quot;) if torch.cuda.is_available() else torch.device(&quot;mps&quot;) if torch.backends.mps.is_available() else torch.device(&quot;cpu&quot;)<br><br>transform = transforms.Compose([<br>            transforms.Resize((28, 28)),<br>            transforms.Grayscale(),<br>            transforms.ToTensor(),<br>            transforms.Normalize((0,), (1,))])<br><br>mnist_train = datasets.MNIST(data_path, train=True, download=True, transform=transform)<br>mnist_test = datasets.MNIST(data_path, train=False, download=True, transform=transform)<br><br>train_loader = DataLoader(mnist_train, batch_size=batch_size, shuffle=True, drop_last=True)<br>test_loader = DataLoader(mnist_test, batch_size=batch_size, shuffle=True, drop_last=True)</pre><p>For our <strong><em>surrogate gradient</em> </strong>approach to avoid the dead neuron problem, we are going to use the known <em>fast sigmoid:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*nJqlinKx4NgRLhHy_uH-jg.png" /></figure><p>where <em>k</em> modulates how smooth our sigmoid function (large <em>K</em> means close to the Heaviside function, and lower <em>K</em> means a smoother function). The usual trade-off is <em>k=25</em>.</p><p>Another important parameter is β, the decay of the membrane:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*aDajJwaBo-SWVuDeoVPJWA.png" /></figure><p>Next to 0, the neuron “forgets fast”, and next to 1, the neuron integrates for a longer time. A common value is 0.5.</p><p>And, for our loss function, we are going to use the Cross-Entropy with rate-encoding as studied:</p><pre>spike_grad = surrogate.fast_sigmoid(slope=25)<br>beta = 0.5<br>loss_fn = SF.ce_rate_loss() # &quot;Cross Entropy Spike Rate Loss&quot;</pre><p>For our network, we are going to build:</p><pre>class Net(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br><br>        self.conv1 = nn.Conv2d(1, 12, 5) #greyscale image [channel=1, H, W]<br>        self.lif1 = snn.Leaky(beta=beta, spike_grad=spike_grad)<br><br>        self.conv2 = nn.Conv2d(12, 64, 5)<br>        self.lif2 = snn.Leaky(beta=beta, spike_grad=spike_grad)<br><br>        self.fc1 = nn.Linear(64*4*4, 10)<br>        self.lif3 = snn.Leaky(beta=beta, spike_grad=spike_grad)<br><br>    def forward(self, x, mem1, mem2, mem3):<br><br>        cur1 = F.max_pool2d(self.conv1(x), 2)      #[B, 12, 12, 12]<br>        spk1, mem1 = self.lif1(cur1, mem1)<br><br>        cur2 = F.max_pool2d(self.conv2(spk1), 2)   #[B, 64, 4, 4]<br>        spk2, mem2 = self.lif2(cur2, mem2)<br><br>        cur3 = self.fc1(spk2.flatten(1))           #[B, 10]<br>        spk3, mem3 = self.lif3(cur3, mem3)<br><br>        return spk3, mem3, mem1, mem2, mem3 #return each mem to be updated<br><br><br>        <br>#forward pass through time<br>def forward_pass(net, num_steps, data):<br>    spk_rec = []<br>    mem_rec = []<br><br>    # init hidden states ONCE (start of sequence)<br>    mem1 = net.lif1.init_leaky()<br>    mem2 = net.lif2.init_leaky()<br>    mem3 = net.lif3.init_leaky()<br><br>    for step in range(num_steps):<br>        #updating voltage thr each step<br>        spk, mem_out, mem1, mem2, mem3 = net(data, mem1, mem2, mem3)<br>        spk_rec.append(spk)<br>        mem_rec.append(mem_out)<br><br>    # stack -&gt; [T, B, 10]<br>    spk_rec = torch.stack(spk_rec)<br>    mem_rec = torch.stack(mem_rec)<br><br>    # permute -&gt; [B, T, 10] for me this is more logic<br>    #spk_rec = spk_rec.permute(1, 0, 2)<br>    #mem_rec = mem_rec.permute(1, 0, 2)<br><br>    return spk_rec, mem_rec</pre><p>Note that the structure is very similar to an RNN:</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class RNNNet(nn.Module):<br>    def __init__(self, input_size=28*28, hidden_size=128, num_classes=10):<br>        super().__init__()<br>        self.hidden_size = hidden_size<br>        self.rnn = nn.RNNCell(input_size, hidden_size)<br>        self.fc = nn.Linear(hidden_size, num_classes)<br><br>    def forward(self, x, num_steps):<br>        &quot;&quot;&quot;<br>        x: [batch, input_size] as does not have explicit time dimension<br>        &quot;&quot;&quot;<br>        batch_size = x.size(0)<br>        h = torch.zeros(batch_size, self.hidden_size, device=x.device)<br><br>        h_rec = []<br><br>        #simulating temporal dynamics<br>        for t in range(num_steps):<br>            h = self.rnn(x, h) #updating hidden values<br>            h_rec.append(h)<br><br>        logits = self.fc(h)<br>        return logits, torch.stack(h_rec)</pre><blockquote><strong>OBS:</strong> as we are dealing with static images (which do not have any explicit temporal dimension) we have to <strong>artificially create one</strong>. The temporal aspect lies on that <strong>for</strong> loop. There are other ways to artificially create temporal dynamics (even if it is not explicit)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CAosJDQXy21m4epF.png" /><figcaption>In our example, it is like converting MNIST into a static, unchanging video. Source: <a href="https://snntorch.readthedocs.io/">https://snntorch.readthedocs.io/</a></figcaption></figure><p>To analyse the accuracy, we can build a function like this one:</p><pre>def batch_accuracy(loader, net, num_steps):<br>  with torch.no_grad():<br>    total = 0<br>    acc = 0<br>    net.eval()<br><br>    loader= iter(loader)<br>    for data, targets in loader:<br>      data = data.to(device)<br>      targets = targets.to(device)<br>      spk_rec, _ = forward_pass(net, num_steps, data)<br><br>      #this function automatically decodes unsing rate encoding<br>      acc += SF.accuracy_rate(spk_rec, targets) * spk_rec.size(1)<br>      total += spk_rec.size(1)<br><br>  return acc/total</pre><p>Finally, our train pipeline:</p><pre>net = Net(beta, spike_grad).to(device)<br><br>optimizer = torch.optim.Adam(net.parameters(), lr=1e-2, betas=(0.9, 0.999))<br>num_epochs = 1<br>loss_hist = []<br>test_acc_hist = []<br>counter = 0<br><br><br>for epoch in range(num_epochs):<br><br>    for data, targets in iter(train_loader):<br>        data = data.to(device)<br>        targets = targets.to(device)<br><br>        #forward pass<br>        net.train()<br>        spk_rec, _ = forward_pass(net, num_steps, data)<br><br>        #initialize the loss &amp; sum over time<br>        loss_val = loss_fn(spk_rec, targets)<br><br>        optimizer.zero_grad()<br>        loss_val.backward()<br>        optimizer.step()<br><br>        #store loss history for plotting<br>        loss_hist.append(loss_val.item()<br><br>        #test set<br>        if counter % 50 == 0:<br>            with torch.no_grad():<br>                net.eval()<br>    <br>                test_acc = batch_accuracy(test_loader, net, num_steps)<br>                print(f&quot;Iteration {counter}, Test Acc: {test_acc * 100:.2f}%\n&quot;)<br>                test_acc_hist.append(test_acc.item())<br>    <br>        counter += 1</pre><p>The model could rapidly learn even with a small network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*tmSHkmyR9cm6kCJH0C-L_g.png" /></figure><p>And we can see that for our fixed slice of time (50 steps), the selected label will be the one with the largest activation throughout this slice of time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*WD9auNUUi5dAC_lP.gif" /></figure><p>In this case, the predicted value is 4, and the correct label is 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmhVPavDTyasS2c9CsBrPg.gif" /><figcaption>Membrane voltage level in each time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LR1miyJ2YbH0oGimonlAag.gif" /><figcaption>Another example of the membrane voltage level</figcaption></figure><h3>Conclusion and Next Challenges</h3><p>The integration of neuroscience and deep learning is an increasingly active research area, aiming to develop models that are more biologically grounded, efficient, and temporally aware.</p><p>Approaches such as spiking neural networks and biologically inspired learning rules offer promising alternatives to conventional deep learning architectures.</p><p>However, significant challenges remain, particularly in terms of scalable training, stable learning dynamics, and effective credit assignment over time. Future progress will depend on deeper theoretical insights and closer interaction between neuroscience, machine learning, and neuromorphic hardware, paving the way for more efficient and interpretable intelligent systems.</p><p>Thank you so much for reading! If you have any suggestions, feel free to contact me!</p><h3>References</h3><ul><li>IEEE Xplore Full-Text PDF: <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=10242251">https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=10242251</a></li><li>SNNTorch Documentation: <a href="https://snntorch.readthedocs.io/">https://snntorch.readthedocs.io/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=113cf2262204" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Latent Permutations with Gumbel-Sinkhorn Networks]]></title>
            <link>https://medium.com/@mathparracho/learning-latent-permutations-with-gumbel-sinkhorn-networks-24e5ce3e4114?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/24e5ce3e4114</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 20:20:32 GMT</pubDate>
            <atom:updated>2025-11-16T17:32:06.334Z</atom:updated>
            <content:encoded><![CDATA[<p>Our famous jigsaw puzzles… who never played it once? It is nice!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eptRT7e3pkh3HtfU09aQBg.jpeg" /><figcaption>“The Angel Appearing to the Shepherds” JigSaw Puzzle —by Thomas Cole</figcaption></figure><p>We can take hours, even days, to solve one like that.</p><p>What if we could use some smart and interesting approach to model this problem? And what if we could apply this to many other different 1-to-1 problems?</p><p>In this article, we’ll look at how <a href="https://arxiv.org/abs/1802.08665"><strong>Gumbel-Sinkhorn Networks</strong></a> provide a smart and elegant solution to the jigsaw puzzle problem. By combining<strong><em> continuous relaxation</em></strong> of permutations with <strong><em>stochastic sampling</em></strong>, these networks allow us to approximate the discrete puzzle arrangement problem using smooth, learnable functions.</p><p>The official paper can be found here: <a href="https://arxiv.org/abs/1802.08665">[1802.08665] Learning Latent Permutations with Gumbel-Sinkhorn Networks</a></p><p>The full code for this article can be found in this link: <a href="https://www.kaggle.com/code/matheusparracho/gumbel-sinkhorn-network">https://www.kaggle.com/code/matheusparracho/gumbel-sinkhorn-network</a></p><p>So, let’s start!</p><h3>Understanding the problem</h3><p>The good thing about neural networks is that they are extremely flexible and powerful at approximating almost any function, and that is awesome! However, in many cases, it is interesting to restrict the space of learnable functions by incorporating <strong><em>inductive biases</em></strong><em> </em>(things we a priori know to be true and relevant in our problem setting).</p><blockquote>Do you want to know a simple example of inductive bias? Imagine that you type for an image generative model to generate an image of a dog. Okay, the model may know the features of a dog, but it does not know where it should be, or the angle of the camera, or the type of trace you want. You can be more detailled to it! Just simply say “Generate an image of a dog in beach on a sunny day”. Perfect! You just incorporated inductive biases to your inference!</blockquote><p>Now let’s think about our jigsaw problem.</p><p>Jigsaw puzzles are a kind of permutation problem: we have a set of pieces that can be arranged in many possible ways, but only one of those permutations is correct. So, we know that our response should have a structured, one-to-one correspondence between each piece and its correct position.</p><blockquote>But how can we “say” to our model that the data has this structure and it does not need to check a much larger space of possible solutions during training?</blockquote><p>Let’s start with a basic type of jigsaw problem: sorting.</p><p>Imagine that we want to sort this vector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*Nj_s0i7DR2e5tZOVZlqIpw.png" /></figure><p>We can simply multiply the left side for the permutation matrix related to our data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*12NDmowzFID3Aelvk6R52g.png" /><figcaption>Permutation Matrix—A well-known special type of matrix only with 0s and 1s</figcaption></figure><p>And, therefore, we will have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*3RXL_tqUyf6y3oxu6KdHjw.png" /></figure><blockquote>How can we make our model learn this specific permutation matrix by already “telling” him that the map <strong>should </strong>be a permutation matrix a priori?</blockquote><p>Let’s analyze some characteristics of the permutation matrix: It is a square matrix containing only 0s and 1s, with exactly one 1 in each row and column, that represents a permutation of elements. And it is known as a <strong><em>doubly stochastic matrix.</em></strong></p><p>And we are going to inject this inductive bias by exactly using the Gumbel-Sinkhorn operator!</p><p>But first, let’s review some important concepts:</p><h3>0. The Gumbel Distribution</h3><p>Before going directly into details of the operator, let’s first understand the intuition behind the Gumbel distribution.</p><p>The Gumbel distribution belongs to the family of <strong><em>extreme value distributions</em></strong>, and it is often used to model the probability of observing the <em>maximum</em> (or <em>minimum</em>) of a set of random variables. For example, if you measure the highest temperature of each day over a year, the distribution of those maximum values tends to follow a Gumbel shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*ZNHOeb8L313tRRTKwPrfSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mp0TcCiE4pjOWmhI.png" /><figcaption>The Gumbel Distribution — Wikipedia</figcaption></figure><p>What makes it interesting for us is its <strong><em>stability under maximum, </em></strong>meaning that if we take many samples from a Gumbel distribution and compute their maximum, the result also follows a Gumbel distribution.</p><h3>1. The Gumbel-Max trick</h3><p>Using the property of the maximum stability of the Gumbel distribution, we can actually <em>sample</em> from a categorical distribution in a very elegant way without explicitly computing probabilities or using non-differentiable sampling operations.</p><p>Imagine we have a set of class logits z=(z_1,z_2,…,z_K), where each z_i​ represents the unnormalized score for a class.</p><p>The goal is to sample one category according to the categorical distribution defined by these logits.</p><p><em>We add Gumbel noise to each logit and simply take the argmax.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*I2Tm3FHYkbRZATHJJ_JVMg.png" /></figure><p>This operation, after <a href="https://lips.cs.princeton.edu/the-gumbel-max-trick-for-discrete-distributions/">some derivations</a>, looks exactly as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*5ujAPnj6db6mOIU4aPQRMw.png" /></figure><p>That is actually the same idea as the VAE reparametrization, but using the Gumbel distribution as our goal is to keep the maximum stability property of the categorical samples.</p><h3>2. The Gumbel-Softmax</h3><p>After getting the intuition behind the Gumbel-Max trick, we can now take one more step forward—making this sampling process differentiable.</p><p>What we are going to do is the common practice of changing the argmax function to his soft version: softmax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*BfDC3iWJaFLac93mRFeJCw.png" /></figure><p>Now we can totally differentiate the function.</p><h3>3. The Gumbel-Sinkhorn operator</h3><p>Notice that, to create doubly stochastic matrices, we can use the softmax function with temperature row-wise:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*IYwYFx2B1UJ_d1SV9i5ICw.png" /></figure><p>where e τ&gt;0 is the temperature parameter that controls how “sharp” or “smooth” the resulting distribution is.</p><p>And, as τ→0, the softmax approaches a one-hot vector, making each row closer to a discrete permutation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*XDi_GFZ67zpOFnKkwrTGIQ.png" /></figure><p>Let’s see, for example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*ahNVFrilDuP1sBK-63Nn7Q.png" /></figure><p>We compute the softmax row-wise for different values of τ:</p><p>For τ=1.0,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*wj63OQiky1kVxT71pRRGNQ.png" /></figure><p>For τ=0.1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*_xdOceJ--FX9CB7dxQ5yqw.png" /></figure><p>Limit τ→0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*4aAPJLCHrS8O6UYrP3K8Tw.png" /></figure><p>As you can see, each row becomes a <strong><em>one-hot vector</em></strong> that selects the maximum element of its row—the discrete permutation structure.</p><p>However, this matrix is only <strong><em>row-stochastic</em></strong>, meaning each row sums to one, but the columns do not necessarily do so.</p><p>To make both row and column normalization, we can use the <strong><em>Sinkhorn normalization</em></strong>: repeatedly normalize the rows and columns until convergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*y45RJsyYHR3JXP_FZ3JGbg.png" /></figure><p>This iterative process, known as the <strong><em>Sinkhorn-Knopp algorithm</em></strong>, guarantees that the resulting matrix S becomes doubly stochastic<strong><em>: </em></strong>exactly what we want.</p><blockquote>At this point, we might think: “Perfect! We can just make τ very small and get a permutation matrix.<br> But there is a thing: permutation matrices are discrete, and we can’t backpropagate through discrete sampling.</blockquote><p>To make this process differentiable, we introduce a continuous <strong><em>relaxation</em></strong>.</p><p>Inspired by the <strong><em>reparameterization trick</em></strong> used in Variational Autoencoders (VAEs), we can inject Gumbel noise into our score matrix to create a differentiable approximation of the discrete permutation process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*WD-iysSA_IFXPZSNHAuxNQ.png" /></figure><p>Then we apply the Sinkhorn normalization on top of this noisy version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*HuGfmo6nYpMXPGsK04GSsg.png" /></figure><p>This final matrix P—smooth, differentiable, and approximately doubly stochastic—is what we call the<em> </em><strong><em>Gumbel-Sinkhorn operator.</em></strong></p><p>In a nutshell, what we are doing can be represented as a <strong><em>continuous relaxation </em></strong>with <strong><em>stochastic sampling</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zV00TkzUJhq0LicnvmWFvQ.png" /><figcaption>The relaxation operation. Source: <a href="https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/DL2/sampling/permutations.html">UVA</a></figcaption></figure><h3>Implementing in Pytorch</h3><p>Let’s start by solving the initial problem proposed in this article: sorting a vector.</p><ol><li>To sample from a Gumbel distribution, we can write:</li></ol><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br><br>def sample_gumbel(shape, eps=1e-9, device=&#39;cpu&#39;):   <br>    u = torch.rand(shape, device=device)<br>    return -torch.log(-torch.log(u + eps) + eps) #sampling Gumbel(0,1)</pre><p>2. Implementing the Sinkhorn algorithm:</p><pre>def sinkhorn(log_alpha, n_iter=20):<br>    &quot;&quot;&quot;<br>    Receives logits (log_alpha) and applies alternating normalization<br>    of rows and columns until it becomes doubly stochastic<br>    &quot;&quot;&quot;<br>    for _ in range(n_iter):<br>        log_alpha = log_alpha - torch.logsumexp(log_alpha, dim=-1, keepdim=True)  #normalize rows<br>        log_alpha = log_alpha - torch.logsumexp(log_alpha, dim=-2, keepdim=True)  #normalize columns<br>    return torch.exp(log_alpha)</pre><p>3. Implementing the Gumbel-Sinkhorn operator:</p><pre>def gumbel_sinkhorn(log_alpha, tau=0.1, n_iter=20, noise=True):<br>    &quot;&quot;&quot;<br>    log_alpha: [batch, N, N] matrix of &quot;scores&quot; (logits)<br>    Returns a differentiable doubly stochastic matrix (approx. permutation)<br>    &quot;&quot;&quot;<br>    if noise:<br>        gumbel = sample_gumbel(log_alpha.shape, device=log_alpha.device)<br>        log_alpha = log_alpha + gumbel<br>    log_alpha = log_alpha / tau<br>    return sinkhorn(log_alpha, n_iter)</pre><p>Now we can create our network and the training pipeline by</p><pre>class SortNet(nn.Module):<br>    def __init__(self, dim):<br>        super().__init__()<br>        self.fc = nn.Linear(dim, dim, bias=False)<br><br>    def forward(self, x, tau=0.1):<br>        log_alpha = self.fc.weight.unsqueeze(0).expand(x.size(0), -1, -1) #[batch, dim, dim]<br>        P = gumbel_sinkhorn(log_alpha, tau=tau, n_iter=20, noise=True)<br>        x_sorted_soft = torch.bmm(P, x.unsqueeze(-1)).squeeze(-1) #apply soft permutation to input vector<br>        return x_sorted_soft, P<br><br><br>torch.manual_seed(0)<br>model = SortNet(dim=4)<br>optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)<br><br>x = torch.tensor([[0.3, -1.2, 2.1, 0.7]])  #input<br>y_target = torch.sort(x)[0]                #true sorted values<br><br>for step in range(1000):<br>    optimizer.zero_grad()<br>    y_pred, P = model(x)<br>    loss = F.mse_loss(y_pred, y_target)<br>    loss.backward()<br>    optimizer.step()</pre><p>And, in the end, we can see as a result:</p><pre>print(&quot;Input:&quot;, x)<br>print(&quot;Output (approximately sorted):&quot;, y_pred)<br>print(&quot;Soft permutation matrix P:&quot;)<br>print(P)<br>print(&quot;Argmax permutation of P:&quot;)<br>print(torch.argmax(P, dim=1))<br><br><br><br>&quot;&quot;&quot;<br>Input: tensor([[ 0.3000, -1.2000,  2.1000,  0.7000]])<br>Output (approximately sorted): tensor([[-1.2000,  0.3000,  0.7000,  2.1000]], grad_fn=&lt;SqueezeBackward1&gt;)<br>Soft permutation matrix P:<br>tensor([[[2.2447e-23, 1.0000e+00, 8.1926e-21, 2.1309e-15],<br>         [1.0000e+00, 2.5296e-07, 2.2603e-19, 1.2527e-06],<br>         [5.1798e-12, 2.9999e-14, 4.0297e-10, 1.0000e+00],<br>         [1.0102e-27, 5.6929e-22, 1.0000e+00, 9.6792e-16]]],<br>       grad_fn=&lt;ExpBackward0&gt;)<br>Argmax permutation of P:<br>tensor([[1, 0, 3, 2]])<br>&quot;&quot;&quot;<br></pre><p>Perfect! We managed to sort our vector!</p><p>Now, let’s implement the idea proposed by the authors, using the MNIST dataset to finally solve the jigsaw puzzle (code below is inspired by the <a href="https://colab.research.google.com/github/phlippe/uvadlc_notebooks/blob/master/docs/tutorial_notebooks/DL2/sampling/permutations.ipynb">UVA notebooks</a> and is completed on the <a href="https://www.kaggle.com/code/matheusparracho/gumbel-sinkhorn-network">Kaggle link</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*T2bNIQO9XGNTE2eB7Obd_Q.png" /><figcaption>Schematics from the <a href="https://arxiv.org/abs/1802.08665">official paper</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*4bmnI70Nky56pAn0TziDGg.png" /></figure><p>That is exactly the same idea proposed above for our sorting problem with the same auxiliary functions, but only with a convolutional layer before to extract some relevant features:</p><pre>import torch<br>import torch.nn as nn<br><br>class SinkhornConvNet(nn.Module):<br>    def __init__(<br>        self,<br>        in_channels: int,<br>        num_pieces: int,<br>        image_size: int,<br>        hidden_channels: int,<br>        kernel_size: int,<br>        tau: float = 1.0,<br>        n_sink_iter: int = 20,<br>    ):<br>        super().__init__(<br><br>        self.tau = tau<br>        self.n_sink_iter = n_sink_iter<br><br>        # g1_step: the conv layer before injecting the inductive bias<br>        self.g_1 = nn.Sequential(<br>            nn.Conv2d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2),<br>            nn.MaxPool2d(2),<br>            nn.ReLU(True),<br>            nn.BatchNorm2d(hidden_channels)<br>        )<br><br>        piece_size = image_size // num_pieces<br>        piece_size_after_conv = (piece_size) // (2 * 1)<br><br>        # g_2 step: inject the inductive bias<br>        self.g_2 = nn.Linear(piece_size_after_conv**2 * hidden_channels, num_pieces**2, bias=False)<br><br><br>    def forward(self, batch_pieces):<br>        batch_size = batch_pieces.shape[0]<br><br>        #switch batch and piece dimensions. We want to apply the same network<br>        #to each of the pieces.<br>        pieces = batch_pieces.transpose(0, 1).contiguous()<br><br>        #apply g_1 to each of the pieces<br>        conv_pieces = []<br>        for piece in pieces:<br>            piece = self.g_1(piece)<br>            conv_piece = piece.reshape(batch_size, -1)<br>            conv_pieces.append(conv_piece)<br><br>        #apply g_2 to each of the pieces<br>        latent_pieces = []<br>        for piece in conv_pieces:<br>            latent_piece = self.g_2(piece)<br>            latent_pieces.append(latent_piece)<br><br>        #create a matrix of log unnormalized assignment probabilities. After this<br>        #the batch dimension is batch in the first position.<br>        log_alphas = torch.stack(latent_pieces, 1)<br><br>        #during training, we sample from the Gumbel-Sinkhorn distribution.<br>        if self.training:<br>            permutation_matrices = gumbel_sinkhorn(log_alphas, tau=self.tau, n_iter=self.n_sink_iter)<br><br>        #during eval, we solve the linear assignment problem.<br>        else:<br>            permutation_matrices = torch.stack([<br>                matching(log_alpha)<br>                for log_alpha in log_alphas.cpu().detach().numpy()]<br>            ).float().to(log_alphas.device)<br><br>        #we obtain the ordered pieces as predicted by our network<br>        ordered_pieces = inverse_permutation_for_image(batch_pieces, permutation_matrices)<br><br>        #return the ordered pieces, along with the predicted permutation.<br>        #we will inspect the predicted permutation matrices during test time.<br>        return ordered_pieces, permutation_matrices</pre><p>Nice! The pipeline is the common supervised learning we already know, with the inputs being the shuffled images and the output being the original images. Details of this pipeline and the auxiliary functions can be found in the <a href="https://www.kaggle.com/code/matheusparracho/gumbel-sinkhorn-network">Kaggle link</a>.</p><p><strong>How can we evaluate its performance?</strong></p><p>We can use the <strong>Kendall-Tau correlation coefficient.</strong></p><p>It is a statistic that measures <em>how similar two orderings (rankings or permutations</em><strong><em>)</em></strong> are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*bl4HHiqy7xoEfweSa5sshw.png" /></figure><p>It tells you <em>how much two lists agree in their order</em>—for example, how close the predicted permutation is to the ground-truth permutation.</p><pre>with torch.no_grad():<br><br>    kendall_taus = []<br><br>    for data in test_loader:<br>        inputs, _ = data<br>        pieces, random_pieces, perm_list = batch_chunk_image(inputs, num_pieces)<br>        pieces, random_pieces = pieces.to(device), random_pieces.to(device)<br><br>        ordered_pieces, predicted_permutation_matrices = model(random_pieces)<br><br>        #create the list of inverse permutation indices from the predicted<br>        #permutation matrix.<br>        predicted_perm_list = predicted_permutation_matrices.transpose(1, 2).max(1)[1]<br><br>        #obtain the Kendall-Tau correlation coefficient for the target<br>        #and predicted list of permutation matrices.<br>        for p1, p2 in zip(perm_list, predicted_perm_list):<br>            kendall_taus.append(<br>                kendalltau(p1.cpu(), p2.cpu())[0]<br>            )<br><br>    print(f&quot;Mean Kendall-Tau: {np.mean(kendall_taus)}&quot;)</pre><p>More details of this coefficient you can find <a href="https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient">here</a></p><h3>Results</h3><p>For training with 2 pieces on each side, we can get results like this:</p><pre>epoch 0|  mean loss 67.4326<br>epoch 1|  mean loss 11.0889<br>epoch 2|  mean loss 6.8962<br>epoch 3|  mean loss 5.4115<br>epoch 4|  mean loss 4.3444<br>epoch 5|  mean loss 3.6695<br>epoch 6|  mean loss 2.9135<br>epoch 7|  mean loss 2.7247<br>epoch 8|  mean loss 2.4278<br>epoch 9|  mean loss 2.171<br><br>Mean Kendall-Tau: 0.9951666666666668</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*fu5gV-mRT873Fy_CJ7MwcQ.png" /><figcaption>Input Shuffled</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*h0fX0kXr3iEKcTGVcdGshQ.png" /><figcaption>Model Output image</figcaption></figure><p>During experimentation, it is noticeable that increasing the number of chunks increases drastically the difficulty of the puzzle itself (which is already expected).</p><p>For example, training with 4 pieces on each side, we have the separation like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*m8jYmwbv4WhoCqmt96RjGA.png" /><figcaption>Separating by 4 pieces</figcaption></figure><p>And the training is a lot more difficult by analysing just the loss decay</p><pre>epoch 0|  mean loss 709.6451<br>epoch 1|  mean loss 554.432<br>epoch 2|  mean loss 513.144<br>epoch 3|  mean loss 490.4276<br>epoch 4|  mean loss 471.2873<br>epoch 5|  mean loss 458.1032<br>epoch 6|  mean loss 446.9516<br>epoch 7|  mean loss 438.28<br>epoch 8|  mean loss 430.7336<br>epoch 9|  mean loss 423.9783<br><br>Mean Kendall-Tau: 0.3167983333333333</pre><p>Keeping the exact same parameters and pipeline, we achieve some results like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*YD0Tc5-_SfuA_FUKEFTgMA.png" /><figcaption>input shuffled</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*6iG9MuQ2mrNQTkWZuRlgWA.png" /><figcaption>output image</figcaption></figure><p>It is interesting to notice, though, that the model was already capable of noticing that the image itself should be contained in the center and has some defined structure. Surely with more training time and deeper networks, it should be quite easy to create permutation matrices!</p><h3>Conclusion</h3><p>Nice! We managed to understand how we could insert inductive bias in our model for the permutation latent matrix via the Gumbel-Sinkhorn operator.</p><p>The gold of this operator is that we can apply this to any matching and assign problems, for instance, <strong><em>feature alignment</em></strong>, where we match keypoints or patches between two images (just like SIFT for instance), or <strong><em>cross-modal retrieval</em></strong>, where embeddings from different modalities, such as text and images, need to be paired. It can also be applied to <strong><em>graph matching</em></strong>, where we find correspondences between nodes of two graphs, or to <strong><em>sequence reordering and ranking tasks</em></strong>, where the model must learn to output an ordered structure.</p><p>In other words, it bridges the gap between deep learning and combinatorial reasoning—enabling our models not only to learn representations but also to learn structured relationships between elements.</p><h3>References</h3><p><a href="https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/DL2/sampling/permutations.html">SGA: Learning Latent Permutations with Gumbel-Sinkhorn Networks — UvA DL Notebooks v1.2 documentation</a></p><p><a href="https://arxiv.org/abs/1802.08665">[1802.08665] Learning Latent Permutations with Gumbel-Sinkhorn Networks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e5ce3e4114" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[At the Core of Transformer Architecture: From Attention to GPT]]></title>
            <link>https://medium.com/@mathparracho/at-the-core-of-transformer-architecture-from-attention-to-gpt-deed149487cf?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/deed149487cf</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 07:17:37 GMT</pubDate>
            <atom:updated>2025-07-08T07:18:20.071Z</atom:updated>
            <content:encoded><![CDATA[<p>Attention: the mechanism that changed how we deal with AI. Text, audio, imaging, i.e. signals, everything can be be processed with attention.</p><p>In this article, I am going to study deeply into the attention mechanism. We’ll explore its mathematical foundations, walk through its code implementation, and see how it powers models like BERT and GPT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QUDKgKLNr3WOuCTG.png" /><figcaption>The Transformers Architecture and its core</figcaption></figure><p>All code can be seen here:</p><ul><li>The Attention Core Mechanism <a href="https://www.kaggle.com/code/matheusparracho/attention-mechanism">kaggle.com/code/matheusparracho/attention-mechanism</a></li><li>BERT Implementation using Hate Speech Dataset <a href="https://www.kaggle.com/code/matheusparracho/bert-attentionmechanism-hatespeechdataset">kaggle.com/code/matheusparracho/bert-attentionmechanism-hatespeechdataset</a></li><li>GPT Implementation using “Shakespeare-style” generation: <a href="https://www.kaggle.com/code/matheusparracho/gpt-shakespeare">kaggle.com/code/matheusparracho/gpt-shakespeare</a></li></ul><p>Now, let’s start!</p><h3>Attention Mechanism — Intuition</h3><p>Imagine that you have a picture of a human face:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*Z7ieRQ8rPFeGWjTgYTWmUA.png" /></figure><p>Now, you split this image into 4 different sections (tokens):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*6BBJfTLq9TNgOgXoNB_ECw.png" /></figure><p>These tokens are simply the pixels contained inside the respective square. Now, consider that we need to understand the relationship between these tokens to understand (in a general context) that this group of sections (batch) is a face. We can, then, model these tokens as a fully-connected graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*Vvx2wHOywavfu8Ug1SJU0g.png" /><figcaption>Connected graph with 4 nodes. We want to understand the relationship between the tokens</figcaption></figure><p>Now, we need a way to map these pixel-domain nodes into an embedding to then be able to manipulate these informations.</p><p>Let’s define 3 different Linear operators:<em> the Query map, the Key map, and the Value map</em>. These maps are simply matrices that will transform the pixel-domain tokens into a latent domain representation.</p><p>These representations are going to be processed in this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*lzrnc1OSyydze4USa6T_gA.png" /></figure><p>The intuition behind doing this operation is that we want to represent each node into something that express relationships. Minimizing the loss function (or maximizing the objective functions) will force these matrices to express these behaviours:</p><ol><li>Query: “What is the node looking for?”</li><li>Key: “What the node has to offer”</li><li>Value: “What the node has to propagate if chosen”</li></ol><blockquote>It may look bizarre at first thinking how optimization will create these behaviours, but indeed, you can really use this interpretation.</blockquote><p>The weights of the maps are trained to optimize for the best representation of the tokens.</p><p>Everything in the Attention operation is differentiable (and linear, actually), which means that <strong>every weight can be optimized via gradient descent.</strong></p><p>To make it easier to understand the operation, let’s forget the parallelism from all tokens for now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*95sT1qjm2jODTlQif8J28Q.png" /></figure><p>Let’s get the example with the Token 1. The first thing we need to do is to make the dot product with all the other tokens of the graph, generating, therefore, scores that correspond how close the token 1 is in comparison to the other tokens.</p><p>These scores can be any real number. So, to make a reasonable comparison between each, we use the softmax function.</p><p>Softmax will transform these values into a probability density function, with <em>αxy </em>being the output probability score relationship between <em>x</em> and <em>y</em>.</p><p>The output of the softmax function is simply scores, we need to multiply it into a matrix to get reasonable weights: a contextualized representation that encodes relevant information from other tokens.</p><p>The attention will compare each node with others, running in a O(n²).</p><p>Let’s first analyse the self-attention and then implement it using Pytorch.</p><h3>Self-Attention</h3><p>The Self-Attention is basically the Attention, but using one single tensor as input. And here we are going to use parallelism.</p><p>The process can be described like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*oPpxQpCItlM_YsFXbs3Z8w.png" /><figcaption>Attention Mechanism</figcaption></figure><p>Let’s implement it. First, implementing the 4 nodes with a 4-dimensional feature vector (imagine this as 4 pictures (tokens) with 4 pixels each, for instance):</p><pre>import torch<br>import torch.nn.functional as F<br><br>#4 nodes, each with a 4-dimensional feature vector<br>num_nodes = 4<br>num_features = 4<br><br>#initial embeddings [nodes, features]<br>X = torch.randn(num_nodes, num_features)  #shape: [4, 4] </pre><p>Mapping it into their linear projections:</p><pre>W_Q = torch.nn.Linear(num_features, num_features, bias=False)<br>W_K = torch.nn.Linear(num_features, num_features, bias=False)<br>W_V = torch.nn.Linear(num_features, num_features, bias=False)<br><br>Q = W_Q(X)  # [4, 4]<br>K = W_K(X)  # [4, 4]<br>V = W_V(X)  # [4, 4]</pre><p>And doing the Attention Operation:</p><pre>#dot product between all queries and keys<br>scores = Q @ K.T                        # shape: [4, 4]<br>scaled_scores = scores / num_features**0.5  # normalizing to be stable<br><br>#sofmax applied by row: the relationship between the nodes!<br>attention_weights = F.softmax(scaled_scores, dim=1)  # [4, 4]<br><br>#output: each line is a node updated based on the influence of the others<br>out = attention_weights @ V  # [4, 4]</pre><p>We can see the weight matrix:</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>sns.heatmap(attention_weights.detach().numpy(), annot=True, cmap=&#39;viridis&#39;)<br>plt.title(&quot;Attention Weights (Node communication)&quot;)<br>plt.xlabel(&quot;Keys (listened nodes)&quot;)<br>plt.ylabel(&quot;Queries (spoken nodes)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*ikFxwdQZYLI2WxJgi1rYOA.png" /></figure><p>As we still have not trained anything yet, the attention weights are just random by now. But this is the way we structure the matrices weights.</p><h3>Multi-Head Attention</h3><p>The multi-head attention is basically many different attention operations running in parallel. Each attention operation we will call “head” and it will process different subspaces of the data.</p><p>Let’s think of an image with 5 blocks of 8 pixels each. Our goal is to apply attention between these blocks and see the relation between them:</p><pre>#5 nodes, each with a point in a 8 dimensional space r8.<br>num_nodes = 5<br>num_features = 8<br><br>#initial embeddings [nodes, features]<br>X = torch.randn(num_nodes, num_features)  #shape: [5, 8]<br><br>#now choosing the number of heads<br>num_heads = 2<br>assert num_features % num_heads == 0 #should be pair by now just to be simple<br>num_subspaces = num_features // num_heads</pre><p>Building a class to formalize the mechanism (it is a good practice) and understanding step by step:</p><pre>class MultiHeadAttention(torch.nn.Module):<br>    def __init__(self, num_features, num_heads):<br>        super().__init__()<br>        self.num_heads = num_heads<br>        <br>        #dividing the different subspaces<br>        self.num_subspaces = num_features// num_heads<br>        <br>        self.W_Q = torch.nn.Linear(num_features, num_features, bias=False)<br>        self.W_K = torch.nn.Linear(num_features, num_features, bias=False)<br>        self.W_V = torch.nn.Linear(num_features, num_features, bias=False)<br>        <br>        #final output<br>        self.W_O = torch.nn.Linear(num_features, num_features, bias=False)<br><br>    def forward(self, X):<br>        <br>        # X.shape -&gt; [num_nodes, num_features]<br>        num_nodes, _ = X.shape #[5, 8]<br>        <br>        &quot;&quot;&quot;<br>        what do we need to do?<br>        1. split the full space (features) into subspaces (head, features)<br>        2. make the attention operation inside each head<br>        &quot;&quot;&quot;<br>        <br>        #projections: [num_nodes, num_features] -&gt; [num_nodes, num_heads, num_subspaces]<br>        Q = self.W_Q(X) #[4, 4]<br>        Q = Q.view(num_nodes, self.num_heads, self.num_subspaces) #[5, 2, 4]<br>        K = self.W_K(X)#[4, 4]<br>        K = K.view(num_nodes, self.num_heads, self.num_subspaces)#[5, 2, 4]<br>        V = self.W_V(X)# [4, 4]<br>        V = V.view(num_nodes, self.num_heads, self.num_subspaces) #[5, 2, 4]<br>        <br>        # [num_nodes, num_heads, num_subspaces] -&gt; [num_heads, num_nodes, num_subspaces]<br>        # why? because the matrix multiplication has to be done within each HEAD <br>        Q = Q.transpose(0, 1) #[2, 5, 4]<br>        K = K.transpose(0, 1) #[2, 5, 4]<br>        V = V.transpose(0, 1) #[2, 5, 4]<br>        <br>        # attention per head: softmax(QK^T / sqrt(d_k)) * V<br>        # [num_heads, num_nodes, num_subspaces] @ [num_heads, num_subspaces, num_nodes] = [num_heads, num_nodes, num_nodes]<br>        <br>        scores = Q @ K.transpose(1, 2) / self.num_subspaces**0.5  # [2, 5, 5]<br>        attn_weights = F.softmax(scores, dim=-1)  # [2, 5, 5]<br><br>        # [num_heads, num_nodes, num_nodes] @ [num_heads, num_nodes, num_subspaces] = [num_heads, num_nodes, num_subspaces]<br>        head_outputs = torch.matmul(attn_weights, V)  # [2, 5, 4]<br><br>        #concatenate heads: [num_nodes, num_heads * num_subspaces] = [num_nodes, num_features]<br>        concat = head_outputs.transpose(0, 1).contiguous().view(num_nodes, -1)  # [5, 8]<br>        <br>        #final projection, just a simple linear layer<br>        output = self.W_O(concat)  # [5, 8]<br>        return output, attn_weights<br><br><br>mha = MultiHeadAttention(num_features=num_features, num_heads=num_heads)<br>output, attn_weights = mha(X)  # inputs: [5,8], output: [5, 8], attn_weights: [2, 5, 5]</pre><p>We can see the attention weights by doing:</p><pre>fig, axs = plt.subplots(1, num_heads, figsize=(12, 5))  # 1 row, num_heads columns<br>for i in range(num_heads):<br>    sns.heatmap(attn_weights[i].detach().numpy(), annot=True, cmap=&#39;viridis&#39;,<br>                ax=axs[i], cbar=i == num_heads - 1)<br>    axs[i].set_title(f&quot;Head {i+1} - Attention Weights&quot;)<br>    axs[i].set_xlabel(&quot;Keys&quot;)<br>    axs[i].set_ylabel(&quot;Queries&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJLxHWwKdfYeSxr1Mg1V2g.png" /><figcaption>The 5x5 matrices of each head side by side</figcaption></figure><p>Of course, we did not train with anything, so it is the weights are all random.</p><h4>Training the Multi-Head Attention!</h4><p><em>In this section, I will show two different ways of training the attention weights.</em></p><p>Now imagine that node 3 has a strong relationship with node 5, and node 1 has a strong relationship with node 2.</p><p>Let’s write this down:</p><pre># we are creating the dictionary as (query, key)<br>target = {<br>    (3, 4): 1.0,  # node 3 looks for node 4<br>    (0, 1): 1.0   # node 0 looks for node 1<br>}</pre><p>Let’s create a loss function, so now we have a loss landscape to optimize and walk into:</p><pre>def attention_loss(attn_weights, target_dict):<br>    loss = 0.0<br>    for (query, key), value in target_dict.items():<br>        for head in range(attn_weights.shape[0]):  # iterating over the heads<br>            pred = attn_weights[head, query, key]  # attetion on head between query -&gt; key<br>            loss += (pred - value)**2  #MSE loss (we could use BCE or KL)<br>    return loss</pre><p>Creating a simple training pipeline:</p><pre>mha = MultiHeadAttention(num_features=num_features, num_heads=num_heads)<br>optimizer = torch.optim.Adam(mha.parameters(), lr=0.01)<br><br>for epoch in range(200):<br>    optimizer.zero_grad()<br>    output, attn_weights = mha(X)<br>    loss = attention_loss(attn_weights, target)<br>    loss.backward()<br>    optimizer.step()</pre><p>Now plotting the attention weights:</p><pre>fig, axs = plt.subplots(1, num_heads, figsize=(12, 5))<br>for i in range(num_heads):<br>    sns.heatmap(attn_weights[i].detach().numpy(), annot=True, cmap=&#39;viridis&#39;,<br>                ax=axs[i], cbar=i == num_heads - 1)<br>    axs[i].set_title(f&quot;Head {i+1} - Attention Weights&quot;)<br>    axs[i].set_xlabel(&quot;Keys&quot;)<br>    axs[i].set_ylabel(&quot;Queries&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctGR_Ozt5MZlmawzmnzivQ.png" /></figure><p><em>Voilà!</em> In both heads, node 0 is looking for 1, and node 4 is looking for 5.</p><blockquote>Interesting, but I mean… in real life we do not know the relation between the nodes, we node something to do it for us.</blockquote><p>That is why we have the final output layer, so we can compare data with data of the same nature.</p><p>Let’s create a matrix of targets to express what we want:</p><pre>target = torch.zeros_like(X)<br>target[3] = X[4]  # node 3 focus on node 4<br>target[0] = X[1]  # node 0 focus on node 1<br><br>&quot;&quot;&quot;<br>tensor([[-1.3373,  1.5901,  1.7353, -1.9798,  1.0730, -1.0990, -0.4069, -0.5938],<br>        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000],<br>        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000],<br>        [-0.5265, -0.8904, -1.1178, -0.0320,  0.4538,  1.8264,  0.2254, -0.6280],<br>        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000]])<br>&quot;&quot;&quot;</pre><blockquote>You may ask, why the target matrix can be built like this? Remember, attention seeks the <strong>similarity</strong> between nodes. The target matrix we built is copying the information presented in node 4 (key) into the query of node 3. So, actually, what we are saying is that 3 is looking some node very similar to 4.</blockquote><p>Now it the training pipeline is simple:</p><pre>def output_loss(output, target):<br>    return F.mse_loss(output, target)<br><br>mha = MultiHeadAttention(num_features=num_features, num_heads=num_heads)<br>optimizer = torch.optim.Adam(mha.parameters(), lr=0.01)<br><br>for epoch in range(200):<br>    optimizer.zero_grad()<br>    <br>    output, attn_weights = mha(X)  # output: [5, 8]<br>    <br>    loss = output_loss(output, target)<br>    loss.backward()<br>    optimizer.step()</pre><p>Good! Let’s train and see the results:</p><pre>fig, axs = plt.subplots(1, num_heads, figsize=(12, 5))<br>for i in range(num_heads):<br>    sns.heatmap(attn_weights[i].detach().numpy(), annot=True, cmap=&#39;viridis&#39;,<br>                ax=axs[i], cbar=i == num_heads - 1)<br>    axs[i].set_title(f&quot;Head {i+1} - Attention Weights&quot;)<br>    axs[i].set_xlabel(&quot;Keys&quot;)<br>    axs[i].set_ylabel(&quot;Queries&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNgBLh4bQHmBimRrsq6zhw.png" /></figure><p>Interesting! Head 1 correctly noticed that node 0 was looking for node 1, and node 3 was looking for node 4. Head 2 noticed only that node 3 was looking for node 4 (parallelism focus on different data features).</p><p>In the Kaggle Notebook, I also trained the model to map the MNIST dataset, and the map can be observed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*qlYLAi9re8i33sMd.png" /></figure><p>In some cases, it may be unstable due to the MSE loss simplicity for the case of attention. That is why it is common to use a feed-forward network after, leading into the well-known transformer architecture:</p><h3>The Transformer Architecture</h3><p>With the Attention Mechanism, we can build one of the most famous architectures developed lately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*gjENAaiqb3WStfWGuv8XTQ.png" /></figure><p>Let’s first start with the Encoder, the left side of the architecture:</p><h3>Creating a Transformer Encoder (and a BERT)</h3><p>The encoder is the architecture responsible for getting complex and deep relationships between <strong>every</strong> token. It is basically the attention and a feed-forward network together working as a Megazord to understand linear and non-linear relationships.</p><p>Let’s break it down into details:</p><p>0. <strong>Tokenization</strong></p><p>Before even starting with the embeddings, when we are dealing with words, we have to understand that there are many different ways of separating these tokens. The usual ones are:</p><p><strong>Word-level Tokenization<em><br></em>Example:</strong> &quot;The dog barked.&quot; → [&quot;The&quot;, &quot;dog&quot;, &quot;barked&quot;, &quot;.&quot;]</p><p><strong>Character-level Tokenization</strong><br><strong>Example:</strong> &quot;dog&quot; → [&quot;d&quot;, &quot;o&quot;, &quot;g&quot;]</p><p><strong>Subword-level Tokenization <em><br></em></strong><em>1. Byte Pair Encoding (BPE)</em><br>Merges frequent pairs of characters/subwords. &quot;lower&quot; → [&quot;low&quot;, &quot;er&quot;]</p><p><em>2. WordPiece (used in BERT)</em><strong><em><br></em></strong>Breaks rare words into known components: &quot;unhappiness&quot; → [&quot;un&quot;, &quot;##happi&quot;, &quot;##ness&quot;]</p><p><em>3. SentencePiece (used in T5, ALBERT)<br></em>Learns subwords without relying on spaces. Works well for languages like Japanese or Chinese.</p><p><strong>Byte-level Tokenization (used in GPT-2, GPT-3)<br></strong>Converts text to bytes (UTF-8), then applies BPE. &quot;hello&quot; → [104, 101, 108, 108, 111] → then merged into byte-level tokens.</p><ol><li><strong>Input Embedding and the Positional Encoding</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*aymdPUbNt7ox-vYlgClE0Q.png" /></figure><p>The <strong>embedding </strong>is just a way to represent the domain we are dealing with as input (words, pixels, signals…) as vectors. There are many different ways of creating embeddings, for example, the embedding for each word:</p><pre>words = [&quot;dog&quot;, &quot;cat&quot;, &quot;hello&quot;] #word-level Tokenization<br><br>num_words = len(words)<br>embedding_dim = 4 # you can choose the size u want<br><br>#each word means each row and each column means each feature<br>embeddings = torch.rand(num_words, embedding_dim)<br><br>print(embeddings.size) # (3,4)</pre><p>As we do not know any relation between the words a priori, each embedding is simply a random vector (or a point in R*).</p><p>So, for instance, if we want to get the embedding of a specific word, we should simply get the index of the row:</p><pre>word = &quot;cat&quot;<br>idx = words.index(word)<br><br>embedding_cat = embeddings(idx)</pre><p>The attention mechanism needs to know “who” each token is. Basically we have to “name” each node (token). This is why we need a <strong>positional encoding</strong>.</p><blockquote>But why? Does not the embedding do this already? Imagine that we have to equal words in the same sentence: “I like being like this” and imagine we have the embedding separated by space (each word means one token). The “like” words will have the same embedding. So how will the attention know which one is the right to understand the right relationship?</blockquote><p>Indeed, the index already tells the position of each token. But we need to group them, and how can we do it?</p><p>The way the paper does it is simple: sum!</p><pre>input_cat = embedding_cat + words.index(cat)</pre><p>Of course, this gives rise to many problems: sum explosions (can be solved with normalization) and poor positional relationships (the paper presents an encoding with sine and cosine).</p><p><strong>What does the paper propose?</strong></p><p>The paper introduces positional encoding using <strong>sine </strong>and <strong>cosine </strong>functions of different frequencies.</p><p>The idea is to generate a unique encoding for each position that the model can use to infer order and relative distance between tokens, <strong><em>even for the same words.</em></strong></p><p>The positional encoding is defined in this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*5ewEAy1ZQHEqjETdVD0R_w.png" /></figure><p>Where <strong><em>pos </em></strong>is the index of each token in the sentence, and <strong><em>i </em></strong>is the index of the embedding dimension. I will show an implementation after to make it clearer.</p><p>This positional encoding maps the index of the token in the sentence to a sinusoid output with different frequencies according to its position. This allows the model to encode the relative and absolute positions of tokens in a continuous and differentiable way.</p><p>And the good point here is that, no matter the size of the sentence,<strong> the positional encoding will always be different</strong> from each position, and also <strong>it will always be between 0 and 1</strong>, avoiding any type of explosions due to the sum.</p><p>At first, it may look scary, but let’s understand it well with an example:</p><p>First, let’s create the embeddings of some words:</p><pre>sentence = &quot;I like being like this&quot;<br>words = sentence.split(&quot; &quot;) #output: [&#39;I&#39;, &#39;like&#39;, &#39;being&#39;, &#39;like&#39;, &#39;this&#39;]<br><br>#we need to create a dictionary with unique IDs for each word<br>word2idx = {word: idx for idx, word in enumerate(set(words))}<br><br>embedding_dim = 8 #you can choose the size actually<br>embedding_table = np.random.rand(len(word2idx), embedding_dim)<br><br>print(word2idx)<br>for word, idx in word2idx.items():<br>    print(f&quot;{word}: {embedding_table[idx]}&quot;)<br><br># now, for each word we have an unique embedding:<br>&quot;&quot;&quot;<br>word2idx: {&#39;being&#39;: 0, &#39;like&#39;: 1, &#39;I&#39;: 2, &#39;this&#39;: 3}<br>being: [0.37454012 0.95071431 0.73199394 0.59865848]<br>like: [0.15601864 0.15599452 0.05808361 0.86617615]<br>I: [0.60111501 0.70807258 0.02058449 0.96990985]<br>this: [0.83244264 0.21233911 0.18182497 0.18340451]<br>&quot;&quot;&quot;</pre><p>To generate our final embeddings, we can make:</p><pre>embeddings = [embedding_table[word2idx[i]] for i in words]<br><br>for word, emb in zip(words, embeddings):<br>    print(f&quot;{word} -&gt; {emb}&quot;)<br><br># and now, the embeddings for our words<br>&quot;&quot;&quot;<br>I -&gt; [0.60111501 0.70807258 0.02058449 0.96990985]<br>like -&gt; [0.15601864 0.15599452 0.05808361 0.86617615]<br>being -&gt; [0.37454012 0.95071431 0.73199394 0.59865848]<br>like -&gt; [0.15601864 0.15599452 0.05808361 0.86617615]<br>this -&gt; [0.83244264 0.21233911 0.18182497 0.18340451]<br>&quot;&quot;&quot;</pre><p>Now, implementing the function shown on the paper and generating the positions:</p><pre>def positional_encoding(max_len, d_model):<br>    pe = np.zeros((max_len, d_model))<br>    for pos in range(max_len):<br>        for i in range(0, d_model, 2):<br>            pe[pos, i] = np.sin(pos / (10000 ** ((2 * i)/d_model)))<br>            if i + 1 &lt; d_model:<br>                pe[pos, i + 1] = np.cos(pos / (10000 ** ((2 * i)/d_model)))<br>    return pe<br><br>pos_enc = positional_encoding(len(words), embedding_dim)<br><br># notice that there is no randominess in this operation<br># the positional encoding will be always the same<br><br>&quot;&quot;&quot;<br>array([[ 0.00000000e+00,  1.00000000e+00,  0.00000000e+00, 1.00000000e+00],<br>       [ 8.41470985e-01,  5.40302306e-01,  9.99999998e-05, 9.99999995e-01],<br>       [ 9.09297427e-01, -4.16146837e-01,  1.99999999e-04, 9.99999980e-01],<br>       [ 1.41120008e-01, -9.89992497e-01,  2.99999995e-04, 9.99999955e-01],<br>       [-7.56802495e-01, -6.53643621e-01,  3.99999989e-04, 9.99999920e-01]])<br>&quot;&quot;&quot;</pre><p>Now, as the paper shows, let’s sum all together:</p><pre>encoded_input = embeddings + pos_enc<br><br>for i, word in enumerate(words):<br>    print(f&quot;{word} -&gt; embedding: {embeddings[i]}, pos_enc: {pos_enc[i]}, final: {encoded_input[i]}&quot;)<br><br>&quot;&quot;&quot;<br>I -&gt; final: [0.60111501 1.70807258 0.02058449 1.96990985]<br>like -&gt; final: [0.99748963 0.69629683 0.05818361 1.86617614]<br>being -&gt; final: [1.28383755 0.53456747 0.73219394 1.59865846]<br>like -&gt; final: [ 0.29713865 -0.83399798  0.05838361  1.8661761 ]<br>this -&gt; final: [ 0.07564015 -0.44130451  0.18222497  1.18340443]<br>&quot;&quot;&quot;<br><br>#and notice that for the both words &quot;like&quot;, the final embedding is different<br>#accordingly to their position.</pre><p><strong>2. The Transformer Block</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*_2nZ-V72e8EjSGay0Z7KwQ.png" /></figure><p>The next step is to use the multi-head attention mechanism we already studied above and, after that, add &amp; normalize the output of the multi-head attention with its input.</p><blockquote>Well, why this step of add and normalize?</blockquote><blockquote>The “Add” step is a already known technique named “residual connection” (widely known as its use in the Resnet Network). It Helps gradients flow better during backpropagation (reduces vanishing gradients).</blockquote><blockquote>The “Norm” step is a layer normalization, and it is a well known technique to stabilize the activations (reduces internal covariate shift), producing less sensitivity to weight initialization, and therefore, faster convergence.</blockquote><p>Using the output of this operation, we simply input it into a feed-forward network and do the same add&amp;normalize operation.</p><p>Let’s implement the Transformer Block:</p><pre>class TransformerBlock(nn.Module):<br>    def __init__(self, embed_dim, num_heads, ff_dim):<br>        super(TransformerBlock, self).__init__()<br>        self.attention = MultiHeadSelfAttention(embed_dim, num_heads)<br>        self.norm1 = nn.LayerNorm(embed_dim)<br>        self.norm2 = nn.LayerNorm(embed_dim)<br>        self.ff = nn.Sequential(<br>            nn.Linear(embed_dim, ff_dim),<br>            nn.ReLU(),<br>            nn.Linear(ff_dim, embed_dim)<br>        )<br>    <br>    def forward(self, x):<br>        #first layer<br>        attn_out, attn_weights = self.attention(x) #getting the output of the attention<br>        x = self.norm1(x + attn_out) #doing the add&amp;norm operation<br>        <br>        #second layer<br>        ff_out = self.ff(x) #using the feed-forward network<br>        x = self.norm2(x + self.dropout(ff_out))#doing the add&amp;norm operation<br>        return x, attn_weights</pre><p>Nice! We have the structure of our Transformer Encoder!</p><p><strong>Creating a BERT from the Transformer Encoder</strong></p><p>Now that we have our encoder capable of creating meaningful embeddings, we can add a classification layer at the end of the encoder to create a BERT, in other words, a classifier using the Transformer Encoder.</p><p>As an example of performance, I am going to train a BERT architecture using the <a href="https://www.kaggle.com/datasets/thedevastator/hate-speech-and-offensive-language-detection">Hate Speech and Offensive Language Detection</a> dataset on Kaggle, with the objective of, given the input as Twitter sentences, classify them into offensive speech or not.</p><p>You can check the full implementation here: <a href="https://www.kaggle.com/code/matheusparracho/bert-attentionmechanism-hatespeechdataset">https://www.kaggle.com/code/matheusparracho/bert-attentionmechanism-hatespeechdataset</a></p><p>The objective of this study is not to achieve the best performance of all, but just to show that the model can learn and get some meaningful patterns. Therefore, I did not explore a lot the data or take any data exploration steps. I just trained with a balanced label set, and that is it.</p><p>The performance can be seen here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*G-qAf62udDmxyoGOn5EeHg.png" /><figcaption>Results on training with the hate-speech dataset</figcaption></figure><p>It is very clear that the model was able to learn by its monotonous loss decay after each epoch and the stable F1 and Accuracy performance.</p><h3>Creating an Attention Decoder (GPT)</h3><p>The right part of the transformer is called GPT. The objective here is to function as an autoregressive model, which means it generates the next token in a sequence based solely on the previously generated tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*7qP89Z59HjlD8SUAm0TYig.png" /></figure><p>The concept of the GPT is almost the same as the BERT, the key difference is the <strong>causality</strong>. GPT is a causal (autoregressive) model, meaning it can only access previous tokens when making predictions.</p><p>To make this causality possible, we implement the <strong>Masked Multi-Head Attention </strong>to avoid the model from “seeing” future words during training or inference. This directional attention is what allows GPT to generate coherent sequences one token at a time.</p><p><strong>Implementing the Masked Multi-Head Attention:</strong></p><p>It is just a Multi-head attention with a “masked layer”: we generate a triangular matrix to be the mask and operates into the attention map. Let’s understand step-by-step:</p><p>Taking as an example the following input:</p><pre>batch_size = 1<br>num_nodes = 3<br>d_model = 6<br><br>X = torch.randn(batch_size, num_nodes, d_model)  # shape: [1, 3, 6]</pre><p>Now we are going to implement the CausalSelfAttention, the actually only difference in GPT:</p><pre>class CausalSelfAttention(nn.Module):<br>    def __init__(self, embed_dim, num_heads):<br>        super().__init__()<br>        assert embed_dim % num_heads == 0, &quot;embed_dim must be divisible by num_heads&quot;<br><br>        #basic sizes<br>        self.embed_dim = embed_dim<br>        self.num_heads = num_heads<br>        self.head_dim = embed_dim // num_heads<br>        self.scale = math.sqrt(self.head_dim)<br><br>        self.q_linear = nn.Linear(embed_dim, embed_dim)<br>        self.k_linear = nn.Linear(embed_dim, embed_dim)<br>        self.v_linear = nn.Linear(embed_dim, embed_dim)<br><br>        self.out_linear = nn.Linear(embed_dim, embed_dim)<br><br>        #upper-triangular causal mask once.<br>        self.mask = torch.tril(torch.ones(num_nodes, num_nodes)).unsqueeze(0).unsqueeze(0)<br><br>        &quot;&quot;&quot;<br><br>        this torch.trill will generate the mask in triangular format <br>        [1, 0, 0<br>         1, 1, 0<br>         1, 1, 1]<br><br>        &quot;&quot;&quot;<br></pre><pre>def forward(self, x: torch.Tensor, *, return_attn: bool = False):<br>        <br>        batch_size, seq_len, _ = x.size()<br><br>        # 1) project inputs to Q, K, V<br>        Q = self.q_linear(x)<br>        K = self.k_linear(x)<br>        V = self.v_linear(x)<br><br>        # 2) reshape for multi-head: (batch, heads, seq, head_dim)<br>        Q = Q.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)<br>        K = K.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)<br>        V = V.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)<br><br>        # 3) scaled dot-product attention<br>        scores = torch.matmul(Q, K.transpose(-2, -1)) / self.scale  # (B, h, S, S)<br><br>        ### HERE IS THE ACTUAL DIFFERENCE ###<br>        # 4) apply causal mask<br>        scores = scores.masked_fill(self.mask == 0, float(&quot;-inf&quot;))<br><br>        &quot;&quot;&quot;<br>        the output will be in format:<br><br>        tensor([[[[-0.8683,    -inf,    -inf],<br>                  [-0.4707, -0.2679,    -inf],<br>                  [-2.0261, -0.4630, -0.4329]],<br>        <br>                 [[ 0.5623,    -inf,    -inf],<br>                  [-0.5046,  0.2130,    -inf],<br>                  [ 0.5423, -0.2369, -0.3398]],<br>        <br>                 [[ 0.7284,    -inf,    -inf],<br>                  [ 0.1550,  0.3851,    -inf],<br>                  [-0.1279,  0.6354, -0.8240]]]], grad_fn=&lt;MaskedFillBackward0&gt;)<br><br><br>        so what actually is happening here?<br>        masked_fill sets all positions in the attention scores matrix <br>        that correspond to &#39;future&#39; tokens to -inf, so that after the softmax step, <br>        these positions become zero probability.<br>        &quot;&quot;&quot;<br><br>        # 5) softmax<br>        attn = F.softmax(scores, dim=-1)<br><br>        # 6) weighted sum of values<br>        context = torch.matmul(attn, V)                             # (B, h, S, D)<br>        context = context.transpose(1, 2).contiguous()              # (B, S, h, D)<br>        context = context.view(batch_size, seq_len, self.embed_dim) # merge heads<br><br>        # 7) final projection<br>        out = self.out_linear(context)<br><br>        return (out, attn) if return_attn else out</pre><p>Nice! Now that we have our Masked Multi-Head Attention, we are going to build the GPT block from the paper:</p><pre>class GPTBlock(nn.Module):<br>    def __init__(self, embed_dim, num_heads, ff_dim, dropout):<br>        super().__init__()<br>        self.ln1 = nn.LayerNorm(embed_dim)<br>        self.sa  = CausalSelfAttention(embed_dim, num_heads, dropout)<br>        self.ln2 = nn.LayerNorm(embed_dim)<br>        self.ff  = nn.Sequential(<br>            nn.Linear(embed_dim, ff_dim),<br>            nn.GELU(),<br>            nn.Linear(ff_dim, embed_dim),<br>            nn.Dropout(dropout)<br>        )<br>    def forward(self, x):<br>        x = x + self.sa(self.ln1(x))<br>        x = x + self.ff(self.ln2(x))<br>        return x</pre><p>Now grouping all together:</p><pre>class MiniGPT(nn.Module):<br>    def __init__(self, vocab, embed_dim, num_heads, ff_dim, layers, dropout):<br>        super().__init__()<br>        self.tok_emb = nn.Embedding(vocab, embed_dim)<br>        self.pos_emb = nn.Embedding(SEQ_LEN, embed_dim)<br>        self.drop    = nn.Dropout(dropout)<br>        self.blocks  = nn.ModuleList([<br>            GPTBlock(embed_dim, num_heads, ff_dim, dropout) for _ in range(layers)<br>        ])<br>        self.ln_f = nn.LayerNorm(embed_dim)<br>        self.head = nn.Linear(embed_dim, vocab, bias=False)  # weight‑tying optional<br>    def forward(self, idx):<br>        B, T = idx.shape<br>        pos  = torch.arange(T, device=idx.device).unsqueeze(0)<br>        x = self.drop(self.tok_emb(idx) + self.pos_emb(pos))<br>        for blk in self.blocks:<br>            x = blk(x)<br>        x = self.ln_f(x)<br>        return self.head(x)</pre><p>Awesome! Now, we are going to train a GPT to create Shakespeare-like sentences. For this, I am going to use one of the Shakespeare datasets that group a whole story and can be found <a href="https://medium.com/raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt">here</a>.</p><p>The whole pipeline of dataset preparation, vocabulary creation and etc can be seen in my Kaggle Notebook here:<br><a href="https://www.kaggle.com/code/matheusparracho/gpt-shakespeare">https://www.kaggle.com/code/matheusparracho/gpt-shakespeare</a></p><p>In the end, the model was able to generate some reasonable texts. Here is the output of the model using “ROMEO” as the input prompt:</p><pre>ROMEO:<br>Virtue is bold, and full of true times,<br>Which now the proud I&#39;ll cup of holy root<br>Upon my ears and most arm yourself.<br>What, dost thou withdraw out my company?<br>And company with conscience and heart<br>To God, thy duke and bid behavior:<br>By whom I boot, my lord, here mistake<br>This business for your lordship.<br><br>LORD WILLOUGHBY:<br>Why, my lord,--<br><br>BUCKINGHAM:<br>Hast thou spoken Edward?<br><br>RIVERS:<br>My royal seal&#39;d</pre><h3>Conclusion</h3><p>In this article, we studied the core of the Transformers models: the attention mechanism. With this, we could create models that can model high-dimensional data and their relationships.</p><p>If you have any thoughts or questions, feel free to share them in the comments. Thanks for reading, and see you in the next one!</p><h3>Bonus: A Self-Diary</h3><p>In parallel with studying the foundations of attention, I am also studying the transistor models for amplifiers.</p><blockquote>Okay, and?…</blockquote><p>Studying the models that explain the principles of a transistor is well-defined, everyone knows how it works, and it explains the behaviour of a transistor pretty well.</p><p>On the other hand, everything here is not universal. It just works! In my opinion, this differentiates between what is an invention and what is discovered. The transistor principle is based on the PN junction of the electrons&#39; behaviour: <strong>nature has defined it</strong>. Here is kinda different, you know what I mean? We are inventing ways of representing data, their relationships, and everything. Everything is an open gate, and we can invent new things, whereas the transistor will always work in that way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deed149487cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating High-Resolution Images with PROGANs — Architecture Implementation and Analysis]]></title>
            <link>https://medium.com/@mathparracho/generating-high-resolution-images-with-progans-architecture-implementation-and-analysis-98dfda26a06d?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/98dfda26a06d</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[gans]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 03:11:26 GMT</pubDate>
            <atom:updated>2025-04-06T03:16:24.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generating High-Resolution Images with PROGANs — Architecture Implementation and Analysis</h3><p>In one of the articles of my “Generative Intuition and Practice” series, we explored ways to train and stabilize the training of GANs. You can check it by clicking <a href="https://medium.com/@mathparracho/generative-adversarial-networks-gans-wgans-wgans-gp-generative-intuition-practice-24cb2dd43ed9"><strong>here</strong></a><strong>.</strong></p><p>We noticed that generating reasonable face structures with GANs, WGANs, and WGANs-GP was possible. But what if we wanted more resolution and more image fidelity? That is what NVIDIA researchers looked for in the <a href="https://arxiv.org/pdf/1710.10196">PROGAN paper</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*6VjMXCnr1gbd-PQYchkYyQ.png" /><figcaption>High Resolution images Generated from the ProGan. Source: NVIDIA</figcaption></figure><p>In this article, we are going to analyze and implement the ideas proposed by the researchers with all the code available here.</p><blockquote><em>Keep in mind that, to achieve these image qualities, the NVIDIA researchers used 2 NVIDIA Tesla P100 for 4 to 6 days. So, as you might imagine, I did not do that otherwise I would kill my laptop (yes I have a laptop). I trained until lower resolutions!</em></blockquote><p>The complete code showed analysed in this article is <a href="https://www.kaggle.com/code/matheusparracho/progan-architecture-implementation-and-analysis">here</a> on Kaggle.</p><p>So, let’s start!</p><h3>The Dataset Studied</h3><p>The dataset used by the researchers is the CelebA, a high-definition dataset of faces. It also provides some annotations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPeLE50WMU14nxsPyAEZMQ.jpeg" /><figcaption>CelebA images with annotations</figcaption></figure><p>It consists of images of more than 200k images from celebrities. It can be accessed directly via Pytorch API via:</p><pre>import torchvision.datasets as datasets<br><br>dataset = datasets.CelebA(<br>        root=&#39;./&#39;,<br>        download=True<br>    )</pre><p>Or, if you want to download by yourself, you can access it directly via the <a href="https://mmlab.ie.cuhk.edu.hk/projects/CelebA.html">website</a>.</p><h3>The Progressive Growing</h3><p>One of the key features the researchers implemented is the concept of progressive training:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*hfcKbyQhfKA3vNFNBvxMDw.png" /><figcaption>Source: NVIDIA</figcaption></figure><p>This means that the training will start with images with a dimension of only 8×8, 16×16, …, up to 1024×1024.</p><blockquote>Interesting. So the idea proposed is that the model firstly will understand the low-level features like shapes and structures, to then, slowly, understand the high-frequency (detailed) features.</blockquote><p>So, to start implementing this idea, I created a function just to deal with this resize pre-processing part:</p><pre>def get_loader(image_size):<br>    transform = transforms.Compose(<br>        [<br>            transforms.Resize((image_size, image_size)), #here is the key<br>            transforms.RandomHorizontalFlip(p=0.5),<br>            transforms.ToTensor(),<br>            transforms.Normalize([0.5] * CHANNELS_IMG, [0.5] * CHANNELS_IMG),<br>        ]<br>    )<br>    batch_size = BATCH_SIZES[image_size]<br>    dataset = datasets.CelebA(<br>        root=&#39;./&#39;,<br>        split=&#39;train&#39;,<br>        transform=transform,<br>        download=True<br>    )<br><br>    # training with only 50% of the dataset otherwise it is going to take too long<br>    num_samples = int(1 * len(dataset))<br>    indices = np.random.choice(len(dataset), num_samples, replace=False)<br>    subset = Subset(dataset, indices)<br><br>    loader = DataLoader(<br>        subset,<br>        batch_size=batch_size,<br>        shuffle=True,<br>        num_workers=NUM_WORKERS,<br>        pin_memory=True,<br>    )<br>    return loader</pre><p>The idea here is that we prepared a function just to deal with these different “resolution parts” of the training.</p><blockquote>Okay, right now we just understand how the model will be trained, but how the architecture is built to receive these different resolution images? Before going deeply into the implementation, we need to see some techniques proposed:</blockquote><h3>Pixel Normalization</h3><p>Before going deeply into the architecture, we need to see also a technique proposed by the researchers: Pixel normalization.</p><p>With the idea of stabilizing the generator training, the authors propose a normalization per pixel, maintaining the features vector normalized and avoiding gradient explosions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*XvGSR5kVJWt9U6UK-Cv4uw.png" /></figure><p>This can be implemented like this:</p><pre>class PixelNorm(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br><br>    def forward(self, x, epsilon=1e-8):<br>        return x / torch.sqrt(torch.mean(x ** 2, dim=1, keepdim=True) + epsilon)</pre><h3>Mini-Batch Standard Deviation</h3><p>The objective of this technique is to help the discriminator detect the lack of diversity in the generated samples.</p><p>A layer is added to the discriminator that computes the standard deviation across the mini-batch and concatenates it as an extra feature.</p><p>This can be implemented like this:</p><pre>    def minibatch_std(self, x):<br>        batch_statistics = (<br>            torch.std(x, dim=0).mean().repeat(x.shape[0], 1, x.shape[2], x.shape[3])<br>        )<br>        # we take the std for each example (across all channels, and pixels) then we repeat it<br>        # for a single channel and concatenate it with the image. In this way the discriminator<br>        # will get information about the variation in the batch/image<br>        return torch.cat([x, batch_statistics], dim=1)</pre><p>This encourages the generator to produce more diverse images since the discriminator will penalize overly similar outputs.</p><h3>Equalized Learning Rate</h3><p>In traditional neural networks, you usually need to specific weight initialization schemes (like Xavier or He initialization) to keep the variance of activations stable across layers.</p><p>In ProGAN, Equalized Learning Rate (ELR) is introduced as a dynamic alternative: instead of carefully initializing the weights, you initialize them with a standard normal distribution, and then scale them at runtime during the forward pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*ZrlL8WMqY8iX9ZGbbpxnKw.png" /></figure><p>This can be implemented in a Convolutional block in this way</p><pre>class WSConv2d(nn.Module):<br>    &quot;&quot;&quot;<br>    inspired and looked at:<br>    https://github.com/nvnbny/progressive_growing_of_gans/blob/master/modelUtils.py<br>    &quot;&quot;&quot;<br><br>    def __init__(<br>        self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, gain=2<br>    ):<br>        super(WSConv2d, self).__init__()<br>        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)<br>        self.scale = (gain / (in_channels * (kernel_size ** 2))) ** 0.5<br>        self.bias = self.conv.bias<br>        self.conv.bias = None<br><br>        #initialize conv layer<br>        nn.init.normal_(self.conv.weight)<br>        nn.init.zeros_(self.bias)<br><br>    def forward(self, x):<br>        #scaling each time during the forward pass<br>        return self.conv(x * self.scale) + self.bias.view(1, self.bias.shape[0], 1, 1)</pre><h3>The Fade-in Transition</h3><p>When a new resolution is introduced, a fade-in mechanism is used to smoothly transition from the previous resolution to the new one. This is controlled by a blending parameter α ∈ [0,1]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*5hUbPbJeJqosFU10w6P_Jw.png" /></figure><p>Using this approach, we can introduce two different concepts: the “fading epochs”, and the “stabilizing epochs”. That means the epochs that the gradient will have to deal with the upscaled resolution (fading epochs), and other epochs that the gradient only has to deal with the same resolution (stabilizing epochs).</p><p>This is going to be implemented in details when we talk about the generator:</p><h3>The Progressive Architecture — Generator</h3><p>Okay, now that we studied the techniques proposed, let’s understand the detailed architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*R41L_Kjx10a3Mp9vvr8PJw.png" /></figure><p>Let’s understand it step by step:</p><ol><li>Sampled from a distribution (e.g., Gaussian) and fed into the network.</li><li>This latent vector is first passed through a dense (fully connected) layer that reshapes it into an initial <em>4×4×channels</em> tensor.</li><li>Convolutional layers with 3×3 filters are applied. After each convolution, a Leaky ReLU activation is used, and Pixelwise normalization replaces traditional batch normalization to improve training stability.</li><li>After training on 4×4 images, the resolution is doubled using an Upscale 2x block (using nearest neighbor upsampling with no learnable weights). New convolutional layers are added after each upscaling step to process the higher resolution (8×8, 16×16, …, k×k) with the fade-in technique.</li></ol><p>The convolutional layer (blue), leaky ReLu activation (yellow), and the PixelNormalization (pink) can be write in just one Generator Block:</p><pre>class GenBlock(nn.Module):<br>    def __init__(self, in_channels, out_channels):<br>        super(GenBlock, self).__init__()<br>        self.conv1 = WSConv2d(in_channels, out_channels, 3, 1, 1)<br>        self.conv2 = WSConv2d(out_channels, out_channels, 3, 1, 1)<br>        self.leaky = nn.LeakyReLU(0.2)<br>        self.pixelnorm = PixelNorm()<br><br>    def forward(self, x):<br>        x = self.conv1(x)<br>        x = self.pixelnorm(x)<br>        x = self.leaky(x)<br>        x = self.conv2(x)<br>        x = self.pixelnorm(x)<br>        x = self.leaky(x)<br>        return x</pre><p>Now let’s group for the whole generator:</p><pre>class Generator(nn.Module):<br>    def __init__(self, z_dim, in_channels, img_channels=3, channels_list=[512,512,256,128,64,32,16]):<br>        super(Generator, self).__init__()<br><br>        self.initial = nn.Sequential(<br>            PixelNorm(),<br>            nn.ConvTranspose2d(z_dim, in_channels, 4, 1, 0),<br>            nn.LeakyReLU(0.2),<br>            WSConv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1),<br>            nn.LeakyReLU(0.2),<br>            PixelNorm(),<br>        )<br><br>        self.initial_rgb = WSConv2d(in_channels, img_channels, kernel_size=1, stride=1, padding=0)<br>        self.prog_blocks = nn.ModuleList()<br>        self.rgb_layers = nn.ModuleList([self.initial_rgb])<br>        self.leaky = nn.LeakyReLU(0.2)<br>        self.in_channels = in_channels<br><br>        # creating the blocks that we will need during the forward step<br>        for out_channels in channels_list:<br>            block = GenBlock(self.in_channels, out_channels).to(DEVICE)<br>            self.prog_blocks.append(block)<br>            rgb_layer = WSConv2d(out_channels, CHANNELS_IMG, kernel_size=1, stride=1, padding=0).to(DEVICE)<br>            self.rgb_layers.append(rgb_layer)<br>            self.in_channels = out_channels<br><br>    def forward(self, x, steps, alpha): #&quot;steps&quot; will determine in which part of the network we are at the moment of the iteration<br>        ### initial fc layer<br>        out = self.initial(x)<br><br>        if steps == 0:<br>            out = self.rgb_layers[0](out)<br>            out = torch.tanh(out)<br>            return out<br><br>        for step in range(steps):<br>            out_less1 = out<br>            out = F.interpolate(out, scale_factor=2, mode=&#39;nearest&#39;)<br>            out = self.prog_blocks[step](out)<br><br>        # alpha fade-in implementation<br>        out_path1 = self.rgb_layers[steps](out) #same resolution<br>        out_path2 = F.interpolate(self.rgb_layers[steps - 1](out_less1), scale_factor=2, mode=&#39;nearest&#39;) #upscaled resolution<br>        out = torch.tanh(alpha * out_path1 + (1 - alpha) * out_path2)<br>        return out</pre><h3>The Progressive Architecture — Discriminator</h3><p>To be able to process the images from the generator in a progressive scale, the discriminator should be able to also get these dynamic images and classify it into real or fake.</p><p>The discriminator follows the progressive structure of the generator, but in reverse. As the generator increases the resolution step-by-step, the discriminator progressively reduces it during training:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*jphuPmUjJD5g0gHU7iD0Cg.png" /></figure><ol><li>The discriminator receives an image <em>x</em> of resolution <em>k×k</em>, either real (from the dataset) or fake (generated).</li><li><strong>From-RGB Layer</strong>: The image is first passed through a 1×1 convolution (green block), to convert the 3-channel RGB input into 1-channel feature maps (dimensionality reduction). This is done at every resolution scale.</li><li><strong>Fade-In Transition:</strong> The same blending technique used in the Generator is also used in Discriminator. To avoid abrupt transition during training, the resolution transition is described by a blending mechanism:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*FhznjvmrZeCo2-71NTJhhg.png" /></figure><p>4. Then, we have the usual 3x3 convolutional kernels within a “Discriminator Block” and, in the last layer, a MiniBatch STD is applied.</p><p>In the same way as the generator, we can create the discriminator block:</p><pre>class DiscBlock(nn.Module):<br>    def __init__(self, in_channels, out_channels):<br>        super(DiscBlock, self).__init__()<br>        self.conv1 = WSConv2d(in_channels, in_channels, 3, 1, 1)<br>        self.conv2 = WSConv2d(in_channels, out_channels, 3, 1, 1)<br>        self.leaky = nn.LeakyReLU(0.2)<br>        self.avg_pool = nn.AvgPool2d(2)<br>        self.dropout = nn.Dropout(0.2)<br><br>    def forward(self, x):<br>        x = self.leaky(self.conv1(x))<br>        x = self.leaky(self.dropout(self.conv2(x)))<br>        x = self.avg_pool(x)<br>        return x</pre><p>And we are going to build the Discriminator pipeline thinking in a “mirrored” version of the Generator:</p><pre>class Discriminator(nn.Module):<br>    def __init__(self, in_channels, img_channels=3, channels_list=[512,512,256,128,64,32,16]):<br>        super(Discriminator, self).__init__()<br>        self.prog_blocks = nn.ModuleList()<br>        self.rgb_layers = nn.ModuleList()<br>        self.leaky = nn.LeakyReLU(0.2)<br>        self.in_channels = in_channels<br><br>        self.initial_rgb = WSConv2d(img_channels, in_channels, kernel_size=1, stride=1, padding=0)<br>        self.rgb_layers.append(self.initial_rgb)<br><br>        self.initial_conv = nn.Sequential(<br>            WSConv2d(in_channels + 1, in_channels, 3, 1, 1),<br>            nn.LeakyReLU(0.2),<br>            WSConv2d(in_channels, in_channels, 4, 1, 0),<br>            nn.LeakyReLU(0.2),<br>            nn.Flatten(),<br>            nn.Linear(in_channels, 1),<br>        )<br><br>        for out_channels in channels_list:<br>            block = DiscBlock(out_channels, self.in_channels).to(DEVICE)<br>            self.prog_blocks.append(block)<br>            rgb_layer = WSConv2d(CHANNELS_IMG, out_channels, kernel_size=1, stride=1, padding=0).to(DEVICE)<br>            self.rgb_layers.append(rgb_layer)<br>            self.in_channels = out_channels<br><br>    def minibatch_std(self, x):<br>        batch_statistics = (<br>            torch.std(x, dim=0).mean().repeat(x.shape[0], 1, x.shape[2], x.shape[3])<br>        )<br>        return torch.cat([x, batch_statistics], dim=1)<br>    <br>    def forward(self, x, steps, alpha):# steps are counted decreasing<br>        if steps == 0:<br>            x = self.leaky(self.rgb_layers[0](x))<br>            x = self.minibatch_std(x)<br>            x = self.initial_conv(x)<br>            return x<br><br>        # actual rgb layer<br>        x_new = self.leaky(self.rgb_layers[steps](x)) #ex 8x8<br>        x_new = self.prog_blocks[steps - 1](x_new) #4x4 bcs has avg pool in block<br><br>        # previous rgb layer<br>        x_old = F.avg_pool2d(x, kernel_size=2)<br>        x_old = self.leaky(self.rgb_layers[steps - 1](x_old))<br><br>        # alpha fade-in<br>        x = alpha * x_new + (1 - alpha) * x_old<br><br>        # all previous layer<br>        for step in range(steps - 1, 0, -1):<br>            x = self.prog_blocks[step - 1](x)<br><br>        x = self.minibatch_std(x)<br>        x = self.initial_conv(x)<br>        return x</pre><h3>Training Pipeline</h3><p>As studied in the previous article <a href="https://medium.com/@mathparracho/generative-adversarial-networks-gans-wgans-wgans-gp-generative-intuition-practice-24cb2dd43ed9"><strong>here</strong></a>, we are going to use the WGANs-GP structure to build our PROGAN pipeline:</p><p>One gradient penalty function to the “GP” apprach:</p><pre>def gradient_penalty(critic, real, fake, steps, alpha, device=&quot;cpu&quot;):<br>    batch_size, C, H, W = real.shape<br>    beta = torch.rand((batch_size, 1, 1, 1), device=device)<br>    beta = beta.expand_as(real)<br>    interpolated_images = real * beta + fake.detach() * (1 - beta)<br>    interpolated_images.requires_grad_(True)<br>    mixed_scores = critic(interpolated_images, steps, alpha)<br>    gradient = torch.autograd.grad(<br>        inputs=interpolated_images,<br>        outputs=mixed_scores,<br>        grad_outputs=torch.ones_like(mixed_scores),<br>        create_graph=True,<br>        retain_graph=True,<br>    )[0]<br>    gradient = gradient.view(gradient.shape[0], -1)<br>    gradient_norm = gradient.norm(2, dim=1)<br>    gp = torch.mean((gradient_norm - 1) ** 2)<br>    return gp</pre><p>And the optimization step:</p><pre>def train_fn(<br>    critic,<br>    gen,<br>    loader,<br>    dataset,<br>    step,<br>    alpha, <br>    opt_critic,<br>    opt_gen,<br>    scaler_gen,<br>    scaler_critic,<br>):<br>    loop = tqdm(loader, leave=True)<br>    for batch_idx, (real, _) in enumerate(loop):<br>        real = real.to(DEVICE)<br>        cur_batch_size = real.shape[0]<br><br>        noise = torch.randn(cur_batch_size, Z_DIM, 1, 1).to(DEVICE)<br><br>        #training discriminator (critic)<br>        with torch.cuda.amp.autocast():<br>            fake = gen(noise, step, alpha)<br>            critic_real = critic(real, step, alpha)<br>            critic_fake = critic(fake.detach(), step, alpha)<br>            gp = gradient_penalty(critic, real, fake, step, alpha, device=DEVICE)<br>            <br>            #loss wgan<br>            &quot;&quot;&quot;<br>            loss_critic = (<br>                -(torch.mean(critic_real) - torch.mean(critic_fake)) + LAMBDA_GP * gp<br>            )<br>            &quot;&quot;&quot;<br><br>            #loss wgan-gp<br>            loss_critic = (<br>                -(torch.mean(critic_real) - torch.mean(critic_fake))<br>                + LAMBDA_GP * gp<br>                + (0.001 * torch.mean(critic_real ** 2))<br>            )<br><br>        critic.zero_grad()<br>        scaler_critic.scale(loss_critic).backward()<br>        scaler_critic.step(opt_critic)<br>        scaler_critic.update()<br><br>        # train generator<br>        with torch.cuda.amp.autocast():<br>            fake = gen(noise, step, alpha)<br>            gen_fake = critic(fake, step, alpha)<br>            loss_gen = -torch.mean(gen_fake)<br><br>        gen.zero_grad()<br>        scaler_gen.scale(loss_gen).backward()<br>        scaler_gen.step(opt_gen)<br>        scaler_gen.update()</pre><p>And the main loop:</p><pre>def main():<br>    channels_list = [out_channels for out_channels in channels.values()]<br>    gen = Generator(Z_DIM, channels[4], img_channels=CHANNELS_IMG, channels_list=channels_list).to(DEVICE)<br>    critic = Discriminator(channels[4], img_channels=CHANNELS_IMG, channels_list=channels_list).to(DEVICE)<br>    gen_opt = optim.Adam(gen.parameters(), lr=LEARNING_RATE, betas=(0.0, 0.99))<br>    critic_opt = optim.Adam(critic.parameters(), lr=LEARNING_RATE, betas=(0.0, 0.99))<br><br>    scaler_gen = torch.cuda.amp.GradScaler()<br>    scaler_critic = torch.cuda.amp.GradScaler()<br><br>    for step, resolution in enumerate(resolutions):<br>        if step &gt; 0:<br>            gen.add_block(channels[resolution])<br>            critic.add_block(channels[resolution])<br><br>        loader = get_loader(resolution)<br>        dataset = loader.dataset<br>        print(f&quot;initializing trainig for {resolution}x{resolution}&quot;)<br><br>        fade_epochs, stabilize_epochs = PROGRESSIVE_EPOCHS[resolution]<br>        total_epochs = fade_epochs + stabilize_epochs<br><br>        for epoch in range(total_epochs):<br>            print(f&quot;epoch [{epoch+1}/{total_epochs}]&quot;)<br><br>            if epoch &lt; fade_epochs:<br>                alpha = epoch / fade_epochs<br>            else:<br>                alpha = 1<br><br>            train_fn(<br>                critic,<br>                gen,<br>                loader,<br>                dataset,<br>                step,<br>                alpha,<br>                critic_opt,<br>                gen_opt,<br>                scaler_gen,<br>                scaler_critic,<br>            )<br><br>        #saving models after each resolution<br>        torch.save(gen.state_dict(), f&quot;generator_{resolution}x{resolution}.pth&quot;)<br>        torch.save(critic.state_dict(), f&quot;discriminator_{resolution}x{resolution}.pth&quot;)</pre><h3>Training Results</h3><p>Ideally, we should expect this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*cqL2Fe_RclLp6oCKeXqmIQ.gif" /></figure><p>But, of course, as I do not have the power neither I want to burn my laptop, I just trained until <strong>256x256 resolution</strong> and with <strong>half of the data</strong> from CelebA. The results were worse, of course, but we can see the evolution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*zAim7fA0nQ4M634d.gif" /><figcaption>CelebA faces generated in my machine after aprox 18h of training from 4x4 images all up to 256x256.</figcaption></figure><p>If you want to check the full video iterating through the generated faced, check this video <a href="https://youtu.be/n2r7oYbp3Aw">here</a>.</p><h3>Conclusion</h3><p>It was interesting to study the different techniques authors used to address the challenges of training high-resolution generative models.</p><p>Each technique played a crucial role in improving the quality, and diversity of generated images. It was interesting to study the power these different and creative ways of dealing with the objective of producing high-quality images.</p><p>NVIDIA also developed the StyleGANs, an updated version of the PROGANs with some new concepts to improve training stability.</p><p>Thank you for reading until here! See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98dfda26a06d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training an Agent to play Flappy Bird! (DQN Modelling — Reinforcement Learning)]]></title>
            <link>https://medium.com/@mathparracho/training-an-agent-to-play-flappy-bird-dqn-modelling-reinforcement-learning-2cb16a9fa184?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cb16a9fa184</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 21:11:01 GMT</pubDate>
            <atom:updated>2025-03-27T21:11:01.357Z</atom:updated>
            <content:encoded><![CDATA[<h3>Training an Agent to play Flappy Bird! (DQN Modelling — Reinforcement Learning)</h3><p>We all know Flappy Bird, that old mobile game that has already taken some minutes of our lives. In this article, I am going to explain how to build a pipeline to train an RL model to play the game and go all way above 100 scores!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9ip-GUPj7jTc2tth9sz0Q.png" /><figcaption>Amazing art generated with the new OpenAI update for image generation</figcaption></figure><p>I am going to cover the mathematical foundations and all the pipelines using Pytorch to train and evaluate the model. In the end, the game will run like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoPHv1_gZp71oOsXOsTXJA.gif" /><figcaption>DQN model running on my machine +100 scores</figcaption></figure><p>All code is available at: <a href="https://www.kaggle.com/code/matheusparracho/flappybird-agent-deep-q-learning">https://www.kaggle.com/code/matheusparracho/flappybird-agent-deep-q-learning</a></p><p>In the end, I am going to show as a bonus the same pipeline (almost) running in different environments (games) and we are going to see how it goes.</p><h3>The Reinforcement Learning (RL) Paradigm</h3><p>In Machine Learning, we have <strong>three </strong>big paradigms/approaches: supervised learning, unsupervised learning, and reinforcement learning.</p><p>In my articles, we already implemented many of them using supervised and unsupervised learning. Now, it is time to study one of the biggest and oldest players: <strong>Reinforcement Learning</strong>.</p><p>At the core of Reinforcement Learning we find a <strong>Markov Decision Process</strong> <strong>(MDP)</strong>, a formal framework used to describe the interaction between the agent and the environment. An MDP is defined by a tuple <strong><em>(S,A,P,R,γ)</em></strong>, where:</p><ul><li><strong>S</strong>: a finite set of states.</li><li><strong>A</strong>: a finite set of actions</li><li><strong>P(s′∣s,a):</strong> the <strong>transition probability</strong> — the probability of moving to state s′ after taking action a in state s.</li><li><strong>R(s,a)</strong>: the expected reward received after taking action a in state s.</li><li><strong>γ∈[0,1]</strong>: the <strong>discount factor</strong>, controlling the importance of future rewards.</li></ul><p>The goal of the agent is to learn a <strong>policy <em>π:S→Δ(A)</em></strong>, where <strong><em>Δ(A)</em></strong> is the probability distribution over actions. The <strong>expected return</strong> at time step <em>t</em>, denoted by <strong><em>Gt</em>​</strong>, is the total discounted reward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*05sa58oWydwfa4nMT_nKzA.png" /></figure><p>This formulation allows the agent to <strong>give importance to immediate rewards more than distant ones</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*b39jbn8izLceCY3r9KgEHg.png" /><figcaption>Typical RL system: an agent takes actions in an environment, which is interpreted into a reward and a state representation, which are fed back to the agent.</figcaption></figure><blockquote>I like to use AREA51 to remember: (<strong>A</strong>ction<strong>R</strong>eward<strong>E</strong>nvironment<strong>A</strong>gent, the 51 you can ignore haha)</blockquote><p>There are many RL algorithms, each designed to optimize learning in different environments. We can, primarily, divide into 2 categories:</p><p><strong><em>Model-Based RL</em></strong></p><p>In Model-Based RL, the agent explicitly learns or is given a model of the environment. This model includes the transition function and the reward function.</p><p>Once the model is known or learned, the agent can simulate future trajectories and plan its actions by optimizing over predicted outcomes. A common planning method is Model Predictive Control (MPC).</p><p>A very common example is a chess AI that learns how the opponent usually plays. It builds a model of the opponent’s moves and plans several steps ahead before taking an action.</p><p><strong><em>In a nutshell, the model learns the rules and simulate outcomes before acting.</em></strong></p><p><strong><em>Model-Free RL</em></strong></p><p>In Model-Free RL, the agent does not learn a model of the environment. Instead, it directly learns a policy <strong><em>π(a|s)</em></strong> or value functions <strong><em>V(s)</em></strong>, <strong><em>Q(s,a)</em></strong> through trial-and-error interactions with the environment.</p><p>These methods usually require <strong>a lot more data</strong>, but they avoid the complexity of learning a good model.</p><p><strong><em>In a nutshell, the model learns by trial-and-error without trying to understand the rules.</em></strong></p><p>Inside the Model-Free RL, we find two other divisions:</p><p><strong><em>The value-based methods<br></em></strong>Where the paradigm is to have a value function that quantifies the reward, that means:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*FWHUUJlvVyvZtme_Jl9_9g.png" /></figure><p>For example, we have the Q-Learning, DQNs, and SARSA…</p><p><strong><em>The policy-based methods<br></em></strong>Where the paradigm is to directly determine the policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*1CJ_ddIVXuJQYz77Ox1Mvg.png" /></figure><p>For example, we have the REINFORCE, PPO, and TRPO…<br>I am not going to focus on details about policy-based methods in this article.</p><p>Observing the taxonomy of RL, we find this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*e8GOHtPxYv5dbwZLKTduXQ.png" /><figcaption>RL classifications and the technique we are going to use in red.</figcaption></figure><p>In our case, for Flappy Bird, I am going to use the Deep Q-Networks (DQN), which means a value-based method.</p><p>So let`s start understanding the key techniques to build our model:</p><h3>The State Value Function V(s)</h3><p>The V(s) function represents the “snapshot of the environment”. It simply gets the state <strong><em>s</em></strong> of the the environment and maps it into a real number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*LcG6W_DjhL3SpDFbP6ypvg.png" /></figure><p>In other words, it tells us “how good is to be in the state s”.</p><h3>The State-Action Value Function Q(s,a)</h3><p>A Q-value is a function <strong><em>Q(s,a)</em></strong> that describes <strong><em>how good is to be in state s and take action a</em></strong>. It outputs a real number. It estimates the expected return if the agent takes action <strong><em>a</em></strong> in state <strong><em>s</em></strong> following the optimal policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*9KFs3roI42KDVI0ehP_e2w.png" /></figure><p>For example, if a neural network with 3 possible actions (3 output layers) outputs the following Q-values for different actions in a state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*bh_SjBMeh_OZzxDOD3yHzQ.png" /></figure><p>Action <em>a1</em> is expected to yield <strong>3.5</strong> cumulative rewards in the future, action <em>a2</em> is expected to yield <strong>-1.2</strong> (which is bad), and action <em>a3</em> is the best choice because it has the highest expected return (<strong>5.7</strong>).</p><p>In a nutshell, it is a function that says how good or not to take that action while the agent is in the state. The algorithm will “learn” this function Q.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*uKXQB7GUjCKQalDPVlxR8Q.png" /><figcaption>Value functions</figcaption></figure><h3>Bellman Equation and the Q-Learning</h3><p>Now that we have the concepts above, we have to introduce them into dynamic programming: the art of optimization.</p><p>The Bellman equation is the foundation of reinforcement learning. This is because it expresses a recursive <strong>relationship </strong>between different states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*KjrMOORB2xVmvoSiqX5lcg.png" /></figure><p>Or for the Q-values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*J66b53euVfjiwnGKOCgMjw.png" /></figure><p>Where γ is the discount of the next reward.</p><p>It may look scary at first, but it is quite simple. The idea is that we break down a complex problem into smaller subproblems using recursion. The equation states that the optimal value of a state is the immediate reward plus the discounted expected value of the future states.</p><p>The Q-learning is an algorithm that is capable of learning the best optimal policy using the Bellman Equation.</p><p>We use the Bellman Equation in this form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*WdenHehObMuMwwNzSK3CPw.png" /></figure><p>Where it calculates in each state for each action in a table, and then, to learn, we have an iterative step updating the values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*K0Cd21xvTNb3RMWLSjK3rg.png" /><figcaption>Bellman equation applied to the Q-Learning algorithm</figcaption></figure><p>In <em>“supervised-learning terms”</em>, what we are doing here is simply getting the target (or the label) to compare with the output of our model and do the backpropagation step. If we call “y” our target, we model it as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*9cVK1BvK4X0fMaLz10q0Qw.png" /></figure><p>And, then, put into the loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*Mmy248MgJdnQgLBPanBzAA.png" /></figure><h3>Epsilon-Greedy Method</h3><p>In RL, we usually come up with two concepts: the <strong>exploration</strong>, and the <strong>exploitation:</strong></p><ul><li><strong>Exploration</strong> refers to trying out new actions that may not seem optimal at first but could lead to better long-term rewards. This is crucial, especially in the early stages of learning, as it allows the agent to gather more information about the environment.</li><li><strong>Exploitation</strong> is the fact of taking advantage of the knowledge the agent has already acquired to choose the action that maximizes the expected reward. Once the agent has a good estimate of the best actions, it tends to exploit this knowledge to perform optimally.</li></ul><p>In the Epsilon-Greedy method, the agent selects the best-known action (exploitation) with a probability of <em>1−ϵ</em> and chooses a random action (exploration) with a probability of <em>ϵ</em>. Over time, <em>ϵ </em>is gradually reduced, leading to more exploitation as the agent gains confidence in its learned policy.</p><p>We can build a simple pseudo-algo like this:</p><pre>p = random()<br><br>if p &lt; epsilon:<br>  pull random action<br>else:<br>  pull current-best action</pre><h3>The Replay Memory</h3><p>Replay Memory is a technique used in reinforcement learning to store and reuse past experiences.</p><p>It is essentially a buffer that records state transitions, including the state, action, reward, and next state. Instead of training the model sequentially with the most recent experiences, which can lead to inefficient learning and high variance, replay memory allows the model to sample and learn from past experiences in a more structured way.</p><p>The objective is to break the temporal correlation between consecutive experiences and help stabilize the learning process.</p><p>It is basically an array that stores the steps and it will be used to sample to avoid bias. We are going to see how to implement it.</p><h3>The Double DQN</h3><p>One of the problems of the DQN algorithm is that it overestimates the true rewards: the Q-values think the agent is going to obtain a higher return than what it will obtain in reality. To fix this, we can use a <strong>target network</strong>. <br><strong><em>It is a training trick.</em></strong></p><p>A target network is a separate neural network used to stabilize training. It is a copy of the main Q-network but is updated less frequently.</p><p>Without it, the Q-network would update its own target values based on its own rapidly changing predictions, making the learning process unstable. By keeping the target network fixed for several iterations, the algorithm ensures that updates are more gradual, improving convergence. This technique significantly enhances the stability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*mi8SuF1-RN0G4wNOcvnCbw.png" /><figcaption>Bellman equation for Double DQNs</figcaption></figure><p>It is going to be clear when we implement it in the pipeline.</p><h3>The Dueling DQN</h3><p>The Dueling technique is another technique to improve the performance and stability of the training. <strong><em>It is an architectural improvement.</em></strong></p><p>The environments where some actions do not affect much (e.g., Atari games) are the ones that take the most advantage of dueling.</p><p>It consists of splitting the last fully connected layer (actions) into two: the Value Stream and the Advantage Stream.</p><ul><li>The Value Stream simply consists of a single output layer that will evaluate how good is the state ( 0 ≤ V ≤ 1 ).</li><li>The Advantage Stream consists of the number of actions and it answers “How much better is each action?”</li></ul><p>And, in the end, we simply sum both to give us the final action decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*PjSe3wVCawOEpXGBmaWZmQ.png" /><figcaption>Common DQN Architecture in the upper image and the Dueling Method on the bottom. (Images here are just illustrative as it has convolutional layers)</figcaption></figure><h3>High-Level Pipeline</h3><p>Okay, now that we have the core concepts, we are going to implement them in the pipeline and understand how everything works.</p><p>In a nutshell, the pipeline we will build is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*wRKV_6NreTacl3BuDYV4qg.png" /></figure><h3>Theoretical Problems that DQN is capable of solving</h3><ol><li><strong>Fully Observable Environments<br></strong>This happens when the agent receives the complete state of the environment at each time step. That means that the agent has all the necessary information.</li><li><strong>Discrete Action Spaces</strong><br>Standard DQN is designed for environments with a finite set of discrete actions, such as “move left,” “jump,” or “shoot.”</li><li><strong>Defined reward signal</strong><br>The reward signal is either known or directly observable after performing an action.</li><li><strong>Relies on Markovian Transitions</strong><br>The environment satisfies the Markov property, meaning the next state depends only on the current state and action, and not on the full history.</li><li><strong>Model-Free Setting</strong><br>DQN is model-free, meaning it does not require knowledge of the environment’s dynamics. It learns purely through interaction.</li><li><strong>Stationary Environments<br></strong>The dynamics of the environment are assumed to be stable over time, meaning the optimal policy does not change.</li></ol><p>So, as you might imagine, it is not capable of dealing with:</p><ol><li><strong>Partially Observable Environments (POMDPs)<br></strong>When the agent only receives partial observations (e.g., limited camera view), DQN struggles</li><li><strong>Continuous Action Spaces</strong><br>DQN cannot handle continuous actions directly</li><li><strong>Sparse Rewards<br></strong>If the agent receives rewards only after many steps, DQN may struggle to learn meaningful behaviors.</li><li><strong>Non-Stationary Environments<br></strong>If the environment changes over time, standard DQN may not adapt well.</li></ol><h3>Our Environment and Code Implementation</h3><p>Now that we reviewed the theory, let`s start by loading the game. To do this, I am going to use gymnasium. <br>Each state is defined by each frame of the game.</p><p>The Gymnasium provides the following <strong>observations </strong>for each state:</p><pre>1. the last pipe&#39;s horizontal position<br>2. the last top pipe&#39;s vertical position<br>3. the last bottom pipe&#39;s vertical position<br>4. the next pipe&#39;s horizontal position<br>5. the next top pipe&#39;s vertical position<br>6. the next bottom pipe&#39;s vertical position<br>7. the next next pipe&#39;s horizontal position<br>8. the next next top pipe&#39;s vertical position<br>9. the next next bottom pipe&#39;s vertical position<br>10. player&#39;s vertical position<br>11. player&#39;s vertical velocity<br>12. player&#39;s rotation</pre><p>These data are the “<em>sensors</em>” of our little bird. With these, we can understand a good policy to make it learn how to play.</p><p>Our bird can do the following <strong>actions</strong>:</p><pre>0. do nothing<br>1. flap</pre><blockquote>The main goal of our model is to search correlations between these sensors. That way, it will know when is time to flap or to do nothing</blockquote><p>You may already see that our FFN will have 12 nodes in our input layer (observations) and 2 nodes (actions) in our output layer (soft-labeling with softmax, not hard-labeling with sigmoid).</p><p>The rewards are structured like this:</p><pre>+0.1 - every frame it stays alive<br>+1.0 - successfully passing a pipe<br>-1.0 - dying<br>−0.5 - touch the top of the screen</pre><p>The <strong>network </strong>will be implemented this way:</p><pre>class DQN(nn.Module):<br><br>    def __init__(self, state_dim, action_dim, hidden_dim=256, enable_dueling_dqn=True):<br>        super(DQN, self).__init__()<br><br>        self.enable_dueling_dqn=enable_dueling_dqn<br>        self.fc1 = nn.Linear(state_dim, hidden_dim)<br><br>        if self.enable_dueling_dqn:<br>            <br>            #value stream<br>            self.fc_value = nn.Linear(hidden_dim, 256)<br>            self.value = nn.Linear(256, 1)<br><br>            #advantages stream<br>            self.fc_advantages = nn.Linear(hidden_dim, 256)<br>            self.advantages = nn.Linear(256, action_dim)<br><br>        else:<br>            # vanilla dqn<br>            self.output = nn.Linear(hidden_dim, action_dim)<br><br>    def forward(self, x):<br>        latent_features = F.relu(self.fc1(x))<br><br>        if self.enable_dueling_dqn:<br>            #value stream calculation<br>            v = F.relu(self.fc_value(latent_features))<br>            V = self.value(v)<br><br>            #advantages stream calculation<br>            a = F.relu(self.fc_advantages(latent_features))<br>            A = self.advantages(a)<br><br>            #Q-value calculation:<br>            &quot;&quot;&quot;<br>              -&gt; V: [batch_size, 1]<br>              -&gt; A: [batch_size, action_dim]<br>              -&gt; V + A = [batch_size, action_dim] + [batch_size, action_dim * 1]<br>              this means that the action tensor is automatically expanded<br>            &quot;&quot;&quot;<br>            Q = V + A - torch.mean(A, dim=1, keepdim=True)<br><br>        else:<br>            Q = self.output(latent_features)<br><br>        return Q</pre><p>There we can see the implementation of the Dueling DQN technique.</p><p>The <strong>pipeline </strong>will be built this way:</p><p><strong>1 — </strong>First, initialize everything:</p><pre>from collections import deque #a formal way to &quot;bilateral arrays&quot;<br>import random<br><br># I mean, there is no mistery here, it is just to be formal<br>class ReplayMemory():<br>    def __init__(self, maxlen):<br>        self.memory = deque([], maxlen=maxlen)<br><br>    def append(self, transition):<br>        self.memory.append(transition)<br><br>    def sample(self, sample_size):<br>        return random.sample(self.memory, sample_size)<br><br>    def __len__(self):<br>        return len(self.memory)</pre><pre>env = gym.make(&quot;FlappyBird-v0&quot;, render_mode=&#39;human&#39;, use_lidar=False) ## to get the 12 state observations<br>num_actions = env.action_space.n<br>print(f&quot;number of possible actions (flap or nothing): {num_actions}&quot;)<br><br>observation_space = env.observation_space<br>num_states = observation_space.shape[0] # Box(low, high, (shape0,), float64)<br>print(f&quot;observation space: {observation_space}&quot;)<br>print(f&quot;observations: {num_states}&quot;)<br><br>rewards_per_episode = []<br>epsilon = 1<br>epsilon_decay = 0.99995<br>epsilon_min = 0.00001<br>mini_batch_size = 32<br>network_sync_rate = 10<br>epsilon_history = []<br>memory = ReplayMemory(maxlen = 100000)<br><br>#instantiating networks<br>policy_dqn = DQN(num_states, num_actions, hidden_dim=256, enable_dueling_dqn=True).to(device)<br>target_dqn = DQN(num_states, num_actions, hidden_dim=256, enable_dueling_dqn=True).to(device)<br>target_dqn.load_state_dict(policy_dqn.state_dict()) #same as the target network<br><br>optimizer = torch.optim.Adam(policy_dqn.parameters(), lr=0.0001)<br>loss_fn = nn.MSELoss()<br><br># track number of steps taken. used for syncing policy =&gt; target network.<br>step_count=0<br><br>best_reward = -float(&quot;inf&quot;) ## see if it is right</pre><p><strong>2 — </strong>Now, we will start the loop for the episodes:</p><pre>#for episode in itertools.count(): #if you want to run indefinitely -&gt; stop whenever you want<br>for episode in range(1000):<br>    <br>    state, _ = env.reset()  # initialize environment. reset returns (state,info).<br>    state = torch.tensor(state, dtype=torch.float, device=device)<br>    <br>    #loop train in the episode<br>    stop_on_reward = 999<br>    terminated = False      #if the env has some goal (not the case of flappybird)<br>    episode_reward = 0.0    #used to accumulate rewards per episode</pre><p><strong>3 —</strong> Inside this loop, we will implement the definitions that make the episode end: when the bird is dead or when it hits a certain score value. Inside it, we will already implement the epsilon-greedy algorithm:</p><pre>while(not terminated and episode_reward &lt; stop_on_reward): #stop if bird is dead or achieved 999 scores on the game<br><br>        ## epsilon-greedy algorithm !!!!!!!!!!<br>        if random.random() &lt; 0.1: ##floating number [0,1] &lt; epsilon<br>            # select random action<br>            action = env.action_space.sample() #env.action_space = [0,1]<br>            action = torch.tensor(action, dtype=torch.int64, device=device)<br>        else:<br>            # select best action<br>            with torch.no_grad():<br>                state_pytorch = state.unsqueeze(dim=0) # state.shape -&gt; [12], state.unsqueeze(dim=0).shape -&gt; [1,12] because pytorch expects a batch dimension<br>                action = policy_dqn(state_pytorch).squeeze().argmax() # action.shape -&gt; [1, 2], action.squeeze(dim=0).shape -&gt; [2], argmax outputs the position of the max(a,b)</pre><p><strong>3 — </strong>Now, we are going to execute the action and save the reward and the tuple <em>(state, action, new_state, reward, terminated) </em>in our replay buffer</p><pre>        #execute action letsgoo<br>        new_state,reward,terminated,truncated,info = env.step(action.item()) #this env.step executes the action on the env<br>        episode_reward += reward<br><br>        new_state = torch.tensor(new_state, dtype=torch.float, device=device)<br>        reward = torch.tensor(reward, dtype=torch.float, device=device)<br><br>        #adding into the replay buffer<br>        memory.append((state, action, new_state, reward, terminated))<br>        step_count+=1<br><br>        state = new_state<br>    rewards_per_episode.append(episode_reward)<br>    # check if it is the best to save the model<br>    if episode_reward &gt; best_reward:<br>            print(f&quot;{datetime.now().strftime(&#39;%m-%d %H:%M:%S&#39;)}: New best reward {episode_reward:0.1f} ({(episode_reward-best_reward)/best_reward*100:+.1f}%) at episode {episode}, saving model...&quot;)<br>            torch.save(policy_dqn.state_dict(), &quot;best_model.pt&quot;)<br>            best_reward = episode_reward</pre><p><strong>4 —</strong> Now, we are going to optimize the network, process the epsilon-decay, and implement the double-dqn substitution if it is the right time:</p><pre><br>    # also an importat part: the model optimization using the memory buffer, epsilon decay and double dqn !!!!!!!!!!<br>    if len(memory) &gt; mini_batch_size:<br>        mini_batch = memory.sample(mini_batch_size)<br>        optimize(mini_batch, policy_dqn, target_dqn) #optimization step<br><br>        # espilon decay... going into the exploitation and avoiding exploration<br>        epsilon = max(epsilon * epsilon_decay, epsilon_min)<br>        epsilon_history.append(epsilon)<br><br>        # the double dqn idea: copy policy network to target network after a certain number of steps<br>        if step_count &gt; network_sync_rate:<br>            target_dqn.load_state_dict(policy_dqn.state_dict())<br>            step_count=0</pre><p><em>The optimize function</em>: Of course, we need to <strong>optimize </strong>our network via gradient descend with the implementation of the Q-Learning algo:</p><pre>def optimize(mini_batch, policy_dqn, target_dqn):<br><br>        #get elements from the env in the mini_batch<br>        states, actions, new_states, rewards, terminations = zip(*mini_batch)<br><br>        states = torch.stack(states)<br>        actions = torch.stack(actions)<br>        new_states = torch.stack(new_states)<br>        rewards = torch.stack(rewards)<br>        terminations = torch.tensor(terminations).float().to(device)<br><br>        discount_factor_g = 0.99<br>        with torch.no_grad():<br>            enable_double_dqn = True #just to implement also without double_dqn<br>            if enable_double_dqn == True:<br>                best_actions_from_policy = policy_dqn(new_states).argmax(dim=1)<br><br>                target_q = rewards + (1-terminations) * discount_factor_g * \<br>                                target_dqn(new_states).gather(dim=1, index=best_actions_from_policy.unsqueeze(dim=1)).squeeze()<br>            else:<br>                #calculate target Q values (expected returns)<br>                target_q = rewards + (1-terminations) * discount_factor_g * target_dqn(new_states).max(dim=1)[0]<br><br>        #calcuate Q values from current policy<br>        current_q = policy_dqn(states).gather(dim=1, index=actions.unsqueeze(dim=1)).squeeze()<br><br>        loss = loss_fn(current_q, target_q)<br><br>        # backprop step<br>        optimizer.zero_grad()  <br>        loss.backward()             # compute gradients<br>        optimizer.step() #propagate it through the model</pre><p>Again, if you want to check the full running code, feel free to visit: <a href="https://www.kaggle.com/code/matheusparracho/flappybird-agent-deep-q-learning">https://www.kaggle.com/code/matheusparracho/flappybird-agent-deep-q-learning</a></p><h3><strong>Results</strong></h3><p>We saved the training elements to check the performance of the model. With these, we can check the training performance by plotting the graph. The training will be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*cL6i6mT0SIjGv2dsQUYLLw.png" /><figcaption>Training results during my training around 90k episodes</figcaption></figure><p>Looking at these graphs, we can observe that the average rewards increased as the model was trained for a longer period. At the same time, the model gradually shifted from exploration to exploitation — meaning that, in the beginning, it was more open to exploring new possibilities, and as it gained more experience, it started to favor actions that had previously yielded better results.</p><p>We can, then, import the trained weights into our model, run the evaluation, and play the game:</p><p>After some 78k episodes, for me, I was able to get +100 scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoPHv1_gZp71oOsXOsTXJA.gif" /><figcaption>DQN model running on my machine +100 scores</figcaption></figure><h3>Bonus: The same pipeline in different environments</h3><p>The same pipeline built for the DQN developed for FlappyBird can be used in other similar environments if they follow the same properties as Flappy Bird. For example:</p><p><strong>Cartpole<br></strong>The CartPole game consists of maintaining a vertical upright pole balanced on a moving cart by applying forces to the left or right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*pWt_Qv-o5nMoK_shWyZW8w.png" /><figcaption>The Cartpole game</figcaption></figure><p>The pole is attached to the cart via a hinge, and the goal is to prevent it from falling over by controlling the horizontal movement of the cart. The episode ends when the pole falls past a certain angle or the cart moves out of bounds.</p><p>For the rewards, we have:</p><pre>+1.0 – for every time step the pole remains balanced (i.e., the episode continues)<br>0.0 – when the episode ends (implicitly no reward is given at termination)</pre><p>For the actions, we have simply:</p><pre>0 – move cart to the left<br>1 – move cart to the right</pre><p>Using the same pipeline and techniques, the model was able to converge into a somehow useful solution rapidly (I guess with some proper parametrization it can go even better). But we achieved these (actually good) results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*vXdtYCwsAY7BUjqz8isBHQ.png" /><figcaption>rewards achieved and epsilon decay graph</figcaption></figure><p>And, finally, playing the game:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*T3esPs53hkHYyss2B2itRw.gif" /><figcaption>Cartpole game after training</figcaption></figure><p><strong>Acrobot</strong></p><p>The Acrobot game consists of a two-link pendulum (like a gymnast swinging on a high bar), where only the second joint is actuated.<br>The goal is to swing the system so that the tip of the lower link reaches a certain height above a certain line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*b7z6d8tGBj71mtnhESLr2w.png" /><figcaption>The acrobot dynamics</figcaption></figure><p>The agent can apply torques at the joint to control the swinging motion and build up enough momentum to reach the target.<br>We have 3 types of actions (our DQN outputs):</p><pre>0: Apply a negative torque (counter-clockwise)<br>1: Apply no torque (do nothing)<br>2: Apply a positive torque (clockwise)</pre><p>As rewards, we have -1 at every time step, forcing the agent to solve the task in as few steps as possible.</p><p>The game ends when the episode length is greater than 500 (that means the reward is -500), or if the acrobot reaches the height expected.</p><p>The observation space consists in:</p><pre>cos(θ1),      #cosine of the angle of the first link<br>sin(θ1),      #sine of the angle of the first link<br>cos(θ2),      #cosine of the angle of the second link<br>sin(θ2),      #sine of the angle of the second link<br>θ̇1,           #angular velocity of the first joint<br>θ̇2            #angular velocity of the second joint</pre><p><strong>An interesting technique used: Fitted Q-iteration</strong></p><p>Beyond using the same pipeline proposed above, I also used a technique named Fitted Q-iteration.</p><p>Let’s first define what <em>online </em>and <em>offline </em>Reinforcement Learning are:</p><ul><li><strong>Online Reinforcement Learning</strong> is what we did before: exploring the environment while also learning from it <strong>at the same time</strong>.</li><li><strong>Offline Reinforcement Learning</strong>, on the other hand, consists of decoupling the data collection and the policy optimization into different parts: first collecting the data with some initial policy, and then optimizing it using the data we collected.</li></ul><p>Also, as you might have noticed, as the agent receives only negative rewards, the accumulative reward will be always negative. So, another interesting technique is to set a reward threshold to <strong>filter the worst episodes</strong>, making sure that only episodes with relatively better performance (i.e., higher — less negative — cumulative reward) are used for training.</p><p>For the offline RL, I use an initial random policy to get the transitions, so that is why I did not use the epsilon decay technique.</p><p>So, to implement this, I created the following function inside a class “FQI_Agent”:</p><pre>    <br>self.reward_threshold = -475<br>def collect_dataset(self):<br>    print(f&quot;collecting {self.num_episodes} random episodes&quot;)<br>    env = gym.make(self.env_id)<br>    num_actions = env.action_space.n<br><br>    total_steps = []<br>    total_rewards = []<br>    data = []<br><br>    for _ in trange(self.num_episodes):<br>        state, _ = env.reset()<br>        done = False<br>        rewards = []<br>        tmp = []<br><br>        while not done:<br>            #our random policy:<br>            action = random.randint(0, num_actions - 1)<br><br>            next_state, reward, terminated, truncated, _ = env.step(action)<br>            done = terminated or truncated<br><br>            tmp.append(Transition(<br>                state=np.array(state, dtype=np.float32),<br>                action=np.array([action], dtype=np.int64),<br>                next_state=np.array(next_state, dtype=np.float32),<br>                reward=np.array([reward], dtype=np.float32),<br>                done=done<br>            ))<br><br>            rewards.append(reward)<br>            state = next_state<br><br>        episode_reward = sum(rewards)<br>        total_rewards.append(episode_reward)<br>        total_steps.append(len(rewards))<br><br>        # here we are filtering the worst episodes<br>        if episode_reward &gt; self.reward_threshold:<br>            data += tmp<br><br>    print(f&quot;total of collected transitions: {self.reward_threshold}): {len(data)}&quot;)<br>    return data, env</pre><p>Good! After collecting our “dataset”, we can train the same way as usual:</p><pre>def train(self):<br>    dataset, env = self.collect_dataset()<br>    num_states = env.observation_space.shape[0]<br>    num_actions = env.action_space.n<br><br>    q_net = DQN(num_states, num_actions, self.hidden_units).to(device)<br>    optimizer = torch.optim.Adam(q_net.parameters(), lr=self.learning_rate)<br><br>    for iteration in range(self.num_iterations):<br>        random.shuffle(dataset)<br><br>        states = torch.tensor([t.state for t in dataset], dtype=torch.float32).to(device)<br>        actions = torch.tensor([t.action for t in dataset], dtype=torch.int64).squeeze().to(device)<br>        rewards = torch.tensor([t.reward for t in dataset], dtype=torch.float32).squeeze().to(device)<br>        next_states = torch.tensor([t.next_state for t in dataset], dtype=torch.float32).to(device)<br>        dones = torch.tensor([t.done for t in dataset], dtype=torch.float32).to(device)<br><br>        with torch.no_grad():<br><br>            #now using our policy (our network)<br>            next_q = q_net(next_states)<br>            max_next_q = next_q.max(1)[0]<br><br>            # the q-learning algo:<br>            targets = rewards + (1 - dones) * self.discount_factor * max_next_q<br><br>        pred_q = q_net(states).gather(1, actions.unsqueeze(1)).squeeze()<br>        loss = self.loss_fn(pred_q, targets) #computing loss<br><br>        #usual optimization pipeline<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br><br>        print(f&quot;[{iteration + 1}/{self.num_iterations}] loss: {loss.item():.4f}&quot;)<br><br>    torch.save(q_net.state_dict(), self.model_path)<br>    print(f&quot;saving model at {self.model_path}&quot;)</pre><p>And, finally, the gameplay:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bMa3pflwfLy5QWDB2N_VnA.gif" /><figcaption>Acrobot running after training</figcaption></figure><h3>Conclusion</h3><p>So, in this article, we could explore the foundations of DQN and techniques that improve training stability and final performance.</p><p>The pipeline studied here can be applied to almost any problem that follows the same RL characteristics as FlappyBird, Cartpole, or Acrobat.</p><p>Nowadays, many real-world problems use RL with something more, like supervised or unsupervised learning. Grouping these techniques can create a really powerful system to model many different phenomena, which is why I believe studying RL is still very interesting and important.</p><p>Feel free to comment any suggestions or to give your opinion! See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cb16a9fa184" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Denoising Diffusion Probabilistic Models (DDPM) — Generative Intuition & Practice]]></title>
            <link>https://medium.com/@mathparracho/denoising-diffusion-probabilistic-models-ddpm-generative-intuition-practice-ef6b10d232a2?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef6b10d232a2</guid>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 18:58:01 GMT</pubDate>
            <atom:updated>2025-01-18T19:08:22.592Z</atom:updated>
            <content:encoded><![CDATA[<h3>Denoising Diffusion Probabilistic Models (DDPM) — Generative Intuition &amp; Practice</h3><h3>Introduction</h3><p>In the few latest articles, we understood how EBMs, GANs, and VAEs work. Now, it is time for one big player in the latest SOTA generative models out there: the Diffusion Models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvClU5LgylulNWLPNpOCfA.png" /><figcaption>Illustrartive image of the Forward/Backward process of a Diffusion Model</figcaption></figure><p>In this article, we are going to see deeply how these models work and how we can create one using Pytorch from scratch. All the code will be on Kaggle. Feel free to check.</p><p>Kaggle Link: <a href="https://www.kaggle.com/code/matheusparracho/denoising-diffusion-probabilistic-models-ddpm">https://www.kaggle.com/code/matheusparracho/denoising-diffusion-probabilistic-models-ddpm</a></p><h3>What are Diffusion Models?</h3><p>Diffusion models have inspiration from non-equilibrium thermodynamics, where a Markov chain of diffusion steps is used to introduce random noise into the data progressively. <br>The model is then trained to reverse this process, effectively denoising the data to generate the desired samples from pure noise.</p><p>Unlike VAEs or flow-based models, diffusion models follow a predetermined procedure during training, and the <strong>latent space has the same high dimensionality as the original data</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FgoPaa8KhsrrRS8MLAd4A.png" /><figcaption>High-Level comparison between different Generative Models</figcaption></figure><p>To reconstruct the data, the UNET architecture is commonly used in its core:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvXoKMHoPJMKpKK7keZMEA.png" /><figcaption>The UNET architecture — commonly used in medical imaging</figcaption></figure><p>We have 2 important “engines” of the Diffusion Model: the <strong>Forward Diffusion Process</strong> and the <strong>Reverse Diffusion Process</strong></p><h3>The Forward Diffusion Process</h3><p>We can resume this part by simply “adding more noise in each iteration”.</p><p>Formerly, given a data point sampled from a real data distribution <em>x0 </em>(where<em> </em><strong><em>x0 ~ q(x)</em></strong>), we define a forward diffusion process. In this process, we gradually add small amounts of Gaussian noise to the data point over a total of <em>T </em>steps. As a result, this process produces a sequence of increasingly noisy samples, denoted as <strong><em>x1, x2, …, xT</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*ecrqCnxr8cXexnZddbd_VQ.png" /></figure><p>That also can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*DyD_7OiuFuc1lgDFl-yvCQ.png" /></figure><p>Or,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*wws_E9Nb_4wRiJpDxC0Ohg.png" /></figure><p>The expression defines the conditional probability of <em>x_t </em>given <em>x_{t-1}</em>. It specifies how the state <em>x_t </em>is generated from the previous state <em>x_{t-1}</em> in the forward diffusion process.</p><p>The distribution is Gaussian, where the mean is <em>sqrt(1 — beta_t) * x_{t-1}</em>, meaning the current state is influenced by the previous state, scaled down by <em>sqrt(1 — beta_t)</em>. The covariance is <em>beta_t * I</em>, which introduces isotropic Gaussian noise controlled by <em>beta_t</em>. As <em>beta_t </em>increases, the influence of <em>x_{t-1}</em> decreases, and more noise is added, gradually corrupting the data.</p><h3>The Reverse Diffusion Process</h3><p>We can resume this part by simply “removing noise in each iteration”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*pdpekrlQqzLdf9DtvSb9YA.png" /></figure><p>The expression shows the joint probability of the sequence x_0, x_1, …, x_T. It starts with x_T, which is assumed to follow a prior distribution p(x_T), typically Gaussian. Then, the reverse process calculates the probability of each preceding state x_{t-1} given the current state x_t, using the learned conditional probabilities p_theta(x_{t-1} | x_t). This process reverses the forward diffusion steps to reconstruct the data.</p><p><em>μθ​(x_t​,t)</em> and <em>σθ(x_t,t)</em> represent the mean and variance learned by the model θ for the distribution at timestep t.</p><h3>One Important Propriety for the Formulation</h3><p>There is an important propriety of the Gaussian distributions that claims that <strong>any linear combination of Gaussian random variables is itself Gaussian</strong>. This means that given the reparametrization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*MAim9hmFofzmXbYvT-UMtg.png" /></figure><p>We can express x_t as a direct mixture of the original data x_0​ and a noise term ϵ∼N(0,I):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*M73PUgE_xBb0No9IYd8gmQ.png" /></figure><p><em>The natural question arises: how do we train it? Let`s see:</em></p><h3>The Variational Lower Bound (VLB or ELBO)</h3><p>Our goal is to learn the distribution capable of denoising the image in each iteration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*hTN0Fq7m-HVxDe7aW3yiGQ.png" /></figure><p>The network takes in two arguments <em>x_t</em>, <em>t</em>, and outputs a vector <em>μθ(x_t, t )</em> and a matrix <em>Σθ(x_t, t)</em>, such that each step in the forward diffusion process can be approximately undone by <em>x_{t − 1} ∼ N(μθ( x_t, t), Σθ(x_t, t))</em>.</p><p>The goal now is to learn the parameters such that <em>pθ(x0)</em> is as close to <em>q(x0)</em> as possible. To do that, we use <strong>maximum likelihood estimation</strong> with variational inference, <strong>which is the same proposition as the VAE</strong>.</p><p>By definition, the ELBO inequality can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*C-zzMsFlkzwJ2NZMccoXmQ.png" /></figure><p>Adding the Expected Value function on both sides:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*tkNVGIxBHrWC9BFtTbhlOg.png" /></figure><p>We see that maximizing the quantity on the right would give us a lower bound on the likelihood of observed data. This allows us to perform variational inference.</p><p>Therefore, we can define the loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*i9IvZQVJR_q9E2YJO52h9g.png" /></figure><p>This expression can be simplified to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*G4JbGVcG1vYIesJwLO2wGA.png" /><figcaption>details on <a href="https://lilianweng.github.io/posts/2021-07-11-diffusion-models/">https://lilianweng.github.io/posts/2021-07-11-diffusion-models/</a></figcaption></figure><p>where C does not depend on the parameter, and thus can be ignored. Since <em>pθ(xT) = N(xT|0, I)</em> also does not depend on the parameter, the term <em>Ex_0 ∼ q[DKL(q(x_T|x_0)‖p_θ(x_T))</em> can also be ignored. This leaves just</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/0*DH7Deu3LwzCwobIv" /></figure><p>to be minimized.</p><p><strong><em>Now let`s understand how we can predict it during training by designing a Noise prediction network.</em></strong></p><p>Since x_{t-1} | x_t is sampled from the reverse diffusion process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*4AeVSCIQDUqY8N7tedxrkA.png" /></figure><p>In the forward step, we have (due to the reparametrization trick):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*fkdZKfFwNoSZ9mFJe2zD2g.png" /></figure><p>So, we can isolate x_0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*ncgJrwIELlWts9BSUI0f-A.png" /></figure><p>Then, we substitute the mean expression on the reverse process, and we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*VUNs0XRnNngfIfswF7x_6A.png" /></figure><p>Where ε(theta) is the noise vector.</p><p>In the DDPM paper, the authors decided not to train the variance Σθ(xt,t). They found that training led to unstable training and worse sample quality. Instead, they fixed the variance to a predefined value: Σθ(xt,t)=[(ξt)^2]*I, where ξt2​ is a constant that can be chosen as either βt​ or σt​ (a parameter related to the noise schedule). Both choices gave similar results in practice.</p><p>Therefore, the loss simplifies to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*Di87qpoSdxKkjB7P2SwQ8g.png" /></figure><p>To be optimized via gradient descent. The paper stated that the even simpler loss</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*aJgZoNPa7NgGvXL3xkcjxA.png" /></figure><p>resulted in better-trained models.</p><p>So, in the end, we have the loss function as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*vPkkSmHKzI7MH87ndt3Crw.png" /></figure><h3>Training &amp; Sampling Algorithms</h3><p>The algorithms proposed are the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*P3l9PgP1_78i5jhRPjhyZw.png" /></figure><p>The idea here is to make the model able to reconstruct the noise based only on a pure-gaussian image and the time step.</p><p>The “time-step input” is very used in auto-regression algorithms like LLM (the sinusoidal embedding), and the goal is just to make the model determine where (in a certain domain) the specific input corresponds.</p><p>For the sampling algorithm, we want the model to be able to reconstruct the original image based on the Langevin Dynamics.</p><p>In Pytorch, the training pipeline can be written like this:</p><pre>#For MNIST dataset<br><br>for i in range(num_epochs):<br><br>  # 1) sample data from our loader<br>  for x,_ in train_loader:<br><br>    # 2) get random time step to make good generalization<br>    t = torch.randint(0,num_time_steps,(batch_size,))<br>    <br>    # 3) add noise to our sampled data (forward diffusion process)<br>    e = torch.randn_like(x, requires_grad=False)<br>    a = scheduler.alpha[t].view(batch_size,1,1,1).cuda()<br>    x = (torch.sqrt(a)*x) + (torch.sqrt(1-a)*e)<br><br>    # 4) pass defused data to model<br>    output = model(x, t)<br><br>    optimizer.zero_grad()<br>    # 5) compare output with noise - the objective is to predict the &quot;noise&quot;<br>    loss = criterion(output, e)<br><br>    loss.backward()<br>    optimizer.step()</pre><p>And the sampling pipeline like this:</p><pre>def sampling(model, scheduler, num_time_steps=1000):<br><br>    # 1) gaussian noise initialization for our final image<br>    x_t = torch.randn(1, 1, 32, 32).cuda()<br>    <br>    # 2) start the reverse diffusion process<br>    for t in reversed(range(1, num_time_steps + 1)):<br>        t_tensor = torch.tensor([t], dtype=torch.float32).cuda()<br>        <br>        # 3) create the noise to be added to our process<br>        z = torch.randn_like(x_t) if t &gt; 1 else 0<br>        <br>        # 4) implementation of the &quot;langevin dynamics&quot; step<br>        alpha_t = scheduler.alpha[t]<br>        alpha_t_bar = scheduler.alpha_cumprod[t]<br>        sigma_t = scheduler.beta[t].sqrt()<br>        <br>        x_t = (1 / alpha_t.sqrt()) * (x_t - ((1 - alpha_t) / (1 - alpha_t_bar).sqrt()) * model(x_t, t_tensor)) + sigma_t * z<br>    <br>    return x_t.cpu().detach()</pre><p>To get reasonable results, it is necessary to train until something close to 70 epochs.</p><h3>Some Results</h3><p>I trained in my machine for 100 epochs and I got some reasonable denoising in MNIST:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UYgrfvkmjT7HDQ5x2iIS6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TDF3gid_W3Soncxdo8jwEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-ejNaQLoPCNx2Gq3KeCspA.png" /></figure><p>The images are shown in different time steps, respectively: 0,15,50,100,200,300,400,550,700, and 999.</p><h3>Conclusion</h3><p>Alright, so in this article, we understood the probabilistic foundations of Diffusion Models and figured out how they actually work and are built. But honestly, that’s just the start. These models are a big deal right now and are being used in a bunch of cutting-edge applications.</p><p>For example, DALL·E and Stable Diffusion — those tools that turn text into realistic images — are built on this approach. In healthcare, they’re being used to create synthetic medical images, which helps a lot when there’s not enough real data available. In gaming and digital art, they help design super-detailed characters and environments that look like they came straight out of someone’s imagination.</p><p>Diffusion Models are everywhere, and they’re not going away anytime soon. They’re literally shaping the future of AI, and honestly, it’s pretty exciting to see where this will go next.</p><p>In the following articles, we are going to see more details on further implementations of Diffusion Models, and how they differ from the “vanilla” DDPM architecture.</p><h3>References</h3><p><a href="https://towardsdatascience.com/diffusion-model-from-scratch-in-pytorch-ddpm-9d9760528946">https://towardsdatascience.com/diffusion-model-from-scratch-in-pytorch-ddpm-9d9760528946</a><br><a href="https://en.wikipedia.org/wiki/Diffusion_model">https://en.wikipedia.org/wiki/Diffusion_model</a><br><a href="https://lilianweng.github.io/posts/2021-07-11-diffusion-models/">https://lilianweng.github.io/posts/2021-07-11-diffusion-models/</a><br><a href="https://en.wikipedia.org/wiki/Evidence_lower_bound">https://en.wikipedia.org/wiki/Evidence_lower_bound</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef6b10d232a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Energy-Based Models and JEMs — Generative Intuition and Practice]]></title>
            <link>https://medium.com/@mathparracho/energy-based-models-and-jems-generative-intuition-and-practice-8a69f1779188?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a69f1779188</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 18:04:47 GMT</pubDate>
            <atom:updated>2024-12-10T19:10:06.708Z</atom:updated>
            <content:encoded><![CDATA[<h3>Energy-Based Models and JEMs — Generative Intuition and Practice</h3><p>Energy-Based Models (EBMs) are a fascinating approach in machine learning that defines probabilities through energy functions, offering a flexible way to model relationships in data via <strong>unsupervised learning</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*4elHGvs5NRDHm9-1555Hgw.png" /><figcaption>EBMs according to DALLE. In parts, it makes sense because in EBMs we are mapping all complex high-dimensional data into a single scalar</figcaption></figure><p>Most traditional models are designed with specific tasks in mind, like classification, regression, or generation. EBMs, on the other hand, take a different approach by focusing on finding the <strong>density estimation</strong>. The goal is to learn the probability density function (distribution) that captures the structure of the entire data space, making it possible to understand and model complex datasets with many elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*AoVpOL_AmTCxbhPaLUL-VA.png" /><figcaption>Synthesizing images, videos, 3D volumetric shapes, and point clouds using MCMC from the learned Energy-based Generative Neural Networks</figcaption></figure><p>In this chapter of the <em>Generative Intuition &amp; Practice</em> series, we will understand the power of modeling Energy-Based Models and explore why modeling a joint distribution is such a powerful idea.</p><p>After that, we are going to explore one interesting extension of EBMs: research on Joint Energy Models and the ways we can use them.</p><p>Of course, with Pytorch code using a <a href="https://www.kaggle.com/datasets/hayder17/breast-cancer-detection">Breast Cancer</a> dataset for exploring the EBMs and the MNIST digits dataset to explore JEMs.<br>Kaggle link: <a href="https://www.kaggle.com/code/matheusparracho/energybasedmodels-jems">https://www.kaggle.com/code/matheusparracho/energybasedmodels-jems</a></p><h3>1) How do we model EBMs?</h3><p>Usually, in classification problems, we are looking to model the conditional probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*wEicTFHRk1uhX0rZFgbSwg.png" /></figure><p>Or, for binary tasks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*veJw_UxpPrzvb1CFF2p0WA.png" /></figure><p>In EBMs, we are interested in finding the probability of the data implicitly using an energy function <strong>E(x)</strong>, where lower energy values correspond to higher probabilities.</p><p>The main goal of this energy function <strong>E(x) </strong>is to<strong> map the high-dimension data into a single scalar.</strong></p><p>The marginal probability <strong>P(x)</strong> is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*ccxkr8wKVAouJ29x0O0acg.png" /></figure><p>Let`s understand this formulation well. <strong>E(x) </strong>is the energy associated to the data, and it can be in the interval <strong>]-∞, +∞[</strong></p><p>However, to formulate a probability distribution, we need to respect two axioms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*_CFd3VicNdZhHp7aZ0_pZg.png" /></figure><p>So, making <strong>exp(E(x))</strong> turns the interval of P(x) into [<strong>0, +∞[</strong>. Now, we need to normalize it by dividing it by the <em>normalizing factor Z</em>. Therefore, we have now P(x) inside the interval [<strong>0, 1].</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*RWYoGTJcz0bfPDNn3jn-6A.png" /></figure><p>The<strong><em> -E(x)</em></strong> <strong><em>(negative of the energy)</em></strong> is just to assign real data to low energy values, and negative samples to high energy values. But you can do the inverse also (this is what I am going to do in this study), just keep track of the loss function.</p><p>Proving the second axiom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*DunozKQ2ER1yHLurpLdGcg.png" /></figure><p>Good! We have modeled the data distribution, but as you have already guessed, how can we calculate the integral over all the data space? The answer is: we cannot.</p><p>We are going to approximate our EBM distribution <strong>q(x)</strong> to the real unknown distribution <strong>p(x) </strong>using <strong>Contrastive Divergence.</strong></p><p><em>Have you already seen something similar? Yes, in VAEs!</em></p><p>Fundamentally, they are looking for the same thing: approximate distributions. However, the way they do this is different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*t-IGwjyQJX-d3nf5WlW1bA.png" /></figure><p>If you are interested in VAEs, check my article: <a href="https://medium.com/@mathparracho/variational-autoencoders-vaes-cvaes-%CE%B2-vaes-generative-intuition-practice-4b7b4011f55b">Variational Autoencoders (VAEs, CVAEs, β-VAEs) — Generative Intuition &amp; Practice</a></p><h3>Training with Contrastive Divergence</h3><p><em>Why can`t we train the same way as VAEs?</em></p><p>We cannot directly maximize the unnormalized probability because there is no assurance that the normalization factor Z will stay the same or that the training data point will become more probable compared to other points in the dataset.</p><p>To address this, we can adjust the training process to focus on <strong>comparing the likelihood</strong> of the training point against a randomly sampled point from the model. This method helps establish a more reliable and stable optimization objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*mPdcSjMkoSzTC0Jd3jIkiw.png" /></figure><p>So, in the end, what we want the energies to be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*pUv0kagaPbr8Ja_cz_3FQQ.png" /><figcaption>Source: <a href="https://deepgenerativemodels.github.io/assets/slides/cs236_lecture11.pdf">https://deepgenerativemodels.github.io/assets/slides/cs236_lecture11.pdf</a></figcaption></figure><p>Where “correct answer” means the data sampled from the original distribution p(x), and “wrong answer” the data sampled from our model q(x) via MCMC.</p><h3>Sampling from q(x) using MCMC</h3><p>To sample data from our model q(x), we are going to use a Markov Chain Monte Carlo technique: Langevin Dynamics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*5VvI3i1B0byAo5hqWN6FAg.png" /></figure><p>The algorithm begins at a random point and gradually moves in the direction of higher probability (lower energy) by descending the gradient over the Energy function. <br>Relying only on this approach is not enough to fully represent the probability distribution. To address this, noise is added to the current sample at each gradient step.</p><h3>The Architecture of an EBM</h3><p>First, we need a function that maps the input to an energy factor (a scalar). This can be expressed by a neural network capable of doing this map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*btJo7dJ0xj8K5GspQZ7muw.png" /></figure><p>In Pytorch, we can write like this:</p><pre>#good practice to use Swish instead of ReLu<br>class Swish(nn.Module):<br>    def forward(self, x):<br>        return x * torch.sigmoid(x)<br><br>class Energy_Model(nn.Module): #MNIST has input as [28x28]<br>    def __init__(self, hidden_features=32, out_dim=1, **kwargs):<br>        super().__init__()<br><br>        c_hid1 = hidden_features // 2<br>        c_hid2 = hidden_features<br>        c_hid3 = hidden_features * 2<br><br><br>        self.conv1 = nn.Conv2d(1, c_hid1, kernel_size=5, stride=2, padding=4)    # [16x16]<br>        self.conv2 = nn.Conv2d(c_hid1, c_hid2, kernel_size=3, stride=2, padding=1)  # [8x8]<br>        self.conv3 = nn.Conv2d(c_hid2, c_hid3, kernel_size=3, stride=2, padding=1)  # [4x4]<br>        self.conv4 = nn.Conv2d(c_hid3, c_hid3, kernel_size=3, stride=2, padding=1)  # [2x2]<br>        self.flatten = nn.Flatten()<br>        self.fc1 = nn.Linear(c_hid3 * 4, c_hid3)<br>        self.fc2 = nn.Linear(c_hid3, out_dim)<br>        self.swish = Swish() <br><br>    def forward(self, x):<br>        x = self.swish(self.conv1(x))<br>        x = self.swish(self.conv2(x))<br>        x = self.swish(self.conv3(x))<br>        x = self.swish(self.conv4(x))<br>        x = self.flatten(x)<br>        x = self.swish(self.fc1(x))<br>        x = self.fc2(x).squeeze(dim=-1) #output as scalar<br>        return x</pre><p>The code above simply introduces a ConvNet capable of mapping the input image into a single scalar.</p><h3>The Sampler — Trick for better training</h3><p>To train with the contrastive divergence objective, it is necessary to generate samples during the training process.</p><p>Due to the high dimensionality of image data, many iterations of MCMC sampling are required to produce reasonable samples.</p><p>A practical technique to reduce the computational cost of sampling is to utilize a <strong>sampling buffer</strong>. This approach involves storing samples from the previous few batches in a buffer and reusing them as the starting points for the MCMC algorithm in subsequent batches. By doing so, the model requires far fewer steps to converge to meaningful samples, significantly reducing the overall sampling cost.</p><pre>class Sampler:<br><br>    def __init__(self, model, img_shape, sample_size, max_len=8192):<br>        &quot;&quot;&quot;<br>        inputs:<br>            model - Neural network to use for modeling E_theta<br>            img_shape - Shape of the images to model<br>            sample_size - Batch size of the samples<br>            max_len - Maximum number of data points to keep in the buffer<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.model = model<br>        self.img_shape = img_shape<br>        self.sample_size = sample_size # same as the batch size<br>        self.max_len = max_len<br>        self.examples = [(torch.rand((1,)+img_shape)*2-1) for _ in range(self.sample_size)]<br><br>    def sample_new_exmps(self, steps=60, step_size=10):<br>        &quot;&quot;&quot;<br>        generates fake samples using the replay buffer and MCMC<br>        &quot;&quot;&quot;<br>        device = next(self.model.parameters()).device <br><br>        ## see on the training algo - 95% of chances to get from the buffer and 5% from random noise<br>        n_new = np.random.binomial(self.sample_size, 0.05)<br>        rand_imgs = torch.rand((n_new,) + self.img_shape, device=device) * 2 - 1<br>        old_imgs = torch.cat(random.choices(self.examples, k=self.sample_size - n_new), dim=0).to(device)<br>        inp_imgs = torch.cat([rand_imgs, old_imgs], dim=0).detach()<br><br>        ## MCMC sampling<br>        inp_imgs = Sampler.generate_samples(self.model, inp_imgs, steps=steps, step_size=step_size)<br><br>        ## update buffer<br>        self.examples = list(inp_imgs.cpu().chunk(self.sample_size, dim=0)) + self.examples<br>        self.examples = self.examples[:self.max_len]<br>        return inp_imgs<br><br><br>    @staticmethod<br>    def generate_samples(model, inp_imgs, steps=60, step_size=10, return_img_per_step=False):<br>        &quot;&quot;&quot;<br>        MCMC step<br>        &quot;&quot;&quot;<br>        device = inp_imgs.device<br>        is_training = model.training<br>        model.eval()<br><br>        #before MCMC: freeze the model<br>        #we are only interested in the gradients of the input.<br>        for p in model.parameters():<br>            p.requires_grad = False<br>        inp_imgs.requires_grad = True<br><br>        had_gradients_enabled = torch.is_grad_enabled()<br>        torch.set_grad_enabled(True)<br><br>        noise = torch.randn(inp_imgs.shape, device=device) <br><br>        imgs_per_step = []<br><br>        for _ in range(steps): #the MCMC interation steps<br>            noise.normal_(0, 0.005)<br>            inp_imgs.data.add_(noise.data)<br>            inp_imgs.data.clamp_(min=-1.0, max=1.0)<br><br>            out_imgs = -model(inp_imgs)<br>            out_imgs.sum().backward()<br>            inp_imgs.grad.data.clamp_(-0.03, 0.03)<br><br>            inp_imgs.data.add_(-step_size * inp_imgs.grad.data)<br>            inp_imgs.grad.detach_()<br>            inp_imgs.grad.zero_()<br>            inp_imgs.data.clamp_(min=-1.0, max=1.0)<br><br>            if return_img_per_step:<br>                imgs_per_step.append(inp_imgs.clone().detach())<br><br>        for p in model.parameters():<br>            p.requires_grad = True<br>        model.train(is_training)<br>        torch.set_grad_enabled(had_gradients_enabled)<br><br>        if return_img_per_step:<br>            return torch.stack(imgs_per_step, dim=0)<br>        else:<br>            return inp_imgs</pre><h3>Training Algorithm</h3><p>Now let`s gather all together and understand the algorithm to train an EBM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJnv31-0hiEme2UV0uaopA.png" /></figure><p>In a nutshell, what we simply do is:</p><ul><li>Get a real sample from the original distribution (our data);</li><li>Get a fake sample from the buffer and use the MCMC sampling algorithm (95% chance) <strong>or </strong>generate a random noise from the Gaussian distribution (5% chance) and use the MCMC sampling algorithm;</li><li>Compare both samples using the contrastive divergence objective and the regularization loss.</li></ul><p>Analyzing the loss function, we can see that reducing the contrastive divergence means that we are lowering the true data indefinitely and increasing the fake data indefinitely.</p><p>However, we are adding a regularization loss. This loss forces both gradients not to explode and be close to zero because we are reducing the square values for each term.</p><p>In Pytorch, we can build the pipeline like this:</p><pre>def train_step(real_imgs, cnn, sampler, optimizer, alpha):<br><br>    real_imgs = real_imgs + torch.randn_like(real_imgs) * 0.005<br>    real_imgs = real_imgs.clamp(min=-1.0, max=1.0)<br><br>    #generate fake images using the buffer and MCMC<br>    fake_imgs = sampler.sample_new_exmps(steps=60, step_size=10)<br><br>    #forward pass<br>    real_out = cnn(real_imgs)<br>    fake_out = cnn(fake_imgs)<br><br>    &quot;&quot;&quot;<br>    # if you want to optimize in GPUs:<br>    inp_imgs = torch.cat([real_imgs, fake_imgs], dim=0)<br>    real_out, fake_out = cnn(inp_imgs).chunk(2, dim=0)<br>    &quot;&quot;&quot;<br><br>    #calculation losses<br>    cdiv_loss = fake_out.mean() - real_out.mean() ## swiching sides (lower the fake and increase the real samples))<br>    reg_loss = alpha * (real_out ** 2 + fake_out ** 2).mean()<br>    loss = reg_loss + cdiv_loss<br><br>    #backprop and parameter updating<br>    optimizer.zero_grad()<br>    loss.backward()<br>    optimizer.step()<br><br>    return loss.item(), reg_loss.item(), cdiv_loss.item(), real_out.mean().item(), fake_out.mean().item()</pre><p>And the training loop:</p><pre>for epoch in range(epochs):<br>    cnn.train()<br>    train_loss, reg_loss, cdiv_loss = 0, 0, 0<br>    avg_real_out, avg_fake_out = 0, 0<br><br>    for real_imgs, _ in train_loader:<br>        real_imgs = real_imgs.to(device)<br>        loss, r_loss, c_loss, r_out, f_out = train_step(real_imgs, cnn, sampler, optimizer, alpha)<br>        train_loss += loss<br>        reg_loss += r_loss<br>        cdiv_loss += c_loss<br>        avg_real_out += r_out<br>        avg_fake_out += f_out<br><br>    scheduler.step()</pre><p>During the training, you are going to see something like this:</p><pre>Epoch 1/5<br>Train Loss: -3.9581, Reg Loss: 3.8090, CDiv Loss: -7.7671<br>Avg Real Out: 3.8694, Avg Fake Out: -3.8978<br>Val CDiv: -9.4341, Val Real Out: 4.1020, Val Fake Out: -5.3322<br><br>Epoch 2/5<br>Train Loss: -4.6312, Reg Loss: 4.5248, CDiv Loss: -9.1560<br>Avg Real Out: 4.2747, Avg Fake Out: -4.8813<br>Val CDiv: -9.6717, Val Real Out: 4.3730, Val Fake Out: -5.2987<br><br>Epoch 3/5<br>Train Loss: -4.6678, Reg Loss: 4.5584, CDiv Loss: -9.2262<br>Avg Real Out: 4.3203, Avg Fake Out: -4.9059<br>Val CDiv: -9.8487, Val Real Out: 4.3247, Val Fake Out: -5.5240<br><br>Epoch 4/5<br>Train Loss: -4.6836, Reg Loss: 4.5614, CDiv Loss: -9.2451<br>Avg Real Out: 4.3486, Avg Fake Out: -4.8965<br>Val CDiv: -9.6424, Val Real Out: 4.2528, Val Fake Out: -5.3896<br><br>Epoch 5/5<br>Train Loss: -4.7212, Reg Loss: 4.5769, CDiv Loss: -9.2981<br>Avg Real Out: 4.3790, Avg Fake Out: -4.9191<br>Val CDiv: -9.6931, Val Real Out: 4.3381, Val Fake Out: -5.3550</pre><p>Observing the “<em>Val Real Out</em>” and “<em>Val Fake Out</em>”, we can see that the average of the energy value turned high, while fake images turned way lower. The model is capable of reducing the energy of the fake samples while increasing the energy of the true samples!</p><p>Good! Our model was capable of describing the true data distribution p(x)!</p><h3>Robustness to Noise and Geometric Transformations</h3><p>Interesting properties to observe in EBMs are their capability to be robust to noise and geometric transformations.<br>Let`s compare, for instance, the energy associated with the image and the same image with some noise to observe the model`s robustness to noise:</p><pre>test_imgs, _ = next(iter(test_loader)) #get image from the real samples<br>exmp_img = test_imgs[0].to(model.device)<br><br>noise_rates = [0.1,0.3,0.5,0.7,0.9,1.1]<br>for noise_rate in noise_rates:<br>    img_noisy = exmp_img + torch.randn_like(exmp_img) * noise_rate<br>    img_noisy.clamp_(min=-1.0, max=1.0)<br>    compare_images(exmp_img, img_noisy)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*cFY92gEqMEd1FXIsDcN_8g.gif" /></figure><p>For instance, if we state a threshold of energy of 0, even for a high amount of noise, we can still observe that the model could classify the image to be part of the real distribution.</p><p>Now, let`s flip the image:</p><pre>img_flipped = exmp_img.flip(dims=(1,2))<br>compare_images(exmp_img, img_flipped) #complete code on kaggle</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*N45mJA-tWj99-ygeE3p0Kg.png" /></figure><p>We can see that the image stayed within the same energy function (I did not use any data augmentation during training).</p><p>Let`s reduce the size of the image, creating a whole big black region:</p><pre>img_tiny = torch.zeros_like(exmp_img)-1<br>img_tiny[:,exmp_img.shape[1]//2:,exmp_img.shape[2]//2:] = exmp_img[:,::2,::2]<br>compare_images(exmp_img, img_tiny)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*4KvExzD_b1xOAsP0PCmLvw.png" /></figure><p>We can see, it is also “size-invariant” if we consider a threshold of 0.</p><h3>Anomaly Detection (Out-of-distribution detection)</h3><p>Using the Energy Model we created, we can detect when a sample comes from the distribution we modeled, or not.</p><p>So, for instance, let`s observe the following:</p><pre>with torch.no_grad():<br> train_imgs,_ = next(iter(train_loader)) #get real samples<br> train_imgs = train_imgs.to(model.device)<br> train_out = model.cnn(train_imgs).mean()<br> print(f&quot;Average score for training images: {train_out.item():4.2f}&quot;)<br><br># OUTPUT: Average score for training images: 5.19</pre><p>We just sampled an image from our data and inputted it into the model.<br>We can observe that the input image sampled from our true data had an energy of around 0. This means that this image comes from the distribution!</p><pre>with torch.no_grad():<br>    rand_imgs = torch.rand((320,) + img_shape).to(device) #generate random noise<br>    rand_imgs = rand_imgs * 2 - 1.0<br>    rand_out = cnn(rand_imgs).mean()<br>    print(f&quot;Average score for random images: {rand_out.item():4.2f}&quot;)<br><br>## OUTPUT: Average score for random images: -5.08</pre><p>Now, we can see that if we input a random noise into the model, it is going to output a way lower energy level associated, meaning that the input is far from the distribution we modeled.</p><h3>Generative Modeling</h3><p>Langevin Dynamics allows us to sample data from the learned distribution.</p><p>Sampling requires us to use the MCMC method in the same way we used it during training. The model should be able to generate reasonable samples if they truly managed to describe the real distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*xnpEnFm69bsk6H_4dTRSzw.png" /><figcaption>Generated samples with 5000 steps and step size of 10</figcaption></figure><p>The idea here is just to observe that the model was capable of modeling the shape of a mammography image and detect, more or less, what to expect when dealing with a distribution of mammography images.</p><p><em>Can I generate really high-fidelity images with EBMs?</em></p><p>Yes! But, of course, this is going to be a <strong>lot </strong>more computationally expensive.<br>If you want to generate more details, you should really tune the hyperparameters, the model itself, and explore a lot the MCMC algorithm with different techniques to improve the buffer.<br>You can check here, for instance: <a href="http://www.stat.ucla.edu/~ywu/GenerativeConvNet/doc/GConvNet.pdf">A Theory of Generative ConvNet</a><br>And also <a href="https://arxiv.org/pdf/1609.09408v1">Cooperative Training of Descriptor and Generator Networks</a></p><h3>Instability Problems</h3><p>EBMs, the way we usually train today, are very unstable and tend to easily diverge.<br>A common technique in training EBMs is to revert to a previously saved stable checkpoint if the model starts to diverge. When divergence is detected, training is paused, and the model is restored to a state from an earlier epoch where divergence had not yet occurred. Training then resumes this time with a different random seed, in the hopes of avoiding further divergence.</p><h3>2) Joint Energy Models (JEMs)</h3><p><em>(In this section, I am going to work with our classical MNIST dataset due to simplicity.)</em></p><p>Joint Energy Models (JEMs) are a type of probabilistic model that unifies energy-based modeling with <strong>supervised learning</strong>. They provide a framework where the learned function serves both as a <strong>classifier </strong>and as an <strong>unnormalized density model</strong>, offering the benefits of <strong>generative </strong>modeling and <strong>discriminative </strong>classification in a single system.<br><em>This work was first published here </em><a href="https://arxiv.org/abs/1912.03263"><em>[1912.03263] Your Classifier is Secretly an Energy-Based Model and You Should Treat it Like One</em></a><em> <br>Also, keep in mind that the authors gave the official code implementation, but in this article, I tried to read and implement the ideas from the paper by myself.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*jFU9gkRgSVRswlt5ueR3tQ.png" /><figcaption>Image from the official paper</figcaption></figure><p>Let`s understand what this formulation means:</p><p><strong>Classifier — The Conditional Probabilistic Function </strong><br>If we have our EBM and we want to use it as a classifier, we can express it as the same softmax we are used to implement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*tANrbpzyY4doIp42wk66HA.png" /></figure><p><strong>LogSumExp (The Generative view)<br></strong>As we saw earlier, we can extract <strong>p(x) </strong>by marginalizing the energy function in terms of <strong>y</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*jAM1gnXXs5cx6bwbsdLJEA.png" /></figure><p>Then we can input into a log function and, therefore, we have our usual LogSumExp:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*7m9AMaquGl-oyQta46WIRw.png" /></figure><p><strong>Identity — Joint View (log(p(x,y))</strong></p><p>Here we are talking about the probability density function of the Energy-Based Model itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*ofAxZZ-z27HPtPamaXvvMQ.png" /></figure><p><em>Okay… but what is the idea?</em></p><p>The idea is that we can train both the discriminative <strong>AND </strong>the generative objectives mutually:</p><p>For the <strong>classifier</strong>, we have our usual cross-entropy loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Yb-iM4Uz9fDKDAN7UGtMzA.png" /></figure><p>Where our goal is to maximize the expected value of the conditional probability regarding the data.</p><p>And for the <strong>generative </strong>objective, we train the same way we studied earlier with EBMs, using contrastive divergence to maximize the marginal probability over the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*s5AhNjDYziKE7LZiulavaw.png" /><figcaption>Our goal</figcaption></figure><p>Using contrastive divergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*mPdcSjMkoSzTC0Jd3jIkiw.png" /></figure><h3>Training Algorithm — JEMs</h3><p>Here I wrote this simple pseudo-algorithm to train JEMs based on the paper from the article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*mKOP8XpdMWPnNbFmCfxe6A.png" /></figure><p>It is interesting to analyze the impact of weighting the generative loss regarding the total performance of the model.</p><h3>Results and Comparisons</h3><p>In my experiments, I trained the same architecture using the JEM paradigm (JEM model) and as a simple classifier (conditional-only training as a vanilla classifier). Then, I compare both performances.</p><p>I also trained using the same weights for both losses (lambda = 1 in Ltotal).</p><p>The results I got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLCVhwJgmv3jQEXDq_MVFw.png" /><figcaption>In MNIST dataset</figcaption></figure><p>We could observe that the JEM took a lot longer to achieve the same accuracy compared to the pure-softmax-based classifier. This is easily explained due to the effort backpropagation takes each epoch to also optimize the gradient of the unnormalized probability distribution, i.e. the objective is more complex on JEMs (even more because I am using lambda=1, i.e. same weight for both objectives).</p><p><em>Also… keep in mind that we are using the MNIST dataset here, it is easier to train with a pure-softmax-based classifier. However, for more complex datasets, the JEM is able to capture more intrinsic features.</em></p><p>The original article states that JEMs are powerful in reducing the <strong>Expected Calibration Error (ECE)</strong>.</p><p><em>What is this Expected Calibration Error?<br></em>The Expected Calibration Error (ECE) is a metric used to evaluate the calibration of a probabilistic model, particularly in classification tasks. Calibration refers to how well the predicted probabilities align with the actual likelihood of events. A model is well-calibrated if, for predictions with a confidence of <strong>p</strong>, the proportion of correct predictions is also approximately <strong>p</strong>.</p><p>We can do this by performing the distance of the <strong>Accuracy </strong>of a bin<em> acc(Bm)</em> and the <strong>Confidence </strong>of a bin <em>conf(Bm):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*yThxpD4N_1Hgw3Rz87LYtA.png" /></figure><p>And, therefore, we can compute the ECE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*-d1jDScyJ-Nppozhu-xAeg.png" /></figure><p>In my experiments, I did not see an exact superiority because the vanilla classifier was already able to achieve a very low ECE. Again, this can be explained due the simplicity of the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lv2HXxc0aIr568g4LSI0nQ.png" /><figcaption>Trained on MNIST both for 10 epochs and Lambda=1.</figcaption></figure><p>On the official paper, on the other hand, they trained in CIFAR100 dataset (considerably more complex in comparison to MNIST) and they were able to get very distinguishable ECE metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*S7U4FhxV4eQgeMaPawVTQQ.png" /></figure><p>I believe the important factor here is that JEM can be way more interesting when dealing with complex datasets.</p><p>The authors also claimed that there is little of a trade-off in terms of accuracy when training EBMs in comparison to simple classifiers. We lose a very tiny bit of accuracy.</p><p>And, of course, one important thing that vanilla classifiers do not have is generative sampling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*62H32i5U8UMCXUQobZO-SA.png" /><figcaption>Images generated from the JEM via MCMC (steps=4000, step_size=0.1 — not correctly calibrated)</figcaption></figure><p>When correctly tuned and explored with different hyperparameters, they can generate really good results (check the papers on the reference)!</p><h3>Conclusion and Discussion</h3><p>We studied in this article EBMs and one interesting approach to integrate EBMs with softmax-based models, the JEMs.</p><p><strong>Energy-Based models are complex</strong>. They are way harder to train in comparison to simple softmax classifiers and I would say almost or even harder to train in comparison to vanilla GANs. <br>They are very sensitive to hyperparameters and can easily diverge during training.</p><p>However, if correctly tuned and trained, they can be <strong>very powerful.</strong></p><p>EBMs are an active research area in neural networks and researchers are finding ways to make EBMs “easier” to train, but also giving more performance. You can check various works in the reference topic.</p><p>Thank you so much for reading and see you in the next chapter!</p><h3>References</h3><p><a href="https://arxiv.org/abs/1912.03263"><em>[1912.03263] Your Classifier is Secretly an Energy Based Model and You Should Treat it Like One</em></a><em> </em>(JEMs)<em><br></em><a href="https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/tutorial8/Deep_Energy_Models.html#Energy-Models">Tutorial 8: Deep Energy-Based Generative Models — UvA DL Notebooks v1.2 documentation</a> (very good!)<br><a href="http://www.stat.ucla.edu/~ywu/GenerativeConvNet/doc/GConvNet.pdf">A Theory of Generative ConvNet</a><br><a href="https://arxiv.org/pdf/1609.09408v1">Cooperative Training of Descriptor and Generator Networks</a><br><a href="https://arxiv.org/pdf/2004.01301">Generative PointNet: Deep Energy-Based Learning on Unordered Point Sets for 3D Generation, Reconstruction, and Classification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a69f1779188" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative Adversarial Networks (GANs, WGANs, WGANs-GP) — Generative Intuition & Practice]]></title>
            <link>https://medium.com/@mathparracho/generative-adversarial-networks-gans-wgans-wgans-gp-generative-intuition-practice-24cb2dd43ed9?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/24cb2dd43ed9</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[generative]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 18:09:14 GMT</pubDate>
            <atom:updated>2024-11-19T18:09:14.988Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generative Adversarial Networks (GANs, WGANs, WGANs-GP) — Generative Intuition &amp; Practice</h3><p>In recent years, Generative Adversarial Networks (GANs) have taken the field of artificial intelligence a lot, emerging as one of the most amazing advancements in the field of Deep Learning.</p><p>This is the second in a series (<strong><em>Generative Intuition &amp; Practice</em></strong>) of three (or maybe more) articles, where we will explore these most prominent generative architectures with Pytorch implementations from scratch using the CelebA dataset: a dataset of faces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*t7KJnWDutt05qxSmS2vFUw.png" /><figcaption>Some Results of epoch10 using wgan-gp</figcaption></figure><p>We are going to see the mathematical foundations of the architecture, how can we implement in Pytorch, and see some results (and problems). This article will be focused on the training and improving the stability of it. The next articles will be focused on improving the quality of the training</p><p>Full code link: <a href="https://www.kaggle.com/code/matheusparracho/generative-adversarial-nets-gans-wgan-wgan-gp">https://www.kaggle.com/code/matheusparracho/generative-adversarial-nets-gans-wgan-wgan-gp</a></p><p>Link to the previous article of <a href="https://medium.com/@mathparracho/variational-autoencoders-vaes-cvaes-%CE%B2-vaes-generative-intuition-practice-4b7b4011f55b"><strong><em>Generative Intuition &amp; Practice — How does VAEs work?</em></strong></a></p><h3><strong>How do GANs work?</strong></h3><p>GANs work by contrasting two neural networks against each other in a game of adversarial training, where one network generates data while the other critiques it.</p><p>Here’s a diagram of how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*x4Vub5Blat-FJSNztsCHGA.png" /></figure><ul><li><strong>Generator (G):</strong> This network creates fake data with the goal of mimicking real data as closely as possible. It starts with random noise and tries to generate data that resembles the real dataset.</li><li><strong>Discriminator (D):</strong> This network evaluates the data, distinguishing between real data from the dataset and the fake data generated by the Generator. Its job is to become better and better at telling real from fake.</li></ul><p><strong><em>So yes, in theory, it can work, but the main question is: how can we train this thing?</em></strong></p><p>Each network has its own objective function, but they are trained together: one to minimize, the other to maximize. Let`s understand deeply each formulation.</p><p><strong>The Discriminator Loss:</strong></p><p>The Discriminator wants to maximize its capability of classifying an input image as fake or real. And this can be expressed like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*sRUyRPmSzKnmu8NZc2Pm1Q.png" /></figure><p>We want to minimize the negative of the expected value of the discriminator output regarding the sample from the real data (<strong>maximize the expected value for high probabilities regarding the real data</strong>) and minimize the negative of the expected value of the negative of the samples generated from the generator (<strong>maximize the expected value for low probabilities regarding the fake data</strong>).</p><p>It is a binary classifier, so… anything similar to the Binary-Cross-Entropy?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*S2Q3sx1xkw3c53-Ld1j9qA.png" /></figure><p>Yes! Because, essentially, they are the same! The only difference here is the “false” label is created by the Generator, and the “true” label is the real image. In other words, the samples are taken from different distributions.</p><p>In a nutshell, I like to see the loss function of the discriminator as just a BCE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*nz_UQDOKn_mGNtTBVXc40A.png" /></figure><p><strong>The Generator Loss:</strong></p><p>The generator, on the other hand, wants to minimize this objective function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*qcANw3tMfyH4RylZOkBPZA.png" /></figure><p>So, here, we want to maximize (minimize the negative) the expected value of the discriminator’s probability output log(D(G(z))). In other words, we just want to <strong>maximize the probability of the Discriminator thinking that the fake images are real</strong>.</p><p><strong>The Monte Carlo Approximation:</strong></p><p>One important thing to know to understand that bridge between the theoretical foundation and the practical/algorithmic step is the <strong>Monte Carlo approximation </strong>for discrete samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*M8uAqKHoeBwR9-T7UZGGDg.png" /></figure><p><em>The expected value is approximated by the average of the samples in the minibatch.</em></p><p>It allows us to compute via iterative methods (discrete).</p><p><strong>The adversarial training:</strong></p><p>The adversarial loss states that we must train each network separately in this certain algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzd_OQLMz7JnJG5BHgdm8Q.png" /><figcaption>Source: Official GAN paper</figcaption></figure><p><em>*notice that in the generator step, we find it different from minimizing the objective -E(log(D(G(z)))).</em></p><p>Let`s analyze the special cases to better understand each update step:</p><ol><li>First, for the real images, we give the label 1, and for the fake images, we give the label 0.</li><li>D(X) and D(G(z)) are inside the interval [0,1] because the activation function of the discriminator is a sigmoid. Tanh is used in the activation function of the generator (G(z)); it is a common practice (when you normalize the images in [-1,1]. If you normalize your images in [0,1], use sigmoid!).</li><li>Knowing that D(.) ∈ [0,1], we can observe that log(D(.)) ∈ [-∞, 0].</li><li>The Discriminator loss (sum of two log functions) still has its image in the interval [-∞, 0]. The <strong>maximum is 0</strong>, and it happens<strong> </strong>when<strong> D(x)=1 and D(G(z))=0</strong>. This means that the discriminator was able to correctly classify between true samples and fake samples.</li><li>The Generator loss (only one log function) has its image in the interval [-∞, 0]. The <strong>minimum is -∞</strong>, and it happens when log(1–1) = log(0), which means <strong>D(G(z)) = 1</strong>, meaning that the discriminator thinks that the fake image is true.</li></ol><p>Okay, so finally we understand that the <strong>Discriminator wants to maximize</strong> its objective function while the <strong>Generator wants to minimize</strong> its objective function. Combining all together knowing the adversarial aspect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*FHQ_faPCqrhuLdGT05peyA.png" /></figure><p>We can write like this because, in the generative update, we do not use the real data, so the first term (E[log(D(x))]) does not appear in the generative step.</p><p>So, in resume, we have this pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kf1STtX8IyLxhzjQaxLM1g.png" /><figcaption>Source: <a href="https://jonathan-hui.medium.com/gan-wasserstein-gan-wgan-gp-6a1a2aa1b490">https://jonathan-hui.medium.com/gan-wasserstein-gan-wgan-gp-6a1a2aa1b490</a></figcaption></figure><p><strong>Proving:</strong></p><p>We want the distribution of the generator <em>Pgenerator(x) </em>to be as close as possible to the distribution of the data <em>Pdata(x).</em></p><p>Let`s observe the discriminator. We want to maximize the objective function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*UkQK56fHOP2ZsaEHMkdY-A.png" /></figure><p>Let`s make the derivative equal to 0 (find the ideal maximum of the function):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*ElhxOj3WFwjxhAmepcNFEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*JXH13IjWD38Q51cF8R4b9g.png" /></figure><p>This is equivalent to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*1sjRBYV0j4G6A3W3YUEQMg.png" /></figure><p>Where <strong><em>D*(x)</em></strong> is the ideal discriminator.</p><p>Now, let`s substitute this ideal discriminator in the original objective function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*Z-GDw-Kr_yEJg2qEneF6rA.png" /></figure><p>This expression is equivalent to Jensen-Shannon Divergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*y6zFl-qkvvVZXdwCaUUAxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*K8eioUMS0DWHbNqRwpNArA.png" /></figure><p>So, minimizing V(G) means that we are minimizing<em> JSD(Pdata||Pgenerator)</em>. In other words, we are minimizing the divergence between <em>Pdata </em>and <em>Pgenerator </em>(approximating both distributions).</p><p>This proof does not guarantee a global maximum, but instead, it states the existence of this critical point.</p><p>Okay, so let`s see how to implement the <strong><em>exact ORIGINAL </em></strong>training algorithm in Pytorch:</p><pre>generator = Generator(z_dim, img_channels).to(device)<br>discriminator = Discriminator(img_channels).to(device)<br><br>optimizer_G = optim.Adam(generator.parameters(), lr=learning_rate, betas=(beta1, 0.999))<br>optimizer_D = optim.Adam(discriminator.parameters(), lr=learning_rate, betas=(beta1, 0.999))<br><br>#original discriminator loss<br>def discriminator_loss(d_real, d_fake):<br>    #as we want to maximize L_d by gradient ascend = we minimize the -L_d by gradient descend<br>    loss = - (torch.mean(torch.log(d_real + 1e-8)) + torch.mean(torch.log(1 - d_fake + 1e-8)))<br>    return loss<br><br>#original generator loss<br>def generator_loss_original(d_fake):<br>    # we want to minimize the G_d by gradient descend<br>    loss = torch.mean(torch.log(1 - d_fake + 1e-8))<br>    return loss<br><br>k = 1 #k as hiperparameter stated in the paper<br><br>#training algorithm<br>for epoch in range(num_epochs):<br>    for i, (real_images, _) in enumerate(tqdm(dataloader)):<br>        real_images = real_images.to(device)<br>        b_size = real_images.size(0)<br><br>        #for loop for training the discriminator<br>        for _ in range(k):<br>            discriminator.zero_grad()<br><br>            #real images discriminator output<br>            d_real = discriminator(real_images).view(-1)<br><br>            #generating fake images by inputting noise into the generator<br>            noise = torch.randn(b_size, z_dim, 1, 1, device=device)<br>            fake_images = generator(noise)<br><br>            #output of the discriminator (without gradients for the generator!)<br>            d_fake = discriminator(fake_images.detach()).view(-1)<br><br>            #finally putting all into the loss<br>            loss_D = discriminator_loss(d_real, d_fake)<br>            loss_D.backward()<br>            optimizer_D.step()<br><br>        #end for loop<br><br>        #training the generator<br>        generator.zero_grad()<br><br>        #generating fake images<br>        noise = torch.randn(b_size, z_dim, 1, 1, device=device)<br>        fake_images = generator(noise)<br><br>        #output of the discriminator using these fake images<br>        d_fake = discriminator(fake_images).view(-1)<br><br>        #loss function for the generator<br>        loss_G = generator_loss(d_fake)<br>        loss_G.backward()<br>        optimizer_G.step()<br>    #end for loop<br>#done<br><br>        #just to check the losses<br>        if i % 100 == 0:<br>            print(f&#39;Epoch [{epoch+1}/{num_epochs}] Batch {i}/{len(dataloader)} &#39;<br>                  f&#39;Loss D: {loss_D.item():.4f}, Loss G: {loss_G.item():.4f}&#39;)</pre><p>If you train the exact algorithm above, the losses are going to collapse quickly:</p><pre>Epoch [1/20] Batch 0/2544 Loss D: 1.4045, Loss G: -0.0215<br>Epoch [1/20] Batch 100/2544 Loss D: 0.0001, Loss G: -0.0000<br>Epoch [1/20] Batch 200/2544 Loss D: 0.0000, Loss G: -0.0000</pre><p>So what happened? The original paper states that:</p><blockquote>Early in learning, when G is poor, D can reject samples with high confidence because they are clearly different from the training data. In this case, log(1 − D(G(z))) saturates. Rather than training G to minimize log(1 − D(G(z))) we can train G to maximize log D(G(z)). This objective function results in the same fixed point of the dynamics of G and D but provides much stronger gradients early in learning.</blockquote><p>So… instead of <strong>minimizing </strong>log(1 − D(G(z))), we will try to <strong>maximize </strong>log D(G(z)):</p><pre>def generator_loss_non_saturating(d_fake):<br>    # we want to maximize L_G = E[log D(G(z))], i.e, minimize -L_G = -E[log D(G(z))]<br>    loss = - torch.mean(torch.log(d_fake + 1e-8))<br>    return loss</pre><p>The losses, now, look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSCMuL5TS5m0N5oB1pFFHw.png" /><figcaption>Red: Generator Loss | Blue: Discriminator Loss</figcaption></figure><p>Finally, let`s see the results from some early epochs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*047MXhF_Hrgfe2r8cmt_pA.gif" /></figure><p>Great! We managed to create our first vanilla GAN!</p><p>Remember to check the <a href="https://www.kaggle.com/code/matheusparracho/generative-adversarial-nets-gans-wgan-wgan-gp">full code link</a>!</p><p><strong><em>How can we evaluate the performance of our GAN? The FID</em></strong></p><p>The <strong>Fréchet Inception Distance</strong> (FID), or <strong>Wasserstein-2 distance</strong> for Gaussian distributions, evaluates the quality of images generated by a GAN by comparing the distribution of real and generated samples in the feature space. Instead of working directly with raw pixel values, FID uses the feature space of a pre-trained Inception network, which captures high-level representations of the images.</p><p>FID measures the difference between two multivariate Gaussian distributions — one for the real images and the other for the generated images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*Hcqp9k46qnbcrMCvNpzGaA.png" /></figure><p>The first term measures the difference in means, while the covariance terms capture the difference in the spread of the feature distributions.</p><p>So, what we do is:</p><ol><li>Generate a large number of samples from the GAN.</li><li>Use the pre-trained Inception network to extract features from both the generated and real samples.</li><li>Compute the mean and covariance for both distributions.</li><li>Apply the FID expression.</li></ol><p>Lower FID scores indicate that the generated samples are closer to the real data distribution, implying higher quality and diversity.</p><p><strong><em>Bonus from my curiosity and learning from my errors: can we train both together in a combined loss?</em></strong></p><p>This question raised my curiosity while I was studying the formulation of this loss. Combining both losses we would have this expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*uducv24-PIbwmqL-VFioew.png" /></figure><p>And why not optimize this only big loss instead of separately training each network using the min-max approach? I mean, it is clear that we are going to have some problems because the loss, at the same time, is updating E(log(1-D(G(z)))) and E(log(D(G(z))))… but let`s give it a try.</p><p>I developed the following algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*VX9rDJuyip-EH9SJ1qExfA.png" /><figcaption>Algorithm for the combined loss in GAN. Source: author</figcaption></figure><p>I tested this approach. Let`s see the results in the epoch2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*w9cN0wW_lPp61r5C-fK52g.png" /><figcaption>Epoch 2 training in the Celeb Dataset</figcaption></figure><p>Terrible! What happened here? The loss collapsed.</p><p>A combined loss function disrupts the adversarial dynamic by forcing the Generator and Discriminator to minimize a shared objective, removing the competition needed for effective training.</p><p>This cooperation confuses gradient directions — each network should have opposing goals — and leads to instability, often causing chaotic outputs or “mode collapse,” where the Generator produces only noise or repetitive patterns.</p><p>In Pytorch, I wrote the combined loss like this:</p><pre>def combined_gan_loss(discriminator, generator, real_images, noise):<br><br>    real_loss = torch.log(discriminator(real_images) + 1e-8).mean()<br><br>    fake_images = generator(noise)<br>    <br>    ##loss for the discriminator using the fake images<br>    fake_loss_discriminator = torch.log(1 - discriminator(fake_images) + 1e-8).mean()<br>    <br>    ##loss to the Generator trying to get fake images to be set as real<br>    fake_loss_generator = torch.log(discriminator(fake_images) + 1e-8).mean()<br><br>    ##combined loss<br>    loss = - (real_loss + fake_loss_discriminator + fake_loss_generator)<br>    return loss</pre><p>All code is written in the Kaggle link.</p><h3>How do WGANs work?</h3><p>Vanilla GANs suffer from two big problems: the notorious issue of <strong>mode collapse</strong> and <strong>training instability</strong> .This variation comes as a way to solve challenges associated with vanilla GANs:</p><p>WGAN is a variation of the vanilla GAN that bases the training on <strong>reducing the Wasserstein Distance</strong> (also known as the Earth Mover’s Distance) <strong>instead of reducing the JS Divergence</strong> of the distributions.</p><p>The W. Distance is more stable and provides better gradients for training, especially when the distributions are far apart.</p><p><strong><em>The Wasserstein Discriminator (or the “Critic”):</em></strong></p><p>Instead of using the loss as a probability distribution function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*Xdyjl_Q9etVnGO9NjfpQvg.png" /></figure><p>We are going to use a pure distance-based objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*xc6ITTeiURXsRm4ZPuAXxA.png" /></figure><p>where 𝐷 is a Lipschitz function (with Lipschitz constant less than or equal to 1). The Wasserstein distance is maximized with respect to 𝐷 to find the largest difference between the expectations of the real and generated samples.</p><p><strong><em>What is the Lipschitz condition?</em></strong></p><p>A function 𝑓 is called Lipschitz-continuous if there exists a constant 𝐾 (called the Lipschitz constant) such that, for any two points 𝑥1 and x2 in the domain 𝑓:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*wDG8bTTuruLSxo4ODzuvIA.png" /></figure><p>This just means that the function 𝑓 cannot vary “too quickly”; its rate of change between two points is limited by the constant 𝐾.</p><p>In a nutshell, it is just to avoid divergence and/or gradient explosion due to the strong change in the gradient.</p><p>The discriminator in a WGAN does not act as a binary classifier (as in conventional GANs). Instead, it tries to assign “scores” to the real and generated samples, so that the score of the real samples <strong><em>D(x) for x~Preal</em></strong><em> </em>is higher than possible, and the score of<em> </em><strong><em>D(G(z)) for z~Pz</em></strong><em> </em>the lower the possible.</p><p>Therefore, the loss function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*XVes-ziRkOVB4K2KzXV34A.png" /></figure><p><strong><em>The Wasserstein Generator:</em></strong></p><p>The generator tries to maximize the average score that the discriminator gives to the generated samples. The generator’s loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*vCJfn7bo6xNvR9d0VRONfg.png" /></figure><p>It tries to maximize the average score that the discriminator gives to the generated samples.</p><p><strong><em>The Training Algorithm:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lMJaTRpLT6lT0jEbIsLiA.png" /><figcaption>Source: Official WGAN Paper</figcaption></figure><p>The idea here is exactly the same as the vanilla GAN, only changing the loss function. We only have to pay attention to these few things in the implementation:</p><ul><li>The experiments presented in the paper used RMSProp as the optimizer</li><li>We have a clipping operation after the backpropagation step due to the Lipschitz condition</li></ul><p>In resume, we have this pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnVKVUEgqmwKFOXO9fKkKQ.png" /><figcaption>Source: <a href="https://jonathan-hui.medium.com/gan-wasserstein-gan-wgan-gp-6a1a2aa1b490">https://jonathan-hui.medium.com/gan-wasserstein-gan-wgan-gp-6a1a2aa1b490</a></figcaption></figure><p>Okay, so let`s see what changes in Pytorch:</p><pre>#using RMSProp<br>optimizer_G = optim.RMSprop(generator.parameters(), lr=learning_rate)<br>optimizer_D = optim.RMSprop(discriminator.parameters(), lr=learning_rate)<br><br>#clipping for Lipschitz condition<br>weight_clip_value = 0.01<br><br>#WGAN distance-based losses<br>def discriminator_loss(d_real, d_fake):<br>    loss = -(torch.mean(d_real) - torch.mean(d_fake))<br>    return loss<br><br>def generator_loss(d_fake):<br>    loss = -torch.mean(d_fake)<br>    return loss</pre><p>And, after the backpropagation step, we need to clamp the weights:</p><pre>for p in discriminator.parameters():<br>    p.data.clamp_(-weight_clip_value, weight_clip_value)</pre><p>However, during my experiments, I notice bad performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8XFCkd6v9pkogOu12T-RQ.png" /><figcaption>Training for early epochs</figcaption></figure><p><strong><em>But what happened here?</em></strong></p><p>The big problem of WGAN is the Lipschitz constraint.</p><p>From the original WGAN paper, we have the following:</p><blockquote>Weight clipping is a clearly terrible way to enforce a Lipschitz constraint. If the clipping parameter is large, then it can take a long time for any weights to reach their limit, thereby making it harder to train the critic till optimality. If the clipping is small, this can easily lead to vanishing gradients when the number of layers is big, or batch normalization is not used (such as in RNNs) … and we stuck with weight clipping due to its simplicity and already good performance.</blockquote><p>The problem in WGAN is to correctly tune the Lipschitz constraint. Clipping is simple but it introduces some problems. The model may still produce poor quality images and does not converge, in particular when the hyperparameter <strong><em>c</em></strong> is not tuned correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*FtMbrQGaR2Wg1fO2GzjL4g.png" /></figure><p>The model performance is very sensitive to this hyperparameter. In the diagram below, when batch normalization is off, the discriminator moves from diminishing gradients to exploding gradients when <strong><em>c</em></strong> increases from 0.01 to 0.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*nnm8iOPO_PkovLMEx_IR0w.png" /><figcaption>Source: official WGAN paper</figcaption></figure><p>I decided not to fine-tune the clipping parameter because the next idea comes to solve this issue:</p><h3>How do WGAN-GPs work?</h3><p><em>Is there a way to fix this issue of the Lipschitz condition caused by the clipping operation?</em></p><p><strong>WGAN-GPs, Wasserstein GAN (Gradient Penalty)</strong>, comes as a way to solve this issue of dependency of the correct (and manual) tuning of the Lipschitz constraint to get good convergence.</p><p>The gradient penalty works by adding a regularization term to the loss function, penalizing the norm of the gradient of the discriminator’s output.</p><p>The regularization stands in this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*iSD1lHVTBs29dTXojlfEEA.png" /></figure><p>The regularization ensures that the gradients are close to 1, basically stating the <em>Lipschitz continuity</em> condition. Therefore, we just substitute the “clipping” operation in the vanilla WGAN implementation by this penalty component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4Lfib4TaROmw8AAgVf78g.png" /></figure><p>The core differences here are the regularization in the loss calculation and ADAM as optimizer.</p><p>In Pytorch, we can implement the gradient penalty in this way:</p><pre>def compute_gradient_penalty(D, real_samples, fake_samples):<br>    alpha = torch.rand(real_samples.size(0), 1, 1, 1, device=device)<br>    interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True)<br>    d_interpolates = D(interpolates)<br>    fake = torch.ones(d_interpolates.size(), device=device)<br><br>    gradients = torch.autograd.grad(<br>        outputs=d_interpolates,<br>        inputs=interpolates,<br>        grad_outputs=fake,<br>        create_graph=True,<br>        retain_graph=True,<br>        only_inputs=True<br>    )[0]<br><br>    gradients = gradients.view(gradients.size(0), -1)<br>    gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()<br>    return gradient_penalty</pre><p>And, now, the loss for the discriminator (or critic) will be:</p><pre>gradient_penalty = compute_gradient_penalty(discriminator, real_images.data, fake_images.data)<br><br>loss_D = -torch.mean(d_real) + torch.mean(d_fake) + lambda_gp * gradient_penalty</pre><p>Now we have a way more reasonable and stable training:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_N5ENMzRVPt2jSjB7ZDZeA.png" /><figcaption>Blue: Discriminator | Orange: Generator</figcaption></figure><p>And we can get way more interesting results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YIfY4yPK6TYsO9se.gif" /><figcaption>Generation using WGAN-GP</figcaption></figure><p>In general, we can see better results only for 5 epochs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*JFL3M8Fk8ZSU6gb2rmXM7Q.png" /></figure><h3>Conclusion and What is next?</h3><p>In this study we observed how we can successfully generate new samples using our generator and some ways we can stabilize the training.</p><p>In the next articles we are going to see how we can improve the quality of the generations using PROGANs. Due to its complexity I decided to write an article specifically with the concepts introduced.</p><p>Also, in the following “episode” of <strong><em>Generative Intuition &amp; Practice</em></strong>, we are going to see how Diffusion Models work!</p><p>So, stay tuned and see you on the next articles!</p><h3>References</h3><p><a href="https://arxiv.org/abs/1406.2661">Generative Adversarial Networks — Official Paper</a></p><p><a href="https://arxiv.org/abs/1701.07875">WGAN — Official Paper</a></p><p><a href="https://arxiv.org/abs/1704.00028">WGANGP — Official Paper</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24cb2dd43ed9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variational Autoencoders (VAEs, CVAEs, β-VAEs) — Generative Intuition & Practice]]></title>
            <link>https://medium.com/@mathparracho/variational-autoencoders-vaes-cvaes-%CE%B2-vaes-generative-intuition-practice-4b7b4011f55b?source=rss-a26c71ab99ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b7b4011f55b</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[generative-model]]></category>
            <dc:creator><![CDATA[Matheus Ramos Parracho]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 01:14:14 GMT</pubDate>
            <atom:updated>2024-11-02T01:14:14.980Z</atom:updated>
            <content:encoded><![CDATA[<h3>Variational Autoencoders (VAEs, CVAEs, β-VAEs) — Generative Intuition &amp; Practice</h3><p>In recent years, deep learning models have revolutionized the way we understand and generate data. We have, today, three big powerful methods of generative architectures, each one of them with specific characteristics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kqiwelLF9Nv6fbET.png" /><figcaption>The generative models trilemma.</figcaption></figure><p>This is the first in a series (<strong><em>Generative Intuition &amp; Practice</em></strong>) of three articles, where we will explore these three most prominent generative architectures with Pytorch implementations from scratch using datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*naxI0qp2RwADJdOM4ebEgA.png" /><figcaption>Illustration of the Multivariate Gaussian Distribution — It is going to be used in the VAE modelling</figcaption></figure><p>In this article, we are going to explore one of the first ideas of modern generative models: the <strong>Variational Autoencoder</strong>. Big generative models nowadays, like OpenAI’s DALL·E, Google’s Imagen, and VAE-GANs are based on VAEs (more complex versions, of course, but VAE is the foundation)!.</p><p>Complete VAEs, CVAEs, and β-VAEs Implementations codes: <a href="https://www.kaggle.com/code/matheusparracho/variational-autoencoders-vae-cvae-vae">Variational Autoencoders Codes</a></p><h3>Review — What is a “Deterministic” Autoencoder?</h3><p>An Autoencoder is a type of neural network used to learn efficient, compressed representations of data, typically for the purpose of dimensionality reduction or unsupervised feature learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3XraiznYV59yO21r.png" /><figcaption>Source: <a href="https://lilianweng.github.io/posts/2018-08-12-vae/">https://lilianweng.github.io/posts/2018-08-12-vae/</a></figcaption></figure><p>The idea is that we have a function responsible for changing the data domains. Suppose we have a signal in the G domain. The network learns how to transform (encode) it into a <strong>fixed vector</strong> in the latent space Z, and then reconstruct (decode) the data from this latent space to the G domain again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*kJtfSzyAKpqsr1gIowkfxw.png" /></figure><p>For the loss function, it is very common to use the MSE loss (exposed above). Here, we are dealing with fixed deterministic functions.</p><p>You can check an implementation with the code I created with more details <a href="https://medium.com/@mathparracho/autoencoders-and-latent-space-studying-their-power-for-data-compression-7f6b59d9694b">here</a></p><p><em>But what if we wanted to sample new data from an Autoencoder? Let`s further understand it with the VAE:</em></p><h3>From Autoencoder to VAE</h3><p>The Variational Autoencoder learns the <strong>probability distribution</strong> over the latent space, rather than encoding each input to a single fixed vector in that space. So, instead of having an <strong>Deterministic Encoder/Decoder</strong>, we have a <strong>Probabilistic Encoder/Decoder.</strong></p><p>This is good because we can easily interpolate between the distributions and, then, generate new samples.</p><p><strong><em>But how does it work? Let`s formalize the problem:</em></strong></p><p>Imagine that we have a true (real) distribution of the data that is described by a <strong><em>p*(x)</em></strong>, where <strong><em>x~Data</em></strong>.</p><p>We want to find a model parameterized by <strong><em>θ </em></strong>that better describes this real data, in other words, a distribution <strong><em>pθ(x) </em></strong>capable of being as close as possible to the true distribution of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*wYxd28lFhP6U4HWfooHpCg.png" /></figure><p>So, actually, we are dealing with this problem: we want to find the best parameters of the model that describes the data, in other words, a problem of maximizing the likelihood on the data that we have (MLE — Maximum Likelihood Estimation).</p><p>Now, we assume an import factor: all this data can be described by an “<strong><em>latent representation — z</em></strong>” that defines some <strong><em>hidden rules </em></strong>for describing this data.</p><p>So, we want a way to map the data from the “Data-Domain” into this “Z-Domain” (inference step) but also a way to reconstruct the data from the “Z-Domain” into the “Data-Domain” (generation step):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*MagYyF5mZBW4oeEqXCNE7g.png" /></figure><p>So, essentially, what we are trying to find is the joint probability distribution that describes the relationship between the two random variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*l3lloKJ3IciG4b4Dl-y7WQ.png" /><figcaption>The joint probability: it shows all the relationships between the 2 random variables</figcaption></figure><p>We do not know the distribution that describes the random variable <strong><em>z</em></strong>, so we assume it follows a multivariate Gaussian distribution N(0,I) as the prior distribution for <strong><em>z. </em></strong>This because we want the latent space to be well structure and regularized. (That is why it is not defined as <strong><em>pθ(z)</em></strong>, but <strong><em>p(z)</em></strong>).</p><p>Let`s try to marginalize this joint distribution to get the probability of <strong><em>pθ(x):</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*A1uKe7-xdSCRpSB5xs7b7g.png" /></figure><p>Calculating this marginal likelihood requires integrating over all possible configurations of <strong><em>z</em></strong>, which is computationally infeasible in high-dimensional latent spaces.</p><p>And, just to be clear, the other way around does not make sense because we do not have the distribution on <strong><em>pθ(x) </em></strong><em>— this is what we want to find</em><strong><em>:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*LJWLnTl0STehJOe64NE0mQ.png" /></figure><p>The idea of the VAE is that we do not need to compute the marginal itself, the idea is to increase the distribution to the real one using the <strong>data</strong> that we have by expressing the Bayesian relationship:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*wRNUdMn6WE1DmWb4BF3L3A.png" /></figure><p>By calculating the posterior <strong><em>pθ(z|x)</em></strong>, we can use the Variational Inference (Amortized VI) theory to approach this problem. The idea is that we introduce an approximate posterior distribution <strong><em>qϕ(z|x)</em></strong>, which we model as a Gaussian distribution, and approximate it to the real posterior <strong><em>pθ(z|x). </em></strong><em>We are going to see further in this article how we can do that.</em></p><p>Using this Bayesian interpretation, we have that our hypothesis is the latent space <strong><em>Z,</em></strong> and our evidence is the likelihood that our distribution parameters <strong><em>θ </em></strong>are appropriate to the data <strong><em>x</em></strong> that we observe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*rANOkqTQVOh-QqUyizLKDA.png" /></figure><p><em>So, let`s recap</em>: the joint distribution <strong><em>pθ(x, z)</em></strong> is tractable because <strong><em>p(z)</em></strong> is a Normal distribution <strong><em>N(z; mean = 0, variance = 1)</em></strong>. The conditional distribution <strong><em>pθ(x|z)</em></strong> can be modeled as either a multivariate Gaussian <strong><em>N(x; mean = μθ(z), variance = σθ * I)</em></strong> for continuous data, where <strong><em>μθ(z)</em></strong> and <strong><em>σθ</em></strong> are parameters learned by the decoder network, or as a Bernoulli distribution for binary data.</p><p>By calculating this posterior <strong><em>pθ(z|x) </em></strong>using Variational Inference, having <strong><em>pθ(z) </em></strong>and <strong><em>pθ(x|z)</em></strong>, we can find<strong><em> pθ(x) </em></strong>using using the Bayes relation showed above. And <em>voilà</em>, we found the real data distribution!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*JqEQc0IJlABXI7jNleL9OA.png" /><figcaption>Schema of everything we need to calculate <em>pθ(x) Source: Author</em></figcaption></figure><p><strong><em>Now let`s understand how we can approximate via Variational Inference:</em></strong></p><p>The point is to go from a Bayesian inference problem to an optimization problem to be calculated via numerical methods (gradient descent in our case). And this can be done via variational inference.</p><p>Since directly computing the true posterior distribution <strong><em>pθ(z|x)</em></strong> is intractable due to the integral over all possible <strong><em>z</em></strong>, we introduce an approximate posterior distribution <strong><em>qϕ(z|x)</em></strong>, which we model as a Gaussian distribution (because it is mathematically tractable). The encoder neural network parameterized by <strong><em>ϕ </em></strong>outputs the parameters (mean and variance) of this Gaussian distribution used by the decoder <strong><em>pθ(x|z)</em></strong>.</p><p>Now, we have two distributions and we want <strong><em>qϕ(z|x) </em></strong>to be as close as possible from the original<strong><em> pθ(x|z). </em></strong>So, ideally, what we want is to minimize the <em>reversed </em>KL-Divergence of the two probability distributions: <strong><em>DKL(qϕ(z|x)||pθ(z|x))</em></strong>.</p><p><strong><em>Why the reversed DKL?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UQH4DTD-ghbJ1GYZ.png" /><figcaption>Source: <a href="https://blog.evjang.com/2016/08/variational-bayes.html">blog.evjang.com/2016/08/variational-bayes.html</a></figcaption></figure><p>DKL is not symmetrical, therefore DKL(P|Q) is not equal to DKL(Q|P) when Q is different from P.</p><p>Reversed DKL places higher penalty on regions where <strong><em>qϕ(z∣x)</em></strong> is high but <strong><em>pθ(z∣x)</em></strong> is low, which encourages <strong><em>q </em></strong>to focus on a “mode-seeking” approximation. This means <strong><em>q </em></strong>will try to find areas where <strong><em>p </em></strong>is high and ignore areas where p is low.</p><p><strong><em>Ok, so now let’s continue with the DKL expression:</em></strong></p><p>We can do some manipulations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*M_5wCWdZbi-NgEZr6k9rzw.png" /></figure><p>We define the Evidence Lower Bound (ELBO), which serves as a tractable surrogate objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*qOwcMcvFHWCsavyiRQLtLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*N8cYRvCv0aRxsAyxNuGlnA.png" /></figure><p>And maximizing the ELBO (or minimize the loss function (-ELBO)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*fwgq-xoxtzN-u3z4yREL8w.png" /></figure><p>is equivalent to simultaneously maximizing <strong><em>ln(pθ(x))</em></strong> and minizine the KL Divergence. In other words, maximizing the log-likelihood of the observed data (reconstruction), and minimizing the divergence of the approximate posterior <strong><em>qϕ(⋅|x)</em></strong> from the exact posterior <strong><em>pθ(⋅|x)</em></strong> (A regularization factor).</p><p>This optimization will be done via gradient descend.</p><p>If you want to know more about the ELBO and this optimization step, check on : <a href="https://en.wikipedia.org/wiki/Variational_autoencoder">Variational autoencoder — Wikipedia</a> and <a href="https://en.wikipedia.org/wiki/Evidence_lower_bound">Evidence lower bound — Wikipedia</a></p><p><strong><em>But… ELBO uses a sampling operation, and this is not differentiable. So how can we make it differentiable?</em></strong></p><p>We can calculate the gradients from regarding <strong><em>θ:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*R4N-NyPBY752GZHhIr9MzA.png" /></figure><p>But for our approximative distribution, we cannot since ϕ appears in the probability distribution itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*Ay6DO8MFVqZaPuuR2dDBAQ.png" /></figure><p><strong><em>This is where the Reparameterization Trick (or stochastic backpropagation) enters:</em></strong></p><p>The idea is to reformulate the sampling operation z~qϕ(z|x) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*wNxe6ZaIZzvl9_an8v638A.png" /></figure><p>μ(x) and σ(x) are the encoder outputs, and ϵ is a normally distributed random variable. This reformulation allows gradients to flow through μ and σ, enabling the use of backpropagation within the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0VVE0o927A1bNqp1.png" /></figure><p>If you want to know more about the reparameterization trick and how the gradients indeed will be, check on : <a href="https://en.wikipedia.org/wiki/Variational_autoencoder">Variational autoencoder — Wikipedia</a></p><p><strong><em>Let`s implement the architecture in Pytorch:</em></strong></p><p>Observing it in Pytorch, we can create a class to encode and then output the parameters of the distribution related to the input data:</p><pre># the MNIST data has each data sample with dimensions: 1x28x28<br><br>class Encoder(nn.Module):<br>    def __init__(self, input_channels, hidden_dim, z_dim):<br>        super(Encoder, self).__init__()<br>        self.conv1 = nn.Conv2d(input_channels, 32, kernel_size=4, stride=2, padding=1)  <br>        self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2, padding=1)              <br>        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1)  <br>           <br>        self.fc_mu = nn.Linear(128 * 4 * 4, z_dim)<br>        self.fc_logvar = nn.Linear(128 * 4 * 4, z_dim)<br><br>    def forward(self, x):<br>        h = F.relu(self.conv1(x)) # 1x28x28 -&gt; 32x14x14<br>        h = F.relu(self.conv2(h)) # 32x14x14 -&gt; 64x7x7<br>        h = F.relu(self.conv3(h)) # 64x7x7 -&gt; 128x4x4<br>        h = h.view(h.size(0), -1) # 128x4x4 -&gt; 128x16 (just to &quot;concatenate all 2D data into 1 single dimension&quot;)<br>        <br>        mu = self.fc_mu(h)<br>        logvar = self.fc_logvar(h)<br>        return mu, logvar</pre><p>The decoding / generative part we want to transform from the Z space into the X again. So let`s see how it can be built:</p><pre>class Decoder(nn.Module):<br>    def __init__(self, z_dim, hidden_dim, output_channels):<br>        super(Decoder, self).__init__()<br>        self.fc = nn.Linear(z_dim, 128 * 4 * 4)<br>        self.deconv1 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, output_padding=1)  # 4x4 -&gt; 8x8<br>        self.deconv2 = nn.ConvTranspose2d(64, 32, kernel_size=4, stride=2, padding=1)                    # 8x8 -&gt; 16x16<br>        self.deconv3 = nn.ConvTranspose2d(32, output_channels, kernel_size=4, stride=2, padding=1)       # 16x16 -&gt; 32x32<br>        self.output_layer = nn.Conv2d(output_channels, output_channels, kernel_size=5, stride=1, padding=0)  # 32x32 -&gt; 28x28<br><br>    def forward(self, z):<br>        h = F.relu(self.fc(z))<br>        h = h.view(-1, 128, 4, 4)<br>        h = F.relu(self.deconv1(h))<br>        h = F.relu(self.deconv2(h))<br>        h = F.relu(self.deconv3(h))<br>        x_recon = torch.sigmoid(self.output_layer(h))<br>        return x_recon</pre><p>So gathering everything together:</p><pre>class VAE(nn.Module):<br>    def __init__(self, input_channels, hidden_dim, z_dim):<br>        super(VAE, self).__init__()<br>        self.encoder = Encoder(input_channels, hidden_dim, z_dim)<br>        self.decoder = Decoder(z_dim, hidden_dim, input_channels)<br><br>    def reparameterize(self, mu, logvar):<br>        std = torch.exp(0.5 * logvar)<br>        eps = torch.randn_like(std) #here is the assumption p(z)=N(0,I)<br>        return mu + eps * std<br><br>    def forward(self, x):<br>        mu, logvar = self.encoder(x)<br>        z = self.reparameterize(mu, logvar)<br>        x_recon = self.decoder(z)<br>        return x_recon, mu, logvar<br><br>#criterion = nn.MSELoss(reduction=&#39;sum&#39;)<br>criterion = nn.BCELoss(reduction=&#39;sum&#39;)<br>def loss_function(recon_x, x, mu, logvar):<br>    MSE = criterion(recon_x, x)<br>    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())<br>    return MSE + KLD</pre><p>So let`s observe the reconstruction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5_tME8NVsT19QAhCJvuEA.gif" /></figure><p>It should look similar to the Vanilla Autoencoder, and, indeed, it works that way. Now we want to see the generative process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sq7777vufOC9cIrdiLfRvw.png" /><figcaption>Train with MSE as Reconstruction Loss</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSsvaypjwYdlAw27gWKHoA.png" /><figcaption>Train with BCE as Reconstruction Loss</figcaption></figure><p>It works, our VAE is sampling from the latent space!</p><p>Using the same configurations I trained the MNIST in the code I posted on <a href="https://www.kaggle.com/code/matheusparracho/variational-autoencoders-vae-cvae-vae">Kaggle</a>, I also trained on the CelebA dataset of faces. And here we have the generation of new faces:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*Aat46etfvlqRkg4RWL30GQ.png" /><figcaption>Generation step using the Vanilla VAE architecture</figcaption></figure><p>So, yes! It managed get the join distribution for face features! Still, there is a lot to tune and to improve, and we are going to see how to improve these results in the next articles.</p><p>Complete code: <a href="https://www.kaggle.com/code/matheusparracho/variational-autoencoders-vae-cvae-vae">Variational Autoencoder</a></p><h3>What is a Conditional Variational Autoencoder (CVAE)?</h3><p>The <strong>CVAE </strong>(Conditional Variational Autoencoder) is a modification of the traditional VAE that introduces conditional outputs based on the input data.</p><p>Here we introduce a simple trick to make the network conditional to the input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*8XMi4mYZQtvTzA2WG2ybLA.png" /><figcaption>Label Concatenation in the Channel Dimension</figcaption></figure><p>The idea is simply to concatenate the information we want to conditionalize in the channel dimension:</p><pre>class ConditionalEncoder(nn.Module):<br>    def __init__(self, input_channels, hidden_dim, z_dim, num_classes):<br>        super(Encoder, self).__init__()<br>        self.num_classes = num_classes<br>        self.conv1 = nn.Conv2d(input_channels + num_classes, 32, kernel_size=4, stride=2, padding=1)<br>        self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2, padding=1)<br>        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1)<br>        self.fc_mu = nn.Linear(128 * 4 * 4, z_dim)<br>        self.fc_logvar = nn.Linear(128 * 4 * 4, z_dim)<br><br>    def forward(self, x, labels):<br><br>        # one-hot encode labels and expand dimensions shape [batch_size, num_classes, spatialY, spatialX],<br>        y = one_hot_encode(labels, self.num_classes).unsqueeze(2).unsqueeze(3) # [64, 10, 1, 1]<br>        y = y.expand(-1, -1, x.size(2), x.size(3)) #[64, 10, 28, 28] make a &quot;layer of conditional information&quot;<br>        # concatenate along the channel dimension<br>        x = torch.cat([x, y], dim=1)<br><br><br>        h = F.relu(self.conv1(x))<br>        h = F.relu(self.conv2(h))<br>        h = F.relu(self.conv3(h))<br>        h = h.view(h.size(0), -1)<br>        mu = self.fc_mu(h)<br>        logvar = self.fc_logvar(h)<br>        return mu, logvar</pre><p>Bonus: We can find a similar approach to deal with spatial coordinates here in this paper with CoorConvs: <a href="https://arxiv.org/abs/1807.03247">Paper</a></p><p>So, for instance, if I want to generate only new “0” samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJJBRdsJpkL7G91Jz3TZBQ.png" /></figure><p>Or, if I want to generate only new “1” samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uhfakn-oZIVvbaNcdJU7Q.png" /></figure><p>Or, only new “2” samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0smiMSUctvotOi83s3jCA.png" /></figure><h3>What is a β-VAE?</h3><p>The <strong>β-VAE</strong> (beta Variational Autoencoder) is a modification of the traditional VAE that introduces a hyperparameter, β (beta), to balance the trade-off between the reconstruction loss and the KL divergence loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*4VSHLLX8vUoLcUKNKy53hg.png" /></figure><p>In β-VAE, the KL divergence term is weighted by β, which controls how much importance is given to this term.</p><p>By increasing β (typically β &gt; 1), the model is encouraged to learn more disentangled representations in the latent space, which can be useful for interpretability and for generating factors of variation in the generated images. When β = 1, it reduces to the standard VAE.</p><p>So we simply put this parameter in our loss:</p><pre>def loss_function(recon_x, x, mu, logvar, beta=1.0):<br>    BCE = criterion(recon_x, x)<br>    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())<br>    return BCE + beta * KLD</pre><p>In a nutshell, this variation is just a form of regularization of the KL Divergence term. And it depends on the scope of your project.</p><h3>Conclusion and “What is next?”</h3><p>In the next articles, I will introduce a more complex variation of VAEs: the <strong>Vector Quantized VAE (VQ-VAE)</strong>. This model incorporates a discrete latent space, allowing it to capture richer features while maintaining a distinct representation of the input data.</p><p>Given the increased complexity and the unique structure of VQ-VAE, I will dedicate a specific article to fully explore its concepts and implementation.</p><p>Also, stay tuned for the next articles (<strong><em>Generative Intuition &amp; Practice</em></strong>), where I am going to analyse GANs and Diffusion Models deeply and compare them with the VAE.</p><p>If you have any questions or suggestions, feel free to comment! See you next time!</p><h3><strong>References:</strong></h3><p><a href="https://arxiv.org/pdf/1312.6114">Official Article</a></p><p><a href="https://blog.evjang.com/2016/08/variational-bayes.html">Eric Jang: A Beginner’s Guide to Variational Methods: Mean-Field Approximation</a></p><p><a href="https://lilianweng.github.io/posts/2018-08-12-vae/">From Autoencoder to Beta-VAE | Lil’Log</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b7b4011f55b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>