GPU Rendering Pipeline, RAW Hazards, and Throughput Workloads

Easy · Software Engineering Fundamentals · Software Engineer · HR Screen

Prompt

Walk through the following three topics in modern GPU architecture, grounding your explanation in hardware pipelines, memory hierarchy and bandwidth, warp/wavefront scheduling, and aggregate throughput:

  1. Triangle-to-Pixel Rendering Pipeline: Trace how a GPU transforms 3D triangle vertices into final shaded pixels in the framebuffer, distinguishing programmable shader stages from dedicated fixed-function hardware units.
  2. Register Read-After-Write (RAW) Hazards: Explain how true register data dependencies arise in pipelined execution and contrast how classic CPU pipelines vs. SIMT GPU execution engines resolve or hide them.
  3. High-Throughput GPU Workloads: Characterize the computation and memory-access patterns where GPUs dramatically outperform CPUs — as well as the patterns where GPUs struggle — and explain the underlying hardware reasons.

Scope & Expectations

  • End-to-end rendering and framebuffer memory behavior: Cover vertex fetch/shading, clipping, perspective division, viewport mapping, quad-based rasterization with barycentric interpolation, Early-Z culling, fragment shading, and blending, plus immediate-mode vs. tile-based bandwidth trade-offs.
  • CPU vs. GPU hazard management: Contrast CPU interlocks, forwarding/bypassing, and out-of-order renaming against GPU per-warp scoreboarding, in-order issue, zero-overhead warp switching, and occupancy limits (Little's law).
  • Throughput vs. bottleneck analysis: Connect SIMT execution, control-flow coherence (warp divergence), memory coalescing, and arithmetic intensity (the Roofline model) to concrete examples of GPU-friendly and GPU-unfriendly workloads.

Step-by-step walkthrough

  1. Frame the big idea: CPUs optimize latency, GPUs optimize throughput

    All three parts of this prompt trace back to one fundamental hardware trade-off:

    • A CPU core is engineered to minimize latency (the time required to finish one sequential task): most of its silicon area goes toward large multi-level caches, branch predictors, and out-of-order execution machinery so a single thread rarely stalls.
    • A GPU is engineered to maximize throughput (the total volume of work finished per second): most of its silicon area goes toward thousands of parallel arithmetic lanes plus specialized fixed-function graphics blocks, accepting slower single-thread speed in exchange for massive aggregate bandwidth and compute.

    Three architectural mechanisms drive that throughput model:

    1. SIMT (Single Instruction, Multiple Threads): Threads execute in fixed-width lockstep groups called warps (or wavefronts — typically 16, 32, or 64 threads depending on the vendor). One instruction fetch/decode unit drives every lane in the warp simultaneously.
    2. Latency hiding via zero-overhead warp switching: Rather than trying to make a 400-cycle DRAM read fast, each GPU core keeps dozens of warps resident inside a large on-chip register file at once. Whenever Warp 0 waits on memory or a multi-cycle math unit, the hardware scheduler issues an instruction from another ready warp on the very next clock cycle without saving or restoring registers.
    3. Fixed-function silicon units: Stages with fixed mathematical definitions — vertex attribute fetch, triangle rasterization, compressed texture filtering, depth testing, and color blending — run in dedicated hardware circuits that deliver far higher speed per watt than general-purpose shader code.
  2. Topic 1A: From 3D triangle vertices to framebuffer pixels

    Here is the end-to-end path of a triangle through a modern GPU rendering pipeline ([Fixed] = dedicated hardware block, [Prog] = programmable shader running on SIMT cores):

    Vertex/Index Buffers (DRAM)
       |
       v
    [Fixed] 1. Input Assembly / Vertex Fetch   (reads positions, normals, UVs; reuses cached vertices)
       |
       v
    [Prog]  2. Vertex Shader                   (transforms each vertex into 4D clip space: x, y, z, w)
       |       (optional Tessellation / Geometry / Mesh stages)
       v
    [Fixed] 3. Primitive Assembly, Clip & Cull (groups 3 vertices -> triangle; clips to view frustum;
       |                                        drops back-facing triangles)
       v
    [Fixed] 4. Perspective Divide & Viewport   ((x/w, y/w, z/w) -> NDC -> screen pixel coordinates)
       |
       v
    [Fixed] 5. Rasterizer                      (finds covered pixels in 2x2 quads; interpolates attrs)
       |
       v
    [Fixed] 6. Early Depth / Stencil (Early-Z) (discards hidden fragments BEFORE running pixel shader)
       |
       v
    [Prog]  7. Fragment (Pixel) Shader         (computes color, sampling mipmapped textures via TMUs)
       |
       v
    [Fixed] 8. Output Merger / ROP             (late depth test, alpha blending, write to Framebuffer)
    

    Trace a concrete coordinate transformation in Stage 4: - Suppose the vertex shader outputs clip-space coordinates (x, y, z, w) = (3, -1, 2, 4). - First, frustum clipping checks -w <= x, y <= w, which (3, -1) satisfies since -4 <= 3, -1 <= 4. - Next, the perspective divide divides by w = 4 (making farther geometry with larger w converge toward the center of view), producing NDC (Normalized Device Coordinates) (0.75, -0.25, 0.5). - Finally, for a 1600 x 900 viewport (with bottom-left origin), the viewport transform maps [-1, 1] onto screen space: - pixel_x = (0.75 + 1) / 2 * 1600 = 1400 - pixel_y = (-0.25 + 1) / 2 * 900 = 337.5

    Two execution details worth highlighting: - Early-Z and front-to-back submission: When the fragment shader neither overwrites depth nor invokes discard, Stage 6 tests the depth buffer before launching Stage 7. Submitting opaque meshes roughly front-to-back lets Early-Z reject occluded background surfaces before spending any shader cycles. - 2x2 pixel quads: Hardware rasterizers dispatch fragments in 2 x 2 pixel blocks (quads) so adjacent lanes can finite-difference UV coordinates to pick the appropriate texture mipmap level (pre-filtered downsampled texture pyramid). Tiny sub-pixel triangles leave up to 3 "helper lanes" per quad doing throwaway work, hurting shading efficiency.

  3. Topic 1B: Edge-function rasterization and barycentric interpolation

    How does the rasterizer test whether pixel center p = (x + 0.5, y + 0.5) lies inside triangle (v0, v1, v2)? For each directed edge a -> b, it evaluates a linear edge function:

    E(a, b, p) = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)

    Geometrically, E(a, b, p) equals twice the signed area of (a, b, p) — positive on the interior side of a counter-clockwise triangle, zero on the boundary, and negative outside. A sample p is covered when all three edge functions are non-negative, and dividing each by E(v0, v1, v2) directly yields the barycentric weights (lambda_0, lambda_1, lambda_2) (non-negative weights summing to 1) used to interpolate vertex attributes!

    def edge_fn(ax, ay, bx, by, px, py):
        """Return twice the signed area of (a, b, p); >= 0 on the inside of edge a->b."""
        return (bx - ax) * (py - ay) - (by - ay) * (px - ax)
    
    
    def rasterize_triangle(v0, v1, v2, width, height):
        """Return (x, y, w0, w1, w2) for pixel centers covered by CCW triangle (v0, v1, v2)."""
        twice_area = edge_fn(*v0, *v1, *v2)
        fragments = []
        for y in range(height):
            for x in range(width):
                px, py = x + 0.5, y + 0.5
                e0 = edge_fn(*v1, *v2, px, py)  # opposite v0
                e1 = edge_fn(*v2, *v0, px, py)  # opposite v1
                e2 = edge_fn(*v0, *v1, px, py)  # opposite v2
                if e0 >= 0 and e1 >= 0 and e2 >= 0:
                    fragments.append((x, y, e0 / twice_area, e1 / twice_area, e2 / twice_area))
        return fragments
    
    
    covered = rasterize_triangle((1, 1), (6, 2), (2, 6), 8, 8)
    

    Tracing v0 = (1, 1), v1 = (6, 2), v2 = (2, 6) (twice_area = 24, geometric area = 12 pixels) covers 15 pixel centers:

    y=5  . . # . . . . .
    y=4  . . # # . . . .
    y=3  . # # # # . . .    At pixel (2, 3), center (2.5, 3.5):
    y=2  . # # # # # . .      e0 = 8.0, e1 = 5.0, e2 = 11.0  (sum = 24.0)
    y=1  . # # # . . . .      weights = (0.333, 0.208, 0.458)
    y=0  . . . . . . . .
         0 1 2 3 4 5 6 7  (x)
    

    Hardware rasterizers add a top-left tie-breaking fill rule so samples lying right on a shared triangle edge are shaded by only one triangle (preventing cracks or double-blending), plus perspective-correct interpolation (interpolating attr / w and 1 / w linearly in screen space before dividing) so textures stay distortion-free under perspective foreshortening.

  4. Topic 1C: Framebuffer bandwidth and immediate-mode vs tile-based GPUs

    Off-chip DRAM transfers cost orders of magnitude more energy per operation than on-chip math. Even at 1920 x 1080 and 60 FPS (2,073,600 pixels): - One clean 4-byte RGBA8 write pass is 8.3 MB per frame (0.5 GB/s at 60 FPS). - With modest 2.5x overdraw (each pixel touched 2.5 times before the nearest surface wins), reading 4-byte depth + writing 4-byte depth + writing 4-byte color (12 bytes per shaded sample) consumes 62.2 MB per frame (3.7 GB/s at 60 FPS) before texture fetches, blending, or MSAA!

    GPUs address this memory bottleneck through two main designs:

    Immediate-Mode GPU (typical on discrete desktop GPUs):
      Triangle stream ---> Shade & depth-test immediately ---> Cached/compressed DRAM framebuffer
    
    Tile-Based GPU (typical on mobile GPUs, e.g., Arm Mali):
      Pass 1 (Geometry): Shade vertices & bin triangles into 16x16 or 32x32 screen tiles
      Pass 2 (Per tile): Rasterize + depth-test + blend inside fast ON-CHIP SRAM tile buffer
                         ---> Flush ONLY final RGBA tile to DRAM (discard transient depth!)
    
    • Immediate-mode architectures rasterize and shade each triangle across the full viewport in submission order, leaning on large L2 caches and lossless delta framebuffer compression to save DRAM bandwidth.
    • Tile-based architectures partition the framebuffer into small tiles (16 x 16 or 32 x 32 pixels) that fit inside on-chip SRAM. All depth tests, overdraw, and alpha blending stay on chip; only resolved final colors write out to DRAM, and transient depth buffers marked DONT_CARE never touch DRAM at all (at the cost of writing and reading binned geometry lists between passes).
  5. Topic 2A: Read-after-write (RAW) hazards in a pipelined processor

    A read-after-write (RAW) hazard (a true data dependency) arises whenever an instruction reads a source register whose value an older in-flight instruction has not finished computing yet.

    Trace a classic 5-stage CPU pipeline (IF = Fetch, ID = Decode & Register Read, EX = Execute, MEM = Memory Access, WB = Write-Back):

    Cycle               1    2    3    4    5    6    7    8
    ----------------------------------------------------------
    1) Interlock only (no forwarding): 2 stall bubbles ("--")
    add r1, r2, r3      IF   ID   EX   MEM  WB
    sub r4, r1, r5           IF   --   --   ID   EX   MEM  WB
    
    2) With ALU forwarding (EX/MEM latch -> EX input): 0 bubbles!
    add r1, r2, r3      IF   ID   EX   MEM  WB
    sub r4, r1, r5           IF   ID   EX   MEM  WB
    
    3) Load-use hazard (data ready at end of MEM): 1 bubble even with forwarding
    lw  r1, 0(r2)       IF   ID   EX   MEM  WB
    add r3, r1, r4           IF   ID   --   EX   MEM  WB
    

    Pipelined CPUs combine five mechanisms to resolve RAW dependencies: - Hardware interlocks (stalls): Detect matching in-flight destination registers during ID and insert pipeline bubbles until the producer finishes. - Forwarding (bypassing): Route results directly from EX/MEM and MEM/WB pipeline latches back to EX inputs, eliminating back-to-back single-cycle ALU stalls while leaving a 1-cycle load-use bubble (or hundreds of cycles on a cache miss). - Compiler instruction scheduling: Fill delay slots between loads and dependent instructions with independent work. - Scoreboarding: Track pending destination registers in a hardware table so variable-latency units stall only instructions that actually read those registers. - Out-of-order execution with register renaming: Execute later independent instructions ahead of stalled instructions while mapping architectural registers onto physical registers — great for single-thread latency, but far too area- and power-hungry to replicate across thousands of GPU lanes.

  6. Topic 2B: How GPUs handle RAW hazards via scoreboards and warp switching

    Rather than building heavy out-of-order hardware per lane, GPUs keep individual warps simple and hide latency across warps:

    • In-order issue per warp + scoreboarding: Each warp issues instructions in program order. A per-warp scoreboard (or compiler-encoded wait counters in instruction metadata) flags destination registers awaiting results from multi-cycle math pipes, texture units, or DRAM loads.
    • Zero-cycle warp switching instead of core stalls: The instant Warp 0 encounters an instruction reading a busy scoreboard register, Warp 0 becomes ineligible. On the very next clock cycle, the warp scheduler picks another resident warp whose source registers are ready and issues its instruction. Because every resident warp owns a dedicated partition of the register file, switching warps incurs zero context-switch delay.

    Little's law gives the number of resident warps required to keep execution units 100% utilized: required_warps = ceil(latency_cycles / independent_instructions_per_warp).

    • 4-cycle ALU pipeline with purely dependent instructions (1 instruction per warp): 4 / 1 = 4 ready warps hide the entire ALU pipeline latency without complex multi-stage bypass muxes.
    • 360-cycle DRAM fetch where the compiler schedules 18 independent instructions per warp before consuming the loaded register: 360 / 18 = 20 active warps completely hide the 360-cycle memory wait!
    • Register pressure vs occupancy: How many warps fit simultaneously (occupancy) depends on on-chip register and shared-memory usage per thread.
    def warps_to_hide_latency(latency_cycles, independent_insts_per_warp):
        """Ceiling division from Little's law: warps needed to issue every cycle."""
        return (latency_cycles + independent_insts_per_warp - 1) // independent_insts_per_warp
    
    
    def max_resident_warps(total_registers, regs_per_thread, warp_size):
        """Maximum warps that fit in a core's register file."""
        regs_per_warp = regs_per_thread * warp_size
        return total_registers // regs_per_warp
    
    
    # Core with 65,536 32-bit registers, 32-thread warps, 360-cycle load, 18 insts/warp
    needed = warps_to_hide_latency(360, 18)        # 20 warps needed
    fit_64 = max_resident_warps(65536, 64, 32)     # 32 warps fit (>= 20 -> latency fully hidden!)
    fit_128 = max_resident_warps(65536, 128, 32)   # 16 warps fit (< 20  -> memory stalls exposed!)
    
  7. Topic 3: Ideal vs poor GPU workloads through the Roofline lens

    GPUs deliver peak performance when a workload combines four properties: 1. Abundant data parallelism: Tens of thousands to millions of independent work items (pixels, vertices, matrix tiles, tensor elements, ray samples). 2. Coherent warp control flow: All threads within a warp follow the same branch path so every SIMT lane performs useful work. 3. Coalesced memory access: Neighboring threads in a warp access contiguous addresses (such as array[tid]), letting hardware merge 32 4-byte reads into a single 128-byte cache-line transaction. 4. High arithmetic intensity: Many floating-point operations (FLOPs) executed per byte moved across DRAM, reusing loaded values in registers or on-chip shared memory.

    The Roofline model pinpoints whether a kernel is memory-bound or compute-bound:

    attainable_FLOP_per_s = min(peak_FLOP_per_s, memory_bandwidth * arithmetic_intensity)

    For a GPU rated at 24 TFLOP/s FP32 compute and 600 GB/s DRAM bandwidth, the ridge point sits at 24,000 / 600 = 40 FLOP/byte:

    Workload                        FLOPs       DRAM bytes (FP32)    FLOP/byte   Hardware bottleneck
    ------------------------------  ----------  -------------------  ----------  ------------------------------------
    Vector SAXPY: y[i] = a*x[i]+y[i]  2 / item  12 B (2 rd + 1 wr)   0.17        Memory-bound: <= 100 GFLOP/s (0.4%!)
    Tiled 4096x4096 Matrix Multiply 1.37e11     201 MB (min 3n^2*4)  ~683        Compute-bound: approaches 24 TFLOP/s
    

    Conversely, four workload patterns run poorly on GPUs: - Branch-heavy warp divergence: If half of a warp takes if (100 cycles) and half takes else (100 cycles), hardware executes both branches sequentially under active-lane masks (200 cycles at 50% lane utilization). - Pointer chasing and scattered gathers/scatters (linked lists, uncoalesced hash lookups, irregular trees): 32 lanes touching 32 separate cache lines multiply memory transactions by up to 32x. - Long serial dependency chains (sequential entropy decoding, stateful single-stream parsers): With parallelism = 1, the GPU's lower clock speed and in-order cores lag far behind a superscalar CPU. - Tiny problem sizes: Kernel launch and host-device transfer overhead (microseconds) outweighs the parallel speedup when processing only a few hundred items.

