GPU Matrix Transpose: From Strided to Coalesced Memory Access
System DesignModel answerLast updated
Explain why a naive GPU matrix transpose causes uncoalesced memory traffic, then design a tiled shared-memory kernel that achieves coalesced reads and writes.
Background
A GPU executes threads in groups (warps or wavefronts, typically 32 or 64 lanes wide). Hardware coalesces memory requests from adjacent lanes into a single transaction only when those lanes access a contiguous, aligned block of addresses. When accesses are strided instead, each lane needs its own transaction, multiplying the effective memory bandwidth demand by the warp width.
A matrix transpose is a classic case where naively satisfying one side of the copy forces the other side to be strided.
Setup
You have a matrix A with R rows and C columns stored in row-major order in global memory. You want to produce matrix B with C rows and R columns, also in row-major, where:
B[col, row] = A[row, col]
A and B are separate allocations (no in-place requirement).
What You Are Expected To Do
-
Analyze the naive kernel. Assign one thread to each output element: thread
(tx, ty)writesB[tx, ty] = A[ty, tx]. Walk through which global-memory addresses adjacent lanes touch on the read side and the write side. Identify which side is coalesced and which is strided, and explain why that matters for throughput. -
Design a tiled kernel. Describe a kernel that uses a shared-memory staging tile to make both the global read and the global write coalesced. Cover:
- How threads cooperatively load a tile from A into scratchpad
- The synchronization needed before the transpose step
- How threads cooperatively write the transposed tile to B
- Why the write is now also coalesced
-
Handle edge cases. R and C are not guaranteed to be multiples of the tile dimension. Explain how to handle partial tiles without out-of-bounds access.
-
Address bank conflicts. Shared memory is divided into banks (typically 32 banks of 4-byte words on modern hardware). Describe when a conflict arises during the scratchpad read step and how a one-column padding trick resolves it.
-
Sketch performance expectations. What roofline metrics would you check? What tile size is a reasonable starting point, and why?
No specific hardware ISA or SDK is required. Use pseudocode or CUDA-style syntax for any code snippets.
Hints
Hint 1
Lay out the naive thread-to-element mapping first, then write out the exact flat index each of the 32 adjacent lanes in a warp computes for the read and for the write. The pattern (contiguous vs. stride-R) becomes obvious from the arithmetic alone.
Hint 2
For the tiled design, think of the operation in two phases: a coalesced load phase where threads fill the shared tile row by row, and a coalesced store phase where they drain it column by row — the shared tile absorbs the transpose so neither global access is strided.
Hint 3
Bank conflicts happen when multiple threads in the same warp read from addresses that map to the same bank (address % 32 == same value). Padding the shared tile's leading dimension by 1 element shifts each row's starting bank, breaking the conflict pattern without changing correctness.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Why the Naive Kernel Is Slow
Assign one thread per output element. Thread with logical coordinates (tx, ty) in a 2-D grid executes:
// naive kernel
int row = blockIdx.y * blockDim.y + threadIdx.y; // maps to A's row
int col = blockIdx.x * blockDim.x + threadIdx.x; // maps to A's col
if (row < R && col < C)
B[col * R + row] = A[row * C + col];
Consider a warp where threadIdx.x varies from 0 to 31 while threadIdx.y is fixed.
- Read side (
A[row * C + col]): ascolincrements by 1, the flat index increments by 1. Adjacent lanes read contiguous addresses → coalesced, one transaction. - Write side (
B[col * R + row]): ascolincrements by 1, the flat index increments by R. With R = 4096, the 32 lanes scatter across 32 cache lines spaced 4096 elements apart → fully strided, up to 32 separate transactions.
The result: memory bandwidth utilization can fall to 1/32 of the hardware peak. The fix is to make both sides contiguous.
2. Tiled Kernel Design
Allocate a shared-memory tile __shared__ float tile[TILE][TILE]. A tile covers a TILE × TILE subregion of A. The kernel proceeds in two phases per block.
Phase 1 — coalesced read into scratchpad:
int aRow = blockIdx.y * TILE + threadIdx.y;
int aCol = blockIdx.x * TILE + threadIdx.x;
if (aRow < R && aCol < C)
tile[threadIdx.y][threadIdx.x] = A[aRow * C + aCol];
__syncthreads();
Adjacent lanes (varying threadIdx.x) read consecutive columns of A → coalesced. The tile is now a local copy of the submatrix.
Phase 2 — coalesced write from scratchpad:
// Swap block indices so this block writes to the transposed output region
int bRow = blockIdx.x * TILE + threadIdx.y;
int bCol = blockIdx.y * TILE + threadIdx.x;
if (bRow < C && bCol < R)
B[bRow * R + bCol] = tile[threadIdx.x][threadIdx.y]; // note swapped indices
__syncthreads();
Adjacent lanes (varying threadIdx.x) write consecutive columns of B's row → coalesced. The transpose happens inside scratchpad — cheap — not in slow global memory.
The __syncthreads() after the load is essential: a thread must not read tile[threadIdx.x][threadIdx.y] until every thread has finished writing to the tile.
3. Edge Handling
When R or C is not a multiple of TILE, the outermost blocks cover a partial region. Guard every global access with bounds checks:
if (aRow < R && aCol < C)
tile[threadIdx.y][threadIdx.x] = A[aRow * C + aCol];
else
tile[threadIdx.y][threadIdx.x] = 0.0f; // fill so reads are safe
The fill value is arbitrary because the corresponding write is also guarded. The __syncthreads() must still execute unconditionally (place it outside the if) to avoid deadlock.
A common mistake is to guard both the load and the sync, leaving some threads skipping the barrier while others wait — this deadlocks or produces undefined behavior.
4. Bank Conflicts and the Padding Fix
With a TILE × TILE tile (e.g., 32 × 32 floats), Phase 2 reads tile[threadIdx.x][threadIdx.y]. For a fixed threadIdx.y, varying threadIdx.x reads elements from different rows but the same column. In a 32-bank layout where bank = (flat index) % 32, every element in a column maps to the same bank → 32-way bank conflict, serializing all 32 lane accesses.
Fix: declare the tile with one extra column:
__shared__ float tile[TILE][TILE + 1];
This shifts each row's start by one float (4 bytes = one bank). Column j of row i now sits at flat offset i * (TILE + 1) + j. For a column-wise access varying i, consecutive elements now map to consecutive banks → conflict-free.
5. Performance Expectations
| Metric | What to Check |
|---|---|
| Achieved memory bandwidth | Should approach device peak (e.g., ~900 GB/s on a modern data-center GPU) |
| Warp efficiency | Near 100% after padding fix |
| Occupancy | Shared memory per block and register pressure; 32 × 33 × 4 bytes ≈ 4.2 KB per block leaves room for multiple resident blocks |
Tile size: 32 × 32 is the standard starting point because it matches a 32-wide warp, fills cache lines cleanly, and leaves sufficient occupancy. Larger tiles (e.g., 64 × 16) can help on architectures with wider memory buses, but require profiling to confirm.
Common mistakes to call out:
- Forgetting
__syncthreads()between load and store phases (race condition). - Placing
__syncthreads()inside a conditional branch (deadlock). - Neglecting the padding column (bank conflicts erase most of the tiling benefit).
- Swapping block-index roles but not thread-index roles in the store address (wrong output layout).