ELLMEngineering Large
Language Models
Download PDF

Chapter 29

Hierarchical Matrix Multiplication

On this page

GEMM performance comes from hierarchical reuse. Each fetched A and B value should participate in many multiply-accumulates before leaving on-chip storage.

With the machine model and host shell in place, the next building block is the matrix multiply that dominates both prefill and the MLP path. In the running example, a linear layer maps activations of width D = 4096 through a weight matrix. Prefill exposes many token rows at once; decode may expose only B = 8 rows. The math is the same GEMM. The efficient schedule is not.

A and B tiles are cooperatively staged; warps consume subtiles; threads or tensor-core fragments accumulate C in registers before an epilogue writes it efficiently.
Open full diagram ↗

A and B tiles are cooperatively staged; warps consume subtiles; threads or tensor-core fragments accumulate C in registers before an epilogue writes it efficiently.

From the equation to the schedule

For C[M,N] = A[M,K] B[K,N], the mathematical work is approximately 2 M N K FLOPs. The implementation chooses a loop ordering and a hierarchy of tiles:

  • grid tiles partition M and N across thread blocks;
  • a block loops over K tiles;
  • warps own subtiles within the block tile;
  • lanes own scalar accumulators or matrix fragments;
  • an epilogue maps accumulator layout to coalesced output stores.

The kernel must balance parallel output tiles against reuse along K.

A correct scalar baseline

Example status: CUDA excerpt; not compiled or benchmarked.

__global__ void gemm_naive(
    const float* A, const float* B, float* C,
    int M, int N, int K) {
  int row = blockIdx.y * blockDim.y + threadIdx.y;
  int col = blockIdx.x * blockDim.x + threadIdx.x;
  if (row >= M || col >= N) return;

  float acc = 0.0f;
  for (int k = 0; k < K; ++k) {
    acc += A[row * K + k] * B[k * N + col];
  }
  C[row * N + col] = acc;
}

This is a valuable oracle and a poor high-performance schedule. Neighboring threads reread A rows and B columns instead of explicitly sharing them.

Cooperative shared-memory tiling

Example status: CUDA excerpt; not compiled or benchmarked.

template<int TILE>
__global__ void gemm_tiled(
    const float* A, const float* B, float* C,
    int M, int N, int K) {
  __shared__ float As[TILE][TILE];
  __shared__ float Bs[TILE][TILE];

  int row = blockIdx.y * TILE + threadIdx.y;
  int col = blockIdx.x * TILE + threadIdx.x;
  float acc = 0.0f;

  for (int k0 = 0; k0 < K; k0 += TILE) {
    int ak = k0 + threadIdx.x;
    int bk = k0 + threadIdx.y;
    As[threadIdx.y][threadIdx.x] =
        (row < M && ak < K) ? A[row * K + ak] : 0.0f;
    Bs[threadIdx.y][threadIdx.x] =
        (bk < K && col < N) ? B[bk * N + col] : 0.0f;
    __syncthreads();

    #pragma unroll
    for (int k = 0; k < TILE; ++k) {
      acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
    }
    __syncthreads();
  }

  if (row < M && col < N) C[row * N + col] = acc;
}

Launch this kernel with a two-dimensional block of exactly (TILE, TILE) threads and a grid covering M and N; TILE * TILE must fit the device's block limit. Out-of-range loads become zero, all participating threads reach both barriers, and the output store is guarded. An early return before a later barrier would leave shared-tile entries uninitialized for an edge block.

Launch contract and the cost of partial tiles

The printed tiled kernel requires blockDim=(TILE,TILE,1), gridDim=(ceil(N/TILE),ceil(M/TILE),1), contiguous row-major inputs, nonoverlapping output, and storage for all M*K, K*N, and M*N elements. The teaching code uses signed int offsets: require every index product to fit that type, or widen multiplication before it occurs, for example size_t(row)*K+k. Casting an already-overflowed product is too late. Handle an empty output on the host rather than launching a zero-sized grid.

Every tile iteration initializes every shared element, including zero fill for out-of-range coordinates. The first barrier makes those writes available to readers. The second prevents a fast warp from overwriting the tile while a slower warp still consumes it. Removing either barrier changes the allowed executions; neither is redundant because the loop index is uniform.

