A compiler turns a 2D convolution into a GPU kernel by giving the output axes to the thread grid and keeping the window axes as loops inside each thread. Emulate that kernel on a simulated thread grid and count its reads of global memory, with and without first copying the input tile each block needs into shared memory.
Implement conv_thread_grid(x, w, stride, block).
x is the input as nested lists of integers with shape [C_in][H][W].
w holds the weights as nested lists of integers with shape [C_out][C_in][KH][KW], with KH≤H and KW≤W.
stride is one integer s≥1 used on both axes. There is no padding and the window is not flipped.
block is the requested block shape (bx, by, bz), all at least 1.
The output has shape [C_out][OH][OW] with OH=⌊(H−KH)/s⌋+1 and OW=⌊(W−KW)/s⌋+1:
out[co][oy][ox]=∑c=0Cin−1∑i=0KH−1∑j=0KW−1x[c][oy⋅s+i][ox⋅s+j]⋅w[co][c][i][j]
The thread grid
- The three output axes are
GLOBAL axes. gidx0 is the output column ox (the grid's x), gidx1 is the output row oy (y) and gidx2 is the output channel co (z). The axes c, i, j are LOOP axes that run inside one thread.
- The extents are (OW,OH,Cout) for x, y, z. The block is clipped to them, bd=min(blockd,extentd), and the grid has ⌈extentd/bd⌉ blocks along axis d. Thread t of block g has index gd⋅bd+td on axis d.
- The guard: a thread whose index reaches or passes the extent on any axis is skipped. It reads nothing and writes nothing.
Counting reads
Only reads of x are counted, one per element. Weight reads are not counted.
- Direct kernel. Every thread that passes the guard reads each of the Cin⋅KH⋅KW input elements of its window from global memory.
- Tiled kernel. Before its threads run, each block copies one input tile from global memory into shared memory. If the block has ny output rows and nx output columns inside the output, the tile is all Cin channels of the covering rectangle of their windows: (ny−1)s+KH rows by (nx−1)s+KW columns. Each tile element is read from global memory once, including elements no window uses when s is larger than the window. The threads then read shared memory only. Every block loads its own tile, and the output channels inside one block share it.
Return
A dict with
"out": the output as nested lists of ints,
"launched": the number of threads in the grid,
"skipped": the number of threads the guard skipped,
"direct_reads": global reads of the direct kernel,
"tiled_reads": global reads of the tiled kernel,
"max_tile": the number of elements in the largest tile, which is the shared memory one block must hold.