<?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 Kari Vierimaa on Medium]]></title>
        <description><![CDATA[Stories by Kari Vierimaa on Medium]]></description>
        <link>https://medium.com/@kavierim?source=rss-365d6b1a19de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GhDRiOuIJeVXO0FC</url>
            <title>Stories by Kari Vierimaa on Medium</title>
            <link>https://medium.com/@kavierim?source=rss-365d6b1a19de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:21:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kavierim/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[Demystifying Isometric Projection in 2D Games (with Python!)]]></title>
            <link>https://medium.com/@kavierim/demystifying-isometric-projection-in-2d-games-with-python-bbcc2038a620?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbcc2038a620</guid>
            <category><![CDATA[2d-graphics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[isometric-projection]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 19:22:47 GMT</pubDate>
            <atom:updated>2025-04-15T19:22:47.751Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Unlock the secrets of the classic 2.5D look: Learn the math, code the transformations in Python, and navigate the challenges of isometric game development.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-Ewx4CQbHY5VNGxsC91eQ.png" /><figcaption>Credit to ChatGPT</figcaption></figure><h3>1. Introduction: Stepping into the Isometric World</h3><p>There’s an undeniable charm to the isometric perspective in video games. From the pioneering flights of <em>Zaxxon</em> and the dungeon crawls of <em>Diablo II</em> to the strategic planning in <em>Age of Empires II</em> and the modern adventures in <em>Hades</em>, the isometric view has offered a unique window into countless virtual worlds. This “pseudo-3D” or “2.5D” look provides a sense of depth and dimensionality distinct from traditional top-down or side-scrolling games, captivating players across decades and genres.</p><p>However, achieving this distinctive visual style involves specific graphical techniques and mathematical transformations that can seem daunting to developers new to the concept. How are 3D-like environments represented using 2D graphics? How are coordinates translated between the game’s logical grid and the pixels on the screen? How are objects layered correctly to maintain that crucial illusion of depth?</p><p>This post aims to demystify isometric projection for beginner-to-intermediate game developers and programmers interested in game graphics. It will delve into the core concepts, explore the underlying mathematics, provide practical implementation examples using Python (with Pygame), discuss common development techniques and challenges, and compare isometric projection with other common viewpoints. By the end, developers should have a solid understanding of how isometric projection works and how to start implementing it in their own 2D game projects. The journey will cover the definition and visual characteristics, the essential coordinate transformations, Python code illustrations, key techniques like depth sorting and tile mapping, and a comparison with other projections.</p><h3>2. Decoding Isometric Projection: Definition and Visuals</h3><p>Understanding isometric projection begins with grasping its place within graphical projection methods and its specific visual traits.</p><p>Core Definition: Parallel Lines and Axonometry</p><p>At its heart, isometric projection is a method for visually representing three-dimensional objects in two dimensions. It falls under the category of parallel projection, meaning that the lines projecting from the 3D object onto the 2D view plane are parallel to each other. This contrasts sharply with perspective projection, where projection lines converge at a single point. Because isometric projection uses parallel lines, objects retain their size regardless of their distance from the viewer.</p><p>More specifically, isometric projection is a type of <strong>axonometric projection</strong>, which itself is a form of orthographic projection where the object is rotated relative to the projection plane to reveal multiple sides. In axonometric projections, the three coordinate axes (X, Y, Z) of the object appear foreshortened on the 2D plane.</p><p>“Equal Measure”: The Ideal Isometric View</p><p>The term “isometric” originates from the Greek for “equal measure”. This name reflects a key characteristic of true isometric projection: the scale along each of the three projected axes is identical, and the angle between any two of these projected axes is exactly 120 degrees. Imagine a cube viewed isometrically; its edges are equally foreshortened, and the resulting 2D outline forms a perfect regular hexagon. This equal measurement ensures a balanced view of the object’s three dimensions. Achieving this view mathematically involves specific rotations before the final orthographic projection.</p><p>Visual Characteristics</p><p>Several visual traits define the isometric look:</p><ul><li><strong>Lack of Perspective Shortening:</strong> Objects do not shrink with distance. This can create a perceived distortion compared to human vision but is useful for technical views.</li><li><strong>Fixed Viewpoint:</strong> The angled “3/4 view” reveals top, front, and side facets simultaneously, creating the characteristic pseudo-3D effect.</li><li><strong>Potential for Ambiguity:</strong> The absence of perspective cues can sometimes make judging depth or relative positions difficult.</li></ul><p>The “Game Isometric” Reality: Dimetric Projection &amp; the 2:1 Ratio</p><p>Here’s a crucial point for game developers: most games we call “isometric” actually use a slight variation, typically a form of dimetric projection. In dimetric projection, only two axes have equal foreshortening and angles.</p><p>The most common variant in pixel art uses a <strong>2:1 pixel ratio</strong>. Instead of the 30° angle of true isometric, the grid axes are drawn at roughly 26.565° (arctan(1/2)). This clever trick means that for every <em>two</em> pixels moved horizontally, the line moves exactly <em>one</em> pixel vertically.</p><p>Why this deviation? Practicality! The 2:1 ratio produces much cleaner, smoother lines on pixel grids (less aliasing) and simplifies rendering calculations, especially for older hardware. It also makes life significantly easier for artists creating tileable assets that fit together perfectly. So, when we talk about implementing isometric projection for classic 2D games, we’re almost always talking about this 2:1 dimetric standard.</p><p>Common Uses</p><p>The isometric perspective is particularly well-suited for genres that benefit from a clear overview of a spatial environment, like Role-Playing Games (RPGs), Real-Time Strategy (RTS) games, city builders, and simulation games. The view allows players to easily manage units, plan strategically, and understand spatial relationships without cumbersome camera controls.</p><h3>3. The Mathematical Foundation: Transforming Coordinates</h3><p>At the core of rendering an isometric game lies the mathematics of coordinate transformation. Game logic often operates in a simple, abstract grid system, but rendering happens in the 2D pixel space of the screen. Bridging this gap requires specific formulas.</p><p>Understanding the Coordinate Systems</p><p>Three main coordinate systems are typically involved:</p><ul><li><strong>Map/Grid Coordinates (mapX, mapY):</strong> The logical representation of the game world, often a 2D array. Most game logic happens here. Units are typically tiles (e.g., tile (3, 5)).</li><li><strong>World Coordinates (worldX, worldY, worldZ):</strong> Represents a conceptual 3D space. The Z coordinate usually represents height. Relevant when dealing with varying heights.</li><li><strong>Screen Coordinates (screenX, screenY):</strong> The final pixel coordinates on the 2D display. The origin (0,0) is typically at the top-left.</li></ul><p><strong>Transformation 1:</strong> Map/Grid to Screen Coordinates (Projection)</p><p>This is the core transformation for drawing your map onto the screen. For the common 2:1 dimetric projection, we observe:</p><ul><li>Increasing mapX by 1 (moving &quot;east&quot;) increases screenX (moves right) and screenY (moves down).</li><li>Increasing mapY by 1 (moving &quot;south&quot;) <em>decreases</em> screenX (moves left) and increases screenY (moves down).</li></ul><p>Assuming tileWidth and tileHeight are the dimensions of the full isometric tile graphic (e.g., 128x64), and tileWidthHalf and tileHeightHalf are half those values (e.g., 64 and 32), the standard formulas are:</p><pre>screenX = (mapX - mapY) * tileWidthHalf<br>screenY = (mapX + mapY) * tileHeightHalf</pre><p>(Note: tileHeightHalf is often tileWidthHalf / 2 for the strict 2:1 ratio, making it tileWidth / 4)</p><p>You’ll also usually add a screen offset (originX, originY) to position the map&#39;s origin on the screen.</p><p><strong>Transformation 2:</strong> Screen to Map/Grid Coordinates (Inverse Projection)</p><p>Needed for interactivity, like figuring out which tile the mouse is over (mouse picking). You can derive these by solving the map-to-screen equations algebraically. Remember to subtract the screen offset before applying these:</p><pre>mapX_float = (screenX / tileWidthHalf + screenY / tileHeightHalf) / 2<br>mapY_float = (screenY / tileHeightHalf - screenX / tileWidthHalf) / 2</pre><p>These give floating-point values. Use floor() or cast to int to get the integer tile indices.</p><pre>mapX = floor(mapX_float)<br>mapY = floor(mapY_float)</pre><p><strong>Transformation 3:</strong> 3D World Coordinates to 2D Isometric Screen Coordinates</p><p>If your game uses true 3D positions (e.g., for height), you need to project worldX, worldY, worldZ. For the common dimetric (2:1) view, a practical approach adapts the map-to-screen formulas, treating worldX, worldY like mapX, mapY on the Z=0 plane, and then adjusting screenY based on worldZ:</p><pre># Dimetric adaptation incorporating world Z for height<br>screenX = (worldX - worldY) * tileWidthHalf<br>screenY = (worldX + worldY) * tileHeightHalf - worldZ * Z_Scale_Factor</pre><p>The Z_Scale_Factor might be tileHeightHalf or even tileHeight, depending on how much vertical shift you want per unit of height.</p><p>These transformations act as a bridge between your simple game logic grid and the skewed visual representation on screen, and back again for input. Developers often create abstraction layers so the core game logic doesn’t need to worry about the isometric skew.</p><h3>4. Bringing it to Life with Python</h3><p>Translating the mathematical formulas into working code is the next step. Python, combined with a library like Pygame for graphics and input, provides a suitable environment for experimenting with isometric projection. The built-in math module handles necessary calculations like floor, random can be used for variety, and pygame.math.Vector2 is highly recommended for simplifying coordinate manipulation.</p><p>Setup:</p><p>Ensure Python and Pygame are installed (pip install pygame). We’ll also import the random module.</p><pre>import pygame<br>import math<br>import random # Import the random module<br><br># --- Constants ---<br>SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600<br>BACKGROUND_COLOR = (0, 0, 20) # Dark Blue<br>HIGHLIGHT_COLOR = (255, 255, 0, 150) # Yellow, semi-transparent<br>GRID_LINE_COLOR = (50, 50, 50) # Dark grey for grid lines<br><br># Define two different tile colors<br>TILE_COLOR_A = (0, 150, 0) # Green<br>TILE_COLOR_B = (0, 100, 150) # Bluish-Green<br><br># Isometric Tile Dimensions (using 2:1 ratio)<br>TILE_WIDTH = 128<br>TILE_HEIGHT = TILE_WIDTH // 2<br>TILE_WIDTH_HALF = TILE_WIDTH // 2<br>TILE_HEIGHT_HALF = TILE_HEIGHT // 2<br><br># Map Dimensions (Example: 10x10 grid)<br>MAP_WIDTH = 10<br>MAP_HEIGHT = 10<br><br># Screen offset<br>SCREEN_OFFSET_X = (SCREEN_WIDTH - (MAP_WIDTH + MAP_HEIGHT) * TILE_WIDTH_HALF / 2) / 2 + (MAP_WIDTH * TILE_WIDTH_HALF / 2)<br>SCREEN_OFFSET_Y = 100<br>SCREEN_OFFSET = pygame.math.Vector2(SCREEN_OFFSET_X, SCREEN_OFFSET_Y)<br></pre><p><strong>Code Example 1: Map-to-Screen Transformation</strong></p><p>This function converts map/grid coordinates to screen pixel coordinates, implementing the common 2:1 dimetric projection.</p><pre>def map_to_screen(map_pos):<br>    &quot;&quot;&quot;Converts map (grid) coordinates to screen pixel coordinates (2:1 dimetric).&quot;&quot;&quot;<br>    screen_x = (map_pos.x - map_pos.y) * TILE_WIDTH_HALF<br>    screen_y = (map_pos.x + map_pos.y) * TILE_HEIGHT_HALF<br>    screen_pos = pygame.math.Vector2(screen_x, screen_y) + SCREEN_OFFSET<br>    return screen_pos</pre><p><strong>Code Example 2: Screen-to-Map Transformation</strong></p><p>This function performs the inverse operation, converting screen pixel coordinates back to map/grid coordinates, useful for mouse interaction.</p><pre>def screen_to_map(screen_pos):<br>    &quot;&quot;&quot;Converts screen pixel coordinates back to map (grid) coords (2:1 dimetric).&quot;&quot;&quot;<br>    adjusted_screen_pos = screen_pos - SCREEN_OFFSET<br>    map_x_float = (adjusted_screen_pos.x / TILE_WIDTH_HALF + adjusted_screen_pos.y / TILE_HEIGHT_HALF) / 2<br>    map_y_float = (adjusted_screen_pos.y / TILE_HEIGHT_HALF - adjusted_screen_pos.x / TILE_WIDTH_HALF) / 2<br>    return pygame.math.Vector2(map_x_float, map_y_float)</pre><p><strong>Code Example 3: Setting up Map Data with Random Colors</strong></p><p>Instead of just storing a tile type, we can store specific data for each tile, like its color. Here, we randomly assign one of two predefined colors to each tile during setup.</p><pre># --- Create Map Data with Random Colors ---<br>map_data = {}<br>for y in range(MAP_HEIGHT):<br>    for x in range(MAP_WIDTH):<br>        # Randomly choose one of the two colors for this tile<br>        chosen_color = random.choice([TILE_COLOR_A, TILE_COLOR_B])<br>        # Store the chosen color in the map data dictionary<br>        map_data[(x, y)] = {&#39;color&#39;: chosen_color}<br><br># Store map coordinates for easier iteration and sorting<br>map_coords_list = list(map_data.keys())<br>map_coords_list.sort(key=lambda coord: (coord[1], coord[0])) # Simple depth sort</pre><p><strong>Code Example 4: Basic Drawing Loop with Polygons and Click Interaction</strong></p><p>This conceptual loop shows how to iterate through the sorted map coordinates, retrieve the stored color for each tile, draw it using pygame.draw.polygon, and handle mouse clicks to identify the clicked tile&#39;s color.</p><pre># --- Helper functions for drawing polygons (Reverted to this method) ---<br>def draw_iso_tile_outline(surface, screen_pos, color, line_width=1):<br>    &quot;&quot;&quot;Draws the diamond shape outline of an isometric tile.&quot;&quot;&quot;<br>    points = [<br>        screen_pos,<br>        screen_pos + pygame.math.Vector2(TILE_WIDTH_HALF, TILE_HEIGHT_HALF),<br>        screen_pos + pygame.math.Vector2(0, TILE_HEIGHT),<br>        screen_pos + pygame.math.Vector2(-TILE_WIDTH_HALF, TILE_HEIGHT_HALF)<br>    ]<br>    pygame.draw.lines(surface, color, True, points, line_width)<br><br>def draw_iso_tile_filled(surface, screen_pos, color):<br>    &quot;&quot;&quot;Draws the filled diamond shape of an isometric tile.&quot;&quot;&quot;<br>    points = [<br>        screen_pos,<br>        screen_pos + pygame.math.Vector2(TILE_WIDTH_HALF, TILE_HEIGHT_HALF),<br>        screen_pos + pygame.math.Vector2(0, TILE_HEIGHT),<br>        screen_pos + pygame.math.Vector2(-TILE_WIDTH_HALF, TILE_HEIGHT_HALF)<br>    ]<br>    pygame.draw.polygon(surface, color, points)<br><br># --- Main Game Setup ---<br>pygame.init()<br>screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))<br>pygame.display.set_caption(&quot;Isometric Demo - Random Colors&quot;) # Updated caption<br>clock = pygame.time.Clock()<br>font = pygame.font.Font(None, 24)<br><br><br><br>mouse_screen_pos = pygame.math.Vector2(0, 0)<br>selected_map_tile = None<br><br># --- Game Loop ---<br>running = True<br>while running:<br>    # --- Event Handling ---<br>    for event in pygame.event.get():<br>        if event.type == pygame.QUIT:<br>            running = False<br>        if event.type == pygame.MOUSEMOTION:<br>            mouse_screen_pos = pygame.math.Vector2(event.pos)<br>        if event.type == pygame.MOUSEBUTTONDOWN:<br>            map_float = screen_to_map(mouse_screen_pos)<br>            clicked_tile_coord = (math.floor(map_float.x), math.floor(map_float.y))<br>            # Check if the click is within the map bounds<br>            if 0 &lt;= clicked_tile_coord[0] &lt; MAP_WIDTH and 0 &lt;= clicked_tile_coord[1] &lt; MAP_HEIGHT:<br>                # *** Retrieve and print the color of the clicked tile ***<br>                clicked_tile_info = map_data.get(clicked_tile_coord)<br>                if clicked_tile_info:<br>                    clicked_tile_color = clicked_tile_info[&#39;color&#39;]<br>                    print(f&quot;Clicked Tile: {clicked_tile_coord}, Stored Color: {clicked_tile_color}&quot;)<br>                else: # Should not happen if bounds check passes, but good practice<br>                     print(f&quot;Clicked Tile: {clicked_tile_coord}, but no data found?&quot;)<br>            else:<br>                print(f&quot;Clicked outside map area.&quot;)<br><br>    # --- Update Logic ---<br>    current_hover_map_float = screen_to_map(mouse_screen_pos)<br>    current_hover_map_tile = (math.floor(current_hover_map_float.x), math.floor(current_hover_map_float.y))<br><br>    if 0 &lt;= current_hover_map_tile[0] &lt; MAP_WIDTH and 0 &lt;= current_hover_map_tile[1] &lt; MAP_HEIGHT:<br>        selected_map_tile = current_hover_map_tile<br>    else:<br>        selected_map_tile = None<br><br>    # --- Drawing ---<br>    screen.fill(BACKGROUND_COLOR)<br><br>    # Draw the map tiles using stored colors<br>    for map_x, map_y in map_coords_list:<br>        map_pos = pygame.math.Vector2(map_x, map_y)<br>        screen_pos = map_to_screen(map_pos)<br><br>        # *** Get the color for this specific tile from map_data ***<br>        tile_info = map_data.get((map_x, map_y))<br>        if tile_info:<br>            tile_color = tile_info[&#39;color&#39;]<br>            # Draw the filled tile with its assigned color<br>            draw_iso_tile_filled(screen, screen_pos, tile_color)<br>            # Draw a thin outline for definition<br>            draw_iso_tile_outline(screen, screen_pos, GRID_LINE_COLOR, 1)<br>        else:<br>             # Fallback if data missing (shouldn&#39;t happen here)<br>             draw_iso_tile_outline(screen, screen_pos, (255,0,0), 2)<br><br><br>    # Highlight the selected tile<br>    if selected_map_tile:<br>        selected_screen_pos = map_to_screen(pygame.math.Vector2(selected_map_tile[0], selected_map_tile[1]))<br>        # Use outline for highlight over polygons<br>        draw_iso_tile_outline(screen, selected_screen_pos, (255, 255, 0), 3) # Thicker yellow outline<br><br><br>    # Display coordinates (Unchanged)<br>    mouse_text = font.render(f&quot;Mouse Screen: ({int(mouse_screen_pos.x)}, {int(mouse_screen_pos.y)})&quot;, True, (255, 255, 255))<br>    map_text_float = font.render(f&quot;Calculated Map (Float): ({current_hover_map_float.x:.2f}, {current_hover_map_float.y:.2f})&quot;, True, (255, 255, 255))<br>    if selected_map_tile:<br>        map_text_int = font.render(f&quot;Hovered Map Tile: {selected_map_tile}&quot;, True, (255, 255, 255))<br>    else:<br>         map_text_int = font.render(f&quot;Hovered Map Tile: (Outside Map)&quot;, True, (255, 255, 255))<br>    screen.blit(mouse_text, (10, 10))<br>    screen.blit(map_text_float, (10, 30))<br>    screen.blit(map_text_int, (10, 50))<br><br>    # --- Update Display ---<br>    pygame.display.flip()<br>    clock.tick(60)<br><br># --- Clean Up ---<br>pygame.quit()</pre><p>This setup demonstrates the core coordinate transformations and how to manage tile-specific data (like color) within your map structure. Clicking allows you to verify the screen_to_map conversion and retrieve data associated with a specific grid location.</p><p><strong>Full code example link:</strong> <a href="https://github.com/kavierim/Medium/blob/main/Isometric_Projection_in_2D_Games/isometric_demo.py">https://github.com/kavierim/Medium/blob/main/Isometric_Projection_in_2D_Games/isometric_demo.py</a></p><h3>5. Navigating Isometric Game Development: Techniques &amp; Challenges</h3><p>Beyond the core mathematics, several practical techniques and inherent challenges shape the development of isometric games.</p><p><strong>Tile Mapping: Building the World</strong></p><p>The foundation of many isometric environments is tile mapping:</p><ul><li><strong>Grid Structures:</strong> The game world is typically conceptualized and stored as a 2D grid or array.</li><li><strong>Tile Dimensions:</strong> Isometric tile graphics often have dimensions reflecting the 2:1 projection ratio, such as 64x32 pixels or 128x64 pixels. The tileWidthHalf and tileHeightHalf used in the formulas correspond to these.</li><li><strong>Layouts:</strong> The “diamond” layout, where grid lines run diagonally on the screen, is naturally produced by the common transformation formulas. Tiles are placed onto the screen using the map_to_screen function.</li><li><strong>Tilesets:</strong> Tile graphics are often combined into larger images called tilesets or sprite sheets for efficiency.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*v1M79l1Kpg2Rql-wLQSF6A.png" /><figcaption>Code in action</figcaption></figure><p><strong>Depth Sorting: The Painter’s Problem</strong></p><p>One of the most significant hurdles in pure 2D isometric rendering is correctly layering objects to create a convincing illusion of depth. Simply drawing tiles based on map layers often fails.</p><ul><li><strong>The Challenge:</strong> An object’s logical position in the map grid doesn’t always guarantee its correct visual layering relative to other objects, especially with varying heights or sizes.</li><li><strong>Painter’s Algorithm:</strong> The fundamental solution is the Painter’s Algorithm: draw objects in order from farthest away (back) to closest (front).</li><li><strong>Simple Sorting Key:</strong> For basic tile maps, sorting all drawable entities based on their map coordinates before rendering each frame is common. A frequently used sort key is mapY or the sum mapX + mapY. Rendering in increasing order of this key generally draws rows or diagonals from back to front.</li><li><strong>Incorporating Height (Z):</strong> When objects have varying heights, the simple sort key is insufficient. The Z dimension must be factored in, perhaps using a key like mapX + mapY + worldZ * Weight.</li><li><strong>Limitations:</strong> Simple sorting based on a single point is inherently flawed and breaks down with large objects, tall objects overlapping shorter ones, or complex shapes.</li><li><strong>Advanced Techniques:</strong> Achieving perfect sorting in pure 2D often requires more sophisticated methods, such as dividing large objects, using multiple rendering layers, topological sorts, or using a 3D engine with an orthographic camera and its built-in Z-buffer. This “leaky abstraction” means grappling with 3D spatial problems despite the 2D foundation.</li></ul><p><strong>Character Movement and Collision</strong></p><p>Integrating character movement involves mapping input to the grid and performing checks within the logical map space:</p><ul><li><strong>Input Mapping:</strong> User input (e.g., arrow keys) needs to be translated into intended movement along the map’s axes (e.g., ‘Up’ might decrement mapY). Isometric characters typically require sprites for multiple directions (often 8).</li><li><strong>Movement Logic:</strong> Perform movement calculations using map coordinates.</li><li><strong>Grid-Based Collision:</strong> Check the target tile in the map data. Allow movement only if the target tile is marked ‘walkable’.</li><li><strong>Rendering:</strong> Use map_to_screen to calculate the drawing coordinates after a valid move.</li></ul><h3>6. Conclusion: Your Next Steps in Isometric Development</h3><p>Isometric projection offers a compelling way to present game worlds, blending the clarity of 2D graphics with the depth illusion of 3D. While often associated with classic titles, its unique advantages ensure its continued relevance in modern game development.</p><p>This exploration covered the fundamental definition, distinguishing between true isometric and the common 2:1 dimetric projection used in games. The core mathematical transformations for converting between map/grid coordinates and screen coordinates were detailed. Practical Python code examples, leveraging Pygame, demonstrated how to implement these transformations and build a basic interactive isometric grid using simple polygon drawing and storing tile-specific data. Key development techniques like tile mapping and the significant challenge of depth sorting were discussed, alongside a comparison highlighting isometric’s strengths and weaknesses.</p><p>The journey into isometric development might seem complex initially, particularly concerning depth sorting. However, the foundational coordinate transformations are based on straightforward geometry and algebra. The provided formulas and Python code serve as a starting point for experimentation. Developers are encouraged to build upon this simple demo — perhaps adding more tile types, experimenting with basic image loading (pygame.image.load), or tackling simple character movement on the grid. Tackling these smaller projects can solidify understanding and provide a platform for exploring more advanced techniques as needed.</p><p>The world of isometric game development, with its rich history and enduring appeal, is well worth exploring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbcc2038a620" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 10 — Beyond Greedy Search & Next Steps]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-10-beyond-greedy-search-next-steps-65010b043996?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/65010b043996</guid>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[further-learning]]></category>
            <category><![CDATA[decoding-strategies]]></category>
            <category><![CDATA[beam-search]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 11:12:16 GMT</pubDate>
            <atom:updated>2025-04-13T11:12:16.958Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 10 — Beyond Greedy Search &amp; Next Steps</h3><p>Discusses advanced decoding techniques, limitations of the scratch build, and directions for further improvements and learning.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 10 — Beyond Greedy Search &amp; Next Steps</h3><p>Welcome to the concluding (and optional) part of our “Transformers From Scratch” series! Over the previous nine parts, we meticulously built a complete Transformer model, piece by piece, culminating in training it on a simple task (<a href="https://medium.com/p/36571a8fd0ff">Part 8</a>) and generating sequences using basic greedy decoding (<a href="https://medium.com/p/9436681abb2e">Part 9</a>).</p><p>Congratulations on making it this far! You now have a much deeper understanding of the inner workings of this powerful architecture.</p><p>In this final part, we’ll reflect on what we’ve built and look ahead:</p><ol><li>Discuss the limitations of Greedy Decoding and explore better strategies.</li><li>Highlight areas where our scratch implementation could be improved or extended.</li><li>Suggest directions for further learning and applying your knowledge.</li></ol><h3>Beyond Greedy Decoding</h3><p>In <a href="https://medium.com/p/9436681abb2e">Part 9</a>, we used Greedy Decoding for generation. It’s simple and fast, but often produces suboptimal results because it only considers the single best token at each step, potentially leading it down a path that isn’t globally optimal or becomes repetitive. Let’s look at better alternatives:</p><h3>1. Beam Search</h3><p>Instead of just keeping the single most likely next token, Beam Search maintains k (the &quot;beam width&quot;) most probable partial sequences (beams) at each step.</p><p><strong>Algorithm Sketch:</strong></p><ol><li>Encode the source sequence. Initialize k beams, each starting with [SOS] and having a score (log probability) of 0.</li><li>Loop for each step up to max_len:<br><strong>a</strong>. For each current beam (partial sequence), predict the logits for the next token using the decoder.<br><strong>b</strong>. Calculate the probabilities (e.g., using log-softmax) for all possible next tokens for all beams.<br><strong>c</strong>. Consider all possible next sequences by extending each beam with every possible next token. Calculate the score for each extended sequence (usually sum of log probabilities).<br><strong>d</strong>. Select the top k highest-scoring extended sequences from the entire pool. These become the new set of beams for the next step.<br><strong>e</strong>. Handle completed sequences (those ending in [EOS]) — store them separately and potentially remove them from the active beams if enough completed sequences are found.</li><li>After the loop (or early stopping), select the highest-scoring completed sequence from the stored list.</li></ol><p>Pros: Often produces more fluent and higher-probability sequences than greedy search.</p><p>Cons: Computationally more expensive (k times the work at each step). Can still favor common/safe sequences and might lack diversity. Requires careful implementation to handle scores and completed beams.</p><h3>2. Sampling Methods</h3><p>Instead of deterministically picking the best token(s), sampling introduces randomness, leading to more diverse and potentially creative outputs.</p><ul><li><strong>Temperature Sampling:</strong> Logits are divided by a temperature value (T) before applying softmax (softmax(logits / T)).<br>T &lt; 1.0: Sharpens the probability distribution, making high-probability tokens even more likely (closer to greedy, less random).<br>T &gt; 1.0: Flattens the distribution, increasing the chance of lower-probability tokens being selected (more random, diverse, potentially less coherent).<br>T = 1.0: Standard softmax probabilities.</li><li><strong>Top-K Sampling:</strong> At each step, only consider the k most probable tokens. Zero out the probability of all other tokens and then re-normalize the probabilities among the top k before sampling. This avoids sampling from the long tail of very unlikely tokens.</li><li><strong>Top-P (Nucleus) Sampling:</strong> Instead of a fixed k, select the smallest set of tokens whose cumulative probability mass exceeds a threshold p (e.g., p=0.9). Sample only from this &quot;nucleus&quot; of tokens. This adapts the number of considered tokens dynamically based on the probability distribution&#39;s shape.</li></ul><p><strong>Pros</strong>: Can produce much more diverse, interesting, and human-like text compared to greedy or beam search. Top-P is often considered a very effective strategy.</p><p><strong>Cons</strong>: Less predictable outputs. Poor parameter choices (e.g., very high temperature) can lead to incoherent text.</p><p>These advanced decoding strategies are often implemented within the .generate() method of libraries like Hugging Face transformers, but understanding the underlying principles is key.</p><h3>Beyond Our Simple Implementation</h3><p>Our scratch implementation focused on understanding the core architecture. Here are areas for improvement and further exploration:</p><ol><li><strong>Tokenization:</strong> We used trivial tokenization. Real-world applications require sophisticated subword tokenization (BPE, WordPiece, SentencePiece) to handle large vocabularies and out-of-vocabulary words effectively. Libraries like Hugging Face tokenizers or Google&#39;s sentencepiece are standard tools.</li><li><strong>Real-World Datasets &amp; Tasks:</strong> Move beyond sequence copying! Try tasks like:<br>- <strong>Machine Translation:</strong> Using datasets like WMT or smaller ones like Multi30k.<br>- <strong>Text Summarization:</strong> Using datasets like CNN/Daily Mail or XSum.<br>- <strong>Language Modeling</strong>: Training the decoder part only on large text corpora. This involves significant data preprocessing and likely much longer training times.</li><li><strong>Training Enhancements:</strong> Implement techniques used in the original paper and common practice:<br>- <strong>Learning Rate Scheduling:</strong> Use the inverse square root schedule described in Section 5.3 of the paper, or other schedulers like cosine annealing.<br>- <strong>Label Smoothing:</strong> Implement label smoothing (Section 5.4) during loss calculation to improve calibration and generalization.<br>- <strong>Weight Tying:</strong> Share the weight matrix between the token embeddings (source/target if same vocab) and the final projection layer (Section 3.4). This reduces parameters and can improve performance.<br>- <strong>Optimizer Parameters:</strong> Tune Adam’s betas or try other optimizers.</li><li><strong>Architectural Variants &amp; Optimizations:<br>- Pre-Layer Normalization:</strong> A common variant applies Layer Normalization <em>before</em> the attention/FFN sub-layers instead of after (x + Sublayer(LayerNorm(x))). This is often found to lead to more stable training for deeper models.<br>- <strong>Activation Function:</strong> Replace ReLU in the FFN with GELU, which is common in models like BERT and GPT.<br>- <strong>Initialization:</strong> Experiment with different parameter initialization schemes.<br>- <strong>Model Size:</strong> Scale the model (d_model, d_ff, num_heads, num_layers) up or down.</li><li><strong>Comparison to Optimized Libraries:</strong> Compare the performance (speed, memory usage) of your scratch implementation to libraries like Hugging Face transformers or PyTorch&#39;s nn.Transformer. Library implementations use highly optimized code (like FlashAttention) that is significantly faster. Understanding your scratch build helps appreciate the engineering in these libraries.</li></ol><h3>Conclusion &amp; Series Wrap-up</h3><p>This brings us to the end of the “Transformers From Scratch” journey! We started with the fundamental concepts from the “Attention Is All You Need” paper and systematically built each component: embeddings, positional encoding, scaled dot-product attention, multi-head attention, layer normalization, feed-forward networks, residual connections, the encoder, the decoder, and the final projection layer. We assembled the full model, prepared data for a simple task, implemented a training loop, and performed basic inference using greedy decoding.</p><p>Building a Transformer from scratch is a significant undertaking, and hopefully, this series has demystified the architecture and provided you with a solid, practical understanding of its inner workings. While you’ll likely use highly optimized library implementations for real-world projects, the insights gained here are invaluable for debugging, customizing, and truly understanding the models you work with.</p><p><strong>Where to go next?</strong></p><ul><li>Re-read the <a href="https://arxiv.org/abs/1706.03762">“Attention Is All You Need”</a> paper.</li><li>Explore the source code of libraries like Hugging Face transformers.</li><li>Read implementation guides like <a href="http://nlp.seas.harvard.edu/2018/04/03/attention.html">“The Annotated Transformer”</a>.</li><li>Experiment with the improvements mentioned above (advanced decoding, better tokenizers, real datasets, architectural variants).</li><li>Dive into specific Transformer-based models like BERT, GPT, T5.</li></ul><p>Thank you for following along with this series. Happy transforming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65010b043996" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 9 — Inference & Greedy Generation]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-9-inference-greedy-generation-9436681abb2e?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/9436681abb2e</guid>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[model-usage]]></category>
            <category><![CDATA[sequence-generation]]></category>
            <category><![CDATA[greedy-decoding]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 06:50:27 GMT</pubDate>
            <atom:updated>2025-04-13T06:50:27.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 9 — Inference &amp; Greedy Generation</h3><p>Uses the trained model for inference, implementing the basic Greedy Decoding strategy to generate output sequences.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 9 — Inference &amp; Greedy Generation</h3><p>Welcome back to the final core part of “Transformers From Scratch”! In <a href="https://medium.com/p/36571a8fd0ff">Part 8: Data &amp; Training</a>, we successfully prepared data for a simple sequence copying task and implemented a training loop to teach our scratch-built Transformer model. We saw the loss decrease, indicating learning occurred.</p><p>Now, the exciting part: using our trained model to <strong>generate output sequences</strong> based on new input. This process is called <strong>inference</strong>. We’ll implement the simplest decoding strategy: <strong>Greedy Decoding</strong>.</p><p>In this post, we will:</p><ol><li>Discuss setting the model for inference (eval() mode).</li><li>Understand the auto-regressive nature of Transformer generation.</li><li>Explain and implement the Greedy Decoding algorithm.</li><li>Run inference using our trained model (from <a href="https://medium.com/p/36571a8fd0ff">Part 8</a>) on sample data.</li></ol><h3>Inference Mode: model.eval() and torch.no_grad()</h3><p>Before using the model for inference, it’s crucial to set it to evaluation mode:</p><pre>model.eval()</pre><p>This tells PyTorch layers like Dropout and Batch Normalization (though we used Layer Normalization) to behave differently than during training (e.g., dropout is disabled).</p><p>Additionally, since we are not training and don’t need gradients, we should wrap our inference code in a with torch.no_grad(): block. This disables gradient calculation, saving memory and speeding up computations.</p><h3>Auto-Regressive Generation</h3><p>Recall that sequence generation with Transformers is <strong>auto-regressive</strong>. The model doesn’t generate the entire output sequence at once. Instead:</p><ol><li>It takes the source sequence and the <em>currently generated</em> part of the target sequence as input.</li><li>It predicts the <em>next</em> token in the target sequence.</li><li>This predicted token is added to the target sequence.</li><li>Steps 1–3 are repeated until a special End-Of-Sequence ([EOS]) token is predicted or a maximum output length is reached.</li></ol><h3>Greedy Decoding Strategy</h3><p>How do we choose the “next token” at each step? There are several strategies (decoding algorithms). The simplest is <strong>Greedy Decoding</strong>.</p><p><strong>Concept:</strong> At every step of the generation process, Greedy Decoding simply selects the single token with the highest probability (or highest logit, since softmax preserves order) as the next token in the sequence.</p><p><strong>Algorithm:</strong></p><ol><li>Encode the input source sequence once using model.encode(). Store the encoder_output.</li><li>Initialize the decoder input sequence with just the Start-Of-Sequence ([SOS]) token ID.</li><li>Start a loop that continues until the [EOS] token is generated or a predefined maximum output length (max_len) is reached.</li><li>Inside the loop:<br><strong>a</strong>. Create the source mask (src_mask) based on the input source sequence.<br><strong>b</strong>. Create the target mask (tgt_mask) for the current decoder input sequence (this includes the look-ahead mask).<br><strong>c</strong>. Pass the current decoder input sequence, encoder_output, src_mask, and tgt_mask to the model.decode() method.<br><strong>d</strong>. Pass the last output vector from the decoder (corresponding to the prediction for the next token) through the model.project() layer to get logits over the vocabulary.<br><strong>e</strong>. Select the token ID with the highest logit value using torch.argmax. This is the predicted next token.<br><strong>f</strong>. Append the predicted token ID to the decoder input sequence.<br><strong>g</strong>. If the predicted token ID is the [EOS] token ID, break the loop.</li><li>Return the generated sequence of token IDs (optionally removing the initial [SOS]).</li></ol><p><strong>Pros &amp; Cons:</strong></p><ul><li><strong>Pro:</strong> Simple, fast, computationally inexpensive.</li><li><strong>Con:</strong> Can get stuck in loops or produce repetitive text. It makes locally optimal choices at each step, which might not lead to the best overall sequence. It doesn’t consider alternative, potentially better sequences that might have slightly lower probability at an early step.</li></ul><h3>Implementation</h3><p>Let’s implement this logic in a function.</p><pre>import torch<br>import torch.nn as nn<br><br># Assume Transformer class and all sub-modules are defined/imported<br># Assume create_src_mask, create_tgt_mask functions are defined/imported<br>from part8g import *<br><br>def greedy_decode(model: Transformer, src: torch.Tensor, src_mask: torch.Tensor, max_len: int, sos_id: int, eos_id: int, device: torch.device):<br>    &quot;&quot;&quot;<br>    Performs greedy decoding to generate an output sequence.<br><br>    Args:<br>        model (Transformer): The trained Transformer model.<br>        src (torch.Tensor): Source sequence IDs, shape (1, src_seq_len). Batch size must be 1.<br>        src_mask (torch.Tensor): Source mask, shape (1, 1, 1, src_seq_len).<br>        max_len (int): Maximum length of the generated sequence.<br>        sos_id (int): Token ID for the Start-Of-Sequence token.<br>        eos_id (int): Token ID for the End-Of-Sequence token.<br>        device (torch.device): Device to run inference on (e.g., &#39;cuda&#39; or &#39;cpu&#39;).<br><br>    Returns:<br>        torch.Tensor: The generated sequence of token IDs, shape (1, generated_seq_len).<br>    &quot;&quot;&quot;<br>    model.eval() # Set model to evaluation mode<br>    src = src.to(device)<br>    src_mask = src_mask.to(device)<br><br>    with torch.no_grad(): # Disable gradient calculations<br>        # 1. Encode the source sequence<br>        encoder_output = model.encode(src, src_mask) # Shape: (1, src_seq_len, d_model)<br><br>        # 2. Initialize decoder input with SOS token<br>        # Shape: (1, 1) representing [SOS]<br>        decoder_input = torch.tensor([[sos_id]], dtype=torch.long, device=device)<br><br>        # 3. Loop until EOS or max_len<br>        for _ in range(max_len - 1): # -1 because we already have SOS<br>            # 3a. Create target mask for the current decoder input sequence<br>            # Shape: (1, 1, current_tgt_len, current_tgt_len)<br>            tgt_mask = create_tgt_mask(decoder_input, PAD_ID).to(device) # Assuming PAD_ID is accessible<br><br>            # 3b. Decode using encoder output and current decoder input<br>            # Shape: (1, current_tgt_len, d_model)<br>            decoder_output = model.decode(encoder_output, src_mask, decoder_input, tgt_mask)<br><br>            # 3c. Project the *last* decoder output token to get logits<br>            # Shape: (1, 1, vocab_size)<br>            logits = model.project(decoder_output[:, -1:]) # Select only the last time step output<br><br>            # 3d. Select the token ID with the highest logit (greedy choice)<br>            # Shape: (1, 1)<br>            _, next_token_id = torch.max(logits, dim=-1)<br><br>            # 3e. Append the predicted token ID to the decoder input sequence<br>            # Shape becomes (1, current_tgt_len + 1)<br>            decoder_input = torch.cat([decoder_input, next_token_id], dim=1)<br><br>            # 3f. Check if EOS token was generated<br>            if next_token_id.item() == eos_id:<br>                break<br><br>    # Return the generated sequence (excluding the initial SOS token if desired)<br>    # return decoder_input[:, 1:] # Exclude SOS<br>    return decoder_input # Include SOS for clarity maybe</pre><p><strong>Code Explanation:</strong></p><ul><li>The function takes the model, source sequence/mask, max length, special token IDs, and device.</li><li>It sets the model to eval() mode and performs operations within torch.no_grad().</li><li>The source sequence is encoded once.</li><li>The decoder_input starts as just the [SOS] token.</li><li>The loop runs max_len - 1 times (at most).</li><li>Inside the loop:<br>- The target mask is created dynamically based on the <em>current</em> decoder_input.<br>- The model.decode method is called.<br>- Crucially, only the output corresponding to the <em>last token</em> of the decoder_output (decoder_output[:, -1:]) is projected to get logits for the <em>next</em> token prediction.<br>- torch.max (or torch.argmax) finds the ID of the token with the highest logit.<br>- torch.cat appends the predicted token ID to the decoder_input sequence for the next iteration.<br>- The loop breaks if [EOS] is predicted.</li><li>Finally, the complete generated sequence (including [SOS]) is returned.</li></ul><h3>Running Inference</h3><p>Let’s use the model we trained (or pretended to train) in Part 8 for our copy task.</p><pre>import torch<br>import random<br><br># Assume Transformer class and all sub-modules are defined/imported<br># Assume greedy_decode, create_src_mask, tokenize_sequence, id_to_token, etc. are defined<br># Assume VOCAB_SIZE, PAD_ID, SOS_TOKEN, EOS_TOKEN, token_to_id, id_to_token are defined<br># Assume device is defined<br>from part9b import *<br><br># --- Load Trained Model (Example) ---<br>print(&quot;\n--- Running Inference ---&quot;)<br><br># 1. Instantiate model architecture (must match training)<br>d_model_inf = 128<br>num_layers_inf = 3<br>num_heads_inf = 4<br>d_ff_inf = 512<br>dropout_inf = 0.1<br>max_len_inf = MAX_PADDED_LEN # Use same max length<br><br>src_embed_inf = InputEmbeddings(d_model_inf, VOCAB_SIZE)<br>tgt_embed_inf = InputEmbeddings(d_model_inf, VOCAB_SIZE)<br>src_pos_inf = PositionalEncoding(d_model_inf, max_len_inf, dropout_inf)<br>tgt_pos_inf = PositionalEncoding(d_model_inf, max_len_inf, dropout_inf)<br>attention_inf = MultiHeadAttention(d_model_inf, num_heads_inf, dropout_inf)<br>ff_inf = PositionwiseFeedForward(d_model_inf, d_ff_inf, dropout_inf)<br>proj_inf = ProjectionLayer(d_model_inf, VOCAB_SIZE)<br><br>encoder_blocks_inf = nn.ModuleList([ EncoderBlock(d_model_inf, copy.deepcopy(attention_inf), copy.deepcopy(ff_inf), dropout_inf) for _ in range(num_layers_inf) ])<br>decoder_blocks_inf = nn.ModuleList([ DecoderBlock(d_model_inf, copy.deepcopy(attention_inf), copy.deepcopy(attention_inf), copy.deepcopy(ff_inf), dropout_inf) for _ in range(num_layers_inf) ])<br><br>encoder_inf = Encoder(d_model_inf, encoder_blocks_inf)<br>decoder_inf = Decoder(d_model_inf, decoder_blocks_inf)<br><br>inference_model = Transformer(<br>    encoder=encoder_inf, decoder=decoder_inf,<br>    src_embed=src_embed_inf, tgt_embed=tgt_embed_inf,<br>    src_pos=src_pos_inf, tgt_pos=tgt_pos_inf,<br>    projection_layer=proj_inf<br>).to(device)<br><br># 2. Load saved weights (if you saved them in Part 8)<br># Example:<br># try:<br>#     model_state_path = &quot;transformer_copy_task.pth&quot;<br>#     inference_model.load_state_dict(torch.load(model_state_path, map_location=device))<br>#     print(f&quot;Loaded trained model weights from {model_state_path}&quot;)<br># except FileNotFoundError:<br>#     print(&quot;WARNING: Trained model weights not found. Using randomly initialized model for inference.&quot;)<br># except Exception as e:<br>#     print(f&quot;WARNING: Error loading model weights: {e}. Using randomly initialized model.&quot;)<br><br># Set to eval mode AFTER loading weights<br>inference_model.eval()<br><br># 3. Prepare Input Sequence<br># Take a random example or define one<br># src_text = [&#39;[SOS]&#39;, &#39;3&#39;, &#39;1&#39;, &#39;4&#39;, &#39;1&#39;, &#39;5&#39;, &#39;[EOS]&#39;]<br>src_text = random.choice(raw_data)[&#39;src&#39;] # Use one from generated data<br><br>print(f&quot;\nInput Sequence (Text): {src_text}&quot;)<br><br># Tokenize and convert to tensor (add batch dimension)<br>src_ids_inf = torch.tensor([pad_sequence(tokenize_sequence(src_text, token_to_id), max_len_inf, PAD_ID)], dtype=torch.long)<br>print(f&quot;Input Sequence (IDs): {src_ids_inf}&quot;)<br><br># 4. Create Source Mask<br>src_mask_inf = create_src_mask(src_ids_inf, PAD_ID)<br>print(f&quot;Source Mask shape: {src_mask_inf.shape}&quot;)<br><br># 5. Run Greedy Decoding<br>sos_id = token_to_id[SOS_TOKEN]<br>eos_id = token_to_id[EOS_TOKEN]<br><br>print(&quot;\nGenerating output using Greedy Decoding...&quot;)<br>generated_ids = greedy_decode(inference_model, src_ids_inf, src_mask_inf, max_len=max_len_inf, sos_id=sos_id, eos_id=eos_id, device=device)<br>print(f&quot;Generated Sequence (IDs): {generated_ids}&quot;)<br><br># 6. Convert Output IDs to Tokens<br>generated_tokens = [id_to_token[id_] for id_ in generated_ids[0].cpu().numpy()] # Get item from batch, move to CPU<br>print(f&quot;Generated Sequence (Text): {generated_tokens}&quot;)<br><br># For copy task, ideally generated_tokens should match src_text<br>if generated_tokens == src_text:<br>    print(&quot;\nSuccess! Generated sequence matches input sequence.&quot;)<br>else:<br>    print(&quot;\nGenerated sequence does NOT perfectly match input sequence (may need more training or better decoding).&quot;)</pre><p><strong>Explanation:</strong></p><ul><li>We instantiate the model architecture exactly as it was during training.</li><li><strong>Crucially</strong>, we would normally load the saved state_dict from the trained model using inference_model.load_state_dict(torch.load(...)). (This step is commented out as we didn&#39;t actually save in the previous draft, but it&#39;s essential in practice).</li><li>We set the model to eval() mode.</li><li>We prepare a sample input sequence (src_text), tokenize it, pad it, and create its source mask.</li><li>We call our greedy_decode function.</li><li>We convert the resulting sequence of IDs back into readable tokens using our id_to_token map.</li><li>We print the input and the generated output for comparison. For the copy task, they should ideally be identical if the model trained successfully.</li></ul><p>Note: to get better training result it would be that we need to change NUM_EPOCHS parameter in part8 code.</p><pre># 3. Run Training Loop<br>NUM_EPOCHS = 50 # Train for a few epochs for demo</pre><h3>What’s Next?</h3><p>We’ve now built, trained (on a simple task), and used our Transformer for inference! This completes the core journey of building the model from scratch.</p><p>However, greedy decoding is quite basic. In the final <a href="https://medium.com/p/65010b043996"><strong>Part 10 (Optional): Advanced Decoding &amp; Next Steps</strong></a>, we’ll briefly discuss more sophisticated decoding strategies like Beam Search and Sampling, mention limitations, and suggest directions for extending your scratch-built Transformer (e.g., using real datasets, better tokenizers).</p><h3>Conclusion</h3><p>Congratulations! You have successfully implemented the core Transformer architecture, trained it on a basic task, and generated output sequences using greedy decoding. This deep dive provides a solid foundation for understanding how these powerful models work internally. While library implementations offer optimized performance and convenience, building it yourself offers invaluable insight.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9436681abb2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 8 — Data & Training]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-8-data-training-36571a8fd0ff?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/36571a8fd0ff</guid>
            <category><![CDATA[dataloader]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[loss-function]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 20:53:34 GMT</pubDate>
            <atom:updated>2025-04-13T11:15:28.759Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 8 — Data &amp; Training</h3><p>Prepares data for a simple task and implements the training loop with loss and optimizer to make the model learn.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 8 — Data &amp; Training</h3><p>Welcome back to “Transformers From Scratch”! In Part 7: Assembling the Full Model, we finally connected all the components — Encoder, Decoder, Embeddings, Positional Encoding, and Projection Layer — into a complete end-to-end Transformer model. We have the architecture, but now we need to teach it how to perform a task.</p><p>This post is all about <strong>preparing data</strong> and implementing a <strong>training loop</strong> to make our scratch-built Transformer learn.</p><p>In this post, we will:</p><ol><li>Choose a simple sequence-to-sequence task suitable for initial testing.</li><li>Prepare the data: define a vocabulary, generate examples, tokenize, and handle padding.</li><li>Implement functions to create the crucial source and target masks.</li><li>Set up a PyTorch Dataset and DataLoader.</li><li>Define the loss function and optimizer.</li><li>Implement the training loop to fine-tune the model’s parameters.</li><li>Run a basic training process.</li></ol><h3>Choosing a Simple Task: Sequence Copying</h3><p>Training a Transformer on a large, real-world task like machine translation requires significant data and computational resources. To verify our implementation and understand the training dynamics, it’s best to start with a much simpler task.</p><p>A classic simple task for sequence-to-sequence models is <strong>sequence copying</strong>. The model receives a sequence like [SOS] 1 2 3 4 5 [EOS] and must learn to output the exact same sequence [SOS] 1 2 3 4 5 [EOS]. While trivial for humans, it forces the model to learn about sequence order, attention, and generation.</p><h3>Data Preparation</h3><h3>1. Vocabulary</h3><p>For our copying task, we need a small vocabulary containing special tokens and the symbols we want to copy (e.g., digits 0–9).</p><pre># Define special tokens and vocabulary<br>PAD_TOKEN = &#39;[PAD]&#39;<br>SOS_TOKEN = &#39;[SOS]&#39; # Start Of Sequence<br>EOS_TOKEN = &#39;[EOS]&#39; # End Of Sequence<br><br># Vocabulary for digits 0-9 plus special tokens<br>VOCAB = [PAD_TOKEN, SOS_TOKEN, EOS_TOKEN] + [str(i) for i in range(10)]<br><br># Create token-to-ID and ID-to-token mappings<br>token_to_id = {token: i for i, token in enumerate(VOCAB)}<br>id_to_token = {i: token for token, i in token_to_id.items()}<br><br>VOCAB_SIZE = len(VOCAB)<br>PAD_ID = token_to_id[PAD_TOKEN]<br><br>print(f&quot;Vocabulary: {VOCAB}&quot;)<br>print(f&quot;Vocab Size: {VOCAB_SIZE}&quot;)<br>print(f&quot;Token to ID: {token_to_id}&quot;)<br>print(f&quot;PAD ID: {PAD_ID}&quot;)</pre><h3>2. Dataset Generation</h3><p>Let’s create a function to generate pairs of source and target sequences for the copying task. We’ll fix the sequence length for simplicity here.</p><pre>import random<br><br>from part8a import *<br><br>def generate_copy_task_data(num_examples: int, min_len: int, max_len: int, vocab: list):<br>    &quot;&quot;&quot;Generates synthetic data for the sequence copying task.&quot;&quot;&quot;<br>    data = []<br>    # Exclude special tokens from the sequence content<br>    content_vocab = [token for token in vocab if token not in [PAD_TOKEN, SOS_TOKEN, EOS_TOKEN]]<br>    for _ in range(num_examples):<br>        seq_len = random.randint(min_len, max_len)<br>        sequence = [random.choice(content_vocab) for _ in range(seq_len)]<br>        # Source and Target are the same, wrapped with SOS/EOS<br>        src = [SOS_TOKEN] + sequence + [EOS_TOKEN]<br>        tgt = [SOS_TOKEN] + sequence + [EOS_TOKEN]<br>        data.append({&#39;src&#39;: src, &#39;tgt&#39;: tgt})<br>    return data<br><br># Example generation<br>NUM_EXAMPLES = 1000<br>MIN_SEQ_LEN = 5<br>MAX_SEQ_LEN = 10 # Keep sequences relatively short for faster training demo<br>raw_data = generate_copy_task_data(NUM_EXAMPLES, MIN_SEQ_LEN, MAX_SEQ_LEN, VOCAB)<br>print(f&quot;\nGenerated {len(raw_data)} examples. First example:&quot;)<br>print(raw_data[0])</pre><h3>3. Tokenization &amp; Padding</h3><p>We need functions to convert these sequences of symbols into sequences of IDs and pad them to a fixed length.</p><pre>from part8a import *<br>from part8b import *<br><br>def tokenize_sequence(sequence: list, token_to_id_map: dict) -&gt; list:<br>    &quot;&quot;&quot;Converts a sequence of tokens to a sequence of IDs.&quot;&quot;&quot;<br>    return [token_to_id_map[token] for token in sequence]<br><br>def pad_sequence(sequence_ids: list, max_len: int, pad_id: int) -&gt; list:<br>    &quot;&quot;&quot;Pads a sequence of IDs to max_len.&quot;&quot;&quot;<br>    padded_ids = sequence_ids + [pad_id] * (max_len - len(sequence_ids))<br>    return padded_ids[:max_len] # Ensure it doesn&#39;t exceed max_len<br><br># Define max length for padding (should accommodate SOS, EOS, and max content length)<br>MAX_PADDED_LEN = MAX_SEQ_LEN + 2 # +2 for SOS and EOS<br><br># Example tokenization and padding<br>example = raw_data[0]<br>src_ids = tokenize_sequence(example[&#39;src&#39;], token_to_id)<br>tgt_ids = tokenize_sequence(example[&#39;tgt&#39;], token_to_id)<br>src_padded = pad_sequence(src_ids, MAX_PADDED_LEN, PAD_ID)<br>tgt_padded = pad_sequence(tgt_ids, MAX_PADDED_LEN, PAD_ID)<br><br>print(f&quot;\nOriginal Src: {example[&#39;src&#39;]}&quot;)<br>print(f&quot;Tokenized Src: {src_ids}&quot;)<br>print(f&quot;Padded Src: {src_padded}&quot;)<br>print(f&quot;Original Tgt: {example[&#39;tgt&#39;]}&quot;)<br>print(f&quot;Tokenized Tgt: {tgt_ids}&quot;)<br>print(f&quot;Padded Tgt: {tgt_padded}&quot;)</pre><h3>Creating Masks</h3><p>Masks are essential for telling the attention mechanisms which parts of the sequence to ignore.</p><h3>1. Source Mask</h3><p>This mask hides padding tokens in the source sequence. It’s used in the Encoder’s self-attention and the Decoder’s cross-attention. Shape: (batch_size, 1, 1, src_seq_len). True where padded.</p><h3>2. Target Mask</h3><p>This mask hides both padding tokens <em>and</em> future tokens (look-ahead) in the target sequence. It’s used in the Decoder’s masked self-attention. Shape: (batch_size, 1, tgt_seq_len, tgt_seq_len). True where padded OR future.</p><pre>import torch<br><br>from part8a import *<br>from part8b import *<br>from part8c import *<br><br>def create_src_mask(src_ids: torch.Tensor, pad_id: int):<br>    &quot;&quot;&quot;<br>    Creates a mask for source sequence padding.<br><br>    Args:<br>        src_ids (torch.Tensor): Source sequence IDs, shape (batch_size, src_seq_len).<br>        pad_id (int): The ID used for padding.<br><br>    Returns:<br>        torch.Tensor: Source mask, shape (batch_size, 1, 1, src_seq_len). True where padded.<br>    &quot;&quot;&quot;<br>    # Check where the source sequence equals the padding ID<br>    src_mask = (src_ids == pad_id)<br>    # Add dimensions for heads and query sequence length for broadcasting<br>    # Shape becomes (batch_size, 1, 1, src_seq_len)<br>    return src_mask.unsqueeze(1).unsqueeze(2)<br><br>def create_tgt_mask(tgt_ids: torch.Tensor, pad_id: int):<br>    &quot;&quot;&quot;<br>    Creates a combined mask for target sequence padding and look-ahead.<br><br>    Args:<br>        tgt_ids (torch.Tensor): Target sequence IDs, shape (batch_size, tgt_seq_len).<br>        pad_id (int): The ID used for padding.<br><br>    Returns:<br>        torch.Tensor: Target mask, shape (batch_size, 1, tgt_seq_len, tgt_seq_len). True where padded or future.<br>    &quot;&quot;&quot;<br>    batch_size, tgt_seq_len = tgt_ids.shape<br><br>    # 1. Create padding mask (similar to source mask, but for target)<br>    # Shape: (batch_size, 1, 1, tgt_seq_len)<br>    tgt_padding_mask = (tgt_ids == pad_id).unsqueeze(1).unsqueeze(2)<br><br>    # 2. Create look-ahead mask<br>    # Shape: (tgt_seq_len, tgt_seq_len)<br>    look_ahead_mask = torch.triu(torch.ones(tgt_seq_len, tgt_seq_len, device=tgt_ids.device), diagonal=1).bool()<br>    # Shape: (1, 1, tgt_seq_len, tgt_seq_len) after unsqueezing for batch/head dims<br>    look_ahead_mask = look_ahead_mask.unsqueeze(0).unsqueeze(0)<br><br>    # 3. Combine padding mask and look-ahead mask<br>    # Padding mask shape is broadcasted to (batch_size, 1, tgt_seq_len, tgt_seq_len)<br>    # Look-ahead mask shape is broadcasted to (batch_size, 1, tgt_seq_len, tgt_seq_len)<br>    # Combine using logical OR: mask is True if EITHER padding OR look-ahead applies.<br>    tgt_mask = tgt_padding_mask | look_ahead_mask<br>    return tgt_mask<br><br># Example mask creation<br>dummy_src_tensor = torch.tensor([src_padded]) # Add batch dimension<br>dummy_tgt_tensor = torch.tensor([tgt_padded])<br><br>src_mask_example = create_src_mask(dummy_src_tensor, PAD_ID)<br>tgt_mask_example = create_tgt_mask(dummy_tgt_tensor, PAD_ID)<br><br>print(f&quot;\nSource Mask shape: {src_mask_example.shape}&quot;) # Should be [1, 1, 1, MAX_PADDED_LEN]<br>print(f&quot;Target Mask shape: {tgt_mask_example.shape}&quot;) # Should be [1, 1, MAX_PADDED_LEN, MAX_PADDED_LEN]<br># print(&quot;Target Mask example:\n&quot;, tgt_mask_example.squeeze()) # Print one mask</pre><h3>Dataset and DataLoader</h3><p>We wrap our data processing logic in a PyTorch Dataset and use DataLoader for batching. During training, the Decoder input (decoder_input) should be the target sequence shifted right (starting with SOS), and the expected output (label) should be the target sequence shifted left (ending with EOS).</p><pre>from torch.utils.data import Dataset, DataLoader<br><br>from part8a import *<br>from part8b import *<br>from part8c import *<br>from part8d import *<br><br>class CopyTaskDataset(Dataset):<br>    &quot;&quot;&quot; Custom Dataset for the sequence copying task. &quot;&quot;&quot;<br>    def __init__(self, data, token_to_id_map, max_len, pad_id):<br>        self.data = data<br>        self.token_to_id = token_to_id_map<br>        self.max_len = max_len<br>        self.pad_id = pad_id<br><br>    def __len__(self):<br>        return len(self.data)<br><br>    def __getitem__(self, idx):<br>        item = self.data[idx]<br><br>        # Tokenize and pad source sequence<br>        src_ids = tokenize_sequence(item[&#39;src&#39;], self.token_to_id)<br>        src_padded = pad_sequence(src_ids, self.max_len, self.pad_id)<br><br>        # Tokenize target sequence<br>        tgt_ids = tokenize_sequence(item[&#39;tgt&#39;], self.token_to_id)<br><br>        # Create decoder input (shifted right: SOS + sequence)<br>        decoder_input_ids = tgt_ids[:-1] # Exclude EOS<br>        decoder_input_padded = pad_sequence(decoder_input_ids, self.max_len, self.pad_id)<br><br>        # Create label (expected output: sequence + EOS)<br>        label_ids = tgt_ids[1:] # Exclude SOS<br>        label_padded = pad_sequence(label_ids, self.max_len, self.pad_id) # Pad labels too<br><br>        return {<br>            &quot;src_ids&quot;: torch.tensor(src_padded, dtype=torch.long),<br>            &quot;decoder_input_ids&quot;: torch.tensor(decoder_input_padded, dtype=torch.long),<br>            &quot;label_ids&quot;: torch.tensor(label_padded, dtype=torch.long)<br>        }<br><br># Create Dataset instance<br>train_dataset = CopyTaskDataset(raw_data, token_to_id, MAX_PADDED_LEN, PAD_ID)<br><br># Create DataLoader instance<br>BATCH_SIZE = 64 # Adjust based on memory<br>train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)<br><br># Check a batch<br>print(&quot;\nChecking DataLoader batch...&quot;)<br>batch = next(iter(train_dataloader))<br>print(&quot;Batch keys:&quot;, batch.keys())<br>print(&quot;src_ids shape:&quot;, batch[&#39;src_ids&#39;].shape) # Expected: [BATCH_SIZE, MAX_PADDED_LEN]<br>print(&quot;decoder_input_ids shape:&quot;, batch[&#39;decoder_input_ids&#39;].shape)<br>print(&quot;label_ids shape:&quot;, batch[&#39;label_ids&#39;].shape)</pre><h3>The Training Loop</h3><h4>Loss Function &amp; Optimizer</h4><ul><li><strong>Loss:</strong> We predict the next token ID, which is a multi-class classification problem over the vocabulary. torch.nn.CrossEntropyLoss is ideal. It combines LogSoftmax and NLLLoss. Importantly, we tell it to ignore our padding token ID when calculating the loss using the ignore_index parameter.</li><li><strong>Optimizer:</strong> We’ll use Adam, a standard choice for Transformers, as mentioned in the paper.</li></ul><pre>import torch<br>import torch.nn as nn<br><br>from part8a import *<br><br># Loss Function (ignore padding)<br>loss_fn = nn.CrossEntropyLoss(ignore_index=PAD_ID)<br><br># Optimizer (Adam) - requires model parameters<br># We will instantiate the model first, then the optimizer<br># Example: optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, betas=(0.9, 0.98), eps=1e-9)<br>LEARNING_RATE = 1e-4 # Example learning rate</pre><h3>Training Step Logic</h3><p>Inside the loop for each batch:</p><ol><li>Get batch (src_ids, decoder_input_ids, label_ids).</li><li>Move batch to device (GPU/CPU).</li><li>Create source and target masks using the functions defined earlier.</li><li>Zero gradients: optimizer.zero_grad().</li><li><strong>Forward Pass:<br></strong>• Pass src_ids and src_mask through model.encode().<br>• Pass decoder_input_ids, encoder_output, src_mask, tgt_mask through model.decode().<br>• Pass decoder_output through model.project() to get logits ([Batch, SeqLen, VocabSize]).</li><li><strong>Calculate Loss:<br></strong>• Reshape logits to [Batch * SeqLen, VocabSize] and labels to [Batch * SeqLen] as expected by CrossEntropyLoss.<br>• Calculate loss: loss = loss_fn(logits_reshaped, labels_reshaped).</li><li><strong>Backward Pass:</strong> loss.backward().</li><li><strong>Optimizer Step:</strong> optimizer.step().</li></ol><h3>Training Loop Implementation</h3><pre>import time<br>import copy<br>import torch<br>import torch.nn as nn<br># Assume Transformer class and all sub-modules are defined/imported<br># Assume create_src_mask, create_tgt_mask are defined<br>from part1a import InputEmbeddings<br>from part1b import PositionalEncoding<br>from part3a import MultiHeadAttention<br>from part4b import PositionwiseFeedForward<br>from part5a import EncoderBlock<br>from part5b import Encoder<br>from part6a import DecoderBlock<br>from part6b import Decoder<br>from part7a import ProjectionLayer<br>from part7b import Transformer<br>from part8d import *<br>from part8e import *<br>from part8f import *<br><br># --- Main Training Script ---<br>device = &quot;cpu&quot; # Change to &quot;cuda&quot; if GPU is available <br><br>def train_one_epoch(model, dataloader, loss_fn, optimizer, device, pad_id):<br>    &quot;&quot;&quot; Trains the model for one epoch. &quot;&quot;&quot;<br>    model.train() # Set model to training mode<br>    total_loss = 0<br>    start_time = time.time()<br><br>    for i, batch in enumerate(dataloader):<br>        # Move data to device<br>        src_ids = batch[&#39;src_ids&#39;].to(device)<br>        decoder_input_ids = batch[&#39;decoder_input_ids&#39;].to(device)<br>        label_ids = batch[&#39;label_ids&#39;].to(device)<br><br>        # Create masks<br>        src_mask = create_src_mask(src_ids, pad_id).to(device)<br>        tgt_mask = create_tgt_mask(decoder_input_ids, pad_id).to(device) # Use decoder_input for tgt mask shape<br><br>        # Zero gradients<br>        optimizer.zero_grad()<br><br>        # Forward pass<br>        encoder_output = model.encode(src_ids, src_mask)<br>        decoder_output = model.decode(encoder_output, src_mask, decoder_input_ids, tgt_mask)<br>        logits = model.project(decoder_output) # Shape: [Batch, SeqLen, VocabSize]<br><br>        # Calculate loss<br>        # Reshape for CrossEntropyLoss: [Batch * SeqLen, VocabSize] and [Batch * SeqLen]<br>        loss = loss_fn(logits.view(-1, logits.shape[-1]), label_ids.view(-1))<br><br>        # Backward pass<br>        loss.backward()<br><br>        # Optimizer step<br>        optimizer.step()<br><br>        total_loss += loss.item()<br><br>        # Optional: Print progress<br>        if (i + 1) % 10 == 0: # Print every 10 batches<br>             elapsed = time.time() - start_time<br>             print(f&quot;  Batch {i+1}/{len(dataloader)}, Loss: {loss.item():.4f}, Time: {elapsed:.2f}s&quot;)<br>             start_time = time.time() # Reset timer<br><br>    avg_loss = total_loss / len(dataloader)<br>    return avg_loss<br><br><br><br># 1. Instantiate the Full Model (from Part 7)<br>#    Make sure all parameters match (d_model, heads, layers, vocab sizes etc.)<br>print(&quot;\n--- Setting up Model for Training ---&quot;)<br>d_model = 128 # Smaller model for faster demo<br>num_layers = 3 # Fewer layers<br>num_heads = 4<br>d_ff = 512<br>dropout = 0.1<br>max_len = MAX_PADDED_LEN # Use padded length for PE<br><br>src_embed_train = InputEmbeddings(d_model, VOCAB_SIZE)<br>tgt_embed_train = InputEmbeddings(d_model, VOCAB_SIZE) # Same vocab for copy task<br>src_pos_train = PositionalEncoding(d_model, max_len, dropout)<br>tgt_pos_train = PositionalEncoding(d_model, max_len, dropout)<br>attention_train = MultiHeadAttention(d_model, num_heads, dropout)<br>ff_train = PositionwiseFeedForward(d_model, d_ff, dropout)<br>proj_train = ProjectionLayer(d_model, VOCAB_SIZE)<br><br>encoder_blocks_train = nn.ModuleList([<br>    EncoderBlock(d_model, copy.deepcopy(attention_train), copy.deepcopy(ff_train), dropout) for _ in range(num_layers)<br>])<br>decoder_blocks_train = nn.ModuleList([<br>    DecoderBlock(d_model, copy.deepcopy(attention_train), copy.deepcopy(attention_train), copy.deepcopy(ff_train), dropout) for _ in range(num_layers)<br>])<br><br>encoder_train = Encoder(d_model, encoder_blocks_train)<br>decoder_train = Decoder(d_model, decoder_blocks_train)<br><br>model = Transformer(<br>    encoder=encoder_train, decoder=decoder_train,<br>    src_embed=src_embed_train, tgt_embed=tgt_embed_train,<br>    src_pos=src_pos_train, tgt_pos=tgt_pos_train,<br>    projection_layer=proj_train<br>).to(device) # Move model to device<br><br># Initialize weights<br>for p in model.parameters():<br>    if p.dim() &gt; 1:<br>        nn.init.xavier_uniform_(p)<br><br>print(f&quot;Model created with {sum(p.numel() for p in model.parameters()):,} parameters.&quot;)<br><br># 2. Define Optimizer<br>optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, betas=(0.9, 0.98), eps=1e-9)<br><br># 3. Run Training Loop<br>NUM_EPOCHS = 5 # Train for a few epochs for demo<br>print(f&quot;\n--- Starting Training for {NUM_EPOCHS} Epochs ---&quot;)<br><br>for epoch in range(1, NUM_EPOCHS + 1):<br>    epoch_start_time = time.time()<br>    avg_epoch_loss = train_one_epoch(model, train_dataloader, loss_fn, optimizer, device, PAD_ID)<br>    epoch_duration = time.time() - epoch_start_time<br>    print(&quot;-&quot; * 50)<br>    print(f&quot;End of Epoch {epoch} | Time: {epoch_duration:.2f}s | Avg Loss: {avg_epoch_loss:.4f}&quot;)<br>    print(&quot;-&quot; * 50)<br><br>print(&quot;Training finished.&quot;)<br># Optional: Save the trained model<br># torch.save(model.state_dict(), &quot;transformer_copy_task.pth&quot;)</pre><h3>Running the Training</h3><p>Executing the script above will:</p><ol><li>Generate the synthetic copy task data.</li><li>Set up the Dataset and DataLoader.</li><li>Instantiate the full Transformer model (using smaller dimensions for this demo).</li><li>Initialize the CrossEntropyLoss and Adam optimizer.</li><li>Run the training loop for the specified number of epochs, printing the loss periodically.</li></ol><p>You should hopefully observe the average loss decreasing over the epochs, indicating that the model is learning to perform the sequence copying task!</p><h3>What’s Next?</h3><p>We’ve successfully trained our scratch-built Transformer! But how do we actually <em>use</em> it to generate sequences? In <a href="https://medium.com/p/9436681abb2e"><strong>Part 9: Inference &amp; Greedy Generation</strong></a>, we’ll implement a simple decoding strategy (greedy search) to generate output sequences from our trained model based on a given input.</p><p>We’re very close to seeing the complete end-to-end process in action!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36571a8fd0ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 7 — Assembling the Full Model]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-7-assembling-the-full-model-eb96ef31f78f?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb96ef31f78f</guid>
            <category><![CDATA[output-layer]]></category>
            <category><![CDATA[model-assembly]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[seq2seq]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 20:37:14 GMT</pubDate>
            <atom:updated>2025-04-13T11:14:52.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 7 — Assembling the Full Model</h3><p>Connects the Encoder, Decoder, embeddings, and positional encodings, adding the final projection layer to create the complete Transformer model.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 7 — Assembling the Full Model</h3><p>Welcome back to the “Transformers From Scratch” series! We’ve come a long way, meticulously building each key component:</p><ul><li><a href="https://medium.com/p/bbce1f39040d">Part 1: Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af">Part 2: Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89">Part 3: Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8">Part 4: Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3">Part 5: The Encoder</a></li><li><a href="https://medium.com/p/989a17347224">Part 6: The Decoder</a></li></ul><p>Now, it’s time for the grand assembly! In this post, we will connect all these pieces — the Embeddings, Positional Encoding, Encoder stack, and Decoder stack — into a single, end-to-end Transformer model. We’ll also add the final layer needed to produce output predictions.</p><p>In this post, we will:</p><ol><li>Implement the final Linear Projection Layer.</li><li>Create the main Transformer class that integrates all components.</li><li>Understand the data flow through the complete model.</li><li>Instantiate and test the full model structure.</li></ol><h3>The Final Output Layer (Projection Layer)</h3><p>The Decoder stack (built in <a href="https://medium.com/p/989a17347224">Part 6</a>) outputs a sequence of vectors, where each vector at position i represents the predicted features for the i-th token in the target sequence. These vectors have the dimension d_model.</p><p>However, to predict the <em>actual next token</em>, we need scores for every possible token in our target vocabulary. This is achieved by adding a final Linear layer after the Decoder stack.</p><p><strong>Concept:</strong> This layer projects the d_model-dimensional output vector from the Decoder into a vector whose size equals the target vocabulary size (tgt_vocab_size). Each element in this output vector represents a raw, unnormalized score (logit) for a corresponding token in the vocabulary. A higher score indicates a higher likelihood for that token being the next token in the sequence.</p><p>The softmax function is typically applied to these logits <em>later</em> (often within the loss function during training, like torch.nn.CrossEntropyLoss, or explicitly during inference) to convert them into probabilities.</p><p><em>(Note: The original paper, Section 3.4, mentions sharing weights between the input/output embedding layers and this final projection layer, often tying the weights. For simplicity in our scratch implementation, we’ll implement this as a separate linear layer first and mention weight tying as a potential optimization/detail).</em></p><h3>Implementing the Projection Layer</h3><pre>import torch<br>import torch.nn as nn<br><br>class ProjectionLayer(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements the final linear layer to project Decoder output to vocabulary size.<br>    &quot;&quot;&quot;<br>    def __init__(self, d_model: int, vocab_size: int):<br>        &quot;&quot;&quot;<br>        Args:<br>            d_model (int): Dimension of the model (input features).<br>            vocab_size (int): Size of the target vocabulary (output features).<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        # A simple linear layer<br>        self.proj = nn.Linear(d_model, vocab_size)<br><br>    def forward(self, x: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Forward pass for the projection layer.<br><br>        Args:<br>            x (torch.Tensor): Input tensor from the Decoder stack,<br>                              shape (batch_size, seq_len, d_model).<br><br>        Returns:<br>            torch.Tensor: Output tensor (logits), shape (batch_size, seq_len, vocab_size).<br>        &quot;&quot;&quot;<br>        # Project the input tensor to the vocabulary size dimension<br>        # (batch_size, seq_len, d_model) -&gt; (batch_size, seq_len, vocab_size)<br>        return self.proj(x)</pre><p><strong>Code Explanation:</strong></p><ul><li>A straightforward nn.Module containing a single nn.Linear layer that maps d_model dimensions to vocab_size dimensions.</li><li>The forward method simply applies this linear transformation.</li></ul><h3>Assembling the Full Transformer Model</h3><p>Now we combine everything! The Transformer class will hold instances of all the modules we&#39;ve built and define the overall forward pass logic, connecting the Encoder and Decoder.</p><p><strong>Concept:</strong> The data flow follows Figure 1 in the paper:</p><ol><li>The source sequence (src) goes through source embedding and positional encoding, then into the Encoder. The src_mask is used within the Encoder&#39;s self-attention layers.</li><li>The target sequence (tgt, typically shifted right during training) goes through target embedding and positional encoding, then into the Decoder.</li><li>The Decoder also receives the output from the Encoder (encoder_output) and uses both the src_mask (for cross-attention) and the tgt_mask (for masked self-attention).</li><li>The Decoder&#39;s output is passed through the final ProjectionLayer to get the logits over the target vocabulary.</li></ol><h3>Implementation</h3><pre>import torch<br>import torch.nn as nn<br><br># Assume all previously defined modules are available/imported:<br># InputEmbeddings, PositionalEncoding, MultiHeadAttention, PositionwiseFeedForward,<br># ResidualConnection, EncoderBlock, Encoder, DecoderBlock, Decoder, ProjectionLayer<br>from part1a import InputEmbeddings<br>from part1b import PositionalEncoding<br>from part5b import Encoder<br>from part6b import Decoder<br>from part7a import ProjectionLayer<br><br>class Transformer(nn.Module):<br>    &quot;&quot;&quot;<br>    The complete Transformer model integrating Encoder, Decoder, Embeddings, etc.<br>    &quot;&quot;&quot;<br>    def __init__(self,<br>                 encoder: Encoder,<br>                 decoder: Decoder,<br>                 src_embed: InputEmbeddings,<br>                 tgt_embed: InputEmbeddings,<br>                 src_pos: PositionalEncoding,<br>                 tgt_pos: PositionalEncoding,<br>                 projection_layer: ProjectionLayer):<br>        &quot;&quot;&quot;<br>        Args:<br>            encoder (Encoder): The Encoder stack.<br>            decoder (Decoder): The Decoder stack.<br>            src_embed (InputEmbeddings): Source embedding layer.<br>            tgt_embed (InputEmbeddings): Target embedding layer.<br>            src_pos (PositionalEncoding): Source positional encoding layer.<br>            tgt_pos (PositionalEncoding): Target positional encoding layer.<br>            projection_layer (ProjectionLayer): Final projection layer.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.encoder = encoder<br>        self.decoder = decoder<br>        self.src_embed = src_embed<br>        self.tgt_embed = tgt_embed<br>        self.src_pos = src_pos<br>        self.tgt_pos = tgt_pos<br>        self.projection_layer = projection_layer<br><br>    def encode(self, src: torch.Tensor, src_mask: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Performs the encoding part of the Transformer.<br><br>        Args:<br>            src (torch.Tensor): Source input tensor (token IDs), shape (batch_size, src_seq_len).<br>            src_mask (torch.Tensor): Source mask.<br><br>        Returns:<br>            torch.Tensor: Encoder output, shape (batch_size, src_seq_len, d_model).<br>        &quot;&quot;&quot;<br>        # Apply source embedding and positional encoding<br>        src = self.src_embed(src)<br>        src = self.src_pos(src)<br>        # Pass through the encoder stack<br>        return self.encoder(src, src_mask)<br><br>    def decode(self, encoder_output: torch.Tensor, src_mask: torch.Tensor,<br>               tgt: torch.Tensor, tgt_mask: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Performs the decoding part of the Transformer.<br><br>        Args:<br>            encoder_output (torch.Tensor): Output from the encoder.<br>            src_mask (torch.Tensor): Source mask (for cross-attention).<br>            tgt (torch.Tensor): Target input tensor (token IDs), shape (batch_size, tgt_seq_len).<br>            tgt_mask (torch.Tensor): Target mask (for self-attention).<br><br>        Returns:<br>            torch.Tensor: Decoder output, shape (batch_size, tgt_seq_len, d_model).<br>        &quot;&quot;&quot;<br>        # Apply target embedding and positional encoding<br>        tgt = self.tgt_embed(tgt)<br>        tgt = self.tgt_pos(tgt)<br>        # Pass through the decoder stack, providing encoder output and masks<br>        return self.decoder(tgt, encoder_output, src_mask, tgt_mask)<br><br>    def project(self, x: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Applies the final projection layer.<br><br>        Args:<br>            x (torch.Tensor): Input tensor (usually from decoder), shape (batch_size, seq_len, d_model).<br><br>        Returns:<br>            torch.Tensor: Output logits, shape (batch_size, seq_len, tgt_vocab_size).<br>        &quot;&quot;&quot;<br>        return self.projection_layer(x)<br><br>    # Optional: Define a full forward pass if needed for simpler training loops,<br>    # but separate encode/decode is often more flexible for inference.<br>    # def forward(self, src, tgt, src_mask, tgt_mask):<br>    #     encoder_output = self.encode(src, src_mask)<br>    #     decoder_output = self.decode(encoder_output, src_mask, tgt, tgt_mask)<br>    #     logits = self.project(decoder_output)<br>    #     return logits</pre><p><strong>Code Explanation:</strong></p><ul><li>__init__: Takes pre-initialized instances of all the major components (Encoder, Decoder, Embeddings, Positional Encodings, Projection Layer) and stores them.</li><li>encode: Takes the source token IDs (src) and source mask (src_mask). It applies the source embedding and positional encoding, then passes the result through the encoder stack.</li><li>decode: Takes the target token IDs (tgt), the encoder_output (from the encode method), the src_mask, and the tgt_mask. It applies target embedding and positional encoding to tgt, then passes everything through the decoder stack.</li><li>project: Takes the output from the decode method (or any tensor of shape ..., d_model) and passes it through the final projection_layer to get vocabulary logits.</li><li><em>(Optional forward):</em> A full forward method could combine these steps, but having separate encode and decode methods is often useful, especially during inference where decoding happens step-by-step.</li></ul><h3>Instantiating and Testing the Full Model</h3><p>Now, let’s put all the parts from the entire series together!</p><pre>import torch<br>import torch.nn as nn<br>import copy # For creating deep copies of layers<br><br># Assume all module classes are defined/imported from previous parts:<br># InputEmbeddings, PositionalEncoding, MultiHeadAttention, PositionwiseFeedForward,<br># ResidualConnection, LayerNormalization, EncoderBlock, Encoder, DecoderBlock, Decoder, ProjectionLayer<br>from part1a import InputEmbeddings<br>from part1b import PositionalEncoding<br>from part3a import MultiHeadAttention<br>from part4b import PositionwiseFeedForward<br>from part5a import EncoderBlock<br>from part5b import Encoder<br>from part6a import DecoderBlock<br>from part6b import Decoder<br>from part7a import ProjectionLayer<br>from part7b import Transformer<br><br>print(&quot;\n--- Testing Full Transformer Model ---&quot;)<br><br># Model Parameters (Matching Base Paper)<br>src_vocab_size = 10000 # Example source vocab size<br>tgt_vocab_size = 11000 # Example target vocab size<br>d_model = 512<br>num_layers = 6 # N=6<br>num_heads = 8<br>dropout = 0.1<br>d_ff = 2048<br>max_seq_len = 100 # Max sequence length for positional encoding<br><br># --- Create instances of the building blocks ---<br><br># Embeddings &amp; Positional Encoding<br>src_embed = InputEmbeddings(d_model, src_vocab_size)<br>tgt_embed = InputEmbeddings(d_model, tgt_vocab_size)<br>src_pos = PositionalEncoding(d_model, max_seq_len, dropout)<br>tgt_pos = PositionalEncoding(d_model, max_seq_len, dropout)<br><br># Attention, FFN, Residuals (can be shared or separate per block/layer)<br>attention = MultiHeadAttention(d_model, num_heads, dropout)<br>feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout)<br># Note: ResidualConnection takes features and dropout, sublayer is passed in forward<br><br># Encoder Blocks &amp; Stack<br>encoder_blocks = nn.ModuleList([<br>    EncoderBlock(d_model, copy.deepcopy(attention), copy.deepcopy(feed_forward), dropout)<br>    for _ in range(num_layers)<br>])<br>encoder = Encoder(d_model, encoder_blocks)<br><br># Decoder Blocks &amp; Stack<br>decoder_blocks = nn.ModuleList([<br>    DecoderBlock(d_model, copy.deepcopy(attention), copy.deepcopy(attention), copy.deepcopy(feed_forward), dropout)<br>    for _ in range(num_layers)<br>])<br>decoder = Decoder(d_model, decoder_blocks)<br><br># Projection Layer<br>projection = ProjectionLayer(d_model, tgt_vocab_size)<br><br># --- Instantiate the Full Transformer ---<br>transformer_model = Transformer(<br>    encoder=encoder,<br>    decoder=decoder,<br>    src_embed=src_embed,<br>    tgt_embed=tgt_embed,<br>    src_pos=src_pos,<br>    tgt_pos=tgt_pos,<br>    projection_layer=projection<br>)<br><br># Initialize parameters (Xavier uniform is common)<br>for p in transformer_model.parameters():<br>    if p.dim() &gt; 1:<br>        nn.init.xavier_uniform_(p)<br><br>print(f&quot;Transformer model created with {sum(p.numel() for p in transformer_model.parameters()):,} parameters.&quot;)<br><br># --- Test with Dummy Data ---<br>batch_size_test = 2<br>src_seq_len_test = 10<br>tgt_seq_len_test = 12<br><br># Dummy source and target sequences (token IDs)<br>dummy_src_seq = torch.randint(1, src_vocab_size, (batch_size_test, src_seq_len_test)) # Avoid 0 if it&#39;s padding<br>dummy_tgt_seq = torch.randint(1, tgt_vocab_size, (batch_size_test, tgt_seq_len_test))<br><br># Dummy masks (False where token is present, True where padded/masked)<br># Simple example: no padding, just look-ahead for target<br>dummy_src_mask_test = torch.zeros(batch_size_test, 1, 1, src_seq_len_test, dtype=torch.bool)<br>dummy_tgt_mask_test = torch.triu(torch.ones(tgt_seq_len_test, tgt_seq_len_test), diagonal=1).bool().unsqueeze(0).unsqueeze(0) # [1, 1, T, T] broadcastable<br><br>print(f&quot;\nDummy Source Seq shape: {dummy_src_seq.shape}&quot;)<br>print(f&quot;Dummy Target Seq shape: {dummy_tgt_seq.shape}&quot;)<br>print(f&quot;Dummy Source Mask shape: {dummy_src_mask_test.shape}&quot;)<br>print(f&quot;Dummy Target Mask shape: {dummy_tgt_mask_test.shape}&quot;)<br><br><br># --- Test encode, decode, project methods ---<br>transformer_model.eval() # Set model to evaluation mode<br>with torch.no_grad():<br>    print(&quot;\nTesting encode...&quot;)<br>    encoder_output_test = transformer_model.encode(dummy_src_seq, dummy_src_mask_test)<br>    print(f&quot;Encoder Output shape: {encoder_output_test.shape}&quot;) # Expected: [B, S_src, Dm] = [2, 10, 512]<br>    assert encoder_output_test.shape == (batch_size_test, src_seq_len_test, d_model)<br><br>    print(&quot;\nTesting decode...&quot;)<br>    decoder_output_test = transformer_model.decode(encoder_output_test, dummy_src_mask_test, dummy_tgt_seq, dummy_tgt_mask_test)<br>    print(f&quot;Decoder Output shape: {decoder_output_test.shape}&quot;) # Expected: [B, S_tgt, Dm] = [2, 12, 512]<br>    assert decoder_output_test.shape == (batch_size_test, tgt_seq_len_test, d_model)<br><br>    print(&quot;\nTesting project...&quot;)<br>    final_logits_test = transformer_model.project(decoder_output_test)<br>    print(f&quot;Final Logits shape: {final_logits_test.shape}&quot;) # Expected: [B, S_tgt, V_tgt] = [2, 12, 11000]<br>    assert final_logits_test.shape == (batch_size_test, tgt_seq_len_test, tgt_vocab_size)<br><br>print(&quot;\nFull Transformer test passed (shape checks).&quot;)</pre><p><strong>Code Explanation:</strong></p><ul><li>We define all necessary hyperparameters (vocab_size, d_model, num_layers, etc.).</li><li>We instantiate all the building blocks: Embeddings, Positional Encodings, Attention, FFN. Note that we use copy.deepcopy when creating the lists of Encoder/Decoder blocks to ensure each block gets its own distinct instances of the sub-modules if desired (though sharing weights across layers for MHA/FFN is also possible, the paper implies distinct parameters per layer).</li><li>We build the Encoder and Decoder stacks using nn.ModuleList.</li><li>We instantiate the final ProjectionLayer.</li><li>We assemble the full Transformer model by passing all the components to its __init__.</li><li>We apply Xavier uniform initialization, a common practice for Transformer parameters.</li><li>We create dummy source/target sequences and masks.</li><li>We test the encode, decode, and project methods sequentially, checking the output shapes at each stage to ensure the data flows correctly through the entire architecture.</li></ul><h3>What’s Next?</h3><p>Congratulations! We have successfully assembled a complete Transformer model from scratch, connecting all the components we’ve built over the previous parts. We now have an end-to-end architecture ready for training.</p><p>In <a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8: Data Preparation &amp; Simple Training Loop</strong></a>, we will finally breathe life into our model. We’ll set up a simple task and dataset, create the necessary data loaders and masks, define a loss function and optimizer, and implement a basic training loop to make our Transformer learn!</p><p>The final steps before seeing our model in action are coming up!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb96ef31f78f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 6 — The Decoder]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-6-the-decoder-989a17347224?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/989a17347224</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[sequence-generation]]></category>
            <category><![CDATA[transformer-devoder]]></category>
            <category><![CDATA[decoder]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 20:23:16 GMT</pubDate>
            <atom:updated>2025-04-13T11:14:36.448Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 6 — The Decoder</h3><p>Builds the Decoder blocks, incorporating masked self-attention and cross-attention, and stacks them into the full Decoder.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 6 — The Decoder</h3><p>Welcome back to “Transformers From Scratch”! In Part 5: The Encoder, we successfully built the Encoder stack, which processes the input sequence into a rich contextual representation. Now, we turn our attention to the other half of the architecture: the <strong>Decoder</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hq4sv7MntPW6m5mn.png" /></figure><p>The Decoder’s role is to take the encoded representation from the Encoder and generate the output sequence, token by token (e.g., translating a sentence, generating a summary). While it shares some components with the Encoder, it has key differences to handle the sequential generation process.</p><p>In this post, we will:</p><ol><li>Understand the structure of a single Decoder block, including its three sub-layers.</li><li>Implement the DecoderBlock module, paying close attention to the different attention mechanisms and masks.</li><li>Implement the full Decoder by stacking multiple DecoderBlock layers.</li><li>Test our implementation.</li></ol><h3>The Decoder Block Structure</h3><p>Referring again to Figure 1 of the <a href="https://arxiv.org/abs/1706.03762">“Attention Is All You Need”</a> paper (right half), we see that a Decoder block is slightly more complex than an Encoder block. It contains <strong>three</strong> main sub-layers, each followed by the “Add &amp; Norm” step (Residual Connection + Layer Normalization):</p><ol><li><strong>Masked Multi-Head Self-Attention:</strong> Similar to the Encoder’s self-attention, but it operates on the <em>target</em> sequence (the output being generated so far). Crucially, it uses a <strong>look-ahead mask</strong>. This prevents positions from attending to subsequent positions, ensuring that the prediction for the current token i only depends on the known outputs at positions less than i. This preserves the auto-regressive property needed for generation.</li><li><strong>Multi-Head Encoder-Decoder Attention (Cross-Attention):</strong> This is where the Decoder interacts with the Encoder’s output.<br>• The <strong>Queries (Q)</strong> come from the output of the previous sub-layer (the masked self-attention layer).<br>• The Keys (K) and Values (V) come from the output of the Encoder stack.<br>• This allows each position in the Decoder to attend to all positions in the input sequence (via the Encoder’s representation), figuring out which parts of the input are relevant for generating the current output token. It typically uses the padding mask from the source sequence (src_mask).</li><li><strong>Position-wise Feed-Forward Network (FFN):</strong> Identical in structure to the FFN used in the Encoder block, providing further non-linear processing.</li></ol><p>The data flow through a single DecoderBlock is:</p><ol><li>Input x (from previous decoder layer or target embedding + PE) goes into Masked Multi-Head Self-Attention (using tgt_mask).</li><li>attn_output_1 = LayerNorm(x + Dropout(MaskedSelfAttention(x))).</li><li>attn_output_1 is used as Query for the Cross-Attention layer. Keys and Values come from encoder_output. Use src_mask.</li><li>attn_output_2 = LayerNorm(attn_output_1 + Dropout(CrossAttention(attn_output_1, encoder_output, encoder_output))).</li><li>attn_output_2 goes into the FFN.</li><li>ffn_output = LayerNorm(attn_output_2 + Dropout(FFN(attn_output_2))).</li><li>This ffn_output is the final output of the DecoderBlock.</li></ol><h3>Implementing the Decoder Block</h3><p>We need instances of Multi-Head Attention for both self-attention and cross-attention, plus the FFN and Residual Connection modules.</p><pre>import torch<br>import torch.nn as nn<br><br># Assume MultiHeadAttention, PositionwiseFeedForward, LayerNormalization,<br># and ResidualConnection classes from previous parts are defined/imported.<br># Example imports (adjust paths if needed):<br># from part3 import MultiHeadAttention<br># from part4 import PositionwiseFeedForward, ResidualConnection<br>from part4b import PositionwiseFeedForward<br>from part4c import ResidualConnection<br>from part3a import MultiHeadAttention<br><br>class DecoderBlock(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements a single block of the Transformer Decoder.<br>    Consists of Masked Self-Attention, Cross-Attention (Encoder-Decoder),<br>    and Feed-Forward sub-layers, each followed by Add &amp; Norm.<br>    &quot;&quot;&quot;<br>    def __init__(self, features: int, self_attention_block: MultiHeadAttention, cross_attention_block: MultiHeadAttention, feed_forward_block: PositionwiseFeedForward, dropout: float):<br>        &quot;&quot;&quot;<br>        Args:<br>            features (int): Number of features (d_model).<br>            self_attention_block (MultiHeadAttention): Pre-initialized Masked Multi-Head Self-Attention module.<br>            cross_attention_block (MultiHeadAttention): Pre-initialized Multi-Head Encoder-Decoder Attention module.<br>            feed_forward_block (PositionwiseFeedForward): Pre-initialized Position-wise Feed-Forward module.<br>            dropout (float): Dropout probability for the residual connections.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.self_attention_block = self_attention_block<br>        self.cross_attention_block = cross_attention_block<br>        self.feed_forward_block = feed_forward_block<br>        # Create three residual connection wrappers<br>        self.residual_connections = nn.ModuleList([ResidualConnection(features, dropout) for _ in range(3)])<br><br>    def forward(self, x: torch.Tensor, encoder_output: torch.Tensor, src_mask: torch.Tensor, tgt_mask: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Forward pass for the DecoderBlock.<br><br>        Args:<br>            x (torch.Tensor): Input tensor from the previous decoder layer or target embeddings,<br>                              shape (batch_size, tgt_seq_len, d_model).<br>            encoder_output (torch.Tensor): Output tensor from the Encoder stack,<br>                                           shape (batch_size, src_seq_len, d_model).<br>            src_mask (torch.Tensor): Source mask (for padding) used in the cross-attention layer.<br>                                     Shape needs to be broadcastable to<br>                                     (batch_size, num_heads, tgt_seq_len, src_seq_len). Example: (batch_size, 1, 1, src_seq_len).<br>            tgt_mask (torch.Tensor): Target mask (look-ahead + padding) used in the self-attention layer.<br>                                     Shape needs to be broadcastable to<br>                                     (batch_size, num_heads, tgt_seq_len, tgt_seq_len). Example: (batch_size, 1, tgt_seq_len, tgt_seq_len).<br><br>        Returns:<br>            torch.Tensor: Output tensor, shape (batch_size, tgt_seq_len, d_model).<br>        &quot;&quot;&quot;<br>        # 1. Apply Masked Multi-Head Self-Attention with Add &amp; Norm<br>        # Query, Key, Value are all &#39;x&#39;. Use target mask (tgt_mask).<br>        x = self.residual_connections[0](x, lambda x_res: self.self_attention_block(x_res, x_res, x_res, tgt_mask))<br><br>        # 2. Apply Multi-Head Cross-Attention (Encoder-Decoder) with Add &amp; Norm<br>        # Query is the output from the previous step (&#39;x&#39;). Key and Value are from the encoder_output.<br>        # Use source mask (src_mask).<br>        x = self.residual_connections[1](x, lambda x_res: self.cross_attention_block(x_res, encoder_output, encoder_output, src_mask))<br><br>        # 3. Apply Position-wise Feed-Forward Network with Add &amp; Norm<br>        x = self.residual_connections[2](x, self.feed_forward_block)<br><br>        return x</pre><p><strong>Code Explanation:</strong></p><p>__init__:</p><ul><li>Takes features (d_model), two separate instances of MultiHeadAttention (one for self-attention, one for cross-attention), an instance of PositionwiseFeedForward, and the dropout rate.</li><li>Stores these sub-modules.</li><li>Initializes a nn.ModuleList with <em>three</em> ResidualConnection modules.</li></ul><p>forward:</p><ul><li>Takes the target input x, the encoder_output, the src_mask (for cross-attention), and the tgt_mask (for self-attention).</li><li><strong>First Sub-layer (Masked Self-Attention):</strong> Calls the first ResidualConnection. The lambda function passes x as Q, K, and V to the self_attention_block along with the tgt_mask.</li><li><strong>Second Sub-layer (Cross-Attention):</strong> Calls the second ResidualConnection. The lambda function passes the output of the previous step (x) as the Query, and the encoder_output as both Key and Value to the cross_attention_block, along with the src_mask.</li><li><strong>Third Sub-layer (FFN):</strong> Calls the third ResidualConnection, passing the output from the cross-attention step (x) and the feed_forward_block.</li><li>Returns the final output tensor for the block.</li></ul><h3>Implementing the Decoder Stack</h3><p>Similar to the Encoder, the full Decoder consists of stacking N identical DecoderBlock layers (N=6 in the paper).</p><h3>Implementation</h3><pre>import torch<br>import torch.nn as nn<br><br># Assuming DecoderBlock class is defined as above<br># Assuming LayerNormalization class from Part 4 is defined/imported<br>from part4a import LayerNormalization<br>from part6a import DecoderBlock <br><br>class Decoder(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements the full Transformer Decoder, consisting of a stack of DecoderBlocks.<br>    &quot;&quot;&quot;<br>    def __init__(self, features: int, layers: nn.ModuleList):<br>        &quot;&quot;&quot;<br>        Args:<br>            features (int): Number of features (d_model). Used for final LayerNorm.<br>            layers (nn.ModuleList): A list of pre-initialized DecoderBlock layers.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.layers = layers<br>        # Final LayerNorm after the stack (consistent with Encoder implementation)<br>        self.norm = LayerNormalization(features)<br><br>    def forward(self, x: torch.Tensor, encoder_output: torch.Tensor, src_mask: torch.Tensor, tgt_mask: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Forward pass for the entire Decoder stack.<br><br>        Args:<br>            x (torch.Tensor): Input tensor (target embeddings + positional encoding),<br>                              shape (batch_size, tgt_seq_len, d_model).<br>            encoder_output (torch.Tensor): Output from the Encoder stack,<br>                                           shape (batch_size, src_seq_len, d_model).<br>            src_mask (torch.Tensor): Source mask for cross-attention layers.<br>            tgt_mask (torch.Tensor): Target mask for self-attention layers.<br><br>        Returns:<br>            torch.Tensor: Output tensor of the decoder stack, shape (batch_size, tgt_seq_len, d_model).<br>        &quot;&quot;&quot;<br>        # Pass the input through each layer in the stack<br>        for layer in self.layers:<br>            # Pass all required inputs to each decoder block<br>            x = layer(x, encoder_output, src_mask, tgt_mask)<br>        # Apply final layer normalization<br>        return self.norm(x)</pre><p><strong>Code Explanation:</strong></p><p>__init__:</p><ul><li>Takes the feature size and a nn.ModuleList of pre-initialized DecoderBlock layers. Includes a final LayerNormalization.</li></ul><p>forward:</p><ul><li>Takes the target input x, the encoder_output, src_mask, and tgt_mask. It iterates through the stack of DecoderBlock layers, passing all necessary arguments (x, encoder_output, src_mask, tgt_mask) to each layer. The output x of one layer becomes the input x for the next. Finally, it applies the Layer Normalization.</li></ul><h3>Testing the Decoder</h3><p>Let’s instantiate the components and test the full Decoder stack.</p><pre>import torch<br>import torch.nn as nn<br><br># Assuming LayerNormalization class from Part 4 is defined/imported<br>from part4b import PositionwiseFeedForward<br>from part5a import MultiHeadAttention<br>from part6a import DecoderBlock<br>from part6b import Decoder<br><br># --- Unit Testing / Verification ---<br>print(&quot;\n--- Testing Decoder ---&quot;)<br><br># Parameters<br>batch_size_test = 4<br>src_seq_len_test = 12 # Source sequence length<br>tgt_seq_len_test = 10 # Target sequence length<br>d_model_test = 512<br>num_heads_test = 8<br>d_ff_test = 2048<br>num_layers_test = 6 # N=6 as in the paper<br>dropout_test = 0.1<br><br># Dummy inputs<br>dummy_tgt = torch.randn(batch_size_test, tgt_seq_len_test, d_model_test) # Target input<br>dummy_encoder_output = torch.randn(batch_size_test, src_seq_len_test, d_model_test) # From Encoder<br><br># Dummy masks<br># Source mask (padding mask for encoder output) -&gt; shape (batch, 1, 1, src_seq_len)<br>dummy_src_mask_dec = torch.zeros(batch_size_test, 1, 1, src_seq_len_test, dtype=torch.bool)<br>if batch_size_test &gt;= 1: dummy_src_mask_dec[0, :, :, -3:] = True # Example padding<br>if batch_size_test &gt;= 2: dummy_src_mask_dec[1, :, :, -2:] = True<br><br># Target mask (look-ahead + padding) -&gt; shape (batch, 1, tgt_seq_len, tgt_seq_len)<br># Combine look-ahead and potential padding mask for target<br>tgt_padding_mask = torch.zeros(batch_size_test, 1, 1, tgt_seq_len_test, dtype=torch.bool) # Example padding mask<br>if batch_size_test &gt;= 1: tgt_padding_mask[0, :, :, -1:] = True<br>look_ahead_mask = torch.triu(torch.ones(tgt_seq_len_test, tgt_seq_len_test), diagonal=1).bool().unsqueeze(0).unsqueeze(0) # Shape [1, 1, T, T]<br># Combine: mask is True if EITHER look-ahead OR padding applies<br>dummy_tgt_mask_dec = (tgt_padding_mask | look_ahead_mask) # Logical OR, shape broadcasts to [B, 1, T, T]<br><br>print(f&quot;Dummy Target Input shape: {dummy_tgt.shape}&quot;)<br>print(f&quot;Dummy Encoder Output shape: {dummy_encoder_output.shape}&quot;)<br>print(f&quot;Dummy Source Mask shape: {dummy_src_mask_dec.shape}&quot;)<br>print(f&quot;Dummy Target Mask shape: {dummy_tgt_mask_dec.shape}&quot;)<br><br># Build Decoder components<br>self_attention = MultiHeadAttention(d_model_test, num_heads_test, dropout_test)<br>cross_attention = MultiHeadAttention(d_model_test, num_heads_test, dropout_test)<br>feed_forward = PositionwiseFeedForward(d_model_test, d_ff_test, dropout_test)<br><br># Create a stack of DecoderBlocks<br>decoder_layers = nn.ModuleList([<br>    DecoderBlock(d_model_test, self_attention, cross_attention, feed_forward, dropout_test)<br>    for _ in range(num_layers_test)<br>])<br><br># Instantiate the Decoder<br>decoder = Decoder(d_model_test, decoder_layers)<br><br># Perform forward pass<br>decoder_output = decoder(dummy_tgt, dummy_encoder_output, dummy_src_mask_dec, dummy_tgt_mask_dec)<br><br># Check output shape<br>print(f&quot;Output shape after Decoder: {decoder_output.shape}&quot;) # Expected: [4, 10, 512]<br>assert decoder_output.shape == dummy_tgt.shape # Output seq len should match target input seq len<br><br>print(&quot;Decoder test passed (shape check).&quot;)</pre><p><strong>Explanation:</strong></p><ul><li>We set up parameters and create dummy tensors for target input (dummy_tgt), encoder output (dummy_encoder_output), source mask (dummy_src_mask_dec), and target mask (dummy_tgt_mask_dec).</li><li>Note the creation of the dummy_tgt_mask_dec, which combines a look-ahead mask (upper triangle) with an example padding mask using logical OR. This ensures positions are masked if they are padding <em>or</em> if they are future tokens.</li><li>We instantiate the necessary sub-modules (two separate MultiHeadAttention instances are needed for self- and cross-attention).</li><li>We build the stack of DecoderBlocks and instantiate the Decoder.</li><li>We pass all required inputs through the decoder.</li><li>We assert that the final output shape matches the <em>target</em> input shape (batch_size, tgt_seq_len, d_model).</li></ul><h3>What’s Next?</h3><p>With both the Encoder (Part 5) and the Decoder (this part) fully implemented, we have the two main processing stacks of the Transformer.</p><p>In <a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7: Assembling the Full Transformer &amp; Final Output Layer</strong></a>, we will finally connect the Encoder and Decoder, along with the Input/Output Embeddings and Positional Encoding, to create the complete end-to-end Transformer model. We will also add the final linear layer that projects the Decoder’s output into vocabulary scores for prediction.</p><p>Almost there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=989a17347224" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 5 — The Encoder]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-5-the-encoder-ef5a3ab87bd3?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef5a3ab87bd3</guid>
            <category><![CDATA[transformer-encoder]]></category>
            <category><![CDATA[model-building]]></category>
            <category><![CDATA[encoder]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 20:14:15 GMT</pubDate>
            <atom:updated>2025-04-13T11:14:18.531Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 5 — The Encoder</h3><p>Assembles the Multi-Head Attention and Feed-Forward networks into Encoder blocks and stacks them to form the full Encoder.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 5 — The Encoder</h3><p>Welcome back to “Transformers From Scratch”! In the previous parts, we’ve meticulously built the fundamental components:</p><ul><li><a href="https://medium.com/p/bbce1f39040d">Part 1: Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af">Part 2: Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89">Part 3: Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8">Part 4: Add &amp; Norm, Feed-Forward</a></li></ul><p>Now it’s time to assemble these pieces to construct the <strong>Encoder</strong> side of the Transformer architecture, as depicted in the <a href="https://arxiv.org/abs/1706.03762">“Attention Is All You Need”</a> paper (Figure 1, left half).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcDzGOs6_WwNVmBAsCUVaQ.png" /><figcaption>Figure 1, Transformer Encoder and Decoder Source: <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></figcaption></figure><p>In this post, we will:</p><ol><li>Understand the structure of a single Encoder block.</li><li>Implement the EncoderBlock module using the components we&#39;ve already built.</li><li>Implement the full Encoder by stacking multiple EncoderBlock layers.</li><li>Test our implementation.</li></ol><h3>The Encoder Block Structure</h3><p>The Encoder’s job is to process the input sequence (embeddings + positional encodings) and generate a contextualized representation for each token. It does this using a stack of identical layers. Each layer, which we’ll call EncoderBlock, has two main sub-layers:</p><ol><li><strong>Multi-Head Self-Attention:</strong> This layer allows each token to attend to all other tokens (including itself) in the input sequence, capturing contextual dependencies.</li><li><strong>Position-wise Feed-Forward Network (FFN):</strong> This layer processes the output of the attention mechanism independently at each position, adding further non-linear transformation capacity.</li></ol><p>Crucially, as we implemented in Part 4, each of these sub-layers is wrapped within a <strong>Residual Connection followed by Layer Normalization</strong> (the “Add &amp; Norm” step). This helps with training stability and gradient flow.</p><p>The data flow through a single EncoderBlock looks like this:</p><ol><li>Input x goes into the Multi-Head Self-Attention sub-layer.</li><li>The output of attention is passed through dropout, added back to the original input x (residual connection), and then normalized: attn_output = LayerNorm(x + Dropout(SelfAttention(x))).</li><li>This attn_output then goes into the Position-wise Feed-Forward Network.</li><li>The output of the FFN is passed through dropout, added back to the <em>input of the FFN</em> (attn_output), and normalized again: ffn_output = LayerNorm(attn_output + Dropout(FFN(attn_output))).</li><li>This ffn_output is the final output of the EncoderBlock.</li></ol><h3>Implementing the Encoder Block</h3><p>We’ll create an nn.Module that encapsulates this structure, taking instances of our previously defined MultiHeadAttention, PositionwiseFeedForward, and ResidualConnection modules.</p><pre>import torch<br>import torch.nn as nn<br><br># Assume MultiHeadAttention, PositionwiseFeedForward, LayerNormalization,<br># and ResidualConnection classes from previous parts are defined/imported.<br># Example imports (adjust paths if needed):<br># from part3 import MultiHeadAttention<br># from part4 import PositionwiseFeedForward, ResidualConnection<br>from part4b import PositionwiseFeedForward<br>from part4c import ResidualConnection<br>from part3a import MultiHeadAttention<br><br>class EncoderBlock(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements a single block of the Transformer Encoder.<br>    Consists of Multi-Head Self-Attention and Position-wise Feed-Forward sub-layers,<br>    each followed by a residual connection and layer normalization.<br>    &quot;&quot;&quot;<br>    def __init__(self, features: int, self_attention_block: MultiHeadAttention, feed_forward_block: PositionwiseFeedForward, dropout: float):<br>        &quot;&quot;&quot;<br>        Args:<br>            features (int): Number of features (d_model).<br>            self_attention_block (MultiHeadAttention): Pre-initialized Multi-Head Self-Attention module.<br>            feed_forward_block (PositionwiseFeedForward): Pre-initialized Position-wise Feed-Forward module.<br>            dropout (float): Dropout probability for the residual connections.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.self_attention_block = self_attention_block<br>        self.feed_forward_block = feed_forward_block<br>        # Create two residual connection wrappers<br>        self.residual_connections = nn.ModuleList([ResidualConnection(features, dropout) for _ in range(2)])<br><br>    def forward(self, x: torch.Tensor, src_mask: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Forward pass for the EncoderBlock.<br><br>        Args:<br>            x (torch.Tensor): Input tensor, shape (batch_size, seq_len, d_model).<br>            src_mask (torch.Tensor): Source mask for the self-attention layer to hide padding tokens.<br>                                     Shape needs to be broadcastable to<br>                                     (batch_size, num_heads, seq_len, seq_len). Example: (batch_size, 1, 1, seq_len).<br><br>        Returns:<br>            torch.Tensor: Output tensor, shape (batch_size, seq_len, d_model).<br>        &quot;&quot;&quot;<br>        # 1. Apply Multi-Head Self-Attention with Add &amp; Norm<br>        # The sublayer function needs to accept only &#39;x&#39;. We use a lambda to pass Q, K, V and the mask.<br>        # Note: For self-attention, query, key, and value are all the same input &#39;x&#39;.<br>        x = self.residual_connections[0](x, lambda x_res: self.self_attention_block(x_res, x_res, x_res, src_mask))<br><br>        # 2. Apply Position-wise Feed-Forward Network with Add &amp; Norm<br>        x = self.residual_connections[1](x, self.feed_forward_block)<br><br>        return x</pre><p><strong>Code Explanation:</strong></p><p>__init__:</p><ul><li>Takes the feature size (d_model), pre-initialized instances of MultiHeadAttention and PositionwiseFeedForward, and the dropout rate.</li><li>Stores the attention and feed-forward blocks.</li><li>Initializes a nn.ModuleList containing two ResidualConnection modules (one for each sub-layer). Using nn.ModuleList ensures these modules are correctly registered with PyTorch.</li></ul><p>forward:</p><ul><li>Takes the input tensor x and the source mask src_mask.</li><li><strong>First Sub-layer (Self-Attention):</strong> It calls the first ResidualConnection module (self.residual_connections[0]).<br>- The input x is passed.<br>- The sublayer argument is provided as a lambda function. This is necessary because our ResidualConnection.forward expects a sublayer that takes only one argument (x), but the MultiHeadAttention.forward method needs query, key, value, and mask. The lambda wraps the call, providing x as Q, K, and V (since it&#39;s self-attention) and passing the src_mask.</li><li><strong>Second Sub-layer (FFN):</strong> The output from the first Add &amp; Norm step is passed as input x to the second ResidualConnection module (self.residual_connections[1]).<br>- The sublayer argument is simply self.feed_forward_block, as its forward method only takes x.</li><li>Returns the final output tensor after both sub-layers and their respective Add &amp; Norm steps.</li></ul><h3>Implementing the Encoder Stack</h3><p>The full Encoder isn’t just one block; it’s a stack of N identical EncoderBlock layers (where N=6 in the original paper). The output of one layer feeds directly into the next.</p><h3>Implementation</h3><pre>import torch<br>import torch.nn as nn<br><br># Assuming EncoderBlock class is defined as above<br># Assuming LayerNormalization class from Part 4 is defined/imported<br>from part4a import LayerNormalization<br>from part5a import EncoderBlock<br><br>class Encoder(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements the full Transformer Encoder, consisting of a stack of EncoderBlocks.<br>    &quot;&quot;&quot;<br>    def __init__(self, features: int, layers: nn.ModuleList):<br>        &quot;&quot;&quot;<br>        Args:<br>            features (int): Number of features (d_model). Used for final LayerNorm.<br>            layers (nn.ModuleList): A list of pre-initialized EncoderBlock layers.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.layers = layers<br>        # Include final LayerNorm after the stack? Paper figure doesn&#39;t show it explicitly AFTER Nx,<br>        # but text implies norm is within each layer&#39;s residual connection.<br>        # Some implementations add it here for extra stability. Let&#39;s add it.<br>        self.norm = LayerNormalization(features)<br><br>    def forward(self, x: torch.Tensor, mask: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Forward pass for the entire Encoder stack.<br><br>        Args:<br>            x (torch.Tensor): Input tensor (from embeddings + positional encoding),<br>                              shape (batch_size, seq_len, d_model).<br>            mask (torch.Tensor): Source mask applied in all self-attention layers.<br><br>        Returns:<br>            torch.Tensor: Output tensor of the encoder stack, shape (batch_size, seq_len, d_model).<br>        &quot;&quot;&quot;<br>        # Pass the input through each layer in the stack<br>        for layer in self.layers:<br>            x = layer(x, mask)<br>        # Apply final layer normalization<br>        return self.norm(x)</pre><p><strong>Code Explanation:</strong></p><p>__init__:</p><ul><li>Takes the feature size (features = d_model) and a nn.ModuleList containing the pre-initialized EncoderBlock layers.</li><li>Stores the list of layers.</li><li>Initializes a final LayerNormalization layer. While the original paper diagram doesn&#39;t explicitly show a LayerNorm <em>after</em> the entire stack (it&#39;s part of each residual connection within the blocks), many implementations add one here for potentially increased stability. We include it here.</li></ul><p>forward:</p><ul><li>Takes the initial input x (output from InputEmbeddings + PositionalEncoding) and the source mask.</li><li>It iterates through the self.layers (the stack of EncoderBlocks), passing the output of one layer as the input to the next. The mask is passed to each block.</li><li>After the loop, it applies the final LayerNormalization to the output of the last block.</li><li>Returns the final encoded representation.</li></ul><h3>Testing the Encoder</h3><p>Let’s instantiate the components and test the full Encoder stack.</p><pre>import torch<br>import torch.nn as nn<br><br># Assuming the supporting modules are defined in separate files<br>from part5a import EncoderBlock<br>from part5b import Encoder<br>from part3a import MultiHeadAttention<br>from part4b import PositionwiseFeedForward<br><br># --- Unit Testing / Verification ---<br>print(&quot;\n--- Testing Encoder ---&quot;)<br><br># Parameters<br>batch_size_test = 4<br>seq_len_test = 12<br>d_model_test = 512<br>num_heads_test = 8<br>d_ff_test = 2048<br>num_layers_test = 6 # N=6 as in the paper<br>dropout_test = 0.1<br><br># Dummy input (output from Embedding + Positional Encoding)<br>dummy_src = torch.randn(batch_size_test, seq_len_test, d_model_test)<br><br># Dummy source mask (e.g., padding mask)<br># Shape: (batch_size, 1, 1, seq_len) -&gt; True where padded<br>dummy_src_mask = torch.zeros(batch_size_test, 1, 1, seq_len_test, dtype=torch.bool)<br># Mask last 3 positions for first item, last 2 for second<br>if batch_size_test &gt;= 1:<br>    dummy_src_mask[0, :, :, -3:] = True<br>if batch_size_test &gt;= 2:<br>    dummy_src_mask[1, :, :, -2:] = True<br># ... add more if needed<br><br>print(f&quot;Dummy Source Input shape: {dummy_src.shape}&quot;)<br>print(f&quot;Dummy Source Mask shape: {dummy_src_mask.shape}&quot;)<br><br># Build Encoder components<br>self_attention = MultiHeadAttention(d_model_test, num_heads_test, dropout_test)<br>feed_forward = PositionwiseFeedForward(d_model_test, d_ff_test, dropout_test)<br><br># Create a stack of EncoderBlocks<br>encoder_layers = nn.ModuleList([<br>    EncoderBlock(d_model_test, self_attention, feed_forward, dropout_test)<br>    for _ in range(num_layers_test)<br>])<br><br># Instantiate the Encoder<br>encoder = Encoder(d_model_test, encoder_layers)<br><br># Perform forward pass<br>encoder_output = encoder(dummy_src, dummy_src_mask)<br><br># Check output shape<br>print(f&quot;Output shape after Encoder: {encoder_output.shape}&quot;) # Expected: [4, 12, 512]<br>assert encoder_output.shape == dummy_src.shape<br><br>print(&quot;Encoder test passed (shape check).&quot;)</pre><p><strong>Explanation:</strong></p><ul><li>We define parameters matching the base Transformer model (N=6, d_model=512, etc.).</li><li>We create dummy source input and a source padding mask.</li><li>We instantiate the sub-modules (MultiHeadAttention, PositionwiseFeedForward) needed for an EncoderBlock.</li><li>We create a nn.ModuleList containing num_layers_test (e.g., 6) instances of EncoderBlock, passing the same shared attention and feed-forward instances (or you could create separate instances for each block if desired, though sharing is standard).</li><li>We instantiate the Encoder with the feature size and the list of blocks.</li><li>We pass the dummy input and mask through the encoder.</li><li>We assert that the final output shape is the same as the input shape (batch_size, seq_len, d_model), which is expected for the Encoder.</li></ul><h3>What’s Next?</h3><p>We have successfully built the entire Encoder component of the Transformer! This stack of layers takes the initial input sequence and transforms it into a sequence of rich contextual representations, ready to be used by the Decoder.</p><p>In <a href="https://medium.com/p/989a17347224"><strong>Part 6: Building the Decoder Block &amp; Decoder Stack</strong></a>, we will tackle the other half of the architecture. The Decoder shares similarities with the Encoder but includes an additional attention mechanism to incorporate information from the Encoder’s output, along with masked self-attention to handle sequence generation.</p><p>Get ready for the Decoder!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef5a3ab87bd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 4 — Add & Norm, Feed-Forward]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-4-add-norm-feed-forward-743763f929c8?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/743763f929c8</guid>
            <category><![CDATA[residual-connection]]></category>
            <category><![CDATA[feed-forward]]></category>
            <category><![CDATA[layer-normalization]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning-techniques]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 19:59:33 GMT</pubDate>
            <atom:updated>2025-04-13T11:14:06.102Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 4 — Add &amp; Norm, Feed-Forward</h3><p>Constructs the supporting Layer Normalization, Position-wise Feed-Forward, and Residual Connection components.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 4 — Add &amp; Norm, Feed-Forward</h3><p>Welcome back to “Transformers From Scratch”! In <a href="https://medium.com/p/d1a3a061ba89">Part 3: Multi-Head Attention</a>, we built the powerful Multi-Head Attention mechanism. While attention is central, the Encoder and Decoder blocks in a Transformer contain other essential components that enable stable training and effective information processing.</p><p>In this post, we will implement these crucial supporting players as described in the <a href="https://arxiv.org/abs/1706.03762">“Attention Is All You Need”</a> paper:</p><ol><li><strong>Layer Normalization:</strong> Stabilizes the network’s activations.</li><li><strong>Position-wise Feed-Forward Network:</strong> Adds further processing capacity after attention.</li><li><strong>Residual Connections:</strong> Helps with gradient flow and enables deeper networks, combining the sublayer output with the input before normalization (“Add &amp; Norm”).</li></ol><p>Let’s build these components.</p><h3>Component 1: Layer Normalization</h3><p>Deep neural networks can suffer from unstable training dynamics, where the distribution of activations in intermediate layers shifts significantly during training (internal covariate shift). Normalization techniques help mitigate this. While Batch Normalization is common in computer vision, <strong>Layer Normalization</strong> is often preferred in Transformers and NLP.</p><p><strong>Concept:</strong> Layer Normalization works by normalizing the features <em>across the embedding dimension</em> for each token independently within a layer. It calculates the mean and standard deviation for all features of a single token and uses them to normalize that token’s feature vector. Unlike Batch Norm, its calculations don’t depend on the batch size, making it more stable for variable sequence lengths common in NLP.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FkH2TwAXqsRrg4YPN6x7dhc&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FkH2TwAXqsRrg4YPN6x7dhc" width="222" height="154" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea332d9dcf369919cbbffc6ac686e97a/href">https://medium.com/media/ea332d9dcf369919cbbffc6ac686e97a/href</a></iframe><p>\hat{x} = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}}</p><p>y = \gamma \hat{x} + \beta</p><p>The formula involves:</p><ol><li>Calculating the mean \mu and variance \sigma^2 across the feature dimension (d_model) for each input vector x in the batch.</li><li>Normalizing x: <br>\hat{x} = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} <br>(where \epsilon is a small value for numerical stability).</li><li>Scaling and shifting the normalized output using learned parameters: <br>y = \gamma \hat{x} + \beta<br>\gamma and \beta are learnable parameters (initialized to 1 and 0 respectively) that allow the network to learn the optimal scale and mean for the normalized activations.</li></ol><h3>Implementing Layer Normalization</h3><pre>import torch<br>import torch.nn as nn<br>import math<br><br>class LayerNormalization(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements Layer Normalization.<br>    &quot;&quot;&quot;<br>    def __init__(self, features: int, eps: float = 1e-6):<br>        &quot;&quot;&quot;<br>        Args:<br>            features (int): Number of features (d_model).<br>            eps (float, optional): Epsilon value for numerical stability. Defaults to 1e-6.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.eps = eps<br>        # Learnable scale parameter (gamma), initialized to ones<br>        self.gamma = nn.Parameter(torch.ones(features))<br>        # Learnable shift parameter (beta), initialized to zeros<br>        self.beta = nn.Parameter(torch.zeros(features))<br><br>    def forward(self, x: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Forward pass for Layer Normalization.<br><br>        Args:<br>            x (torch.Tensor): Input tensor, shape (batch_size, seq_len, features)<br><br>        Returns:<br>            torch.Tensor: Normalized tensor, shape (batch_size, seq_len, features)<br>        &quot;&quot;&quot;<br>        # Calculate mean and standard deviation along the feature dimension (-1)<br>        # keepdim=True maintains the dimension for broadcasting<br>        mean = x.mean(dim=-1, keepdim=True)<br>        std = x.std(dim=-1, keepdim=True)<br><br>        # Normalize the input<br>        # (x - mean) / sqrt(std^2 + eps)<br>        normalized_x = (x - mean) / torch.sqrt(std**2 + self.eps) # Using std directly: (x - mean) / (std + self.eps) is also common<br><br>        # Apply scale (gamma) and shift (beta)<br>        # gamma and beta have shape (features), they will broadcast correctly<br>        output = self.gamma * normalized_x + self.beta<br>        return output</pre><p><strong>Code Explanation:</strong></p><ul><li>__init__: Stores the eps value and initializes the learnable gamma (scale) and beta (shift) parameters using nn.Parameter. They are initialized to 1s and 0s respectively, so initially, the normalization effect is dominant.</li><li>forward:<br>- Calculates the mean and std of the input x across the last dimension (features or d_model), keeping the dimension for broadcasting.<br>- Normalizes x using the calculated mean, standard deviation, and the small eps value to prevent division by zero.<br>- Applies the learned scale (gamma) and shift (beta) to the normalized tensor.</li></ul><h3>Component 2: Position-wise Feed-Forward Network (FFN)</h3><p>After the attention mechanism processes the relationships between tokens, each position’s resulting vector is passed through a <strong>Position-wise Feed-Forward Network (FFN)</strong> independently. This provides additional non-linear processing capacity to the model.</p><p><strong>Concept (Section 3.3 in the paper):</strong> The FFN consists of two linear transformations with a non-linear activation function (typically ReLU in the original paper, though GELU is common now) in between.</p><p>FFN(x) = Activation(x @ W1 + b1) @ W2 + b2</p><p>Or using nn.Linear:</p><p>FFN(x) = Linear2(Activation(Linear1(x)))</p><p>The input and output dimension is d_model, but the inner dimension (d_ff) is typically larger (e.g., d_ff = 4 * d_model). The <em>same</em> FFN (same weights W1, b1, W2, b2) is applied to each position (seq_len dimension) identically and independently. Dropout is also typically applied within the FFN.</p><h3>Implementing the FFN</h3><pre>import torch<br>import torch.nn as nn<br><br>class PositionwiseFeedForward(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements the Position-wise Feed-Forward Network.<br>    &quot;&quot;&quot;<br>    def __init__(self, d_model: int, d_ff: int, dropout: float):<br>        &quot;&quot;&quot;<br>        Args:<br>            d_model (int): Input and output dimension.<br>            d_ff (int): Inner dimension of the feed-forward network.<br>            dropout (float): Dropout probability.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        # First linear layer (d_model -&gt; d_ff)<br>        self.linear_1 = nn.Linear(d_model, d_ff)<br>        # Activation function (ReLU as per original paper)<br>        self.activation = nn.ReLU()<br>        # Dropout layer<br>        self.dropout = nn.Dropout(dropout)<br>        # Second linear layer (d_ff -&gt; d_model)<br>        self.linear_2 = nn.Linear(d_ff, d_model)<br><br>    def forward(self, x: torch.Tensor):<br>        &quot;&quot;&quot;<br>        Forward pass for the FFN.<br><br>        Args:<br>            x (torch.Tensor): Input tensor, shape (batch_size, seq_len, d_model)<br><br>        Returns:<br>            torch.Tensor: Output tensor, shape (batch_size, seq_len, d_model)<br>        &quot;&quot;&quot;<br>        # Apply layers sequentially: Linear1 -&gt; Activation -&gt; Dropout -&gt; Linear2<br>        x = self.linear_1(x)<br>        x = self.activation(x)<br>        x = self.dropout(x) # Dropout usually applied after activation<br>        x = self.linear_2(x)<br>        return x</pre><p><strong>Code Explanation:</strong></p><ul><li>__init__: Initializes the two nn.Linear layers (mapping d_model to d_ff and back to d_model), the nn.ReLU activation, and a nn.Dropout layer.</li><li>forward: Applies the layers in sequence to the input tensor x.</li></ul><h3>Component 3: Residual Connections (Add &amp; Norm Structure)</h3><p>A key technique enabling very deep networks like the Transformer is the use of <strong>Residual Connections</strong> (or skip connections), combined with Layer Normalization.</p><p><strong>Concept (Section 3.1 &amp; 5.4):</strong> Each sub-layer (like Multi-Head Attention or the FFN) in the Transformer block is wrapped in an “Add &amp; Norm” step. The structure is:</p><p>Output = LayerNorm(Input + Dropout(Sublayer(Input)))</p><p>Where:</p><ul><li>Input: The input to the sub-layer (e.g., the output from the previous layer or the initial embeddings).</li><li>Sublayer: The function implemented by the sub-layer itself (e.g., MultiHeadAttention or PositionwiseFeedForward).</li><li>Dropout: Dropout is applied to the <em>output</em> of the sub-layer.</li><li>+: The output of the (dropout-applied) sub-layer is added back to the original Input. This is the residual connection. It allows the network to bypass the sub-layer if needed and helps gradients flow directly.</li><li>LayerNorm: Layer Normalization is applied <em>after</em> the addition.</li></ul><h3>Implementing the Residual Connection Wrapper</h3><p>We can create a helper module to encapsulate this logic.</p><pre>import torch<br>import torch.nn as nn<br><br># Assuming LayerNormalization class is defined as above<br>from part4a import LayerNormalization<br><br>class ResidualConnection(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements the Add &amp; Norm step: LayerNorm(x + Dropout(Sublayer(x)))<br>    &quot;&quot;&quot;<br>    def __init__(self, features: int, dropout: float):<br>        &quot;&quot;&quot;<br>        Args:<br>            features (int): Number of features (d_model).<br>            dropout (float): Dropout probability to apply to the sublayer output.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.dropout = nn.Dropout(dropout)<br>        self.norm = LayerNormalization(features)<br><br>    def forward(self, x: torch.Tensor, sublayer: nn.Module):<br>        &quot;&quot;&quot;<br>        Forward pass for the residual connection.<br><br>        Args:<br>            x (torch.Tensor): Input tensor (batch_size, seq_len, features).<br>            sublayer (nn.Module): The sublayer module (e.g., MultiHeadAttention, PositionwiseFeedForward)<br>                                  to apply before the residual connection.<br><br>        Returns:<br>            torch.Tensor: Output tensor after dropout, addition, and normalization.<br>        &quot;&quot;&quot;<br>        # Apply the sublayer, then dropout, then add the original input x (residual connection),<br>        # and finally apply layer normalization.<br>        # Note: The paper applies norm *after* the addition.<br>        sublayer_output = sublayer(x)<br>        return self.norm(x + self.dropout(sublayer_output))</pre><p><strong>Code Explanation:</strong></p><ul><li>__init__: Initializes the nn.Dropout and LayerNormalization layers. It takes the feature size (d_model) for LayerNorm and the dropout rate.</li><li>forward: This method takes both the input x <em>and</em> the sublayer module (like MHA or FFN) as arguments.</li></ul><ol><li>It first applies the sublayer to the input x.</li><li>It applies dropout to the output of the sublayer.</li><li>It adds the original input x to the dropout-applied sublayer output (the &quot;Add&quot; part).</li><li>It applies LayerNormalization to the result of the addition (the &quot;Norm&quot; part).</li></ol><p><em>Usage Note:</em> When building the Encoder/Decoder blocks later, we will pass the actual Multi-Head Attention or FFN modules as the sublayer argument to this ResidualConnection module&#39;s forward method.</p><h3>Testing the Modules</h3><p>Let’s perform simple checks to ensure our modules work and produce outputs of the expected shapes.</p><pre>import torch<br>import torch.nn as nn<br><br># assuming the supporting modules are defined in separate files<br>from part4a import LayerNormalization<br>from part4b import PositionwiseFeedForward<br>from part4c import ResidualConnection<br><br># --- Unit Testing / Verification ---<br>print(&quot;\n--- Testing Supporting Modules ---&quot;)<br><br># Parameters<br>batch_size_test = 4<br>seq_len_test = 10<br>d_model_test = 512<br>d_ff_test = 2048 # Typical inner FFN dimension<br>dropout_test = 0.1<br><br># Dummy input<br>dummy_input = torch.randn(batch_size_test, seq_len_test, d_model_test)<br>print(f&quot;Dummy Input shape: {dummy_input.shape}&quot;)<br><br># --- Test LayerNormalization ---<br>ln_layer = LayerNormalization(d_model_test)<br>ln_output = ln_layer(dummy_input)<br>print(f&quot;Output shape after LayerNorm: {ln_output.shape}&quot;) # Expected: [4, 10, 512]<br>assert ln_output.shape == dummy_input.shape<br># Check if mean is close to 0 and std is close to 1 after norm (before scale/shift)<br># Note: We test the internal logic conceptually here; exact 0/1 depends on eps and learned params<br>print(&quot;LayerNormalization test passed (shape check).&quot;)<br><br># --- Test PositionwiseFeedForward ---<br>ffn_layer = PositionwiseFeedForward(d_model_test, d_ff_test, dropout_test)<br>ffn_output = ffn_layer(dummy_input)<br>print(f&quot;Output shape after FFN: {ffn_output.shape}&quot;) # Expected: [4, 10, 512]<br>assert ffn_output.shape == dummy_input.shape<br>print(&quot;PositionwiseFeedForward test passed (shape check).&quot;)<br><br># --- Test ResidualConnection ---<br># Create a dummy sublayer (e.g., a simple Linear layer for shape testing)<br>dummy_sublayer = nn.Linear(d_model_test, d_model_test)<br>residual_layer = ResidualConnection(d_model_test, dropout_test)<br>residual_output = residual_layer(dummy_input, dummy_sublayer) # Pass input and sublayer<br>print(f&quot;Output shape after ResidualConnection: {residual_output.shape}&quot;) # Expected: [4, 10, 512]<br>assert residual_output.shape == dummy_input.shape<br>print(&quot;ResidualConnection test passed (shape check).&quot;)</pre><p><strong>Explanation:</strong></p><ul><li>We instantiate each of the three modules (LayerNormalization, PositionwiseFeedForward, ResidualConnection).</li><li>For ResidualConnection, we create a dummy nn.Linear layer to act as the sublayer just for testing purposes.</li><li>We pass dummy input through each module and assert that the output shape remains (batch_size, seq_len, d_model), which is crucial for stacking layers.</li></ul><h3>What’s Next?</h3><p>We have now built all the essential supporting components for a standard Transformer block: Layer Normalization, the Position-wise Feed-Forward Network, and the Residual Connection wrapper that implements the “Add &amp; Norm” logic.</p><p>In <a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5: Building the Encoder Block &amp; Encoder Stack</strong></a>, we will finally assemble these pieces, along with the Multi-Head Attention from Part 3, to create a complete Encoder block. We will then stack these blocks to form the full Encoder component of the Transformer!</p><p>Get ready to put the pieces together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=743763f929c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 3 — Multi-Head Attention]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-3-multi-head-attention-d1a3a061ba89?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1a3a061ba89</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[model-building]]></category>
            <category><![CDATA[multi-head-attention]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 19:38:12 GMT</pubDate>
            <atom:updated>2025-04-13T11:13:47.597Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 3 — Multi-Head Attention</h3><p>Implements Multi-Head Attention, allowing the model to focus on different representation subspaces simultaneously.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 3 — Multi-Head Attention</h3><p>Welcome back to “Transformers From Scratch”! In <a href="https://medium.com/p/6c0634ce79af">Part 2: Scaled Dot-Product Attention</a>, we implemented the core attention calculation that allows the model to weigh the importance of different tokens in a sequence. Now, we’ll build upon that foundation to create <strong>Multi-Head Attention</strong>, a key component described in the <a href="https://arxiv.org/abs/1706.03762">“Attention Is All You Need”</a> paper (Section 3.2.2).</p><p>Multi-Head Attention enhances the model’s ability to capture complex relationships by running the basic attention mechanism multiple times in parallel with different learned perspectives.</p><p>In this post, we will:</p><ol><li>Understand the motivation behind using multiple attention “heads”.</li><li>Break down the Multi-Head Attention mechanism step-by-step.</li><li>Implement the MultiHeadAttention layer as a PyTorch nn.Module.</li><li>Test our implementation.</li></ol><h3>Why Multi-Head Attention?</h3><p>The Scaled Dot-Product Attention we built in Part 2 calculates a single set of attention weights, effectively averaging information from different value vectors based on a single representation of query-key similarity. While powerful, the paper’s authors found this could be limiting. Averaging might make it difficult for the model to distinguish information from different “representational subspaces.”</p><p>Imagine trying to understand a complex sentence. You might simultaneously pay attention to its grammatical structure, the semantic meaning of words, and perhaps coreference (which pronouns refer to which nouns). A single attention mechanism might struggle to focus on all these aspects at once.</p><p><strong>Multi-Head Attention</strong> addresses this by running the Scaled Dot-Product Attention multiple times (h times, or h &quot;heads&quot;) in parallel. The key idea is:</p><ol><li>Project the original Queries, Keys, and Values into h different, lower-dimensional subspaces using learned linear transformations.</li><li>Let each “head” perform attention independently within its subspace, potentially focusing on different aspects of the relationships between tokens.</li><li>Concatenate the results from all heads.</li><li>Combine the concatenated information using another learned linear transformation.</li></ol><p>This allows the model to jointly attend to information from different representation subspaces at different positions, leading to a richer overall representation.</p><h3>The Multi-Head Attention Mechanism</h3><p>Let’s break down the process mathematically and conceptually, following Figure 2 (right) in the paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*83EB9CufUJoZPeGA.png" /><figcaption>Multi-Head Attention, Source: <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></figcaption></figure><ol><li><strong>Input:</strong> Query (Q), Key (K), Value (V) tensors, typically with shape [batch_size, seq_len, d_model].</li><li><strong>Linear Projections:</strong> Project Q, K, V into h heads using learned weight matrices W^Q_i, W^K_i, W^V_i for each head i=1...h.<br>- Q_i = QW^Q_i <br>- K_i = KW^K_i <br>- V_i = VW^V_i<br>- Each projection reduces the dimension from d_model to d_k (for Q, K) and d_v (for V). Typically, d_k = d_v = d_{model} / h. This ensures the total computation remains similar to single-head attention with dimension d_model.</li><li><strong>Parallel Scaled Dot-Product Attention:</strong> Apply the attention function we built in Part 2 to each head independently:<br>- head_i = Attention(Q_i,K_i,V_i) = softmax(\frac{Q_i K_i^T}{sqrt{d_k}}V_i<br>- Each head_i will have shape [batch_size, seq_len_q, d_v].</li><li><strong>Concatenation:</strong> Concatenate the outputs of all heads along the last dimension:<br>- Concat(head_1, …, head_h)<br>- The resulting tensor has shape [batch_size, seq_len_q, h * d_v]. Since h * d_v = d_{model}, the shape becomes [batch_size, seq_len_q, d_model].</li><li><strong>Final Linear Projection:</strong> Apply a final linear transformation using weight matrix W^O to the concatenated output:<br>- MultiHead(Q, K, V) = Concat(head_1, …, head_h) W^O<br>- The final output has shape [batch_size, seq_len_q, d_model].</li></ol><h3>Implementation</h3><p>We’ll implement this as an nn.Module. We&#39;ll need the scaled_dot_product_attention function from Part 2.</p><pre>import torch<br>import torch.nn as nn<br>import math<br><br># Assume scaled_dot_product_attention function from Part 2 is available/imported<br># def scaled_dot_product_attention(query, key, value, mask=None, dropout=None): ...<br>from part2a import scaled_dot_product_attention<br><br>class MultiHeadAttention(nn.Module):<br>    &quot;&quot;&quot;<br>    Implements Multi-Head Attention mechanism.<br>    &quot;&quot;&quot;<br>    def __init__(self, d_model: int, num_heads: int, dropout: float):<br>        &quot;&quot;&quot;<br>        Args:<br>            d_model (int): Total dimension of the model.<br>            num_heads (int): Number of attention heads.<br>            dropout (float): Dropout probability.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        assert d_model % num_heads == 0, &quot;d_model must be divisible by num_heads&quot;<br><br>        self.d_model = d_model<br>        self.num_heads = num_heads<br>        self.d_k = d_model // num_heads # Dimension of keys/queries per head<br><br>        # Linear layers for Q, K, V projections (applied before splitting heads)<br>        self.W_q = nn.Linear(d_model, d_model)<br>        self.W_k = nn.Linear(d_model, d_model)<br>        self.W_v = nn.Linear(d_model, d_model)<br><br>        # Final linear layer after concatenating heads<br>        self.W_o = nn.Linear(d_model, d_model)<br><br>        self.dropout = nn.Dropout(dropout)<br><br>        # We store the attention weights from the last forward pass<br>        # for visualization or analysis (optional)<br>        self.attention_weights = None<br><br>    def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = None):<br>        &quot;&quot;&quot;<br>        Forward pass for Multi-Head Attention.<br><br>        Args:<br>            query (torch.Tensor): Query tensor, shape (batch_size, seq_len_q, d_model)<br>            key (torch.Tensor): Key tensor, shape (batch_size, seq_len_k, d_model)<br>            value (torch.Tensor): Value tensor, shape (batch_size, seq_len_v, d_model)<br>                                  Note: seq_len_k and seq_len_v are typically the same.<br>            mask (torch.Tensor, optional): Mask tensor, typically for padding or look-ahead.<br>                                           Shape needs to be broadcastable for attention scores.<br>                                           Example shapes: (batch_size, 1, 1, seq_len_k) for padding mask,<br>                                                         (1, 1, seq_len_q, seq_len_k) for look-ahead mask.<br><br>        Returns:<br>            torch.Tensor: Output tensor, shape (batch_size, seq_len_q, d_model)<br>        &quot;&quot;&quot;<br>        batch_size = query.shape[0]<br><br>        # 1. Apply linear projections W_q, W_k, W_v<br>        # Input shapes: (batch_size, seq_len, d_model)<br>        # Output shapes: (batch_size, seq_len, d_model)<br>        Q = self.W_q(query)<br>        K = self.W_k(key)<br>        V = self.W_v(value)<br><br>        # 2. Reshape Q, K, V for multi-head processing<br>        # Change shape from (batch_size, seq_len, d_model) to<br>        # (batch_size, seq_len, num_heads, d_k) and then transpose to<br>        # (batch_size, num_heads, seq_len, d_k)<br>        # d_k = d_model // num_heads<br>        Q = Q.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)<br>        K = K.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)<br>        V = V.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2) # Assuming d_v = d_k<br><br>        # 3. Apply Scaled Dot-Product Attention for each head<br>        # Q, K, V shapes: (batch_size, num_heads, seq_len, d_k)<br>        # Mask shape needs to be broadcastable to (batch_size, num_heads, seq_len_q, seq_len_k)<br>        # output shape: (batch_size, num_heads, seq_len_q, d_k)<br>        # attention_weights shape: (batch_size, num_heads, seq_len_q, seq_len_k)<br>        output, self.attention_weights = scaled_dot_product_attention(Q, K, V, mask, self.dropout)<br><br>        # 4. Concatenate heads and reshape<br>        # Transpose output back to (batch_size, seq_len_q, num_heads, d_k)<br>        output = output.transpose(1, 2).contiguous()<br>        # Reshape to (batch_size, seq_len_q, d_model) by combining heads<br>        output = output.view(batch_size, -1, self.d_model) # self.d_model = num_heads * d_k<br><br>        # 5. Apply final linear projection W_o<br>        # Input shape: (batch_size, seq_len_q, d_model)<br>        # Output shape: (batch_size, seq_len_q, d_model)<br>        output = self.W_o(output)<br><br>        return output</pre><p><strong>Code Explanation:</strong></p><ol><li><strong>__init__</strong>:<br>- Takes d_model, num_heads, and dropout rate as input.<br>- Asserts that d_model is divisible by num_heads.<br>- Calculates d_k (dimension per head).<br>- Initializes four nn.Linear layers: W_q, W_k, W_v for initial projections, and W_o for the final output projection. All map d_model to d_model.<br>- Initializes a nn.Dropout layer.<br>- Initializes self.attention_weights to None (we&#39;ll store the weights from the last call here).</li><li><strong>forward</strong>:<br>- Takes query, key, value, and an optional mask.<br>- <strong>Linear Projections:</strong> Applies W_q, W_k, W_v to the inputs.<br>- <strong>Reshape for Heads:</strong> This is a crucial step. The projected tensors (shape batch, seq_len, d_model) are reshaped and transposed to (batch_size, num_heads, seq_len, d_k).<br>- .view(batch_size, -1, self.num_heads, self.d_k) splits the last dimension (d_model) into num_heads and d_k.<br>- .transpose(1, 2) swaps the seq_len and num_heads dimensions so that calculations within scaled_dot_product_attention are performed correctly per head.<br>- <strong>Scaled Dot-Product Attention:</strong> Calls the function implemented in Part 2, passing the reshaped Q, K, V and the mask. The mask needs to be broadcastable (e.g., by adding dimensions for batch and head if it’s just a sequence mask). The function returns the attention output and weights for each head.<br>- <strong>Concatenate Heads:</strong> The output from attention (shape batch, heads, seq_len, d_k) needs to be reshaped back to (batch, seq_len, d_model).<br>- .transpose(1, 2) swaps heads and seq_len back.<br>- .contiguous() ensures the tensor is stored contiguously in memory after transposing (required before .view()).<br>- .view(batch_size, -1, self.d_model) merges the num_heads and d_k dimensions back into d_model.<br>- <strong>Final Projection:</strong> Applies the final linear layer W_o to the concatenated output.<br>- Returns the final output tensor.</li></ol><h3>Testing the Multi-Head Attention Module</h3><p>Let’s test our MultiHeadAttention module with dummy inputs.</p><pre>import torch<br><br># import earlier code<br>from part3a import MultiHeadAttention<br><br># --- Unit Testing / Verification ---<br>print(&quot;\n--- Testing Multi-Head Attention ---&quot;)<br><br># Parameters<br>batch_size_test = 4<br>seq_len_test = 10 # Sequence length for Q, K, V (can differ for K/V if not self-attention)<br>d_model_test = 512<br>num_heads_test = 8<br>dropout_test = 0.1<br><br># Create dummy input tensors<br>dummy_q = torch.randn(batch_size_test, seq_len_test, d_model_test)<br>dummy_k = torch.randn(batch_size_test, seq_len_test, d_model_test)<br>dummy_v = torch.randn(batch_size_test, seq_len_test, d_model_test)<br><br># Create a dummy mask (e.g., padding mask for key/value sequence)<br># Mask shape (batch_size, 1, 1, seq_len_k) -&gt; True where padded<br>dummy_mask_mha = torch.zeros(batch_size_test, 1, 1, seq_len_test, dtype=torch.bool)<br># Let&#39;s mask the last 2 positions for the first batch item, last 1 for the second<br>if batch_size_test &gt;= 1:<br>    dummy_mask_mha[0, :, :, -2:] = True<br>if batch_size_test &gt;= 2:<br>    dummy_mask_mha[1, :, :, -1:] = True<br># Add more mask examples if batch_size_test &gt; 2...<br><br>print(f&quot;Dummy Q/K/V shape: {dummy_q.shape}&quot;) # Expected: [4, 10, 512]<br>print(f&quot;Dummy Mask shape: {dummy_mask_mha.shape}&quot;) # Expected: [4, 1, 1, 10]<br><br># Instantiate the module<br>mha_layer = MultiHeadAttention(d_model_test, num_heads_test, dropout_test)<br><br># Perform forward pass<br>output_mha = mha_layer(dummy_q, dummy_k, dummy_v, mask=dummy_mask_mha)<br><br># Check output shape<br>print(f&quot;Output shape after MultiHeadAttention: {output_mha.shape}&quot;) # Expected: [4, 10, 512]<br>assert output_mha.shape == (batch_size_test, seq_len_test, d_model_test)<br><br># Check stored attention weights shape (optional)<br># Stored weights are from the scaled_dot_product_attention call<br># Shape: (batch_size, num_heads, seq_len_q, seq_len_k)<br>print(f&quot;Stored Attention Weights shape: {mha_layer.attention_weights.shape}&quot;) # Expected: [4, 8, 10, 10]<br>assert mha_layer.attention_weights.shape == (batch_size_test, num_heads_test, seq_len_test, seq_len_test)<br><br>print(&quot;MultiHeadAttention test passed.&quot;)</pre><p><strong>Explanation:</strong></p><ul><li>We instantiate MultiHeadAttention with our chosen parameters.</li><li>We create dummy Q, K, V tensors with the expected input shape (batch_size, seq_len, d_model).</li><li>We create an example padding mask (shape batch_size, 1, 1, seq_len_k) where True indicates positions to be masked in the Key sequence.</li><li>We pass these through the mha_layer.</li><li>We assert that the final output shape is (batch_size, seq_len, d_model), confirming that the heads were correctly combined and projected back to the original model dimension.</li><li>We also check the shape of the stored attention_weights, which come from the underlying scaled dot-product attention call.</li></ul><h3>What’s Next?</h3><p>We have now successfully implemented Multi-Head Attention, building directly upon the Scaled Dot-Product Attention from Part 2. This is a major component of both the Encoder and Decoder blocks.</p><p>However, attention isn’t the only ingredient. In <a href="https://medium.com/p/743763f929c8"><strong>Part 4: Residual Connections, Layer Normalization &amp; Feed-Forward Networks</strong></a>, we will implement the crucial supporting players within a Transformer block: the Add &amp; Norm steps (residual connections + layer normalization) and the Position-wise Feed-Forward Network. These components help stabilize training and add further processing capacity to the model.</p><p>See you in the next part!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1a3a061ba89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers From Scratch: Part 2 — Scaled Dot-Product Attention]]></title>
            <link>https://medium.com/@kavierim/transformers-from-scratch-part-2-scaled-dot-product-attention-6c0634ce79af?source=rss-365d6b1a19de------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c0634ce79af</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[self-attention]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[transformer-core]]></category>
            <dc:creator><![CDATA[Kari Vierimaa]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 19:33:58 GMT</pubDate>
            <atom:updated>2025-04-13T11:13:28.392Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers From Scratch: Part 2 — Scaled Dot-Product Attention</h3><p>Builds the core Scaled Dot-Product Attention mechanism, including masking and scaling.</p><p><strong>About This Series: Transformers From Scratch</strong></p><p>This post is part of a series dedicated to building the Transformer architecture from the ground up using Python and PyTorch. We dive deep into each component (Attention, Embeddings, Encoders, Decoders) to gain a fundamental understanding, moving beyond using pre-built libraries. Follow along to implement and train your own Transformer!</p><p><strong>Series Index:</strong></p><ul><li><a href="https://medium.com/p/f62a2a16a2a2"><strong>Part 0:</strong> Introduction &amp; Foundations</a></li><li><a href="https://medium.com/p/bbce1f39040d"><strong>Part 1:</strong> Input Embeddings &amp; Positional Encoding</a></li><li><a href="https://medium.com/p/6c0634ce79af"><strong>Part 2:</strong> Scaled Dot-Product Attention</a></li><li><a href="https://medium.com/p/d1a3a061ba89"><strong>Part 3:</strong> Multi-Head Attention</a></li><li><a href="https://medium.com/p/743763f929c8"><strong>Part 4:</strong> Add &amp; Norm, Feed-Forward</a></li><li><a href="https://medium.com/@kavierim/ef5a3ab87bd3"><strong>Part 5:</strong> The Encoder</a></li><li><a href="https://medium.com/p/989a17347224"><strong>Part 6:</strong> The Decoder</a></li><li><a href="https://medium.com/p/eb96ef31f78f"><strong>Part 7:</strong> Assembling the Full Model</a></li><li><a href="https://medium.com/p/36571a8fd0ff"><strong>Part 8:</strong> Data &amp; Training</a></li><li><a href="https://medium.com/p/9436681abb2e"><strong>Part 9:</strong> Inference &amp; Greedy Generation</a></li><li><a href="https://medium.com/p/65010b043996"><strong>Part 10:</strong> Beyond Greedy Search &amp; Next Steps <em>(Optional)</em></a></li></ul><h3>Transformers From Scratch: Part 2 — Scaled Dot-Product Attention</h3><p>Welcome back to the “Transformers From Scratch” series! In <a href="https://medium.com/p/bbce1f39040d">Part 1: Input Embeddings &amp; Positional Encoding</a>, we prepared our input by converting token IDs into vectors containing both semantic and positional information. Now, we dive into the absolute heart of the Transformer: the <strong>Attention Mechanism</strong>.</p><p>Specifically, we will implement the <strong>Scaled Dot-Product Attention</strong>, the core calculation defined in the <a href="https://arxiv.org/abs/1706.03762">“Attention Is All You Need”</a> paper (Section 3.2.1). This mechanism allows the model to weigh the relevance of different parts of the input sequence when processing a specific element.</p><p>In this post, we will:</p><ol><li>Understand the intuition behind the Query, Key, and Value (Q, K, V) vectors used in attention.</li><li>Break down the Scaled Dot-Product Attention formula step-by-step.</li><li>Implement this attention mechanism as a reusable Python function using PyTorch.</li><li>Test our implementation with dummy data.</li></ol><h3>The Attention Mechanism: Query, Key, Value (Q, K, V)</h3><p>Think of attention like searching for information in a database or library.</p><ul><li><strong>Query (Q):</strong> Represents what information you are currently looking for. For a specific word you’re processing, the Query vector asks, “What other words are relevant to understanding <em>this</em> word?”</li><li><strong>Key (K):</strong> Represents the “label” or identifier for the information available. Each word in the sequence has a Key vector essentially saying, “Here’s the kind of information I hold.”</li><li><strong>Value (V):</strong> Represents the actual information content. Each word also has a Value vector, which is the information to be retrieved if that word is deemed relevant.</li></ul><p>The attention mechanism works by:</p><ol><li>Comparing the <strong>Query</strong> vector of the current word with the <strong>Key</strong> vectors of all words in the sequence (including itself).</li><li>Calculating a <strong>score</strong> based on the similarity between the Query and each Key (higher score means higher relevance).</li><li>Converting these scores into <strong>weights</strong> (probabilities that sum to 1).</li><li>Using these weights to compute a <strong>weighted sum of all the Value vectors</strong>.</li></ol><p>The result is an output vector for the current word that incorporates information from other relevant words in the sequence, weighted by their relevance (attention score). Later, we’ll see how Q, K, and V are derived from the input embeddings using linear transformations.</p><h3>Scaled Dot-Product Attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*2MjJ9DePe4eImYqS12ctjg.png" /><figcaption>Scaled Dot-Product Attention. Source <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></figcaption></figure><p>The specific type of attention used in the original Transformer is called Scaled Dot-Product Attention. Its formula is:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FqmPXcxNYAb8cKLvxYEVFAj&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FqmPXcxNYAb8cKLvxYEVFAj" width="460" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/111ccf8089ecdf9e2dfc19492ce4217f/href">https://medium.com/media/111ccf8089ecdf9e2dfc19492ce4217f/href</a></iframe><p>Let’s break this down:</p><p>Attention(Q, K, V) = softmax( (Q @ K^T) / sqrt(d_k) ) @ V</p><ol><li>Q @ K^T (Matrix Multiply Q and K Transposed):<br>- This calculates the dot product between every query vector in Q and every key vector in K.<br>- If Q has shape [..., seq_len_q, d_k] and K has shape [..., seq_len_k, d_k], then K^T has shape [..., d_k, seq_len_k].<br>- The result (Q @ K^T) has shape [..., seq_len_q, seq_len_k]. This matrix contains the raw <strong>attention scores</strong> or compatibility scores between each query and each key. score[i, j] represents the relevance of key j to query i.</li><li>/ sqrt(d_k) (Scaling):<br>- The scores are scaled down by dividing by the square root of the dimension of the key vectors (d_k).<br>- <strong>Why?</strong> As explained in the paper (footnote in Section 3.2.1), for large values of d_k, the dot products can grow very large in magnitude. Large inputs to the softmax function can result in extremely small gradients, making training difficult. Scaling helps keep the dot product magnitudes under control.</li><li>Masking (Optional):<br>- Before applying softmax, we often need to apply a <strong>mask</strong>. Masking involves setting certain attention scores to a very large negative number (like -infinity). When softmax is applied, these positions will have a weight of effectively zero.<br>- <strong>Why mask?<br> — Padding Mask:</strong> To ignore padding tokens added to sequences to make them the same length within a batch. We don’t want the model attending to meaningless padding.<br> — <strong>Look-Ahead Mask (for Decoders):</strong> To prevent a position from attending to subsequent positions in the sequence. This is crucial during training the decoder to ensure it only uses information from previous tokens to predict the next one (preserving the auto-regressive property).<br>- We’ll implement masking by adding -1e9 (a very large negative number) to the scores at masked positions.</li><li>softmax(...):<br>- The softmax function is applied along the key dimension (seq_len_k). This converts the scaled scores into probability distributions, where all weights for a given query sum to 1.<br>- The output, often called <strong>attention weights</strong>, has the same shape as the scores: [..., seq_len_q, seq_len_k]. weights[i, j] is the attention weight query i gives to key j.</li><li>@ V (Matrix Multiply with V):<br>- The attention weights are multiplied by the Value matrix V (shape [..., seq_len_v, d_v], where usually seq_len_k == seq_len_v).<br>- The output shape is [..., seq_len_q, d_v]. Each output vector output[i] is a weighted sum of all value vectors in V, where the weights are determined by the attention scores calculated using query i.</li></ol><h3>Implementation</h3><p>Let’s implement this logic in a Python function using PyTorch.</p><pre>import torch<br>import torch.nn as nn<br>import math<br><br>def scaled_dot_product_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = None, dropout: nn.Dropout = None):<br>    &quot;&quot;&quot;<br>    Computes the Scaled Dot-Product Attention.<br><br>    Args:<br>        query (torch.Tensor): Query tensor, shape (batch_size, num_heads, seq_len_q, d_k)<br>        key (torch.Tensor): Key tensor, shape (batch_size, num_heads, seq_len_k, d_k)<br>        value (torch.Tensor): Value tensor, shape (batch_size, num_heads, seq_len_v, d_v)<br>                                Note: seq_len_k and seq_len_v are typically the same.<br>        mask (torch.Tensor, optional): Mask tensor, shape broadcastable to<br>                                       (batch_size, num_heads, seq_len_q, seq_len_k).<br>                                       Positions with True or 1 will be masked (set to -inf). Defaults to None.<br>        dropout (nn.Dropout, optional): Dropout layer to apply to attention weights. Defaults to None.<br><br>    Returns:<br>        torch.Tensor: The output tensor after attention, shape (batch_size, num_heads, seq_len_q, d_v)<br>        torch.Tensor: The attention weights, shape (batch_size, num_heads, seq_len_q, seq_len_k)<br>    &quot;&quot;&quot;<br>    d_k = query.shape[-1]  # Dimension of keys/queries<br><br>    # 1. Calculate Attention Scores: (Q @ K^T)<br>    # Transpose key tensor for matrix multiplication: (..., seq_len_k, d_k) -&gt; (..., d_k, seq_len_k)<br>    # Result shape: (batch_size, num_heads, seq_len_q, seq_len_k)<br>    attention_scores = torch.matmul(query, key.transpose(-2, -1))<br><br>    # 2. Scale the scores<br>    attention_scores = attention_scores / math.sqrt(d_k)<br><br>    # 3. Apply Mask (if provided)<br>    if mask is not None:<br>        # Apply the mask by filling positions with a large negative value (-1e9).<br>        # This ensures that these positions get near-zero probability after softmax.<br>        # The mask should have True/1 where positions should be masked.<br>        attention_scores = attention_scores.masked_fill(mask == True, -1e9) # Or mask == 1<br><br>    # 4. Apply Softmax to get Attention Weights<br>    # Softmax is applied on the last dimension (seq_len_k) to get probabilities over keys.<br>    # Shape: (batch_size, num_heads, seq_len_q, seq_len_k)<br>    attention_weights = torch.softmax(attention_scores, dim=-1)<br><br>    # 5. Apply Dropout (optional)<br>    if dropout is not None:<br>        attention_weights = dropout(attention_weights)<br><br>    # 6. Multiply weights by Values: (Weights @ V)<br>    # Shape: (batch_size, num_heads, seq_len_q, d_v)<br>    output = torch.matmul(attention_weights, value)<br><br>    return output, attention_weights</pre><p><strong>Code Explanation:</strong></p><ul><li>The function takes query, key, value, an optional mask, and an optional dropout layer as input.</li><li>It calculates d_k from the query&#39;s last dimension.</li><li>torch.matmul(query, key.transpose(-2, -1)) computes Q @ K^T. We transpose the last two dimensions of the key tensor.</li><li>Scores are scaled by math.sqrt(d_k).</li><li>If a mask is provided, masked_fill replaces the scores with -1e9 where the mask is True (or 1).</li><li>torch.softmax(..., dim=-1) calculates the attention weights along the key dimension.</li><li>Optional dropout is applied to the weights.</li><li>torch.matmul(attention_weights, value) computes the final weighted sum.</li><li>The function returns both the final attention output and the attention weights (useful for visualization/analysis).</li></ul><h3>Testing the Attention Function</h3><p>Let’s create some dummy tensors and a mask to see our function in action.</p><pre>import torch<br><br># Import the scaled_dot_product_attention function from part2a<br>from part2a import scaled_dot_product_attention<br><br># --- Unit Testing / Verification ---<br>print(&quot;\n--- Testing Scaled Dot-Product Attention ---&quot;)<br><br># Parameters (Example)<br>batch_size_test = 2<br>num_heads_test = 8 # Number of attention heads (will be relevant in Part 3)<br>seq_len_q_test = 5 # Sequence length for queries<br>seq_len_k_test = 7 # Sequence length for keys/values<br>d_k_test = 64 // num_heads_test # Dimension of keys/queries per head<br>d_v_test = 64 // num_heads_test # Dimension of values per head<br>d_model_test = 64 # Total model dimension (d_k * num_heads)<br><br># Dummy tensors<br># Note the shape: (batch_size, num_heads, seq_len, dim_per_head)<br>dummy_q = torch.randn(batch_size_test, num_heads_test, seq_len_q_test, d_k_test)<br>dummy_k = torch.randn(batch_size_test, num_heads_test, seq_len_k_test, d_k_test)<br>dummy_v = torch.randn(batch_size_test, num_heads_test, seq_len_k_test, d_v_test) # seq_len_k == seq_len_v<br><br>print(f&quot;Dummy Q shape: {dummy_q.shape}&quot;)<br>print(f&quot;Dummy K shape: {dummy_k.shape}&quot;)<br>print(f&quot;Dummy V shape: {dummy_v.shape}&quot;)<br><br># --- Test without mask ---<br>print(&quot;\nTesting without mask:&quot;)<br>output_no_mask, weights_no_mask = scaled_dot_product_attention(dummy_q, dummy_k, dummy_v)<br>print(f&quot;Output shape (no mask): {output_no_mask.shape}&quot;)       # Expected: [2, 8, 5, 8] (batch, heads, seq_q, dv)<br>print(f&quot;Weights shape (no mask): {weights_no_mask.shape}&quot;)     # Expected: [2, 8, 5, 7] (batch, heads, seq_q, seq_k)<br>assert output_no_mask.shape == (batch_size_test, num_heads_test, seq_len_q_test, d_v_test)<br>assert weights_no_mask.shape == (batch_size_test, num_heads_test, seq_len_q_test, seq_len_k_test)<br># Check if weights sum to 1 (approximately due to float precision)<br>assert torch.allclose(weights_no_mask.sum(dim=-1), torch.ones_like(weights_no_mask.sum(dim=-1))), &quot;Weights don&#39;t sum to 1&quot;<br>print(&quot;Test without mask passed.&quot;)<br><br># --- Test with a simple look-ahead mask (for decoder self-attention) ---<br># Create a mask for the query sequence length (seq_len_q_test = 5)<br># Mask should be (seq_len_q, seq_len_k). Here seq_q=seq_k=5 for self-attention mask<br>mask_size = seq_len_q_test<br># Create an upper triangular matrix (True above the diagonal)<br>look_ahead_mask = torch.triu(torch.ones(mask_size, mask_size), diagonal=1).bool()<br># Expand mask to match attention score shape (batch_size, num_heads, seq_len_q, seq_len_k)<br># We can use broadcasting: Unsqueeze for batch and head dimensions.<br># Mask shape needs to be compatible: (1, 1, seq_len_q, seq_len_k) or similar<br>dummy_mask = look_ahead_mask.unsqueeze(0).unsqueeze(0) # Shape: [1, 1, 5, 5]<br><br># Adjust dummy K/V seq len to match Q seq len for self-attention mask test<br>dummy_k_masked = torch.randn(batch_size_test, num_heads_test, seq_len_q_test, d_k_test)<br>dummy_v_masked = torch.randn(batch_size_test, num_heads_test, seq_len_q_test, d_v_test)<br><br>print(&quot;\nTesting with look-ahead mask:&quot;)<br>print(f&quot;Look-ahead mask shape: {dummy_mask.shape}&quot;)<br>print(&quot;Mask (True means masked):&quot;)<br>print(look_ahead_mask) # Show the basic mask structure<br><br>output_masked, weights_masked = scaled_dot_product_attention(dummy_q, dummy_k_masked, dummy_v_masked, mask=dummy_mask)<br>print(f&quot;Output shape (masked): {output_masked.shape}&quot;)   # Expected: [2, 8, 5, 8]<br>print(f&quot;Weights shape (masked): {weights_masked.shape}&quot;) # Expected: [2, 8, 5, 5]<br>assert output_masked.shape == (batch_size_test, num_heads_test, seq_len_q_test, d_v_test)<br>assert weights_masked.shape == (batch_size_test, num_heads_test, seq_len_q_test, seq_len_q_test) # seq_k adjusted<br># Check if masked weights are zero<br>masked_positions_weights = weights_masked.masked_select(dummy_mask)<br>assert torch.all(masked_positions_weights == 0), &quot;Masked positions have non-zero weights!&quot;<br># Check if non-masked weights sum to 1<br># Note: Need to be careful here, sum across seq_k dim<br>assert torch.allclose(weights_masked.sum(dim=-1), torch.ones_like(weights_masked.sum(dim=-1))), &quot;Weights don&#39;t sum to 1&quot;<br><br>print(&quot;Test with mask passed.&quot;)</pre><p><strong>Explanation:</strong></p><ul><li>We define some example dimensions. Note that the shapes include a num_heads dimension, anticipating the next part of the series.</li><li>We create random tensors for Q, K, V.</li><li>We first test the function without any mask, checking the output shapes and ensuring the attention weights sum to 1 along the key dimension.</li><li>We then create a simple upper-triangular look_ahead_mask (typical for decoder self-attention) where future positions are masked (True).</li><li>We unsqueeze the mask to make its shape broadcastable to the attention scores’ shape (batch_size, num_heads, seq_len_q, seq_len_k).</li><li>We call the attention function <em>with</em> the mask and verify that the output shapes are correct and that the weights in the masked positions are indeed zero (or extremely close due to floating-point precision, but masked_fill with -1e9 should make them effectively zero after softmax).</li></ul><h3>What’s Next?</h3><p>We have now implemented the core computation engine of the Transformer’s attention! This Scaled Dot-Product Attention function calculates how much each element should attend to every other element.</p><p>However, the paper found it beneficial to run this attention mechanism multiple times in parallel with different learned projections of Q, K, and V. This is called <a href="https://medium.com/p/d1a3a061ba89"><strong>Multi-Head Attention</strong>. In <strong>Part 3: Multi-Head Attention</strong></a>, we will build the module that incorporates multiple scaled dot-product “heads”, allowing the model to jointly attend to information from different representation subspaces.</p><p>Stay tuned as we assemble the next crucial piece!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c0634ce79af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>