<?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 Saptarshi MT on Medium]]></title>
        <description><![CDATA[Stories by Saptarshi MT on Medium]]></description>
        <link>https://medium.com/@saptarshimt?source=rss-279584d7a23c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Saptarshi MT on Medium</title>
            <link>https://medium.com/@saptarshimt?source=rss-279584d7a23c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:48:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saptarshimt/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[Facial 3D Pose Estimation]]></title>
            <link>https://medium.com/@saptarshimt/facial-pose-estimation-bf75f8db1ffb?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf75f8db1ffb</guid>
            <category><![CDATA[pose-estimation]]></category>
            <category><![CDATA[3d-modeling]]></category>
            <category><![CDATA[keypoint-detection]]></category>
            <category><![CDATA[image-translation]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 08:47:38 GMT</pubDate>
            <atom:updated>2026-02-11T10:30:57.973Z</atom:updated>
            <content:encoded><![CDATA[<p>The following article is inspired from <a href="https://arxiv.org/pdf/2012.07791"><strong>Img2Pose</strong></a><strong> </strong>paper.</p><p>This is the start of my 3D journey. It will be a long one !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*tDJbmfupnoQbGj1f" /><figcaption>Euler angles Yaw, Pitch &amp; Role. It tells how a face turns in 3D, i.e can rotate in <strong>only three fundamental ways</strong>. Left-Right (Yaw), Up-Down(Pitch) &amp; Tilt Sideways(Roll). More info at the article.</figcaption></figure><p>There are a total of 68 primary facial keypoints. Once these keypoints are detected, the 3D pose of a face — namely pitch, yaw, and roll — can be estimated, allowing us to determine the face’s orientation in three-dimensional space. However, detecting and regressing these keypoints requires predicting 136 values (x, y coordinates for each keypoint), which can be challenging for most models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/0*fEF6s9gU9LKiFPHe" /></figure><p>As a result, an alternative indirect approach is often used: Instead of predicting all keypoints explicitly, our model predicts 9 values: 6 rotation parameters and 3 translation parameters. Using just these 9 values we can estimate key-points and pose of the face — making the learning problem significantly more tractable using even a smaller model.</p><blockquote><strong>From 3D World Coordinates to the 2D Image Plane</strong></blockquote><p>Whenever we capture a photograph of a real-world object, the camera performs a geometric transformation that maps points from the three-dimensional (3D) world onto a two-dimensional (2D) image plane. This transformation is governed by the principles of projective geometry and is commonly referred to as the <strong>camera projection model</strong>.</p><p>Mathematically, this process can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*pHRESGrZ2PF2GmPIZLOssg.png" /></figure><ol><li>The matrix <strong>[R∣t]</strong> represents the extrinsic camera parameters, which define the rotation and translation between the world coordinate system and the camera coordinate system. They describe the pose (position and orientation) of the camera relative to the world and are independent of any specific object in the scene.</li><li>Intrinsic Parameters: Camera Matrix <strong>K </strong>encodes the internal characteristics of the camera and maps points from the camera coordinate system to the image plane.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Bv8zHMPITXvrhbfdhNMY0Q.png" /></figure><p>In practice, the exact camera intrinsic matrix <strong>K</strong> is often unknown. Estimating <strong>K</strong> requires explicit camera calibration using known calibration patterns, which is rarely feasible in unconstrained, in-the-wild image settings. As a result, many vision systems rely on <strong>approximate intrinsics derived from image properties</strong>, most commonly the image <strong>width and height.</strong></p><p>When calibration data is unavailable, it is common to assume that the principal point lies at the center of the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*S73zU7xV-Kq2YMmyVn5i5g.png" /></figure><p>where <strong>W and H </strong>denote the image width and height in pixels, respectively.<br> This assumption holds reasonably well for most consumer cameras and introduces minimal error for many applications.</p><p>Same goes for the focal length cannot be directly recovered from a single image without additional constraints. However, a widely used heuristic is to approximate it as a function of the image size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*SCdFdjPv5aVoCuxLll6dkg.png" /></figure><p>Under these assumptions, the intrinsic matrix becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*4pqFYGxBsjhN-BGmu8oT-Q.png" /></figure><p>This approximation allows 3D-to-2D projection and pose estimation to proceed without explicit camera calibration.</p><blockquote><strong>Rotation and Translation</strong></blockquote><p>Let’s now focus on the two remaining unknowns: the rotation <strong>R</strong> and translation<strong> t</strong>. These parameters are not known beforehand and must be predicted by the neural network. The camera intrinsic matrix <strong>K</strong>, on the other hand, is assumed to be fixed and is defined using simple image properties.</p><p>Translation shifts the object’s position relative to the camera, affecting where it appears on the image plane. Rotation changes the object’s orientation in 3D space, determining how its shape and pose are perceived in the 2D image.</p><h4>A R<strong>otation matrix</strong></h4><p>is a mathematical tool used to turn a vector (or an object) around a fixed point (the origin) without changing its size or shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWO0sBQ73MYZSw7MhcC4sg.png" /></figure><p>In the real 3D world (like in a video game engine), an object is usually rotated on all three axes. We call these <strong>Euler Angles</strong> (Roll, Pitch, Yaw).</p><p>To get the final position, we multiply the matrices. <strong>Order matters! <br></strong>If you want to rotate around X, <em>then</em> Y, <em>then</em> Z, the math looks like this (remember, we read right-to-left in matrix math):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*vFYI_BatX1Bk5bhk0swKlw.png" /></figure><p>Rotation matrices are a specific subset of matrices called <strong>Special Orthogonal matrices</strong>, denoted as SO(n). They have very specific and useful properties :</p><ol><li>The columns of a rotation matrix are <strong>orthogonal unit vectors</strong>. <br><strong>Unit :</strong> The length of every column is 1. (Rotations do not stretch space). <br><strong>Orthogonal :</strong> The dot product of any two columns is 0. (The axes remain perpendicular; the space does not shear or skew).</li><li>The Inverse is the Transpose.</li><li>The Determinant is +1. The determinant measures how the area (or volume) changes. Since the determinant is 1, the area of the object stays the same.</li></ol><h4>A transaltion vector</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*h7RQvm4-LkD7heg2rWopAw.png" /></figure><p>where:</p><ul><li><strong>tx :​</strong> represents horizontal displacement (left or right). Increasing moves the object to the right in the image; decreasing it moves the object to the left.</li><li><strong>ty :</strong>​ represents vertical displacement (up or down). Increasing moves the object downward in the image; decreasing it moves the object upward (depending on the image coordinate convention).</li><li><strong>tz :</strong> represents depth (distance from the camera). It controls how <strong>close or far</strong> the object is from the camera. Larger tz means object appears smaller, and vice-versa.</li></ul><p>An important practical detail is that <strong>tz</strong> is <strong>scale-ambiguous</strong> when camera intrinsics are approximated. Increasing the focal length while proportionally increasing <strong>tz</strong> produces almost the same projection.</p><p>This is why many pose-estimation systems:</p><ul><li>fix <strong>K</strong></li><li>learn<strong> tz</strong> relative to a canonical object size (e.g., average face size).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*XurcP1EApha_z9iJSys5eQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8E3ygfHBWFDIEqIXSzEm6Q.png" /></figure><p><em>This is a </em><strong><em>full 6DoF head pose</em></strong><em>:</em></p><ul><li><em>3 DoF rotation</em></li><li><em>3 DoF translation</em></li></ul><blockquote><strong>Main Idea, Approach and Dataset</strong></blockquote><p>Our main goal is given 2D image predict [R t]. We already have images (wider-face or similar dataset), but we don’t have target values R &amp; t.</p><p>Coming to our main equation, i explained all the components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*led_2APqGvjeNywhoWJG2Q.png" /></figure><p>In the WIDER Face dataset, each image is annotated with five facial key-points: the centers of the two eyes, the nose tip, and the two corners of the mouth. <br>These annotated key-points correspond to <strong>2D image coordinates</strong> and form the left-hand side of the 3D–2D projection equation.</p><p>The camera intrinsic matrix <strong>K</strong> is fixed at the beginning of the pipeline. Since the original images vary in resolution, each detected face crop is resized to a fixed resolution of 128×128 pixels. The intrinsic parameters — focal length<strong> f </strong>and principal point<strong> (cx,cy)</strong> — are then defined accordingly, with the principal point assumed to lie at the image center and the focal length chosen proportional to the image size.</p><p>To define the corresponding <strong>3D points (x,y,z)</strong>, we rely on the <strong>mean Basel Face Model (BFM)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*1uCXV4aiopGGhOicTpFrlA.png" /></figure><p>The BFM is a statistical 3D face model built from a large collection of high-quality 3D face scans. Its mean shape represents an average human face and contains over 53,000 densely sampled 3D facial vertices, providing a consistent and anatomically meaningful facial geometry.</p><p>We select a small subset of 3D points from the mean BFM that correspond semantically to the annotated 2D landmarks — namely, the two eye centers, the nose tip, and the mouth corners. These selected 3D points act as canonical reference locations in object space and are paired with the observed 2D keypoints from the image.</p><p>This correspondence between fixed 3D landmarks from the mean BFM model and observed 2D facial key-points allows the system to estimate the unknown rotation and translation parameters, effectively recovering the 3D pose of the face from sparse 2D annotations.</p><p>************************************************************************</p><p>To reiterate, we work with thousands of face images, each annotated with its own set of five 2D facial keypoints. These 2D locations naturally vary from image to image due to differences in identity, pose, expression, and camera viewpoint. In our formulation, the camera intrinsic matrix <strong>K</strong> is fixed, and the corresponding 3D points are also fixed: we use the same five canonical landmarks extracted from the mean BFM 3D face model for every image. With these components in place, the goal is to estimate the rotation <strong>R</strong> and translation <strong>t </strong>for each face.</p><p>At this point, a natural question arises: if each face has different 2D key-points, shouldn’t the underlying 3D points also be different for each individual? After all, no two faces are exactly the same.</p><p>The key insight is that we are <strong>not trying to recover the exact 3D facial geometry of each person</strong>. Instead, we assume that all faces can be approximated by a common canonical shape — the mean BFM face — and that the observed differences in 2D keypoints are primarily explained by changes in pose rather than identity. Under this assumption, the role of <strong>R</strong> and <strong>t</strong> is to align the fixed 3D reference points to the observed 2D keypoints in the image.</p><p>In other words, the same set of 3D landmarks is reused across all images, while the pose parameters vary per image. This simplification allows us to decouple pose estimation from identity-specific shape variation, making the problem well-posed even with sparse 2D annotations. Although this approximation ignores fine-grained facial differences, it is sufficient for robust head pose estimation, where the primary objective is to recover orientation and position rather than detailed facial geometry.</p><blockquote><strong>Data Preparation</strong></blockquote><pre>import scipy.io as sio<br>import numpy as np<br>import cv2<br>import matplotlib.pyplot as plt<br>import os<br>import random<br>from pathlib import Path<br>import matplotlib.patches as patches<br>from PIL import Image<br>from tqdm import tqdm<br><br>import torch<br>from torch.utils.data import Dataset<br>from torchvision import transforms<br><br>from torch.optim.lr_scheduler import _LRScheduler<br>import math<br><br>from vit import Encoder<br><br>device = &#39;mps&#39;</pre><pre># https://www.kaggle.com/datasets/linhlthk19/basel-face-model<br>bfm = sio.loadmat(&quot;01_MorphableModel.mat&quot;)<br><br># Mean face (3N, 1) → (N, 3)<br>mean_shape = bfm[&quot;shapeMU&quot;].reshape(-1, 3)<br>print(mean_shape.shape)  # (~53490, 3)</pre><pre># https://github.com/anilbas/BFMLandmarks/blob/master/Landmarks68_BFM.anl<br><br>lm68 = np.array([<br>22143,22813,22840,23250,44124,45884,47085,47668,48188,48708,<br>49299,50498,52457,32022,32386,32359,32979,38886,39636,40030,<br>40238,40433,41172,41368,41578,42011,42646,8291,8305,8314,<br>8320,6783,7687,8331,8977,9879,1832,3760,5050,6087,4546,<br>3516,10731,11758,12919,14859,13191,12157,5523,6155,7442,<br>8345,9506,10799,11199,10179,9277,8374,7471,6566,5909,<br>7322,8354,9386,10941,9141,8367,7194<br>]) - 1 <br><br>face_68 = mean_shape[lm68]<br><br># normalise by nose<br>face_68_sub = face_68 - face_68[30] <br>face_68_std = np.std(face_68 - face_68[30])<br>face_68 = face_68_sub / face_68_std <br><br># 3D landmarks from BFM mean shape<br>nose_3d = face_68[30]<br>left_eye_3d = face_68[36:42].mean(axis=0)<br>right_eye_3d = face_68[42:48].mean(axis=0)<br>left_mouth_3d = face_68[48]<br>right_mouth_3d = face_68[54]<br><br>FACE_3D = np.stack([<br>    left_eye_3d,<br>    right_eye_3d,<br>    nose_3d,<br>    left_mouth_3d,<br>    right_mouth_3d<br>])  # (5, 3)</pre><p>From the above we get our 5 set of 3D key-points. These are fixed.</p><p>Moving on to 2D key-points we get it from wider face dataset.</p><pre># https://github.com/deepinsight/insightface/tree/master/detection/retinaface<br><br>def parse_wider_face_landmark_txt(txt_path):<br>    samples = []<br>    current_image = None<br><br>    with open(txt_path, &#39;r&#39;) as f:<br>        for line in f:<br>            line = line.strip()<br><br>            if line.startswith(&#39;#&#39;):<br>                # New image<br>                if current_image is not None:<br>                    samples.append(current_image)<br><br>                image_path = line[2:]  # remove &quot;# &quot;<br>                current_image = {<br>                    &quot;image_path&quot;: image_path,<br>                    &quot;faces&quot;: []<br>                }<br><br>            else:<br>                nums = list(map(float, line.split()))<br>                assert len(nums) == 20, f&quot;Expected 20 values, got {len(nums)}&quot;<br><br>                x, y, w, h = map(int, nums[:4])<br><br>                lm = nums[4:19]<br>                landmarks = []<br>                for i in range(0, 15, 3):<br>                    lx, ly, v = lm[i:i+3]<br>                    landmarks.append((lx, ly, int(v)))<br><br>                score = nums[19]<br><br>                face = {<br>                    &quot;bbox&quot;: [x, y, w, h],<br>                    &quot;landmarks&quot;: landmarks,<br>                    &quot;score&quot;: score<br>                }<br><br>                current_image[&quot;faces&quot;].append(face)<br><br>        if current_image is not None:<br>            samples.append(current_image)<br><br>    return samples<br><br>samples = parse_wider_face_landmark_txt(&#39;/Users/saptarshimallikthakur/Downloads/retinaface_gt_v1.1/train/label.txt&#39;)</pre><pre>def visualize_sample_plt(sample, image_root, max_faces=None):<br>    img_path = os.path.join(image_root, sample[&quot;image_path&quot;])<br>    img = Image.open(img_path).convert(&quot;RGB&quot;)<br><br>    fig, ax = plt.subplots(1, figsize=(10, 10))<br>    ax.imshow(img)<br>    ax.axis(&#39;off&#39;)<br><br>    faces = sample[&quot;faces&quot;]<br>    if max_faces is not None:<br>        faces = faces[:max_faces]<br><br>    for face in faces:<br>        x, y, w, h = face[&quot;bbox&quot;]<br><br>        # Draw bounding box<br>        rect = patches.Rectangle(<br>            (x, y), w, h,<br>            linewidth=2,<br>            edgecolor=&#39;lime&#39;,<br>            facecolor=&#39;none&#39;<br>        )<br>        ax.add_patch(rect)<br><br>        # Draw landmarks<br>        for (lx, ly, v), color, name in zip(<br>            face[&quot;landmarks&quot;],<br>            LANDMARK_COLORS,<br>            LANDMARK_NAMES<br>        ):<br>            if v != -1:<br>                ax.scatter(lx, ly, c=color, s=30)<br>                ax.text(lx + 2, ly + 2, name, fontsize=8, color=color)<br><br>    plt.show()<br><br>LANDMARK_COLORS = [<br>    &#39;blue&#39;,     # left eye<br>    &#39;cyan&#39;,     # right eye<br>    &#39;red&#39;,      # nose<br>    &#39;yellow&#39;,   # left mouth<br>    &#39;magenta&#39;   # right mouth<br>]<br><br>LANDMARK_NAMES = [<br>    &#39;left_eye&#39;, &#39;right_eye&#39;, &#39;nose&#39;, &#39;left_mouth&#39;, &#39;right_mouth&#39;<br>]<br><br>samples = parse_wider_face_landmark_txt(&#39;/Users/saptarshimallikthakur/Downloads/retinaface_gt_v1.1/train/label.txt&#39;)<br><br>folder = &#39;/Users/saptarshimallikthakur/Pictures/WIDER_train/images&#39;<br><br>visualize_sample_plt(samples[100], folder)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*hctJCRp7zz5XdF83s82UaA.png" /><figcaption>example from the wider face dataset.</figcaption></figure><p>Now we have all the components. We move on to estimate [R t].</p><pre>dataset = []<br><br>MIN_SCORE = 0.5<br>MIN_VALID_LMS = 4<br>MAX_REPROJ_ERR = 5# pixels<br><br>CROP_SIZE = 128<br>f         = CROP_SIZE * 2  # w + h or you can set f = w or h<br>cx  = cy  = CROP_SIZE / 2  # w/2 and h/2<br><br>K = np.array([<br>    [f, 0, cx],<br>    [0, f, cy],<br>    [0, 0, 1]<br>], dtype=np.float32)</pre><pre>def bbox_xywh_to_xyxy(bbox):<br>    x, y, w, h = bbox<br>    return x, y, x + w, y + h<br><br>def landmarks_to_crop(landmarks, bbox, crop_size):<br>    x1, y1, x2, y2 = bbox_xywh_to_xyxy(bbox)<br><br>    face_2d = []<br>    for lx, ly, v in landmarks:<br>        cx = (lx - x1) / (x2 - x1)<br>        cy = (ly - y1) / (y2 - y1)<br>        face_2d.append([cx * crop_size, cy * crop_size])<br><br>    return np.array(face_2d, dtype=np.float32)<br><br><br>def estimate_pose(face_3d, face_2d, K):<br>    face_3d = face_3d.astype(np.float32)<br>    face_2d = face_2d.astype(np.float32)<br><br>    success, rvec, tvec = cv2.solvePnP(<br>        face_3d,<br>        face_2d,<br>        K,<br>        None,<br>        flags=cv2.SOLVEPNP_EPNP<br>    )<br><br>    if success:<br>        success, rvec, tvec = cv2.solvePnP(<br>            face_3d,<br>            face_2d,<br>            K,<br>            None,<br>            rvec,<br>            tvec,<br>            useExtrinsicGuess=True,<br>            flags=cv2.SOLVEPNP_ITERATIVE<br>        )<br><br>    if not success:<br>        return None, None<br><br>    R, _ = cv2.Rodrigues(rvec)<br>    T = tvec.reshape(3)<br><br>    return R, T<br><br><br>def process_face(face, face_3d, K, crop_size, min_score=0.4):<br>    if face[&quot;score&quot;] &lt; min_score:<br>        return None<br><br>    face_2d = landmarks_to_crop(<br>        face[&quot;landmarks&quot;],<br>        face[&quot;bbox&quot;],<br>        crop_size<br>    )<br><br>    R, T = estimate_pose(face_3d, face_2d, K)<br>    return R, T<br><br><br>def landmarks_to_crop_with_vis(landmarks, bbox, crop_size):<br>    x, y, w, h = bbox<br>    x1, y1, x2, y2 = x, y, x + w, y + h<br><br>    lms_crop = []<br>    for lx, ly, v in landmarks:<br>        if v == -1:<br>            lms_crop.append([0.0, 0.0, 0])<br>        else:<br>            cx = (lx - x1) / (x2 - x1) * crop_size<br>            cy = (ly - y1) / (y2 - y1) * crop_size<br>            lms_crop.append([cx, cy, v])<br><br>    return np.array(lms_crop, dtype=np.float32)<br><br><br>def valid_landmark_count(landmarks):<br>    return sum(1 for _, _, v in landmarks if v != -1)<br><br>def project_3d(face_3d, R, T, K):<br>    pts = (R @ face_3d.T + T[:, None]).T<br>    pts = pts / pts[:, 2:3]<br>    pts = (K @ pts.T).T[:, :2]<br>    return pts</pre><pre>for sample_idx, sample in enumerate(samples):<br>    for face_idx, face in enumerate(sample[&quot;faces&quot;]):<br><br>        # 1. score filter<br>        if face[&quot;score&quot;] &lt; MIN_SCORE:<br>            continue<br><br>        # 2. landmark availability filter<br>        if valid_landmark_count(face[&quot;landmarks&quot;]) &lt; MIN_VALID_LMS:<br>            continue<br><br>        # 3. convert landmarks → crop space<br>        face_2d_crop = landmarks_to_crop_with_vis(<br>            face[&quot;landmarks&quot;],<br>            face[&quot;bbox&quot;],<br>            CROP_SIZE<br>        )<br><br>        # use only (x,y) for PnP<br>        face_2d_xy = face_2d_crop[:, :2]<br><br>        # 4. estimate pose<br>        R, T = estimate_pose(FACE_3D, face_2d_xy, K)<br>        if R is None:<br>            continue<br><br>        # 5. sanity check (optional but HIGHLY recommended)<br>        if T[2] &lt;= 0:<br>            continue  # face behind camera = garbage<br><br>        # 5. reprojection error filter (CRITICAL)<br>        proj = project_3d(FACE_3D, R, T, K)<br>        reproj_err = np.mean(np.linalg.norm(proj - face_2d_xy, axis=1))<br><br>        if reproj_err &gt; MAX_REPROJ_ERR:<br>            continue<br><br>        dataset.append({<br>            &quot;image_path&quot;: sample[&quot;image_path&quot;],<br>            &quot;bbox&quot;: face[&quot;bbox&quot;],<br>            &quot;landmarks_img&quot;: face[&quot;landmarks&quot;],<br>            &quot;landmarks_crop&quot;: face_2d_crop.tolist(),<br>            &quot;R&quot;: R.tolist(),<br>            &quot;T&quot;: T.tolist()<br>        })<br><br>    # progress log<br>    if sample_idx % 100 == 0:<br>        print(f&quot;Processed {sample_idx}/{len(samples)} images, &quot;<br>              f&quot;dataset size = {len(dataset)}&quot;)</pre><p>Finally our dataset preparation is complete. We now have our target values i.e [R t]. Given an image we predict R &amp; t.</p><pre>def crop_and_resize(img_path, bbox, crop_size):<br>    img = Image.open(img_path).convert(&quot;RGB&quot;)<br>    x, y, w, h = bbox<br>    crop = img.crop((x, y, x + w, y + h))<br>    crop = crop.resize((crop_size, crop_size), Image.BILINEAR)<br>    return np.array(crop)<br><br>def visualize_pose_sample(sample_item, image_root):<br>    img_path = f&quot;{image_root}/{sample_item[&#39;image_path&#39;]}&quot;<br>    bbox = sample_item[&quot;bbox&quot;]<br><br>    crop = crop_and_resize(img_path, bbox, CROP_SIZE)<br><br>    lms_crop = np.array(sample_item[&quot;landmarks_crop&quot;])[:, :2]<br>    R = np.array(sample_item[&quot;R&quot;])<br>    T = np.array(sample_item[&quot;T&quot;])<br><br>    proj = project_3d(FACE_3D, R, T, K)<br><br>    plt.figure(figsize=(4, 4))<br>    plt.imshow(crop)<br>    plt.axis(&quot;off&quot;)<br><br>    # GT landmarks<br>    plt.scatter(<br>        lms_crop[:, 0],<br>        lms_crop[:, 1],<br>        c=&quot;red&quot;,<br>        s=40,<br>        label=&quot;GT landmarks&quot;<br>    )<br><br>    # Reprojected landmarks<br>    plt.scatter(<br>        proj[:, 0],<br>        proj[:, 1],<br>        c=&quot;cyan&quot;,<br>        s=30,<br>        marker=&quot;x&quot;,<br>        label=&quot;Reprojected&quot;<br>    )<br><br>    for i, name in enumerate(<br>        [&quot;L-eye&quot;, &quot;R-eye&quot;, &quot;Nose&quot;, &quot;L-mouth&quot;, &quot;R-mouth&quot;]<br>    ):<br>        plt.text(<br>            lms_crop[i, 0] + 2,<br>            lms_crop[i, 1] + 2,<br>            name,<br>            color=&quot;red&quot;,<br>            fontsize=8<br>        )<br><br>    plt.legend()<br>    plt.show()<br><br>import random<br>for _ in range(3):<br>    visualize_pose_sample(random.choice(dataset), folder)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*a-_hHpXBJFUjEM3Cr9kkDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*VmlPtGTlZ8KVO_r4FJ6Ixw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*9H4VGGFSLIWQVC7QpHr-bw.png" /></figure><pre>class WIDERPoseDataset(Dataset):<br>    def __init__(self, data, img_dir):<br>        self.data = data<br>        self.img_dir = img_dir<br>        <br>        # Standard ImageNet normalization<br>        self.transform = transforms.Compose([<br>            transforms.ToTensor(),<br>            transforms.Resize((CROP_SIZE,CROP_SIZE)),<br>            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])<br>        ])<br><br>    def __len__(self):<br>        return len(self.data)<br><br>    def __getitem__(self, idx):<br>        item = self.data[idx]<br>        <br>        # Load Image<br>        img_path = os.path.join(self.img_dir, item[&#39;image_path&#39;])<br>        img      = cv2.imread(img_path)<br>        img      = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>        x,y,w,h  = item[&#39;bbox&#39;]<br>        crop     = img[y:y+h, x:x+w]<br>        crop     = self.transform(crop)<br><br>        # Prepare Labels<br>        R_mat = np.array(item[&#39;R&#39;], dtype=np.float32) # (3,) if Rodrigues or (3,3)<br>        T = np.array(item[&#39;T&#39;], dtype=np.float32) # (3,)<br><br>        # Convert Matrix to 6D representation (First 2 columns flattened)<br>        # R6d = [r11, r21, r31, r12, r22, r32]<br>        pose_6d = R_mat[:, :2].T.flatten() <br>        <br>        # Combine Pose [6D Rot, 3D Trans] -&gt; 9 values<br>        label = np.concatenate([pose_6d, T])<br><br>        # Ground Truth 2D points for Reprojection Loss<br>        lms_2d = torch.tensor(item[&#39;landmarks_crop&#39;], dtype=torch.float32) # (5, 2)<br>        <br>        return {<br>            &quot;image&quot;: crop,           <br>            &quot;target&quot;: torch.tensor(label, dtype=torch.float32),<br>            &quot;lms_2d&quot;: lms_2d                 <br>        }<br><br>final_dataset = WIDERPoseDataset(dataset, folder)<br>dataloader = torch.utils.data.DataLoader(final_dataset, batch_size=32, shuffle=True)<br><br>del final_dataset, dataset</pre><p>You might also be wondering why we took first 2 columns and not third ?</p><p><em>Well the answer lies in </em><strong><em>Gram-Schmidt method </em></strong><em>technique presented in 2019, in a paper by </em><strong><em>Zhou et al.</em></strong><em> (“On the Continuity of Rotation Representations in Neural Networks”). More on that in next section.</em></p><blockquote><strong>Modelling</strong></blockquote><p>We will be using pure ViT for feature extraction and then use small head for predicting the 9 values. Link to Encoder is in my previous<a href="https://medium.com/@saptarshimt/key-point-detection-building-a-simple-lightweight-model-from-scratch-a179f433a4a6"> article</a>.</p><pre>EMB_DIM    = 192<br>NUM_HEADS  = EMB_DIM // 32<br>PATCH_SIZE = 8<br>DEPTH      = 6<br><br>class VitPose(torch.nn.Module):<br>    def __init__(self, emb_dim=192):<br>        super().__init__()<br>        self.encoder = Encoder(patch_size=PATCH_SIZE, embed_dim=emb_dim, depth=DEPTH, num_heads=NUM_HEADS, mlp_ratio=3)<br><br>        num_patches = (CROP_SIZE // PATCH_SIZE) ** 2  <br>        flattened_dim = num_patches * emb_dim   <br><br>        self.norm = torch.nn.LayerNorm(flattened_dim)<br>        self.head = torch.nn.Sequential(<br>            torch.nn.Linear(flattened_dim, 32),<br>            torch.nn.ReLU(),<br>            torch.nn.Linear(32 , 9)  # 6D Rot (6) + 3D Trans (3)<br>        )<br><br>        # --- APPLY INITIALIZATION ---<br>        self.apply(self._init_weights)<br>        <br>        # Specific override for the Head (Optional but recommended for Regression)<br>        # Initialize the final layer to near-zero to start with a &quot;neutral&quot; prediction<br>        torch.nn.init.constant_(self.head[-1].weight, 0)<br>        torch.nn.init.constant_(self.head[-1].bias, 0)<br><br>    def _init_weights(self, m):<br>        &quot;&quot;&quot;<br>        ViT weight initialization<br>        :param m: module<br>        &quot;&quot;&quot;<br>        if isinstance(m, torch.nn.Linear):<br>            # Truncated Normal (std=0.02) is the standard for ViTs<br>            torch.nn.init.trunc_normal_(m.weight, std=0.02)<br>            if m.bias is not None:<br>                torch.nn.init.constant_(m.bias, 0)<br>        <br>        elif isinstance(m, torch.nn.LayerNorm):<br>            torch.nn.init.constant_(m.bias, 0)<br>            torch.nn.init.constant_(m.weight, 1.0)<br><br>    def forward(self, img):<br>        x    = self.encoder(img) # (B, N, D)<br>        x    = x.flatten(1)<br>        x    = self.norm(x)<br>        pose = self.head(x) # (B,9)<br>        return pose<br><br>model = VitPose(EMB_DIM)<br>model.to(device)<br><br>total = sum(p.numel() for p in model.parameters())<br>trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)<br><br>print(f&quot;Total params     : {total:,}&quot;)<br>print(f&quot;Trainable params : {trainable:,}&quot;)<br><br>Total params     : 4,648,073<br>Trainable params : 4,648,073</pre><p>If you are training a Neural Network to predict pose, <br><em>Predicting a raw </em><strong><em>Rotation Matrix</em></strong><em> is mathematically broken.</em></p><p><strong>The Problem: The Orthogonality Constraint.</strong><br>A rotation matrix has strict rules:</p><ol><li>Columns must be unit length.</li><li>Columns must be perpendicular (orthogonal).</li><li>Determinant must be 1.</li></ol><p>A Neural Network outputs <strong>unconstrained floats. </strong>It may not fulfil all conditions.</p><p>Instead we predict <strong>6 numbers</strong>. <br>You ask the network to predict two 3D vectors, let’s call them<strong> ‘vector a &amp; b’</strong>. <br>These represent the first two columns of a rotation matrix (the X-axis and the Y-axis).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mI855yVabaocZZTY7PM0Qg.png" /></figure><pre>def compute_rotation_matrix_from_6d(poses):<br>    &quot;&quot;&quot;<br>    Constructs rotation matrix from 6D representation.<br>    poses: (B, 6)<br>    Returns: (B, 3, 3)<br>    &quot;&quot;&quot;<br>    x_raw = poses[:, 0:3] # First column<br>    y_raw = poses[:, 3:6] # Second column<br><br>    # Gram-Schmidt Orthogonalization<br>    x = x_raw / (torch.norm(x_raw, dim=1, keepdim=True) + 1e-8)<br>    z = torch.cross(x, y_raw, dim=1)<br>    z = z / (torch.norm(z, dim=1, keepdim=True) + 1e-8)<br>    y = torch.cross(z, x, dim=1)<br><br>    # Stack columns<br>    x = x.unsqueeze(2)<br>    y = y.unsqueeze(2)<br>    z = z.unsqueeze(2)<br>    matrix = torch.cat((x, y, z), 2) # (B, 3, 3)<br>    return matrix</pre><blockquote><strong>Loss &amp; Training</strong></blockquote><p>The loss has 2 components, MSE loss on prediction and Projection loss i.e how far are the predicted-projected 2D points from original 2D landmarks.</p><pre>def batch_project_3d(points_3d, R, T, K):<br>    &quot;&quot;&quot;<br>    points_3d: (B, 3, N) or (1, 3, N)<br>    R:         (B, 3, 3)<br>    T:         (B, 3, 1)<br>    K:         (B, 3, 3) or (1, 3, 3)<br>    &quot;&quot;&quot;<br>    # 1. Camera Transformation: P_cam = R * X + T<br>    # bmm = Batch Matrix Multiply<br>    # R (B,3,3) * points (B,3,N) -&gt; (B,3,N)<br>    cam_points = torch.bmm(R, points_3d) + T <br><br>    # 2. Perspective Projection: P_uv = K * P_cam<br>    uv_homo = torch.bmm(K, cam_points)<br><br>    # 3. Normalize: u = x/z, v = y/z<br>    # Avoid div by zero with 1e-8<br>    uv_points = uv_homo[:, :2, :] / (uv_homo[:, 2:3, :] + 1e-8)<br>    <br>    # Returns (B, 2, N)<br>    return uv_points<br><br>class ReprojectionLoss(torch.nn.Module):<br>    def __init__(self, face_3d_coords, K_matrix):<br>        super().__init__()<br>        # Register as buffers so they move to GPU automatically<br>        self.register_buffer(&#39;face_3d&#39;, torch.tensor(face_3d_coords, dtype=torch.float32).t().unsqueeze(0)) # (1, 3, N)<br>        self.register_buffer(&#39;K&#39;, torch.tensor(K_matrix, dtype=torch.float32).unsqueeze(0)) # (1, 3, 3)<br><br>    def forward(self, pred_pose, gt_proj):<br>        batch_size = pred_pose.shape[0]<br><br>        # Expand K and Face3D to match batch size<br>        # (1, 3, N) -&gt; (B, 3, N)<br>        face_3d_batch = self.face_3d.repeat(batch_size, 1, 1)<br>        K_batch       = self.K.repeat(batch_size, 1, 1)<br><br>        # Reconstruct Matrices<br>        pred_R = compute_rotation_matrix_from_6d(pred_pose[:, :6])<br>        pred_T = pred_pose[:, 6:].unsqueeze(2) # (B, 3, 1)<br><br>        # --- USE THE FUNCTION HERE ---<br>        pred_proj = batch_project_3d(face_3d_batch, pred_R, pred_T, K_batch).permute(0, 2, 1) # (B, N, 2)<br><br>        # 4. FIX: Slice Ground Truth to match (x, y)<br>        if gt_proj.shape[-1] == 3:<br>            gt_proj_2d = gt_proj[:, :, :2] # Drop visibility column<br>        else:<br>            gt_proj_2d = gt_proj<br><br>        loss = torch.nn.functional.l1_loss(pred_proj, gt_proj_2d)<br>        return loss<br><br>proj_loss_fn = ReprojectionLoss(FACE_3D, K).to(device)<br>mse_loss_fn  = torch.nn.MSELoss().to(device)</pre><p>We will be training for 50 epochs using cosine scheduled learning rate and Adam optimizer.</p><pre>class CustomLRScheduler(_LRScheduler):<br>    def __init__(self, optimizer, total_steps, warmup_steps_ratio, min_lr, max_lr, last_epoch=-1):<br>        self.total_steps = total_steps<br>        self.warmup_steps = int(total_steps * warmup_steps_ratio)<br>        self.min_lr = min_lr<br>        self.max_lr = max_lr<br>        super(CustomLRScheduler, self).__init__(optimizer, last_epoch)<br><br>    def get_lr(self):<br>        current_step = self.last_epoch<br>        if current_step &lt; self.warmup_steps:<br>            lr = self.min_lr + (self.max_lr - self.min_lr) * (current_step / self.warmup_steps)<br>        else:<br>            progress = (current_step - self.warmup_steps) / (self.total_steps - self.warmup_steps)<br>            decay_factor = math.exp(-1.0 * progress)<br>            lr = self.min_lr + (self.max_lr - self.min_lr) * decay_factor<br>            lr = max(lr, self.min_lr)<br>        return [lr for _ in self.base_lrs]<br>    <br>EPOCHS = 100<br>TOTAL_STEPS = len(dataloader)*EPOCHS<br><br>LEARNING_RATE_MIN = 1e-6<br>LEARNING_RATE_MAX = 1e-3<br>WARMUP_RATIO = 0.01<br><br>optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE_MAX, betas=(0.9, 0.98), eps=1e-9)<br><br>scheduler = CustomLRScheduler(<br>    optimizer,TOTAL_STEPS,<br>    warmup_steps_ratio=WARMUP_RATIO,<br>    min_lr=LEARNING_RATE_MIN,<br>    max_lr=LEARNING_RATE_MAX<br>)<br><br>model.train()<br><br>for epoch in range(EPOCHS):<br><br>    train_total_loss = train_mse_loss = train_proj_loss = 0.0<br><br>    progress_bar = tqdm(dataloader, desc=f&quot;Epoch {epoch+1}/{EPOCHS}&quot;, leave=True, unit=&#39;batch&#39;)<br><br>    for batch in progress_bar:<br><br>        imgs          = batch[&#39;image&#39;].to(device)<br>        target        = batch[&quot;target&quot;].to(device) <br>        lms_2d        = batch[&#39;lms_2d&#39;].to(device)                <br><br>        pred = model(imgs)                          <br>        mse_loss  = mse_loss_fn(pred, target)<br>        proj_loss = 0.01 * proj_loss_fn(pred, lms_2d)<br><br>        loss = mse_loss + proj_loss<br><br>        train_total_loss  += loss.item()<br>        train_mse_loss    += mse_loss.item()<br>        train_proj_loss   += proj_loss.item()<br><br>        optimizer.zero_grad()<br>        loss.backward()<br><br>        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)<br>        optimizer.step()<br>        scheduler.step()<br><br>        progress_bar.set_postfix(tot_loss=loss.item(), mse_loss=mse_loss.item(), proj_loss=proj_loss.item(), lr=f&quot;{scheduler.get_last_lr()[0]:.6f}&quot;)<br><br>    loss_tensor    = torch.tensor([train_total_loss, train_mse_loss, train_proj_loss], device=device)<br>    avg_total_loss = loss_tensor[0].item() / len(dataloader)<br>    avg_mse_loss   = loss_tensor[1].item() / len(dataloader)<br>    avg_proj_loss  = loss_tensor[2].item() / len(dataloader)<br><br>    print(f&quot;Epoch {epoch+1} | Total_Loss {avg_total_loss:.4f} | MSE_Loss {avg_mse_loss:.4f} | Proj_Loss {avg_proj_loss:.4f} &quot;)<br>    <br>    torch.save(model.state_dict(), &#39;model.pt&#39;)<br><br>Epoch 1/100: 100%|██████████| 753/753 [04:13&lt;00:00,  2.97batch/s, lr=0.001000, mse_loss=0.149, proj_loss=0.0801, tot_loss=0.229] <br>Epoch 1 | Total_Loss 1.0628 | MSE_Loss 0.7492 | Proj_Loss 0.3136 <br>Epoch 2/100: 100%|██████████| 753/753 [04:22&lt;00:00,  2.87batch/s, lr=0.000990, mse_loss=0.0748, proj_loss=0.0591, tot_loss=0.134]<br>Epoch 2 | Total_Loss 0.1997 | MSE_Loss 0.1246 | Proj_Loss 0.0751 <br>.<br>.<br>.<br>Epoch 49/100: 100%|██████████| 753/753 [04:11&lt;00:00,  2.99batch/s, lr=0.000616, mse_loss=0.0145, proj_loss=0.0339, tot_loss=0.0484] <br>Epoch 49 | Total_Loss 0.0400 | MSE_Loss 0.0093 | Proj_Loss 0.0307 <br>Epoch 50/100: 100%|██████████| 753/753 [04:11&lt;00:00,  3.00batch/s, lr=0.000610, mse_loss=0.00589, proj_loss=0.0276, tot_loss=0.0335]<br>Epoch 50 | Total_Loss 0.0397 | MSE_Loss 0.0091 | Proj_Loss 0.0306 <br>.<br>.<br>.<br>Epoch 99/100: 100%|██████████| 753/753 [04:14&lt;00:00,  2.96batch/s, lr=0.000372, mse_loss=0.00213, proj_loss=0.0213, tot_loss=0.0235]<br>Epoch 99 | Total_Loss 0.0297 | MSE_Loss 0.0044 | Proj_Loss 0.0252 <br>Epoch 100/100: 100%|██████████| 753/753 [04:14&lt;00:00,  2.96batch/s, lr=0.000369, mse_loss=0.00306, proj_loss=0.0264, tot_loss=0.0295]<br>Epoch 100 | Total_Loss 0.0297 | MSE_Loss 0.0045 | Proj_Loss 0.0252 </pre><p><strong><em>Note:</em></strong><em> You might have to play with projection loss weight if you loss ain’t improving.</em></p><blockquote><strong>Inference</strong></blockquote><p>Now in inference we will just pass an image.</p><ul><li>The model will output 9 values which is 6 for rotation matrix corresponding to first two columns and 3 for translation vector.</li><li>Using <strong><em>Gram-Schmidt </em></strong>formula we then compute all 9 rotation values.</li><li>Now using the mean face BFM model (which as explained is static and pre-defined) we can project the 3D points accurately on the face image, hence indirectly solving the facial key-point detection problem efficiently !</li></ul><pre>inference_model = VitPose(EMB_DIM)<br>inference_model.load_state_dict(torch.load(&quot;model.pt&quot;, map_location=device))<br>inference_model.to(device)<br>inference_model.eval()</pre><pre>index      = 110<br>image_root = &#39;/Users/saptarshimallikthakur/Pictures/WIDER_train/images&#39;<br>sample     = samples[index]<br>img_path   = os.path.join(image_root, sample[&quot;image_path&quot;])<br><br># Standard ImageNet normalization<br>transform = transforms.Compose([<br>    transforms.ToTensor(),<br>    transforms.Resize((CROP_SIZE,CROP_SIZE)),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])<br>])<br><br>FACE_3D_T = torch.tensor(FACE_3D, dtype=torch.float32).to(device).t().unsqueeze(0)<br>K_T       = torch.tensor(K, dtype=torch.float32).unsqueeze(0).to(device)<br><br>img = cv2.imread(img_path)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br><br>valid_faces = [f for f in sample[&#39;faces&#39;] if f[&#39;score&#39;] &gt; 0.5]<br><br># Big vertical figure<br>plt.figure(figsize=(8, 6 * len(valid_faces)))<br><br>for idx, face in enumerate(valid_faces):<br><br>    x, y, w, h = face[&#39;bbox&#39;]<br>    crop      = img[y:y+h, x:x+w]<br>    crop_t    = transform(crop).unsqueeze(0).to(device)<br>    viz_crop  = cv2.resize(crop, (CROP_SIZE, CROP_SIZE))<br><br>    with torch.no_grad():<br>        pred_pose = inference_model(crop_t)<br>        pred_R    = compute_rotation_matrix_from_6d(pred_pose[:, :6])<br>        pred_T    = pred_pose[:, 6:].unsqueeze(2)<br><br>        pred_proj = batch_project_3d(FACE_3D_T, pred_R, pred_T, K_T)<br>        points    = pred_proj.squeeze(0).cpu().numpy()<br><br>    # One row, one plot<br>    ax = plt.subplot(len(valid_faces), 1, idx + 1)<br>    ax.imshow(viz_crop)<br><br>    ax.scatter(points[0], points[1], s=200, c=&#39;cyan&#39;, marker=&#39;.&#39;)<br><br>    ax.scatter(points[0, 2], points[1, 2], s=200, c=&#39;red&#39;, marker=&#39;x&#39;)<br><br>    # ax.set_title(f&quot;Face {idx+1} (Score: {face[&#39;score&#39;]:.2f})&quot;, fontsize=14)<br>    ax.axis(&#39;off&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*JzoC9KP00xCESlSg3771BA.png" /></figure><p>We can predict all 68 facial key-points too and not just 5 which we used for [R t] estimation !</p><pre>index      = 103<br>image_root = &#39;/Users/saptarshimallikthakur/Pictures/WIDER_train/images&#39;<br>sample     = samples[index]<br>img_path   = os.path.join(image_root, sample[&quot;image_path&quot;])<br><br># Standard ImageNet normalization<br>transform = transforms.Compose([<br>    transforms.ToTensor(),<br>    transforms.Resize((CROP_SIZE,CROP_SIZE)),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])<br>])<br><br>FACE_3D_T = torch.tensor(face_68, dtype=torch.float32).to(device).t().unsqueeze(0)<br>K_T       = torch.tensor(K, dtype=torch.float32).unsqueeze(0).to(device)<br><br>img = cv2.imread(img_path)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br><br>valid_faces = [f for f in sample[&#39;faces&#39;] if f[&#39;score&#39;] &gt; 0.5]<br><br># Big vertical figure<br>plt.figure(figsize=(8, 6 * len(valid_faces)))<br><br>for idx, face in enumerate(valid_faces):<br><br>    x, y, w, h = face[&#39;bbox&#39;]<br>    crop      = img[y:y+h, x:x+w]<br>    crop_t    = transform(crop).unsqueeze(0).to(device)<br>    viz_crop  = cv2.resize(crop, (CROP_SIZE, CROP_SIZE))<br><br>    with torch.no_grad():<br>        pred_pose = inference_model(crop_t)<br>        pred_R    = compute_rotation_matrix_from_6d(pred_pose[:, :6])<br>        pred_T    = pred_pose[:, 6:].unsqueeze(2)<br><br>        pred_proj = batch_project_3d(FACE_3D_T, pred_R, pred_T, K_T)<br>        points    = pred_proj.squeeze(0).cpu().numpy()<br><br>    # One row, one plot<br>    ax = plt.subplot(len(valid_faces), 1, idx + 1)<br>    ax.imshow(viz_crop)<br><br>    ax.scatter(points[0], points[1], s=200, c=&#39;cyan&#39;, marker=&#39;.&#39;)<br><br>    # ax.scatter(points[0, 2], points[1, 2], s=200, c=&#39;red&#39;, marker=&#39;x&#39;)<br><br>    ax.set_title(f&quot;Face {idx+1} (Score: {face[&#39;score&#39;]:.2f})&quot;, fontsize=14)<br>    ax.axis(&#39;off&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*dzkPOuN9ZHJ8gEbp_N9M7A.png" /></figure><p><em>You can improve results by using a better pre-trained backbone (frozen) for feature extraction and just add a trainable head for prediction, unlike in my case where every component was initialised and trained from scratch.</em></p><blockquote>Additional Notes</blockquote><p>There is still one thing that I didn’t cover and that is <strong>rvec</strong> which you might have seen in :</p><pre>R, _ = cv2.Rodrigues(rvec)</pre><p>where<strong> R</strong> is the rotation matrix which we talked in-depth in article above, while <strong>rvec</strong> is the rotation vector of shape [1, 3].</p><p><strong>rvec</strong> is a compact way to represent a rotation using only <strong>3 numbers</strong>, instead of the <strong>9 numbers</strong> required for a Rotation Matrix. It is a clever mathematical hack that packs two pieces of information into a single 3D vector (x, y, z).</p><ol><li><strong>The Direction:</strong> The direction the vector points indicates the <strong>Axis of Rotation</strong> (the imaginary line the object spins around).</li><li><strong>The Magnitude (Length):</strong> The length of the vector indicates the <strong>Angle of Rotation</strong> (theta) in radians.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*IGmAJGQ1TvSumKZP2VlXYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pP31o9JHBJGYIe9L6BmIQ.png" /></figure><p>In computer vision (like calibrating a camera or solving solvePnP to find a face’s pose), the computer tries to “guess” the rotation.</p><ul><li>If the solver guesses a <strong>Matrix</strong>, it has to guess 9 numbers. But it must also ensure those 9 numbers form a valid orthogonal matrix (columns perpendicular, length 1). This is extremely difficult for an optimizer.</li><li>If the solver guesses an <strong>rvec</strong>, it can guess <em>any</em> 3 numbers. There are no constraints. It creates a smooth “search space” for the algorithm to find the best rotation.</li></ul><p><em>Still we don’t use it in neural network prediction.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GP_kil26mrWavxUCroodNA.png" /></figure><blockquote>Yaw, Pitch &amp; Roll</blockquote><p>As we discussed, these are the three <strong>Euler Angles</strong> that describe the 3D orientation (rotation) of an object in space relative to a camera or a coordinate system.</p><ul><li>Left-Right (Yaw),</li><li>Up-Down(Pitch) &amp;</li><li>Tilt Sideways(Roll).</li></ul><p>It is used in <strong>Driver Monitoring Systems (DMS):</strong></p><ul><li><strong>Yaw:</strong> Is the driver looking at the road or out the side window?</li><li><strong>Pitch:</strong> Is the driver nodding off (falling asleep)?</li></ul><p>The values are computed from rotation matrix.</p><pre>def compute_euler_angles_from_rotation_matrices(R):<br>    &quot;&quot;&quot;<br>    R: (B, 3, 3) pytorch tensor or (3, 3) numpy array<br>    Returns: yaw, pitch, roll in degrees<br>    &quot;&quot;&quot;<br>    # If numpy, convert to tensor for easier handling (or keep pure numpy)<br>    is_tensor = torch.is_tensor(R)<br>    <br>    if is_tensor:<br>        # Check if singular (Gimbal Lock)<br>        sy = torch.sqrt(R[:, 0, 0] * R[:, 0, 0] +  R[:, 1, 0] * R[:, 1, 0])<br>        singular = sy &lt; 1e-6<br><br>        x = torch.zeros_like(sy)<br>        y = torch.zeros_like(sy)<br>        z = torch.zeros_like(sy)<br><br>        # Standard Case<br>        x[~singular] = torch.atan2(R[~singular, 2, 1], R[~singular, 2, 2])<br>        y[~singular] = torch.atan2(-R[~singular, 2, 0], sy[~singular])<br>        z[~singular] = torch.atan2(R[~singular, 1, 0], R[~singular, 0, 0])<br><br>        # Singular Case (Gimbal lock)<br>        x[singular] = torch.atan2(-R[singular, 1, 2], R[singular, 1, 1])<br>        y[singular] = torch.atan2(-R[singular, 2, 0], sy[singular])<br>        z[singular] = 0<br><br>        # Convert Radians to Degrees<br>        return x * (180 / math.pi), y * (180 / math.pi), z * (180 / math.pi)<br>    <br>    else:<br>        # Numpy Version<br>        sy = math.sqrt(R[0,0] * R[0,0] +  R[1,0] * R[1,0])<br>        singular = sy &lt; 1e-6<br><br>        if not singular:<br>            x = math.atan2(R[2,1] , R[2,2])<br>            y = math.atan2(-R[2,0], sy)<br>            z = math.atan2(R[1,0], R[0,0])<br>        else:<br>            x = math.atan2(-R[1,2], R[1,1])<br>            y = math.atan2(-R[2,0], sy)<br>            z = 0<br><br>        return np.array([x, y, z]) * (180 / math.pi)<br><br>index      = 103<br>image_root = &#39;/Users/saptarshimallikthakur/Pictures/WIDER_train/images&#39;<br>sample     = samples[index]<br>img_path   = os.path.join(image_root, sample[&quot;image_path&quot;])<br><br># Standard ImageNet normalization<br>transform = transforms.Compose([<br>    transforms.ToTensor(),<br>    transforms.Resize((CROP_SIZE,CROP_SIZE)),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])<br>])<br><br>FACE_3D_T = torch.tensor(FACE_3D, dtype=torch.float32).to(device).t().unsqueeze(0)<br>K_T       = torch.tensor(K, dtype=torch.float32).unsqueeze(0).to(device)<br><br>img = cv2.imread(img_path)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br><br>valid_faces = [f for f in sample[&#39;faces&#39;] if f[&#39;score&#39;] &gt; 0.5]<br><br># Big vertical figure<br>plt.figure(figsize=(8, 6 * len(valid_faces)))<br><br>for idx, face in enumerate(valid_faces):<br><br>    x, y, w, h = face[&#39;bbox&#39;]<br>    crop      = img[y:y+h, x:x+w]<br>    crop_t    = transform(crop).unsqueeze(0).to(device)<br>    viz_crop  = cv2.resize(crop, (CROP_SIZE, CROP_SIZE))<br><br>    with torch.no_grad():<br>        pred_pose = inference_model(crop_t)<br>        pred_R    = compute_rotation_matrix_from_6d(pred_pose[:, :6])<br><br>        pitch, yaw, roll = compute_euler_angles_from_rotation_matrices(pred_R)<br><br>    yaw_val   = yaw[0].item()<br>    pitch_val = pitch[0].item()<br>    roll_val  = roll[0].item()<br><br>    if pitch_val &gt; 0:<br>        pitch_val -= 180<br>    else:<br>        pitch_val += 180<br><br>    ax = plt.subplot(len(valid_faces), 1, idx + 1)<br>    ax.imshow(viz_crop)<br><br>    ax.set_title(<br>        f&quot;Yaw: {yaw_val:.2f} | Pitch: {pitch_val:.2f} | Roll: {roll_val:.2f}&quot;,<br>        fontsize=14<br>    )<br><br>    ax.axis(&#39;off&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><p>Opencv and BFM have different coordinate axis direction.</p><ul><li><strong>OpenCV (Camera):</strong> The Y-axis points <strong>DOWN</strong> (pixel 0,0 is top-left).</li><li><strong>BFM (3D Model):</strong> The Y-axis usually points <strong>UP</strong> (Cartesian coordinates).</li></ul><p>When cv2.solvePnP tries to fit the “Y-Up” face model onto the “Y-Down” image, it finds that the best way to match the points is to <strong>rotate the face 180 degrees around the X-axis (Pitch)</strong>.</p><p>Effectively, the math thinks: <em>“To make this 3D face match the picture, I have to flip it upside down.”</em></p><p>In the below</p><ul><li>Yaw negative means head is positioned left</li><li>Pitch negative means head is positioned facing up</li><li>Roll negative means negative means head tilted right.</li></ul><p>Small values — &gt; [-5,5] means neutral (IMHO).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*smFpojWMvNgMutA5ajIKlw.png" /></figure><blockquote>The End</blockquote><blockquote><em>And thats it folks. Happy learning !</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf75f8db1ffb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key-point Detection : Building a simple, lightweight model from scratch]]></title>
            <link>https://medium.com/@saptarshimt/key-point-detection-building-a-simple-lightweight-model-from-scratch-a179f433a4a6?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a179f433a4a6</guid>
            <category><![CDATA[pose-estimation]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[keypoint-detection]]></category>
            <category><![CDATA[coco-dataset]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 08:05:58 GMT</pubDate>
            <atom:updated>2026-02-06T10:55:31.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Key-point Detection : Building a simple, lightweight model from scratch</h3><p>The following key-point detection model which I will go through, is built purely on transformer architecture (ViT) and trained on COCO key-point dataset. It is a lightweight model consisting of just 3 Million Parameters. Let’s proceed !</p><blockquote><strong>ViT (for feature extraction)</strong></blockquote><p>To briefly describe the <strong>Vision Transformer (ViT) encoder</strong>, the model begins by dividing an input image into small, non-overlapping patches. Each patch is then converted into an embedding vector and combined with a <strong>learnable positional embedding</strong> through addition. The positional embedding provides spatial information, allowing the model to understand the relative locations of different patches within the image.</p><p>These patch embeddings are passed through multiple <strong>self-attention layers</strong>, where each patch learns its relationship with every other patch in the image. The output of the attention mechanism is further processed using a <strong>Multi-Layer Perceptron (MLP)</strong>, resulting in transformed feature representations. Importantly, the dimensionality of these representations remains consistent with the input embedding dimension while encoding richer contextual information.</p><p>In our implementation, the ViT encoder receives an input image of size <strong>(224, 224, 3)</strong> and produces a learned feature map of size <strong>(28, 28, 192)</strong>. This corresponds to dividing the image into <strong>8 × 8 patches</strong>, where each patch is represented by a <strong>192-dimensional embedding vector</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*DCcrQvnftNOav7hzShMXZw.png" /></figure><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class MultiHeadSelfAttention(nn.Module):<br>    def __init__(self, dim, num_heads, attn_dropout=0.0, proj_dropout=0.0):<br>        super().__init__()<br>        assert dim % num_heads == 0, &quot;dim must be divisible by num_heads&quot;<br><br>        self.num_heads = num_heads<br>        self.head_dim = dim // num_heads<br>        self.scale = self.head_dim ** -0.5<br><br>        self.qkv = nn.Linear(dim, dim * 3, bias=True)<br>        self.attn_drop = nn.Dropout(attn_dropout)<br>        self.proj = nn.Linear(dim, dim)<br>        self.proj_drop = nn.Dropout(proj_dropout)<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        x: (B, N, D)<br>        &quot;&quot;&quot;<br>        B, N, D = x.shape<br><br>        qkv = self.qkv(x)                      # (B, N, 3D)<br>        qkv = qkv.reshape(B, N, 3, self.num_heads, self.head_dim)<br>        qkv = qkv.permute(2, 0, 3, 1, 4)        # (3, B, H, N, Hd)<br><br>        q, k, v = qkv[0], qkv[1], qkv[2]<br><br>        attn = (q @ k.transpose(-2, -1)) * self.scale<br>        attn = attn.softmax(dim=-1)<br>        attn = self.attn_drop(attn)<br><br>        out = attn @ v                         # (B, H, N, Hd)<br>        out = out.transpose(1, 2).reshape(B, N, D)<br><br>        out = self.proj(out)<br>        out = self.proj_drop(out)<br>        return out<br>    <br>class MLP(nn.Module):  # SwiGLU<br>    def __init__(self, dim, hidden_dim, dropout=0.0):<br>        super().__init__()<br>        self.w_gate = nn.Linear(dim, hidden_dim, bias=True)<br>        self.w_value = nn.Linear(dim, hidden_dim, bias=True)<br>        self.w_out = nn.Linear(hidden_dim, dim, bias=True)<br>        self.drop = nn.Dropout(dropout)<br><br>    def forward(self, x):<br>        gate = F.silu(self.w_gate(x))     # SiLU on gate<br>        value = self.w_value(x)<br>        x = gate * value<br>        x = self.w_out(x)<br>        x = self.drop(x)<br>        return x<br>    <br>class RMSNorm(nn.Module):<br>    def __init__(self, dim, eps=1e-6):<br>        super().__init__()<br>        self.eps = eps<br>        self.weight = nn.Parameter(torch.ones(dim))<br><br>    def forward(self, x):<br>        # x: (B, N, D)<br>        # Calculate RMS: sqrt(mean(x^2))<br>        rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)<br>        return x * rms * self.weight<br>    <br>class TransformerBlock(nn.Module):<br>    def __init__(<br>        self,<br>        dim,<br>        num_heads,<br>        mlp_ratio=3.0,<br>        attn_dropout=0.0,<br>        dropout=0.0<br>    ):<br>        super().__init__()<br><br>        self.norm1 = RMSNorm(dim)<br>        self.attn = MultiHeadSelfAttention(<br>            dim, num_heads, attn_dropout, dropout<br>        )<br><br>        self.norm2 = RMSNorm(dim)<br>        self.mlp = MLP(<br>            dim,<br>            int(dim * mlp_ratio),<br>            dropout<br>        )<br><br>    def forward(self, x):<br>        x = x + self.attn(self.norm1(x))   # Pre-LN<br>        x = x + self.mlp(self.norm2(x))<br>        return x<br><br># PURE VIT<br>    <br>class PatchEmbedding(nn.Module):<br>    def __init__(self, patch_size, in_channels, embed_dim):<br>        super().__init__()<br>        self.patch_size = patch_size<br>        self.in_channels = in_channels<br><br>        patch_dim = in_channels * patch_size * patch_size<br>        self.proj = nn.Linear(patch_dim, embed_dim)<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        x: (B, C, H, W)<br>        returns:<br>            x: (B, N, D)<br>            grid_hw: (H_p, W_p)<br>        &quot;&quot;&quot;<br>        B, C, H, W = x.shape<br>        P = self.patch_size<br><br>        assert H % P == 0 and W % P == 0, &quot;Image size must be divisible by patch size&quot;<br><br>        H_p, W_p = H // P, W // P<br><br>        # (B, C, H, W) → (B, H_p, W_p, C, P, P)<br>        x = x.view(B, C, H_p, P, W_p, P)<br>        x = x.permute(0, 2, 4, 1, 3, 5)<br><br>        # (B, H_p, W_p, C, P, P) → (B, N, C*P*P)<br>        x = x.reshape(B, H_p * W_p, C * P * P)<br><br>        # Linear projection → embedding dim<br>        x = self.proj(x)  # (B, N, D)<br><br>        return x, (H_p, W_p)<br><br>class Encoder(nn.Module):<br>    def __init__(<br>        self,<br>        patch_size=16,<br>        in_channels=3,<br>        embed_dim=192,<br>        depth=6,<br>        num_heads=3,<br>        mlp_ratio=3.0,<br>        dropout=0.0,<br>        attn_dropout=0.0,<br>        base_grid_size=(16, 16),  # reference size (e.g. 256/16)<br>    ):<br>        super().__init__()<br><br>        self.patch_embed = PatchEmbedding(patch_size, in_channels, embed_dim)<br><br>        num_base_patches = base_grid_size[0] * base_grid_size[1]<br>        self.pos_embed = nn.Parameter(torch.zeros(1, num_base_patches, embed_dim))<br><br>        self.pos_drop = nn.Dropout(dropout)<br><br>        self.blocks = nn.ModuleList([<br>            TransformerBlock(<br>                embed_dim,<br>                num_heads,<br>                mlp_ratio,<br>                attn_dropout,<br>                dropout<br>            )<br>            for _ in range(depth)<br>        ])<br><br>        self.norm = RMSNorm(embed_dim)<br>        self._init_weights()<br><br>    def _init_weights(self):<br>        nn.init.trunc_normal_(self.pos_embed, std=0.02)<br><br>    def interpolate_pos_encoding(self, x, grid_hw):<br>        &quot;&quot;&quot;<br>        x: (B, N, D)<br>        grid_hw: (H, W) patch grid<br>        &quot;&quot;&quot;<br><br>        H0 = W0 = int(self.pos_embed.shape[1] ** 0.5)<br>        patch_pos = self.pos_embed.reshape(1, H0, W0, -1).permute(0, 3, 1, 2)<br><br>        patch_pos = F.interpolate(<br>            patch_pos,<br>            size=grid_hw,<br>            mode=&quot;bicubic&quot;,<br>            align_corners=False<br>        )<br><br>        patch_pos = patch_pos.permute(0, 2, 3, 1).reshape(1, -1, patch_pos.shape[1])<br>        return patch_pos<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        x: (B, C, H, W)<br>        &quot;&quot;&quot;<br><br>        x, (H, W) = self.patch_embed(x)  # (B, N, D)<br><br>        pos_embed = self.interpolate_pos_encoding(x, (H, W))<br>        x = x + pos_embed<br>        x = self.pos_drop(x)<br><br>        for blk in self.blocks:<br>            x = blk(x)<br><br>        x = self.norm(x)<br>        return x</pre><blockquote><strong>Data Preparation</strong></blockquote><p>As mentioned earlier, we will be using COCO train 2017 dataset. There are 17 key points :</p><pre>COCO_KEYPOINTS = [&#39;nose&#39;, &#39;left_eye&#39;, &#39;right_eye&#39;, &#39;left_ear&#39;, &#39;right_ear&#39;,<br>                  &#39;left_shoulder&#39;, &#39;right_shoulder&#39;, &#39;left_elbow&#39;, &#39;right_elbow&#39;,<br>                  &#39;left_wrist&#39;, &#39;right_wrist&#39;, &#39;left_hip&#39;, &#39;right_hip&#39;,<br>                  &#39;left_knee&#39;, &#39;right_knee&#39;, &#39;left_ankle&#39;, &#39;right_ankle&#39;<br>                  ]</pre><p>We resize all input images to a resolution of <strong>(224, 224, 3)</strong> and scale the corresponding <strong>17 key-point coordinates (x, y)</strong> accordingly. While the resized images serve as the model inputs, we further transform the target values (key-points).</p><p>Each of the 17 scaled key-point coordinates is additionally mapped onto a <strong>(56, 56)</strong> feature map. The final target representation consists of <strong>17 channels</strong>, where each channel corresponds to a specific key-point. Therefore, the final target tensor has a shape of <strong>(56, 56, 17)</strong>. All model predictions and loss computations are performed at this resolution.</p><p>The model learns to predict key-point locations relative to the <strong>(56, 56)</strong> feature map, generating one prediction per channel for each key-point. This channel-wise representation helps the model focus on learning each key-point independently.</p><p>Using a <strong>(56, 56)</strong> feature map instead of the original <strong>(224, 224)</strong> resolution reduces the spatial search space, making it easier for the model to accurately localize key-points. Once predictions are obtained, they can be scaled back to the original image resolution, providing an efficient and effective localization strategy.</p><p>For each of the <strong>17 key-points</strong>, the corresponding <strong>(56, 56)</strong> feature map is initially sparse, where all values are zero except at the exact key-point location, which is assigned a value of 1. Although reducing the resolution to <strong>(56, 56)</strong> simplifies the localization task, learning from such highly sparse targets remains challenging for the model.</p><p>To address this issue, we introduce <strong>Gaussian heatmaps</strong> as target representations. Instead of assigning a value of 1 only at the exact key-point location, we generate a Gaussian distribution centered at the key-point. The pixel value at the key-point location remains close to 1, while surrounding pixels are assigned progressively smaller non-zero values as their distance from the key-point increases. All remaining pixels retain values close to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FQQI0DHHFW0fWeCzChIVg.png" /><figcaption>Example of a (56,56) feature-map with 3 channels each for one key-point. Notice the blacks are zero values with few pixels being non-zeros i.e the bright region. The centre of the bright region is peak bright indicating the actual key-point location with surrounding having lower values as they gradually move further away.</figcaption></figure><p>This approach allows the model to first learn the approximate region of the key-point before accurately identifying the exact location by detecting the peak value in the heatmap. Additionally, Gaussian heatmaps reduce target sparsity and create smoother gradients during training. Rather than predicting a single non-zero value within a large zero-valued map, the model benefits from a localized region of meaningful supervision, which improves training stability and convergence.</p><pre>def generate_target(joints, joints_vis, output_size=(56, 56), imgsize=224, sigma=2):<br>    &quot;&quot;&quot;<br>    Generates Gaussian Heatmaps.<br>    joints: [17, 2] coordinates (x, y) in the INPUT IMAGE scale (e.g., 224 x 224)<br>    joints_vis: [17] visibility flags (0=hidden, 1=visible, 2=visible+labeled)<br>    &quot;&quot;&quot;<br>    num_joints = joints.shape[0]<br>    target = torch.zeros((num_joints, output_size[0], output_size[1]), dtype=torch.float32)<br>    target_weight = torch.zeros((num_joints, 1), dtype=torch.float32)<br>    <br>    tmp_size = sigma * 1<br><br>    for joint_id in range(num_joints):<br>        # 1. Check visibility. If 0, skip generation, weight remains 0.<br>        v = joints_vis[joint_id]<br>        if v == 0:<br>            continue<br>            <br>        target_weight[joint_id] = 1.0<br><br>        # 2. Scale coordinate to Heatmap size <br>        # Assuming input 224-&gt; output 56, stride is 4<br>        feat_stride = imgsize // output_size[0]<br>        mu_x = int(joints[joint_id][0] / feat_stride + 0.5)<br>        mu_y = int(joints[joint_id][1] / feat_stride + 0.5)<br>        <br>        # 3. Check if joint is inside the heatmap bounds<br>        ul = [int(mu_x - tmp_size), int(mu_y - tmp_size)]<br>        br = [int(mu_x + tmp_size + 1), int(mu_y + tmp_size + 1)]<br><br>        if ul[0] &gt;= output_size[1] or ul[1] &gt;= output_size[0] or br[0] &lt; 0 or br[1] &lt; 0:<br>            # Joint outside heatmap<br>            target_weight[joint_id] = 0<br>            continue<br><br>        # 4. Generate Gaussian<br>        size = 2 * tmp_size + 1<br>        x = torch.arange(0, size, dtype=torch.float32)<br>        y = torch.arange(0, size, dtype=torch.float32)<br><br>        yy, xx = torch.meshgrid(y, x, indexing=&quot;ij&quot;)<br><br>        xx = xx - tmp_size<br>        yy = yy - tmp_size<br><br>        g = torch.exp(-(xx**2 + yy**2) / (2 * sigma**2))<br><br><br>        # 5. Handle Boundary Clipping (if Gaussian goes off edge)<br>        g_x = max(0, -ul[0]), min(br[0], output_size[1]) - ul[0]<br>        g_y = max(0, -ul[1]), min(br[1], output_size[0]) - ul[1]<br>        img_x = max(0, ul[0]), min(br[0], output_size[1])<br>        img_y = max(0, ul[1]), min(br[1], output_size[0])<br><br>        target[joint_id][img_y[0]:img_y[1], img_x[0]:img_x[1]] = g[g_y[0]:g_y[1], g_x[0]:g_x[1]]<br><br>    return target, target_weight</pre><p>Final dataset preparation</p><pre>def square_crop_with_margin(img, bbox, margin=0):<br>    &quot;&quot;&quot;<br>    Crops the image around the bbox and pads to make it square.<br>    Returns: cropped_img, (x_offset, y_offset)<br>    &quot;&quot;&quot;<br>    x, y, w, h = map(int, bbox)<br>    H, W = img.shape[:2]<br><br>    # Add margin<br>    x -= margin<br>    y -= margin<br>    w += 2*margin<br>    h += 2*margin<br><br>    # Make square<br>    center_x = x + w / 2<br>    center_y = y + h / 2<br>    side = max(w, h)<br>    <br>    # Calculate new top-left<br>    new_x = int(center_x - side / 2)<br>    new_y = int(center_y - side / 2)<br>    side = int(side)<br><br>    # Handle padding if crop goes out of bounds<br>    pad_l = max(0, -new_x)<br>    pad_t = max(0, -new_y)<br>    pad_r = max(0, (new_x + side) - W)<br>    pad_b = max(0, (new_y + side) - H)<br><br>    # Crop valid area<br>    crop_x1 = max(0, new_x)<br>    crop_y1 = max(0, new_y)<br>    crop_x2 = min(W, new_x + side)<br>    crop_y2 = min(H, new_y + side)<br><br>    cropped = img[crop_y1:crop_y2, crop_x1:crop_x2]<br><br>    # Pad with zeros (black) to maintain square shape<br>    if pad_l &gt; 0 or pad_t &gt; 0 or pad_r &gt; 0 or pad_b &gt; 0:<br>        cropped = cv2.copyMakeBorder(cropped, pad_t, pad_b, pad_l, pad_r, cv2.BORDER_CONSTANT, value=(0,0,0))<br><br>    return cropped, new_x, new_y, side<br><br>class COCOKeypointDataset(Dataset):<br>    def __init__(self, coco_json, img_dir, input_size=(224, 224), heatmap_size=(56, 56), max_samples=None):<br>        &quot;&quot;&quot;<br>        Standard Pose Estimation Dataset.<br>        Output: Image [3, 224, 224], Target [17, 56, 56], TargetWeight [17, 1]<br>        &quot;&quot;&quot;<br>        with open(coco_json, &quot;r&quot;) as f:<br>            self.data = json.load(f)<br>        <br>        self.img_dir = img_dir<br>        self.input_size = input_size   # e.g., (224, 224)<br>        self.heatmap_size = heatmap_size # e.g., (56, 56)<br><br>        # Image normalization (Standard ImageNet mean/std)<br>        self.transform = T.Compose([<br>            T.ToTensor(),<br>            T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>        ])<br><br>        self.samples = []<br>        <br>        # Create a lookup for image filenames to avoid O(N) search<br>        self.img_id_to_file = {img[&#39;id&#39;]: img[&#39;file_name&#39;] for img in self.data[&#39;images&#39;]}<br><br>        print(&quot;🔍 Building COCO keypoint dataset...&quot;)<br>        for ann in tqdm(self.data[&quot;annotations&quot;], desc=&quot;Processing annotations&quot;):<br>            if ann[&quot;category_id&quot;] != 1 or ann[&quot;num_keypoints&quot;] == 0:<br>                continue<br>            <br>            # We treat every annotation (person) as a training sample<br>            img_filename = self.img_id_to_file.get(ann[&quot;image_id&quot;])<br>            if not img_filename: continue<br><br>            img_path = os.path.join(self.img_dir, img_filename)<br>            <br>            # Store everything needed to process on the fly<br>            self.samples.append({<br>                &quot;img_path&quot;: img_path,<br>                &quot;bbox&quot;: ann[&quot;bbox&quot;],<br>                &quot;keypoints&quot;: ann[&quot;keypoints&quot;] # List of [x, y, v, x, y, v...]<br>            })<br>            <br>            if max_samples and len(self.samples) &gt;= max_samples:<br>                break<br>        <br>        print(f&quot;✅ Total valid samples: {len(self.samples)}&quot;)<br><br>    def __len__(self):<br>        return len(self.samples)<br><br>    def __getitem__(self, idx):<br>        s = self.samples[idx]<br>        <br>        # 1. Load Image<br>        img = cv2.imread(s[&quot;img_path&quot;])<br>        if img is None:<br>            raise ValueError(f&quot;Image not found: {s[&#39;img_path&#39;]}&quot;)<br>        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br><br>        # 2. Parse Raw Keypoints<br>        raw_kps = np.array(s[&quot;keypoints&quot;]).reshape(-1, 3) # [17, 3] -&gt; (x, y, v)<br>        joints = raw_kps[:, :2].astype(np.float32)<br>        joints_vis = raw_kps[:, 2].astype(np.float32)<br><br>        # 3. Crop Logic (Square crop around person)<br>        crop_img, offset_x, offset_y, crop_side = square_crop_with_margin(img, s[&quot;bbox&quot;], margin=10)<br><br>        # 4. Transform Keypoints to Crop Coordinates<br>        # (x_new = x_old - top_left_crop_x)<br>        joints[:, 0] -= offset_x<br>        joints[:, 1] -= offset_y<br><br>        # 5. Resize to Model Input Size (e.g., 224x224)<br>        # We need the scale factor<br>        resize_ratio_x = self.input_size[1] / crop_side<br>        resize_ratio_y = self.input_size[0] / crop_side # Should be same since square<br><br>        img_final = cv2.resize(crop_img, (self.input_size[1], self.input_size[0]))<br>        <br>        # Apply same scale to joints<br>        joints[:, 0] *= resize_ratio_x<br>        joints[:, 1] *= resize_ratio_y<br><br>        # 6. Generate Heatmaps &amp; Weights<br>        # joints are now in 224x224 space. generate_target will divide by 4.<br>        target_heatmaps, target_weights = generate_target(<br>            joints, <br>            joints_vis, <br>            self.heatmap_size<br>        )<br><br>        # 7. Apply Image Transforms (Norm, Tensor)<br>        img_tensor = self.transform(img_final)<br><br>        return {<br>            &quot;image&quot;: img_tensor,            # [3, 224, 224]<br>            &quot;target&quot;: target_heatmaps,      # [17, 56, 56]<br>            &quot;target_weight&quot;: target_weights # [17, 1]<br>        }<br><br># Define paths (Adjust to your local paths)<br>JSON_PATH = &quot;/Users/saptarshimallikthakur/Pictures/detection daatset/COCO/annotations/person_keypoints_train2017.json&quot;<br>IMG_DIR = &quot;/Users/saptarshimallikthakur/Pictures/detection daatset/COCO/train2017&quot;<br><br>dataset = COCOKeypointDataset(<br>    coco_json=JSON_PATH,<br>    img_dir=IMG_DIR,<br>    input_size=(224, 224),<br>    heatmap_size=(56, 56)<br>)<br><br>dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)</pre><blockquote><strong>Final Model</strong></blockquote><p>Now we already wrote our feature extractor i.e the ViT encoder model. However it outputs (28,28,192) feature-size while our target is of (56,56,17) size. Sow we simply upscale and reduce the channels and built the final trainable model.</p><pre>device = &#39;mps&#39;<br><br>EMB_DIM = 192<br>NUM_HEADS = EMB_DIM // 32<br>PATCH_SIZE = 8<br>DEPTH = 6<br><br>class PatchUnembedding(nn.Module):<br>    def __init__(self, patch_size, out_channels, embed_dim):<br>        super().__init__()<br>        self.patch_size = patch_size<br>        self.out_channels = out_channels<br><br>        self.proj = nn.Linear(embed_dim, out_channels * patch_size * patch_size)<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        x: (B, N, D)<br>        &quot;&quot;&quot;<br>        B, N, D = x.shape<br><br>        H = W = int(N ** 0.5)<br>        assert H * W == N, f&quot;N={N} is not a perfect square&quot;<br><br>        P = self.patch_size<br>        C = self.out_channels<br><br>        x = self.proj(x)                <br>        x = x.view(B, H, W, C, P, P)<br>        x = x.permute(0, 3, 1, 4, 2, 5)   <br>        x = x.reshape(B, C, H * P, W * P)<br><br>        return x<br><br>class VitPose(nn.Module):<br>    def __init__(self, emb_dim=192):<br>        super().__init__()<br>        # Increased depth and MLP ratio for better capacity<br>        self.encoder = Encoder(patch_size=PATCH_SIZE, embed_dim=emb_dim, depth=DEPTH, num_heads=NUM_HEADS, mlp_ratio=3)<br>        self.unpatch = PatchUnembedding(2, 17, emb_dim)<br><br>    def forward(self, img):<br>        x = self.encoder(img) # (B, N, D)<br>        x = self.unpatch(x) # (B,C,H,W)<br>        return x<br><br>model = VitPose(EMB_DIM)<br>model.to(device)<br><br>total = sum(p.numel() for p in model.parameters())<br>trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)<br><br>print(f&quot;Total params     : {total:,}&quot;)<br>print(f&quot;Trainable params : {trainable:,}&quot;)<br>print(f&quot;Frozen params    : {total - trainable:,}&quot;)<br><br>Total params     : 2,989,892<br>Trainable params : 2,989,892<br>Frozen params    : 0</pre><blockquote><strong>Training</strong></blockquote><p>We shall be using simple MSE style loss however sum and not mean since majority of the pixel targets are zeros which artifically reduces the loss a lot.</p><pre>class JointsMSELoss(nn.Module):<br>    def __init__(self, use_target_weight=True):<br>        super(JointsMSELoss, self).__init__()<br>        self.criterion = nn.MSELoss(reduction=&#39;none&#39;) <br>        self.use_target_weight = use_target_weight<br><br>    def forward(self, output, target, target_weights):<br>        batch_size = output.size(0)<br>        num_joints = output.size(1)<br>        <br>        heatmaps_pred = output.reshape((batch_size, num_joints, -1))<br>        heatmaps_gt = target.reshape((batch_size, num_joints, -1))<br>        <br>        loss = 0.5 * self.criterion(heatmaps_pred, heatmaps_gt)<br>        <br>        if self.use_target_weight:<br>            loss = loss * target_weights<br>        <br>        # CHANGED: Sum over pixels instead of Mean, as many background pixels and those are zeros !<br>        loss = loss.sum(dim=2) <br>        <br>        # Normalize by batch size and valid joints only<br>        loss = loss.sum() / target_weights.sum().clamp(min=1)<br>        return loss<br><br>class CustomLRScheduler(_LRScheduler):<br>    def __init__(self, optimizer, total_steps, warmup_steps_ratio, min_lr, max_lr, last_epoch=-1):<br>        self.total_steps = total_steps<br>        self.warmup_steps = int(total_steps * warmup_steps_ratio)<br>        self.min_lr = min_lr<br>        self.max_lr = max_lr<br>        super(CustomLRScheduler, self).__init__(optimizer, last_epoch)<br><br>    def get_lr(self):<br>        current_step = self.last_epoch<br>        if current_step &lt; self.warmup_steps:<br>            lr = self.min_lr + (self.max_lr - self.min_lr) * (current_step / self.warmup_steps)<br>        else:<br>            progress = (current_step - self.warmup_steps) / (self.total_steps - self.warmup_steps)<br>            decay_factor = math.exp(-1.0 * progress)<br>            lr = self.min_lr + (self.max_lr - self.min_lr) * decay_factor<br>            lr = max(lr, self.min_lr)<br>        return [lr for _ in self.base_lrs]<br>    <br>EPOCHS = 5<br>TOTAL_STEPS = len(dataloader)*EPOCHS<br><br>LEARNING_RATE_MIN = 1e-5<br>LEARNING_RATE_MAX = 1e-3<br>WARMUP_RATIO = 0.1<br><br># --- Optimizer ---<br>optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE_MAX, betas=(0.9, 0.98), eps=1e-9)<br>loss_fn = JointsMSELoss().to(device)<br>scheduler = CustomLRScheduler(<br>    optimizer,TOTAL_STEPS,<br>    warmup_steps_ratio=WARMUP_RATIO,<br>    min_lr=LEARNING_RATE_MIN,<br>    max_lr=LEARNING_RATE_MAX<br>)<br><br><br>model.train()<br><br>for epoch in range(EPOCHS):<br><br>    loss_train = 0.0<br><br>    progress_bar = tqdm(dataloader, desc=f&quot;Epoch {epoch+1}/{EPOCHS}&quot;, leave=True, unit=&#39;batch&#39;)<br><br>    for batch in progress_bar:<br><br>        imgs          = batch[&#39;image&#39;].to(device)<br>        target        = batch[&quot;target&quot;].to(device)                  <br>        target_weight = batch[&quot;target_weight&quot;].to(device)  <br><br>        pred = model(imgs)                          <br>        loss = loss_fn(pred, target, target_weight)<br><br>        loss_train += loss.item()<br><br>        optimizer.zero_grad()<br>        loss.backward()<br><br>        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)<br>        optimizer.step()<br>        scheduler.step()<br><br>        progress_bar.set_postfix(loss=loss.item(), lr=f&quot;{scheduler.get_last_lr()[0]:.6f}&quot;)<br><br>    loss_tensor = torch.tensor([loss_train], device=device)<br>    avg_loss = loss_tensor[0].item() / len(dataloader)<br><br>    print(f&quot;Epoch {epoch+1} | Loss {avg_loss:.4f} | &quot;)<br>    <br>    torch.save(model.state_dict(), &#39;model.pt&#39;)</pre><p>As you can see below the model is learning and it still has lot of room to learn since loss is reducing gradually. However due to limited time i trained only for 5 epcohs.</p><pre>Epoch 1/5: 100%|██████████| 4682/4682 [1:37:48&lt;00:00,  1.25s/batch, loss=4.52, lr=0.000896]<br>Epoch 1| Loss 7.4668 | <br>Epoch 2/5: 100%|██████████| 4682/4682 [1:38:32&lt;00:00,  1.26s/batch, loss=3.63, lr=0.000719]<br>Epoch 2| Loss 4.0147 | <br>Epoch 3/5: 100%|██████████| 4682/4682 [1:38:41&lt;00:00,  1.26s/batch, loss=4.12, lr=0.000578]<br>Epoch 3| Loss 3.5980 | <br>Epoch 4/5: 100%|██████████| 4682/4682 [1:38:44&lt;00:00,  1.27s/batch, loss=3.37, lr=0.000465]<br>Epoch 4| Loss 3.3258 | <br>Epoch 5/5: 100%|██████████| 4682/4682 [1:38:45&lt;00:00,  1.27s/batch, loss=2.54, lr=0.000374]<br>Epoch 5| Loss 3.1308 |</pre><blockquote><strong>Inference</strong></blockquote><p>During inference, the following steps are performed:</p><ol><li>Obtain the <strong>bounding box coordinates</strong> of the person, either from annotations or from a human detection model.</li><li><strong>Crop the person region</strong> from the original image using the bounding box coordinates.</li><li><strong>Preprocess the cropped image</strong> using the same transformations applied during the training pipeline.</li><li><strong>Pass the processed crop</strong> through the trained key-point detection model to obtain predicted key-point coordinates.</li><li><strong>Project the predicted coordinates back</strong> to the original image space and visualize the key-points on the image.</li></ol><pre>COCO_KEYPOINTS = [&#39;nose&#39;, &#39;left_eye&#39;, &#39;right_eye&#39;, &#39;left_ear&#39;, &#39;right_ear&#39;,<br>                  &#39;left_shoulder&#39;, &#39;right_shoulder&#39;, &#39;left_elbow&#39;, &#39;right_elbow&#39;,<br>                  &#39;left_wrist&#39;, &#39;right_wrist&#39;, &#39;left_hip&#39;, &#39;right_hip&#39;,<br>                  &#39;left_knee&#39;, &#39;right_knee&#39;, &#39;left_ankle&#39;, &#39;right_ankle&#39;<br>                  ]<br><br>device = &#39;mps&#39;<br><br>coco_json = &quot;/Users/saptarshimallikthakur/Pictures/detection daatset/COCO/annotations/person_keypoints_train2017.json&quot;<br>img_dir   = &quot;/Users/saptarshimallikthakur/Pictures/detection daatset/COCO/train2017&quot;<br><br>with open(coco_json, &quot;r&quot;) as f:<br>    data = json.load(f)<br><br># Image normalization (Standard ImageNet mean/std)<br>transform = T.Compose([<br>    T.ToTensor(),<br>    T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>])<br><br>samples = []<br><br># Create a lookup for image filenames to avoid O(N) search<br>img_id_to_file = {img[&#39;id&#39;]: img[&#39;file_name&#39;] for img in data[&#39;images&#39;]}<br><br>print(&quot;🔍 Building COCO keypoint dataset...&quot;)<br>for ann in tqdm(data[&quot;annotations&quot;], desc=&quot;Processing annotations&quot;):<br>    if ann[&quot;category_id&quot;] != 1 or ann[&quot;num_keypoints&quot;] == 0:<br>        continue<br>    <br>    # We treat every annotation (person) as a training sample<br>    img_filename = img_id_to_file.get(ann[&quot;image_id&quot;])<br>    if not img_filename: continue<br><br>    img_path = os.path.join(img_dir, img_filename)<br>    <br>    # Store everything needed to process on the fly<br>    samples.append({<br>        &quot;img_path&quot;: img_path,<br>        &quot;bbox&quot;: ann[&quot;bbox&quot;],<br>        &quot;keypoints&quot;: ann[&quot;keypoints&quot;] # List of [x, y, v, x, y, v...]<br>    })</pre><pre>def preprocess_image(img_path, bbox, input_size=(224,224)):<br>    img = cv2.imread(img_path)<br>    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br><br>    # Square crop (same as training)<br>    crop_img, offset_x, offset_y, crop_side = square_crop_with_margin(<br>        img, bbox, margin=10<br>    )<br><br>    # Resize<br>    img_resized = cv2.resize(crop_img, input_size)<br><br>    # Normalize<br>    img_tensor = T.ToTensor()(img_resized)<br>    img_tensor = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])(img_tensor)<br><br>    return img_tensor.unsqueeze(0), offset_x, offset_y, crop_side, img<br><br>def heatmaps_to_keypoints(heatmaps, threshold=0.2, input_size=(224,224)):<br>    &quot;&quot;&quot;<br>    heatmaps: (1, 17, H, W)<br>    returns: (17, 2) in input image scale<br>    &quot;&quot;&quot;<br>    B, J, H, W = heatmaps.shape<br>    heatmaps = heatmaps.cpu().numpy()<br><br>    keypoints = np.zeros((J, 2), dtype=np.float32)<br><br>    for j in range(J):<br>        hm = heatmaps[0, j]<br>        conf = hm.max()<br><br>        if conf &lt; threshold:<br>            keypoints[j, 0] = -1e6<br>            keypoints[j, 1] = -1e6<br>            continue<br>        <br>        idx = np.argmax(hm)<br>        y, x = np.unravel_index(idx, hm.shape)<br><br>        # Scale back to input resolution<br>        keypoints[j, 0] = x * (input_size[1] / W)<br>        keypoints[j, 1] = y * (input_size[0] / H)<br><br>    return keypoints<br><br>def map_back_to_original(kps, offset_x, offset_y, crop_side, input_size=(224,224)):<br>    scale_x = crop_side / input_size[1]<br>    scale_y = crop_side / input_size[0]<br><br>    kps_orig = kps.copy()<br>    kps_orig[:, 0] *= scale_x<br>    kps_orig[:, 1] *= scale_y<br><br>    kps_orig[:, 0] += offset_x<br>    kps_orig[:, 1] += offset_y<br><br>    return kps_orig<br><br>def draw_keypoints(img, keypoints):<br>    img_vis = img.copy()<br>    for i, (x, y) in enumerate(keypoints):<br>        if x &lt; 0 or y &lt; 0:<br>            continue<br>        cv2.circle(img_vis, (int(x), int(y)), 3, (0,255,0), -1)<br>        cv2.putText(<br>            img_vis, COCO_KEYPOINTS[i],<br>            (int(x)+3, int(y)+3),<br>            cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255,255,0), 1<br>        )<br>    return img_vis</pre><pre>model = VitPose(EMB_DIM)<br>model.load_state_dict(torch.load(&quot;model.pt&quot;, map_location=device))<br>model.to(device)<br>model.eval()<br><br><br>for index in range(50):#random.sample(range(10000),10):<br>    img_path = samples[index][&#39;img_path&#39;]<br>    bbox     = samples[index][&#39;bbox&#39;]<br><br>    with torch.no_grad():<br>        img_tensor, offset_x, offset_y, crop_side, orig_img = preprocess_image(img_path, bbox)<br>        img_tensor = img_tensor.to(device)<br>        pred_heatmaps = model(img_tensor)   # (1, 17, 56, 56)<br><br>    kps_input = heatmaps_to_keypoints(pred_heatmaps)<br>    kps_orig = map_back_to_original(kps_input, offset_x, offset_y, crop_side)<br><br>    vis = draw_keypoints(orig_img, kps_orig)<br><br>    plt.figure(figsize=(15,15))<br>    plt.imshow(vis)<br>    plt.axis(&quot;off&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6ZpoRIJUWdvFvNKHOGmXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYrykYE0cZW9eePnjSHfRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwLgxBemaYJK9UZ2oPul3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7gHQqokqFwHWMGLmTNAWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1Y_vmsbixd6g8q986EnGA.png" /></figure><p>And that’s it. To improve the results, increase model parameters and training time.</p><p>Till then Happy Learning !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a179f433a4a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object as Points : Anchor free object detection from scratch (2019) | Tensorflow]]></title>
            <link>https://medium.com/@saptarshimt/object-as-points-anchor-free-object-detection-from-scratch-2019-tensorflow-6170eb815c07?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6170eb815c07</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[from-scratch]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 14:51:35 GMT</pubDate>
            <atom:updated>2025-07-17T03:21:07.941Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object as Points : Anchor free object detection from scratch | Tensorflow</h3><p>The following article is inspired from the paper which implemented Centernet for object detection ( <a href="https://arxiv.org/abs/1904.07850">https://arxiv.org/abs/1904.07850</a> ).</p><blockquote>In this paper, we propose a simpler and faster approach to object detection. We represent each object by a single point at the center of its bounding box. From this center point, we directly predict properties like size, orientation, and pose using image features. Our method turns object detection into a keypoint detection task. A fully convolutional network takes the input image and produces a heatmap, where each peak marks an object center. From these points, we estimate the object’s height and width. The model is trained with standard dense supervision and runs in a single forward pass during inference, with no need for post-processing steps like non-maximum suppression.</blockquote><ul><li>I will be using Pascal VOC 2012 dataset with 20 classes for training purpose.</li><li>My base model for feature extraction will be a light-weight imagenet pretrained MobileNetV3 Small.</li></ul><h3>What is a Heatmap?</h3><ul><li>A <strong>heatmap</strong> in this case is a tensor of shape <strong>(H, W, C).</strong></li><li>H and W = spatial dimensions (e.g., 56×56)</li><li>C = number of object classes (e.g., 20)</li></ul><p>Each pixel (i, j) in the heatmap contains <strong>C scores</strong>, one for each class. These scores indicate how likely it is that an object of that class is centered at that pixel.</p><p>Let’s say the output heatmap is (56, 56, 20). At location (25, 30), we have 20 values like:</p><ul><li>[0.01, 0.04, 0.02, …, 0.91 (for ‘dog’), …, 0.03]</li><li>That means: “There is a <strong>high confidence</strong> (0.91) that a ‘dog’ object is centered at pixel (25, 30).”</li></ul><p>Basically a peak (high value) in any class-channel suggests the center of that class’s object.<br>Heatmap also plays a critical role in determining which pixel contains the object center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*DimwG8YvzWBmWiTd7D0KGw.png" /><figcaption>Object location at (25,22) in 56x56x1 feature map.</figcaption></figure><p>Now based on the provided image you would notice that there is a distribution spread gradually decreasing as we move away from the actual location of object.</p><blockquote>When creating the ground truth heatmap for training, we don’t set a hard 1 at just the exact center pixel of an object. Instead, we <strong>draw a 2D Gaussian</strong> centered at the object’s center point.</blockquote><h4>Why use a Gaussian instead of a single hot pixel?</h4><ol><li><strong>Robustness to localization error:</strong></li></ol><ul><li>Nearby pixels around the true center also carry some confidence.</li><li>This helps the model learn even if its predicted center is slightly off.</li></ul><p><strong>2. Smooth gradients:</strong></p><ul><li>A single hot pixel (1 at center, 0 everywhere else) creates sparse gradients during training.</li><li>A Gaussian provides a smoother loss surface, making training more stable and effective.</li></ul><p><strong>3. Better convergence:</strong></p><ul><li>The model receives partial credit for predicting near the center.</li><li>This encourages the network to gradually refine its predictions.</li></ul><p>Heatmap slice (e.g., 7×7 patch around center):</p><pre>0.01  0.03  0.08  0.12  0.08  0.03  0.01  <br>0.03  0.10  0.25  0.35  0.25  0.10  0.03  <br>0.08  0.25  0.60  0.85  0.60  0.25  0.08  <br>0.12  0.35  0.85  1.00  0.85  0.35  0.12  <br>0.08  0.25  0.60  0.85  0.60  0.25  0.08  <br>0.03  0.10  0.25  0.35  0.25  0.10  0.03  <br>0.01  0.03  0.08  0.12  0.08  0.03  0.01</pre><p>Here, the value 1.0 is at the object center, but neighboring values are also &gt; 0, due to the <strong>2D Gaussian kernel</strong>.</p><p>Note : The spread of distribution or Gaussian radius is chosen based on object size.</p><pre>def calculate_gaussian_radius(box_size, min_overlap=0):<br>    &quot;&quot;&quot;<br>    Calculates the radius of the Gaussian bump based on the size of the bounding box.<br>    This is a Python implementation of the logic from the official CornerNet/CenterNet code.<br><br>    Args:<br>        box_size (tuple or list): A tuple of (box_height, box_width).<br>        min_overlap (float): The minimum IoU required between the circle and the box.<br><br>    Returns:<br>        int: The calculated radius, rounded up to the nearest integer.<br>    &quot;&quot;&quot;<br>    height, width = box_size<br><br>    # Formula derived from solving the IoU equations for a circle and a box<br>    a1 = 1.0<br>    b1 = (height + width)<br>    c1 = width * height * (1 - min_overlap) / (1 + min_overlap)<br>    sq1 = np.sqrt(b1 ** 2 - 4 * a1 * c1)<br>    r1 = (b1 - sq1) / (2 * a1)<br><br>    a2 = 4.0<br>    b2 = 2 * (height + width)<br>    c2 = (1 - min_overlap) * width * height<br>    sq2 = np.sqrt(b2 ** 2 - 4 * a2 * c2)<br>    r2 = (b2 - sq2) / (2 * a2)<br><br>    a3 = 4 * min_overlap<br>    b3 = -2 * min_overlap * (height + width)<br>    c3 = (min_overlap - 1) * width * height<br>    sq3 = np.sqrt(b3 ** 2 - 4 * a3 * c3)<br>    r3 = (b3 + sq3) / (2 * a3)<br>    <br>    # Return the smallest valid radius, rounded up<br>    # A radius is valid if its discriminant (the value inside sqrt) is non-negative<br>    valid_radii = []<br>    if b1 ** 2 - 4 * a1 * c1 &gt;= 0:<br>        valid_radii.append(r1)<br>    if b2 ** 2 - 4 * a2 * c2 &gt;= 0:<br>        valid_radii.append(r2)<br>    if b3 ** 2 - 4 * a3 * c3 &gt;= 0:<br>        valid_radii.append(r3)<br><br>    if not valid_radii:<br>        # Fallback if no solution is found (e.g., for very small boxes)<br>        # This is unlikely with standard min_overlap values<br>        return 0<br>    else:<br>        return math.ceil(min(valid_radii))<br><br><br># --- Example Usage ---<br>box_height, box_width = 60, 100<br>radius = calculate_gaussian_radius((box_height, box_width))<br>print(f&quot;For a box of size ({box_height}, {box_width}), the calculated radius is: {radius}&quot;) <br><br>small_box_h, small_box_w = 10, 15<br>small_radius = calculate_gaussian_radius((small_box_h, small_box_w))<br>print(f&quot;For a box of size ({small_box_h}, {small_box_w}), the calculated radius is: {small_radius}&quot;) <br><br># --- Output ---<br>- For a box of size (60, 100), the calculated radius is: 30<br>- For a box of size (10, 15), the calculated radius is: 5</pre><pre>def draw_gaussian(heatmap, center, radius):<br>    &quot;&quot;&quot;<br>    Draws a 2D Gaussian &quot;bump&quot; onto a heatmap.<br><br>    Args:<br>        heatmap (np.ndarray): A 2D numpy array of shape (H, W) representing one<br>                              channel of the target heatmap.<br>        center (tuple): The (x, y) integer coordinates of the center of the bump.<br>        radius (int): The integer radius of the Gaussian bump.<br>    &quot;&quot;&quot;<br>    # The diameter of the patch to calculate<br>    diameter = 2 * radius + 1<br>    <br>    # If the radius is 0, we don&#39;t need to do anything<br>    if radius == 0:<br>        return heatmap<br><br>    # Create a grid of x and y coordinates for the patch<br>    x = np.arange(0, diameter, 1, float)<br>    y = np.arange(0, diameter, 1, float)[:, np.newaxis]<br>    <br>    # The center of the patch is at (radius, radius)<br>    x0 = y0 = radius<br>    <br>    # Calculate the Gaussian. Sigma is derived from the radius.<br>    sigma = diameter / 10<br>    g = np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))<br><br>    # Get the integer coordinates of the center on the main heatmap<br>    center_x, center_y = center<br><br>    # Determine the boundaries of where to place the patch on the heatmap<br>    # This handles edge cases where the object is near the border.<br>    left = min(center_x, radius)<br>    right = min(heatmap.shape[1] - 1 - center_x, radius)<br>    top = min(center_y, radius)<br>    bottom = min(heatmap.shape[0] - 1 - center_y, radius)<br>    <br>    # Select the slice of the heatmap to be updated<br>    masked_heatmap = heatmap[center_y - top : center_y + bottom + 1, <br>                             center_x - left : center_x + right + 1]<br>    <br>    # Select the corresponding slice from the generated Gaussian patch<br>    masked_gaussian = g[radius - top : radius + bottom + 1,<br>                        radius - left : radius + right + 1]<br>    <br>    # Place the Gaussian on the heatmap by taking the maximum value.<br>    # This is important for handling overlapping objects of the same class.<br>    if masked_heatmap.shape == masked_gaussian.shape:<br>        np.maximum(masked_heatmap, masked_gaussian, out=masked_heatmap)<br>        <br>    return heatmap<br><br># --- Example Usage ---<br><br># Create a blank 56x56 heatmap channel<br>heatmap_channel = np.zeros((56, 56), dtype=np.float32)<br><br># Define our object&#39;s properties<br>center_point = (25, 22) # (x, y)<br>feature_map_radius = 5<br><br># Draw the gaussian<br>draw_gaussian(heatmap_channel, center_point, feature_map_radius)<br><br># Check the values<br>print(f&quot;Value at center (25, 22): {heatmap_channel[22, 25]:.4f}&quot;)<br>print(f&quot;Value at neighbor (26, 22): {heatmap_channel[22, 26]:.4f}&quot;)<br>print(f&quot;Value at neighbor (24, 23): {heatmap_channel[23, 24]:.4f}&quot;)<br>print(f&quot;Value far away (30, 22): {heatmap_channel[22, 30]:.4f}&quot;) <br><br># --- Output ---<br>Value at center (25, 22): 1.0000<br>Value at neighbor (26, 22): 0.6615<br>Value at neighbor (24, 23): 0.4376<br>Value far away (30, 22): 0.0000</pre><h3>Offset prediction</h3><p>When we extract feature map from an input image (e.g., 224×224 → 56×56), the <strong>object center may not fall exactly on an integer location</strong> in the output heatmap.<br>But heatmaps are <strong>discrete</strong>, so during training, the center gets <strong>rounded down</strong> to the nearest integer pixel. To recover the <strong>exact continuous center</strong>, we predict a <strong>fractional offset</strong> from the integer heatmap location.</p><p>Setup:</p><ul><li>Input image size: 224<strong>×224</strong></li><li>Output heatmap size: 56<strong>×56</strong><br> (since 224/ 4 = 56)</li><li>Downsampling ratio: <strong>4×</strong></li></ul><h4><strong>Ground Truth Center Example:</strong></h4><p>Let’s say the object’s actual center in the input image is at <strong>(x, y) = (101.3, 203.8)</strong>.</p><p>After downsampling by 4:</p><ul><li>cx = 101.3 / 4 = 25.325 ,<br>cy = 203.8 / 4 = 50.95</li></ul><p>Rounded heatmap location:</p><ul><li>px = int(25.325) = 25 ,<br>py = int(50.95) = 50</li></ul><p>Now the offset is:</p><ul><li>offset_x = 25.325–25 = 0.325 ,<br>offset_y = 50.95–50 = 0.95</li></ul><p>Without predicting the offset, the decoded center would be at (25, 50) × 4 = (100, 200) → <strong>error of over 1 pixel</strong> in both axes.<br>With offset, we get:</p><ul><li>center_x = (25 + 0.325) × 4 = 101.3 ,<br>center_y = (50 + 0.95) × 4 = 203.8</li></ul><h3>Size prediction</h3><p>Once we find the <strong>center point</strong> of an object on the heatmap, we need to know how <strong>big</strong> the object is — i.e., its <strong>width and height</strong> in the original image.</p><p>That’s what <strong>size prediction</strong> does:</p><ul><li><strong>Predict the width and height</strong> of the bounding box for each object — from the image features at the detected center point.</li></ul><h3>Data Preparation</h3><pre>LABELS = [&#39;aeroplane&#39;,  &#39;bicycle&#39;, &#39;bird&#39;,  &#39;boat&#39;,      &#39;bottle&#39;, <br>          &#39;bus&#39;,        &#39;car&#39;,      &#39;cat&#39;,  &#39;chair&#39;,     &#39;cow&#39;,<br>          &#39;diningtable&#39;,&#39;dog&#39;,    &#39;horse&#39;,  &#39;motorbike&#39;, &#39;person&#39;,<br>          &#39;pottedplant&#39;,&#39;sheep&#39;,  &#39;sofa&#39;,   &#39;train&#39;,   &#39;tvmonitor&#39;]<br><br>NUM_CLASSES = len(LABELS)<br><br>def data_generator(train_data, batch_size, INPUT_SIZE=224, FEATURE_MAP_SIZE=56, NUM_CLASSES=1):<br>    &quot;&quot;&quot;<br>    Generator yielding (batch_images, [heatmap, size_with_mask, offset_with_mask]) without preloading all images<br>    &quot;&quot;&quot;<br>    num_samples = len(train_data)<br>    indices = np.arange(num_samples)<br>    DOWNSAMPLING_RATIO = INPUT_SIZE / FEATURE_MAP_SIZE<br><br>    while True:<br>        np.random.shuffle(indices)<br>        for start in range(0, num_samples, batch_size):<br>            end = start + batch_size<br>            batch_idx = indices[start:end]<br>            <br>            batch_images = np.zeros((len(batch_idx), INPUT_SIZE, INPUT_SIZE, 3), dtype=np.float32)<br>            heatmaps     = np.zeros((len(batch_idx), FEATURE_MAP_SIZE, FEATURE_MAP_SIZE, NUM_CLASSES), dtype=np.float32)<br>            size_maps    = np.zeros((len(batch_idx), FEATURE_MAP_SIZE, FEATURE_MAP_SIZE, 2), dtype=np.float32)<br>            offset_maps  = np.zeros((len(batch_idx), FEATURE_MAP_SIZE, FEATURE_MAP_SIZE, 2), dtype=np.float32)<br>            masks        = np.zeros((len(batch_idx), FEATURE_MAP_SIZE, FEATURE_MAP_SIZE), dtype=np.float32)<br><br>            for b, idx in enumerate(batch_idx):<br>                x = train_data[idx]<br>                w_img, h_img = x[&#39;width&#39;], x[&#39;height&#39;]<br>                image = cv2.imread(x[&#39;filename&#39;])<br>                image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)<br>                image = cv2.resize(image, (INPUT_SIZE, INPUT_SIZE)).astype(np.float32) <br><br>                batch_images[b] = image<br><br>                for obj in x[&#39;object&#39;]:<br>                    xmin = obj[&#39;xmin&#39;] * INPUT_SIZE / w_img<br>                    xmax = obj[&#39;xmax&#39;] * INPUT_SIZE / w_img<br>                    ymin = obj[&#39;ymin&#39;] * INPUT_SIZE / h_img<br>                    ymax = obj[&#39;ymax&#39;] * INPUT_SIZE / h_img<br><br>                    cx = (xmin + xmax) / 2<br>                    cy = (ymin + ymax) / 2<br>                    bw = xmax - xmin<br>                    bh = ymax - ymin<br>                    class_id = LABELS.index(obj[&#39;name&#39;])<br><br>                    fx, fy = cx / DOWNSAMPLING_RATIO, cy / DOWNSAMPLING_RATIO<br>                    px, py = int(fx), int(fy)<br><br>                    if px &lt; 0 or px &gt;= FEATURE_MAP_SIZE or py &lt; 0 or py &gt;= FEATURE_MAP_SIZE:<br>                        continue<br><br>                    radius = calculate_gaussian_radius((bh, bw), min_overlap=0.1) / DOWNSAMPLING_RATIO<br>                    radius = max(1, round(radius))<br>                    draw_gaussian(heatmaps[b, :, :, class_id], (px, py), radius)<br><br>                    off_x, off_y = fx - px, fy - py<br>                    size_maps[b, py, px, :]   = [bw, bh]<br>                    offset_maps[b, py, px, :] = [off_x, off_y]<br>                    masks[b, py, px]          = 1.0<br><br>            size_with_mask   = np.concatenate([size_maps,   masks[..., np.newaxis]], axis=-1)<br>            offset_with_mask = np.concatenate([offset_maps, masks[..., np.newaxis]], axis=-1)<br><br>            y_true_dict = {<br>                &#39;heatmap_out&#39;: heatmaps,<br>                &#39;size_out&#39;: size_with_mask,<br>                &#39;offset_out&#39;: offset_with_mask<br>            }<br><br>            yield batch_images, y_true_dict<br><br>ds = data_generator(train_image, batch_size=32, NUM_CLASSES=NUM_CLASSES)</pre><h3>Model Building</h3><ul><li><strong>Feature Extractor:</strong> We use <strong>MobileNetV3-Small</strong>, a lightweight and high-accuracy model originally trained on the ImageNet classification task. Given an input image of size <strong>(224, 224, 3)</strong>, it produces a <strong>(7, 7, 576)</strong> feature map. This output is then <strong>upsampled to (56, 56)</strong> to match the resolution at which object center points are defined.</li></ul><pre>@register_keras_serializable(&quot;Custom&quot;)<br>class FeatureExtractor(layers.Layer):<br>    def __init__(self, input_shape=(224, 224, 3), weights_path=&quot;weights_mobilenet_v3_small_224_1.0_float_no_top_v2.h5&quot;,**kwargs):<br>        super().__init__(**kwargs)<br>        self.backbone = MobileNetV3Small(input_shape=input_shape,<br>                                         weights=None,<br>                                         include_top=False,<br>                                         pooling=None)<br>        if weights_path:<br>            self.backbone.load_weights(weights_path)<br>        self.backbone.trainable = False<br><br>        self.up_stack = tf.keras.Sequential([<br>                    # First upsampling stage<br>                    layers.UpSampling2D(size=(2, 2), interpolation=&#39;bilinear&#39;),<br>                    layers.Conv2D(256, 3, padding=&#39;same&#39;, use_bias=False, kernel_initializer=&#39;he_normal&#39;),<br>                    layers.BatchNormalization(),<br>                    layers.ReLU(),<br><br>                    # Second upsampling stage<br>                    layers.UpSampling2D(size=(2, 2), interpolation=&#39;bilinear&#39;),<br>                    layers.Conv2D(128, 3, padding=&#39;same&#39;, use_bias=False, kernel_initializer=&#39;he_normal&#39;),<br>                    layers.BatchNormalization(),<br>                    layers.ReLU(),<br><br>                    # Third upsampling stage<br>                    layers.UpSampling2D(size=(2, 2), interpolation=&#39;bilinear&#39;),<br>                    layers.Conv2D(64, 3, padding=&#39;same&#39;, use_bias=False, kernel_initializer=&#39;he_normal&#39;),<br>                    layers.BatchNormalization(),<br>                    layers.ReLU()<br>                ], name=&quot;upsample_stack&quot;)<br><br>    def call(self, x):<br>        x = self.backbone(x)<br>        x = self.up_stack(x)<br>        return x # (56,56,128)</pre><ul><li><strong>Decoder Head:</strong> This module takes the upsampled feature map as input and generates the desired outputs — including the heatmap for object centers, size predictions (width and height), and offset values — required for object detection.</li></ul><blockquote><strong><em>Note:</em></strong><em> You might notice that the heatmap head uses </em><strong><em>sigmoid</em></strong><em> activation.<br> If you’re wondering </em><strong><em>why not softmax</em></strong><em>, here’s the reason:</em></blockquote><p>In <strong>CenterNet-style object detection</strong>, the heatmap is a <strong>dense pixel-wise classification map</strong>, where <strong>each pixel independently predicts whether it’s the center of an object of a particular class</strong>.</p><h4>🔍 Why Sigmoid (per-pixel, per-class activation)?</h4><ul><li><strong>Sigmoid</strong> treats each class channel independently — it outputs a <strong>probability between 0 and 1</strong> for <strong>each class at each pixel location</strong>.</li><li>This is necessary because <strong>multiple objects of different classes can exist at different locations</strong> in the same image.</li><li>For example, at pixel (x1, y1), a &quot;car&quot; might be centered; at (x2, y2), a &quot;person&quot; — both need independent binary predictions.</li></ul><h4>🚫 Why not Softmax?</h4><ul><li><strong>Softmax</strong> normalizes <strong>across all classes at a pixel</strong>, meaning the sum of class scores at each pixel = 1.</li><li>This implies <strong>only one class can be active per pixel</strong>, which makes sense in image classification but <strong>not in object detection</strong> where:</li><li>Most pixels are background (should have all class scores ≈ 0)</li><li>Some pixels should activate for one specific class (center points)</li><li>Softmax would wrongly assign probability mass even to irrelevant classes</li></ul><h4>✅ Summary:</h4><ul><li><strong>Sigmoid</strong> allows <strong>independent per-class binary classification</strong> at each pixel (ideal for center detection).</li><li><strong>Softmax</strong> is unsuitable because it forces competition between classes at each pixel — which isn’t the case in center heatmap prediction.</li></ul><pre>@register_keras_serializable(&quot;Custom&quot;)<br>class MLPDecoder(layers.Layer):<br>    def __init__(self, embedding_dim, num_classes, name=&quot;mlp_decoder&quot;, **kwargs):<br>        super().__init__(name=name, **kwargs)<br><br>        # Heatmap Head<br>        self.heatmap_head = tf.keras.Sequential([<br>            layers.Conv2D(embedding_dim, 3, padding=&quot;same&quot;, activation=&#39;relu&#39;),<br>            layers.Conv2D(num_classes, 1, activation=&#39;sigmoid&#39;, bias_initializer=tf.keras.initializers.Constant(-2.19))<br>        ], name=&#39;heatmap_head&#39;)<br><br>        # Size Head<br>        self.size_head = tf.keras.Sequential([<br>            layers.Conv2D(embedding_dim, 3, padding=&quot;same&quot;, activation=&#39;relu&#39;),<br>            layers.Conv2D(2, 1, activation=None)<br>        ], name=&#39;size_head&#39;)<br><br>        # Offset Head<br>        self.offset_head = tf.keras.Sequential([<br>            layers.Conv2D(embedding_dim, 3, padding=&quot;same&quot;, activation=&#39;relu&#39;),<br>            layers.Conv2D(2, 1, activation=None)<br>        ], name=&#39;offset_head&#39;)<br><br>    def call(self, features):<br>        heatmap = self.heatmap_head(features)<br>        size = self.size_head(features)<br>        offset = self.offset_head(features)<br>        return heatmap, size, offset</pre><ul><li>Final model combining the above two :</li></ul><pre>@register_keras_serializable(&quot;Custom&quot;)<br>class BuildCenterNet(tf.keras.Model):<br>    def __init__(self, input_shape=(224, 224, 3), num_classes=20, decoder_embedding_dim=64,**kwargs):<br>        super().__init__(name=&#39;CenterNet&#39;,**kwargs)<br><br>        self.backbone = FeatureExtractor(input_shape=input_shape)<br>        self.decoder = MLPDecoder(embedding_dim=decoder_embedding_dim, num_classes=num_classes)<br>        self._input_shape = input_shape<br><br>    def call(self, inputs):<br>        x = self.backbone(inputs)<br>        heatmap, size, offset = self.decoder(x)<br>        return {&#39;heatmap_out&#39;: heatmap, &#39;size_out&#39;: size, &#39;offset_out&#39;: offset}<br><br>    def get_model(self):<br>        inp = layers.Input(shape=self._input_shape)<br>        out = self.call(inp)       <br>        return Model(inp, out, name=f&quot;{self.name}_model&quot;)<br>    <br>centernet = BuildCenterNet(input_shape=(224, 224, 3), num_classes=NUM_CLASSES, decoder_embedding_dim=64)<br>detector = centernet.get_model()<br>detector.summary()<br><br><br>┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓<br>┃ Layer (type)                    ┃ Output Shape           ┃       Param # ┃<br>┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩<br>│ input_layer_1 (InputLayer)      │ (None, 224, 224, 3)    │             0 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ feature_extractor               │ (None, 56, 56, 64)     │     2,636,656 │<br>│ (FeatureExtractor)              │                        │               │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ mlp_decoder (MLPDecoder)        │ [(None, 56, 56, 20),   │       112,344 │<br>│                                 │ (None, 56, 56, 2),     │               │<br>│                                 │ (None, 56, 56, 2)]     │               │<br>└─────────────────────────────────┴────────────────────────┴───────────────┘<br><br> Total params: 2,749,000 (10.49 MB)<br> Trainable params: 1,808,984 (6.90 MB)<br> Non-trainable params: 940,016 (3.59 MB)</pre><h3>Loss Function</h3><h4>What is Focal Loss (in CenterNet)?</h4><p>In <strong>CenterNet</strong>, the model predicts a <strong>heatmap</strong> of size (H, W, C) where:</p><ul><li>H × W = spatial resolution of the heatmap</li><li>C = number of object classes<br> Each pixel in this heatmap represents the <strong>probability of that class&#39;s object center</strong> being at that location.</li></ul><p>Now, <strong>most of the heatmap is background (0s)</strong> and only a few pixels are object centers (1s). This causes <strong>class imbalance</strong>, and traditional losses like Binary Cross-Entropy (BCE) would be dominated by easy negatives.</p><p>To fix this, <strong>CenterNet uses a variant of Focal Loss</strong> that:</p><ul><li>Focuses more on hard examples (e.g., where the model is unsure about object centers)</li><li>Suppresses easy negatives (where the model confidently predicts 0)</li></ul><p>Let’s define:</p><ul><li>p = predicted probability at location (x, y) for a class (i.e., output of sigmoid)</li><li>y = ground truth value at that pixel (1 for object center, &lt;1 for nearby pixels, 0 for background)</li></ul><h4>The Focal Loss used in CenterNet is:</h4><p>For each pixel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*uWkmq_ZozOXsTExEfyHu2Q.png" /></figure><p>Where:</p><ul><li>p is the <strong>sigmoid output</strong> from the heatmap</li><li>y is the ground truth (1 at center, 0 elsewhere, or a Gaussian if smoothed)</li><li>α (alpha) = <strong>2</strong>, to down-weight easy examples</li><li>β (beta) = <strong>4</strong>, to suppress large gradients from non-center locations</li></ul><h4>🔴 At Object Centers (y = 1):</h4><ul><li>We want p → 1</li><li>The loss is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*AAgBcwcRvyr8e8slIWQ5Tw.png" /></figure><ul><li>If p is low (hard example), the loss is <strong>high</strong></li><li>If p is close to 1 (correct), the loss becomes <strong>very small</strong></li></ul><h4>⚫ At Background Pixels (y = 0 or near 0 from Gaussian tail):</h4><ul><li>We want p → 0</li><li>The loss is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*uVPVJr5tyxRiKbrQy9qcvA.png" /></figure><ul><li>If p is already small, it’s <strong>down-weighted</strong></li><li>If p is mistakenly high, loss is <strong>strong</strong>, encouraging correction</li></ul><h4>🎯 Why This Variant is Special in CenterNet:</h4><p>It’s a <strong>modified focal loss for dense heatmap regression</strong>. <br>Unlike RetinaNet’s focal loss (for classification), this version:</p><ul><li>Treats <strong>every pixel</strong> as a binary classification problem (object center or not)</li><li>Uses the <strong>Gaussian-shaped ground truth</strong> (values between 0 and 1) to softly supervise nearby pixels</li><li>This makes it suitable for keypoint-style object detection, where center prediction is critical.</li></ul><p>Let’s say we’re detecting a <strong>dog</strong>, centered at (50, 30) in a 56×56 heatmap.<br>The ground truth y around that center might look like:</p><pre>[0.01, 0.04, 0.1, 0.2, 0.1, 0.04, 0.01]<br>[0.04, 0.15, 0.3, 0.6, 0.3, 0.15, 0.04]<br>[0.1 , 0.3 , 0.6, 1.0, 0.6, 0.3 , 0.1 ]<br>[ ... and so on ... ]</pre><ul><li>Focal loss penalizes the network more if it misses this peak.</li><li>It also <strong>softly supervises</strong> the surrounding areas with small loss weights.</li></ul><pre>def masked_l1_loss(y_true_with_mask, y_pred):<br>    &quot;&quot;&quot;<br>    Calculates a masked L1 loss for the size and offset heads.<br>    <br>    Args:<br>        y_true_with_mask (Tensor): Ground truth tensor of shape (batch, H, W, 3).<br>                                   The first 2 channels are the targets (w,h or dx,dy).<br>                                   The 3rd channel is the binary mask.<br>        y_pred (Tensor): The model&#39;s prediction of shape (batch, H, W, 2).<br>                         <br>    Returns:<br>        Tensor: A scalar loss value.<br>    &quot;&quot;&quot;<br>    # 1. Unpack the ground truth targets and the mask<br>    y_true = y_true_with_mask[..., :2]  # Shape: (batch, 56, 56, 2)<br>    mask   = y_true_with_mask[..., 2]   # Shape: (batch, 56, 56)<br><br>    # 2. Calculate the L1 error for all pixels<br>    absolute_error = tf.abs(y_true - y_pred)<br><br>    # 3. Apply the mask to ignore pixels that are not object centers.<br>    # We expand the mask&#39;s dimensions to match the error tensor for multiplication<br>    masked_error = absolute_error * tf.expand_dims(mask, axis=-1)<br><br>    # 4. Sum the error and normalize by the number of objects in the batch.<br>    # Add a small epsilon to prevent division by zero if a batch has no objects.<br>    num_objects = tf.reduce_sum(mask) + 1e-8<br>    total_loss = tf.reduce_sum(masked_error) / num_objects<br>    return total_loss<br><br>def focal_loss(y_true, y_pred,<br>                         alpha=2.0,  # focusing exponent<br>                         beta =4.0,  # extra negative exponent<br>                         eps  =1e-4):<br>    &quot;&quot;&quot;<br>    CenterNet-style focal loss for heat-map heads.<br><br>    Args<br>    ----<br>    y_true: (B,H,W,C) float32, Gaussian bumps (centre == 1).<br>    y_pred: (B,H,W,C) float32, after sigmoid.<br>    alpha : float, focusing exponent (paper uses 2).<br>    beta  : float, exponent for negatives (paper uses 4).<br><br>    Returns<br>    -------<br>    scalar Tensor<br>    &quot;&quot;&quot;<br>    # Clip prediction for log stability<br>    y_pred = tf.clip_by_value(y_pred, eps, 1. - eps)<br><br>    pos_inds = tf.cast(tf.equal(y_true, 1.0), tf.float32)<br>    neg_inds = tf.cast(tf.less(y_true, 1.0), tf.float32)<br><br>    # Positive loss: -(1-ŷ)^α log(ŷ)<br>    pos_loss = - tf.pow(1. - y_pred, alpha) * tf.math.log(y_pred) * pos_inds<br><br>    # Negative loss: -(1-y)^β ŷ^α log(1-ŷ)<br>    neg_weight = tf.pow(1. - y_true, beta)<br>    neg_loss = - tf.pow(y_pred,   alpha) * tf.math.log(1. - y_pred) * neg_weight * neg_inds<br><br>    # Normalise by number of positive centres<br>    num_pos  = tf.reduce_sum(pos_inds)<br>    total_loss = tf.reduce_sum(pos_loss + neg_loss)<br>    return tf.math.divide_no_nan(total_loss, num_pos)</pre><h3>The Two Worlds: Positive vs. Negative :</h3><h4>Going more in deep in how this specific focal loss behaves</h4><p>This specific focal loss function sharply divides the world into two cases:</p><ol><li><strong>Positive Case (y_true == 1.0):</strong> The model is trained to predict 1. The loss is calculated using pos_loss.</li><li><strong>Negative Case (y_true &lt; 1.0):</strong> The model is trained to predict 0. The loss is calculated using neg_loss.</li></ol><blockquote>For <em>any</em> negative case, the ideal prediction that results in zero loss is y_pred = 0.</blockquote><blockquote>“If this is a negative location, but it’s very close to a positive one. I will apply low penalty for any mistakes made here.”</blockquote><h4>Example</h4><pre># Define a NumPy version of the focal loss<br>def focal_loss_np(y_true, y_pred, alpha=1.0, beta=4.0, eps=1e-4):<br>    # Clip predictions for stability<br>    y_pred = np.clip(y_pred, eps, 1. - eps)<br>    <br>    pos_inds = (y_true == 1.0).astype(np.float32)<br>    neg_inds = (y_true &lt; 1.0).astype(np.float32)<br>    <br>    # Positive loss: -(1-ŷ)^α log(ŷ)<br>    pos_loss = - np.power(1. - y_pred, alpha) * np.log(y_pred) * pos_inds<br>    <br>    # Negative loss: -(1-y)^β ŷ^α log(1-ŷ)<br>    neg_weight = np.power(1. - y_true, beta)<br>    neg_loss = - np.power(y_pred, alpha) * np.log(1. - y_pred) * neg_weight * neg_inds<br>    <br>    num_pos = pos_inds.sum()<br>    total_loss = (pos_loss + neg_loss).sum()<br>    return total_loss / num_pos if num_pos &gt; 0 else 0.0</pre><p><strong>Case 1 : prediction probability close to true value (low loss)</strong></p><pre># Create True example arrays with B=1, H=W=5, C=3<br>y_true = np.zeros((1, 5, 5, 3), dtype=np.float32)<br># Place one positive center in each channel<br>indices = [(0, 2, 2, 0), (0, 1, 1, 1), (0, 3, 3, 2)]<br>for idx in indices:<br>    y_true[idx] = 1<br><br><br># Create pred example arrays with B=1, H=W=5, C=3<br>y_pred = np.zeros((1, 5, 5, 3), dtype=np.float32)<br># Place one positive center in each channel<br>indices = [(0, 2, 2, 0), (0, 1, 1, 1), (0, 3, 3, 2)]<br>for idx in indices:<br>    y_pred[idx] = 0.8<br><br>--&gt; Focal Loss: 0.044628948 </pre><p><strong>Case 2 : False Positive (Hard Negative) prediction results in high loss</strong></p><pre># Create True example arrays with B=1, H=W=5, C=3<br>y_true = np.zeros((1, 5, 5, 3), dtype=np.float32)<br># Place one positive center in each channel<br>indices = [(0, 2, 2, 0), (0, 1, 1, 1), (0, 3, 3, 2)]<br>for idx in indices:<br>    y_true[idx] = 1<br><br># Create pred example arrays with B=1, H=W=5, C=3<br>y_pred = np.zeros((1, 5, 5, 3), dtype=np.float32)<br># Place one positive center in each channel<br>indices = [(0, 2, 2, 0), (0, 1, 1, 1), (0, 3, 3, 2)]<br>for idx in indices:<br>    y_pred[idx] = 0.5<br><br># Hard Negative<br>indices = [(0, 1, 2, 1)]<br>for idx in indices:<br>    y_pred[idx] = 0.6<br><br>--&gt; Focal Loss: 0.227</pre><p><strong>Case 3 : Introducing Soft negative results in lower loss than in Case-2</strong></p><pre># Create True example arrays with B=1, H=W=5, C=3<br>y_true = np.zeros((1, 5, 5, 3), dtype=np.float32)<br># Place one positive center in each channel<br>indices = [(0, 2, 2, 0), (0, 1, 1, 1), (0, 3, 3, 2)]<br>for idx in indices:<br>    y_true[idx] = 1<br><br># Soft Negative<br>indices = [(0, 1, 2, 1)]<br>for idx in indices:<br>    y_true[idx] = 0.8<br><br># Create pred example arrays with B=1, H=W=5, C=3<br>y_pred = np.zeros((1, 5, 5, 3), dtype=np.float32)<br># Place one positive center in each channel<br>indices = [(0, 2, 2, 0), (0, 1, 1, 1), (0, 3, 3, 2)]<br>for idx in indices:<br>    y_pred[idx] = 0.5<br><br># Predict high confidence at a soft-negative<br>indices = [(0, 1, 2, 1)]<br>for idx in indices:<br>    y_pred[idx] = 0.6<br><br>--&gt; Focal Loss: 0.0449</pre><p><strong>Case 4 : Soft Negative stays but hard negative prediction from Case-2 goes away results in same loss as in Case-1</strong></p><pre># Create True example arrays with B=1, H=W=5, C=3<br>y_true = np.zeros((1, 5, 5, 3), dtype=np.float32)<br># Place one positive center in each channel<br>indices = [(0, 2, 2, 0), (0, 1, 1, 1), (0, 3, 3, 2)]<br>for idx in indices:<br>    y_true[idx] = 1<br><br># Soft Negative<br>indices = [(0, 1, 2, 1)]<br>for idx in indices:<br>    y_true[idx] = 0.8<br><br># Create pred example arrays with B=1, H=W=5, C=3<br>y_pred = np.zeros((1, 5, 5, 3), dtype=np.float32)<br># Place one positive center in each channel<br>indices = [(0, 2, 2, 0), (0, 1, 1, 1), (0, 3, 3, 2)]<br>for idx in indices:<br>    y_pred[idx] = 0.5<br><br>--&gt; Focal Loss: 0.044628948</pre><p><strong>When y_true = 0.7, the location is treated as a “low importance negative.”</strong></p><ul><li>Making a big mistake there (predicting 0.7) is heavily forgiven, resulting in a low loss.</li><li>Making the <em>correct</em> prediction there (predicting 0) results in <strong>zero loss</strong>, which is even lower.</li></ul><h4>Conclusion</h4><p>The “soft targets” in this focal loss implementation are not treated as additional positive examples. Instead, they are treated as <strong>special negative examples whose importance in the loss calculation is massively reduced</strong>. This is a technique used in heatmap-based object detection to handle the areas immediately surrounding a ground-truth object center, where a small positive prediction from the model is acceptable or even desirable, and shouldn’t be penalized as a mistake.</p><h3>Training &amp; Saving Model</h3><pre># 1. Define the loss dictionary<br>loss_dict = {<br>    &#39;heatmap_out&#39;: focal_loss,<br>    &#39;size_out&#39;: masked_l1_loss,<br>    &#39;offset_out&#39;: masked_l1_loss<br>}<br><br># 2. Define the loss weights dictionary (standard values from the paper)<br>loss_weights_dict = {<br>    &#39;heatmap_out&#39;: 1.0,<br>    &#39;size_out&#39;: 0.1,<br>    &#39;offset_out&#39;: 1.0<br>}<br><br># 3. Compile the model<br>detector.compile(<br>    optimizer=tf.keras.optimizers.Adam(1e-4),<br>    loss=loss_dict,<br>    loss_weights=loss_weights_dict<br>)<br><br>num_samples = len(train_image) <br>batch_size = 32<br>steps_per_epoch = num_samples // batch_size <br><br>history = detector.fit(ds, epochs=70, steps_per_epoch=steps_per_epoch)</pre><pre>import tf2onnx<br>import tensorflow as tf<br><br>spec = (tf.TensorSpec((None, 224, 224, 3), tf.float32, name=&quot;input&quot;),)<br><br>onnx_model, _ = tf2onnx.convert.from_keras(<br>    detector,<br>    input_signature=spec,<br>    opset=13,  # or 17 depending on your deployment needs<br>    output_path=&quot;centernet_inference.onnx&quot;<br>)<br><br>detector.save(&#39;centernet_mobilenetv3S.keras&#39;)<br><br>detector.compile()  # resets training state (optimizer, loss, metrics)<br>detector.save(&quot;centernet_inference.keras&quot;, include_optimizer=False)</pre><h3>Inference (tf)</h3><pre>from keras.models import load_model<br><br>detector = load_model(<br>    &quot;centernet_inference.keras&quot;,<br>    custom_objects={&quot;FeatureExtractor&quot;: FeatureExtractor},<br>    compile=False<br>)</pre><h3>Inference (Onnx)</h3><pre>import cv2<br>import numpy as np<br>import onnxruntime as ort<br>from scipy.ndimage import maximum_filter<br>import matplotlib.pyplot as plt<br><br># Constants<br>INPUT_SIZE = 224<br>DOWNSAMPLING_RATIO = 4<br>LABELS = [<br>    &#39;aeroplane&#39;, &#39;bicycle&#39;, &#39;bird&#39;, &#39;boat&#39;, &#39;bottle&#39;, &#39;bus&#39;, &#39;car&#39;, &#39;cat&#39;, &#39;chair&#39;, &#39;cow&#39;,<br>    &#39;diningtable&#39;, &#39;dog&#39;, &#39;horse&#39;, &#39;motorbike&#39;, &#39;person&#39;, &#39;pottedplant&#39;, &#39;sheep&#39;, &#39;sofa&#39;, &#39;train&#39;, &#39;tvmonitor&#39;<br>]<br><br># Load ONNX model<br>session = ort.InferenceSession(&quot;centernet_inference.onnx&quot;, providers=[&#39;CPUExecutionProvider&#39;])<br>input_name = session.get_inputs()[0].name<br>print(&quot;Input name:&quot;, input_name)<br>print(&quot;Input shape:&quot;, session.get_inputs()[0].shape)<br><br># Preprocess image<br>def preprocess_img(img_path):<br>    image = cv2.imread(img_path)<br>    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>    image = cv2.resize(image, (INPUT_SIZE, INPUT_SIZE)).astype(np.float32)<br>    return image<br><br># Decode model outputs to bounding boxes<br>def decode_detections(heatmap, size_map, offset_map, threshold):<br>    pooled = maximum_filter(heatmap[0], size=3, mode=&#39;constant&#39;)<br>    peaks = (heatmap[0] == pooled) &amp; (heatmap[0] &gt; threshold)<br><br>    y_coords, x_coords, class_ids = np.where(peaks)<br>    scores = heatmap[0, y_coords, x_coords, class_ids]<br>    pred_sizes = size_map[0, y_coords, x_coords, :]<br>    pred_offsets = offset_map[0, y_coords, x_coords, :]<br><br>    boxes, decoded_scores, decoded_labels = [], [], []<br>    for i in range(len(scores)):<br>        px, py = x_coords[i], y_coords[i]<br>        w, h = pred_sizes[i]<br>        off_x, off_y = pred_offsets[i]<br><br>        center_x = (px + off_x) * DOWNSAMPLING_RATIO<br>        center_y = (py + off_y) * DOWNSAMPLING_RATIO<br><br>        x_min = center_x - w / 2<br>        y_min = center_y - h / 2<br>        x_max = center_x + w / 2<br>        y_max = center_y + h / 2<br><br>        boxes.append([x_min, y_min, x_max, y_max])<br>        decoded_scores.append(scores[i])<br>        decoded_labels.append(class_ids[i])<br><br>    return np.array(boxes), np.array(decoded_scores), np.array(decoded_labels)<br><br>def run_inference_and_display(image_path, session, input_name, LABELS, preprocess_img, decode_detections, threshold=0.5):<br>    # Preprocess input<br>    image = preprocess_img(image_path)<br>    image_tensor = np.expand_dims(image, axis=0)<br>    <br>    # Run inference<br>    predictions = session.run(None, {input_name: image_tensor})<br>    pred_heatmap, pred_offset, pred_size = predictions<br><br>    # Prepare original image for drawing<br>    original_image = image.astype(&#39;uint8&#39;)<br><br>    # Decode outputs<br>    boxes, scores, labels = decode_detections(pred_heatmap, pred_size, pred_offset, threshold)<br><br>    # Draw bounding boxes and labels<br>    for i in range(len(boxes)):<br>        x_min, y_min, x_max, y_max = boxes[i].astype(int)<br>        score = scores[i]<br>        label_name = LABELS[int(labels[i])]<br>        text = f&quot;{label_name}: {score:.2f}&quot;<br><br>        # Draw bounding box<br>        cv2.rectangle(original_image, (x_min, y_min), (x_max, y_max), (0, 255, 0), 1)<br><br>        # Text styling<br>        font = cv2.FONT_HERSHEY_SIMPLEX<br>        font_scale = 0.3<br>        thickness = 1<br>        (text_w, text_h), _ = cv2.getTextSize(text, font, font_scale, thickness)<br>        text_x, text_y = x_min, y_min - text_h + 4<br><br>        # Background for text<br>        cv2.rectangle(original_image,<br>                      (text_x - 1, text_y - text_h - 2),<br>                      (text_x + text_w + 1, text_y + 2),<br>                      (0, 0, 0), -1)<br><br>        # Draw text<br>        cv2.putText(original_image, text, (text_x, text_y),<br>                    font, font_scale, (0, 255, 0), thickness, cv2.LINE_AA)<br><br>    # Show image<br>    plt.imshow(original_image)<br>    plt.axis(&#39;off&#39;)<br>    plt.show()<br><br>run_inference_and_display(<br>    image_path=&#39;&#39;,<br>    session=session,<br>    input_name=input_name,<br>    LABELS=LABELS,<br>    preprocess_img=preprocess_img,<br>    decode_detections=decode_detections,<br>    threshold=0.5<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*X5tkww6vxNvexlND1JhBdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*9UoyLFSQWDfobZy5PiBuTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*-UjJDClDb4eyIQ7hRxvODw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*xufIRxgiW71PrDYFLMOr5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Y7ds9kDwb2MvMk-F1Q5Upw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*GroQ59TssJmUjeqOKs55-g.png" /></figure><p>The above prediction results are on PASCAL VOC dataset. It is clear model is working and our theory is sound. <br>Below are some test cases of images i took from internet and shot myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*yjl7G_sA61qG2_BGjCcJjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*beHcDMj4jDNdbWa0GIPBEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*ZKkIn7cMsBrDi11KgNEfSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*oIWZWvh2Q5ScCWGZhG0obg.png" /></figure><p>Upon reviewing the real-world test cases, it’s evident that the model performance is very average — likely due to limited diversity of the VOC dataset.</p><p>To address this, we can :</p><ol><li>make the backbone trainable with a low learning rate (e.g., 1e-5)</li><li>switch to a dataset that includes a broader range of scenarios and lighting conditions, such as COCO or Open Images</li><li>Increase image resolution to 512 or 640 (YOLO)</li><li>Switch to a better pre-trained backbone</li></ol><p>If our goal is to train the model on a specific class — such as human beings for tracking and analytics — we can reduce the model size and selectively use images that contain the desired class. This targeted approach results in a win-win: a more lightweight model with improved accuracy.</p><p>Until then, happy learning! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6170eb815c07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training Segformer from scratch | Semantic segmentation | Tensorflow]]></title>
            <link>https://medium.com/@saptarshimt/training-segformer-from-scratch-semantic-segmentation-tensorflow-09600f575455?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/09600f575455</guid>
            <category><![CDATA[segformer]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[semantic-segmentation]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 15:49:08 GMT</pubDate>
            <atom:updated>2025-07-10T07:52:24.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YXc1Sb3BYDvMjid4.png" /><figcaption>Source : <a href="https://github.com/ACSEkevin/An-Overview-of-Segformer-and-Details-Description">https://github.com/ACSEkevin/An-Overview-of-Segformer-and-Details-Description</a></figcaption></figure><h4>Overlap Patch Embedding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*qbrjrOO2gDNO1gAiH_4Dvg.png" /><figcaption>Normal ViT patch embedding vs Segformer Overlap pathc embedding</figcaption></figure><p>Overlapping patches are extracted using a <strong>Conv2D layer</strong> with:</p><ul><li>Overlapping patches (via stride &lt; kernel size) ensure <strong>neighboring pixels</strong> influence <strong>multiple patches</strong>, improving local spatial understanding.</li><li>This creates patches that <strong>share pixels</strong>, ensuring continuity.</li><li>The convolutional embedding also implicitly learns <strong>positional encoding</strong></li><li>Overlap results in <strong>less aggressive downsampling</strong> → retains more <strong>spatial and semantic information</strong> from the original image.</li></ul><pre>class OverlapPatchEmbeddings(layers.Layer):<br>    &quot;&quot;&quot;<br>    Layer that creates overlapping patch embeddings from input images using Conv2D.<br><br>    Args:<br>        patch_size (int): Size of the convolution kernel. Determines patch size.<br>        stride (int): Stride for convolution. Controls patch overlap.<br>        embedding_dim (int): Number of output channels for embedding.<br>        name (str): Optional name for the layer.<br>    &quot;&quot;&quot;<br>    def __init__(self, patch_size=7, stride=4, embedding_dim=16, name=None, **kwargs):<br>        super().__init__(name=name, **kwargs)<br>        self.conv = layers.Conv2D(<br>            filters=embedding_dim,<br>            kernel_size=patch_size,<br>            strides=stride,<br>            padding=&quot;same&quot;,<br>            name=&quot;patch_embed_conv&quot;<br>        )<br>        self.norm = layers.LayerNormalization(epsilon=1e-5)<br><br>    def call(self, inputs):<br>        &quot;&quot;&quot;<br>        Apply convolution and layer normalization to generate patch embeddings.<br><br>        Args:<br>            inputs (Tensor): Input tensor of shape (batch_size, H, W, C).<br><br>        Returns:<br>            Tensor: Patch embeddings of shape (batch_size, H/stride, W/stride, embedding_dim).<br>        &quot;&quot;&quot;<br>        x = self.conv(inputs)<br>        x = self.norm(x)<br>        return x</pre><h4>Efficient Self-Attention</h4><p>Efficient attention uses:</p><ul><li>Downsamples key &amp; value matrices using <strong>Conv2D</strong></li><li>Reduces spatial dimension <strong>before attention calculation</strong></li><li>Attention becomes: Q × (K↓ × V↓) → Faster &amp; less memory</li></ul><pre>class EfficientSelfAttention(layers.Layer):<br>    &quot;&quot;&quot;<br>    Efficient Self-Attention with optional spatial reduction.<br><br>    Args:<br>        num_heads (int): Number of attention heads.<br>        embedding_dim (int): Total embedding dimension (must be divisible by num_heads).<br>        sr_ratio (int): Spatial reduction ratio for K/V (sr_ratio &gt; 1 enables reduction).<br>        name (str): Optional name for the layer.<br>    &quot;&quot;&quot;<br>    def __init__(self, num_heads, embedding_dim, sr_ratio=1, name=None, **kwargs):<br>        super().__init__(name=name, **kwargs)<br>        <br>        if embedding_dim % num_heads != 0:<br>            raise ValueError(&quot;Embedding dimension must be divisible by number of heads.&quot;)<br>        <br>        self.num_heads = num_heads<br>        self.embedding_dim = embedding_dim<br>        self.head_dim = embedding_dim // num_heads<br>        self.sr_ratio = sr_ratio<br><br>        # Projections for query, key, value<br>        self.q_proj = layers.Dense(embedding_dim, name=&quot;q_proj&quot;)<br>        self.k_proj = layers.Dense(embedding_dim, name=&quot;k_proj&quot;)<br>        self.v_proj = layers.Dense(embedding_dim, name=&quot;v_proj&quot;)<br>        self.out_proj = layers.Dense(embedding_dim, name=&quot;out_proj&quot;)<br><br>        self.attn_drop = layers.Dropout(0.1)<br>        self.proj_drop = layers.Dropout(0.1)<br><br>        # Sequence reduction<br>        if sr_ratio &gt; 1:<br>            self.sr_conv = layers.Conv2D(<br>                filters=embedding_dim,<br>                kernel_size=sr_ratio,<br>                strides=sr_ratio,<br>                padding=&quot;same&quot;,<br>                name=&quot;sr_conv&quot;<br>            )<br>            self.sr_norm = layers.LayerNormalization(epsilon=1e-5, name=&quot;sr_norm&quot;)<br><br>    def call(self, x, H, W):<br>        &quot;&quot;&quot;<br>        Args:<br>            x (Tensor): Input tensor of shape (B, N=H*W, C).<br>            H (int): Height of the original spatial feature map.<br>            W (int): Width of the original spatial feature map.<br><br>        Returns:<br>            Tensor: Output of shape (B, N, C) after self-attention.<br>        &quot;&quot;&quot;<br>        B, N = tf.shape(x)[0], tf.shape(x)[1]<br><br>        # === 1. Query projection ===<br>        q = self.q_proj(x)                                      # (B, N, C)<br>        q = tf.reshape(q, [B, N, self.num_heads, self.head_dim])<br>        q = tf.transpose(q, [0, 2, 1, 3])                        # (B, heads, N, head_dim)<br><br>        # === 2. Spatial Reduction (for K/V) ===<br>        if self.sr_ratio &gt; 1:<br>            x_2d = tf.reshape(x, [B, H, W, self.embedding_dim])        # (B, H, W, C)<br>            x_reduced = self.sr_conv(x_2d)                             # (B, H//sr, W//sr, C)<br>            x_reduced = tf.reshape(x_reduced, [B, -1, self.embedding_dim])<br>            kv_input = self.sr_norm(x_reduced)                         # (B, N_kv, C)<br>        else:<br>            kv_input = x  # No spatial reduction<br><br>        # === 3. Key and Value projections ===<br>        k = self.k_proj(kv_input)<br>        v = self.v_proj(kv_input)<br><br>        k = tf.reshape(k, [B, -1, self.num_heads, self.head_dim])<br>        k = tf.transpose(k, [0, 2, 3, 1])  # (B, heads, head_dim, N_kv)<br><br>        v = tf.reshape(v, [B, -1, self.num_heads, self.head_dim])<br>        v = tf.transpose(v, [0, 2, 1, 3])  # (B, heads, N_kv, head_dim)<br><br>        # === 4. Scaled Dot-Product Attention ===<br>        scale = tf.math.sqrt(tf.cast(self.head_dim, tf.float32))<br>        attn_scores = tf.matmul(q, k) / scale                     # (B, heads, N, N_kv)<br>        attn_weights = tf.nn.softmax(attn_scores, axis=-1)<br>        attn_weights = self.attn_drop(attn_weights)<br><br>        attn_output = tf.matmul(attn_weights, v)                 # (B, heads, N, head_dim)<br><br>        # === 5. Recombine heads and final projection ===<br>        attn_output = tf.transpose(attn_output, [0, 2, 1, 3])    # (B, N, heads, head_dim)<br>        attn_output = tf.reshape(attn_output, [B, N, self.embedding_dim])<br>        attn_output = self.out_proj(attn_output)<br>        return self.proj_drop(attn_output)</pre><h4>MixFFN</h4><p>Linear -&gt; Depthwise Conv -&gt; GELU -&gt; Linear</p><ul><li><strong>Depthwise convolution</strong> injects <strong>spatial inductive bias</strong></li><li>Acts like a local filter on the feature map</li><li>Enables FFN to <strong>capture spatial patterns</strong> within each channel</li><li>Enhances <strong>local feature extraction</strong> within transformer blocks improving <strong>segmentation boundary accuracy</strong></li><li>Combines <strong>global (attention)</strong> + <strong>local (MixFFN)</strong> context modeling</li></ul><pre>class MixFFN(layers.Layer):<br>    &quot;&quot;&quot;<br>    Mix-FeedForward Network (Mix-FFN) layer with spatial mixing using depthwise convolution.<br><br>    Args:<br>        embedding_dim (int): Input and output embedding dimension.<br>        expansion_factor (int): Multiplier to expand embedding dimension in the intermediate layer.<br>        name (str): Optional name for the layer.<br>    &quot;&quot;&quot;<br>    def __init__(self, embedding_dim, expansion_factor=4, name=None, **kwargs):<br>        super().__init__(name=name, **kwargs)<br>        self.hidden_dim = embedding_dim * expansion_factor<br><br>        # First MLP layer (expansion)<br>        self.mlp1 = layers.Dense(self.hidden_dim, name=&quot;mlp1&quot;)<br><br>        # Depthwise separable convolution for positional encoding effect<br>        self.conv = layers.DepthwiseConv2D(kernel_size=3,strides=1,padding=&quot;same&quot;,name=&quot;dw_conv&quot;)<br><br>        # Activation and regularization<br>        self.act = layers.Activation(&quot;gelu&quot;)<br>        self.mlp2 = layers.Dense(embedding_dim, name=&quot;mlp2&quot;)<br>        self.drop = layers.Dropout(0.1)<br><br>    def call(self, x, H, W):<br>        &quot;&quot;&quot;<br>        Forward pass of MixFFN.<br><br>        Args:<br>            x (Tensor): Input tensor of shape (B, N, C), where N = H × W.<br>            H (int): Height of spatial grid.<br>            W (int): Width of spatial grid.<br><br>        Returns:<br>            Tensor: Output tensor of shape (B, N, C).<br>        &quot;&quot;&quot;<br>        B, N, C = tf.unstack(tf.shape(x))<br><br>        # 1. First linear layer<br>        x_proj = self.mlp1(x)  # (B, N, hidden_dim)<br><br>        # 2. Reshape to spatial form and apply 3x3 conv<br>        x_spatial = tf.reshape(x_proj, [B, H, W, self.hidden_dim])<br>        x_conv = self.conv(x_spatial)<br><br>        # 3. Flatten spatial output back to sequence<br>        x_flat = tf.reshape(x_conv, [B, N, self.hidden_dim])<br><br>        # 4. Activation → second linear layer → dropout<br>        x_out = self.act(x_flat)<br>        x_out = self.mlp2(x_out)<br>        return self.drop(x_out)</pre><h4>Transformer Block</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dusvBalIgnEekVUq.png" /></figure><pre>class TransformerBlock(layers.Layer):<br>    &quot;&quot;&quot;<br>    Transformer block consisting of:<br>    1. LayerNorm → Efficient Self-Attention → Residual<br>    2. LayerNorm → Mix-FeedForward Network → Residual<br><br>    Args:<br>        num_heads (int): Number of attention heads.<br>        embedding_dim (int): Embedding dimension.<br>        sr_ratio (int): Spatial reduction ratio for attention.<br>        expansion_factor (int): Expansion factor for FFN.<br>        name (str): Optional name for the block.<br>    &quot;&quot;&quot;<br>    def __init__(self, num_heads, embedding_dim, sr_ratio, expansion_factor, name=None, **kwargs):<br>        super().__init__(name=name, **kwargs)<br>        <br>        # LayerNorm + Attention<br>        self.norm1 = layers.LayerNormalization(epsilon=1e-5, name=&quot;norm1&quot;)<br>        self.attn = EfficientSelfAttention(<br>            num_heads=num_heads,<br>            embedding_dim=embedding_dim,<br>            sr_ratio=sr_ratio,<br>            name=&quot;attention&quot;<br>        )<br><br>        # LayerNorm + FFN<br>        self.norm2 = layers.LayerNormalization(epsilon=1e-5, name=&quot;norm2&quot;)<br>        self.ffn = MixFFN(<br>            embedding_dim=embedding_dim,<br>            expansion_factor=expansion_factor,<br>            name=&quot;ffn&quot;<br>        )<br><br>    def call(self, x, H, W):<br>        &quot;&quot;&quot;<br>        Args:<br>            x (Tensor): Input tensor of shape (B, N, C).<br>            H (int): Height of spatial feature map.<br>            W (int): Width of spatial feature map.<br><br>        Returns:<br>            Tensor: Output tensor of shape (B, N, C).<br>        &quot;&quot;&quot;<br>        # === Attention Block ===<br>        x_attn = self.norm1(x)<br>        x = x + self.attn(x_attn, H, W)<br><br>        # === FFN Block ===<br>        x_ffn = self.norm2(x)<br>        x = x + self.ffn(x_ffn, H, W)<br><br>        return x</pre><h4>Final MitEncoder (putting above all together)</h4><pre>class MiTEncoder(layers.Layer):<br>    &quot;&quot;&quot;<br>    MiT (Mix Transformer) Encoder with 4 stages.<br><br>    Each stage:<br>    - Applies overlap patch embedding (with downsampling)<br>    - Processes with 2 Transformer blocks<br>    - Stores output feature maps for decoder<br>    &quot;&quot;&quot;<br>    def __init__(self, embedding_dims, num_heads, sr_ratios, expansion_factors, name=&quot;mit_encoder&quot;, **kwargs):<br>        super().__init__(name=name, **kwargs)<br><br>        # Stage 1<br>        self.overlap0 = OverlapPatchEmbeddings(patch_size=7, stride=4, embedding_dim=embedding_dims[0], name=&quot;patch_embed_1&quot;)<br>        self.block0_1 = TransformerBlock(num_heads[0], embedding_dims[0], sr_ratios[0], expansion_factors[0], name=&quot;block1_1&quot;)<br>        self.block0_2 = TransformerBlock(num_heads[0], embedding_dims[0], sr_ratios[0], expansion_factors[0], name=&quot;block1_2&quot;)<br>        self.norm0 = layers.LayerNormalization(epsilon=1e-5, name=&quot;norm1&quot;)<br><br>        # Stage 2<br>        self.overlap1 = OverlapPatchEmbeddings(patch_size=3, stride=2, embedding_dim=embedding_dims[1], name=&quot;patch_embed_2&quot;)<br>        self.block1_1 = TransformerBlock(num_heads[1], embedding_dims[1], sr_ratios[1], expansion_factors[1], name=&quot;block2_1&quot;)<br>        self.block1_2 = TransformerBlock(num_heads[1], embedding_dims[1], sr_ratios[1], expansion_factors[1], name=&quot;block2_2&quot;)<br>        self.norm1 = layers.LayerNormalization(epsilon=1e-5, name=&quot;norm2&quot;)<br><br>        # Stage 3<br>        self.overlap2 = OverlapPatchEmbeddings(patch_size=3, stride=2, embedding_dim=embedding_dims[2], name=&quot;patch_embed_3&quot;)<br>        self.block2_1 = TransformerBlock(num_heads[2], embedding_dims[2], sr_ratios[2], expansion_factors[2], name=&quot;block3_1&quot;)<br>        self.block2_2 = TransformerBlock(num_heads[2], embedding_dims[2], sr_ratios[2], expansion_factors[2], name=&quot;block3_2&quot;)<br>        self.norm2 = layers.LayerNormalization(epsilon=1e-5, name=&quot;norm3&quot;)<br><br>        # Stage 4<br>        self.overlap3 = OverlapPatchEmbeddings(patch_size=3, stride=2, embedding_dim=embedding_dims[3], name=&quot;patch_embed_4&quot;)<br>        self.block3_1 = TransformerBlock(num_heads[3], embedding_dims[3], sr_ratios[3], expansion_factors[3], name=&quot;block4_1&quot;)<br>        self.block3_2 = TransformerBlock(num_heads[3], embedding_dims[3], sr_ratios[3], expansion_factors[3], name=&quot;block4_2&quot;)<br>        self.norm3 = layers.LayerNormalization(epsilon=1e-5, name=&quot;norm4&quot;)<br><br>    def call(self, x):<br>        features = []<br><br>        # --- Stage 1 ---<br>        x = self.overlap0(x)                            # (B, H1, W1, C1)<br>        B, H, W, C = tf.shape(x)[0], tf.shape(x)[1], tf.shape(x)[2], tf.shape(x)[3]<br>        x = tf.reshape(x, [B, H * W, C])<br>        x = self.block0_1(x, H, W)<br>        x = self.block0_2(x, H, W)<br>        x = self.norm0(x)<br>        x = tf.reshape(x, [B, H, W, C])<br>        features.append(x)<br><br>        # --- Stage 2 ---<br>        x = self.overlap1(x)<br>        B, H, W, C = tf.shape(x)[0], tf.shape(x)[1], tf.shape(x)[2], tf.shape(x)[3]<br>        x = tf.reshape(x, [B, H * W, C])<br>        x = self.block1_1(x, H, W)<br>        x = self.block1_2(x, H, W)<br>        x = self.norm1(x)<br>        x = tf.reshape(x, [B, H, W, C])<br>        features.append(x)<br><br>        # --- Stage 3 ---<br>        x = self.overlap2(x)<br>        B, H, W, C = tf.shape(x)[0], tf.shape(x)[1], tf.shape(x)[2], tf.shape(x)[3]<br>        x = tf.reshape(x, [B, H * W, C])<br>        x = self.block2_1(x, H, W)<br>        x = self.block2_2(x, H, W)<br>        x = self.norm2(x)<br>        x = tf.reshape(x, [B, H, W, C])<br>        features.append(x)<br><br>        # --- Stage 4 ---<br>        x = self.overlap3(x)<br>        B, H, W, C = tf.shape(x)[0], tf.shape(x)[1], tf.shape(x)[2], tf.shape(x)[3]<br>        x = tf.reshape(x, [B, H * W, C])<br>        x = self.block3_1(x, H, W)<br>        x = self.block3_2(x, H, W)<br>        x = self.norm3(x)<br>        x = tf.reshape(x, [B, H, W, C])<br>        features.append(x)<br><br>        return features  # List of 4 tensors: [(B, H1, W1, C1), ..., (B, H4, W4, C4)]</pre><h4>Decoder Block</h4><p>The decoder takes <strong>multi-scale features</strong> from the 4 encoder stages and fuses them using a <strong>lightweight MLP-based architecture</strong> for final per-pixel segmentation.</p><ol><li>Each encoder feature (from 4 stages) is passed through:</li></ol><ul><li><strong>MLP projection</strong> → Unifies channel dimensions</li><li><strong>Bilinear Upsampling</strong> → Brings all feature maps to the same spatial size</li></ul><p>2. The upsampled features are:</p><ul><li><strong>Concatenated along channel axis</strong></li><li>Fused via another <strong>MLP + Conv + BN</strong></li></ul><p>3. Final head: <strong>1×1 Conv</strong> → Outputs class logits per pixel</p><pre>class MLPDecoder(layers.Layer):<br>    &quot;&quot;&quot;<br>    MLP-based decoder for SegFormer.<br>    - Unifies encoder feature dimensions<br>    - Upsamples all to the same scale (H/4 × W/4)<br>    - Concatenates and fuses them<br>    - Produces segmentation mask<br>    &quot;&quot;&quot;<br>    def __init__(self, embedding_dim, num_classes, name=&quot;mlp_decoder&quot;, **kwargs):<br>        super().__init__(name=name, **kwargs)<br>        self.embedding_dim = embedding_dim<br>        self.num_classes = num_classes<br><br>        # 1. MLPs to unify channel dimensions from encoder stages<br>        self.unify_mlps = [<br>            layers.Conv2D(embedding_dim, kernel_size=1, padding=&quot;same&quot;, name=f&quot;unify_mlp_{i+1}&quot;)<br>            for i in range(4)<br>        ]<br><br>        # 2. Fusion block: concatenate + project back to embedding_dim<br>        self.fusion_mlp = layers.Conv2D(<br>            filters=embedding_dim, kernel_size=1, use_bias=False, padding=&quot;same&quot;, name=&quot;fusion_mlp&quot;<br>        )<br>        self.norm = layers.BatchNormalization()<br>        self.act = layers.Activation(&quot;relu&quot;)<br>        self.dropout = layers.Dropout(0.1)<br><br>        # 3. Final classification head<br>        self.classify_mlp = layers.Conv2D(<br>            filters=num_classes, kernel_size=1, padding=&quot;same&quot;, name=&quot;classify_mlp&quot;<br>        )<br>        self.softmax = layers.Softmax(axis=-1)<br><br>    def call(self, encoder_features):<br>        &quot;&quot;&quot;<br>        Args:<br>            encoder_features (List[Tensor]): 4-stage features from encoder.<br>                Shapes: [(B, H/4, W/4, C1), ..., (B, H/32, W/32, C4)]<br><br>        Returns:<br>            Tensor: Segmentation map of shape (B, H, W, num_classes)<br>        &quot;&quot;&quot;<br>        target_shape = tf.shape(encoder_features[0])[1:3]  # Use H/4, W/4 as base<br><br>        unified_and_resized = []<br>        for i in range(4):<br>            x = self.unify_mlps[i](encoder_features[i])  # (B, h_i, w_i, embed_dim)<br>            x = tf.image.resize(x, size=target_shape, method=&quot;bilinear&quot;)  # Align scale to (H/4, W/4)<br>            unified_and_resized.append(x)<br><br>        # Fuse features<br>        fused = layers.Concatenate(axis=-1)(unified_and_resized)  # (B, H/4, W/4, 4*embed_dim)<br>        fused = self.fusion_mlp(fused)<br>        fused = self.norm(fused)<br>        fused = self.act(fused)<br>        fused = self.dropout(fused)<br><br>        # Predict segmentation mask (still at H/4, W/4)<br>        mask = self.classify_mlp(fused)<br><br>        # Upsample to input resolution<br>        output_size = target_shape * 4<br>        mask = tf.image.resize(mask, size=output_size, method=&quot;bilinear&quot;)<br>        return self.softmax(mask)<br>    <br>def build_segformer(<br>    input_shape=(224, 224, 3),<br>    num_classes=19,<br>    embedding_dims=[32, 64, 128, 256],<br>    num_heads=[1, 2, 4, 8],<br>    sr_ratios=[8, 4, 2, 1],<br>    expansion_factors=[4, 4, 4, 4],<br>    decoder_embedding_dim=256<br>):<br>    &quot;&quot;&quot;<br>    Build SegFormer architecture with MiT encoder and MLP decoder.<br><br>    Returns:<br>        tf.keras.Model: Keras model instance.<br>    &quot;&quot;&quot;<br>    inputs = layers.Input(shape=input_shape)<br><br>    # Encoder: MiT<br>    encoder = MiTEncoder(<br>        embedding_dims=embedding_dims,<br>        num_heads=num_heads,<br>        sr_ratios=sr_ratios,<br>        expansion_factors=expansion_factors,<br>    )<br><br>    # Decoder: MLP<br>    decoder = MLPDecoder(<br>        embedding_dim=decoder_embedding_dim,<br>        num_classes=num_classes<br>    )<br><br>    # Forward pass<br>    features = encoder(inputs)           # List of 4 (B, H_i, W_i, C_i)<br>    segmentation_mask = decoder(features)<br><br>    return Model(inputs=inputs, outputs=segmentation_mask, name=&quot;SegFormer&quot;)</pre><pre>seg_b0 = build_segformer(<br>    input_shape=(256, 256, 3),<br>    num_classes=N_CLASSES,<br>    embedding_dims=[32, 64, 128, 256],<br>    num_heads=[1, 2, 4, 8],<br>    sr_ratios=[8, 4, 2, 1],<br>    expansion_factors=[4, 4, 4, 4],<br>    decoder_embedding_dim=256<br>)<br><br>seg_b0.summary()<br><br>┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓<br>┃ Layer (type)        ┃ Output Shape      ┃    Param # ┃ Connected to      ┃<br>┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━┩<br>│ input_layer         │ (None, 256, 256,  │          0 │ -                 │<br>│ (InputLayer)        │ 3)                │            │                   │<br>├─────────────────────┼───────────────────┼────────────┼───────────────────┤<br>│ mit_encoder         │ [(None, 64, 64,   │  2,928,576 │ input_layer[0][0] │<br>│ (MiTEncoder)        │ 32), (None, 32,   │            │                   │<br>│                     │ 32, 64), (None,   │            │                   │<br>│                     │ 16, 16, 128),     │            │                   │<br>│                     │ (None, 8, 8,      │            │                   │<br>│                     │ 256)]             │            │                   │<br>├─────────────────────┼───────────────────┼────────────┼───────────────────┤<br>│ mlp_decoder         │ (None, None,      │    390,413 │ mit_encoder[0][0… │<br>│ (MLPDecoder)        │ None, 13)         │            │ mit_encoder[0][1… │<br>│                     │                   │            │ mit_encoder[0][2… │<br>│                     │                   │            │ mit_encoder[0][3] │<br>└─────────────────────┴───────────────────┴────────────┴───────────────────┘<br><br> Total params: 3,318,989 (12.66 MB)</pre><h4>Dataset creation (City Scapes)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OGh7bxUYuTaJ6-7v" /></figure><pre>EPOCHS=20<br>BATCH_SIZE=32<br>HEIGHT=256<br>WIDTH=256<br>CHANNELS=3<br>N_CLASSES=13<br>AUTO = tf.data.AUTOTUNE<br><br>def process_path(file_path):<br>    image = tf.io.read_file(file_path)<br>    image = tf.image.decode_jpeg(image, channels=3)<br>    image = tf.image.convert_image_dtype(image, tf.float32)<br>    image = tf.image.resize(image, [HEIGHT, WIDTH * 2])<br><br>    # Split into image and mask<br>    image_part = image[:, :WIDTH, :]<br>    mask_part = image[:, WIDTH:, 0] * 255.0  # scale if needed<br><br>    # Binning mask<br>    bins = tf.constant([20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240], dtype=tf.float32)<br>    mask_binned = tf.reduce_sum(tf.cast(tf.greater(mask_part[..., tf.newaxis], bins), tf.int32), axis=-1)<br><br>    return image_part, mask_binned  <br><br>def get_dataset(file_list, batch_size=BATCH_SIZE, shuffle=True):<br>    dataset = tf.data.Dataset.from_tensor_slices(file_list)<br>    if shuffle:<br>        dataset = dataset.shuffle(buffer_size=len(file_list))<br>    dataset = dataset.map(process_path, num_parallel_calls=AUTO)<br>    dataset = dataset.batch(batch_size)<br>    dataset = dataset.prefetch(AUTO)<br>    return dataset<br><br>train_filenames = glob.glob(&quot;/Users/saptarshimallikthakur/Desktop/cityscapes_data/train/*.jpg&quot;)<br>val_filenames = glob.glob(&quot;/Users/saptarshimallikthakur/Desktop/cityscapes_data/val/*.jpg&quot;)<br><br>train_dataset = get_dataset(train_filenames)<br>val_dataset = get_dataset(val_filenames, shuffle=False)</pre><pre># Get one batch from tf.data.Dataset<br>for imgs, segs in train_dataset.take(1):<br>    imgs_np = imgs.numpy()<br>    segs_np = segs.numpy()<br>    break<br><br>imgs.shape, segs.shape <br><br># (TensorShape([32, 256, 256, 3]), TensorShape([32, 256, 256]))</pre><pre>def give_color_to_seg_img(seg, n_classes=N_CLASSES):<br>    <br>    seg_img = np.zeros( (seg.shape[0],seg.shape[1],3) ).astype(&#39;float&#39;)<br>    colors = sns.color_palette(&quot;hls&quot;, n_classes)<br>    <br>    for c in range(n_classes):<br>        segc = (seg == c)<br>        seg_img[:,:,0] += (segc*( colors[c][0] ))<br>        seg_img[:,:,1] += (segc*( colors[c][1] ))<br>        seg_img[:,:,2] += (segc*( colors[c][2] ))<br><br>    return(seg_img)<br><br># Visualize the first item in batch<br>image = imgs_np[0]                             # shape: (256, 256, 3)<br>mask = give_color_to_seg_img(segs_np[0])<br>masked_image = image * 0.5 + mask * 0.5        # overlay<br><br># Plot<br>fig, axs = plt.subplots(1, 3, figsize=(20, 20))<br>axs[0].imshow(image)<br>axs[0].set_title(&#39;Original Image&#39;)<br>axs[1].imshow(mask)<br>axs[1].set_title(&#39;Segmentation Mask&#39;)<br>axs[2].imshow(masked_image)<br>axs[2].set_title(&#39;Masked Image&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpUB6jtAUI0JhNUKKN5RnA.png" /></figure><h4>Training</h4><pre>TRAIN_STEPS = len(train_dataset)<br>VAL_STEPS = len(val_dataset)<br><br>seg_b0.compile(optimizer=&quot;adam&quot;, loss=&#39;sparse_categorical_crossentropy&#39;, metrics=[&quot;accuracy&quot;])<br>history = seg_b0.fit(train_dataset, validation_data=val_dataset, steps_per_epoch=TRAIN_STEPS, <br>                     validation_steps=VAL_STEPS, epochs=50)</pre><h4>Inference</h4><pre>test_iter = iter(test_dataset)<br><br>for i in range(5):<br>    imgs, segs = next(test_iter)  # imgs: (B, H, W, 3), segs: (B, H, W)<br>    <br>    img_np = imgs[0].numpy()<br>    seg_np = segs[0].numpy()<br>    <br>    # Model prediction<br>    pred = seg_b0.predict(imgs[:1])        # shape: (1, H, W, N_CLASSES)<br>    pred_mask = np.argmax(pred[0], axis=-1)<br>    <br>    # Color masks<br>    pred_colored = give_color_to_seg_img(pred_mask)<br>    true_colored = give_color_to_seg_img(seg_np)<br>    <br>    # Overlay<br>    pred_overlay = cv2.addWeighted(img_np.astype(np.float32), 0.5, pred_colored.astype(np.float32), 0.5, 0)<br>    true_overlay = cv2.addWeighted(img_np.astype(np.float32), 0.5, true_colored.astype(np.float32), 0.5, 0)<br><br>    # Plotting<br>    plt.figure(figsize=(12, 4))<br>    <br>    plt.subplot(1, 3, 1)<br>    plt.imshow(img_np)<br>    plt.title(&quot;Original&quot;)<br>    plt.axis(&quot;off&quot;)<br><br>    plt.subplot(1, 3, 2)<br>    plt.imshow(pred_overlay)<br>    plt.title(&quot;Prediction&quot;)<br>    plt.axis(&quot;off&quot;)<br><br>    plt.subplot(1, 3, 3)<br>    plt.imshow(true_overlay)<br>    plt.title(&quot;Ground Truth&quot;)<br>    plt.axis(&quot;off&quot;)<br><br>    plt.tight_layout()<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZMcGJvypBGx_zWpNi15QQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Em84Li68ed37ojlkYGlRVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BifY2Qv0tl8NvLj_HB0P4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wUdCwTLymb9HyEm13dW3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QW8evB2DbmhPZ50Vfm0Jgg.png" /></figure><p>Thank You !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09600f575455" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training a Vision Language Model from scratch (VLM multi-modal)]]></title>
            <link>https://medium.com/@saptarshimt/training-a-vision-language-model-from-scratch-vlm-multi-modal-a0b43c5966b1?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0b43c5966b1</guid>
            <category><![CDATA[vision-language-model]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[multi-modal-llm]]></category>
            <category><![CDATA[llama-2]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 13:48:47 GMT</pubDate>
            <atom:updated>2025-06-11T14:00:14.704Z</atom:updated>
            <content:encoded><![CDATA[<p>So after my previous blog on <a href="https://medium.com/@saptarshimt/llama-decoder-text-summarisation-from-scratch-3c248094e4a3">LLM from scratch</a> i thought about training a model for generating text based on user text and image input. Most of the base model (LLama) and text preprocessing is based on the previous llm blog, so i decided to go in detail on the vision model part and how it integrates with llm. Of course i will provide the entire architecture code and how training and inference is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OuIuaRooFvhT0rKd.jpeg" /></figure><blockquote>Data Preparation</blockquote><p>I will be using GQA, Llava-Pretrain and FS-VQA datasets. Maximum 2 questions are sampled per image resulting in total text-image pair being 500k samples. The final data looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEyBW2S3HqCPllK6WrHvqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M586MsqvsUIWu5eOYdDZpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Sy3-LJuyc20iNRO4tkbYA.png" /></figure><p>I used Byte Pair Encoding (BPE) for text tokenization. After analysis, I selected a VOCAB_SIZE of 8000 and a MAX_LEN of 37. The tokenizer includes special tokens: &lt;BOS&gt;, &lt;SEP&gt;, and &lt;EOS&gt;. The input format for the LLM is structured as follows:</p><pre>&lt;BOS&gt; input_text &lt;SEP&gt; target_text &lt;EOS&gt;</pre><p><strong>Example:</strong></p><pre>&lt;BOS&gt; who is holding the horse ? &lt;SEP&gt; the man is holding the horse . &lt;EOS&gt;</pre><p>This format helps the model clearly distinguish between the input and the expected output during training.</p><pre>MAX_WORD_LEN = 85 # word length pre tokenization<br><br># 1) Text cleaning ------------------------------------------------------<br>def clean_text(text: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Remove HTML, normalize whitespace, preserve punctuation/numbers/casing.<br>    &quot;&quot;&quot;<br>    # text = text.lower()<br>    text = re.sub(r&#39;&lt;image&gt;&#39;, &#39;&#39;, text, flags=re.IGNORECASE)<br>    text = re.sub(r&#39;[^a-zA-Z0-9.,!?]+&#39;, &#39; &#39;, text)<br>    text = text.replace(&#39;\r&#39;, &#39; &#39;).replace(&#39;\n&#39;, &#39; &#39;)<br>    text = re.sub(r&#39;\s+&#39;, &#39; &#39;, text)<br>    return text.strip().lower()<br><br>df[&#39;target_text&#39;] = df[&#39;target_text&#39;].apply(lambda x: clean_text(x))<br>df[&#39;input_text&#39;] = df[&#39;input_text&#39;].apply(lambda x: clean_text(x))<br><br>text_pairs = []<br><br>for img,i,j in zip(df.img_path,df.input_text,df.target_text):<br>    try:<br>        if len(i.split(&quot; &quot;)+j.split(&quot; &quot;)) &lt; MAX_WORD_LEN: <br>            text_pairs.append((img,i,j))<br>    except:<br>        pass<br><br>###################### TOKENIZATION AND DATA PREP ######################<br><br>BATCH_SIZE = 64<br>MAX_LEN = 37 # token length which will be now used in model building<br>VOCAB_SIZE = 8000<br>SPECIAL_TOKENS = [&#39;[PAD]&#39;,&#39;[UNK]&#39;,&#39;[BOS]&#39;,&#39;[EOS]&#39;,&#39;[SEP]&#39;]  <br><br># Initialize and train<br>tokenizer = Tokenizer(BPE(unk_token=&#39;[UNK]&#39;))<br>tokenizer.pre_tokenizer = Whitespace()<br>trainer = BpeTrainer(vocab_size=VOCAB_SIZE, special_tokens=SPECIAL_TOKENS)<br>tokenizer.train([CORPUS_FILE], trainer)<br><br># 0) Configure your tokenizer *once* at startup, not per-example<br>tokenizer.enable_truncation(<br>    max_length=MAX_LEN<br>)<br><br>tokenizer.enable_padding(<br>    pad_id=pad_id,<br>    pad_token=&#39;[PAD]&#39;,<br>    length=MAX_LEN<br>)<br><br>def encode_text(texts):<br>    encodings = tokenizer.encode(texts).ids<br>    return np.array(encodings, dtype=np.int32)<br><br># 1) encode_pair → return a NumPy array<br>def encode_pair(text_a: str, text_b: str) -&gt; np.ndarray:<br>    enc = tokenizer.encode(text_a, text_b).ids<br>    return np.array(enc, dtype=np.int32)   # shape: [MAX_LEN]<br><br>def encode_example(img_path, text: str, summary: str):<br>    ids = encode_pair(text, summary)           # np.ndarray, shape=[MAX_LEN]<br>    labels = np.concatenate([ids[1:], [pad_id]])  # shape=[MAX_LEN]<br><br>    # find SEP<br>    sep_idxs = np.where(labels == sep_id)[0]<br>    sep_pos = int(sep_idxs[0]) if sep_idxs.size else len(ids)<br><br>    # build base mask: 1 only for positions &gt; sep_pos AND not PAD<br>    positions = np.arange(len(labels))<br>    loss_mask = (positions &gt; sep_pos).astype(np.float32) * (labels != pad_id).astype(np.float32)<br><br>    return img_path, ids, labels.astype(np.int32), loss_mask<br><br># ── 0. do *all* tokenisation once ──────────────────────────<br>triples = [encode_example(img, t, s) for (img, t, s) in text_pairs]   # Python loop, done **once**<br>img_path, ids, labels, masks = map(lambda k: tf.constant(np.stack(k, 0)),zip(*triples))                      # shapes [N, MAX_LEN]<br><br># ── 1. build the purely-TF dataset ─────────────────────────<br>ds = (<br>    tf.data.Dataset.from_tensor_slices({&#39;img_path&#39;:img_path,&quot;input_ids&quot;: ids, &quot;labels&quot;: labels, &quot;loss_mask&quot;: masks})<br>    .shuffle(len(text_pairs))<br>    .batch(BATCH_SIZE)<br>    .prefetch(tf.data.AUTOTUNE)<br>)</pre><p><strong>Note:</strong> For token embeddings, I will train a custom embedding layer tailored to my text dataset using:</p><pre>self.token_embedding = tf.keras.layers.Embedding(input_dim=VOCAB_SIZE, output_dim=d_model)</pre><p>This allows the model to learn embeddings specific to the vocabulary and context of the dataset.</p><blockquote>Image Encoder</blockquote><p>The image encoder transforms an input image into embedding vectors. For this, I’ll be using <strong>MobileViT (frozen)</strong>, which offers a strong balance between performance and efficiency. One key advantage is that it produces a final feature map of shape (8, 8, 320), which can be reshaped into 64 image tokens of dimension 320. This lower embedding size (compared to 576 in MobileNetV3 Small) helps keep the overall model lightweight and faster to train, without significantly compromising accuracy.</p><p><strong>Note:</strong> While it’s possible to use a custom CNN model, I opted for a pre-trained one with <strong>frozen (non-trainable)</strong>, as it provides rich image features learned from millions of images — offering better generalization and faster convergence.</p><pre>import tensorflow as tf<br>from tensorflow.keras import Input, Model<br>from tensorflow.keras.layers import Layer, Reshape<br><br># Load the frozen SavedModel from disk<br>saved_model_path = &#39;mobilevit-tensorflow2-xxs-1k-256-fe-v1&#39;<br>loaded_model = tf.saved_model.load(saved_model_path)<br>encode_fn = loaded_model.signatures[&#39;serving_default&#39;]<br><br># Wrap the SavedModel call in a custom Keras layer<br>class FrozenEncoder(Layer):<br>    def call(self, inputs):<br>        outputs = encode_fn(inputs)<br>        return outputs[&#39;features_swish&#39;]  # returns [B, H, W, C]<br><br># Build a Keras model with the encoder<br>def build_image_encoder():<br>    input_tensor = Input(shape=(256, 256, 3))<br>    feat_map = FrozenEncoder()(input_tensor)  # [B, H, W, C]<br>    shape = feat_map.shape<br>    reshaped = Reshape((shape[1] * shape[2], shape[3]))(feat_map)  # [B, HW, C]<br>    return Model(inputs=input_tensor, outputs=reshaped)<br><br># Image preprocessing function<br>def decode_and_resize(path):<br>    img = tf.io.read_file(path)<br>    img = tf.image.decode_jpeg(img, channels=3)<br>    img = tf.image.resize(img, [256, 256])<br>    img = tf.cast(img, tf.float32) / 255.0<br>    return img<br><br># EXAMPLE.....<br><br># Build the encoder model<br>model = build_image_encoder()<br><br># Prepare image batch<br>paths = tf.constant([<br>    &quot;/Users/saptarshimallikthakur/Desktop/imgs/Screenshot 2025-06-08 at 7.36.42 AM.png&quot;,<br>    &quot;/Users/saptarshimallikthakur/Desktop/imgs/girraffe.jpg&quot;<br>])<br>images = tf.map_fn(decode_and_resize, paths, fn_output_signature=tf.float32)<br><br># Extract features<br>v3_output = model(images, training=False)<br>print(&quot;Feature shape:&quot;, v3_output.shape). # Feature shape: (2, 64, 320)</pre><blockquote>Decoder LLM</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0m5pWz3VVtFFQj62.png" /></figure><p>We will use the LLaMA architecture with slight modifications asthe text-generating decoder. Each decoder block will include the following components:</p><ul><li><strong>Masked Self-Attention</strong>: This layer takes text tokens of shape (Batch, Token_Length, Dimension=320) as input for the Query, Key, and Value. It applies look-ahead masking to prevent information leakage from future tokens and outputs tokens of the same shape. Rotary Positional Embeddings (RoPE) are applied to encode positional information.</li><li><strong>Cross-Attention</strong>: In this layer, the image features of shape (Batch, 64, 320) serve as the Key and Value, while the output of the masked self-attention layer serves as the Query. RoPE is <strong>not</strong> applied in this cross-attention layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*9swXqzBOjUiV4XVwRv3bEQ.png" /><figcaption>Source : <a href="https://www.mdpi.com/2076-3417/12/23/12221">https://www.mdpi.com/2076-3417/12/23/12221</a></figcaption></figure><p>Other Llama details are included in my previous blog. Please refer.</p><pre>def apply_rope(x, sin, cos):<br>    &quot;&quot;&quot;<br>    x   : (B, h, T, d) even-sized last dim (d must be multiple of 2)<br>    sin : (T, d//2)     broadcastable<br>    cos : (T, d//2)<br>    &quot;&quot;&quot;<br>    #This separates each feature vector&#39;s dimensions into 2 halves — like real and imaginary parts.<br>    x_even = x[..., 0::2]      # Get even-dimension values → shape: (B, h, T, d/2)<br>    x_odd  = x[..., 1::2]      # Get odd-dimension values → shape: (B, h, T, d/2)<br><br>    # This is a 2D rotation formula applied to each positional index and head.<br>    # It &quot;rotates&quot; the embedding vector in its dimensional space based on position.<br>    x_rot_even =  x_even *  cos - x_odd * sin<br>    x_rot_odd  =  x_even *  sin + x_odd * cos<br>    <br>    # interleave even/odd back together<br>    x_rot = tf.stack([x_rot_even, x_rot_odd], axis=-1)   # (..., d/2, 2)<br>    return tf.reshape(x_rot, tf.shape(x))                # (..., d)<br><br>def make_sincos(seq_len, dim, base=10000):<br>    &#39;&#39;&#39;<br>    Returns sin, cos with shape (seq_len, dim//2)<br>    &#39;&#39;&#39;<br>    pos = tf.cast(tf.range(seq_len), tf.float32)                       # (T,)<br>    i   = tf.cast(tf.range(0, dim, 2), tf.float32) / dim              # (d/2,)<br>    theta = pos[:, None] / (base ** i[None, :])                       # (T, d/2)<br>    return tf.sin(theta), tf.cos(theta)<br><br>class MultiHeadAttention(tf.keras.layers.Layer):<br>    &quot;&quot;&quot;<br>    Vanilla multi-head (scaled-dot-product) attention implemented from scratch.<br><br>    Args<br>    ----<br>    d_model     : int   – total embedding size (must be divisible by num_heads)  <br>    num_heads   : int   – number of attention heads  <br>    dropout     : float – dropout on attention weights (0.0 = no dropout)<br><br>    Call Signature<br>    --------------<br>    output, attn_scores = mha(<br>        query,                     # (B, T_q, d_model)<br>        value=None,                # (B, T_v, d_model)  – defaults to query<br>        key=None,                  # (B, T_k, d_model)  – defaults to value<br>        mask=None,                 # (B, 1, T_q, T_k) or (B, T_q, T_k)<br>        use_causal_mask=False,     #  True → autoregressive causal mask<br>        training=None<br>    )<br>    &quot;&quot;&quot;<br>    def __init__(self, d_model, num_heads, dropout=0.0, **kwargs):<br>        super().__init__(**kwargs)<br>        if d_model % num_heads != 0:<br>            raise ValueError(<br>                f&quot;d_model={d_model} must be divisible by num_heads={num_heads}&quot;<br>            )<br><br>        self.d_model   = d_model<br>        self.num_heads = num_heads<br>        self.depth     = d_model // num_heads<br><br>        # Linear projections for Q, K, V and final output<br>        self.wq   = tf.keras.layers.Dense(d_model, use_bias=False)<br>        self.wk   = tf.keras.layers.Dense(d_model, use_bias=False)<br>        self.wv   = tf.keras.layers.Dense(d_model, use_bias=False)<br>        self.wo   = tf.keras.layers.Dense(d_model, use_bias=False)<br><br>        self.dropout = tf.keras.layers.Dropout(dropout)<br><br>    # ────────────────────────────────────────────────────────────────────────<br>    # Helpers<br>    # ────────────────────────────────────────────────────────────────────────<br>    def _split_heads(self, x, B):<br>        &quot;&quot;&quot;<br>        Reshape (B, T, d_model) → (B, num_heads, T, depth)<br>        so we can run attention on each head in parallel.<br>        &quot;&quot;&quot;<br>        x = tf.reshape(x, (B, -1, self.num_heads, self.depth))<br>        return tf.transpose(x, perm=[0, 2, 1, 3])<br><br>    @staticmethod<br>    def _scaled_dot_product_attention(q, k, v, mask, dropout,training=None):<br>        &quot;&quot;&quot;<br>        Core attention: softmax(QKᵀ / √d_k) V<br>        Returns: (B, h, T_q, depth_v), (B, h, T_q, T_k)<br>        &quot;&quot;&quot;<br>        dk = tf.cast(tf.shape(k)[-1], tf.float32)<br>        scores = tf.matmul(q, k, transpose_b=True) / tf.math.sqrt(dk)  # (B,h,T_q,T_k)<br><br>        if mask is not None:<br>            # broadcast automatically if mask rank &lt; scores rank<br>            scores += (mask * -1e9)  # large negative → zero probability<br><br>        attn = tf.nn.softmax(scores, axis=-1)<br>        attn = dropout(attn,training=training)<br>        output = tf.matmul(attn, v)  # (B,h,T_q,depth)<br>        return output<br><br>    # ────────────────────────────────────────────────────────────────────────<br>    # Forward pass<br>    # ────────────────────────────────────────────────────────────────────────<br>    def call(<br>        self,<br>        query,<br>        value=None,<br>        key=None,<br>        mask=None,<br>        use_causal_mask=False,<br>        training=None,<br>        self_attention=False<br>    ):<br>        if value is None:<br>            value = query<br>        if key is None:<br>            key = value<br><br>        B = tf.shape(query)[0]<br>        Tq = tf.shape(query)[1]          # sequence length of Q<br>        Tk = tf.shape(key)[1]<br><br>        # 1. Linear projections<br>        q = self.wq(query)   # (B, T_q, d_model)<br>        k = self.wk(key)     # (B, T_k, d_model)<br>        v = self.wv(value)   # (B, T_v, d_model)<br><br>        # 2. Reshape for multi-head<br>        q = self._split_heads(q, B)  # (B, h, T_q, depth)<br>        k = self._split_heads(k, B)  # (B, h, T_k, depth)<br>        v = self._split_heads(v, B)  # (B, h, T_v, depth)<br><br>        # 3) -----------------  ROTARY  -----------------<br>        # Build sin/cos for the longest sequence we need this step<br>        max_len = tf.maximum(Tq, Tk)<br>        sin, cos = make_sincos(max_len, self.depth)       # depth = d_model / num_heads<br><br>        # Slice sin/cos to actual lengths (broadcast works automatically)<br>        # RoPE modifies Q and K such that their dot product reflects not just content similarity but also relative position.<br>        if self_attention:<br>            q = apply_rope(q, sin[:Tq], cos[:Tq])             # rotate Q<br>            k = apply_rope(k, sin[:Tk], cos[:Tk])             # rotate K<br>        # ----------------------------------------------<br><br>        # 3. (Optional) Causal mask: block future positions<br>        if use_causal_mask:<br>            T_q = tf.shape(q)[2]<br>            T_k = tf.shape(k)[2]<br>            causal = 1.0 - tf.linalg.band_part(tf.ones((T_q, T_k)), -1, 0)  # lower-tri  # 1 → masked<br>            causal = causal[tf.newaxis, tf.newaxis, :, :]  # (1,1,T_q,T_k)<br>            mask = causal if mask is None else tf.maximum(mask, causal)<br><br>        # 4. Scaled dot-product attention<br>        attn_out = self._scaled_dot_product_attention(<br>            q, k, v, mask, self.dropout,training=training,<br>        )  # (B,h,T_q,depth), (B,h,T_q,T_k)<br><br>        # 5. Concatenate heads<br>        attn_out = tf.transpose(attn_out, perm=[0, 2, 1, 3])  # (B,T_q,h,depth)<br>        attn_out = tf.reshape(attn_out, (B, -1, self.d_model))  # (B,T_q,d_model)<br><br>        # 6. Final linear layer<br>        output = self.wo(attn_out)  # (B,T_q,d_model)<br><br>        return output<br>    <br>class RMSNorm(tf.keras.layers.Layer):<br>    def __init__(self, hidden_size, epsilon=1e-8, **kwargs):<br>        super(RMSNorm, self).__init__(**kwargs)<br>        self.hidden_size = hidden_size<br>        self.epsilon = epsilon<br>        <br>        # Learnable scale parameter γ (same shape as last dim of input)<br>        self.scale = self.add_weight(<br>            name=&quot;scale&quot;,<br>            shape=(self.hidden_size,),<br>            initializer=&quot;ones&quot;,<br>            trainable=True<br>        )<br><br>    def call(self, x):<br>        rms = tf.sqrt(tf.reduce_mean(tf.square(x), axis=-1, keepdims=True) + self.epsilon)<br>        norm_x = x / rms<br>        return norm_x * self.scale<br><br>class CausalSelfAttention(tf.keras.layers.Layer):<br><br>    def __init__(self, d_model, num_heads, dropout=0.0):<br>        super().__init__()<br>        self.mha = MultiHeadAttention(d_model=d_model,num_heads=num_heads,dropout=dropout)<br>        self.rmsnorm = RMSNorm(d_model)<br>        self.add = tf.keras.layers.Add()<br><br>    def call(self, x, padding_mask=None, training=None):<br><br>        rms_x1 = self.rmsnorm(x)<br>        attn_output = self.mha(<br>            query=rms_x1, value=rms_x1, key=rms_x1,<br>            mask=padding_mask,          # may be None<br>            use_causal_mask=True,<br>            training=training,<br>            self_attention=True<br>        )<br>        rms_x1 = self.add([x, attn_output])<br>        return rms_x1<br>    <br>class CrossAttention(tf.keras.layers.Layer):<br>    &quot;&quot;&quot;Q = text, K=V = image patches (already projected).&quot;&quot;&quot;<br>    def __init__(self, d_model, num_heads, dropout=0.0):<br>        super().__init__()<br>        self.mha =  MultiHeadAttention(d_model=d_model,num_heads=num_heads,dropout=dropout)<br>        self.rmsnorm = RMSNorm(d_model)<br>    def call(self, x, kv, training=False):<br>        norm_x = self.rmsnorm(x)<br>        attn_out = self.mha(query=norm_x, key=kv, value=kv, training=training)<br>        return x + attn_out</pre><pre>class SwiGLU(tf.keras.layers.Layer):<br>    def __init__(self, hidden_dim,factor=4):<br>        super().__init__()<br>        self.lin1 = tf.keras.layers.Dense(factor*hidden_dim,use_bias=False)   # W1<br>        self.lin2 = tf.keras.layers.Dense(hidden_dim,use_bias=False)       # W2<br><br>    def call(self, x):<br>        x_ = self.lin1(x)                          # shape: (..., 4d)<br>        a, b = tf.split(x_, num_or_size_splits=2, axis=-1)  # split<br>        gated = a * (b * tf.sigmoid(b))            # SwiGLU: a ⊙ SiLU(b)<br>        return self.lin2(gated)<br><br>class FeedForward(tf.keras.layers.Layer):<br>    def __init__(self, d_model, dropout_rate=0.1):<br>        super().__init__()<br><br>        self.seq = tf.keras.Sequential(<br>            [<br>                SwiGLU(d_model),<br>                tf.keras.layers.Dropout(dropout_rate),<br>            ]<br>        )<br>        self.rmsnorm = RMSNorm(d_model)<br><br>    def call(self, x, training=None):<br>        y = self.seq(self.rmsnorm(x), training=training)  # pre-norm<br>        return x + y                                  # residual on raw x<br>    <br>class DecoderBlock(tf.keras.layers.Layer):<br>    def __init__(self, *, d_model, num_heads, dropout_rate=0.1):<br>        super().__init__()<br>        self.causal_self_attention = CausalSelfAttention(num_heads=num_heads, d_model=d_model, dropout=dropout_rate)<br>        self.cross_attn = CrossAttention(num_heads=num_heads, d_model=d_model, dropout=dropout_rate)<br>        self.ffn = FeedForward(d_model)<br><br>    def call(self, x, kv, padding_mask=None, training=None):<br>        x = self.causal_self_attention(x, padding_mask=padding_mask, training=training)<br>        x = self.cross_attn(x, kv, training=training)<br>        x = self.ffn(x,training=training)<br>        return x<br><br>class Decoder(tf.keras.layers.Layer):<br>    def __init__(<br>        self, *, num_layers, d_model, num_heads, dropout_rate=0.1,pad_token_id = pad_id):<br>        super(Decoder, self).__init__()<br><br>        self.d_model = d_model<br>        self.num_layers = num_layers<br>        self.pad_token_id = pad_token_id<br><br>        self.token_embedding = tf.keras.layers.Embedding(input_dim=VOCAB_SIZE,output_dim=d_model)<br>        self.img_embedding = build_image_encoder()<br>        <br>        self.dropout = tf.keras.layers.Dropout(dropout_rate)<br>        <br>        self.dec_layers = [DecoderBlock(d_model=d_model, num_heads=num_heads, dropout_rate=dropout_rate) for _ in range(num_layers)]<br><br>    def call(self, inputs, training=None):<br>        imgs, text_ids = inputs  # imgs:(B,H,W,3)  text_ids:(B,T)<br>        pad_mask = tf.cast(tf.equal(text_ids, self.pad_token_id), tf.float32)[:, tf.newaxis, tf.newaxis, :]<br><br>        kv = self.img_embedding(imgs,training=False)<br>        x = self.token_embedding(text_ids)<br><br>        # Make sure img_emb has the same dtype as text_emb<br>        kv = tf.cast(kv, dtype=x.dtype)<br>        x = self.dropout(x, training=training)<br><br>        for layer in self.dec_layers:<br>            x = layer(x, kv, padding_mask=pad_mask, training=training)<br><br>        return x<br>    <br>class Transformer(tf.keras.Model):<br>    def __init__(self, *, num_layers, d_model, num_heads, input_vocab_size, dropout_rate=0.1):<br>        super().__init__()<br>        self.decoder = Decoder(num_layers=num_layers,d_model=d_model,num_heads=num_heads,dropout_rate=dropout_rate,)<br>        self.rmsnorm = RMSNorm(d_model)<br>        self.final_layer = tf.keras.layers.Dense(input_vocab_size)<br><br>    def call(self, inputs,training=False):<br>        x = self.decoder(inputs,training=training)  # (batch_size, target_len, d_model)<br>        x = self.rmsnorm(x)<br>        logits = self.final_layer(x)  # (batch_size, target_len, target_vocab_size)<br>        return logits</pre><p>Finally building the model :</p><pre>num_layers = 6<br>d_model = 320  # v3_output.shape[-1]<br>num_heads = 12 # each head with 32 dimension<br>dropout_rate = 0.1<br>EPOCHS = 2<br><br>model = Transformer(<br>    num_layers=num_layers,<br>    d_model=d_model,<br>    num_heads=num_heads,<br>    input_vocab_size=VOCAB_SIZE,<br>    dropout_rate=0.1<br>)<br><br>dummy_path   = tf.constant([&quot;/Users/saptarshimallikthakur/Desktop/imgs/Screenshot 2025-06-08 at 7.36.42 AM.png&quot;])   # (1,)  string<br>images = tf.map_fn(decode_and_resize, dummy_path, fn_output_signature=tf.float32)<br>dummy_tokens = tf.zeros((1, MAX_LEN), dtype=tf.int32)<br>_ = model((images, dummy_tokens))              <br>model.summary()</pre><pre>┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓<br>┃ Layer (type)                    ┃ Output Shape           ┃       Param # ┃<br>┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩<br>│ decoder (Decoder)               │ ?                      │    11,167,360 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ rms_norm_18 (RMSNorm)           │ ?                      │           320 │<br>├─────────────────────────────────┼────────────────────────┼───────────────┤<br>│ dense_60 (Dense)                │ (1, 37, 8000)          │     2,568,000 │<br><br> Total params: 13,735,680 (52.40 MB)<br> Trainable params: 13,735,680 (52.40 MB)<br> Non-trainable params: 0 (0.00 B)</pre><p>In large language models (LLMs), learning rate scheduling plays a crucial role in stable and efficient training. A common strategy involves a <strong>linear warm-up</strong> phase followed by a <strong>cosine decay</strong>. During warm-up, the learning rate gradually increases from zero to a peak value over the first few thousand steps, helping the model avoid divergence early in training. After warm-up, the learning rate decays smoothly following a cosine curve, allowing the model to converge gradually and avoid overshooting minima. This scheduling technique balances exploration and stability across long training runs.</p><pre>WARM_FRAC   = 0.1        # keep the fast ramp-up<br>DECAY_RATE  = 4<br>LR_FLOOR    = 1e-6<br>LR_PEAK_DESIRED = 5e-4     # choose 8e-4 or 9e-4<br><br># pre-compute the scale that gives that peak<br>num_steps     = EPOCHS * len(text_pairs) // BATCH_SIZE<br>warmup_steps  = int(num_steps * WARM_FRAC)<br>current_peak  = 1.0 / tf.sqrt(tf.cast(d_model * warmup_steps, tf.float32))<br>LR_SCALE      = LR_PEAK_DESIRED / current_peak.numpy()<br><br>@tf.keras.utils.register_keras_serializable()   # so it can round-trip in SavedModel/H5<br>class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):<br>    def __init__(self, d_model, total_steps=num_steps,<br>                 warmup_frac=WARM_FRAC, decay_rate=DECAY_RATE,<br>                 lr_scale=LR_SCALE):<br>        super().__init__()<br>        self.d_model      = tf.cast(d_model, tf.float32)<br>        self.warmup_steps = tf.cast(int(total_steps * warmup_frac), tf.float32)<br>        self.decay_rate   = decay_rate<br>        self.decay_steps  = tf.cast(total_steps, tf.float32)<br>        self.lr_scale     = tf.cast(lr_scale, tf.float32)<br><br>    def __call__(self, step):<br>        step  = tf.cast(step, tf.float32)<br>        arg1  = tf.math.rsqrt(step)<br>        arg2  = step * tf.math.pow(self.warmup_steps, -1.5)<br>        warm  = tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)<br>        decay = tf.math.exp(-self.decay_rate *<br>                            tf.maximum(step - self.warmup_steps, 0.) /<br>                            self.decay_steps)<br>        lr = warm * decay * self.lr_scale <br>        return tf.maximum(lr, LR_FLOOR)<br><br>    # ----------  NEW  ----------<br>    def get_config(self):<br>        return {<br>            &quot;d_model&quot;:      int(self.d_model.numpy()),   # cast back to Python types<br>            &quot;total_steps&quot;:  int(self.decay_steps.numpy()),<br>            &quot;warmup_frac&quot;:  float(self.warmup_steps.numpy() / self.decay_steps.numpy()),<br>            &quot;decay_rate&quot;:   self.decay_rate,<br>            &quot;lr_scale&quot;:     float(self.lr_scale.numpy()),<br>        }<br><br>    @classmethod<br>    def from_config(cls, config):<br>        return cls(**config)<br>    <br>learning_rate = CustomSchedule(d_model)<br><br>optimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9, clipnorm=1.0)<br><br>temp_learning_rate_schedule = CustomSchedule(d_model)<br><br>plt.plot(temp_learning_rate_schedule(tf.range(num_steps, dtype=tf.float32)))<br>plt.ylabel(&quot;Learning Rate&quot;)<br>plt.xlabel(&quot;Train Step&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*KurE6I0YMoa-QDVNLR6XnQ.png" /></figure><blockquote>Training</blockquote><pre>ds_for_fit = ds.map(<br>    lambda b: (<br>        (tf.map_fn(decode_and_resize, b[&#39;img_path&#39;], fn_output_signature=tf.float32), b[&quot;input_ids&quot;]),<br>        b[&quot;labels&quot;],<br>        b[&quot;loss_mask&quot;]<br>    ),<br>    num_parallel_calls=tf.data.AUTOTUNE<br>)<br><br><br># 3) Compile with a standard sparse‐CE loss and let Keras use sample weights<br>model.compile(<br>    optimizer=optimizer,<br>    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=&quot;mean_with_sample_weight&quot;),<br>    metrics=[&quot;sparse_categorical_accuracy&quot;]<br>)<br><br># Build callbacks<br>callbacks = [<br>    EarlyStopping(monitor=&quot;loss&quot;, patience=3,<br>                  restore_best_weights=True, verbose=1),<br>    ModelCheckpoint(<br>        filepath=&quot;best_summary.keras&quot;,        # or &quot;best_summary.h5&quot;<br>        monitor=&quot;loss&quot;,<br>        save_best_only=True,<br>        verbose=1             # full model (weights + optimizer + LR schedule)<br>    )<br>]<br><br># 4) Fit!  Keras will print epoch/step progress by default<br>history = model.fit(<br>    ds_for_fit,<br>    epochs=EPOCHS,<br>    callbacks=callbacks,<br>    verbose=1    # 1 = progress bar, loss &amp; acc per epoch<br>)</pre><pre>Epoch 1/3<br>[1m17789/17789[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 672ms/step - loss: 4.1653 - sparse_categorical_accuracy: 0.1268<br>Epoch 1: loss improved from inf to 3.27987, saving model to best_summary.keras<br>[1m17789/17789[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m11979s[0m 672ms/step - loss: 4.1652 - sparse_categorical_accuracy: 0.1268<br>Epoch 2/3<br>[1m17789/17789[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 667ms/step - loss: 2.5832 - sparse_categorical_accuracy: 0.1728<br>Epoch 2: loss improved from 3.27987 to 2.56137, saving model to best_summary.keras<br>[1m17789/17789[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m11863s[0m 667ms/step - loss: 2.5832 - sparse_categorical_accuracy: 0.1728<br>Epoch 3/3<br>[1m17789/17789[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 662ms/step - loss: 2.4849 - sparse_categorical_accuracy: 0.1750<br>Epoch 3: loss improved from 2.56137 to 2.48282, saving model to best_summary.keras<br>[1m17789/17789[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m11779s[0m 662ms/step - loss: 2.4849 - sparse_categorical_accuracy: 0.1750<br>Restoring model weights from the end of the best epoch: 3.</pre><blockquote>Inference</blockquote><pre>def encode(text: str) -&gt; list[int]:<br>    &quot;&quot;&quot;<br>    Encodes the prompt for inference, creating a sequence that ends<br>    right after the [SEP] token, with NO PADDING.<br>    &quot;&quot;&quot;<br>    # 1. Temporarily disable padding on the tokenizer<br>    tokenizer.no_padding()<br>    <br>    # 2. Encode the text. The post-processor will add [BOS] and [SEP].<br>    # This will return: [BOS, id, id, ..., SEP]<br>    text_ids = tokenizer.encode(text).ids<br>    <br>    # 3. IMPORTANT: Re-enable padding for any other part of your code that might need it<br>    tokenizer.enable_padding(pad_id=pad_id, pad_token=&#39;[PAD]&#39;, length=MAX_LEN)<br>    <br>    return text_ids<br><br>def generate_answer(image_path: str,<br>                    question:   str,<br>                    max_new_tokens: int = 30) -&gt; str:<br>    <br>    img_token = tf.constant([image_path])<br>    img_token = tf.map_fn(decode_and_resize, img_token, fn_output_signature=tf.float32)<br>    <br>    # 1. Encode the prompt (image placeholders + question)<br>    # This creates: [IMG]...[IMG] [BOS] question [SEP]<br>    prompt_ids = encode(question)<br>    text_tokens = tf.constant([prompt_ids], dtype=tf.int32)<br>    <br>    # 2. Autoregressive loop<br>    for _ in range(max_new_tokens):<br>        # Use direct model call for performance (not model.predict)<br>        # Pass training=False<br>        logits = model((img_token, text_tokens), training=False)[:, -1, :] / 0.1 # temperature<br>    <br>        # Sample the next token<br>        next_id = tf.random.categorical(logits, 1, dtype=tf.int32)<br><br>        # Append the new token<br>        text_tokens = tf.concat([text_tokens, next_id], 1)<br><br>        # Stop ONLY if EOS is generated<br>        if next_id[0, 0] == eos_id:<br>            break<br><br>    # 3. Decode the generated output<br>    generated_ids = text_tokens.numpy().tolist()[0] <br><br>    print(generated_ids)<br>    <br>    # --- END FIX ---<br><br>    # Display image for context<br>    imgbgr = cv2.imread(image_path)<br>    if imgbgr is not None:<br>        imgrgb = cv2.cvtColor(imgbgr,cv2.COLOR_BGR2RGB)<br>        plt.imshow(imgrgb)<br>        plt.title(f&quot;Q: {question}&quot;)<br>        plt.axis(&#39;off&#39;)<br>        plt.show()<br><br>    print(tokenizer.decode(generated_ids).strip())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*_ArTXqeQNYMJbOZYaF3hqQ.png" /><figcaption><strong>A.</strong> men and women walking on a street .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*wLSNQfsD7zjkIwI1XqZgAg.png" /><figcaption><strong>A.</strong> the animal is gray .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*WPp3m9q2pPaGDA-HBRdVTQ.png" /><figcaption><strong>A.</strong> yes , there is a dog .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*II1AuWRa79L8gj-rXymc0w.png" /><figcaption><strong>A. </strong>the animal is sleeping .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*8NZfDtaD7_3tLJeBbFS6ow.png" /><figcaption><strong>A.</strong> the animal is standing .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*3n8aLsdeFgt2bjmuyyfpMQ.png" /><figcaption><strong>A.</strong> there is 1 dog .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ZbDSijl-popHJQb5R47G6Q.png" /><figcaption><strong>A. </strong>there are 2 animals .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*syuHg2DAsIiXj3TvSvJr3Q.png" /><figcaption><strong>A.</strong> zebra .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*nzOXawCNYDmeDbI214_-ag.png" /><figcaption><strong>A</strong>. the main point of the image is flower .</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*0GINerYQz-uK-ajleLGzxQ.png" /><figcaption><strong>A.</strong> pink flowers in the garden</figcaption></figure><p>And that’s it folks !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0b43c5966b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Llama - Decoder Transformer Text Summarisation from Scratch]]></title>
            <link>https://medium.com/@saptarshimt/llama-decoder-text-summarisation-from-scratch-3c248094e4a3?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c248094e4a3</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[scratch]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[text-summarization]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 19:03:54 GMT</pubDate>
            <atom:updated>2025-06-13T02:01:48.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*mLpVaOcio3NzH9QI.png" /><figcaption>Llama Architecture - Credit : Milan Tamang</figcaption></figure><p>In this article, I’ll walk you through the complete process of coding an end-to-end text summarization model. We’ll start by exploring and writing the model architecture, then move on to data preparation, loss function design, and scheduler implementation. Finally, we’ll cover training and inference. Get ready — it’s going to be an extensive deep dive!</p><p>NOTE : As a pre-requisite please learn about masked attention and transformer architecture.</p><blockquote><strong>Rotary Position Encoding, Word Embedding and Attention Mechanism</strong></blockquote><p>For a Natural Language Processing (NLP) model to process and understand human language, words and sentences must be converted into a numerical format. This is precisely where the concept of <strong>word embeddings</strong> comes into play.</p><p>A word embedding is a numerical representation of a word in a high-dimensional space. The key idea behind this representation is that words with similar meanings will have similar numerical representations, meaning the “distance” between their embeddings in this space will be small.</p><p>For instance, consider these simplified 4-dimensional embeddings:</p><p>‘KING’ : [1,1,1,2], ‘QUEEN’ : [1,1,1,3] and ‘RIVER’ : [1,9,8,1].</p><p>As you can observe, the numerical &quot;distance&quot; between the vector for &#39;KING&#39; and &#39;QUEEN&#39; is much smaller than the distance between &#39;KING&#39; and &#39;RIVER&#39;. This allows an NLP model to quantify and understand the semantic similarity between words.</p><p>While word embeddings help models understand individual word meanings and relationships, the <strong>order of words</strong> is crucial for comprehending the full meaning of a sentence. Consider these two sentences:</p><ul><li>“A man is standing on a cow.”</li><li>“A cow is standing on a man.”</li></ul><p>Both sentences use the exact same words, but their arrangement completely alters the meaning. This highlights a limitation of basic word embeddings alone.</p><blockquote>From this we can infere that along with word embedding which captures relationship between words, postional information also matters when understanding the meaning of sentence. Hence for a NLP model to get complete understanding of sentence we need to provide both of them.</blockquote><p>Before proceeding i will provide word embedding code :</p><pre>class TokenEmbedding(tf.keras.layers.Layer):<br>    &quot;&quot;&quot;<br>    <br>    Args:<br>        vocab_size (int): Vocabulary size (number of unique tokens).<br>        d_model (int): Embedding dimension.<br>    &quot;&quot;&quot;<br>    def __init__(self, vocab_size, d_model):<br>        super().__init__()<br><br>        # Learnable token embeddings<br>        self.embedding = tf.keras.layers.Embedding(<br>            input_dim=vocab_size, <br>            output_dim=d_model, <br>            mask_zero=True  # Ensures padding token is masked<br>        )<br><br>    def compute_mask(self, *args, **kwargs):<br>        # Pass through the mask from the embedding layer<br>        return self.embedding.compute_mask(*args, **kwargs)<br><br>    def call(self, x):<br>        &quot;&quot;&quot;<br>        Args:<br>            x: Tensor of token indices → shape: (batch_size, sequence_length)<br>        <br>        Returns:<br>            Tensor of shape (batch_size, sequence_length, d_model)<br>        &quot;&quot;&quot;<br><br>        # Convert token indices to dense vectors → (batch_size, seq_len, d_model)<br>        x = self.embedding(x)<br><br>        return x</pre><p>In the above class word embeddings are learnt while training process, based on text provided.</p><p>d_model refers to the dimensionality of the embedding space into which words (or other tokens) will be encoded. In simpler terms, it defines the length of the numerical vector that represents each word.</p><p>vocab_size denotes the total number of unique words (or tokens) that the model is designed to learn and encode into these numerical representations. It represents the size of the vocabulary that the model will handle.</p><p>Now that we have word embedded, we look at attention mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyLSJscwleXzn7KG6myf_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DIcRqmz69kv7u3Jx" /><figcaption>Attention Score</figcaption></figure><p>A sentence containing ‘t’ tokens each embedded in ‘d’ dimensional vector is passed as show in the image. As mentioned earlier any NLP model needs to understand the realtionship between words in a sentence. Hence we pass it through linear projection layer called Q-query, K-key and V-value which are basically learnable matrices. Each word in a sentence i.e X1,X2 and X3 are passed through these linear projection, matrix multiplied for similarity learning and returned as it is in (t,d) form. Dividing by the square root of dk is a scaling factor that stabilizes gradients.</p><p><strong><em>Multi-head self attention </em></strong>captures multiple meaning in a sentence. The philosphy is each attention head can <strong>focus on different parts of the input</strong>. For example:</p><ul><li>One head might focus on <strong>local context</strong> (e.g., next word).</li><li>Another might look at <strong>global structure</strong> (e.g., sentence-level relationships).</li></ul><p>Multi-head attention increases the <strong>representational capacity</strong> of the model:</p><ul><li>Each head has its own <strong>query, key, value projection layers</strong>, so it learns a <strong>unique subspace</strong>.</li><li>Final output is a <strong>concatenation</strong> of all heads → more information, richer embedding.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ii2XrLwi-vYq56bv8bVKkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBmnd3YsN8yir_CwA540vA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*2YPdzCm1WfRiFeEf3vy8PQ.png" /><figcaption>Multi Head Attention</figcaption></figure><blockquote><strong>Self-attention</strong> comes from the fact each word in the sentence is scored against all the words. So a word can attend to itself. The scores are passed through a softmax function where they will sum to 1, making them easy to interpret as probabilities. When we run multiple attention layers at the same time it leads to <strong>Multi-head Attention</strong>. This is done by running the attention layers at the same time, concatenating the results, and passing them to the feedforward layer.</blockquote><pre>class MultiHeadAttention(tf.keras.layers.Layer):<br>    &quot;&quot;&quot;<br>    Llama multi-head (scaled-dot-product) attention implemented from scratch.<br><br>    Args<br>    ----<br>    d_model     : int   – total embedding size (must be divisible by num_heads)  <br>    num_heads   : int   – number of attention heads  <br>    dropout     : float – dropout on attention weights (0.0 = no dropout)<br><br>    Call Signature<br>    --------------<br>    T_q = T_k = T_v<br><br>    output, attn_scores = mha(<br>        query,                     # (B, T_q, d_model)<br>        value=None,                # (B, T_v, d_model)  – defaults to query<br>        key=None,                  # (B, T_k, d_model)  – defaults to value<br>        mask=None,                 # (B, 1, T_q, T_k) or (B, T_q, T_k)<br>        use_causal_mask=False,     # True → autoregressive causal mask<br>        training=None<br>    )<br>    &quot;&quot;&quot;<br>    def __init__(self, d_model, num_heads, dropout=0.0, **kwargs):<br>        super().__init__(**kwargs)<br>        if d_model % num_heads != 0:<br>            raise ValueError(<br>                f&quot;d_model={d_model} must be divisible by num_heads={num_heads}&quot;<br>            )<br><br>        self.d_model   = d_model<br>        self.num_heads = num_heads<br>        self.depth     = d_model // num_heads<br><br>        # Linear projections for Q, K, V and final output<br>        self.wq   = tf.keras.layers.Dense(d_model, use_bias=False)<br>        self.wk   = tf.keras.layers.Dense(d_model, use_bias=False)<br>        self.wv   = tf.keras.layers.Dense(d_model, use_bias=False)<br>        self.wo   = tf.keras.layers.Dense(d_model, use_bias=False)<br><br>        self.dropout = tf.keras.layers.Dropout(dropout)<br><br>    # ────────────────────────────────────────────────────────────────────────<br>    # Helpers<br>    # ────────────────────────────────────────────────────────────────────────<br>    def _split_heads(self, x, B):<br>        &quot;&quot;&quot;<br>        Reshape (B, T, d_model) → (B, num_heads, T, depth)<br>        so we can run attention on each head in parallel.<br>        &quot;&quot;&quot;<br>        x = tf.reshape(x, (B, -1, self.num_heads, self.depth))<br>        return tf.transpose(x, perm=[0, 2, 1, 3])<br><br>    @staticmethod<br>    def _scaled_dot_product_attention(q, k, v, mask, dropout,training=None):<br>        &quot;&quot;&quot;<br>        Core attention: softmax(QKᵀ / √d_k) V<br>        Returns: (B, h, T_q, depth_v), (B, h, T_q, T_k)<br>        &quot;&quot;&quot;<br>        dk = tf.cast(tf.shape(k)[-1], tf.float32)<br>        scores = tf.matmul(q, k, transpose_b=True) / tf.math.sqrt(dk)  # (B,h,T_q,T_k)<br><br>        if mask is not None:<br>            # broadcast automatically if mask rank &lt; scores rank<br>            scores += (mask * -1e9)  # large negative → zero probability<br><br>        attn = tf.nn.softmax(scores, axis=-1)<br>        attn = dropout(attn,training=training)<br>        output = tf.matmul(attn, v)  # (B,h,T_q,depth)<br>        return output<br><br>    # ────────────────────────────────────────────────────────────────────────<br>    # Forward pass<br>    # ────────────────────────────────────────────────────────────────────────<br>    def call(<br>        self,<br>        query,<br>        value=None,<br>        key=None,<br>        mask=None,<br>        use_causal_mask=False,<br>        training=None<br>    ):<br>        if value is None:<br>            value = query<br>        if key is None:<br>            key = value<br><br>        B = tf.shape(query)[0]<br>        Tq = tf.shape(query)[1]          # sequence length of Q<br>        Tk = tf.shape(key)[1]<br><br>        # 1. Linear projections<br>        q = self.wq(query)   # (B, T_q, d_model)<br>        k = self.wk(key)     # (B, T_k, d_model)<br>        v = self.wv(value)   # (B, T_v, d_model)<br><br>        # 2. Reshape for multi-head<br>        q = self._split_heads(q, B)  # (B, h, T_q, depth)<br>        k = self._split_heads(k, B)  # (B, h, T_k, depth)<br>        v = self._split_heads(v, B)  # (B, h, T_v, depth)<br><br>        # 3) -----------------  ROTARY  -----------------<br>        # Build sin/cos for the longest sequence we need this step<br>        max_len = tf.maximum(Tq, Tk)<br>        sin, cos = make_sincos(max_len, self.depth)       # depth = d_model / num_heads<br><br>        # Slice sin/cos to actual lengths (broadcast works automatically)<br>        # RoPE modifies Q and K such that their dot product reflects not just content similarity but also relative position.<br>        q = apply_rope(q, sin[:Tq], cos[:Tq])             # rotate Q<br>        k = apply_rope(k, sin[:Tk], cos[:Tk])             # rotate K<br>        # ----------------------------------------------<br><br>        # 3. (Optional) Causal mask: block future positions<br>        if use_causal_mask:<br>            T_q = tf.shape(q)[2]<br>            T_k = tf.shape(k)[2]<br>            causal = 1.0 - tf.linalg.band_part(tf.ones((T_q, T_k)), -1, 0)  # lower-tri  # 1 → masked<br>            causal = causal[tf.newaxis, tf.newaxis, :, :]  # (1,1,T_q,T_k)<br>            mask = causal if mask is None else tf.maximum(mask, causal)<br><br>        # 4. Scaled dot-product attention<br>        attn_out = self._scaled_dot_product_attention(<br>            q, k, v, mask, self.dropout,training=training,<br>        )  # (B,h,T_q,depth), (B,h,T_q,T_k)<br><br>        # 5. Concatenate heads<br>        attn_out = tf.transpose(attn_out, perm=[0, 2, 1, 3])  # (B,T_q,h,depth)<br>        attn_out = tf.reshape(attn_out, (B, -1, self.d_model))  # (B,T_q,d_model)<br><br>        # 6. Final linear layer<br>        output = self.wo(attn_out)  # (B,T_q,d_model)<br><br>        return output</pre><p>Proceeding, usually in normal transformer model we would add embedding vector of a word with the positional information (also encoded in same high dimensional space) before passing it. However it was found that adding kind of is inefficent as it would harm the inter realtionship between the meaning of words. We wanted the word embedding to stay as it is for maximal word inter-relationship information flow to model, while encoding postional info in latter stage.</p><p>Introduced in Llama, <strong>‘Rotary Positional Encoding’</strong> is a mathematical way to incorporate postional information of words in a text directly in attention mechanism.</p><ul><li>The same word at different positions ends up with different rotated vectors</li><li>The inner product between tokens reflects their <strong>relative distances</strong></li></ul><blockquote>RoPE modifies <strong>Query and Key </strong>such that their <strong>dot product</strong> reflects <strong>not just content similarity</strong> but also <strong>relative position</strong>.</blockquote><pre>def apply_rope(x, sin, cos):<br>    &quot;&quot;&quot;<br>    x   : (B, h, T, d) even-sized last dim (d must be multiple of 2)<br>    sin : (T, d//2)     broadcastable<br>    cos : (T, d//2)<br>    &quot;&quot;&quot;<br>    #This separates each feature vector&#39;s dimensions into 2 halves — like real and imaginary parts.<br>    x_even = x[..., 0::2]      # Get even-dimension values → shape: (B, h, T, d/2)<br>    x_odd  = x[..., 1::2]      # Get odd-dimension values → shape: (B, h, T, d/2)<br><br>    # This is a 2D rotation formula applied to each positional index and head.<br>    # It &quot;rotates&quot; the embedding vector in its dimensional space based on position.<br>    x_rot_even =  x_even *  cos - x_odd * sin<br>    x_rot_odd  =  x_even *  sin + x_odd * cos<br>    <br>    # interleave even/odd back together<br>    x_rot = tf.stack([x_rot_even, x_rot_odd], axis=-1)   # (..., d/2, 2)<br>    return tf.reshape(x_rot, tf.shape(x))                # (..., d)<br><br>def make_sincos(seq_len, dim, base=10000):<br>    &#39;&#39;&#39;<br>    Returns sin, cos with shape (seq_len, dim//2)<br>    &#39;&#39;&#39;<br>    pos = tf.cast(tf.range(seq_len), tf.float32)                       # (T,)<br>    i   = tf.cast(tf.range(0, dim, 2), tf.float32) / dim              # (d/2,)<br>    theta = pos[:, None] / (base ** i[None, :])                       # (T, d/2)<br>    return tf.sin(theta), tf.cos(theta)</pre><p>Given a token, RoPE applies a rotation to its respective key and query vectors based on its position in the sequence. This rotation is achieved by multiplying the vectors with a <em>rotation matrix</em>.</p><p><strong>Rotation Matrix:</strong> A rotation matrix in 2D space (the simplest case) is as following, where θ is an arbitrary angle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pIe0uwlvJQjrAm9K.png" /><figcaption>Rotation matrix with angle θ</figcaption></figure><p>If you multiply above matrix by a vector in 2D then it just changes the angle of the vector and keep the length of the vector the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7VI1nDwGP0qaxZxv.png" /><figcaption>product of rotation matrix and a vector x</figcaption></figure><p><strong>Now, how is it applied to the key and query vector?</strong></p><p>Notice that query vector is the multiplication of the query matrix and the token embedding, i.e.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VkMHtJY0z52piFnR.png" /></figure><p>Now if we apply the rotation matrix to it, we are rotating the query vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RNM3OMRYmqwyrmAB.png" /></figure><p>In all above, we assumed the token <em>x</em> is happening at position 1 ! If it is happening at an arbitrary position <em>m</em> then the rotation matrix will contain <em>m</em> in it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JCBF4A6e6i_Bb35h.png" /></figure><p>In my code:</p><pre>x_even = x[…, 0::2] # (B, h, T, d/2)<br>x_odd = x[…, 1::2] # (B, h, T, d/2)</pre><p>Means for every token/word embedding:</p><ul><li>x_even grabs every <strong>even-indexed</strong> dimension: x_0, x_2, x_4, ..., x_{d-2}</li><li>x_odd grabs every <strong>odd-indexed</strong> dimension: x_1, x_3, x_5, ..., x_{d-1}</li><li>x = [x_0, x_1, x_2, x_3, x_4, x_5, x_6, x_7] full vector</li></ul><blockquote>Pair 1: (x_0, x_1) → 1st 2D rotation<br>Pair 2: (x_2, x_3) → 2nd 2D rotation<br>Pair 3: (x_4, x_5) → 3rd 2D rotation<br>Pair 4: (x_6, x_7) → 4th 2D rotation</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*jUmnbJvg7ZvE_C2PFiLEbw.png" /></figure><pre>x_rot_even = x_even * cos - x_odd * sin<br>x_rot_odd  = x_even * sin + x_odd * cos</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*wCg-cE9Yfj5_F53hAvboxQ.png" /></figure><p>θ (theta) defines the <strong>rotation angle</strong> per:</p><blockquote>t <strong>— Token position</strong> in the sequence (e.g., 0 for first word, 1 for second, etc.)</blockquote><blockquote>k — <strong>Index of the dimension pair</strong> within the token’s embedding vector</blockquote><p>So for token t, and pair (x_{2k}, x_{2k+1}), we need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*sXxrCOusPbmzWl8VSlPQdw.png" /></figure><p>This angle θ_{t,k} is used to rotate the k-th 2D vector slice at position t.</p><blockquote>RMSNorm</blockquote><p>We completed ROPE, Input Token Embedding and Multi-Head Attention. The Self-Attention code ends below.</p><pre>class RMSNorm(tf.keras.layers.Layer):<br>    def __init__(self, hidden_size, epsilon=1e-8, **kwargs):<br>        super(RMSNorm, self).__init__(**kwargs)<br>        self.hidden_size = hidden_size<br>        self.epsilon = epsilon<br>        <br>        # Learnable scale parameter γ (same shape as last dim of input)<br>        self.scale = self.add_weight(<br>            name=&quot;scale&quot;,<br>            shape=(self.hidden_size,),<br>            initializer=&quot;ones&quot;,<br>            trainable=True<br>        )<br><br>    def call(self, x):<br>        rms = tf.sqrt(tf.reduce_mean(tf.square(x), axis=-1, keepdims=True) + self.epsilon)<br>        norm_x = x / rms<br>        return norm_x * self.scale<br><br>class CausalSelfAttention(tf.keras.layers.Layer):<br><br>    def __init__(self, d_model, num_heads, dropout=0.0):<br>        super().__init__()<br>        self.mha = MultiHeadAttention(d_model=d_model,<br>                                      num_heads=num_heads,<br>                                      dropout=dropout)<br>        self.rmsnorm = RMSNorm(d_model)<br>        self.add = tf.keras.layers.Add()<br><br>    def call(self, x, padding_mask=None, training=None):<br><br>        rms_x1 = self.rmsnorm(x)<br><br>        attn_output = self.mha(<br>            query=rms_x1, value=rms_x1, key=rms_x1,<br>            mask=padding_mask,          # may be None<br>            use_causal_mask=True,<br>            training=training,<br>        )<br>        rms_x1 = self.add([x, attn_output])<br>        return rms_x1</pre><p>What we did was, given input embedding we pass through RMSNorm and then to Multi-Head Attention. It is like :</p><ul><li>RMSNormalisation</li><li>Self-Attention</li><li>Residual Connection</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*6uwCD5HHuDmLgyEsCD7dvA.png" /><figcaption>Only scales by <strong>vector magnitude. No mean subtraction</strong> (not centered)</figcaption></figure><p>LLaMA uses <strong>PreNorm</strong> layout (norm → attention), where centering is less crucial. It is used for stable training by moveing normalization outside the residual path, allowing gradients to <strong>flow more directly</strong>. It is faster, cheaper, and simpler (no mean computation)</p><blockquote><strong>SwiGLU</strong> is a gated activation function — short for <strong>Swish-Gated Linear Unit</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*zE9HSa9dsqrsxrQhjE9jdQ.png" /></figure><p>or for same but visually better for understanding :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*S8AJaNp0gvOKKJHMqZ0GeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*YpXgSW41zCazte3SXD9sBg.png" /><figcaption>Source : <a href="https://rohitbandaru.github.io/blog/Transformer-Design-Guide-Pt2/">https://rohitbandaru.github.io/blog/Transformer-Design-Guide-Pt2/</a></figcaption></figure><pre>class SwiGLU(tf.keras.layers.Layer):<br>    def __init__(self, hidden_dim,factor=4):<br>        super().__init__()<br>        self.lin1 = tf.keras.layers.Dense(factor*hidden_dim,use_bias=False)   # W1<br>        self.lin2 = tf.keras.layers.Dense(hidden_dim,use_bias=False)       # W2<br><br>    def call(self, x):<br>        x_ = self.lin1(x)                          # shape: (..., 4d)<br>        a, b = tf.split(x_, num_or_size_splits=2, axis=-1)  # split<br>        gated = a * (b * tf.sigmoid(b))            # SwiGLU: a ⊙ SiLU(b)<br>        return self.lin2(gated)</pre><ul><li><strong>Gating</strong> helps model learn <strong>which features to keep/ignore.</strong></li><li><strong>Swish</strong> is smoother and empirically better than ReLU or GELU</li><li>Stronger gradient flow</li></ul><pre>class FeedForward(tf.keras.layers.Layer):<br>    def __init__(self, d_model, dropout_rate=0.1):<br>        super().__init__()<br><br>        self.seq = tf.keras.Sequential(<br>            [<br>                SwiGLU(d_model),<br>                tf.keras.layers.Dropout(dropout_rate),<br>            ]<br>        )<br>        self.rmsnorm = RMSNorm(d_model)<br><br>    def call(self, x, training=None):<br>        y = self.seq(self.rmsnorm(x), training=training)  # pre-norm<br>        return x + y                                  # residual on raw x<br>    <br>class DecoderLayer(tf.keras.layers.Layer):<br>    def __init__(self, *, d_model, num_heads, dropout_rate=0.1):<br>        super().__init__()<br>        self.causal_self_attention = CausalSelfAttention(num_heads=num_heads, d_model=d_model, dropout=dropout_rate)<br>        self.ffn = FeedForward(d_model)<br><br>    def call(self, x, padding_mask=None, training=None):<br>        x = self.causal_self_attention(x, padding_mask=padding_mask, training=training)<br>        x = self.ffn(x,training=training)<br>        return x<br><br>class Decoder(tf.keras.layers.Layer):<br>    def __init__(<br>        self, *, num_layers, d_model, num_heads, vocab_size, dropout_rate=0.1<br>    ):<br>        super(Decoder, self).__init__()<br><br>        self.d_model = d_model<br>        self.num_layers = num_layers<br><br>        self.pos_embedding = TokenEmbedding(vocab_size=vocab_size, d_model=d_model)<br>        self.dropout = tf.keras.layers.Dropout(dropout_rate)<br>        <br>        self.dec_layers = [DecoderLayer(d_model=d_model, num_heads=num_heads, dropout_rate=dropout_rate)<br>                           for _ in range(num_layers)]<br><br>        self.last_attn_scores = None<br><br>    def call(self, x, training=None):<br>        pad_mask = self.pos_embedding.compute_mask(x)<br>        if pad_mask is not None:<br>            pad_mask = tf.cast(~pad_mask, tf.float32)[:, tf.newaxis, tf.newaxis, :]<br><br>        x = self.pos_embedding(x)<br>        x = self.dropout(x, training=training)<br><br>        for layer in self.dec_layers:<br>            x = layer(x, padding_mask=pad_mask, training=training)<br><br>        return x<br><br>class Transformer(tf.keras.Model):<br>    def __init__(self, *, num_layers, d_model, num_heads, input_vocab_size, dropout_rate=0.1):<br>        super().__init__()<br><br>        self.decoder = Decoder(<br>            num_layers=num_layers,<br>            d_model=d_model,<br>            num_heads=num_heads,<br>            vocab_size=input_vocab_size,<br>            dropout_rate=dropout_rate,<br>        )<br><br>        self.rmsnorm = RMSNorm(d_model)<br>        self.final_layer = tf.keras.layers.Dense(input_vocab_size)<br><br>    def call(self, inputs,training=False):<br>        # To use a Keras model with `.fit` you must pass all your inputs in the<br>        # first argument.<br>        x = inputs<br><br>        x = self.decoder(x,training=training)  # (batch_size, target_len, d_model)<br><br>        # Final linear layer output.<br>        x = self.rmsnorm(x)<br>        logits = self.final_layer(x)  # (batch_size, target_len, target_vocab_size)<br><br>        try:<br>            # Drop the keras mask, so it doesn&#39;t scale the losses/metrics.<br>            # b/250038731<br>            del logits._keras_mask<br>        except AttributeError:<br>            pass<br><br>        # Return the final output<br>        return logits</pre><blockquote>DATA PREPARATION</blockquote><p>For our dataset we will be using 3 of them : Inshorts news summairsation, samsum &amp; dialogsumm.</p><pre>df1 = pd.read_excel(&quot;Inshorts Cleaned Data.xlsx&quot;).dropna(subset=[&#39;Headline&#39;,&#39;Short&#39;]).rename(columns={&#39;Headline&#39;:&#39;target_txt&#39;,&#39;Short&#39;:&#39;input_txt&#39;})[[&#39;target_txt&#39;,&#39;input_txt&#39;]]<br>df2 = pd.read_csv(&#39;train.csv&#39;).rename(columns={&#39;dialogue&#39;:&#39;input_txt&#39;,&#39;summary&#39;:&#39;target_txt&#39;})[[&#39;target_txt&#39;,&#39;input_txt&#39;]]<br>df3 = pd.read_json(&#39;train.json&#39;).rename(columns={&#39;dialogue&#39;:&#39;input_txt&#39;,&#39;summary&#39;:&#39;target_txt&#39;})[[&#39;target_txt&#39;,&#39;input_txt&#39;]]<br><br>train_df = pd.concat([df1,df2,df3]).reset_index(drop=True)<br><br># 1) Text cleaning ------------------------------------------------------<br>def clean_text(text: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Remove HTML, normalize whitespace, preserve punctuation/numbers/casing.<br>    &quot;&quot;&quot;<br>    try:<br>        # text = text.lower()<br>        text = re.sub(r&#39;[^a-zA-Z0-9.,!?]+&#39;, &#39; &#39;, text)<br>        text = text.replace(&#39;\r&#39;, &#39; &#39;).replace(&#39;\n&#39;, &#39; &#39;)<br>        text = re.sub(r&#39;\s+&#39;, &#39; &#39;, text)<br>        return text.strip().lower()<br>    except:<br>        return text<br><br>train_df[&#39;target_txt&#39;] = train_df[&#39;target_txt&#39;].apply(lambda x: clean_text(x))<br>train_df[&#39;input_txt&#39;] = train_df[&#39;input_txt&#39;].apply(lambda x: clean_text(x))<br><br># Combine summary + dialogue and split on whitespace<br>raw_lens = [<br>    len(f&quot;{s} {d}&quot;.split()) <br>    for s, d in tqdm(zip(train_df[&quot;target_txt&quot;], train_df[&quot;input_txt&quot;]), total=len(train_df))<br>]<br><br>lens = np.array(raw_lens)<br><br># Print summary stats<br>def pct(x): return np.percentile(lens, x)<br><br>print(f&quot;Total examples    : {len(lens):,}&quot;)<br>print(f&quot;Min / Max words   : {lens.min()} / {lens.max()}&quot;)<br>print(f&quot;Mean ± std        : {lens.mean():.1f} ± {lens.std():.1f}&quot;)<br>print(&quot;--- Percentiles (word count per raw text pair) ---&quot;)<br>for p in [50, 90, 95, 98, 99]:<br>    print(f&quot;{p:&gt;3}% : {pct(p):.0f} words&quot;)<br><br>&#39;&#39;&#39;/Users/saptarshimallikthakur/Desktop/Extraas/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html<br>  from .autonotebook import tqdm as notebook_tqdm<br>100%|██████████| 82296/82296 [00:00&lt;00:00, 335684.31it/s]Total examples    : 82,296<br>Min / Max words   : 6 / 1164<br>Mean ± std        : 93.4 ± 58.7<br>--- Percentiles (word count per raw text pair) ---<br> 50% : 73 words<br> 90% : 164 words<br> 95% : 218 words<br> 98% : 284 words<br> 99% : 330 words&#39;&#39;&#39;<br><br><br>MAX_LEN = int(pct(90))<br><br>text_pairs = []<br><br>for i,j in zip(train_df.input_txt,train_df.target_txt):<br>    try:<br>        if len(i.split(&quot; &quot;)+j.split(&quot; &quot;)) &lt; MAX_LEN:       # BOS, SEP,EOS extra<br>            text_pairs.append((i,j))<br>    except:<br>        pass</pre><pre>from tokenizers import Tokenizer, models, trainers, pre_tokenizers<br><br>rng            = np.random.default_rng(42)<br>valid_mask     = rng.random(len(train_df)) &lt; 0.05          # 5 % hold-out<br>train_df_, valid_df = train_df[~valid_mask], train_df[valid_mask]<br><br># ⇢ cache validation texts so we can loop over them many times<br>valid_texts = [f&quot;{s} {d}&quot; for s, d in<br>               zip(valid_df[&quot;target_txt&quot;], valid_df[&quot;input_txt&quot;])]<br><br>def train_tokenizer(text_iter, vocab_size: int) -&gt; Tokenizer:<br>    tok = Tokenizer(models.BPE(unk_token=&quot;[UNK]&quot;))<br>    tok.pre_tokenizer = pre_tokenizers.Whitespace()<br>    trainer = trainers.BpeTrainer(vocab_size=vocab_size,<br>                                  min_frequency=2,<br>                                  special_tokens=[&quot;[UNK]&quot;])<br>    tok.train_from_iterator(text_iter, trainer)<br>    return tok<br><br>def avg_pieces_per_word(tok: Tokenizer, texts) -&gt; float:<br>    pieces = words = 0<br>    for t in texts:<br>        ids   = tok.encode(t).ids<br>        pieces += len(ids)<br>        words  += len(t.split())<br>    return pieces / words<br><br>vocab_sizes = [1000,2000,3000,4000,6000,8000,10000,12000,16000,20000]<br>pieces_per_word, oov_rate = [], []<br><br>for k in vocab_sizes:<br>    print(k)<br>    train_iter = (f&quot;{s} {d}&quot; for s, d in<br>                  zip(train_df_[&quot;target_txt&quot;], train_df_[&quot;input_txt&quot;]))<br>    tok = train_tokenizer(train_iter, k)<br><br>    # 1) average sub-words per word on validation set<br>    pieces_per_word.append(avg_pieces_per_word(tok, valid_texts))<br><br>    # 2) OOV percentage on validation set<br>    unk_id = tok.token_to_id(&quot;[UNK]&quot;)<br>    total = unk = 0<br>    for t in valid_texts:<br>        ids   = tok.encode(t).ids<br>        total += len(ids)<br>        unk   += sum(id_ == unk_id for id_ in ids)<br>    oov_rate.append(100 * unk / total)<br><br># ── plot ───────────────────────────────────────────────────────────────<br>plt.figure(figsize=(7,3))<br>plt.subplot(1,2,1)<br>plt.plot(vocab_sizes, pieces_per_word, marker=&#39;o&#39;)<br>plt.title(&quot;pieces / word&quot;); plt.xlabel(&quot;vocab size&quot;)<br><br>plt.subplot(1,2,2)<br>plt.plot(vocab_sizes, oov_rate, marker=&#39;o&#39;)<br>plt.title(&quot;OOV %&quot;); plt.xlabel(&quot;vocab size&quot;)<br><br>plt.tight_layout(); plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vx9fJ3AG8-Lfa3XMmItYjg.png" /></figure><pre>VOCAB_SIZE = 4000<br><br>CORPUS_FILE = &#39;all_texts.txt&#39;<br>SPECIAL_TOKENS = [&#39;[PAD]&#39;, &#39;[UNK]&#39;, &#39;[BOS]&#39;, &#39;[EOS]&#39;,&#39;[SEP]&#39;]<br><br>with open(CORPUS_FILE, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:<br>    for _, row in train_df.iterrows():<br>        f.write(str(row[&#39;target_txt&#39;]) + &#39; &#39; + str(row[&#39;input_txt&#39;]) + &#39;\n&#39;)<br><br>from tokenizers import Tokenizer<br>from tokenizers.models import BPE<br>from tokenizers.pre_tokenizers import Whitespace<br>from tokenizers.trainers import BpeTrainer<br>from tokenizers.processors import TemplateProcessing<br><br># Initialize and train<br>tokenizer = Tokenizer(BPE(unk_token=&#39;[UNK]&#39;))<br>tokenizer.pre_tokenizer = Whitespace()<br>trainer = BpeTrainer(vocab_size=VOCAB_SIZE, special_tokens=SPECIAL_TOKENS)<br>tokenizer.train([CORPUS_FILE], trainer)<br><br># 3) Configure post-processing, padding &amp; truncation ------------------<br>pad_id = tokenizer.token_to_id(&#39;[PAD]&#39;)<br>unk_id = tokenizer.token_to_id(&#39;[UNK]&#39;)<br>bos_id = tokenizer.token_to_id(&#39;[BOS]&#39;)<br>eos_id = tokenizer.token_to_id(&#39;[EOS]&#39;)<br>sep_id = tokenizer.token_to_id(&#39;[SEP]&#39;)<br><br># Add BOS/EOS around single sequences<br>tokenizer.post_processor = TemplateProcessing(<br>    single=&#39;[BOS] $A [SEP]&#39;,<br>    pair=&#39;[BOS] $A [SEP] $B [EOS]&#39;,<br>    special_tokens=[(&#39;[BOS]&#39;, bos_id), (&#39;[EOS]&#39;, eos_id),(&#39;[SEP]&#39;, sep_id)],<br>)</pre><pre># ------------------------------------------------------------<br># 0)  Make sure `tok` points to the FINAL tokenizer<br>#     → trained on the full corpus with your chosen vocab_size<br># ------------------------------------------------------------<br>tok = tokenizer          # whatever variable you use<br><br># ------------------------------------------------------------<br># 1)  Get token counts for every example<br>#     (here: concatenate summary + dialogue; split if you want)<br># ------------------------------------------------------------<br>lens = []<br><br>for s, d in tqdm(zip(train_df[&quot;target_txt&quot;], train_df[&quot;input_txt&quot;]),<br>                 total=len(train_df)):<br>    txt   = f&quot;{s} {d}&quot;<br>    ids   = tok.encode(txt).ids<br>    lens.append(len(ids))<br><br>lens = np.array(lens)<br><br># ------------------------------------------------------------<br># 2)  Print key stats<br># ------------------------------------------------------------<br>def pct(x): return np.percentile(lens, x)<br><br>print(f&quot;Total samples    : {len(lens):,}&quot;)<br>print(f&quot;Min / Max tokens : {lens.min()} / {lens.max()}&quot;)<br>print(f&quot;Mean ± std       : {lens.mean():.1f} ± {lens.std():.1f}&quot;)<br>print(&quot;--- percentiles (tokens) ---&quot;)<br>for p in (50, 90, 95, 98, 99):<br>    print(f&quot;{p:&gt;3}% : {pct(p):.0f}&quot;)<br><br># ------------------------------------------------------------<br># 3)  Quick histogram    (no seaborn, single plot, no colors set)<br># ------------------------------------------------------------<br>plt.hist(lens, bins=50)<br>plt.xlabel(&quot;tokens per example&quot;)<br>plt.ylabel(&quot;count&quot;)<br>plt.title(&quot;Tokenised length distribution&quot;)<br>plt.show()</pre><p>100%|██████████| 73988/73988 [00:07&lt;00:00, 10556.69it/s]<br>Total samples : 73,988<br>Min / Max tokens : 11 / 368<br>Mean ± std : 110.5 ± 29.4<br> — — percentiles (tokens) — -<br> 50% : 106<br> 90% : 145<br> 95% : 178<br> 98% : 202<br> 99% : 214</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*8iThuPrxa905yC7w9qZRIg.png" /></figure><pre>BATCH_SIZE = 32<br>MAX_LEN = int(pct(p))<br><br># 0) Configure your tokenizer *once* at startup, not per-example<br>tokenizer.enable_truncation(<br>    max_length=MAX_LEN<br>)<br><br>tokenizer.enable_padding(<br>    pad_id=pad_id,<br>    pad_token=&#39;[PAD]&#39;,<br>    length=MAX_LEN<br>)<br><br>def encode_text(texts, max_length=MAX_LEN):<br>    encodings = tokenizer.encode(texts)<br>    return np.array(encodings.ids, dtype=np.int32)<br><br># 1) encode_pair → return a NumPy array<br>def encode_pair(text_a: str, text_b: str) -&gt; np.ndarray:<br>    enc = tokenizer.encode(text_a, text_b)<br>    return np.array(enc.ids, dtype=np.int32)   # shape: [MAX_LEN]<br><br>def encode_example(text: str, summary: str):<br>    ids = encode_pair(text, summary)           # np.ndarray, shape=[MAX_LEN]<br>    labels = np.concatenate([ids[1:], [pad_id]])  # shape=[MAX_LEN]<br><br>    # find SEP<br>    sep_idxs = np.where(labels == sep_id)[0]<br>    sep_pos = int(sep_idxs[0]) if sep_idxs.size else len(ids)<br><br>    # build base mask: 1 only for positions &gt; sep_pos AND not PAD<br>    positions = np.arange(len(labels))<br>    base_mask = (positions &gt; sep_pos).astype(np.float32) * (labels != pad_id).astype(np.float32)<br><br>    return ids, labels.astype(np.int32), base_mask<br><br># ── 0. do *all* tokenisation once ──────────────────────────<br>triples = [encode_example(t, s) for (t, s) in text_pairs]   # Python loop, done **once**<br>ids, labels, masks = map(lambda k: tf.constant(np.stack(k, 0)),<br>                         zip(*triples))                      # shapes [N, MAX_LEN]<br><br># ── 1. build the purely-TF dataset ─────────────────────────<br>ds = (<br>    tf.data.Dataset.from_tensor_slices(<br>        {&quot;input_ids&quot;: ids, &quot;labels&quot;: labels, &quot;loss_mask&quot;: masks}<br>    )<br>    .shuffle(len(text_pairs))<br>    .batch(BATCH_SIZE)<br>    .prefetch(tf.data.AUTOTUNE)<br>)</pre><p>In training we need appropriate loss to guide the model for proper ouput.</p><blockquote>Train the model to generate a <strong>summary</strong>, not repeat or memorize the input.<br>So the <strong>loss</strong> should be computed <strong>only on the summary part</strong> of the sequence.</blockquote><p>Let’s say your example text is:</p><pre>Input Text: &quot;A man on Moon!&quot;<br>Summary:    &quot;Historic event.&quot;</pre><p>Tokenized Input for the Model by concatenate both into a <strong>single sequence</strong> during training:</p><pre>INPUT_IDs = [&lt;BOS&gt;, A, man, on, Moon, !, &lt;SEP&gt;, Historic, event, ., &lt;EOS&gt;]</pre><p><strong>LABEL_IDs (Target)</strong> = shifted version for teacher forcing:</p><pre>LABEL_IDs = [A, man, on, Moon, !, &lt;SEP&gt;, Historic, event, ., &lt;EOS&gt;]</pre><ul><li>The shift is required so that at timestep t, the model predicts token t+1.</li></ul><blockquote>Loss Mask:</blockquote><blockquote>We <strong>don’t want the model to learn to regenerate the input</strong>, only the summary.</blockquote><p>So we use a loss mask:</p><pre>LOSS_MASK = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]  # Only for the summary and &lt;EOS&gt;</pre><p>This tells the model:</p><blockquote>“Only calculate loss on the summary tokens — ignore the input and the separator.”</blockquote><h4>Why This Matters</h4><ul><li>Without masking, the model might waste capacity trying to predict the input tokens (which it already knows).</li><li>The mask forces it to focus <strong>only on learning to generate summaries</strong>.</li></ul><p>During <strong>inference</strong>, we only pass in:</p><pre>[&lt;BOS&gt;, A, man, on, Moon, !, &lt;SEP&gt;]</pre><p>and let the model generate:</p><pre>Historic event . &lt;EOS&gt;</pre><blockquote>Training Part</blockquote><h4>Transformers Are Deep and Sensitive</h4><ul><li>Transformers have <strong>lots of layers</strong>, residual connections, and <strong>layer normalization</strong>.</li><li>A large learning rate early on causes <strong>exploding gradients</strong> and destabilizes training.</li><li>A tiny learning rate makes training slow or ineffective.</li></ul><p>→ <strong>We need to control learning rate carefully</strong>, especially in early and late training.</p><h4>Phase 1: Warmup (Start Small, Then Increase)</h4><ul><li>Start with a very <strong>small learning rate</strong> (e.g., 1e-6)</li><li>Gradually increase over the first <strong>few thousand steps</strong></li><li>Helps avoid divergence when model weights are untrained</li></ul><h4>Phase 2: Decay (Reduce LR Over Time)</h4><p>After warmup, learning rate decays — often:</p><ul><li><strong>Inverse square root decay</strong></li><li><strong>Cosine decay</strong></li><li><strong>Exponential decay</strong></li></ul><p>As training progresses, we want to <strong>fine-tune</strong> the weights, not make big jumps. Smaller LRs allow more stable convergence.</p><pre>WARM_FRAC   = 0.1      # keep the fast ramp-up<br>DECAY_RATE  = 4<br>LR_FLOOR    = 1e-6<br>LR_PEAK_DESIRED = 8e-4     # choose 8e-4 or 9e-4<br>EPOCHS = 20<br><br># pre-compute the scale that gives that peak<br>num_steps     = EPOCHS * len(text_pairs) // BATCH_SIZE<br>warmup_steps  = int(num_steps * WARM_FRAC)<br>current_peak  = 1.0 / tf.sqrt(tf.cast(d_model * warmup_steps, tf.float32))<br>LR_SCALE      = LR_PEAK_DESIRED / current_peak.numpy()<br><br>@tf.keras.utils.register_keras_serializable()   # so it can round-trip in SavedModel/H5<br>class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):<br>    def __init__(self, d_model, total_steps=num_steps,<br>                 warmup_frac=WARM_FRAC, decay_rate=DECAY_RATE,<br>                 lr_scale=LR_SCALE):<br>        super().__init__()<br>        self.d_model      = tf.cast(d_model, tf.float32)<br>        self.warmup_steps = tf.cast(int(total_steps * warmup_frac), tf.float32)<br>        self.decay_rate   = decay_rate<br>        self.decay_steps  = tf.cast(total_steps, tf.float32)<br>        # self.lr_scale     = tf.cast(lr_scale, tf.float32)<br><br>    def __call__(self, step):<br>        step  = tf.cast(step, tf.float32)<br>        arg1  = tf.math.rsqrt(step)<br>        arg2  = step * tf.math.pow(self.warmup_steps, -1.5)<br>        warm  = tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)<br>        decay = tf.math.exp(-self.decay_rate *<br>                            tf.maximum(step - self.warmup_steps, 0.) /<br>                            self.decay_steps)<br>        lr = warm * decay #* self.lr_scale <br>        return tf.maximum(lr, LR_FLOOR)<br><br>    # ----------  NEW  ----------<br>    def get_config(self):<br>        return {<br>            &quot;d_model&quot;:      int(self.d_model.numpy()),   # cast back to Python types<br>            &quot;total_steps&quot;:  int(self.decay_steps.numpy()),<br>            &quot;warmup_frac&quot;:  float(self.warmup_steps.numpy() / self.decay_steps.numpy()),<br>            &quot;decay_rate&quot;:   self.decay_rate,<br>            # &quot;lr_scale&quot;:     float(self.lr_scale.numpy()),<br>        }<br><br>    @classmethod<br>    def from_config(cls, config):<br>        return cls(**config)<br>    <br>learning_rate = CustomSchedule(d_model)<br><br>optimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9, clipnorm=1.0)<br>    <br>temp_learning_rate_schedule = CustomSchedule(d_model)<br><br>plt.plot(temp_learning_rate_schedule(tf.range(num_steps, dtype=tf.float32)))<br>plt.ylabel(&quot;Learning Rate&quot;)<br>plt.xlabel(&quot;Train Step&quot;)<br><br>print(temp_learning_rate_schedule(tf.range(num_steps, dtype=tf.float32)))</pre><p>tf.Tensor(<br>[1.000000e-06 1.000000e-06 1.000000e-06 … 7.943662e-06 7.942890e-06<br> 7.942117e-06], shape=(46242,), dtype=float32)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*rDSFrSjwtizJ_IRk2QuVlw.png" /></figure><pre># 2) Repack your dataset for .fit()<br># Each element becomes (x, y, sample_weight)<br>ds_for_fit = ds.map(lambda b: (           # ds originally yields dicts<br>    b[&quot;input_ids&quot;],        # x<br>    b[&quot;labels&quot;],           # y_true<br>    b[&quot;loss_mask&quot;]         # sample_weight: 1.0 on summary tokens, 0 elsewhere<br>))<br><br># 3) Compile with a standard sparse‐CE loss and let Keras use sample weights<br>model.compile(<br>    optimizer=optimizer,<br>    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=&quot;none&quot;),<br>    metrics=[&quot;sparse_categorical_accuracy&quot;]<br>)<br><br># Model&#39;s output (logits) is: logits = self.final_layer(x)  # (batch_size, target_len, target_vocab_size).<br># This is a tensor of logits, where for each position in the sequence, you have a score for every possible token in your vocabulary.<br># Because labels are integer token IDs (e.g., [10, 54, 3, 0, 0]) and not one-hot encoded vectors (e.g., [[0..1..0], [0..1..0], ...]), SparseCategoricalAccuracy is the appropriate metric. <br># It correctly compares the integer label at each timestep with the class that has the highest logit output by the model for that timestep.<br><br># Build callbacks<br>callbacks = [<br>    EarlyStopping(monitor=&quot;loss&quot;, patience=3,<br>                  restore_best_weights=True, verbose=1),<br>    ModelCheckpoint(<br>        filepath=&quot;best_summary.keras&quot;,        # or &quot;best_summary.h5&quot;<br>        monitor=&quot;loss&quot;,<br>        save_best_only=True,<br>        verbose=1             # full model (weights + optimizer + LR schedule)<br>    )<br>]<br><br># 4) Fit!  Keras will print epoch/step progress by default<br>history = model.fit(<br>    ds_for_fit,<br>    epochs=EPOCHS,<br>    callbacks=callbacks,<br>    verbose=1    # 1 = progress bar, loss &amp; acc per epoch<br>)<br><br>&#39;&#39;&#39;<br>Epoch 1/20<br>2025-06-03 17:07:28.547068: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:117] Plugin optimizer for device_type GPU is enabled.<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 204ms/step - loss: 0.5447 - sparse_categorical_accuracy: 0.0128<br>Epoch 1: loss improved from inf to 0.48176, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m475s[0m 204ms/step - loss: 0.5447 - sparse_categorical_accuracy: 0.0128<br>Epoch 2/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 195ms/step - loss: 0.3736 - sparse_categorical_accuracy: 0.0387<br>Epoch 2: loss improved from 0.48176 to 0.35755, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m452s[0m 195ms/step - loss: 0.3736 - sparse_categorical_accuracy: 0.0387<br>Epoch 3/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 198ms/step - loss: 0.3092 - sparse_categorical_accuracy: 0.0495<br>Epoch 3: loss improved from 0.35755 to 0.30344, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m458s[0m 198ms/step - loss: 0.3092 - sparse_categorical_accuracy: 0.0495<br>Epoch 4/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 198ms/step - loss: 0.2653 - sparse_categorical_accuracy: 0.0571<br>Epoch 4: loss improved from 0.30344 to 0.26387, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m457s[0m 198ms/step - loss: 0.2653 - sparse_categorical_accuracy: 0.0571<br>Epoch 5/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 194ms/step - loss: 0.2348 - sparse_categorical_accuracy: 0.0635<br>Epoch 5: loss improved from 0.26387 to 0.23369, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m449s[0m 194ms/step - loss: 0.2348 - sparse_categorical_accuracy: 0.0635<br>Epoch 6/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 195ms/step - loss: 0.2106 - sparse_categorical_accuracy: 0.0690<br>Epoch 6: loss improved from 0.23369 to 0.21018, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m450s[0m 195ms/step - loss: 0.2106 - sparse_categorical_accuracy: 0.0690<br>Epoch 7/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 195ms/step - loss: 0.1945 - sparse_categorical_accuracy: 0.0726<br>Epoch 7: loss improved from 0.21018 to 0.19466, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m450s[0m 195ms/step - loss: 0.1945 - sparse_categorical_accuracy: 0.0726<br>Epoch 8/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 195ms/step - loss: 0.1830 - sparse_categorical_accuracy: 0.0744<br>Epoch 8: loss improved from 0.19466 to 0.18467, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m451s[0m 195ms/step - loss: 0.1830 - sparse_categorical_accuracy: 0.0744<br>Epoch 9/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 196ms/step - loss: 0.1764 - sparse_categorical_accuracy: 0.0756<br>Epoch 9: loss improved from 0.18467 to 0.17765, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m453s[0m 196ms/step - loss: 0.1764 - sparse_categorical_accuracy: 0.0756<br>Epoch 10/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 199ms/step - loss: 0.1712 - sparse_categorical_accuracy: 0.0767<br>Epoch 10: loss improved from 0.17765 to 0.17246, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m459s[0m 199ms/step - loss: 0.1712 - sparse_categorical_accuracy: 0.0767<br>Epoch 11/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 201ms/step - loss: 0.1669 - sparse_categorical_accuracy: 0.0773<br>Epoch 11: loss improved from 0.17246 to 0.16853, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m464s[0m 201ms/step - loss: 0.1669 - sparse_categorical_accuracy: 0.0773<br>Epoch 12/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 201ms/step - loss: 0.1651 - sparse_categorical_accuracy: 0.0776<br>Epoch 12: loss improved from 0.16853 to 0.16572, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m465s[0m 201ms/step - loss: 0.1651 - sparse_categorical_accuracy: 0.0776<br>Epoch 13/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 201ms/step - loss: 0.1631 - sparse_categorical_accuracy: 0.0784<br>Epoch 13: loss improved from 0.16572 to 0.16335, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m465s[0m 201ms/step - loss: 0.1631 - sparse_categorical_accuracy: 0.0784<br>Epoch 14/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 201ms/step - loss: 0.1605 - sparse_categorical_accuracy: 0.0783<br>Epoch 14: loss improved from 0.16335 to 0.16158, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m465s[0m 201ms/step - loss: 0.1605 - sparse_categorical_accuracy: 0.0783<br>Epoch 15/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 201ms/step - loss: 0.1593 - sparse_categorical_accuracy: 0.0785<br>Epoch 15: loss improved from 0.16158 to 0.16021, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m465s[0m 201ms/step - loss: 0.1593 - sparse_categorical_accuracy: 0.0785<br>Epoch 16/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 200ms/step - loss: 0.1584 - sparse_categorical_accuracy: 0.0787<br>Epoch 16: loss improved from 0.16021 to 0.15912, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m462s[0m 200ms/step - loss: 0.1584 - sparse_categorical_accuracy: 0.0787<br>Epoch 17/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 196ms/step - loss: 0.1573 - sparse_categorical_accuracy: 0.0789<br>Epoch 17: loss improved from 0.15912 to 0.15815, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m455s[0m 197ms/step - loss: 0.1573 - sparse_categorical_accuracy: 0.0789<br>Epoch 18/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 197ms/step - loss: 0.1572 - sparse_categorical_accuracy: 0.0787<br>Epoch 18: loss improved from 0.15815 to 0.15758, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m455s[0m 197ms/step - loss: 0.1572 - sparse_categorical_accuracy: 0.0787<br>Epoch 19/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 197ms/step - loss: 0.1564 - sparse_categorical_accuracy: 0.0789<br>Epoch 19: loss improved from 0.15758 to 0.15695, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m455s[0m 197ms/step - loss: 0.1564 - sparse_categorical_accuracy: 0.0789<br>Epoch 20/20<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 197ms/step - loss: 0.1564 - sparse_categorical_accuracy: 0.0789<br>Epoch 20: loss improved from 0.15695 to 0.15656, saving model to best_summary.keras<br>[1m2313/2313[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m455s[0m 197ms/step - loss: 0.1564 - sparse_categorical_accuracy: 0.0789<br>Restoring model weights from the end of the best epoch: 20.<br><br>&#39;&#39;&#39;</pre><blockquote>Inference Part</blockquote><pre>def encode_dialogue(text: str, max_len: int = MAX_LEN) -&gt; tf.Tensor:<br>    &quot;&quot;&quot;<br>    Returns [BOS] dialogue [EOS] *without* any padding.<br>    &quot;&quot;&quot;<br>    tokenizer.no_padding()                         # turn padding off<br>    tokenizer.enable_truncation(max_length=max_len)<br>    ids = tokenizer.encode(text).ids               # already BOS/EOS<br>    return tf.constant(ids, tf.int32)              # 1-D tensor<br><br><br>def generate_summary(<br>    dialogue_ids: tf.Tensor,        # [BOS] … [EOS]  (no pads)<br>    model: tf.keras.Model,<br>    max_new: int = 120,<br>    temperature: float = 0.1<br>) -&gt; tf.Tensor:<br>    &quot;&quot;&quot;<br>    Produce [BOS] dialogue [SEP] summary … [EOS]<br>    &quot;&quot;&quot;<br>    prompt = tf.concat([dialogue_ids[:-1], [sep_id]], 0)[None, :]  # add batch dim<br><br>    for _ in range(max_new):<br>        if prompt.shape[1] &gt; MAX_LEN:                # keep within PE range<br>            break<br><br>        logits  = model.predict(prompt,verbose=False)[:, -1, :] / temperature<br>        next_id = tf.random.categorical(logits, 1, dtype=tf.int32)<br>        prompt  = tf.concat([prompt, next_id], 1)<br><br>        if next_id[0, 0] == eos_id:<br>            break<br><br>    return tf.squeeze(prompt, 0)<br><br>def display_text_and_summary(dialogue: str, target: str, model):<br>    &quot;&quot;&quot;<br>    Given a raw dialogue string and a summary model, this function:<br>      1. Encodes the dialogue into token IDs.<br>      2. Generates [BOS] dialogue [SEP] summary [EOS].<br>      3. Splits at [SEP], decodes each part, and prints:<br>         - &quot;Text: &lt;original dialogue…&gt;&quot;<br>         - &quot;Summary: &lt;generated summary…&gt;&quot;<br>    &quot;&quot;&quot;<br>    # 1. Encode the dialogue (adds [BOS] … [EOS])<br>    dlg_ids = encode_dialogue(clean_text(dialogue))<br><br>    # 2. Generate the full sequence [BOS] dialogue [SEP] summary [EOS]<br>    full_ids = generate_summary(dlg_ids, model)<br><br>    # 3. Convert to a plain Python list so we can find sep_id<br>    full_ids_list = full_ids.numpy().tolist()<br><br>    # 4. Find the position of sep_id<br>    sep_index = full_ids_list.index(sep_id)<br><br>    # 5. Split into dialogue_part and summary_part<br>    dialogue_part = full_ids_list[:sep_index]<br>    summary_part  = full_ids_list[sep_index + 1:]  # skip the sep_id itself<br><br>    # 6. Decode each slice<br>    text_str    = decode_token_ids(dialogue_part)<br>    summary_str = decode_token_ids(summary_part)<br><br>    # 7. Print on two lines<br>    print(&quot;\n Text:&quot;, text_str)<br>    print(&quot;\n Genrated Summary:&quot;, summary_str)<br>    print(&quot;\n Original Summary:&quot;, target)</pre><pre><br>for j in range(5):<br>    print(j)<br>    dialogue = df1[&#39;input_txt&#39;][j]<br>    summary = df1[&#39;target_txt&#39;][j]<br>    display_text_and_summary(dialogue, summary, model)<br>    print(&#39;----------------&#39;)<br><br>&#39;&#39;&#39;<br><br>0<br><br> Text: [BOS] the cbi on saturday booked four former officials of sy nd ic ate bank and six others for che ating , for ger y , criminal con spir acy and ca using 20 9 crore loss to the state run bank . the accused had avail ed home lo ans and credit from sy nd ic ate bank on the bas is of for ged and f ab ric ated documents . these funds were fra ud ul ent ly transfer red to the companies owned by the accused person s .<br><br> Genrated Summary: 4 ex officials booked for che ating bank officials [EOS]<br><br> Original Summary: 4 ex-bank officials booked for cheating bank of ₹209 crore<br>----------------<br>1<br><br> Text: [BOS] chief justice j s k he har has said the supreme court will go paper less in six to seven months in a bid to save funds and make the jud ic i ary e co friend ly . he further said the ap ex court will colle ct all the records electron ically from the lower cour ts and the high cour ts so that there is no need to file hard cop ies .<br><br> Genrated Summary: sc to go paper less in 6 months sc [EOS]<br><br> Original Summary: Supreme Court to go paperless in 6 months: CJI<br>----------------<br>2<br><br> Text: [BOS] at least three people were killed , including a police man , while 30 others were w ound ed on saturday evening in two explos ions in sy l h et , bangladesh . the explos ions were target ted at people and police officials who were witness ing an over 30 hour long gun fight between ex tre m ists and comm and os . earlier on friday , a man had b low n himself up in front of a check point near dha ka airport .<br><br> Genrated Summary: 3 killed in bangladesh , 30 injured in bangladesh [EOS]<br><br> Original Summary: At least 3 killed, 30 injured in blast in Sylhet, Bangladesh<br>----------------<br>3<br><br> Text: [BOS] muk esh am ban i led reliance indust ries ril was bar red from trad ing in fut ures market for a year over stake sale in reliance pet role um r pl . in 200 7 , ril sold 4 . 1 stake in r pl , but shares were first 39 short sold 39 in fut ures market to avoid a fall in r pl sto cks . short sale means selling shares with plans to buy them back later at lower prices .<br><br> Genrated Summary: reliance indust ries ril bar red from trad ing in reliance pet role [EOS]<br><br> Original Summary: Why has Reliance been barred from trading in futures?<br>----------------<br>4<br><br> Text: [BOS] a new trailer for the upcoming super hero film 39 justice league 39 was released on saturday . based on the d c com ics super hero team , the film stars ben aff le ck as 39 bat man 39 , gal g ad ot as 39 wonder woman 39 , ez ra m ill er as 39 the fl ash 39 and jason mom o a as 39 a qu aman 39 . directed by z ack s ny der , the film is scheduled to release on november 17 , 2017 .<br><br> Genrated Summary: new trailer of 39 justice league 39 released [EOS]<br><br> Original Summary: New trailer of &amp;#39;Justice League&amp;#39; released<br><br>----------------<br>5<br><br> Text: [BOS] at least 20 people were reportedly injured after over 30 blast s oc cur red at an or d n ance fact ory in mad hya pradesh 39 s jab al pur on saturday evening . nearly 50 fire tend ers were ru sh ed to the or d n ance fact ory kh amar ia of k to res c ue the tra pped victims . the access to the fact ory was rest ric ted after the army personnel took over the res c ue operations .<br><br> Genrated Summary: 20 injured in mp 39 s jab al pur on fl ash [EOS]<br><br> Original Summary: 30 blasts occur at ordnance factory in MP,  20 injured <br>----------------<br><br>&#39;&#39;&#39;</pre><p>Some more results :</p><pre><br>3809<br><br> Text: [BOS] tai wan ese manufact uring major , which asse m bles apple 39 s i phones , has ac quired a major ity 5 4 . 5 stake in soft bank 39 s asia capital unit for over 4 , 000 crore . after complet ion of the deal , the unit will no longer be a soft bank af fil i ate and fo x con n will become 34 the decision maker on invest ments 34 for the fund . fo x con n will also partner with soft bank for the 100 billion 39 vision fund 39 .<br><br> Genrated Summary: apple ceo buy s 5 4 . 5 4 stake in soft bank [EOS]<br><br> Original Summary: iphone assembler foxconn buys 54.5 stake in softbank unit<br>----------------<br>61416<br><br> Text: [BOS] person1 the sk ir t looks beautiful . can i try it on ? person2 of course . person1 well , i think this one is a little too small . would you please bring me a big ger one ? person2 i am sorry the lar ger ones are out of stock now . but you might be luck y at our br anch .<br><br> Genrated Summary: person1 tries on a sk ir t and person2 recommends a big ger one . [EOS]<br><br> Original Summary: person1 tries on a skirt and wants a bigger one, but it s sold out.<br>----------------<br>16225<br><br> Text: [BOS] the un general assembly on december 11 , 19 46 vot ed to estab lish the united nations international children 39 s emergency fund un ice f , to bring life sa ving aid and prote ction to children in the after ma th of world war ii . un ice f gre w into a v oc al adv oc ate of children 39 s rights during the 19 70 s and is currently working across 19 0 countries for child rights .<br><br> Genrated Summary: un ice f 39 s emergency fund un ice f to 5 nations [EOS]<br><br> Original Summary: unicef founded on this day in 1946<br>----------------<br>69860<br><br> Text: [BOS] peter i need to take care of my little nie ce during the weekend peter and i have no idea how to spend time with kids jor dan how old is she ? peter 4 ma the w sorry mate , i have no experience jor dan kids this age tend to be very active jor dan maybe you can play ball with her ? peter sounds like a good idea<br><br> Genrated Summary: peter wants to take care of his little nie ce during the weekend . [EOS]<br><br> Original Summary: peter needs to take care of his little niece during the weekend, but he doesn t know how to spend time with her. jordan suggested playing ball with her.<br>----------------<br>69903<br><br> Text: [BOS] ter ry li a , are you in du bl in ? li a yes .... so bo red tom but why ? li a why not ? ky lie aren t we sup posed do be in cam bridge ? li a we re sup posed to res ide there jenny true , this is a general rule jenny but does any body control it ? tom i think that the super vis or is in charge of controll ing it jenny my super vis or has never asked me where i live tom but you re always at the college , more vis ible than any body , more than the de an himself jenny true , hahaha li a i don t like it do much there , as you know ter ry so don t compla in you re bo red li a p<br><br> Genrated Summary: li a is in du bl in for a conference . jenny is in cam bridge . he s in cam bridge . [EOS]<br><br> Original Summary: lia is bored in dublin although students are supposed to live in cambridge. supervisors should control students residence. jenny s residence has never been questioned because she spends a lot of time at college.<br>----------------<br>11286<br><br> Text: [BOS] the central information commission has pul led up prime minister s office p mo for not provid ing any information if 39 jan a gan a man a 39 was the country 39 s national an them and 39 v and e mat ar am 39 , the national song . the commission has now directed the p mo to initi ate fresh ef for ts to find out hist or ical fac ts about 39 jan a gan a man a 39 and 39 v and e mat ar am 39 , and the stat us ac cor ded to them .<br><br> Genrated Summary: don 39 t give no info on national an them , e mat ar am 39 s national an them [EOS]<br><br> Original Summary: centre gave no reply to rti if jana gana was national anthem<br>----------------<br>13419<br><br> Text: [BOS] australia defeated pakistan by an innings and 18 runs in the second test at mel bour ne cricket ground , taking an un assa il able 2 0 lead in the three match test series . in rep ly to australia 39 s 6 24 8 d , pakistan were dis missed for 16 3 in the second innings with mit ch ell star c pick ing up four wickets . this was pakistan 39 s fifth straight test loss , their joint most success ive defeat s .<br><br> Genrated Summary: australia defeat pakistan by an innings in 2nd test [EOS]<br><br> Original Summary: pakistan suffer fifth consecutive test match defeat<br>----------------<br>68810<br><br> Text: [BOS] ern ie im fed up with p pl j ere my then y ru te x ting me ern ie cause y know ern ie your special in a way j ere my lol du de so gay<br><br> Genrated Summary: p pl j ere my is im fed up with p pl j ere my . [EOS]<br><br> Original Summary: ernie is fed up with people, but considers jeremy his special friend.<br>----------------<br>12204<br><br> Text: [BOS] according to government data , 80 of the farmers who committed suicide in 2015 due to deb t or bank rup t cy had taken lo ans from banks and registered mic r of in ance institut ions . only about 10 of those farmers had taken lo ans from money l end ers , the data added . this is the first time n cr b has categ or ised such suic ides by farmers based on the sour ce of lo ans .<br><br> Genrated Summary: 80 of farmers committed to deb t cy in 2015 [EOS]<br><br> Original Summary: 80 debt related farmer suicides due to bank loans ncrb<br>----------------<br>19429<br><br> Text: [BOS] the government on monday allowed farmers to purch ase seed s with old demonet ised 500 currency notes from cent res or and out lets belong ing to the central government or the state government . to support farmers for the current ra bi cro p , the seed s will be provid ed to them from the p sus , seed s corpor ations , ag ric ul tur al univers ities and the ic ar , on show ing a val id pro of of ident ity .<br><br> Genrated Summary: govt allows farmers to buy old 500 notes from govt [EOS]<br><br> Original Summary: govt allows farmers to buy seeds with old 500 notes<br>----------------<br>45265<br><br> Text: [BOS] the government has decided to set up six new i its , hr d minister sm r iti ir ani said in a written rep ly in the parliament on monday . i its will be set up at goa , t ir up ati andhra pradesh , pal ak k ad kerala , bh il ai ch h att is gar h , khan pur nag ro ta j amp k and d har w ad karnataka . a cost of 1 , 4 11 . 80 crore will be in cur red between 2015 16 and 201 8 19 to run these institut ions .<br><br> Genrated Summary: govt to set up 6 new i its in parliament [EOS]<br><br> Original Summary: govt to set up six new iits smriti irani<br>----------------<br>24801<br><br> Text: [BOS] a relig ious government body in malays ia has directed e ater ies selling hot do gs to ren ame their products or ris k being denied hal al cert ification . the malays ian islamic development department director sir aj uddin su ha ime e said the name might lead to 34 conf us ion 34 and 34 do gs are considered un clean 34 in islam . the rul ing was called 34 st up id and back ward 34 by tourism and c ulture minister n az ri az iz .<br><br> Genrated Summary: relig ious govt body body den ies selling hot do gs [EOS]<br><br> Original Summary: hot dogs must be renamed, says malaysian religious govt body<br>----------------<br>51022<br><br> Text: [BOS] qu ant ico ref le ctions 39 , the te as er of the re new ed first season of the priyanka chopra starrer american television series 39 qu ant ico 39 , was youtube 39 s n in th most vie wed video in india on friday . the ext ended epis od es from the thr ill er series will premi ere on march 6 . the te as er posted on the video sharing platform on february 28 has gar ner ed over 13 . 0 2 lakh view s so far . n<br><br> Genrated Summary: 39 qu ant ico 39 te as er of priyanka 39 s new ed 1st season [EOS]<br><br> Original Summary: 39 quantico 39 teaser in youtube 39 s most viewed today<br>----------------<br>26639<br><br> Text: [BOS] e commerce major amazon india chief amit agar wal said the firm has ac com pl ished in three years what ri v als had n t in 10 , despite launch ing earlier and acqu ir ing many companies . 34 we ve grow n 13 5 ... year over year in every quarter this year , against fl at growth for others , 34 he said . this follow s flipkart ceo b in ny bans al 39 s com ments that amazon mis jud ged customers needs in the fest ive sale .<br><br> Genrated Summary: amazon india 39 s biggest gain in 3 years in 10 yrs [EOS]<br><br> Original Summary: amazon has done in 3yrs what rivals couldn 39 t in 10 agarwal<br>----------------<br>24251<br><br> Text: [BOS] former brazil ian football er p el holds the guinness world record for the most number of goals scored by an individ ual in a spec ified period . the forward scored 1 , 27 9 goals from 7 september 19 5 6 to 1 october 197 7 in 1 , 36 3 games . p el , who was among st time 39 s 100 most infl u ential people of the 20 th century , was born on 23 october 19 40 .<br><br> Genrated Summary: p el holds most number of goals in a day [EOS]<br><br> Original Summary: pel holds guinness world record for most career goals<br>----------------<br>3414<br><br> Text: [BOS] a british air ways flight from london was delay ed after cre w inform ed the passengers they couldn 39 t take off due to a mou se spot ting . the cre w jok ed the mou se couldn 39 t enter the us air space without a pass port , and that they need ed a new plane , which led to a four hour delay . british air ways apolog ised , saying passengers were happy to be on a mou se free aircraft .<br><br> Genrated Summary: british air ways flight delay ed due to cre w [EOS]<br><br> Original Summary: mouse delays british airways flight by 4 hours<br>----------------<br>53981<br><br> Text: [BOS] delhi deputy chief minister man ish s is odi a and several aap leaders on sunday joined the p w d t ask force form ed by the government to clean up pil ing gar b age across the capital ow ing to the mc d workers 39 strike . the strike over non payment of du es ent ered the fifth day and saw a series of political allegations being trad ed between bjp and aap leaders .<br><br> Genrated Summary: delhi deputy cm s is odi a to clean up pil ing delhi [EOS]<br><br> Original Summary: aap leaders join task force to clean delhi<br>----------------<br>9773<br><br> Text: [BOS] a jun ior engine er in assam 39 s nag a on district was allegedly forced to touch bjp mla d im bes war d as 39 feet for remo ving the leg is l ator 39 s car which was block ing the road to the office . the act was caught on camera by the media present there . in the video , the bjp mla is seen sc old ing the engine er , who then touch es his feet and apolog ises .<br><br> Genrated Summary: assam mla forced to touch bjp mla 39 s car [EOS]<br><br> Original Summary: video shows junior engineer touching bjp mla s feet<br>----------------<br>13530<br><br> Text: [BOS] officers of the central crime station , hyderabad have arrested a director of mus add il al je well ers for allegedly selling gold worth 100 crore to f ic tit ious customers . the je well er used fake names and fake address es on the bill s , according to reports . the arrest was made after the income tax department lo d ged a complaint alleg ing fra ud by the je well er .<br><br> Genrated Summary: mumbai police arrest s fake gold worth 100 crore gold worth 100 crore [EOS]<br><br> Original Summary: jeweller arrested for selling 100 crore gold to fake buyers<br>----------------<br>19920<br><br> Text: [BOS] world number two no v ak d jok o vic on thursday blast ed the chair ump ire fer g us mur phy after being given a 34 time viol ation 34 for break ing the 25 second rule during his at p tour fin als match against david g off in in london . d jok o vic ar gu ed that he should have been given a war ning first and slammed mur phy saying , 34 you have no cl ue about the game . 34<br><br> Genrated Summary: d jok o vic blast s chair ump ire , mur phy chair ump ire [EOS]<br><br> Original Summary: novak djokovic blasts chair umpire at atp tour finals<br>----------------</pre><p>The results are okayish, especially considering the model was trained on a relatively small dataset of 70,000 samples and 4,000 tokens, using a compact transformer with only two layers. We also need to factor in that we’re performing <strong>tokenization</strong> specifically for our dataset and learning the <strong>word embeddings</strong> during the training process. This approach was chosen to demonstrate a <strong>from-scratch implementation</strong>, which is the goal of this blog post.</p><p>Otherwise, utilizing a <strong>pre-trained tokenizer</strong> and <strong>pre-trained word embeddings</strong> would boost performance. In such a scenario, the attention mechanism of the model would primarily need to learn the intricate relationships and contextual dependencies between the already meaningful word representations, rather than starting from scratch to learn the embeddings themselves.</p><p>Feel free to comment for any mistakes you notice.</p><p>Good day and Thank You !</p><p>Credits :</p><ul><li><a href="https://youtube.com/@futuremojo?si=FumqXAUI4bHqxCrp">https://youtube.com/@futuremojo?si=FumqXAUI4bHqxCrp</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c248094e4a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VQ-VAE | Simplistic TensorFlow Implementation from scratch]]></title>
            <link>https://medium.com/@saptarshimt/vq-vae-simplistic-tensorflow-implementation-from-scratch-ccc9fab702e4?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccc9fab702e4</guid>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[vector-quantization]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 07:22:06 GMT</pubDate>
            <atom:updated>2024-08-04T07:22:06.584Z</atom:updated>
            <content:encoded><![CDATA[<p>Vector Quantized Variational Autoencoders (VQ-VAE) are a type of neural network architecture designed for unsupervised learning, particularly effective in tasks like image and audio generation. Here’s a breakdown of its components and how it works:</p><ol><li><strong>Variational Autoencoder (VAE) Basics</strong>:</li></ol><ul><li><strong>Encoder</strong>: Maps input data (e.g., images) to a latent space, producing latent vectors that represent compressed versions of the input.</li><li><strong>Decoder</strong>: Reconstructs the input data from these latent vectors.</li><li><strong>Latent Space Regularization</strong>: Ensures the latent space has desirable properties, typically done by imposing a prior distribution (like a Gaussian distribution). With this regularisation term, we prevent the model to encode data far apart in the latent space and encourage as much as possible returned distributions to “overlap”, satisfying this way the expected continuity and completeness conditions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vgQ6nZEUDEQpF9jV.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1pDLIcI91KniviME.png" /></figure><p><strong>2. Vector Quantization (VQ)</strong>:</p><ul><li>In VQ-VAE, instead of directly using continuous latent vectors, the latent vectors are quantized to a finite set of embeddings.</li><li>This means the continuous latent vectors from the encoder are replaced by the nearest vectors from a predefined codebook (a set of discrete vectors).</li><li>The quantization process introduces a discrete bottleneck, forcing the latent representations to be selected from a limited set of vectors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dE2OMjJ7kYZsg5Gx.png" /></figure><pre>import tensorflow as tf<br>from tensorflow.keras import layers, Model<br>from keras.datasets import mnist, fashion_mnist<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Load data.<br>(x_train, y_train), (x_test, y_test) = mnist.load_data()<br><br># Normalize data.<br>x_test = x_test / np.max(x_train)<br>x_train = x_train / np.max(x_train)<br><br># Add input channel dimension.<br>x_train = x_train.reshape(-1, 28, 28, 1)<br>x_test = x_test.reshape(-1, 28, 28, 1)</pre><h4>Architecture breakdown</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fbqrtlAIOEwP3Yo_.png" /></figure><h4>Defining our Code Blocks</h4><pre>&#39;&#39;&#39; 1. Our Mnist input of shape (60000, 28, 28, 1) is first passed through an encoder block for feature extraction. &#39;&#39;&#39;<br><br>encoder = tf.keras.Sequential([<br>layers.Conv2D(16, kernel_size=4, strides=2, padding=&#39;same&#39;, input_shape=(28,28, 1)),<br>layers.BatchNormalization(),<br>layers.ReLU(),<br>layers.Conv2D(4, kernel_size=4, strides=2, padding=&#39;same&#39;),<br>layers.BatchNormalization(),<br>layers.ReLU(),<br>])<br><br>&#39;&#39;&#39; 2.  The extracted features gets further passed through a pre quant convolution to get desired shape  (60000, 28, 28, D),<br>         where D is equivalent to the Embedding dimension of our CODE BOOK. &#39;&#39;&#39;<br><br>pre_quant_conv = layers.Conv2D(2, kernel_size=1)<br><br>&#39;&#39;&#39; 3.  Lets define our embedding code book vector of total 3 embeddings each of dimension 2. And then initialise some random values(weights to it)&#39;&#39;&#39;<br><br>embedding = layers.Embedding(3,2)<br>_ = embedding(tf.constant([[0, 1, 2]]))<br><br>&#39;&#39;&#39; 4.  after feature extracteion from image gets passed through vector quantize layer  we pass it through post quant convolution for change in last dimension &#39;&#39;&#39;<br><br>post_quant_conv = layers.Conv2D(4, kernel_size=1)<br><br># Commitment Loss Beta<br>beta = 0.2<br><br>&#39;&#39;&#39; 5. Finally the we get ouput image from the Decoder &#39;&#39;&#39;<br><br>decoder = tf.keras.Sequential([<br>layers.Conv2DTranspose(16, kernel_size=4, strides=2, padding=&#39;same&#39;),<br>layers.BatchNormalization(),<br>layers.ReLU(),<br>layers.Conv2DTranspose(1, kernel_size=4, strides=2, padding=&#39;same&#39;),<br>layers.Activation(&#39;tanh&#39;)<br>])</pre><h4>Architecture of our Vector quantization layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FE1YV-Y75ea69Ltd.png" /></figure><h4>The Forward Process</h4><ol><li>Pass the input through encoder and then pre quant conv layer to get desired H<em>W</em>C</li></ol><pre>x = tf.random.normal(shape=(60, 28, 28, 1))<br>encoded_output = encoder(x)<br>quant_input = pre_quant_conv(encoded_output)<br>quant_input.shape. <br><br>output # TensorShape([60, 7, 7, 2])</pre><p>2. Reshape the feature input to (B<em>H</em>W, C) — -&gt; (60 * 7 * 7,2) where 2 represents the same dimension embedding as our code book vector.</p><pre>B,H, W,C = quant_input.shape<br>quant_input = tf.reshape(quant_input, (B*H*W, C))</pre><p>3. Now find the nearest code book embedding for each (B * H * W) input with our code book embedding (3*2). Replace the nearest embedding vector of dimension 2 with our feature input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7ig1NpkoGq4ws0gVK_e7Q.png" /></figure><pre>dist = tf.norm(tf.expand_dims(quant_input, axis=1) - tf.expand_dims(embedding.weights[0], axis=0), axis=-1)<br>quant_output = tf.gather(embedding.weights[0], tf.argmin(dist,axis=1))</pre><h4>Losses</h4><ol><li><strong>Commitment Loss (</strong><strong>commitment_loss)</strong>: This loss is calculated as the mean squared difference between the output of the quantization layer (quant_output) and the input to the quantization layer (quant_input). The tf.stop_gradient function is used to prevent the gradients from flowing into the quant_input.</li><li><strong>Codebook Loss (</strong><strong>codebook_loss)</strong>: This loss is calculated as the mean squared difference between the output of the quantization layer (quant_output) and the input to the quantization layer (quant_input). The tf.stop_gradient function is used to prevent the gradients from flowing into the quant_output.</li><li><strong>Quantization Losses (</strong><strong>quantize_losses)</strong>: This is the total loss for the quantization layer. It&#39;s calculated as the sum of the codebook_loss and the commitment_loss scaled by a factor beta.</li><li><strong>Quantization Output (</strong><strong>quant_output)</strong>: This is the final output of the quantization layer. It&#39;s calculated as the input to the quantization layer (quant_input) plus the difference between the output of the quantization layer (quant_output) and the input to the quantization layer (quant_input), where the difference is stopped from backpropagation using tf.stop_gradient.</li></ol><p>These losses are typically used in Vector Quantized Variational AutoEncoders (VQ-VAE), where the commitment_loss ensures that the encoder commits to the discrete latent representations in the codebook, and the codebook_loss ensures that the codebook adapts to the encoder&#39;s representations. The quantize_losses is the total loss that is minimized during training. The quant_output is the final output of the quantization layer that is used for further processing or decoding.</p><pre>commitment_loss = tf.reduce_mean(tf.square(tf.stop_gradient(quant_output) - quant_input))<br>codebook_loss = tf.reduce_mean(tf.square(quant_output-tf.stop_gradient(quant_input)))<br><br>quantize_losses = codebook_loss + beta*commitment_loss<br><br># reconstruction_loss = tf.reduce_mean(tf.square(data - output))<br># total_loss = reconstruction_loss + quantize_losses</pre><p>5. finally pass through our post conv and encoder block</p><pre>quant_output = quant_input + tf.stop_gradient(quant_output - quant_input)<br>quant_output = tf.reshape(quant_output, (B, H, W, C))<br><br>decoder_input = post_quant_conv(quant_output)<br>output = decoder(decoder_input)<br><br>output.shape<br><br># TensorShape([60, 28, 28, 1])</pre><h4>Putting our entire code in one block and executing it</h4><pre># Load and preprocess the MNIST dataset<br>(x_train, y_train), (x_test, y_test) = mnist.load_data()<br>x_train = x_train.astype(&#39;float32&#39;) / 255.<br>x_test = x_test.astype(&#39;float32&#39;) / 255.<br>x_train = x_train.reshape(-1, 28, 28, 1)<br>x_test = x_test.reshape(-1, 28, 28, 1)<br><br># Define the VQ-VAE model<br>class VQVAE(tf.keras.Model):<br>    def __init__(self):<br>        super(VQVAE, self).__init__()<br>        <br>        self.encoder = tf.keras.Sequential([<br>            layers.Conv2D(16, kernel_size=4, strides=2, padding=&#39;same&#39;, input_shape=(28,28, 1)),<br>            layers.BatchNormalization(),<br>            layers.ReLU(),<br>            layers.Conv2D(8, kernel_size=4, strides=2, padding=&#39;same&#39;),<br>            layers.BatchNormalization(),<br>            layers.ReLU(),<br>        ])<br><br>        self.pre_quant_conv = layers.Conv2D(4, kernel_size=1)<br><br>        self.embedding = layers.Embedding(10,4)     # I chose 10 vectors each of dimension 4 because 10 digits in mnist.<br>        _ = self.embedding(tf.constant([[0, 1, 2,3]]))<br><br>        self.post_quant_conv = layers.Conv2D(4, kernel_size=1)<br><br>        self.decoder = tf.keras.Sequential([<br>            layers.Conv2DTranspose(16, kernel_size=4, strides=2, padding=&#39;same&#39;),<br>            layers.BatchNormalization(),<br>            layers.ReLU(),<br>            layers.Conv2DTranspose(1, kernel_size=4, strides=2, padding=&#39;same&#39;),<br>            layers.Activation(&#39;tanh&#39;)<br>        ])<br><br>    def call(self, x,y=None):<br>        encoded_output = self.encoder(x)<br>        quant_input = self.pre_quant_conv(encoded_output)<br><br>        B,H, W,C = quant_input.shape<br>        quant_input = tf.reshape(quant_input, (B*H*W, C))<br><br>        dist = tf.norm(tf.expand_dims(quant_input, axis=1) - tf.expand_dims(self.embedding.weights[0], axis=0), axis=-1)<br>        quant_output = tf.gather(self.embedding.weights[0], tf.argmin(dist,axis=1))<br><br>        commitment_loss = tf.reduce_mean(tf.square(tf.stop_gradient(quant_output) - quant_input))<br>        codebook_loss = tf.reduce_mean(tf.square(quant_output-tf.stop_gradient(quant_input)))<br><br>        quantize_losses = codebook_loss + beta*commitment_loss<br><br>        quant_output = quant_input + tf.stop_gradient(quant_output - quant_input)<br>        quant_output = tf.reshape(quant_output, (B, H, W, C))<br><br>        decoder_input = self.post_quant_conv(quant_output)<br>        output = self.decoder(decoder_input)<br><br>        return output, quantize_losses<br><br>    def train_step(self, data):<br>        x, y = data<br>        with tf.GradientTape() as tape:<br>            output, quantize_losses = self.call(x,y)<br>            reconstruction_loss = tf.reduce_mean(tf.square(data - output))<br>            total_loss = reconstruction_loss + quantize_losses<br>        grads = tape.gradient(total_loss, self.trainable_variables)<br>        self.optimizer.apply_gradients(zip(grads, self.trainable_variables))<br>        return {&quot;loss&quot;: total_loss, &quot;reconstruction_loss&quot;: reconstruction_loss, &quot;quantize_losses&quot;: quantize_losses}<br><br># Instantiate and compile the model<br>model = VQVAE()<br>model.compile(optimizer=&#39;adam&#39;)<br><br># Train the model<br>model.fit(x_train, x_train, epochs=5, batch_size=32)</pre><h4>Inference</h4><pre>k = model.predict(x_train)<br><br>for i in [1, 10, 25, 60]:<br>    fig, axes = plt.subplots(1, 2, figsize=(12, 6))<br>    <br>    # Plot generated image<br>    axes[0].imshow(k[0][i])<br>    axes[0].set_title(&#39;Generated&#39;)<br>    axes[0].axis(&#39;off&#39;)<br>    <br>    # Plot real image<br>    axes[1].imshow(x_train[i])<br>    axes[1].set_title(&#39;Real&#39;)<br>    axes[1].axis(&#39;off&#39;)<br>    <br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*GZx75KZPDw69jssUCXn2kg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*zy4Xae3DJe-1DzyEDQC3Tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*TRbemuZKcBaKR7nzMJUO0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*7aDShZp8iIejfiGNCPJOug.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccc9fab702e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yolo V1 (Pascal VOC) | Simplistic Pytorch Implementation from scratch]]></title>
            <link>https://medium.com/@saptarshimt/yolo-v1-pascal-voc-simplistic-pytorch-implementation-from-scratch-961fa36f4d4d?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/961fa36f4d4d</guid>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 19:30:33 GMT</pubDate>
            <atom:updated>2024-07-21T13:56:56.566Z</atom:updated>
            <content:encoded><![CDATA[<p>The idea is to segment the image into a grid and predict the existence of bounding boxes for the classes we are considering. In YOLO v1 the grid size is 7 x 7. When it comes to labeling the data, a grid cell is labeled to contain an object only if the center of the bounding box is in it. If the grid cell contains a center, the “objectness” is labeled 1 and 0 otherwise. The model will try to predict the probability that a grid cell contains a center. If it contains a center, each class related to those centers will be labeled with 1s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cpFGLU594s-Edx14.png" /></figure><pre>import numpy as np <br>import pandas as pd <br>import matplotlib.pyplot as plt<br>import  xml.etree.ElementTree as ET<br>import cv2<br>import shutil<br>import torch<br>import os<br>from torch.utils.data import TensorDataset, DataLoader</pre><pre>train_images=&quot;JPEGImages/&quot;<br>train_maps=&quot;Annotations/&quot;<br><br>classes=[&#39;aeroplane&#39;,&#39;bicycle&#39;,&#39;bird&#39;,&#39;boat&#39;,&#39;bottle&#39;,&#39;bus&#39;,&#39;car&#39;,&#39;cat&#39;,&#39;chair&#39;,&#39;cow&#39;,&#39;diningtable&#39;,&#39;dog&#39;,&#39;horse&#39;,&#39;motorbike&#39;,&#39;person&#39;,&#39;pottedplant&#39;,&#39;sheep&#39;,&#39;sofa&#39;,&#39;train&#39;,&#39;tvmonitor&#39;]<br><br>N_CLASSES=len(classes)<br>H,W=224,224<br>SPLIT_SIZE=int(H/32)<br>BATCH_SIZE=32</pre><p><strong>WRITE FUNCTION TO EXTRACT BOUNDING BOXES FROM EACH IMAGE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPoaZHU93nY5JdFN6zqARw.png" /></figure><pre># This function preprocesses an XML file containing object detection annotations.<br>def preprocess_xml(filename):<br>    <br>    # Parse the XML file using ElementTree.<br>    tree = ET.parse(filename)<br>    root = tree.getroot()<br>    <br>    # Extract image size from the XML.<br>    size_tree = root.find(&#39;size&#39;)<br>    height = float(size_tree.find(&#39;height&#39;).text)<br>    width = float(size_tree.find(&#39;width&#39;).text)<br>    <br>    # Initialize list to store bounding boxes.<br>    bounding_boxes = []<br>    <br>    # Create a dictionary to map class names to indices.<br>    class_dict = {classes[i]: i for i in range(len(classes))}<br>    <br>    # Iterate through each object annotation in the XML.<br>    for object_tree in root.findall(&#39;object&#39;):<br>        # Extract bounding box coordinates.<br>        for bounding_box in object_tree.iter(&#39;bndbox&#39;):<br>            xmin = float(bounding_box.find(&#39;xmin&#39;).text)<br>            xmax = float(bounding_box.find(&#39;xmax&#39;).text)<br>            ymin = float(bounding_box.find(&#39;ymin&#39;).text)<br>            ymax = float(bounding_box.find(&#39;ymax&#39;).text)<br>            break<br>        <br>        # Extract class name of the object.<br>        class_name = object_tree.find(&#39;name&#39;).text<br>        <br>        # Calculate normalized bounding box coordinates and append to the list.<br>        bounding_box = [<br>            (xmin + xmax) / (2 * width),<br>            (ymin + ymax) / (2 * height),<br>            (xmax - xmin) / width,<br>            (ymax - ymin) / height,<br>            class_dict[class_name]<br>        ]<br>        bounding_boxes.append(bounding_box)<br>    <br>    # Convert the list of bounding boxes to a TensorFlow tensor and return.<br>    return torch.tensor(bounding_boxes)</pre><h4>INITIALISING THE YOLO OUTPUT FUNCTION</h4><ol><li><strong>Initialize output label tensor</strong>: This creates a 3D numpy array of zeros with dimensions SPLIT_SIZE x SPLIT_SIZE x (N_CLASSES + 5). SPLIT_SIZE is the number of grid cells the image is divided into along the width and height, and N_CLASSES is the number of object classes. The + 5 accounts for the 5 parameters of the bounding box (objectness score, x, y, width, height).</li><li><strong>Calculate grid positions</strong>: For each bounding box, it calculates the grid cell coordinates (grid_x, grid_y) that the center of the bounding box falls into. This is done by multiplying the normalized x and y coordinates of the bounding box center by SPLIT_SIZE.</li><li><strong>Convert to integer grid indices</strong>: The floating point grid coordinates are converted to integer indices (i, j) which represent the row and column of the grid cell in the output tensor.</li></ol><pre>def generate_output(bounding_boxes):<br>    # Initialize output label tensor<br>    output_label = np.zeros((SPLIT_SIZE, SPLIT_SIZE, N_CLASSES + 5))<br><br>    # Iterate through bounding boxes<br>    for b in range(len(bounding_boxes)):<br>        # Calculate grid positions<br>        grid_x = bounding_boxes[..., b, 0] * SPLIT_SIZE<br>        grid_y = bounding_boxes[..., b, 1] * SPLIT_SIZE<br>        <br>        # Convert to integer grid indices<br>        i = int(grid_x)<br>        j = int(grid_y)<br><br>        # Assign values to output label tensor<br>        output_label[i, j, 0:5] = [1., grid_x % 1, grid_y % 1, bounding_boxes[..., b, 2], bounding_boxes[..., b, 3]]<br>        output_label[i, j, 5 + int(bounding_boxes[..., b, 4])] = 1.<br><br>    # Convert output label tensor to TensorFlow tensor<br>    return torch.tensor(output_label)</pre><p>This part of the code is assigning values to the output label tensor for each bounding box:</p><ul><li>output_label[i, j, 0:5] = [1., grid_x % 1, grid_y % 1, bounding_boxes[..., b, 2], bounding_boxes[..., b, 3]]: This line is assigning the first five values for the grid cell (i, j). The values are:</li></ul><ol><li>1.: This is the objectness score, which indicates the presence of an object in the bounding box. It is set to 1 because there is an object in this bounding box.</li><li>grid_x % 1: This is the x-coordinate of the center of the bounding box relative to the grid cell. It is calculated as the remainder of grid_x divided by 1, which gives the fractional part of grid_x.</li><li>grid_y % 1: This is the y-coordinate of the center of the bounding box relative to the grid cell. It is calculated in the same way as grid_x % 1.</li><li>bounding_boxes[..., b, 2]: This is the width of the bounding box, normalized by the width of the image.</li><li>bounding_boxes[..., b, 3]: This is the height of the bounding box, normalized by the height of the image.</li></ol><ul><li>output_label[i, j, 5 + int(bounding_boxes[..., b, 4])] = 1.: This line is assigning the class label for the object in the bounding box. The class label is represented as a one-hot vector,</li></ul><p><strong>i)</strong> where the index corresponding to the class of the object is set to 1, and all other indices are set to 0.</p><p><strong>ii)</strong> The class index is obtained from the last element of the bounding box (bounding_boxes[..., b, 4]), and 5 + int(bounding_boxes[..., b, 4]) is the index in the output label tensor where the class label should be set to 1.</p><p><strong>iii)</strong> The int() function is used to convert the class index to an integer, in case it is a floating-point number.</p><p><strong>iv)</strong> The 5 + is because the first 5 elements of the depth dimension are used for the bounding box parameters, so the class labels start from the 6th element.</p><p><strong>Note the number of grid cells are 7x7. We are only taking ‘1 CLASS PER GRID CELL’ as opposed traditionally taking 2 classes.</strong></p><p><strong>Therefore our output will be of format 7x7x(5+C), where C=20 classes.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*1D17g2hj89aaQcV6oCLh0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2D6nDf8JyPpd8d7M5N9dQ.png" /></figure><p><strong>GET THE ANNOTATION AND IMAGE FILE PATHS</strong></p><pre>im_paths=[]<br>xml_paths=[]<br><br>for i in os.listdir(train_maps)[:5000]:<br>    im_paths.append(train_images+i[:-3]+&#39;jpg&#39;)<br>    xml_paths.append(train_maps+i)</pre><p><strong>GET THE IMAGE AND BOUNDING BOX COORDINATES AND CLASS</strong></p><pre>import torchvision.transforms as transforms<br>from PIL import Image<br><br># Define transformations<br>transform = transforms.Compose([<br>    transforms.Resize((H, W)),<br>    transforms.ToTensor(),<br>])<br><br>images = []<br>for im_path in im_paths:<br>    # Open image using PIL<br>    img = Image.open(im_path).convert(&#39;RGB&#39;)<br>    <br>    # Apply transformations<br>    img_tensor = transform(img)<br>    <br>    images.append(img_tensor)<br><br># Stack tensors<br>images = torch.stack(images)</pre><p><strong>GENERATE BOUNDING BOX OUTPUT COORDINATE</strong></p><pre>boxes = []<br><br>for xml_path in xml_paths:<br>    <br>    boxes.append(generate_output(preprocess_xml(xml_path)))<br>    <br>boxes = torch.tensor(boxes,dtype=torch.float32)</pre><p><strong>ARCHITECTURE</strong></p><p>A pretrained ResNet50 model was used as the backbone for this YOLO architecture, this saves us the cost of training a backbone model from scratch. A good architecture is key to having a more accurate classifier and detector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bTt4_pTOCZAWDDFl.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EZjMCAjleUsyfQqv.png" /></figure><pre>import torch.nn as nn<br>import torchvision.models as models<br><br>NUM_FILTERS = 512<br>OUTPUT_DIM = int(N_CLASSES + 5)<br><br># Load pre-trained ResNet50<br>base_model = models.resnet50(pretrained=True)<br><br># Remove the last fully connected layer<br>base_model = nn.Sequential(*list(base_model.children())[:-2])<br><br># Freeze the base model<br>for param in base_model.parameters():<br>    param.requires_grad = False<br><br><br># Define additional layers<br>conv_layers = nn.Sequential(<br>    nn.Conv2d(2048, NUM_FILTERS, kernel_size=3, padding=1),<br>    nn.BatchNorm2d(NUM_FILTERS),<br>    nn.LeakyReLU(0.1),<br>    <br>    nn.Conv2d(NUM_FILTERS, NUM_FILTERS, kernel_size=3, padding=1),<br>    nn.BatchNorm2d(NUM_FILTERS),<br>    nn.LeakyReLU(0.1),<br>    <br>    nn.Conv2d(NUM_FILTERS, NUM_FILTERS, kernel_size=3, padding=1),<br>    nn.BatchNorm2d(NUM_FILTERS),<br>    nn.LeakyReLU(0.1)<br>)<br><br>flatten = nn.Flatten()<br><br>dense_layers = nn.Sequential(<br>    nn.Linear(NUM_FILTERS * (H // 32) * (W // 32), NUM_FILTERS),<br>    nn.BatchNorm1d(NUM_FILTERS),<br>    nn.LeakyReLU(0.1),<br>    <br>    nn.Linear(NUM_FILTERS, int(SPLIT_SIZE * SPLIT_SIZE * OUTPUT_DIM)),<br>    nn.Sigmoid()<br>)<br><br># Combine all layers into a single sequential model<br>model = nn.Sequential(<br>    base_model,<br>    conv_layers,<br>    flatten,<br>    dense_layers,<br>    nn.Unflatten(1, (SPLIT_SIZE, SPLIT_SIZE, OUTPUT_DIM))<br>)<br><br># Print model summary<br>print(model)</pre><h4><strong>LOSS FUNCTION</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cpd0i-veQu8WRP6NZeUFog.png" /></figure><p>There are 5 terms in the loss function as shown above.</p><p><strong>1. term (x, y):</strong></p><p>The bounding box x and y coordinates is parametrized to be offsets of a particular grid cell location so they are also bounded between 0 and 1. And the sum of square error (SSE) is estimated only when there is object.</p><p><strong>2. term (w, h):</strong></p><p>The bounding box width and height are normalized by the image width and height so that they fall between 0 and 1. SSE is estimated only when there is object. Since small deviations in large boxes matter less than in small boxes. square root of the bounding box width w and height h instead of the width and height directly to partially address this problem.</p><p><strong>3&amp;4. term (The confidence) (i.e. the IOU between the predicted box and any ground truth box):</strong></p><p>In every image many grid cells do not contain any object. This pushes the “confidence” scores of those cells towards zero, often overpowering the gradient from cells that do contain objects, and makes the model unstable. Thus, the loss from confidence predictions for boxes that don’t contain objects, is decreased, i.e. λ_noobj=0.5.</p><p><strong>5. term (Class Probabilities):</strong></p><p>SSE of class probabilities when there is objects. λcoord: Due to the same reason mentioned in 3rd and 4th terms, λcoord = 5 to increase the loss from bounding box coordinate predictions.</p><pre>def difference(x, y):<br>    return torch.sum((y - x)**2)<br><br>def yolo_loss(y_true, y_pred):<br>    target = y_true[..., 0]  # Grid cell where we have information of object presence<br>    <br>    #--------------------------------------- for object<br>    <br>    target_indices = target == 1<br>    y_pred_extract = y_pred[target_indices]<br>    y_target_extract = y_true[target_indices]<br>    <br>    object_loss = difference(y_pred_extract[..., 0].float(), torch.ones_like(y_pred_extract[..., 0]).float())<br>    <br>    #------------------------------------------------------ for no object<br>    <br>    target_indices_no_obj = target == 0<br>    y_pred_extract_no_obj = y_pred[target_indices_no_obj]<br>    y_target_extract_no_obj = y_true[target_indices_no_obj]<br><br>    no_obj_loss = difference(y_pred_extract_no_obj[..., 0].float(), torch.zeros_like(y_pred_extract_no_obj[..., 0]).float())<br>    <br>    #-------------------------------------------------------- for object class loss<br>    <br>    y_pred_extract_class = y_pred[target_indices][:, 5:]<br>    class_extract = y_true[target_indices][:, 5:]<br>    <br>    class_loss = difference(y_pred_extract_class.float(), class_extract.float())<br>    <br>    #--------------------------------------------------------- for object center loss<br>    <br>    y_pred_extract_center = y_pred[target_indices][:, 1:3]<br>    center_target = y_true[target_indices][:, 1:3]<br>    <br>    center_loss = difference(y_pred_extract_center.float(), center_target.float())<br>    <br>    #------------------------------------------------------- for width and height<br>    <br>    size_pred = y_pred[target_indices][:, 3:5]<br>    size_target = y_true[target_indices][:, 3:5]<br>    <br>    size_loss = difference(torch.sqrt(torch.abs(size_pred.float())), torch.sqrt(torch.abs(size_target.float())))<br>    <br>    box_loss = center_loss + size_loss<br>    <br>    lambda_coord = 5<br>    lambda_no_obj = 0.5<br>    <br>    loss = object_loss + (lambda_no_obj * no_obj_loss) + lambda_coord * box_loss + class_loss<br>    <br>    return loss</pre><h4>TRAINING</h4><pre># Move model and data to MPS device<br>device = torch.device(&quot;mps&quot; if torch.backends.mps.is_available() else &quot;cpu&quot;)<br>model.to(device)<br>images = images.to(device)<br>boxes = boxes.to(device)<br><br><br># Define your loss function and optimizer<br>optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)<br><br># Training loop<br>num_epochs = 50<br>for epoch in range(num_epochs):<br>    model.train()<br>    running_loss = 0.0<br><br>    # Assuming batch size of 32 and iterating through batches<br>    batch_size = 32<br>    for i in range(0, len(images), batch_size):<br>        img_batch = images[i:i+batch_size]<br>        target_batch = boxes[i:i+batch_size]<br><br>        # Forward pass<br>        outputs = model(img_batch)<br><br>        # Assuming you have a custom YOLO-like loss function<br>        loss = yolo_loss(target_batch,outputs)<br><br>        # Backward pass and optimize<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br><br>        running_loss += loss.item()<br><br>    # Print average loss for epoch<br>    print(f&#39;Epoch [{epoch+1}/{num_epochs}], Loss: {running_loss / (len(images) / batch_size)}&#39;)<br><br>print(&#39;Finished Training&#39;)</pre><h4>PREDICT &amp; VISUALISE</h4><pre>for j in [60,10,5,4,3416,500,600,800,560,1000,595,1400,1657]:<br>    <br>    output = model(images[j:j+32])[:1]. #SINCE MODEL TAKES 32 AS BATCH AND NOT SINGLE IMAGE<br><br>    # Threshold for detection<br>    THRESH = 0.25<br><br>    # Get object positions<br>    object_positions = torch.where(output[..., 0] &gt;= THRESH)<br>    selected_output = output[object_positions]<br><br>    # Initialize lists for final boxes and scores<br>    final_boxes = []<br>    final_scores = []<br><br>    # Iterate through object positions<br>    for i in range(len(object_positions[0])):<br>        if selected_output[i][0] &gt; THRESH:<br>            # Extract box parameters<br>            output_box = selected_output[i][1:5].float()<br>            x_centre = (object_positions[1][i] + output_box[0]) * 32<br>            y_centre = (object_positions[2][i] + output_box[1]) * 32<br>            x_width, y_height = torch.abs(224 * output_box[2]), torch.abs(224 * output_box[3])<br>            x_min, y_min = int(x_centre - (x_width / 2)), int(y_centre - (y_height / 2))<br>            x_max, y_max = int(x_centre + (x_width / 2)), int(y_centre + (y_height / 2))<br><br>            # Adjust bounding box coordinates<br>            x_min = max(0, x_min)<br>            y_min = max(0, y_min)<br>            x_max = min(224, x_max)<br>            y_max = min(224, y_max)<br><br>            # Append to final boxes<br>            final_boxes.append([x_min, y_min, x_max, y_max, <br>                               classes[torch.argmax(selected_output[i][5:]).item()]])<br>            final_scores.append(selected_output[i][0].item())<br><br><br>    img = np.array(images[j].permute(1, 2, 0).to(&#39;cpu&#39;)).copy()<br>    <br>    for i in range(len(final_boxes)):<br><br>        # Extract object classes and boxes<br>        object_classes = final_boxes[i][4]<br>        nms_output = final_boxes[i][0:4]<br><br>        x1, y1 = nms_output[:2]<br>        x2, y2 = nms_output[2:]<br><br>        # Specify the color (in BGR format) and thickness<br>        color = (255, 0, 0) <br>        thickness = 2<br><br>        # Draw the rectangle<br>        cv2.rectangle(img, (x1, y1), (x2, y2), color, thickness)<br>        <br>        # Add text (object classes) <br>        font = cv2.FONT_HERSHEY_SIMPLEX<br>        font_scale = 0.5<br>        font_color = (255, 255, 255)  <br>        text_position = (x1, y2)  <br><br>        cv2.putText(img, object_classes, text_position, font, font_scale, font_color, thickness)<br>    plt.imshow(img)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*y5jpylB_uY88IzpN9WUcjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*kLoa2Lo5m9qpkHPX6DO5TA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*qwZlfWoNptfATehBBm5CAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*wgD1-qdo_7pcdLhfewPR9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*NRmVKbyKyNsJkr9BABLafQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*dKOvlJCNONjuai4DgrNSkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*rOkB7mlpwx5eCboZyIuyTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*HHvrxk3uccceFTsMgodHeA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=961fa36f4d4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SR3 - Super Resolution Diffusion via Iterative Refinement | A simple TensorFlow implementation…]]></title>
            <link>https://medium.com/@saptarshimt/sr3-super-resolution-diffusion-via-iterative-refinement-a-simple-tensorflow-implementation-from-18708a64f280?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/18708a64f280</guid>
            <category><![CDATA[generative-modeling]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[image-super-resolution]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 07:28:27 GMT</pubDate>
            <atom:updated>2024-07-10T02:24:40.693Z</atom:updated>
            <content:encoded><![CDATA[<h3>SR3 - Super Resolution Diffusion via Iterative Refinement | A simple TensorFlow implementation (from scratch)</h3><p>Diffusion Models are generative models, meaning that they are used to generate data similar to the data on which they are trained.</p><p>They work by successive addition of Gaussian noise through various time steps typically 1000. And then we go on learning to recover the data by <em>reversing</em> this noising process.After training, we can use the Diffusion Model to generate data by simply passing randomly sampled noise through the learned denoising process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J-AonhID-spQmDPs.png" /></figure><h4>SR3</h4><p>In super resolution diffusion we add one extra term i.e low resolution bicubic upsampled images to the noise along with the time steps. By adding i mean concatenating bicubic upsampled image with the noise along the channel dimension i.e if we first upsample a low resolution image for example (32,32,3) → (128,128,3) and then concatenate along channel axis with pure noise of the same dimension i.e (128,128,3) to obtain (128,128,6). The reason for doing it is so that to provide sense of direction to the model on what it actually needs to generate i.e super resolution version of the image.</p><p>Everything will get clearer as we code along!</p><pre>from tensorflow.keras.layers import Conv2D, BatchNormalization, Activation, MaxPool2D, Conv2DTranspose, Concatenate, Input,Dense<br>from tensorflow.keras.models import load_model<br>from tensorflow.keras import layers<br>from tensorflow.keras.models import Model<br>import tensorflow as tf<br>from keras import backend as k<br>import numpy as np<br>from tqdm import tqdm<br>import os<br>import matplotlib.pyplot as plt<br>from tqdm.auto import trange, tqdm<br>import pandas as pd<br>import cv2<br>import gc<br><br>for gpu in tf.config.list_physical_devices(&#39;GPU&#39;):<br>    tf.config.experimental.set_memory_growth(gpu, True)</pre><p>We load the Faces Dataset, training on only 300 images with a resolution of 128x128 pixels. Our dataset creation process involves taking the 128x128 images as high-resolution (hr_images). To generate low-resolution (lr_images), we first downscale the hr_images to 32x32 pixels and then rescale them back to 128x128 pixels. Interestingly, even in their original 128x128 resolution, the hr_images become corrupted when used as lr_images.</p><p>Alternatively, you could work with a dataset that consists of paired (hr, lr) images. In this case, you can perform bicubic upscaling on the lr_images, avoiding the unnecessary intermediate steps described above.</p><pre>base_dir = &#39;lfw_images/lfw_funneled&#39;<br><br># List to store image arrays<br>hr_img = []<br>lr_img = []<br><br># Loop through each folder (person) in the base directory<br>for person in os.listdir(base_dir):<br><br>    person_dir = os.path.join(base_dir, person)<br>    <br>    # Check if the item is a directory<br>    if os.path.isdir(person_dir):<br>        <br>        # Loop through each image file in the person&#39;s directory<br>        for image_file in os.listdir(person_dir):<br>            image_path = os.path.join(person_dir, image_file)<br>            <br>            # Read the image using OpenCV<br>            img = cv2.imread(image_path)<br>            <br>            # Convert the image to RGB (OpenCV uses BGR by default)<br>            img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>            img_rgb = img_rgb/255<br>            hr = cv2.resize(img_rgb,(128,128),interpolation=cv2.INTER_CUBIC)<br>            # scale down hr image to 32,32 and then upsample to 128,128.<br>            lr = cv2.resize(img_rgb,(32,32),interpolation=cv2.INTER_CUBIC)<br>            lr = cv2.resize(lr,(128,128),interpolation=cv2.INTER_CUBIC)<br>            <br>            # Append the image array to the list<br>            hr_img.append(hr)<br>            lr_img.append(lr)<br>            <br>hr_img = np.array(hr_img[:300])<br>lr_img = np.array(lr_img[:300])</pre><p>We add noise linearly to each image for total 1000 time-steps , and get the noisy image and noise for each corresponding image and time step.</p><pre>timesteps = 1000<br><br># create a fixed beta schedule<br>beta = np.linspace(0.0001, 0.02, timesteps)<br><br># this will be used as discussed in the reparameterization trick<br>alpha = 1 - beta<br>alpha_bar = np.cumprod(alpha, 0)<br>alpha_bar = np.concatenate((np.array([1.]), alpha_bar[:-1]), axis=0)<br>sqrt_alpha_bar = np.sqrt(alpha_bar)<br>one_minus_sqrt_alpha_bar = np.sqrt(1-alpha_bar)<br><br><br>def add_noise(x_0, t):<br>    noise = np.random.normal(size=x_0.shape)<br>    sqrt_alpha_bar_t = np.reshape(np.take(sqrt_alpha_bar, t), [-1, 1, 1, 1])<br>    one_minus_sqrt_alpha_bar_t = np.reshape(np.take(one_minus_sqrt_alpha_bar, t), [-1, 1, 1, 1])<br>    noisy_img = sqrt_alpha_bar_t  * x_0 + one_minus_sqrt_alpha_bar_t  * noise<br>    return tf.convert_to_tensor(noisy_img),tf.convert_to_tensor(noise)<br><br>fig = plt.figure(figsize=(15, 30))<br><br>for index, i in enumerate([1,5,29,499,999]):<br>    noisy_im, noise = add_noise(hr_img[0], np.array([i,]))<br>    noisy_im = noisy_im[0] # 1,28,28,1 shape<br>    plt.subplot(1, 5, index+1)<br>    plt.axis(&#39;off&#39;)<br>    plt.imshow(noisy_im)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgvunXIqX9EzLjDas8wJ5g.png" /></figure><p>Now we define the UNET model that takes input as noisy image and outputs noise as prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9_0KqQyGSYaBs0f896aSg.png" /></figure><pre>def block(x_img, x_ts):<br>    <br>    x_parameter = layers.Conv2D(64, kernel_size=3, padding=&#39;same&#39;)(x_img)<br>    x_parameter = layers.Activation(&#39;relu&#39;)(x_parameter)<br><br>    time_parameter = layers.Dense(64)(x_ts)<br>    time_parameter = layers.Activation(&#39;relu&#39;)(time_parameter)<br>    time_parameter = layers.Reshape((1, 1, 64))(time_parameter)<br>    x_parameter = x_parameter * time_parameter<br>    <br>    # -----<br>    x_out = layers.Conv2D(64, kernel_size=3, padding=&#39;same&#39;)(x_img)<br>    x_out = x_out + x_parameter<br>    x_out = layers.LayerNormalization()(x_out)<br>    x_out = layers.Activation(&#39;relu&#39;)(x_out)<br>    <br>    return x_out<br><br>def make_model():<br>    x1_ = x_input1 = layers.Input(shape=(128,128, 3), name=&#39;x_input1&#39;)    # input noisy image<br>    x2_ = x_input2 = layers.Input(shape=(128,128, 3), name=&#39;x_input2&#39;)   # input bicubic upscaled image<br>    <br>    x = tf.concat([x1_,x2_],axis=3)  # concatenate input noisy image and input bicubic upscaled image along the Channel axis <br>    <br>    x_ts = x_ts_input = layers.Input(shape=(1,), name=&#39;x_ts_input&#39;)<br>    x_ts = layers.Dense(64)(x_ts)<br>    x_ts = layers.LayerNormalization()(x_ts)<br>    x_ts = layers.Activation(&#39;relu&#39;)(x_ts)<br>    <br>    # ----- left ( down ) -----<br>    x = x32 = block(x, x_ts)<br>    x = layers.MaxPool2D(2)(x)<br>    <br>    x = x16 = block(x, x_ts)<br>    x = layers.MaxPool2D(2)(x)<br>    <br>    x = x8 = block(x, x_ts)<br>    <br>    # ----- MLP -----<br>    x = layers.Flatten()(x)<br>    x = layers.Concatenate()([x, x_ts])<br>    x = layers.Dense(64)(x)<br>    x = layers.LayerNormalization()(x)<br>    x = layers.Activation(&#39;relu&#39;)(x)<br><br>    x = layers.Dense(32*32*64)(x)<br>    x = layers.LayerNormalization()(x)<br>    x = layers.Activation(&#39;relu&#39;)(x)<br>    x = layers.Reshape((32,32,64))(x)<br>    <br>    # ----- right ( up ) -----<br>    x = layers.Concatenate()([x, x8])<br>    x = block(x, x_ts)<br>    x = layers.UpSampling2D(2)(x)<br>    <br>    x = layers.Concatenate()([x, x16])<br>    x = block(x, x_ts)<br>    x = layers.UpSampling2D(2)(x)<br>    <br>    x = layers.Concatenate()([x, x32])<br>    x = block(x, x_ts)<br>    <br>    x = Concatenate()([x, x1_, x2_])<br>    <br>    # ----- output -----<br>    x = layers.Conv2D(3, kernel_size=1, padding=&#39;same&#39;)(x)<br>    <br>    return tf.keras.models.Model([x_input1,x_input2, x_ts_input], x)<br><br>model = make_model()<br>model.summary()<br><br><br>optimizer = tf.keras.optimizers.legacy.Adam(learning_rate=0.0008)<br>loss_func = tf.keras.losses.MeanSquaredError()<br>model.compile(loss=loss_func, optimizer=optimizer)</pre><h3>Training</h3><p>Here due to memory issue i did the following steps :</p><ol><li>from the time steps 999 to 100 i sarted saving at interval of 100. i.e at 900,800,700,…100.</li><li>going from 100 to 50, 50 to 10 and 10 to 1, i again saved the models.</li></ol><p>The above process was done so that each of those models will help in predicting the noise. A model trained at time step 50 won’t be useful to predict noise at time step 910.</p><p>For each time step from 999 to 1, i prepared dataset of noisy_images and noise part and then trained the model.</p><pre>from tensorflow.keras.models import load_model<br><br>t = np.arange(1000,-1,-1)<br><br>for i in t[-1000:-99]:<br>    print(&#39; timesteps &#39;,i)<br>    noisy_im, noise = add_noise(hr_img,np.array([i,]))<br>    time = tf.convert_to_tensor(np.repeat([i,],300))<br>    <br>    if i&gt;997:<br>        model.fit([noisy_im,lr_img,time],noise,epochs=30)<br>    else:<br>        model.fit([noisy_im,lr_img,time],noise,epochs=30)<br>        <br>    if i %100==0:<br>            model.save(f&#39;model_checkpoint.h5_{i}&#39;)<br>            tf.keras.backend.clear_session()<br>            gc.collect()<br>            <br>for i in t[-100:-50]:<br>    print(&#39; timesteps &#39;,i)<br>    noisy_im, noise = add_noise(hr_img,np.array([i,]))<br>    time = tf.convert_to_tensor(np.repeat([i,],300))<br>    <br>    model.fit([noisy_im,lr_img,time],noise,epochs=3)<br>        <br>    if i == 50:<br>            model.save(f&#39;model_checkpoint.h5_{i}&#39;)<br>            tf.keras.backend.clear_session()<br>            gc.collect()  <br>            <br>for i in t[-50:-10]:<br>    print(&#39; timesteps &#39;,i)<br>    noisy_im, noise = add_noise(hr_img,np.array([i,]))<br>    time = tf.convert_to_tensor(np.repeat([i,],300))<br>    <br>    model.fit([noisy_im,lr_img,time],noise,epochs=5)<br>        <br>    if i == 10:<br>            model.save(f&#39;model_checkpoint.h5_{i}&#39;)<br>            tf.keras.backend.clear_session()<br>            gc.collect()  <br>            <br>for i in t[-10:-1]:<br>    print(&#39; timesteps &#39;,i)<br>    noisy_im, noise = add_noise(hr_img,np.array([i,]))<br>    time = tf.convert_to_tensor(np.repeat([i,],300))<br>    <br>    model.fit([noisy_im,lr_img,time],noise,epochs=20)<br>        <br>    if i == 1:<br>        model.save(f&#39;model_checkpoint.h5_{i}&#39;)<br>        tf.keras.backend.clear_session()<br>        gc.collect() </pre><h3>Sampling and Visualisation</h3><pre>def ddim(x_t, pred_noise, t, step_size):<br>    alpha_t_bar = np.reshape(np.take(alpha_bar, t), [-1, 1, 1, 1])<br>    alpha_t_minus_one = np.reshape(np.take(alpha_bar, t-step_size), [-1, 1, 1, 1])<br>        <br>    pred = (x_t - ((1 - alpha_t_bar) ** 0.5) * pred_noise)/ (alpha_t_bar ** 0.5)<br>    pred = (alpha_t_minus_one ** 0.5) * pred<br><br>    pred = pred + ((1 - alpha_t_minus_one) ** 0.5) * pred_noise<br>    return pred<br><br>inf_step = 1</pre><ol><li>We first sample random noise and get our bicubic upscaled images from our low resolution as reference image.</li><li>For each checkpoint we load a model and predict for the relevant range.</li></ol><pre>x1 = tf.random.normal((4,128,128,3))<br>x2 = lr_img[97:101]<br><br>t = np.arange(1000,-1,-1)<br>checkpoints = [1000,900, 800, 700, 600, 500, 400, 300, 200, 100, 50, 10, 1]<br><br>for k in range(len(checkpoints)):<br>    <br>    if checkpoints[k]==1:<br>        break<br>        <br>    model = load_model(f&#39;model_checkpoint.h5_{checkpoints[k+1]}&#39;)<br>    <br>    for i in t[-checkpoints[k]:-checkpoints[k+1]]:<br>        pred_noise = model.predict([x1,x2,np.repeat(i,4)],verbose=0)<br>        x1 = ddim(x1, pred_noise, i, inf_step)<br>        <br>        if any(t-inf_step) == 0:<br>            break</pre><pre># Create a figure and axis for the plots<br>fig, axes = plt.subplots(4, 3, figsize=(15, 20))<br><br>for i in range(4):<br>    # Display x1[i] on the first axis<br>    axes[i][0].imshow(x1[i])<br>    axes[i][0].set_title(&#39;SR3 Super Resolution my implementation&#39;)<br>    axes[i][0].axis(&#39;off&#39;)<br><br>    # Display hr_img[100+i] on the second axis<br>    axes[i][1].imshow(hr_img[97+i])<br>    axes[i][1].set_title(&#39;Ground Truth (HR)&#39;)<br>    axes[i][1].axis(&#39;off&#39;)<br><br>    # Display lr_img[100+i] on the third axis<br>    axes[i][2].imshow(lr_img[97+i])<br>    axes[i][2].set_title(&#39;Bicubic Upscaled&#39;)<br>    axes[i][2].axis(&#39;off&#39;)<br><br># Show the plots<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZGO0fA2aWXXQVQyEUfocw.png" /></figure><h4>Further Improvements</h4><ol><li>Make the U-NET model more deeper with many parameters and train on several thousands of images if not a lakh to get better generalised result on test data. My model because it was trained on just 300 images will perform poorly on test dataset.</li><li>I am passing the time-variable(t) using a sample dense layer followed by relu. Originally transformers was used but due to model complexity and the increase in training cost i avoided it. You should try it for better results.</li><li>Try incorporating classifier free guidance for faster and better convergence. I will make a future post going through the theory and implementing it.</li></ol><p>And thats all folks! Feel free to comment or reach out if you spot any mistakes.</p><h4>Thank You! 🙏</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18708a64f280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Pyramid Network (FPN) Object Detection | TensorFlow from scratch]]></title>
            <link>https://medium.com/@saptarshimt/feature-pyramid-network-object-detection-tensorflow-from-scratch-430e8ad50b85?source=rss-279584d7a23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/430e8ad50b85</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[feature-pyramid-network]]></category>
            <dc:creator><![CDATA[Saptarshi MT]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 17:22:06 GMT</pubDate>
            <atom:updated>2024-07-08T18:43:12.224Z</atom:updated>
            <content:encoded><![CDATA[<p>In the following article I will walk you through a detail explanation of implementing a custom object detection model using feature pyramid network built on top of a pre-trained CNN model for feature extraction known as backbone i.e ResNet50. I will be training the model on Pascal VOC dataset on a small sample of first 1000 images.</p><h4>ResNet-50</h4><p>ResNet-50 is a convolutional neural network (CNN) that excels at image classification. It’s like a highly trained image analyst who can dissect a picture, identify objects and scenes within it, and categorize them accordingly.</p><h4>FPN</h4><p>Imagine you’re trying to find a specific object in a picture. Sometimes, the object is small and detailed, requiring you to zoom in. Other times, it’s large and takes up most of the picture, so you need a wider view.</p><p>A <strong>Feature Pyramid Network (FPN)</strong> is like having multiple “zoom levels” of the picture, each capturing different levels of detail. It helps computer vision models, like those used for object detection, see objects at various scales.</p><p>Here’s how it works:</p><ol><li><strong>Backbone Network:</strong> A base network (like ResNet50) processes the image, creating feature maps at different resolutions. Think of these as zoomed-in and zoomed-out versions of the image.</li><li><strong>Top-Down Pathway:</strong> FPN takes the highest-resolution feature map (most zoomed-in) and upsamples it. Then, it combines this upsampled map with the next lower-resolution map, effectively “injecting” fine details into the coarser map. This process repeats, creating a pyramid of feature maps with increasing resolution and detail.</li><li><strong>Lateral Connections:</strong> These connections allow information to flow horizontally between feature maps at the same resolution. This helps refine the features and ensures that information from different scales is integrated effectively.</li></ol><p><strong>Benefits of FPN:</strong></p><ul><li><strong>Multi-scale Object Detection:</strong> FPN allows models to detect objects of various sizes, from small details to large structures.</li><li><strong>Improved Accuracy:</strong> By combining information from different scales, FPN improves the overall accuracy of object detection.</li><li><strong>Efficiency:</strong> FPN reuses features from the backbone network, making it more efficient than training separate models for different scales.</li></ul><p>In essence, FPN acts like a powerful magnifying glass, allowing computer vision models to see the world in greater detail and accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_2Hr5CvM62bEI5jKgTavw.png" /></figure><h3>Image and Label Preprocessing</h3><ol><li>There are 20 classes in the PASCAL VOC dataset, and 1 extra class (None) will be added to refer the background class indicating presence of no object.</li><li>The image and all the ground truth bounding boxes will be rescaled to (416,416,3).</li></ol><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import os, cv2<br>import xml.etree.ElementTree as ET<br>import tensorflow as tf<br><br>devices = tf.config.experimental.list_physical_devices(&quot;GPU&quot;)<br>for device in devices:<br>    tf.config.experimental.set_memory_growth(device=device, enable=True)<br>    <br>from tensorflow import keras<br>from keras import Sequential, Model<br><br>LABELS_bf = [&#39;None&#39;,&#39;aeroplane&#39;,  &#39;bicycle&#39;, &#39;bird&#39;,  &#39;boat&#39;,      &#39;bottle&#39;, <br>          &#39;bus&#39;,        &#39;car&#39;,      &#39;cat&#39;,  &#39;chair&#39;,     &#39;cow&#39;,<br>          &#39;diningtable&#39;,&#39;dog&#39;,    &#39;horse&#39;,  &#39;motorbike&#39;, &#39;person&#39;,<br>          &#39;pottedplant&#39;,&#39;sheep&#39;,  &#39;sofa&#39;,   &#39;train&#39;,   &#39;tvmonitor&#39;]<br><br>LABELS = [&#39;aeroplane&#39;,  &#39;bicycle&#39;, &#39;bird&#39;,  &#39;boat&#39;,      &#39;bottle&#39;, <br>          &#39;bus&#39;,        &#39;car&#39;,      &#39;cat&#39;,  &#39;chair&#39;,     &#39;cow&#39;,<br>          &#39;diningtable&#39;,&#39;dog&#39;,    &#39;horse&#39;,  &#39;motorbike&#39;, &#39;person&#39;,<br>          &#39;pottedplant&#39;,&#39;sheep&#39;,  &#39;sofa&#39;,   &#39;train&#39;,   &#39;tvmonitor&#39;]<br><br>train_image_folder = &quot;JPEGImages/&quot;<br>train_annot_folder = &quot;Annotations/&quot;<br><br>def parse_annotation(ann_dir, img_dir, labels=[]):<br>    &#39;&#39;&#39;<br>    output:<br>    - Each element of the train_image is a dictionary containing the annoation infomation of an image.<br>    - seen_train_labels is the dictionary containing<br>            (key, value) = (the object class, the number of objects found in the images)<br>    &#39;&#39;&#39;<br>    all_imgs = []<br>    seen_labels = {}<br>    <br>    for ann in sorted(os.listdir(ann_dir)):<br>        if &quot;xml&quot; not in ann:<br>            continue<br>        img = {&#39;object&#39;:[]}<br><br>        tree = ET.parse(ann_dir + ann)<br>        <br>        for elem in tree.iter():<br>            if &#39;filename&#39; in elem.tag:<br>                path_to_image = img_dir + elem.text<br>                img[&#39;filename&#39;] = path_to_image<br>                ## make sure that the image exists:<br>                if not os.path.exists(path_to_image):<br>                    assert False, &quot;file does not exist!\n{}&quot;.format(path_to_image)<br>            if &#39;width&#39; in elem.tag:<br>                img[&#39;width&#39;] = int(elem.text)<br>            if &#39;height&#39; in elem.tag:<br>                img[&#39;height&#39;] = int(elem.text)<br>            if &#39;object&#39; in elem.tag or &#39;part&#39; in elem.tag:<br>                obj = {}<br>                <br>                for attr in list(elem):<br>                    if &#39;name&#39; in attr.tag:<br>                        <br>                        obj[&#39;name&#39;] = attr.text<br>                        <br>                        if len(labels) &gt; 0 and obj[&#39;name&#39;] not in labels:<br>                            break<br>                        else:<br>                            img[&#39;object&#39;] += [obj]<br><br>                        if obj[&#39;name&#39;] in seen_labels:<br>                            seen_labels[obj[&#39;name&#39;]] += 1<br>                        else:<br>                            seen_labels[obj[&#39;name&#39;]]  = 1<br><br>                            <br>                    if &#39;bndbox&#39; in attr.tag:<br>                        for dim in list(attr):<br>                            if &#39;xmin&#39; in dim.tag:<br>                                obj[&#39;xmin&#39;] = int(round(float(dim.text)))<br>                            if &#39;ymin&#39; in dim.tag:<br>                                obj[&#39;ymin&#39;] = int(round(float(dim.text)))<br>                            if &#39;xmax&#39; in dim.tag:<br>                                obj[&#39;xmax&#39;] = int(round(float(dim.text)))<br>                            if &#39;ymax&#39; in dim.tag:<br>                                obj[&#39;ymax&#39;] = int(round(float(dim.text)))<br><br>        if len(img[&#39;object&#39;]) &gt; 0:<br>            all_imgs += [img]<br>                        <br>    return all_imgs, seen_labels<br><br>## Parse annotations <br>train_image, seen_train_labels = parse_annotation(train_annot_folder,train_image_folder, labels=LABELS)<br>print(&quot;N train = {}&quot;.format(len(train_image)))<br><br># Scale Image and Ground truth bounding box coordinates<br><br>def fun(x,H,W):<br>    <br>    w = x[&#39;width&#39;]       # image height and width <br>    h = x[&#39;height&#39;]<br>    <br>    attr = []<br>    for i in x[&#39;object&#39;]:<br>        <br>        t = {}<br>        <br>        xmin = i[&#39;xmin&#39;]*W/w     # scale the coordinates to (W,H) == (416,416).<br>        xmax = i[&#39;xmax&#39;]*W/w<br>        <br>        ymin = i[&#39;ymin&#39;]*H/h<br>        ymax = i[&#39;ymax&#39;]*H/h<br>        <br>        name = i[&#39;name&#39;]<br>        <br>        t[&#39;name&#39;] = name<br>        t[&#39;xmin&#39;] = xmin<br>        t[&#39;ymin&#39;] = ymin<br>        t[&#39;xmax&#39;] = xmax<br>        t[&#39;ymax&#39;] = ymax<br>        <br>        attr.append(t)<br>    <br>    image = cv2.imread(x[&#39;filename&#39;])<br>    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>    image = cv2.resize(image,(W,H))#/255  # resize to (416,416) and normalize.<br>    <br>    return image,attr</pre><p>The target output will be having 25 values which will be of the form</p><p><strong>[centre_x, centre_y, width, height, objectness_score, 20 classes(one hot encoded)]</strong></p><pre>images = []<br>coord = []<br>labels = []<br>classes = []<br><br>def fun_binary(x):<br>    if x&gt;=1:<br>        return 1<br>    else:<br>        return 0<br><br>for i in range(1000):<br>    <br>    # example of resized image and coordinates<br>    img,attr = fun(train_image[i],416,416)<br>    <br>    <br>    coord_ = []<br>    labels_ = []<br>    class_ = []<br>    for j in range(len(attr)):<br>        <br>        attr_ = attr[j]<br>        xmin,ymin,xmax,ymax = attr_[&#39;xmin&#39;],attr_[&#39;ymin&#39;],attr_[&#39;xmax&#39;],attr_[&#39;ymax&#39;]<br>        cx = (xmin+xmax)/2<br>        cy = (ymin+ymax)/2<br>        w = xmax-xmin<br>        h = ymax-ymin<br>        labels__ = attr_[&#39;name&#39;]<br>        <br>        coord_.append([cx,cy,w,h])<br>        labels_.append([fun_binary(LABELS_bf.index(labels__))])<br>        class_.append(tf.one_hot(LABELS.index(labels__),20))<br>        <br>    images.append(img)<br>    coord.append(coord_)<br>    labels.append(labels_)<br>    classes.append(class_)<br>    <br>    <br>images = np.array(images)</pre><h4>Anchor Boxes</h4><ol><li>Anchor boxes are predefined collection of boxes into which the ground truth labels will be mapped. The anchor boxes encompass a variety widths, heights and aspect ratios to match the possible ground truth label for objects in a dataset.</li><li>The advantage of anchor boxes is that you can evaluate all object predictions at once. Anchor boxes eliminate the need for scanning an image or making multiple passes through the model for each area of interest.</li><li>The anchor boxes will be generated on 3 different scales (or feature maps) of (width,height) i.e (52,52), (26,26) &amp; (13,13) each scale having 3 anchors.</li></ol><ul><li>The anchors corresponding to scale (52,52) are small and will help in detecting small size objects as the feature map is of high resolution. Correspondingly a total of 52 * 52 * 3 = 8112 anchor boxes will be created.</li><li>The anchors corresponding to scale (26,26) are medium and will help in detecting medium size objects as the feature map is of mid resolution. Correspondingly a total of 26 * 26 * 3 = 2028 anchor boxes will be created.</li><li>The anchors corresponding to scale (13,13) are big and will help in detecting big size objects as the feature map is of low resolution. Correspondingly a total of 13 * 13 * 3 = 507 anchor boxes will be created.</li></ul><pre>wh_52 = np.array([(10, 13), (16, 30), (33, 23)])<br>wh_26 = np.array([(30, 61), (62, 45),(59, 119)])<br>wh_13 = np.array([(116, 90), (156, 198), (373, 326)])<br><br># Define the feature map size and number of anchors per point<br>feature_map_size = 13<br>anchors_per_point = 3<br><br># Define the image size<br>image_size = 416<br><br># Create a grid of center points<br>x_centers = np.linspace(0, image_size, feature_map_size + 2)[1:-1]<br>y_centers = np.linspace(0, image_size, feature_map_size + 2)[1:-1]<br>center_grid = np.array(np.meshgrid(x_centers, y_centers)).T.reshape(-1, 2)<br><br># Create anchor boxes<br>anchor_boxes = np.zeros((feature_map_size, feature_map_size, anchors_per_point, 4))<br><br>for i in range(feature_map_size):<br>    for j in range(feature_map_size):<br>        for k in range(anchors_per_point):<br>            cx, cy = center_grid[i * feature_map_size + j]<br>            w, h = wh_13[k]<br>            <br>            anchor_boxes[i, j, k] = [cx, cy,w, h]<br><br># Clip the anchor boxes to ensure they&#39;re within the image boundaries<br>anchor_boxes = np.clip(anchor_boxes, 0, image_size)<br><br># Reshape the anchor boxes to (52*52*3, 4)<br>anchor_boxes_reshaped_13 = anchor_boxes.reshape(-1, 4)<br><br>print(f&quot;Shape of anchor boxes: {anchor_boxes.shape}&quot;)<br>print(f&quot;Shape of reshaped anchor boxes: {anchor_boxes_reshaped_13.shape}&quot;)<br><br>####################################################################################<br>print(&#39;------&#39;)<br><br># Define the feature map size and number of anchors per point<br>feature_map_size = 26<br>anchors_per_point = 3<br><br># Define the image size<br>image_size = 416<br><br># Create a grid of center points<br>x_centers = np.linspace(0, image_size, feature_map_size + 2)[1:-1]<br>y_centers = np.linspace(0, image_size, feature_map_size + 2)[1:-1]<br>center_grid = np.array(np.meshgrid(x_centers, y_centers)).T.reshape(-1, 2)<br><br># Create anchor boxes<br>anchor_boxes = np.zeros((feature_map_size, feature_map_size, anchors_per_point, 4))<br><br>for i in range(feature_map_size):<br>    for j in range(feature_map_size):<br>        for k in range(anchors_per_point):<br>            cx, cy = center_grid[i * feature_map_size + j]<br>            w, h = wh_26[k]<br>            <br>            anchor_boxes[i, j, k] = [cx, cy,w, h]<br><br># Clip the anchor boxes to ensure they&#39;re within the image boundaries<br>anchor_boxes = np.clip(anchor_boxes, 0, image_size)<br><br># Reshape the anchor boxes to (52*52*3, 4)<br>anchor_boxes_reshaped_26 = anchor_boxes.reshape(-1, 4)<br><br>print(f&quot;Shape of anchor boxes: {anchor_boxes.shape}&quot;)<br>print(f&quot;Shape of reshaped anchor boxes: {anchor_boxes_reshaped_26.shape}&quot;)<br><br><br>####################################################################################<br>print(&#39;------&#39;)<br><br># Define the feature map size and number of anchors per point<br>feature_map_size = 52<br>anchors_per_point = 3<br><br># Define the image size<br>image_size = 416<br><br># Create a grid of center points<br>x_centers = np.linspace(0, image_size, feature_map_size + 2)[1:-1]<br>y_centers = np.linspace(0, image_size, feature_map_size + 2)[1:-1]<br>center_grid = np.array(np.meshgrid(x_centers, y_centers)).T.reshape(-1, 2)<br><br># Create anchor boxes<br>anchor_boxes = np.zeros((feature_map_size, feature_map_size, anchors_per_point, 4))<br><br>for i in range(feature_map_size):<br>    for j in range(feature_map_size):<br>        for k in range(anchors_per_point):<br>            cx, cy = center_grid[i * feature_map_size + j]<br>            w, h = wh_52[k]<br>            <br>            anchor_boxes[i, j, k] = [cx, cy,w, h]<br><br># Clip the anchor boxes to ensure they&#39;re within the image boundaries<br>anchor_boxes = np.clip(anchor_boxes, 0, image_size)<br><br># Reshape the anchor boxes to (52*52*3, 4)<br>anchor_boxes_reshaped_52 = anchor_boxes.reshape(-1, 4)<br><br>print(f&quot;Shape of anchor boxes: {anchor_boxes.shape}&quot;)<br>print(f&quot;Shape of reshaped anchor boxes: {anchor_boxes_reshaped_52.shape}&quot;)<br><br>ab = tf.cast(tf.concat([anchor_boxes_reshaped_52,anchor_boxes_reshaped_26,anchor_boxes_reshaped_13],axis=0),tf.float32)</pre><pre>def convert_to_corners(b):<br><br>    boxes= tf.cast(b,tf.float32)<br>    return tf.concat(<br>        [boxes[..., :2] - boxes[..., 2:] / 2.0, boxes[..., :2] + boxes[..., 2:] / 2.0],<br>        axis=-1,<br>    )<br><br>def calculate_iou(gt_boxes_, anchor_boxes_):<br>    <br>    gt_boxes = convert_to_corners(gt_boxes_)<br>    anchor_boxes = convert_to_corners(anchor_boxes_)<br><br>    # Expand dimensions for broadcasting<br>    gt_boxes = tf.expand_dims(gt_boxes, axis=1)<br>    anchor_boxes = tf.expand_dims(anchor_boxes, axis=0)  <br><br>    # Calculate intersection coordinates<br>    x_left = tf.maximum(gt_boxes[:, :, 0], anchor_boxes[:, :, 0])<br>    y_top = tf.maximum(gt_boxes[:, :, 1], anchor_boxes[:, :, 1])<br>    x_right = tf.minimum(gt_boxes[:, :, 2], anchor_boxes[:, :, 2])<br>    y_bottom = tf.minimum(gt_boxes[:, :, 3], anchor_boxes[:, :, 3])<br><br>    # Calculate intersection area<br>    intersection_area = tf.maximum(0.0, x_right - x_left) * tf.maximum(0.0, y_bottom - y_top)<br><br>    # Calculate areas of gt_boxes and anchor_boxes<br>    gt_areas = (gt_boxes[:, :, 2] - gt_boxes[:, :, 0]) * (gt_boxes[:, :, 3] - gt_boxes[:, :, 1])<br>    anchor_areas = (anchor_boxes[:, :, 2] - anchor_boxes[:, :, 0]) * (anchor_boxes[:, :, 3] - anchor_boxes[:, :, 1])<br><br>    # Calculate union area<br>    union_area = gt_areas + anchor_areas - intersection_area<br><br>    # Calculate IoU<br>    iou = intersection_area / union_area<br><br>    return iou,tf.cast(tf.expand_dims(gt_boxes_,axis=1),tf.float32)</pre><p><strong>Scaling Ground Truth box to predefined Anchor boxes</strong></p><ul><li>Corresponding to all the anchor boxes created we find iou between them and all the objects in an image</li><li>We assign ground truth boxes to an anchor box with highest matching iou.</li><li>We scale the ground truth box coordinates corresponding to that particular anchor box coordinate as shown in the figure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGbNa8P_Dj0odSqifRcvZA.png" /></figure><ul><li>We also concatenate objectness_score (0 or 1 or -1) and one_hot_encoded class labels with our scaled coordinates.</li></ul><p><strong>Note:</strong> Score of 1 is assigned to matching anchor box. Score of 0 is assigned to all anchors having ious &lt; 0.2 which represents background class. Score of -1 is assigned to all those anchors having ious&gt;0.2 but not assigned ground truth boxes. -1 indicates they don’t need to be accounted during objectness_loss function.</p><pre>targets = []<br><br>for i in range(len(images)):<br>    <br>    iou, gt = calculate_iou(coord[i], ab)<br><br>    class_ = tf.expand_dims(classes[i],axis=1)<br><br>    # Get the number of objects in the image<br>    num_objects = tf.shape(coord[i])[0]<br><br>    # Find top anchor boxes for each object<br>    top_k = tf.minimum(1, tf.shape(iou)[1])  # In case there are fewer than 1 anchors<br>    _, top_indices = tf.nn.top_k(iou, k=top_k)<br><br>    # Create a mask for top anchors per object<br>    top_mask = tf.reduce_sum(tf.one_hot(top_indices, depth=tf.shape(iou)[1]), axis=1)<br>    top_mask = tf.reduce_sum(top_mask, axis=0)<br>    top_mask = tf.minimum(top_mask, 1)  # Ensure mask is binary<br><br>    # Assign labels based on new criteria<br>    iou_condition = tf.where(top_mask &gt; 0, 1.0,<br>                             tf.where(tf.reduce_max(iou, axis=0) &lt; 0.2, 0.0, -1.0))<br><br>    max_iou = tf.reduce_max(iou, axis=0)<br>    gt_idx = tf.argmax(iou, axis=0)<br><br>    l = tf.cast(tf.expand_dims(labels[i], axis=1), tf.float32)<br>    gt2= tf.concat([gt, l,class_], axis=-1)<br>    gt2_ = tf.gather(gt2, gt_idx)<br>    gt3 = tf.reshape(gt2_, [-1, 25])<br><br>    gt3_label = gt3[..., 4:] * tf.reshape(iou_condition, [-1, 1])<br><br>    gt4 = tf.concat(<br>        [<br>            (gt3[:, :2] - ab[:, :2]) / ab[:, 2:4],<br>            tf.math.log((gt3[:, 2:4] + 1e-7) / ab[:, 2:]),<br>        ],<br>        axis=-1,<br>    )<br><br>    gt4 = gt4 / [0.1, 0.1, 0.2, 0.2]<br>    gt5 = tf.concat([gt4, gt3_label], axis=-1)<br><br>    targets.append(gt5)<br>    <br>    <br>ft = tf.cast(targets,tf.float32)<br>fi = tf.cast(images,tf.float32)</pre><h3>Model Architecture</h3><ol><li>As mentioned we will use a pre-trained backbone i.e ResNet for feature extraction from the image and select 3 layers at different positions for anchor box generation. Those 3 layers will be of different feature map size i.e (52,52) from the initial layer, (26,26) from the middle layer and (13,13) from the latter layers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QyeSnPohnBss73U4v88vQ.png" /></figure><p>2. Each of those layers will predict object coordinates, objectness score and classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJRlGjJL0U_gLWElFHVe4Q.png" /></figure><pre>def get_backbone():<br>    &quot;&quot;&quot;Builds ResNet50 with pre-trained imagenet weights&quot;&quot;&quot;<br>    backbone = keras.applications.ResNet50(include_top=False, input_shape=[416,416, 3])<br>    <br>    # Freeze all layers in the backbone<br>    backbone.trainable = False<br>    <br>    outputs = [<br>        backbone.get_layer(layer_name).output<br>        for layer_name in [&quot;conv3_block4_out&quot;, &quot;conv4_block6_out&quot;,&quot;conv5_block3_out&quot;]<br>    ]<br>    return backbone, outputs<br><br>def build_head(output_filters, bias_init):<br>    &quot;&quot;&quot;Builds the class/box predictions head.&quot;&quot;&quot;<br>    kernel_init = tf.initializers.RandomNormal(0.0, 0.01)<br>    <br>    return keras.Sequential([<br>        keras.Input(shape=[None, None, 256]),<br>        keras.layers.Conv2D(256, 3, padding=&quot;same&quot;, kernel_initializer=kernel_init, activation=&quot;relu&quot;),<br>        keras.layers.Conv2D(256, 3, padding=&quot;same&quot;, kernel_initializer=kernel_init, activation=&quot;relu&quot;),<br>        keras.layers.Conv2D(256, 3, padding=&quot;same&quot;, kernel_initializer=kernel_init, activation=&quot;relu&quot;),<br>        keras.layers.Conv2D(256, 3, padding=&quot;same&quot;, kernel_initializer=kernel_init, activation=&quot;relu&quot;),<br>        keras.layers.Conv2D(<br>            output_filters, 3, 1, padding=&quot;same&quot;,<br>            kernel_initializer=kernel_init, bias_initializer=bias_init<br>        )<br>    ])<br><br>def apply_heads(feature, obj_head,cls_head, box_head):<br>    return obj_head(feature),cls_head(feature), box_head(feature)<br><br>def build_model():<br>    # Backbone<br>    backbone, (c3_output, c4_output, c5_output) = get_backbone()<br><br>    # FPN<br>    p3_output = keras.layers.Conv2D(256, 1, 1, &quot;same&quot;)(c3_output)<br>    p4_output = keras.layers.Conv2D(256, 1, 1, &quot;same&quot;)(c4_output)<br>    p5_output = keras.layers.Conv2D(256, 1, 1, &quot;same&quot;)(c5_output)<br><br>    p4_output = p4_output + keras.layers.UpSampling2D(2)(p5_output)<br>    p3_output = p3_output + keras.layers.UpSampling2D(2)(p4_output)<br><br>    p3_output = keras.layers.Conv2D(256, 3, 1, &quot;same&quot;)(p3_output)<br>    p4_output = keras.layers.Conv2D(256, 3, 1, &quot;same&quot;)(p4_output)<br>    p5_output = keras.layers.Conv2D(256, 3, 1, &quot;same&quot;)(p5_output)<br><br>    # Prediction heads<br>    prior_probability = tf.constant_initializer(-np.log((1 - 0.01) / 0.01))<br>    <br>    obj_head = build_head(3 * 1, prior_probability)<br>    cls_head = build_head(3 * 20, &#39;zeros&#39;)<br>    box_head = build_head(3 * 4, &quot;zeros&quot;)<br><br>    # Apply heads to each feature level<br>    outputs = []<br>    for feature in [p3_output, p4_output, p5_output]:<br>        obj_out,cls_out, box_out = apply_heads(feature, obj_head,cls_head, box_head)<br>        <br>        # Reshape<br>        batch_size = tf.shape(cls_out)[0]<br>        height = tf.shape(cls_out)[1]<br>        width = tf.shape(cls_out)[2]<br>        <br>        cls_out = tf.reshape(cls_out, (batch_size, height * width * 3, 20))<br>        box_out = tf.reshape(box_out, (batch_size, height * width * 3, 4))<br>        obj_out = tf.reshape(obj_out, (batch_size, height * width * 3, 1))<br>        <br>        output = tf.concat([box_out,obj_out, cls_out], axis=-1)<br>        outputs.append(output)<br>    <br>    # Concatenate outputs from all scales<br>    final_output = tf.concat(outputs, axis=1)<br>    <br>    return keras.Model(inputs=backbone.inputs, outputs=final_output)<br><br># Create the model<br>model = build_model()<br><br>model.summary()</pre><h3>Loss Function</h3><p>We will be calculating 3 losses :</p><p><strong>1. Localisation Loss (loc_loss):</strong></p><ul><li>This loss measures the difference between the predicted bounding box coordinates and the ground truth bounding box coordinates for positive samples (objects).</li><li>It uses the Huber loss function, which is less sensitive to outliers compared to mean squared error.</li><li>The loss is normalised by the number of positive samples.</li></ul><p><strong>2. Objectness Loss (obj_loss):</strong></p><ul><li>This loss measures the confidence of the model in predicting whether an anchor box contains an object or not.</li><li>It uses binary cross-entropy loss for both positive and negative samples. ( 0 &amp; 1 only. -1 label assigned anchors are not taken to account)</li><li>For negative samples, hard negative mining is applied to select the top 3 * num_pos (three times the number of positive samples) hardest negatives based on their cross-entropy loss. This helps focus the training on the most challenging negative examples.</li><li>The loss is normalised by the number of positive samples.</li></ul><p><strong>3. Class Loss (class_cross_entropy):</strong></p><ul><li>This loss measures the accuracy of the model in predicting the class of the object within a positive anchor box.</li><li>It uses categorical cross-entropy loss.</li><li>The loss is normalised by the number of positive samples.</li></ul><p><strong>Total Loss:</strong></p><p>The total loss is the sum of the localisation loss, objectness loss, and class loss. This combined loss function encourages the model to learn accurate bounding box predictions, correctly classify objects, and distinguish between objects and background.</p><h4><strong>Hard Negative Mining</strong></h4><p>Imagine you’re training a model to detect cats in images. You have lots of images with cats (positive samples) and lots without cats (negative samples).</p><p>During training, the model might easily learn to identify clear cat images. But it might struggle with images that are blurry, have cats partially hidden, or have objects that look <em>similar</em> to cats. These tricky negative samples are the “hard negatives”.</p><p>Hard negative mining focuses the model’s attention on these challenging negative examples. Instead of treating all negatives equally, it selects the ones that the model is <em>most</em> likely to misclassify as positive.</p><p>Here’s how it works in the code:</p><ol><li><strong>Calculate cross-entropy loss for all negative samples.</strong> This measures how confident the model is that each negative sample <em>doesn’t</em> contain a cat.</li><li><strong>Select the top ‘k’ negative samples with the highest loss.</strong> These are the “hardest” negatives because the model is most uncertain about them.</li><li><strong>Only use these hard negatives for calculating the objectness loss.</strong> This forces the model to learn better representations and become more robust to these challenging cases.</li></ol><p>By focusing on the hardest negatives, hard negative mining helps the model improve its overall performance and generalisation ability.</p><pre>def total_loss(y_true, y_pred):<br>    y_true = tf.cast(y_true, dtype=tf.float32)<br>    y_pred = tf.cast(y_pred, dtype=tf.float32)<br><br>    pos_mask = tf.cast(tf.equal(tf.squeeze(y_true[..., 4:5], axis=-1), 1.0), tf.float32)<br>    <br>    neg_mask = tf.cast(tf.equal(tf.squeeze(y_true[..., 4:5], axis=-1), 0.0), tf.float32)<br><br>    num_pos = tf.maximum(1.0, tf.cast(tf.math.count_nonzero(pos_mask, axis=-1), tf.float32))<br><br>    loc_loss = tf.compat.v1.losses.huber_loss(labels=y_true[..., :4],<br>                                              predictions=y_pred[..., :4],<br>                                              reduction=&quot;none&quot;)<br>    loc_loss = tf.reduce_sum(loc_loss, axis=-1)<br>    loc_loss = tf.where(tf.equal(pos_mask, 1.0), loc_loss, 0.0)<br>    loc_loss = tf.reduce_sum(loc_loss, axis=-1)<br>    loc_loss = loc_loss / num_pos<br>    <br>    # OBJECT LOSS<br>    cce = tf.losses.BinaryCrossentropy(from_logits=True, reduction=&#39;none&#39;)<br>    cross_entropy = cce(y_true[..., 4:5], y_pred[..., 4:5])<br><br>    num_neg = 3*num_pos<br><br>    neg_cross_entropy = tf.where(tf.equal(neg_mask, 1.0), cross_entropy, 0.0)<br>    sorted_dfidx = tf.cast(tf.argsort(neg_cross_entropy, direction=&#39;DESCENDING&#39;, axis=-1), tf.int32)<br>    rank = tf.cast(tf.argsort(sorted_dfidx, axis=-1), tf.int32)<br>    num_neg = tf.cast(num_neg, dtype=tf.int32)<br>    <br>    neg_loss = tf.where(rank &lt; tf.expand_dims(num_neg, axis=1), neg_cross_entropy, 0.0)<br>    pos_loss = tf.where(tf.equal(pos_mask, 1.0), cross_entropy, 0.0)<br><br>    # Combine objectness losses<br>    obj_loss = tf.reduce_sum(pos_loss + neg_loss, axis=-1)<br>    obj_loss = obj_loss / num_pos  # Normalize by number of positive samples<br>    <br>    <br>    # classes<br>    cce = tf.losses.CategoricalCrossentropy(from_logits=True, reduction=&#39;none&#39;)<br>    class_cross_entropy = cce(y_true[...,5:],y_pred[...,5:])<br>    class_cross_entropy = tf.where(tf.equal(pos_mask, 1.0), class_cross_entropy, 0.0)<br>    class_cross_entropy = tf.reduce_sum(class_cross_entropy, axis=-1)/num_pos<br><br>    # Combine losses<br>    total_loss = loc_loss + obj_loss + class_cross_entropy<br>    return total_loss</pre><h4>Training</h4><pre># Define the learning rate schedule<br>def lr_schedule(epoch, lr):<br>    return lr * 0.99<br><br># Create the learning rate scheduler callback<br>lr_scheduler = keras.callbacks.LearningRateScheduler(lr_schedule)<br><br># Define your initial learning rate<br>initial_lr = 1e-4<br><br># Compile the model with Adam optimizer and your custom learning rate<br>optimizer = keras.optimizers.Adam(learning_rate=initial_lr)<br><br>model.compile(loss=total_loss, optimizer=optimizer)<br><br>model.fit(fi, ft, epochs=50, callbacks=[lr_scheduler])</pre><h4>Inference</h4><pre>def decode_predictions(y_pred, anchor_boxes):<br>    # Assuming y_pred has shape [batch_size, num_anchors, 4]<br>    # and anchor_boxes has shape [num_anchors, 4]<br>    <br>    # Split the predictions into center and size components<br>    pred_xy = y_pred[..., :2]<br>    pred_wh = y_pred[..., 2:]<br>    <br>    # Decode center coordinates<br>    decoded_xy = pred_xy * anchor_boxes[..., 2:4] + anchor_boxes[..., :2]<br>    <br>    # Decode width and height<br>    decoded_wh = tf.math.exp(pred_wh) * anchor_boxes[..., 2:4]<br>    <br>    # Combine to get final bounding box coordinates<br>    decoded_boxes = tf.concat([decoded_xy, decoded_wh], axis=-1)<br>    <br>    return decoded_boxes<br><br>for j in range(30):<br>    <br>    pred = model.predict(fi[j:j+1])<br>    idx = tf.argsort(pred[...,4])[0][::-1][:25]<br>    scores = tf.sort(pred[...,4])[0][::-1][:25]<br>    pred1 = pred[...,:4]*[0.1, 0.1, 0.2, 0.2]<br>    pred2 = decode_predictions(tf.cast(pred1,tf.float32), ab)<br>    pred3 = np.array(pred2[0])[idx]<br>    <br>    label = pred[...,5:][0][idx]<br>    xmin = pred3[:,0] - pred3[:,2]/2<br>    ymin = pred3[:,1] - pred3[:,3]/2<br>    xmax = pred3[:,0] + pred3[:,2]/2<br>    ymax = pred3[:,1] + pred3[:,3]/2<br>    fp = np.vstack((xmin,ymin,xmax,ymax)).T<br>    idxx = tf.image.non_max_suppression(fp, scores, max_output_size=10, iou_threshold=0.2, score_threshold=float(&#39;-inf&#39;))<br>    image = images[j].copy()<br>    for i in idxx:<br>        <br>        fpp = fp[i]<br>        <br>        label_ = label[i]<br>        label_ = LABELS[tf.argmax(label_)]<br>        # Extract bounding box coordinates and class index.<br>        x_min, y_min, x_max, y_max = fpp<br>        # Draw bounding box rectangle on the image.<br>        cv2.rectangle(image, (int(x_min), int(y_min)), (int(x_max), int(y_max)), (0, 255, 0), 2)<br>        <br>        # Calculate the center of the bounding box<br>        center_x = int((x_min + x_max) / 2)<br>        center_y = int((y_min + y_max) / 2)<br>        <br>        # Get text size<br>        (text_width, text_height), _ = cv2.getTextSize(label_, cv2.FONT_HERSHEY_SIMPLEX, 0.9, 2)<br>        <br>        # Calculate text position to center it in the bounding box<br>        text_x = center_x - text_width // 2<br>        text_y = center_y + text_height // 2<br>        <br>        # Add class text in the center of the bounding box<br>        cv2.putText(image, label_, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)<br>    <br>    plt.imshow(image)<br>    plt.show()</pre><h4>Prediction Examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*ZTf_3Qgmh68eAFtXCFb1Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*S6KKACa8dbs9PrGZeAnI3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*4Jln5QyJKDIkrVmJ1w8ieQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*iYeKUMJfHRaouBCnUfcnLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*KRBklwJK2Ao6aC-4O1zhGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*oO7hCnF6am6Vcicqtg9sBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*wN6Pulo8QLaX3KqqXmT1_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*iv3MprCv1xLdKMh2MLGHTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*3WO2naVjvs1K4yHEbYMuTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*7_FeHxH4vvFiIaT_r3Ukdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*vzWskcnmSF4GzD9KiVC8hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*QkW_lNZaT5xynRasbPA2AA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*1aOnYigrCniH_6aX3A5V5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*wa3aUHrzN7nxPMgL4YXFgQ.png" /></figure><p>And thats all folks! If you spot mistakes or think few improvements could be made please reach out or comment.</p><h4><strong>Thank You ! </strong>🙏</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=430e8ad50b85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>