Intuition & how it works

Picture a CPU core as a nimble courier motorcycle engineered to deliver one package from A to B in minimal elapsed time (low latency), and a GPU as a fleet of 50 express trains engineered to haul tens of thousands of passengers per hour along parallel tracks (high throughput). Passengers seated in the same car move in lockstep (SIMT — Single Instruction, Multiple Threads, where a fixed group of 16–64 threads called a warp runs one instruction across parallel lanes). Whenever Train 0 waits 360 cycles for cargo from off-chip DRAM, the dispatcher never leaves the tracks empty — it advances Train 1 on the very next cycle because Train 1's state is already resident on chip!

Why do oversimplified mental models break down? Treating 3D rendering as "merely running a vertex shader then a pixel shader" overlooks the fixed-function silicon stages (frustum clipping, perspective division, 2 x 2 quad rasterization, Early-Z depth culling, hardware texture filtering, and ROP blending) that make real-time graphics power-efficient. Similarly, resolving read-after-write (RAW) hazards (where an instruction reads a register before an older instruction finishes writing it) via wide CPU-style out-of-order hardware on every GPU lane would explode chip area, whereas stalling an entire GPU core on every DRAM access would leave ALUs idle over 95% of the time.

Trace both pipelines on concrete examples:

1. Rendering 1 triangle: v0=(1,1), v1=(6,2), v2=(2,6)
   Vertex shader (runs 3 times) -> Clip & divide by w -> Viewport transform ->
   Rasterizer evaluates 3 linear edge functions -> 15 covered pixels (barycentric weights) ->
   Early-Z culls occluded pixels -> Fragment shader shades survivors -> ROP blends to tile/DRAM

