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: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:
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 eachPEcomputes one multiply-accumulate (output = input_B * stationary_A + partial_sum_in). - Interconnection is strictly nearest-neighbor between adjacent
PEs (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
Bufferfeeds rows of B skewed by 1 cycle per row:- Row 0 receives
j, thenk, thenlstarting at Cycle 0. - Row 1 receives
m, thenn, thenodelayed by 1 cycle (starting at Cycle 1). - Row 2 receives
p, thenq, thenrdelayed by 2 cycles (starting at Cycle 2). Top inputs into Row 0 are0(initial partial sums).
- Row 0 receives
Let’s trace the exact values moving through the array cycle by cycle:
- Cycle 0:
jentersPE(0,0)(holdinga) with partial sum0\toPE(0,0)outputsa*jdownward towardPE(1,0), and forwardsjrightward. - Cycle 1:
PE(0,0)receivesk\to sendsa*kdownward.PE(0,1)(holdingd) receivesjfrom the left \to sendsd*jdownward.PE(1,0)(holdingb) receivesmfrom the Buffer anda*jfrom above \to sendsa*j + b*mdownward!
- Cycle 2:
PE(2,0)(holdingc) receivespfrom the Buffer anda*j + b*mfrom above \to outputsP = a*j + b*m + c*p!- Simultaneously,
PE(1,0)outputsa*k + b*n;PE(1,1)outputsd*j + e*m;PE(0,0)outputsa*l,PE(0,1)outputsd*k, andPE(0,2)outputsg*j.
- Cycle 3:
PE(2,0)outputsQ = a*k + b*n + c*q!PE(2,1)outputsS = d*j + e*m + f*p!
- Cycle 4:
PE(2,0)outputsR = a*l + b*o + c*r!PE(2,1)outputsT = d*k + e*n + f*q!PE(2,2)outputsV = g*j + h*m + i*p!
- Cycle 5:
PE(2,1)outputsU = d*l + e*o + f*r!PE(2,2)outputsW = g*k + h*n + i*q!
- Cycle 6:
PE(2,2)outputs the final elementX = 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
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 atPE(r, j)on the exact same cycle as the accumulated partial sum fromPE(r-1, j).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:
- Four Compute Engines:
- Tensor Engine (128 \times 128 systolic array): Specialized for matrix multiplication. It is unidirectional—it reads inputs from
SBUFand writes outputs strictly toPSUM. - Vector Engine (128-wide): Specialized for element-wise operations and vector reductions (can read/write both
SBUFandPSUM). - Scalar Engine (128-wide): Specialized for predefined non-linear functions (such as
ReLU) on single elements (can read/write bothSBUFandPSUM). - GPSIMD Engine (128-wide): General-purpose programmable SIMD processors (reads/writes
SBUF).
- Tensor Engine (128 \times 128 systolic array): Specialized for matrix multiplication. It is unidirectional—it reads inputs from
- Two Software-Managed On-Chip SRAMs:
SBUF(State Buffer,24 MB): A 2D memory organized asPartition (P)(128parallel lanes) \timesFree (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 of512.
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} BecauseSBUFdelivers 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 insideSBUFandPSUM!
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
PSUMbank depth of 512).
When tensors fit within these limits, a basic NKI MatMul kernel follows 8 explicit software-managed steps:
- Allocate input tensors in
SBUF:lhsT_SBUF = nl.ndarray(lhsT.shape, ..., buffer=nl.sbuf)andrhs_SBUF = ... - Copy inputs from
HBMtoSBUFvia DMA:nisa.dma_copy(dst=lhsT_SBUF, src=lhsT)andnisa.dma_copy(dst=rhs_SBUF, src=rhs). - Allocate output tensor in
PSUM:output_PSUM = nl.ndarray(..., dtype=nl.float32, buffer=nl.psum). - Perform MatMul on the Tensor Engine:
output_PSUM = nisa.nc_matmul(lhsT_SBUF, rhs_SBUF). - Allocate output tensor in
SBUF:output_SBUF = nl.ndarray(..., buffer=nl.sbuf). - Copy result from
PSUMintoSBUF:nisa.tensor_copy(dst=output_SBUF, src=output_PSUM). - Allocate output tensor in
HBM:output = nl.ndarray((M, N), ..., buffer=nl.shared_hbm). - Copy final output from
SBUFtoHBMvia 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
SBUFCapacity: To minimize HBM transfers, keep large SBUF tiles (M_tile,N_tile,K_tile) of both input tensors and the corresponding output tile simultaneously insideSBUF(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 eachSBUFtile, the Tensor Engine steps through 128 \times 128 and 128 \times 512 hardware sub-tiles using the fast10 TB/sSBUF, so each input block is loaded from slow HBM only a few times!
- M_{\text{tile}} \cdot K_{\text{tile}} is the size of the stationary input tile held in
✎ Check Your Understanding
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
PSUMbank depth of 512 constrains N \le 512.Why must the
SBUFcapacity tiling constraint include the output tile term (M_{\text{tile}} \cdot N_{\text{tile}}) in addition to the two input tiles? Answer: BecausePSUMis tiny (2 MB) and results must be copied intoSBUF(output_SBUF) before moving to HBM; reserving space for the output tile alongside both input tiles preventsSBUFoverflow/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:
- 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} - 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} - 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} - 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:
- Input Channels (
IC): A color RGB image stores a tuple(r, g, b)per pixel, adding anIC = 3(or generally IC feature channels) dimension! Each filter also gains theICdimension—we multiply the 3D[IC, FH, FW]filter against the[IC, FH, FW]input patch and sum across allICchannels. - Output Channels (
OC): To detect multiple features at once (edges, textures, ears, eyes), we applyOCdistinct 3D filters—never summing across different filters! Both W and O (and the bias B) gain theOCdimension. - Batch Size (
BS): To processBSimages simultaneously using the same filters, both input X and output O gain theBSdimension.
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:
- Find one dot product: Fix a single filter tap
(fh, fw)and a single spatial pixel(oh, ow). Multiplying theICelements at that pixel across allICchannels of one filter and summing them up is literally a vector dot product alongIC! BecauseICis a multiple of128,ICaligns directly with the Tensor Engine’s contraction dimension K! (We will simply loop overfhin0..FH-1andfwin0..FW-1outside, accumulating intoPSUM, to cover the full FH \times FW filter!) - Stack across Output Channels (
OC) \to Matrix-Vector Product: Now stack128different filters along theOCdimension. That turns our single dot product into a matrix-vector multiply[IC, OC].T @ [IC, 1]. BecauseOCis also a multiple of128, the weights[128, 128]fit cleanly as the stationary tensor! - Stack across Spatial Image Dimensions (
OW, etc.) \to Full MatMul! Instead of processing just one spatial pixel, stack adjacent output width pixels alongOW(< 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 everync_matmulresult into the samePSUMoutput 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
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}.
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 inPSUM.