Count memory transactions for a warp's global loads
On a GPU, threads of a warp that read neighbouring addresses get served by a few wide memory transactions (coalesced). Scattered or strided reads need many more, which is a common reason a kernel is slow. This is a simplified model simulated in NumPy, not a measurement of real hardware.
Write count_transactions(addrs, access_bytes, segment_bytes=128, warp_size=32).
- addrs: list of byte addresses, one per thread, in thread order. Threads 0..31 form warp 0, 32..63 warp 1, and so on (the last warp may be partial).
- Each thread reads access_bytes bytes starting at its address, i.e. bytes addr .. addr + access_bytes - 1.
- Memory is split into aligned segments of segment_bytes. A warp issues one transaction per DISTINCT segment touched by any byte of any of its threads.
Return the total number of transactions over all warps (int).
def count_transactions(addrs, access_bytes, segment_bytes=128, warp_size=32)Example
32 threads reading 4-byte floats at addresses 0, 4, ..., 124 touch one segment: 1 transaction. With a stride of 8 floats (addresses 0, 32, 64, ...) the warp spans 1024 bytes: 8 transactions.
Understand the idea
GPU memory is read in aligned chunks called segments. When the 32 threads of a warp read neighbouring bytes, one or two wide transactions serve them all; when they read scattered bytes, each distant segment costs its own transaction. Think of a delivery van: one trip to a single street serves many houses, but houses in different towns need separate trips. Worked example with 128-byte segments: 32 threads read 8-byte values at 0, 8, ..., 248. They touch bytes 0 to 255, so segments 0 and 1: 2 transactions. Now 32 threads read 4-byte values starting at 64: bytes 64 to 191 span segments 0 and 1, so again 2, because the start is not aligned. With a stride of 128 bytes, each thread lands in its own segment: 32. Rule: for each warp of warp_size consecutive threads, collect every segment index from addr // segment_bytes to (addr + access_bytes - 1) // segment_bytes for every thread, count the distinct ones, and add up over all warps (the last warp may be short). This is the first thing to check when a CUDA kernel is memory bound.