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):

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:

Let’s trace the exact values moving through the array cycle by cycle:

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:

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:

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!

✎ 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):

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]):

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.