ELLMEngineering Large
Language Models
Download PDF

Chapter 27

GPU Execution, Memory, and Resource Accounting

On this page

Threads execute in warps, warps are scheduled on streaming multiprocessors, and data moves through a hierarchy whose capacity grows as latency and sharing scope increase. Performance follows from how well the schedule uses those resources.

Before optimizing any kernel in the running example, you need a model of how the GPU executes work and where data can live. The rest of this part repeatedly asks: which level holds the tile, which group synchronizes, and which resource saturates first?

Registers and shared memory provide explicit locality; caches and HBM provide progressively larger scope. Each level has a capacity, bandwidth, allocation unit, and synchronization cost.
Open full diagram ↗

Registers and shared memory provide explicit locality; caches and HBM provide progressively larger scope. Each level has a capacity, bandwidth, allocation unit, and synchronization cost.

The execution hierarchy

A kernel launch creates a grid. The grid contains thread blocks. A block is assigned to one streaming multiprocessor, or SM, and normally remains there until it finishes. Threads in a block can cooperate through shared memory and block-scoped barriers. Threads from unrelated blocks cannot assume concurrent residency or execution order.

Threads are issued in warps, commonly 32 lanes. A warp scheduler selects an eligible warp whose next instruction has ready operands. The GPU hides latency by switching among ready warps and by exploiting independent instructions within each warp.

Newer architectures add optional execution levels such as thread-block clusters and distributed shared-memory access. These features can coordinate nearby blocks, but they do not invalidate the basic reasoning method: define the participating group, storage scope, synchronization contract, and resource cost.

SIMT, divergence, and predication

CUDA uses a single-instruction, multiple-thread execution model. Lanes in a warp may have different registers and addresses while issuing the same instruction. If lanes take different control paths, the warp executes the necessary paths under different masks.

Divergence cost depends on three facts:

  • how many lanes are active on each path;
  • how much work each path contains;
  • whether the compiler converts a short branch into predicated instructions.

Branch divergence is not the same as memory divergence. A uniform branch can still issue scattered loads. A divergent branch can be inexpensive if only a few predicated instructions differ.

Example status: CUDA excerpt; not compiled or benchmarked.

// The boundary condition diverges only in the final block.
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
  y[i] = alpha * x[i] + y[i];
}

Do not remove a cheap bounds check by launching a separate cleanup kernel unless measurement shows the tail dominates. Extra launches and code variants can cost more than limited edge divergence.

Warp scheduling and latency hiding

A warp becomes ineligible when it waits for data, a dependency, a barrier, or an execution resource. Latency hiding requires other eligible warps or independent instructions. This produces two forms of parallelism:

  • thread-level parallelism: many resident warps can run while another waits;
  • instruction-level parallelism: one thread or warp has several independent operations in flight.

Apply this to the running example. A memory-bound decode gather over paged KV may need many resident warps because each warp has dependent long-latency loads. A prefill tensor-core mainloop can run well at lower occupancy if it has an effective asynchronous pipeline and enough independent matrix operations.

Memory spaces and their contracts

Registers are thread-private and compiler allocated. Register pressure can reduce resident blocks; excess live values spill to local memory, which is physically backed by device memory and cached.

Shared memory is block-scoped, explicitly indexed, and suited to tiles, cross-thread exchange, reductions, and staging. Its capacity is reserved per block and therefore affects residency.

L1 and L2 caches provide hardware-managed reuse. L2 is shared across SMs and often explains why a second benchmark pass appears faster. Cache state must be considered when comparing cold and warm behavior.

Global/device memory is device-wide and typically backed by device DRAM; HBM is the physical memory technology in the running GPU example. It offers high bandwidth but much higher latency than on-chip storage. Coalescing and reuse determine useful bandwidth.

Constant memory is read-only from device code and can efficiently broadcast when a warp reads the same address. Divergent constant addresses serialize through the cache path.

Pinned host memory supports higher-bandwidth and asynchronous host-device transfers, but it is a scarce host resource. Unified memory can simplify address management, but page migration and fault behavior must be understood for performance-critical paths.