2. RAW hazard:  I1: r1 = load [addr]   (360-cycle DRAM read)
                I2: r2 = r1 + 5        (needs r1!)
   - Pipelined CPU: interlocks/forwards short ALU ops; reorders later instructions in one thread.
   - GPU core: scoreboard marks Warp 0's `r1` busy -> scheduler issues Warp 1, Warp 2, ...
     on consecutive cycles -> zero wasted cycles whenever enough ready warps fit in registers!

Key points

  • End-to-end rendering pipeline: Input assembly fetches indexed vertices → vertex shader emits clip-space (x, y, z, w) → primitive assembly, frustum clipping, and back-face culling → perspective divide (x/w, y/w, z/w) to Normalized Device Coordinates and viewport mapping → rasterizer tests sample coverage via linear edge functions and computes perspective-correct barycentric weights → Early-Z discards hidden fragments prior to shading → fragment shader evaluates surface color using hardware-filtered mipmaps → ROP / output merger performs late depth/stencil tests, alpha blending, and framebuffer writes.
  • Bandwidth-aware GPU architectures: Overdraw and texture sampling easily demand multi-GB/s bandwidth at 1080p60. Desktop immediate-mode GPUs mitigate DRAM traffic with large L2 caches and lossless framebuffer compression, while mobile tile-based GPUs (such as Arm Mali) bin primitives into small screen tiles (16 x 16 or 32 x 32 pixels) so depth testing and blending stay inside fast on-chip SRAM and only resolved final colors flush to DRAM.
  • CPU vs GPU RAW dependency handling: CPU pipelines combine interlocks, forwarding (bypassing) from EX/MEM and MEM/WB latches (still leaving at least a 1-cycle load-use bubble), compiler scheduling, scoreboarding, and out-of-order register renaming. GPUs issue instructions in order per warp, track pending destination registers via a lightweight scoreboard (or compiler wait barriers), and hide long latencies via zero-cost warp switching.
  • Occupancy and Little's law: Hiding an L-cycle latency with K independent instructions per warp requires ceil(L / K) resident warps (e.g., 360 / 18 = 20 warps). Consuming too many registers or too much shared memory per thread reduces occupancy (the count of warps simultaneously resident on a core), exposing memory stalls.
  • High-throughput vs poor GPU workloads: GPUs thrive on massive data parallelism, uniform warp branches, coalesced contiguous memory accesses, and high arithmetic intensity (FLOPs / byte above the Roofline model ridge point, such as tiled matrix multiply at ~680 FLOP/byte vs vector a*x + y at 0.17 FLOP/byte). They struggle on warp divergence, pointer-chasing irregular data structures, serial dependency chains, and tiny inputs.

