# CS152 Lecture 23: Spatial Architectures Trainium ### Section 1: Domain-Specific Spatial Accelerators — Systolic Arrays for Matrix Multiplication We have traced general-purpose processors from out-of-order superscalars and VLIW to vectors, GPUs, and cache-coherent/weakly-consistent multiprocessors. Yet modern workloads—especially deep learning—are dominated by one colossal computational kernel: **Matrix Multiplication (MatMul)** and its close cousin, 2D Convolution. General-purpose CPUs and even SIMT GPUs still pay instruction fetch, decode, register-file access, and scheduling overhead on every operation. To maximize operations per watt and per $\text{mm}^2$, domain-specific accelerators turn to **Spatial Architectures**—most famously the **Systolic Array**. #### Matrix Multiplication Dataflows: Output-Stationary vs. Input-Stationary Consider multiplying an $M \times K$ matrix $A$ by a $K \times N$ matrix $B$ to produce an $M \times N$ output matrix $Z$: $$Z_{m, n} = \sum_{k=0}^{K-1} A_{m, k} \cdot B_{k, n}$$ Here $K$ is called the **contraction dimension** (the dimension summed over). Notice how changing the nesting order of the three `for` loops creates different **dataflow stationary patterns** (which tensor stays pinned in place during the innermost loop): - **Output-Stationary (`Z`-stationary) Loop Nest:** ```python for m ...: for n ...: for k ...: Z[m, n] += A[m, k] * B[k, n] ``` The element `Z[m, n]` being accumulated does not change during the inner loop over $K$. - **A-Stationary (Weight-Stationary) Loop Nest:** ```python for m ...: for k ...: for n ...: Z[m, n] += A[m, k] * B[k, n] ``` The input element `A[m, k]` stays fixed in place during the inner loop over $N$. #### Worked Walkthrough: Weight-Stationary MatMul on a $3 \times 3$ Systolic Array Let's build a **$3 \times 3$ Weight-Stationary (`A`-stationary) Systolic Array** to compute: $$Z = \begin{pmatrix} P & Q & R \\ S & T & U \\ V & W & X \end{pmatrix} = \begin{pmatrix} a & b & c \\ d & e & f \\ g & h & i \end{pmatrix} \times \begin{pmatrix} j & k & l \\ m & n & o \\ p & q & r \end{pmatrix}$$ For example, $P = a\cdot j + b\cdot m + c\cdot p$ and $W = g\cdot k + h\cdot n + i\cdot q$. Look at the hardware topology of the systolic array: - It is a $3 \times 3$ grid of simple **Processing Elements (`PE`)**, where each `PE` computes one multiply-accumulate (`output = input_B * stationary_A + partial_sum_in`). - **Interconnection is strictly nearest-neighbor** between adjacent `PE`s (no global crossbar or broadcast buses across the whole chip!): horizontal wires pass moving matrix-$B$ elements rightward; vertical wires pass partial sums downward. - **Crucial Layout Rule:** The preloaded stationary tensor $A$ is **transposed** inside the array! - Column 0 holds $[a,\ b,\ c]^T$ (top-to-bottom). - Column 1 holds $[d,\ e,\ f]^T$. - Column 2 holds $[g,\ h,\ i]^T$. - **Input Skewing from the Buffer:** To make partial sums meet their matching $B$ operands at the exact right cycle as data flows rhythmically ("systolically") through the grid, the `Buffer` feeds rows of $B$ **skewed by 1 cycle per row**: - Row 0 receives `j`, then `k`, then `l` starting at Cycle 0. - Row 1 receives `m`, then `n`, then `o` delayed by **1 cycle** (starting at Cycle 1). - Row 2 receives `p`, then `q`, then `r` delayed by **2 cycles** (starting at Cycle 2). Top inputs into Row 0 are `0` (initial partial sums). Let's trace the exact values moving through the array cycle by cycle: - **Cycle 0:** `j` enters `PE(0,0)` (holding `a`) with partial sum `0` $\to$ `PE(0,0)` outputs **`a*j`** downward toward `PE(1,0)`, and forwards `j` rightward. - **Cycle 1:** - `PE(0,0)` receives `k` $\to$ sends `a*k` downward. - `PE(0,1)` (holding `d`) receives `j` from the left $\to$ sends **`d*j`** downward. - `PE(1,0)` (holding `b`) receives `m` from the Buffer and `a*j` from above $\to$ sends **`a*j + b*m`** downward! - **Cycle 2:** - `PE(2,0)` (holding `c`) receives `p` from the Buffer and `a*j + b*m` from above $\to$ outputs **`P = a*j + b*m + c*p`**! - Simultaneously, `PE(1,0)` outputs `a*k + b*n`; `PE(1,1)` outputs `d*j + e*m`; `PE(0,0)` outputs `a*l`, `PE(0,1)` outputs `d*k`, and `PE(0,2)` outputs `g*j`. - **Cycle 3:** - `PE(2,0)` outputs **`Q = a*k + b*n + c*q`**! - `PE(2,1)` outputs **`S = d*j + e*m + f*p`**! - **Cycle 4:** - `PE(2,0)` outputs **`R = a*l + b*o + c*r`**! - `PE(2,1)` outputs **`T = d*k + e*n + f*q`**! - `PE(2,2)` outputs **`V = g*j + h*m + i*p`**! - **Cycle 5:** - `PE(2,1)` outputs **`U = d*l + e*o + f*r`**! - `PE(2,2)` outputs **`W = g*k + h*n + i*q`**! - **Cycle 6:** - `PE(2,2)` outputs the final element **`X = g*l + h*o + i*r`**! Look at what the systolic array just achieved: every `PE` did useful work using only local wires, reusing the stationary matrix $A$ across all columns of $B$ and reusing each streamed element of $B$ across all columns of $A$ with zero instruction fetch/decode overhead! #### ✎ Check Your Understanding 1. Why must the rows of the moving matrix $B$ be **skewed** (delayed by 1 cycle per row) before entering a weight-stationary systolic array? **Answer:** Because the partial sum travels downward at 1 row per cycle; delaying Row $r$ of $B$ by $r$ cycles ensures that `B[r, c]` arrives at `PE(r, j)` on the exact same cycle as the accumulated partial sum from `PE(r-1, j)`. 2. In the $3 \times 3$ weight-stationary systolic array above, why is the preloaded stationary matrix $A$ stored **transposed** across the PE grid? **Answer:** Because all partial sums for one output row of $Z$ (e.g., $P, Q, R$ which all use weights $a, b, c$) must accumulate vertically down a single column of PEs (`PE(0,0) -> PE(1,0) -> PE(2,0)`), requiring row 0 of $A$ (`a, b, c`) to sit down column 0 of the PE array. --- ### Section 2: Accelerator Case Study — AWS Trainium, Memory Hierarchy, and Tiled MatMul Let's examine how a real-world cloud machine-learning accelerator—**AWS Trainium**—builds an entire programmable system around systolic arrays. Each Trainium chip integrates **High-Bandwidth Memories (`HBM`)**, **Communication Interfaces** (`Host PCIe`, `DMA`, `Collective Communication`, `NeuronLink-v2`), and **NeuronCore-v2** compute cores. #### Inside NeuronCore: Engines, Scratchpads, and the Bandwidth Gap Each **NeuronCore** contains **four specialized compute engines** (each with its own `SEQ` sequencer so all four can run in parallel, coordinated by compiler-inserted synchronization instructions via the `Sync Engine`) and **two software-managed on-chip SRAM scratchpads**: 1. **Four Compute Engines:** - **Tensor Engine ($128 \times 128$ systolic array):** Specialized for matrix multiplication. It is **unidirectional**—it reads inputs from `SBUF` and writes outputs strictly to `PSUM`. - **Vector Engine ($128$-wide):** Specialized for element-wise operations and vector reductions (can read/write both `SBUF` and `PSUM`). - **Scalar Engine ($128$-wide):** Specialized for predefined non-linear functions (such as `ReLU`) on single elements (can read/write both `SBUF` and `PSUM`). - **GPSIMD Engine ($128$-wide):** General-purpose programmable SIMD processors (reads/writes `SBUF`). 2. **Two Software-Managed On-Chip SRAMs:** - **`SBUF` (State Buffer, `24 MB`):** A 2D memory organized as **`Partition (P)` (`128` parallel lanes) $\times$ `Free (F)` dimension**. In Trainium's NKI programming interface, a tensor's first dimension (`tensor.shape[0]`) *always* maps along the 128-partition dimension, feeding directly into the 128 lanes/contraction inputs of the engines. - **`PSUM` (Partial Sum Buffer, `2 MB`):** Also 2D, with its 128-partition dimension aligned to the Tensor Engine outputs and a **maximum Free dimension of `512`**. Why are those on-chip scratchpads (`SBUF` and `PSUM`) the key to performance? Look at the **Bandwidth Gap in the Memory Hierarchy**: - **Host CPU Memory (DRAM, `1 TB`):** `16 GB/sec` - **Device Memory (HBM, `16 GB`):** `0.5 TB/sec` - **On-chip `SBUF` (`24 MB`) + `PSUM` (`2 MB`):** **`10 TB/sec`**! $$\frac{\text{BW}(\text{SBUF})}{\text{BW}(\text{HBM})} = \frac{10\text{ TB/sec}}{0.5\text{ TB/sec}} = \mathbf{20\times}$$ Because `SBUF` delivers **$20\times$ higher bandwidth than HBM**, an accelerator starved by HBM reads will leave the $128 \times 128$ Tensor Engine idle 95% of the time unless software **maximizes data reuse inside `SBUF` and `PSUM`**! #### Hardware Dimension Constraints and Basic MatMul Dataflow The Tensor Engine executes `dst = nisa.nc_matmul(stationary, moving)`, computing `dst = stationary.T @ moving` (remember the stationary tensor is transposed!). Its physical hardware imposes strict maximum matrix tile sizes: - **Stationary tensor:** **$M \le 128$, $K \le 128$** (constrained by the $128 \times 128$ Tensor Engine array). - **Moving tensor:** **$K \le 128$, $N \le 512$** (constrained by `PSUM` bank depth of $512$). When tensors fit within these limits, a basic NKI MatMul kernel follows **8 explicit software-managed steps**: 1. **Allocate input tensors in `SBUF`:** `lhsT_SBUF = nl.ndarray(lhsT.shape, ..., buffer=nl.sbuf)` and `rhs_SBUF = ...` 2. **Copy inputs from `HBM` to `SBUF` via DMA:** `nisa.dma_copy(dst=lhsT_SBUF, src=lhsT)` and `nisa.dma_copy(dst=rhs_SBUF, src=rhs)`. 3. **Allocate output tensor in `PSUM`:** `output_PSUM = nl.ndarray(..., dtype=nl.float32, buffer=nl.psum)`. 4. **Perform MatMul on the Tensor Engine:** `output_PSUM = nisa.nc_matmul(lhsT_SBUF, rhs_SBUF)`. 5. **Allocate output tensor in `SBUF`:** `output_SBUF = nl.ndarray(..., buffer=nl.sbuf)`. 6. **Copy result from `PSUM` into `SBUF`:** `nisa.tensor_copy(dst=output_SBUF, src=output_PSUM)`. 7. **Allocate output tensor in `HBM`:** `output = nl.ndarray((M, N), ..., buffer=nl.shared_hbm)`. 8. **Copy final output from `SBUF` to `HBM` via DMA:** `nisa.dma_copy(dst=output, src=output_SBUF)`. #### Two-Level Kernel Optimization: Tiling for Engine Size and `SBUF` Capacity What if our matrices have dimensions $M, K, N \gg 128/512$, or are too huge to fit inside the $24\text{ MB}$ `SBUF`? We must apply **Tiling**—partitioning the computation into small blocks so data can be reused on-chip! - **Strategy 1 — Tiling based on Tensor Engine dimensions:** Partition the stationary tensor into **$128 \times 128$** tiles and the moving tensor into **$128 \times 512$** tiles. To compute one $128 \times 512$ output block, we iterate along the contraction dimension $K$ across one row of stationary blocks and one column of moving blocks, accumulating their partial dot products directly in `PSUM`! - **The Trap of Naive Tiling (Low Data Reuse):** If you iterate naively over output blocks without keeping tiles resident in `SBUF`, look what happens to a single stationary block: to compute each of the 8 output blocks across row 0 of the output tensor, you end up **reloading the exact same stationary block from HBM $8\times$** (`Load 1x, Load 2x, ..., Load 8x`), blowing right through the $20\times$ HBM bandwidth bottleneck! - **Strategy 2 — Tiling based on `SBUF` Capacity:** To minimize HBM transfers, keep large **SBUF tiles** (`M_tile`, `N_tile`, `K_tile`) of both input tensors *and* the corresponding output tile simultaneously inside `SBUF` (avoiding buffer spilling), enforcing the **SBUF Capacity Constraint**: $$M_{\text{tile}} \cdot K_{\text{tile}} + N_{\text{tile}} \cdot K_{\text{tile}} + M_{\text{tile}} \cdot N_{\text{tile}} \le \text{SBUF\_size}$$ *(or $M_{\text{tile}} \cdot K + N_{\text{tile}} \cdot K + M_{\text{tile}} \cdot N_{\text{tile}} \le \text{SBUF\_size}$ when an entire $K$-strip fits!)* Let's unpack each term (measured in elements, or bytes once multiplied by element byte width): - $M_{\text{tile}} \cdot K_{\text{tile}}$ is the size of the stationary input tile held in `SBUF`. - $N_{\text{tile}} \cdot K_{\text{tile}}$ is the size of the moving input tile held in `SBUF`. - $M_{\text{tile}} \cdot N_{\text{tile}}$ is the size of the accumulated output tile held in `SBUF`. Inside each `SBUF` tile, the Tensor Engine steps through $128 \times 128$ and $128 \times 512$ hardware sub-tiles using the fast `10 TB/s` `SBUF`, so **each input block is loaded from slow HBM only a few times**! #### ✎ Check Your Understanding 1. What hardware components constrain the maximum stationary tile size ($128 \times 128$) and moving tile size ($128 \times 512$) on AWS Trainium's Tensor Engine? **Answer:** The **$128 \times 128$ systolic array** dimensions constrain $M \le 128$ and $K \le 128$, while the **`PSUM` bank depth of 512** constrains $N \le 512$. 2. Why must the `SBUF` capacity tiling constraint include the output tile term ($M_{\text{tile}} \cdot N_{\text{tile}}$) in addition to the two input tiles? **Answer:** Because `PSUM` is tiny (`2 MB`) and results must be copied into `SBUF` (`output_SBUF`) before moving to HBM; reserving space for the output tile alongside both input tiles prevents `SBUF` overflow/spilling. --- ### Section 3: Mapping 2D Deep Learning Convolution onto a Systolic Array Now let's tackle one of the most important mapping problems in deep learning hardware: **how to run 2D Convolution on a systolic array specialized strictly for Matrix Multiplication!** #### 2D Convolution Fundamentals and Worked Example In deep learning, **2D Convolution** extracts local spatial features (such as edges or textures) by sliding a learnable **Weight/Filter ($W$)** over **Input data ($X$)**, performing element-wise multiplication followed by summation, and adding a **Bias ($B$)**. Let's work a complete 2D example with $4 \times 4$ input $X$ (`IW = 4, IH = 4`), $3 \times 3$ filter $W$ (`FW = 3, FH = 3`), bias $B = 5$, and stride $= 1$: $$X = \begin{pmatrix} 1 & 0 & 2 & 4 \\ 3 & 5 & 1 & 0 \\ 7 & 6 & 2 & 9 \\ 5 & 8 & 8 & 3 \end{pmatrix}, \qquad W = \begin{pmatrix} -1 & 3 & 1 \\ 2 & 0 & 1 \\ -2 & 1 & 4 \end{pmatrix}$$ First, compute the output dimensions (`OW`, `OH`) for stride 1: $$OW = IW - FW + 1 = 4 - 3 + 1 = 2, \qquad OH = IH - FH + 1 = 4 - 3 + 1 = 2$$ Now slide the $3 \times 3$ filter over all four valid $3 \times 3$ patches of $X$: 1. **Top-left `(0, 0)`:** $$(1)(-1)+(0)(3)+(2)(1) + (3)(2)+(5)(0)+(1)(1) + (7)(-2)+(6)(1)+(2)(4) = 1 + 7 + 0 = 8 \xrightarrow{+5} \mathbf{13}$$ 2. **Top-right `(0, 1)`:** $$(0)(-1)+(2)(3)+(4)(1) + (5)(2)+(1)(0)+(0)(1) + (6)(-2)+(2)(1)+(9)(4) = 10 + 10 + 26 = 46 \xrightarrow{+5} \mathbf{51}$$ 3. **Bottom-left `(1, 0)`:** $$(3)(-1)+(5)(3)+(1)(1) + (7)(2)+(6)(0)+(2)(1) + (5)(-2)+(8)(1)+(8)(4) = 13 + 16 + 30 = 59 \xrightarrow{+5} \mathbf{64}$$ 4. **Bottom-right `(1, 1)`:** $$(5)(-1)+(1)(3)+(0)(1) + (6)(2)+(2)(0)+(9)(1) + (8)(-2)+(8)(1)+(3)(4) = -2 + 21 + 4 = 23 \xrightarrow{+5} \mathbf{28}$$ Giving the $2 \times 2$ output $O = \begin{pmatrix} 13 & 51 \\ 64 & 28 \end{pmatrix}$. #### Full Deep Learning Convolution Tensors Real neural-network convolution layers extend those 2D matrices into **4D tensors**: 1. **Input Channels (`IC`):** A color RGB image stores a tuple `(r, g, b)` per pixel, adding an `IC = 3` (or generally $IC$ feature channels) dimension! Each filter also gains the `IC` dimension—we multiply the 3D `[IC, FH, FW]` filter against the `[IC, FH, FW]` input patch and **sum across all `IC` channels**. 2. **Output Channels (`OC`):** To detect multiple features at once (edges, textures, ears, eyes), we apply `OC` distinct 3D filters—**never summing across different filters**! Both $W$ and $O$ (and the bias $B$) gain the `OC` dimension. 3. **Batch Size (`BS`):** To process `BS` images simultaneously using the same filters, both input $X$ and output $O$ gain the `BS` dimension. Summarizing the full ML convolution tensor shapes (with Trainium's preferred alignment `IC % 128 == 0` and `OC % 128 == 0`): - Input data ($X$): `[BS, IC, IH, IW]` - Weight/Filter ($W$): `[OC, IC, FH, FW]` - Bias ($B$): `[OC]` - Output data ($O$): `[BS, OC, OH, OW]` #### Transforming 2D Convolution into a Systolic-Array MatMul How do we run that 4D convolution on Trainium's Tensor Engine, which *only* executes `dst = stationary.T @ moving` for `[128, 128].T @ [128, f_dim]`? Notice what a matrix multiply actually is: **many stacked vector dot products along the contraction dimension $K = 128$!** Let's find the hidden dot products inside 2D convolution in three steps: 1. **Find one dot product:** Fix a single filter tap `(fh, fw)` and a single spatial pixel `(oh, ow)`. Multiplying the `IC` elements at that pixel across all `IC` channels of one filter and summing them up is **literally a vector dot product along `IC`**! Because `IC` is a multiple of `128`, **`IC` aligns directly with the Tensor Engine's contraction dimension $K$!** *(We will simply loop over `fh` in `0..FH-1` and `fw` in `0..FW-1` outside, accumulating into `PSUM`, to cover the full $FH \times FW$ filter!)* 2. **Stack across Output Channels (`OC`) $\to$ Matrix-Vector Product:** Now stack `128` different filters along the `OC` dimension. That turns our single dot product into a matrix-vector multiply `[IC, OC].T @ [IC, 1]`. Because `OC` is also a multiple of `128`, the weights `[128, 128]` fit cleanly as the **stationary tensor**! 3. **Stack across Spatial Image Dimensions (`OW`, etc.) $\to$ Full MatMul!** Instead of processing just one spatial pixel, stack adjacent output width pixels along `OW` (`< 512`) as the columns of the moving tensor! Now for each `(fh, fw)` tap, the Tensor Engine computes one full hardware **MatMul**: $$[IC,\ OC]^T \times [IC,\ OW] = [128,\ 128]^T \times [128,\ OW]$$ As `(fh, fw)` iterates from `(0, 0)` to `(FH-1, FW-1)`, hardware shifts the starting pointer in the input image accordingly and accumulates every `nc_matmul` result into the same `PSUM` output tile! Finally, look at how we pack the weight tensor $W$ into `SBUF` so that `IC` or `OC` aligns with `SBUF`'s `128`-lane **Partition dimension (`shape[0]`)**: ```python W_tiled = nl.ndarray( shape=(128, OC // 128, 128, IC // 128, FH, FW), dtype=W.dtype, buffer=nl.sbuf ) ``` When creating `SBUF` tensors in NKI, the **first dimension (`128`)** is always the partition dimension (feeding the 128 parallel lanes of the Tensor Engine), while the remaining dimensions live in the free dimension—allowing us to feed $128 \times 128$ weight tiles straight into the systolic array at $10\text{ TB/s}$! *[Editor Note: removed title slide, today/agenda overview slide, external documentation URL, and course lab logistics/grade breakdown slides.]* #### ✎ Check Your Understanding 1. Given an input tensor of size $IH = 32, IW = 32$, a filter of size $FH = 5, FW = 5$, and stride $= 1$, what are the output dimensions $OH$ and $OW$? **Answer:** $OH = 32 - 5 + 1 = \mathbf{28}$ and $OW = 32 - 5 + 1 = \mathbf{28}$. 2. When mapping a 2D Convolution onto Trainium's $128 \times 128$ Tensor Engine (`[128, 128].T @ [128, OW]`), which convolution dimension serves as the **contraction dimension** ($K$), and how are the filter height and width ($FH, FW$) handled? **Answer:** The **Input Channel (`IC`)** dimension serves as the contraction dimension ($K$), and the filter height and width ($FH, FW$) are handled by looping over each `(fh, fw)` tap, shifting the input window, and accumulating partial results in `PSUM`.