For block tile sizes B_M,B_N,B_K, one full K-stage loads B_K*(B_M+B_N) scalars and performs 2*B_M*B_N*B_K useful FLOPs. Ignoring output traffic, intensity is 2*B_M*B_N / (s*(B_M+B_N)) for s bytes per scalar. Increasing B_K alone cancels out of this expression. It changes barrier amortization and storage, not A/B reuse per output tile.

For the square teaching kernel, nominal executed multiply-add positions are ceil(M/T)*ceil(N/T)*ceil(K/T)*T^3; useful positions are M*N*K. Their ratio quantifies tail waste before compiler effects. At (M,N,K)=(33,33,33) and T=32, useful work occupies only about 13.7 percent of those positions. A larger tile is not automatically better for small or ragged matrices.

Arithmetic intensity from tile reuse

Ignoring the final store, a square block tile of width T loads roughly 2 T^2 values per K tile and performs roughly 2 T^3 FLOPs. Let 2026-10-12T12:02:55.665757 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ be the number of bytes per stored value. The input-traffic arithmetic intensity, measured in FLOPs per byte, is:

2026-10-12T12:02:55.673303 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The numerator counts FLOPs; the denominator counts input bytes for one full square tile stage.

Larger T raises reuse, but resource consumption grows. The estimate also assumes each input tile is loaded once and does not include cache effects, epilogue traffic, or edge waste.

Running-example intensity sketch

Consider the decode projection that maps M = B = 8 rows through K = N = D = 4096 in FP16 weights.

  • FLOPs are approximately 2 * 8 * 4096 * 4096 = 2.7e8.
  • Weight traffic alone is approximately 4096 * 4096 * 2 = 34 MB if weights are read once.
  • Arithmetic intensity against weights is roughly 2.7e8 / 3.4e7 = 8 FLOP/byte before activation and output traffic.

On a device whose HBM roof is near 3 TB/s, even perfect weight streaming yields only tens of microseconds of memory time, while tensor-core peak would finish the math much faster if data were free. Decode linear layers are therefore often weight-bandwidth bound at small batch. Prefill with M = 2048 raises intensity and can move toward the compute roof for the same weights.

Register tiling and microkernels

One thread can compute an r_m x r_n output patch. It loads a small vector from A and B, then updates multiple independent accumulators. Register tiling increases reuse from shared memory and exposes instruction-level parallelism.

The cost is r_m * r_n accumulator registers plus address and staging state. Large microtiles can lower occupancy and cause spills. A good microkernel balances accumulator reuse against live-state pressure.

Tensor-core execution

Tensor cores execute matrix multiply-accumulate on architecture-defined fragments. A high-performance tensor-core kernel must:

  • use supported input, accumulator, and output types;
  • satisfy alignment and layout constraints;
  • stage data in a layout that avoids shared-memory conflicts;
  • map lanes to matrix fragments correctly;
  • pipeline copies and MMA instructions;
  • define numerical behavior for reduced precision and accumulation;
  • execute an efficient epilogue.

Mixed precision changes the error model. FP16 or BF16 inputs with FP32 accumulation usually reduce accumulation error compared with low-precision accumulation, but input rounding and operation order still differ from an FP32 reference. TF32, FP8, INT8, and block-scaled formats each require a stated quality contract.

Multi-stage pipelines and asynchronous copies

Let stage s hold the tile being consumed and stage s + 1 the tile being filled. A software pipeline repeats:

  1. issue an asynchronous copy for a future A/B tile;
  2. wait until the current stage is ready;
  3. execute MMA on the current stage;
  4. advance the circular stage index.

More stages can cover memory latency but consume more shared memory. At some point the extra stage reduces resident blocks or adds address and synchronization overhead without improving tensor-core utilization.

Modern architectures may provide bulk-copy engines and warp-specialized schedules in which producer warps move data while consumer warps issue MMA. The transferable idea is division of labor with explicit pipeline state, not one architecture-specific mnemonic.

Layouts and the epilogue

The accumulator layout that suits MMA instructions may not produce coalesced global stores. The epilogue remaps fragments, often through shared memory, and applies operations such as:

2026-10-12T12:02:55.681016 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Fusing bias, scaling, activation, quantization, or residual operations can eliminate a full read and write. An overgrown epilogue can increase registers, inhibit vector stores, or create too many specialized variants.

Split-K, Stream-K, and persistent scheduling

When M and N expose too few output tiles but K is large, split K across blocks. Partial C tiles are combined with atomics or a workspace reduction. The extra reduction is worthwhile when it unlocks otherwise idle SMs.

In the running example's decode GEMM with M = 8, ordinary output tiling may leave most of the GPU idle. Splitting K creates more independently schedulable work, at the cost of partial-result traffic. Persistence alone cannot create parallelism when too few output tiles exist; it must be paired with a work decomposition that exposes enough tasks.

Stream-K-like scheduling distributes K work more evenly across a fixed set of work units to reduce wave quantization and tail imbalance. Persistent kernels keep blocks resident and pull tiles from a global or hierarchical queue. These strategies improve utilization for awkward shapes but add coordination and deterministic-order questions.

Batched and grouped GEMM

Batched GEMM executes many matrices with compatible shapes and strides. Grouped GEMM accepts varying shapes and offsets. Both appear in attention heads, adapters, and mixture-of-experts layers.

Small matrices may be launch- and scheduling-bound. Grouping several problems into one persistent kernel increases available work but requires load balancing. Sorting by shape can improve efficiency while adding preprocessing and reordering cost.

Library, template framework, or custom kernel

Use cuBLAS or another vendor library for standard dense GEMM. Use a template framework such as CUTLASS when you need controlled layouts, data types, schedules, or epilogues without writing every hardware primitive. Write a custom kernel when the operator is unusual enough that the library boundary creates material traffic or launch cost.

The decision is based on end-to-end value, maintainability, architecture coverage, and test burden. Beating a library on one shape is not the same as owning a production GEMM.

Design Exercises

  1. Why does tiling increase arithmetic intensity?
  2. Fix the out-of-bounds and barrier bug in a naive shared-memory kernel.
  3. What tradeoff determines tile size and pipeline depth?
  4. When does split-K help, and what new cost does it create?
  5. How do tensor cores change implementation and error analysis?
  6. Why does a high-performance GEMM need an epilogue?

Worked Solutions

1. Tiling and arithmetic intensity

A tile is loaded once into shared memory and reused by many output accumulators. For a square width-T tile, input traffic grows like T^2 while multiply-accumulate work grows like T^3, so operations per loaded byte grow with T. The exact gain depends on cache, dtype, edge tiles, and whether the compiler actually preserves the intended reuse.

2. Bounds and barriers

Do not return threads that will be needed at a later __syncthreads(). Every thread loads either a valid element or zero into each shared tile, then all threads reach the barrier. After compute, all threads reach the second barrier before the tile is overwritten. Only the final global store is predicated on a valid output coordinate.

3. Tile size and pipeline depth

Larger tiles and more stages increase reuse and overlap. They also consume shared memory, registers, threads, and instruction budget, which can reduce residency or spill. The optimum is the smallest resource footprint that keeps copy and compute pipelines busy for representative shapes. Use the occupancy calculation and achieved-stall profile, then benchmark nearby configurations.

4. Split-K

Split-K helps when the M-by-N tile grid is too small to occupy the device and K is large enough to partition. It creates multiple partial results for each C tile, requiring atomic accumulation or a separate reduction workspace. That adds traffic, synchronization, possible nondeterminism, and initialization cost. It loses when ordinary output parallelism is already sufficient.

5. Tensor cores and error

Implementation changes from scalar FMA loops to architecture-defined matrix fragments, with stricter dtype, alignment, and layout requirements. The kernel must pipeline data into the MMA path and map fragments to an output epilogue. Error analysis must specify input conversion, accumulation dtype, rounding, operation order, saturation or scaling for integer and FP8 paths, and tolerance versus a high-precision reference.

6. The epilogue

MMA accumulator fragments are arranged for compute, not necessarily coalesced output. The epilogue rearranges them for efficient stores and applies alpha, beta, bias, activation, residual, or quantization while the values are still on chip. Without it, output stores may be inefficient and downstream elementwise kernels would reread and rewrite the entire matrix.