Common mistakes

  • Equating vertex-shader frequency with fragment-shader frequency: Vertex shaders run once per unique post-cache vertex, whereas fragment shaders run for every surviving covered sample (plus 2 x 2 quad helper lanes) — often orders of magnitude more invocations.
  • Omitting fixed-function stages between shaders: Skipping clipping, perspective division (/ w), edge-function rasterization, or Early-Z leaves out how 3D clip coordinates become perspective-correct 2D pixels and why front-to-back draw ordering saves work.
  • Claiming GPUs hide DRAM latency primarily with huge caches: Per thread, GPU cache capacity is tiny; GPUs hide latency primarily by switching across dozens of resident warps while using caches to coalesce and amplify bandwidth.
  • Claiming forwarding removes every CPU RAW stall: Forwarding eliminates back-to-back single-cycle ALU stalls, but a memory load produces data at the end of MEM, forcing at least a 1-cycle stall for an immediately dependent instruction (and far more on a cache miss).
  • Treating 100% occupancy as unconditionally optimal: Allocating more registers per thread to hold a larger tile on chip can slash DRAM traffic enough to run faster even at 50% occupancy, provided enough warps remain to cover latency.
  • Trying to speed up memory-bound kernels with faster math: Elementwise y = a*x + y (0.17 FLOP/byte) saturates DRAM bandwidth below 1% of peak compute; only fusing kernels so intermediate results stay in registers raises arithmetic intensity.