Coalescing with a transaction example

For many modern CUDA devices, global accesses by a warp are serviced by the 32-byte sectors needed to cover the requested addresses. Consider 32 lanes loading adjacent float values from a 32-byte-aligned base:

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

The warp requests 128 contiguous bytes, so four 32-byte sectors contain all values. Shift the base by one float and the same logical 128 bytes can span five sectors. Access one float every 32 floats and the warp may request one sector per lane while using only 4 bytes from each.

Useful bandwidth is:

requested_bytes / transferred_bytes * measured_bus_bandwidth

This ratio explains why a kernel can report high device-memory throughput while delivering little useful data.

In the running example, a well-laid-out KV vector of width d = 128 in FP16 is 256 bytes per token per head. A warp that loads those values as contiguous pairs can cover them with a small number of sectors. The same logical read through a badly packed page table, with lanes jumping across pages, can multiply transferred sectors without increasing useful bytes.

Alignment and vectorized access

Vector loads such as float4 reduce instruction count when pointers are aligned and each thread owns adjacent data. They do not automatically fix a bad warp-level access pattern. A warp of threads performing aligned vector loads should still cover compact contiguous sectors.

Use scalar tail handling or a predicated final vector. Never reinterpret an unaligned pointer as a wider vector type solely to obtain fewer instructions. Validate compiler output because source-level vector syntax may be split when alignment is not provable.

Shared-memory banks

Shared memory is divided into banks. A common mapping for four-byte words is conceptually:

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

If lanes access different addresses in the same bank, the access may be serialized into several transactions. If lanes read the same address, hardware can broadcast.

A transpose tile often adds one padding column:

Example status: CUDA excerpt; not compiled or benchmarked.

__shared__ float tile[32][33];

tile[threadIdx.y][threadIdx.x] = input[row * ld + col];
__syncthreads();

// Column access now advances by 33 words rather than 32.
float value = tile[threadIdx.x][threadIdx.y];

Without padding, a column stride equal to the bank count maps many lanes to one bank. Padding rotates successive rows through different banks.

Derive bank conflicts from the address function

For one scalar 32-bit shared-memory access per lane, let lane l read word w(l) = w0 + s*l, with 32 active lanes and positive integer stride s. The bank index is b(l) = (w0 + s*l) mod 32. Two lanes collide when s*(l1-l2) is divisible by 32. Consequently, the period is 32/gcd(s,32): that many distinct banks are visited and each receives gcd(s,32) distinct words. Strides 1, 2, 8, 32, and 33 therefore give conflict multiplicities 1, 2, 8, 32, and 1 under this access model.

This is a derivation for distinct word addresses within one warp instruction. A broadcast in which lanes read the same word is a different case; it must not be counted as 32 conflicting words. Vector instructions, subword types, and instructions decomposed into multiple transactions require analysis of the actual instruction and its transactions. The CUDA SIMT programming guide documents the underlying bank organization.

For a row-major tile with leading dimension L, a column read has s=L. Padding L=32 to L=33 changes the modular mapping without changing the logical matrix. The cost is 32 extra floats per 32-row tile. For a double-buffered tile, charge that padding twice to the shared-memory occupancy budget. Padding is therefore a schedule decision with an explicit capacity cost.

Quantitative occupancy

Theoretical occupancy is active warps divided by the architectural warp limit per SM. Resident blocks are bounded by the minimum of several ceilings:

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

Register allocation occurs in architecture-specific granularity, so a small increase in registers per thread can cross a step and remove an entire resident block. Dynamic shared memory has a similar cliff.

Worked example

Suppose an illustrative SM supports 2,048 threads, 64 resident warps, 65,536 registers, and 100 KiB of shared memory. A block has 256 threads, uses 64 registers per thread, and reserves 32 KiB shared memory.

  • thread ceiling: floor(2048 / 256) = 8 blocks;
  • register ceiling: floor(65536 / (256 * 64)) = 4 blocks;
  • shared-memory ceiling: floor(100 KiB / 32 KiB) = 3 blocks.