Follow-up questions

  • Why do fragment shaders that overwrite depth or invoke discard degrade Early-Z culling? By default, the fixed-function Early-Z stage compares and updates the depth buffer before executing the fragment shader, immediately allowing occluded surfaces drawn later to skip shading too. Whenever a shader writes gl_FragDepth or conditionally calls discard (for example on cutout foliage or fences), the GPU does not know the final visibility or depth until the shader finishes, forcing Late-Z updates and stalling early depth rejection for overlapping geometry behind it.
  • What causes warp divergence in SIMT execution, and how can shader or kernel authors mitigate it? Warp divergence occurs when lanes inside the same warp take different paths at a conditional branch: because all lanes share one program counter, the hardware executes the then path with else lanes masked inactive and then executes the else path with then lanes masked inactive, paying the sum of both branch latencies. Authors reduce divergence by sorting or binning work items (rays, tiles, particles) by material/branch outcome, replacing short conditionals with branchless select/min/max expressions, or compacting rare slow-path items into a separate pass.
  • Which render-pass mistakes defeat the DRAM bandwidth advantages of a tile-based mobile GPU? Tile-based GPUs save power and bandwidth when each tile starts fresh in on-chip SRAM, completes all draws and blending on chip, and discards temporary attachments at pass end. Those savings evaporate if an application specifies LOAD instead of CLEAR at pass start (dragging old DRAM contents back into SRAM), uses STORE instead of DONT_CARE on transient depth/stencil buffers, or switches back and forth between framebuffers mid-frame (forcing every tile across the screen to flush to DRAM and reload repeatedly).

Follow-up questions

Similar questions

More Arm interview questions

All 4 Arm questions →