The shared-memory limit allows 3 blocks, or 24 warps, which is 37.5 percent theoretical occupancy. That may be enough if the kernel pipelines memory well. Reducing shared memory to admit a fourth block helps only if the added warps hide a real stall and the redesign does not add traffic.

This cliff appears later when FlashAttention or decode kernels grow pipeline stages or accumulator tiles: more on-chip state can raise reuse and still lower achieved bandwidth if residency collapses.

Synchronization and memory ordering

__syncthreads() is a block barrier and establishes the shared-memory visibility needed by participating threads. It must be reached by all non-exited threads in the block along a convergent control path.

Warp shuffles exchange register values without shared memory. They require an accurate active mask. Passing a full mask when the final warp has inactive lanes can read undefined values or violate the primitive's participation contract.

Atomics make an update indivisible at a declared scope, but atomicity is not a general barrier. Memory fences order the calling thread's memory operations at a specified scope; they do not by themselves make another thread wait or establish a complete publication protocol. Correct concurrent code states both the ordering requirement and the rendezvous requirement.

Resource-led optimization table

Symptom Likely resource Evidence Candidate response
Many long-scoreboard stalls Dependent memory latency Scattered loads, low eligible warps Coalesce, prefetch, increase independent work
High sectors per requested byte Memory transactions Poor global-load efficiency Change layout or lane-to-data mapping
Low residency with spills Registers Local loads/stores, allocation report Shorten live ranges, reduce tile, split kernel
Barrier-heavy timeline Synchronization Warp stalls at barriers, imbalance Repartition work, warp-level exchange
High issue utilization, low tensor utilization Instruction mix Scalar work dominates Reduce address/control overhead, use MMA path

Design Exercises

  1. Explain coalescing using lane addresses and transactions.
  2. When is low occupancy acceptable?
  3. Why does padding a shared-memory transpose tile help?
  4. What is the difference between a barrier, an atomic, and a memory fence?
  5. A kernel reaches 80 percent of HBM bandwidth. What optimizations remain plausible?

Worked Solutions

1. Coalescing

Assume each of 32 lanes loads one adjacent four-byte word from an aligned base. The addresses cover 128 contiguous bytes, which can be serviced by four aligned 32-byte sectors on many modern devices. A four-byte base offset can make the range cross a fifth sector. A large stride can require nearly one sector per lane. The goal is to minimize transferred sectors per useful byte, not merely to make each thread's local access look sequential.

2. Low occupancy

Low occupancy is acceptable when existing warps already hide the limiting latency or when instruction-level parallelism and asynchronous pipelines keep execution units busy. Large register tiles, tensor-core fragments, or multi-stage shared-memory pipelines often trade occupancy for reuse. It is unacceptable when the profile shows few eligible warps and exposed memory or dependency stalls that another resident block could cover.

3. Padding a transpose tile

A square tile with row length equal to the shared-memory bank count makes column access advance by a whole bank cycle, so many lanes select the same bank. Adding one element changes the stride to a value relatively prime to the bank count, spreading lanes across banks. The cost is a small shared-memory increase; the benefit is fewer serialized bank transactions.

4. Barrier, atomic, and fence

A barrier makes a group wait until all participants arrive and usually supplies memory visibility for a defined scope. An atomic serializes one read-modify-write operation on a location but does not make unrelated threads rendezvous. A fence orders the calling thread's memory operations at a scope but does not wait for consumers; a correctly synchronized publication/read protocol is still required. Many producer-consumer algorithms require both an ordering mechanism and a separately communicated readiness condition.

5. At 80 percent of HBM bandwidth

First determine whether 80 percent is bus traffic or useful requested bytes. If useful bandwidth is genuinely near the sustainable ceiling, large gains require fewer bytes: fuse passes, improve cache or shared-memory reuse, compress data, change layout, or change the algorithm. Smaller gains may come from reducing uncoalesced sectors, fixing partition camping, overlapping tails, or removing launches. Optimizing arithmetic alone is unlikely to matter unless it overlaps the memory path poorly.