Module contents
Lesson 25 of 26Advanced 120 min

GPU II: efficient kernels, tiled matmul and PyTorch on the RTX 4060

From a working kernel to a fast one. Build shared-memory tiled matrix multiplication toward cuBLAS performance; study GPU reductions and scans, Tensor Cores and precision, fused-kernel design behind FlashAttention and torch.compile, and kernel profiling with Nsight Compute. Finish with massive Monte Carlo on the local GPU.

After this lesson you can

  • Implement naive, shared-memory tiled and register-tiled matmul, and measure performance against cuBLAS.
  • Avoid shared-memory bank conflicts.
  • Explain Tensor Core operation and precision and control TF32, FP16 and BF16 in PyTorch.
  • Design and hand-write a fused kernel for a chain of memory-bound operations.
  • Profile a kernel with Nsight Compute and interpret throughput, occupancy and warp stall causes.

Before you start

Motivation: where does a transformer’s time go?

Ivanov, Dryden, Ben-Nun, Li and Hoefler measured in 2021 where training time went for a BERT encoder layer in PyTorch (Data Movement Is All You Need, table 1). Tensor contractions (matrix products) performed 99.80% of floating-point operations and took 61.0% of time. Statistical normalizations (softmax, layer norm) performed 0.17% of operations and took 25.5% of time; elementwise operations (biases, activations, dropout, residual additions) performed 0.03% and took 13.5% of time. Nearly four out of ten seconds went to operations doing very little computation.

The roofline model explains this: a large matrix product has hundreds of flops per byte and is compute-bound; GELU performs a few flops per number read and written and is memory-bound. Knowing which is which determines optimization: matmul must approach peak compute, requiring each datum to be reused many times from small, fast memories; an elementwise chain must move fewer bytes, requiring fusion into one kernel. Both ideas are the same tiling of the memory hierarchy brought to the GPU, and together yield FlashAttention.

The previous lesson covered SIMT architecture, the CUDA execution model (grid, blocks, 32-thread warps), the GPU memory hierarchy, coalescing and occupancy. Here you move from a working kernel to a fast one on the course RTX 4060 Laptop:

  • Tiled matmul in shared memory, its bank conflicts and register tiling, measuring each step against cuBLAS. You will see a result contradicting the textbook and why.
  • Reductions and scans: trees, warp shuffles, atomics and why two runs may give different numbers.
  • Tensor Cores and TF32, FP16 and BF16 precision, with predicted and measured error.
  • Fused-kernel design, handwritten, with Triton and torch.compile.
  • Kernel profiling with Nsight Compute, and Monte Carlo with 10910^9 samples.

Your GPU, measured

Everything below is measured on your GPU. The first cell prints its parameters and defines two lab tools: a CUDA kernel compiler in about fifty lines and a CUDA-event timer.

The compiler uses NVRTC, NVIDIA’s runtime CUDA C++ compiler bundled with PyTorch, and the CUDA driver API to load the binary and launch it on PyTorch tensor memory. You need not install the CUDA toolkit or nvcc. Launching a kernel is precisely this: compile for your GPU architecture (sm_89 on RTX 40), load the module and call cuLaunchKernel with grid, block and an array of argument pointers. cupy.RawKernel and torch.utils.cpp_extension.load_inline do the same more conveniently; here you see it without black boxes.

[ ]Your GPU and a kernel compiler in 50 linesLocal GPU
import ctypes, glob, os, sys, math, time
import torch

def _cargar_nvrtc():
    base = os.path.dirname(torch.__file__)          # NVRTC viene con las ruedas de PyTorch con CUDA
    patrones = ["lib/nvrtc64_1*_0.dll"] if sys.platform == "win32" else ["lib/libnvrtc.so*", "../nvidia/cu*/lib/libnvrtc.so*"]
    for p in patrones:
        for ruta in sorted(glob.glob(os.path.join(base, p)), reverse=True):
            try:
                return ctypes.CDLL(ruta)
            except OSError:
                pass
    raise OSError("no encuentro NVRTC: instala PyTorch con CUDA o usa cupy.RawKernel")

nvrtc = _cargar_nvrtc()
cuda = ctypes.CDLL("nvcuda.dll" if sys.platform == "win32" else "libcuda.so.1")   # API de driver

def _ok(r, que):
    if r != 0:
        raise RuntimeError(f"{que} devolvió el código {r}")

class Kernel:
    """Compila código CUDA con NVRTC y lo lanza sobre tensores de PyTorch, en su stream actual."""
    def __init__(self, fuente, nombre, **defs):
        torch.zeros(1, device="cuda")                               # contexto de CUDA activo (el de PyTorch)
        fuente = "".join(f"#define {k} {v}\n" for k, v in defs.items()) + fuente
        prog = ctypes.c_void_p()
        _ok(nvrtc.nvrtcCreateProgram(ctypes.byref(prog), fuente.encode(), b"k.cu", 0, None, None), "nvrtcCreateProgram")
        p = torch.cuda.get_device_properties(0)
        opts = [f"--gpu-architecture=sm_{p.major}{p.minor}".encode()]
        if nvrtc.nvrtcCompileProgram(prog, len(opts), (ctypes.c_char_p * len(opts))(*opts)) != 0:
            tam = ctypes.c_size_t(); nvrtc.nvrtcGetProgramLogSize(prog, ctypes.byref(tam))
            log = ctypes.create_string_buffer(tam.value); nvrtc.nvrtcGetProgramLog(prog, log)
            raise RuntimeError("error de compilación:\n" + log.value.decode())
        tam = ctypes.c_size_t(); _ok(nvrtc.nvrtcGetCUBINSize(prog, ctypes.byref(tam)), "nvrtcGetCUBINSize")
        cubin = ctypes.create_string_buffer(tam.value); _ok(nvrtc.nvrtcGetCUBIN(prog, cubin), "nvrtcGetCUBIN")
        nvrtc.nvrtcDestroyProgram(ctypes.byref(prog))
        self.modulo, self.f = ctypes.c_void_p(), ctypes.c_void_p()
        _ok(cuda.cuModuleLoadData(ctypes.byref(self.modulo), cubin), "cuModuleLoadData")
        _ok(cuda.cuModuleGetFunction(ctypes.byref(self.f), self.modulo, nombre.encode()), "cuModuleGetFunction")

    def __call__(self, grid, block, *args, smem=0):
        vals = [ctypes.c_void_p(a.data_ptr()) if isinstance(a, torch.Tensor) else ctypes.c_int(a) if isinstance(a, int)
                else ctypes.c_float(a) for a in args]                # punteros, int32 y float32
        params = (ctypes.c_void_p * len(vals))(*[ctypes.cast(ctypes.byref(v), ctypes.c_void_p) for v in vals])
        g = tuple(grid) + (1,) * (3 - len(grid)); b = tuple(block) + (1,) * (3 - len(block))
        stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream)
        _ok(cuda.cuLaunchKernel(self.f, *g, *b, smem, stream, params, None), "cuLaunchKernel")

    def _atributo(self, codigo):
        v = ctypes.c_int(); _ok(cuda.cuFuncGetAttribute(ctypes.byref(v), codigo, self.f), "cuFuncGetAttribute"); return v.value
    def registros(self): return self._atributo(4)                  # CU_FUNC_ATTRIBUTE_NUM_REGS
    def smem_estatica(self): return self._atributo(1)              # CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES
    def bloques_por_sm(self, hilos, smem=0):                       # ocupación teórica, según el driver
        v = ctypes.c_int()
        _ok(cuda.cuOccupancyMaxActiveBlocksPerMultiprocessor(ctypes.byref(v), self.f, hilos, ctypes.c_size_t(smem)), "cuOccupancy")
        return v.value

def tiempo_gpu(f, rep=20):
    """Mejor tiempo (s) de f() con eventos de CUDA, tras una ejecución de calentamiento."""
    f(); torch.cuda.synchronize()
    ts = []
    for _ in range(rep):
        e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
        e0.record(); f(); e1.record(); torch.cuda.synchronize()
        ts.append(e0.elapsed_time(e1) / 1e3)
    return min(ts)

p = torch.cuda.get_device_properties(0)
print(f"{p.name}: cómputo {p.major}.{p.minor}, {p.multi_processor_count} SM, {p.total_memory / 2**30:.1f} GiB")
print(f"por SM: {p.max_threads_per_multi_processor} hilos, {p.regs_per_multiprocessor} registros, "
      f"{p.shared_memory_per_multiprocessor // 1024} KiB de memoria compartida (hasta {p.shared_memory_per_block_optin // 1024} KiB por bloque)")
print(f"L2: {p.L2_cache_size // 2**20} MiB; bus de {p.memory_bus_width} bits a {p.memory_clock_rate / 1e6:.3f} GHz "
      f"-> ancho de banda teórico {2 * p.memory_clock_rate * 1e3 * p.memory_bus_width / 8 / 1e9:.0f} GB/s")
SUMA = r'''
extern "C" __global__ void suma(const float* x, const float* y, float* z, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) z[i] = x[i] + y[i];
}'''
k_suma = Kernel(SUMA, "suma")
x = torch.arange(10, dtype=torch.float32, device="cuda"); z = torch.empty_like(x)
k_suma((1,), (32,), x, x, z, 10)
print("prueba:", z.tolist())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Theoretical bandwidth follows the usual formula: GDDR6 transfers two data items per clock cycle, so 2×8.001×109×128/8≈2562 \times 8.001 \times 10^9 \times 128 / 8 \approx 256 GB/s. That is the manufacturer’s memory ceiling; what matters is what you reach.

Vector addition: the memory ceiling

z=x+y\vb{z} = \vb{x} + \vb{y} in float32 performs 1 flop per element and moves 12 bytes (two 4-byte reads and one write): arithmetic intensity 1/12≈0.0831/12 \approx 0.083 flops per byte, the lowest of any useful kernel. It therefore measures sustained GPU bandwidth, and the size sweep reveals L2 cache: while all three vectors fit, the kernel does not go to DRAM.

[ ]Vector addition: L2 and DRAM bandwidthLocal GPU
for lg in (18, 20, 21, 22, 24, 26):
    n = 1 << lg
    x, y = torch.randn(n, device="cuda"), torch.randn(n, device="cuda"); z = torch.empty_like(x)
    def diez():                                     # diez lanzamientos seguidos: amortiza el coste fijo con n pequeño
        for _ in range(10): k_suma(((n + 255) // 256,), (256,), x, y, z, n)
    t = tiempo_gpu(diez) / 10
    print(f"n = 2^{lg:2d} ({12 * n / 2**20:5.0f} MiB entre los tres): {12 * n / t / 1e9:6.0f} GB/s, {n / t / 1e9:5.1f} GFLOP/s")
assert torch.equal(z, x + y)
B_DRAM = 12 * n / t / 1e9
t = tiempo_gpu(lambda: torch.add(x, y, out=z))
print(f"torch.add con n = 2^26: {12 * n / t / 1e9:.0f} GB/s")
del x, y, z
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

While the three vectors fit in 32 MiB L2 (n=220n = 2^{20} and 2212^{21}, 12 and 24 MiB), the kernel exceeds 900 GB/s: L2 serves over four times faster than DRAM. With n=218n = 2^{18} it drops to 165 GB/s because each launch moves only 3 MiB and fixed launch cost matters. From 2222^{22} (48 MiB) data no longer fit and bandwidth falls to 208–213 GB/s, 81–83% of theoretical 256; torch.add reaches 227. The value at n=226n = 2^{26}, B=212B = 212 GB/s, is the global-memory ceiling used by the rest of the lesson.

A note on all timings below. They come from a reference run on the course RTX 4060 Laptop, whose GPU clock changes with temperature, available power and other processes: in test runs the same naive kernel gave 590 to 970 GFLOP/s. Matmul cells therefore repeat each measurement in three interleaved rounds and retain the best, and conclusions rely on factors of 2 or more that repeat across runs. Your numbers will differ; large ratios will not.

Shared-memory tiled matmul

The previous lesson’s naive kernel assigns one thread to each C=AB\mat{C} = \mat{A}\mat{B} element, with n×nn \times n matrices in row-major order, and traverses the entire dot product from global memory. With threadIdx.x across columns, a warp’s 32 threads read the same aika_{ik} (broadcast) and 32 consecutive elements of an B\mat{B} row (coalesced access): the good naive version.

extern "C" __global__ void mm_ingenuo(const float* A, const float* B, float* C, int n) {
    int fila = blockIdx.y * blockDim.y + threadIdx.y;
    int col  = blockIdx.x * blockDim.x + threadIdx.x;
    if (fila < n && col < n) {
        float acc = 0.0f;
        for (int k = 0; k < n; ++k) acc += A[fila * n + k] * B[k * n + col];
        C[fila * n + col] = acc;
    }
}

Each thread requests 2n2n numbers from global memory for 2n2n flops, and the whole kernel requests 2n32n^3: each element of A\mat{A} and B\mat{B} is requested nn times. If every request went to DRAM, intensity would be 2 flops per 8 bytes, 0.250.25, and with n=2048n = 2048 the kernel would take 2⋅20483⋅4 B/212 GB/s≈0.322 \cdot 2048^3 \cdot 4 \text{ B} / 212 \text{ GB/s} \approx 0.32 s. Reuse is enormous and unused: all threads in a block row read the same A\mat{A} row.

The solution is the CPU’s one level lower. An T×TT \times T-thread block computes an T×TT \times T tile of C\mat{C} and traverses the product in phases: each phase threads cooperatively load one A\mat{A} tile and one B\mat{B} tile into shared memory (each thread fetches one element of each), synchronize, and each thread accumulates its TT products by reading shared memory inside the SM.

extern "C" __global__ void mm_tiles(const float* A, const float* B, float* C, int n) {
    __shared__ float As[T][T];
    __shared__ float Bs[T][T];
    int tx = threadIdx.x, ty = threadIdx.y;
    int fila = blockIdx.y * T + ty, col = blockIdx.x * T + tx;
    float acc = 0.0f;
    for (int t = 0; t < n; t += T) {
        As[ty][tx] = (fila < n && t + tx < n) ? A[fila * n + t + tx] : 0.0f;   // carga cooperativa y coalescida
        Bs[ty][tx] = (t + ty < n && col < n) ? B[(t + ty) * n + col] : 0.0f;
        __syncthreads();                                                      // los dos tiles, completos
        for (int k = 0; k < T; ++k) acc += As[ty][k] * Bs[k][tx];
        __syncthreads();                                                      // nadie los pisa antes de tiempo
    }
    if (fila < n && col < n) C[fila * n + col] = acc;
}

Zero padding makes the kernel work for any nn, not only multiples of TT. Both barriers are essential: without the first, a fast thread would read As locations its neighbor has not written; without the second, a fast thread would start loading the next tile over one another thread is still reading. Such errors do not always manifest because they depend on warp scheduling order.

Proof

There are (n/T)2(n/T)^2 blocks, each traversing n/Tn/T phases. Each phase loads 2T22T^2 numbers (one A\mat{A} tile and one B\mat{B} tile), totaling (n/T)2⋅(n/T)⋅2T2=2n3/T(n/T)^2 \cdot (n/T) \cdot 2T^2 = 2n^3/T. The kernel performs 2n32n^3 flops with 4⋅2n3/T4 \cdot 2n^3/T requested bytes, or 2n3/(8n3/T)=T/42n^3 / (8n^3/T) = T/4 flops per byte. Both T×TT \times T-float tiles occupy 8T28T^2 bytes.

∎

Tile size has two bounds. T2≤1024T^2 \le 1024, because a block cannot exceed 1024 threads, so T≤32T \le 32 with one element per thread. Shared memory per block and per SM is finite: with T=32T = 32 it is 8 KiB per block, far below the 48 KiB a block can allocate statically. The actual limit is occupancy: a 4060 SM supports 1536 threads, so with T=32T = 32 (1024 threads per block) only one block fits per SM and occupancy falls to 67%; with T=16T = 16 six 256-thread blocks fit, 100%.

InteractiveTiled matmul within a thread block
A (global)B (global)C (global)As (shared)Bs (shared)C: one register per threadselected thread (3, 5) · 256 threads per block · k completed: 0 of 128
step 1 / 56
  • A tile and what the thread reads
  • B tile and what the thread reads
  • __syncthreads()
Tile 1 of 8: cooperative load. Each of the 256 threads brings one element of A and one of B into shared memory.
Tile size TT
Thread global reads so far: tiled / naive2 / 0
On completion (n = 128): tiled / naive16 / 256
Global bytes per flop (naive: 4)0.250
Shared memory per block2.00 KiB
Blocks per SM (limit: threads per SM)6
Theoretical occupancy100 %
Measured, n = 2048: tiled / naive (GFLOP/s)729 / 659
C = AB with n = 128 in global memory (above) and a T × T thread block computing the highlighted C tile. Below are two shared-memory tiles and accumulators, one register per thread. Play the animation: each round loads, synchronizes (red border), accumulates T products and synchronizes again. Click the C tile to follow another thread: which As row and Bs column does it read? Compare its global reads with the naive version and change T to 8 and 32: what does each size gain and cost? The last reading shows lab-measured GFLOP/s.
NumericHow much tiling saves
In tiled matmul with T×TT \times T tiles and TT dividing nn, by what factor do global-memory reads fall relative to the naive kernel when T=32T = 32?

What your GPU measures

Time to measure. The cell compiles naive and tiled versions with T=8,16,32T = 8, 16, 32, runs them with n=2048n = 2048, checks error against a product in float64 and asks the driver for registers per thread and blocks fitting per SM.

[ ]Naive and tiled matmulLocal GPU
INGENUO = r'''
extern "C" __global__ void mm_ingenuo(const float* A, const float* B, float* C, int n) {
    int fila = blockIdx.y * blockDim.y + threadIdx.y;
    int col  = blockIdx.x * blockDim.x + threadIdx.x;
    if (fila < n && col < n) {
        float acc = 0.0f;
        for (int k = 0; k < n; ++k) acc += A[fila * n + k] * B[k * n + col];
        C[fila * n + col] = acc;
    }
}'''
TILES = r'''
extern "C" __global__ void mm_tiles(const float* A, const float* B, float* C, int n) {
    __shared__ float As[T][T];
    __shared__ float Bs[T][T];
    int tx = threadIdx.x, ty = threadIdx.y;
    int fila = blockIdx.y * T + ty, col = blockIdx.x * T + tx;
    float acc = 0.0f;
    for (int t = 0; t < n; t += T) {
        As[ty][tx] = (fila < n && t + tx < n) ? A[fila * n + t + tx] : 0.0f;
        Bs[ty][tx] = (t + ty < n && col < n) ? B[(t + ty) * n + col] : 0.0f;
        __syncthreads();
        #pragma unroll
        for (int k = 0; k < T; ++k) acc += As[ty][k] * Bs[k][tx];
        __syncthreads();
    }
    if (fila < n && col < n) C[fila * n + col] = acc;
}'''
torch.backends.cuda.matmul.allow_tf32 = False          # float32 de verdad en la referencia (lo verás en Tensor Cores)
n = 2048
g = torch.Generator(device="cuda").manual_seed(0)
A = torch.randn(n, n, device="cuda", generator=g); B = torch.randn(n, n, device="cuda", generator=g)
C = torch.empty_like(A)
REF64 = A.double() @ B.double()
def err_rel(X): return ((X.double() - REF64).norm() / REF64.norm()).item()
k_ing = Kernel(INGENUO, "mm_ingenuo")
k_tiles = {T: Kernel(TILES, "mm_tiles", T=T) for T in (8, 16, 32)}
lanzar = {"ingenuo": (lambda: k_ing((n // 32, n // 8), (32, 8), A, B, C, n), k_ing, 256)}
for T in (8, 16, 32):
    lanzar[f"tiles {T}"] = (lambda k=k_tiles[T], T=T: k((n // T, n // T), (T, T), A, B, C, n), k_tiles[T], T * T)
res = {nombre: float("inf") for nombre in lanzar}
for vuelta in range(3):                # tres vueltas intercaladas, el mejor tiempo: el reloj de un portátil varía
    for nombre, (f, _, _) in lanzar.items():
        res[nombre] = min(res[nombre], tiempo_gpu(f, rep=5))
print(f"{'kernel':10s} {'ms':>7s} {'GFLOP/s':>8s} {'error':>8s} {'regs':>5s} {'bloques/SM':>10s} {'ocupación':>9s}")
for nombre, (f, k, h) in lanzar.items():
    C.zero_(); f(); bl = k.bloques_por_sm(h)
    print(f"{nombre:10s} {res[nombre] * 1e3:7.2f} {2 * n**3 / res[nombre] / 1e9:8.0f} {err_rel(C):8.1e} "
          f"{k.registros():5d} {bl:10d} {bl * h / 1536:9.0%}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All four kernels are correct and share error 8.1×10−78.1 \times 10^{-7} from summing 2048 products in float32. The driver confirms occupancy calculations: 67% with T=32T = 32 (one 1024-thread block per SM) and 100% with the others; with T=8T = 8 the limit is 24 blocks per SM, exactly filling 1536 threads. The theorem says tiled versions request 8, 16 and 32 times less global memory than naive. Yet in the reference run naive achieves 659 GFLOP/s, T=8T = 8 is slower (541), and T=16T = 16 and T=32T = 32 gain 11% and 5% (729 and 695). In test runs the best tiled-to-naive ratio varied from 0.8 to 1.8. No sign of a factor of 16.

Why the textbook fails here

The theorem’s argument assumes each naive request goes to DRAM. Calculate backwards: naive requests 2n3⋅42n^3 \cdot 4 bytes =68.7= 68.7 GB in 26.1 ms, 2.6 TB/s, twelve times DRAM capability. Almost no request reaches DRAM. Caches serve them: in an 32×832 \times 8-thread block, a warp’s 32 threads request the same aika_{ik} (one transaction), and all 8 warps request the same B\mat{B} row segment, retained in SM L1; neighboring blocks reuse what remains in 32 MiB L2, fitting A\mat{A} and B\mat{B} (16 MiB each). Naive already gets cache tiling for free. Simon Boehm found the same on an A6000: his shared-memory kernel gained only 50% over coalesced naive (2980 versus 1987 GFLOP/s), partly due to the latter’s good L1 hit rate (worklog).

What limits both? The inner loop. Per FMA, naive performs two reads served by L1 (one A\mat{A}, one B\mat{B}) and tiled two shared-memory reads (one As, one Bs). L1 and shared memory are the same SM SRAM with the same bandwidth. Both kernels need 8 bytes from that memory per 2 flops, 0.250.25 flops per byte, their bottleneck. The bank-conflict section measures shared-memory throughput for 4-byte reads and shows T=16T = 16 at 81% of that ceiling. Moving a tile from L1 to shared memory does not change operands delivered per FMA; it changes who manages the cache. Real gains require fewer reads per FMA, which register tiling below does.

Tile size does not help as expected either. With T=8T = 8 there are four times more blocks, each with two warps, and each 8-FMA phase pays loads, two barriers and loop overhead; with T=32T = 32 the block’s 1024 threads wait at every barrier for the slowest and only one block fits per SM. T=16T = 16 is often the middle ground.

Bank conflicts

Shared memory is not monolithic: it is divided into 32 banks, each serving one 4-byte word per cycle. The word at address aa (in 4-byte words) lives in bank a mod 32a \bmod 32. When a warp reads, each bank simultaneously serves all threads requesting the same word (broadcast); if two request different words in one bank, hardware splits the request into multiple passes.

Proof

Threads ℓ\ell and ℓ′\ell' go to the same bank if and only if (ℓ−ℓ′)s≡0(mod32)(\ell - \ell')s \equiv 0 \pmod{32}. With g=gcd⁡(s,32)g = \gcd(s, 32), that is equivalent to (ℓ−ℓ′)(s/g)≡0(mod32/g)(\ell - \ell') (s/g) \equiv 0 \pmod{32/g} and, since s/gs/g and 32/g32/g are coprime, to ℓ≡ℓ′(mod32/g)\ell \equiv \ell' \pmod{32/g}. The {0,…,31}\{0, \dots, 31\} classes modulo 32/g32/g each contain gg elements, so each used bank receives gg threads. Their addresses differ because s≥1s \ge 1. There is conflict if and only if g>1g > 1, that is, ss is even.

∎

The important case is reading a column of a row-major 32×3232 \times 32-float tile: thread ℓ\ell reads tile[ℓ][c] at word 32ℓ+c32\ell + c. Stride is 32 and all 32 threads go to one bank: a 32-way conflict turning one read into 32. The classic fix declares the tile tile[32][33]: the unused padding column makes stride 33, odd, and the theorem says no conflict remains. It costs 128 bytes per tile.

InteractiveBank conflicts
threadbank012345678910111213141516171819202122232425262728293031one bar per distinct address in the bank · passes = 3232 × 32 float tile in shared memory (each row shown is 32 words, one per bank)032one row = 32 words = 32 banks
  • no conflict
  • bank with multiple addresses
Reads per second measured on the RTX 4060 (lab microbenchmark), relative to stride 1, by stride; the horizontal line is the 1/degree prediction if banks were the only limit
123481632336465100 %0
The busiest bank receives 32 distinct addresses: the access splits into 32 passes and the banks deliver 3.1% of their bandwidth. Add a padding column.
Warp access
0
Address of thread ellellℓ · 32
Distinct addresses32
Conflict degree32
Useful bandwidth (model)3.1 %
Measured in the lab7 % (stride 32)
Above, a warp's 32 threads and their banks; below each bank, one bar per distinct address received. In the middle, the shared-memory tile is drawn over banks: each row is 32 consecutive words, one per bank, with requested words colored. Start reading an unpadded column: all 32 words land in bank 0. Increase padding to 1 and see the column become diagonal. Try «Stride» mode with 2, 6, 16, 31 and 0. Below, reads per second measured on your GPU by the lab microbenchmark.

Conflict degree can be calculated for any access pattern, not just a stride. This cell does so and checks the theorem for every stride through 64:

[ ]Conflict degree of an access patternBrowser
from math import gcd
from collections import defaultdict

def grado_conflicto(direcciones):
    """Pasadas que necesita un warp: máximo de direcciones distintas por banco (palabras de 4 bytes)."""
    por_banco = defaultdict(set)
    for a in direcciones:
        por_banco[a % 32].add(a)
    return max(len(v) for v in por_banco.values())

assert all(grado_conflicto([l * s for l in range(32)]) == gcd(s, 32) for s in range(1, 65))
patrones = {
    "fila de tile[32][32]": [5 * 32 + l for l in range(32)],
    "columna de tile[32][32]": [l * 32 for l in range(32)],
    "columna de tile[32][33]": [l * 33 for l in range(32)],
    "todos la misma palabra": [7] * 32,
    "double, stride 1 (dos palabras por hilo)": [2 * l for l in range(32)],
    "escritura de A traspuesta: As[l % 8][l // 8]": [(l % 8) * 32 + l // 8 for l in range(32)],
    "la misma, con relleno 4: As[8][32 + 4]": [(l % 8) * 36 + l // 8 for l in range(32)],
}
for nombre, d in patrones.items():
    print(f"{nombre:42s} grado {grado_conflicto(d)}")

Two lines deserve comment. double has degree 2 in this 4-byte-word model, but actual hardware serves a warp’s 64-bit accesses in two halves without extra penalty: the 32-bank, 4-byte model describes 32-bit accesses well and needs qualification for wider ones. The last two are the pattern by which the register-tiling kernel below writes transposed A\mat{A} to shared memory: degree 8 without padding and 1 with 4-column padding, not 1. Correct padding depends on the access pattern, and this calculation selects it.

The microbenchmark and a case where it does not matter

In the lab, a kernel loops over shared-memory reads at a requested stride, barely touching global memory so shared memory itself is the only bottleneck. Addresses change each round by a multiple of 32 words (banks do not change), preventing the compiler from hoisting reads out of the loop into registers: an “optimized away” microbenchmark measures something else. A second kernel reads conflict-free 16 bytes at a time (float4), and finally the classic experiment repeats: tiled transpose of a large matrix, with and without padding.

[ ]Banks: stride and transpose microbenchmarkLocal GPU
from math import gcd
BANCOS = r'''
extern "C" __global__ void bancos(float* out, int stride, int reps) {
    __shared__ float s[32 * 72];
    for (int i = threadIdx.x; i < 32 * 72; i += blockDim.x) s[i] = (float)i;
    __syncthreads();
    int base = (threadIdx.x & 31) * stride;                 // hilo l del warp: palabra l * stride
    float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;      // cuatro acumuladores independientes
    for (int r = 0; r < reps; ++r) {
        int o = base + 32 * (r & 7);                         // cambia con r (el compilador no puede sacar las lecturas
        #pragma unroll                                       // del bucle) y en un múltiplo de 32: los mismos bancos
        for (int j = 0; j < 32; j += 4) {                    // desplazamientos constantes: una instrucción LDS por lectura
            a0 += s[o + j]; a1 += s[o + j + 1]; a2 += s[o + j + 2]; a3 += s[o + j + 3];
        }
    }
    out[blockIdx.x * blockDim.x + threadIdx.x] = a0 + a1 + a2 + a3;
}
extern "C" __global__ void bancos128(float* out, int reps) {      // lo mismo con lecturas de 16 bytes (float4)
    __shared__ float4 s4[768];
    for (int i = threadIdx.x; i < 768; i += blockDim.x) s4[i] = make_float4(i, i, i, i);
    __syncthreads();
    int base = threadIdx.x & 31;                            // un warp lee 32 float4 seguidos: 512 bytes sin conflicto
    float4 a = make_float4(0.0f, 0.0f, 0.0f, 0.0f), c = a, e = a;
    for (int r = 0; r < reps; ++r) {
        int o = (base + 32 * r) & 255;                      // no se repite con un periodo corto: nada que sacar del bucle
        float4 v = s4[o], w = s4[o + 256], z = s4[o + 512];
        a.x += v.x; a.y += v.y; a.z += v.z; a.w += v.w;
        c.x += w.x; c.y += w.y; c.z += w.z; c.w += w.w;
        e.x += z.x; e.y += z.y; e.z += z.z; e.w += z.w;
    }
    out[blockIdx.x * blockDim.x + threadIdx.x] = a.x + a.y + a.z + a.w + c.x + c.y + c.z + c.w + e.x + e.y + e.z + e.w;
}'''
k_bancos, k_bancos128 = Kernel(BANCOS, "bancos"), Kernel(BANCOS, "bancos128")
bloques, hilos, reps = 24 * 6, 256, 512
out = torch.empty(bloques * hilos, device="cuda")
strides = (0, 1, 2, 3, 4, 8, 16, 32, 33, 64, 65)
medida_bancos = {s: 0.0 for s in strides}
for vuelta in range(3):                                     # tres vueltas intercaladas: el reloj de la GPU varía
    for s in strides:
        t = tiempo_gpu(lambda: k_bancos((bloques,), (hilos,), out, s, reps), rep=10)
        medida_bancos[s] = max(medida_bancos[s], bloques * hilos * reps * 32 / t / 1e9)
for s in strides:
    print(f"stride {s:2d}: grado {gcd(s, 32) if s else 1:2d}   {medida_bancos[s]:6.0f} miles de millones de lecturas/s"
          f"   ({medida_bancos[s] / medida_bancos[1]:5.0%} del stride 1)")
t128 = min(tiempo_gpu(lambda: k_bancos128((bloques,), (hilos,), out, reps), rep=10) for _ in range(3))
print(f"memoria compartida sin conflictos, lecturas de 4 bytes:  {medida_bancos[1] * 4 / 1e3:.1f} TB/s entre los 24 SM")
print(f"memoria compartida sin conflictos, lecturas de 16 bytes: {bloques * hilos * reps * 48 / t128 / 1e12:.1f} TB/s")

TRASPUESTA = r'''
extern "C" __global__ void traspuesta(const float* A, float* B, int n) {
    __shared__ float tile[32][32 + RELLENO];
    int x = blockIdx.x * 32 + threadIdx.x, y = blockIdx.y * 32 + threadIdx.y;
    for (int j = 0; j < 32; j += 8) tile[threadIdx.y + j][threadIdx.x] = A[(y + j) * n + x];   // lee filas: coalescido
    __syncthreads();
    x = blockIdx.y * 32 + threadIdx.x; y = blockIdx.x * 32 + threadIdx.y;
    for (int j = 0; j < 32; j += 8) B[(y + j) * n + x] = tile[threadIdx.x][threadIdx.y + j]; // lee columnas del tile
}'''
n_t = 8192
M = torch.randn(n_t, n_t, device="cuda"); Mt = torch.empty_like(M)
for relleno in (0, 1):
    k = Kernel(TRASPUESTA, "traspuesta", RELLENO=relleno)
    t = tiempo_gpu(lambda: k((n_t // 32, n_t // 32), (32, 8), M, Mt, n_t))
    assert torch.equal(Mt, M.T)
    print(f"traspuesta por tiles, relleno {relleno}: {8 * n_t * n_t / t / 1e9:5.0f} GB/s")
t = tiempo_gpu(lambda: Mt.copy_(M)); print(f"copia (cota superior):         {8 * n_t * n_t / t / 1e9:5.0f} GB/s")
del M, Mt
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Conflict degree shows in time. Strides 32 and 64 (degree 32) read at 6–7% of stride 1, while odd strides (3, 33, 65) lose nothing beyond clock variation (86–107%): padding works and stride 33 is as fast as 1. But the curve is not exactly 1/grado1/\text{grado}: a two-way conflict is free (101%), and from four ways performance resembles 2/grado2/\text{grado} (39, 23, 13 and 7%, versus 50, 25, 12.5 and 6.25%).

The next two lines explain why. With conflict-free 16-byte reads, the same shared memory delivers 6.6 TB/s, 1.8 times its 4-byte-read throughput (3.6 TB/s). Banks can deliver almost twice as much: the limit on 4-byte reads is the SM’s read-instruction rate, not banks. A two-way conflict occupies banks twice as long, but fits in the slack; from four ways, banks dominate. These 3.6 and 6.6 TB/s figures are shared-memory roofline ceilings.

Transpose tells the other half. Without padding, every tile-column read has a 32-way conflict, yet the kernel reaches 222 GB/s, as with padding (218) and matrix copy (219). It is DRAM-bound, and shared memory has spare capacity even serving each column in 32 passes. A bank conflict costs time only when shared memory is the bottleneck.

Before continuing, a question. You know 1×11 \times 1 kernels (one C\mat{C} element per thread) are limited by operand delivery from L1 and shared memory, not global memory.

QuizWhat should I change first?
Your shared-memory tiled matmul without register tiling reaches a small fraction of cuBLAS float32 on your RTX 4060. Four changes are possible: register tiling, vectorized loads (float4), double-buffered tiles and Tensor Cores with TF32. What is their likely impact order, greatest first?

Beyond: register tiling, vectorized loads and double buffering

If operand delivery from L1 and shared memory is the bottleneck, the remedy is tiling one level lower: each thread computes not one C\mat{C} element but a small TM×TNTM \times TN block, retaining reused values in registers. At each kk step, the thread reads TMTM values from an A\mat{A} tile column and TNTN from an B\mat{B} tile row from shared memory, and performs TM⋅TNTM \cdot TN FMA without rereading: the outer product of two small vectors.

Proof

At each kk step the thread performs TM+TNTM + TN 4-byte reads and TM⋅TNTM \cdot TN FMA, or 2 TM TN2\,TM\,TN flops. Reads per FMA are (TM+TN)/(TM TN)(TM + TN)/(TM\,TN) and intensity 2 TM TN/(4(TM+TN))2\,TM\,TN / (4(TM + TN)). Substitution gives the three cases.

∎

Moving from 1×11 \times 1 to 8×88 \times 8 multiplies shared-memory intensity eightfold. The cost is registers: TM⋅TNTM \cdot TN accumulators plus TM+TNTM + TN operands are 80 floats per thread with 8×88 \times 8, and an SM has 65536 32-bit registers, so fewer threads fit. It does not matter: each thread now has 64 independent FMA per step, ample parallelism to hide latency without many warps (Volkov called it “better performance at lower occupancy” in 2010).

Block level is chosen using the same calculation. A block computing an BM×BNB_M \times B_N tile of C\mat{C} in BKB_K steps loads (BM+BN)BK(B_M + B_N)B_K numbers from global memory per phase and performs 2BMBNBK2B_M B_N B_K flops: BMBN2(BM+BN)\frac{B_M B_N}{2(B_M + B_N)} flops per byte, 32 with BM=BN=128B_M = B_N = 128. In the kernel below, each 256-thread block computes an 128×128128 \times 128 tile and each thread an 8×88 \times 8 tile.

A loading detail explains constant RELLENO. The A\mat{A} tile is stored transposed, As[k][r], so a thread’s TMTM reads are contiguous. While loading, consecutive warp threads read A\mat{A} by rows (coalesced) and write As with kk varying fastest: thread ℓ\ell writes word k⋅(BM+RELLENO)+rk \cdot (B_M + \text{RELLENO}) + r with k=ℓ mod 8k = \ell \bmod 8 and r=4w+⌊ℓ/8⌋r = 4w + \lfloor \ell / 8 \rfloor (ww is the warp). Without padding, BMB_M is divisible by 32 and bank is r mod 32r \bmod 32: only four banks for 32 threads, an 8-way conflict (the conflict-degree cell’s last pattern). With padding 4, bank is (4k+r) mod 32(4k + r) \bmod 32 and 4k+⌊ℓ/8⌋4k + \lfloor \ell / 8 \rfloor traverses 0,…,310, \dots, 31 exactly once: no conflict, and each As row still starts at a 16-byte-aligned address as vectorized loads require. Padding 1 would break alignment.

[ ]Register tiling and comparison with cuBLASLocal GPU
REGISTROS = r'''
extern "C" __global__ void __launch_bounds__((BM * BN) / (TM * TN))
mm_registros(const float* __restrict__ A, const float* __restrict__ B, float* __restrict__ C, int n) {
    __shared__ float As[BK][BM + RELLENO];          // A traspuesta: As[k][r] = A[f0 + r][t + k]
    __shared__ float Bs[BK][BN];
    const int hilos = (BM * BN) / (TM * TN), tid = threadIdx.x;
    const int tf = tid / (BN / TN), tc = tid % (BN / TN);  // el hilo calcula C[f0 + tf*TM + i][c0 + tc*TN + j]
    const int f0 = blockIdx.y * BM, c0 = blockIdx.x * BN;
    float acc[TM][TN] = {0.0f}, rA[TM], rB[TN];
    for (int t = 0; t < n; t += BK) {
        for (int i = tid; i < BM * BK; i += hilos) { int r = i / BK, k = i % BK; As[k][r] = A[(f0 + r) * n + t + k]; }
        for (int i = tid; i < BK * BN; i += hilos) { int k = i / BN, c = i % BN; Bs[k][c] = B[(t + k) * n + c0 + c]; }
        __syncthreads();
        #pragma unroll
        for (int k = 0; k < BK; ++k) {
            #pragma unroll
            for (int i = 0; i < TM; ++i) rA[i] = As[k][tf * TM + i];   // TM + TN lecturas de memoria compartida...
            #pragma unroll
            for (int j = 0; j < TN; ++j) rB[j] = Bs[k][tc * TN + j];
            #pragma unroll
            for (int i = 0; i < TM; ++i)
                #pragma unroll
                for (int j = 0; j < TN; ++j) acc[i][j] += rA[i] * rB[j];  // ...para TM * TN FMA desde registros
        }
        __syncthreads();
    }
    for (int i = 0; i < TM; ++i)
        for (int j = 0; j < TN; ++j) C[(f0 + tf * TM + i) * n + c0 + tc * TN + j] = acc[i][j];
}'''
# requiere que BM, BN y BK dividan a n (aquí n = 2048)
k_reg, lanzar_reg = {}, {}
for (BM, BN, BK, TM, TN) in [(64, 64, 8, 4, 4), (128, 128, 8, 8, 8)]:
    for relleno in (0, 4):
        k = k_reg[(BM, TM, relleno)] = Kernel(REGISTROS, "mm_registros", BM=BM, BN=BN, BK=BK, TM=TM, TN=TN, RELLENO=relleno)
        h = BM * BN // (TM * TN)
        lanzar_reg[f"{BM}x{BN}x{BK}, {TM}x{TN} por hilo, relleno {relleno}"] = (lambda k=k, BM=BM, BN=BN, h=h: k((n // BN, n // BM), (h,), A, B, C, n), k)

def con_torch(dt, tf32=False, rep=10):
    torch.backends.cuda.matmul.allow_tf32 = tf32
    a, b = A.to(dt), B.to(dt)
    t = tiempo_gpu(lambda: a @ b, rep=rep)
    e = err_rel(a @ b)
    torch.backends.cuda.matmul.allow_tf32 = False
    return t, e
blas = [("cuBLAS float32", torch.float32, False), ("cuBLAS TF32 (Tensor Cores)", torch.float32, True),
        ("cuBLAS float16 (Tensor Cores)", torch.float16, False), ("cuBLAS bfloat16 (Tensor Cores)", torch.bfloat16, False),
        ("cuBLAS float64", torch.float64, False)]
err_blas = {}
for nombre in list(lanzar_reg) + [b[0] for b in blas]:
    res[nombre] = float("inf")
for vuelta in range(3):                                  # intercalado, como antes
    for nombre, (f, _) in lanzar_reg.items():
        res[nombre] = min(res[nombre], tiempo_gpu(f, rep=5))
    for nombre, dt, tf in blas:
        t, err_blas[nombre] = con_torch(dt, tf, rep=2 if dt == torch.float64 else 5)
        res[nombre] = min(res[nombre], t)
print(f"{'configuración':34s} {'ms':>6s} {'GFLOP/s':>8s} {'error':>8s} {'regs':>5s}")
for nombre, (f, k) in lanzar_reg.items():
    C.zero_(); f()
    print(f"{nombre:34s} {res[nombre] * 1e3:6.2f} {2 * n**3 / res[nombre] / 1e9:8.0f} {err_rel(C):8.1e} {k.registros():5d}")
print()
for nombre, _, _ in blas:
    print(f"{nombre:34s} {res[nombre] * 1e3:6.2f} {2 * n**3 / res[nombre] / 1e9:8.0f} {err_blas[nombre]:8.1e}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The jump matches the theorem. With 4×44 \times 4 per thread, 4750 and 5054 GFLOP/s (without padding and with padding 4); with 8×88 \times 8, 6634 and 4916: 6.5 to 9.1 times the T=16T = 16 tiled kernel. The best reaches cuBLAS in float32 (6658). Error remains 8.1×10−78.1 \times 10^{-7} because each cijc_{ij} is still summed in the same order.

Two details deserve attention. The 4×44 \times 4 kernel performs 1 flop per byte read from shared memory and runs at 5054 GFLOP/s: it needs 5.1 TB/s, above the 3.6 from 4-byte reads. It cannot be reading 4 bytes at a time. Its TMTM values of As and TNTN of Bs are contiguous and 16-byte aligned, and assembly can serve them with 16-byte reads, whose ceiling is 6.6 TB/s. In NVRTC-generated PTX they remain scalar reads; to see actual GPU instructions you need SASS (cuobjdump -sass from the CUDA toolkit) or Nsight Compute. Second, padding removes the 8-way conflict when writing As but does not systematically change time (it wins or loses depending on run). The calculation explains why: per phase, an 8×88 \times 8 kernel thread writes 4 values to As and 4 to Bs, and reads 128 from shared memory. A conflict on 3% of accesses is unnoticeable.

Tensor Cores change the scale: TF32 gives 11652 GFLOP/s, 1.75 times float32, and float16 and bfloat16 give 19531 and 18790, nearly three times. float64 reaches 166 GFLOP/s, 40 times less than float32: NVIDIA consumer GPUs have very few double-precision units. If your problem needs float64, a consumer GPU is not the tool; if it can live with 16 bits, it is.

GPU reductions and scans

Summing nn numbers is the pattern behind norms, dot products, softmax, Monte Carlo means and network loss. On a CPU it is a loop; on a GPU it is a design problem: tens of thousands of threads and one answer.

The shared-memory tree with sequential addressing works like this: at each level, threads t<pt < p add s[t] += s[t + p] and pp is halved.

for (int p = blockDim.x / 2; p > 0; p >>= 1) {
    if (tid < p) s[tid] += s[tid + p];      // los hilos activos son contiguos: warps enteros se quedan quietos
    __syncthreads();
}

Two details make the naive version expensive. If active threads satisfy tid % (2*p) == 0 (interleaved addressing), all warps mix active and inactive threads until the end: divergence at every level plus bank conflicts because active threads read at even stride. With sequential addressing active threads form a prefix and extra warps do nothing. In the final five levels one warp suffices, needing no shared memory or barriers: __shfl_down_sync(0xffffffff, v, d) gives each thread the v register value of the thread dd positions away in one instruction.

for (int d = 16; d > 0; d >>= 1) v += __shfl_down_sync(0xffffffff, v, d);   // el hilo 0 del warp acaba con la suma

A tree of depth ⌈log⁡2n⌉\lceil \log_2 n \rceil is exactly pairwise summation: relative error is bounded by ⌈log⁡2n⌉ u\lceil \log_2 n \rceil\, u times ∑∣xi∣/∣∑xi∣\sum \abs{x_i} / \abs{\sum x_i} (to first order), versus (n−1) u(n - 1)\,u for sequential summation. The actual reduction is hybrid: with HH total threads, each sequentially sums about n/Hn/H elements, then the tree combines HH partials, making the bound order (n/H+log⁡2H) u(n/H + \log_2 H)\,u. With n=226n = 2^{26} and H=192⋅256=49152H = 192 \cdot 256 = 49152 threads that is about 1380 chained additions versus 67 million in the sequential loop: the GPU sums better than the naive CPU loop, not by chance but because it needs parallelism.

Atomics and nondeterminism

atomicAdd(&total, v) reads, adds and writes total as one indivisible operation: multiple threads can accumulate to one address without races. But block arrival order depends on the scheduler, and floating-point addition is not associative: (a+b)+c(a + b) + c and a+(b+c)a + (b + c) can differ in the last bit. Two executions of the same kernel on the same data may differ. All are equally correct: the difference is within the summation error bound.

InteractiveOrder of a float32 reduction
each warp: shuffle tree and one atomicAdd5 levels per warp + 2048 atomicAdd in variable orderError per run, in float32 ulpsexact−20.0+20.0
  • sequential
  • tree (deterministic)
  • atomics: one run
6 distinct results in 6 runs with the same data: warps reach atomicAdd in a different order, and floating-point addition is not associative. None is “the correct one”.
Method
2^16 = 65,536
Exact sum (float64)32725.261
Float32 result (atomics, last)32725.250
Error in float32 ulps−5.4
Relative error bound2052 u = 0.0001223
Distinct results in 6 runs6
n uniform float32 numbers in [0, 1), actually summed in float32 in three ways: sequential, tree (shared memory or shuffles), and atomics (each warp tree-sums its 32 values and performs atomicAdd; warp arrival order changes each run). Above, sum structure; below, each run's error in float32 ulps. Start with atomics and press “Another run”: same data, different result. Switch to tree and sequential and raise n to 2^22: how does each error grow?
[ ]Three reductions on your GPULocal GPU
REDUCCIONES = r'''
extern "C" __global__ void suma_arbol(const float* x, float* parciales, int n) {
    __shared__ float s[256];
    int tid = threadIdx.x;
    float acc = 0.0f;
    for (int i = blockIdx.x * blockDim.x + tid; i < n; i += gridDim.x * blockDim.x) acc += x[i];  // stride de rejilla
    s[tid] = acc;
    __syncthreads();
    for (int p = blockDim.x / 2; p > 0; p >>= 1) {
        if (tid < p) s[tid] += s[tid + p];
        __syncthreads();
    }
    if (tid == 0) parciales[blockIdx.x] = s[0];
}
extern "C" __global__ void suma_shuffles(const float* x, float* parciales, int n) {
    __shared__ float s[32];
    int tid = threadIdx.x;
    float acc = 0.0f;
    for (int i = blockIdx.x * blockDim.x + tid; i < n; i += gridDim.x * blockDim.x) acc += x[i];
    for (int d = 16; d > 0; d >>= 1) acc += __shfl_down_sync(0xffffffff, acc, d);   // árbol dentro del warp
    if ((tid & 31) == 0) s[tid >> 5] = acc;
    __syncthreads();
    if (tid < 32) {                                                                  // el primer warp suma los parciales
        acc = (tid < blockDim.x / 32) ? s[tid] : 0.0f;
        for (int d = 16; d > 0; d >>= 1) acc += __shfl_down_sync(0xffffffff, acc, d);
        if (tid == 0) parciales[blockIdx.x] = acc;
    }
}
extern "C" __global__ void suma_atomica(const float* x, float* total, int n) {
    float acc = 0.0f;
    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) acc += x[i];
    for (int d = 16; d > 0; d >>= 1) acc += __shfl_down_sync(0xffffffff, acc, d);
    if ((threadIdx.x & 31) == 0) atomicAdd(total, acc);                              // un atomicAdd por warp
}'''
N = 1 << 26
x = torch.rand(N, device="cuda", generator=torch.Generator(device="cuda").manual_seed(1))
exacta = x.double().sum().item()
G = 24 * 8                                              # 8 bloques de 256 hilos por SM
parciales = torch.empty(G, device="cuda"); total = torch.zeros(1, device="cuda")
k_arbol, k_shfl, k_atom = (Kernel(REDUCCIONES, nm) for nm in ("suma_arbol", "suma_shuffles", "suma_atomica"))
def segunda_pasada(): return parciales.sum().item()     # los 192 parciales, con torch.sum
for nombre, k in (("árbol en compartida", k_arbol), ("shuffles de warp", k_shfl)):
    t = tiempo_gpu(lambda: k((G,), (256,), x, parciales, N))
    print(f"{nombre:22s} {4 * N / t / 1e9:5.0f} GB/s   error relativo {abs(segunda_pasada() - exacta) / exacta:.1e}")
def atomica():
    total.zero_(); k_atom((G,), (256,), x, total, N)
t = tiempo_gpu(atomica)
vistos = []
for _ in range(20):
    atomica(); vistos.append(total.item())
print(f"{'atómicas':22s} {4 * N / t / 1e9:5.0f} GB/s   {len(set(vistos))} resultados distintos en 20 ejecuciones, "
      f"de {min(vistos):.1f} a {max(vistos):.1f} (exacta {exacta:.3f})")
t = tiempo_gpu(lambda: x.sum())
print(f"{'torch.sum':22s} {4 * N / t / 1e9:5.0f} GB/s   error relativo {abs(x.sum().item() - exacta) / exacta:.1e}")
import numpy as np
xc = x.cpu().numpy()                                    # np.cumsum suma en orden, un elemento tras otro
sec = float(np.cumsum(xc, dtype=np.float32)[-1])
print(f"{'secuencial (CPU)':22s}            error relativo {abs(sec - exacta) / exacta:.1e}   (resultado {sec:.1f})")
del x, xc
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All three reductions run at memory speed, 210–217 GB/s, like vector addition, and torch.sum reaches 241 because it only reads: addition is free compared with fetching data. Both trees give relative errors 5.0×10−85.0 \times 10^{-8} and 9.2×10−99.2 \times 10^{-9}, below float32 unit roundoff (6.0×10−86.0 \times 10^{-8}). Atomics give 11 distinct results in 20 runs, between 33 553 424 and 33 553 474: up to 25 ulps apart (there consecutive float32 are spaced 2), all equally valid.

Sequential summation in float32 gives exactly 16 777 216=22416\,777\,216 = 2^{24}, 50% error. Beyond 2242^{24}, consecutive float32 are spaced 2 apart, and adding a number below 1 always rounds to the same value: the loop keeps “adding” over 33 million remaining numbers without changing the result. This is extreme sequential-sum stagnation and the practical reason GPU reductions accumulate only a few elements serially per thread.

Scans

A scan (prefix sum) computes yi=x1+⋯+xiy_i = x_1 + \dots + x_i for every ii. It is central to array compaction, radix sorting, cumulative histograms and, in sequence models, parallel linear recurrences seen in recurrence vectorization. Two classic shared-memory algorithms are:

  • Hillis and Steele (1986): at level d=0,1,…d = 0, 1, \dots, each yiy_i with i≥2di \ge 2^d adds yi−2dy_{i - 2^d}. It takes ⌈log⁡2n⌉\lceil \log_2 n \rceil steps but ∑d(n−2d)=n⌈log⁡2n⌉−(n−1)\sum_d (n - 2^d) = n\lceil\log_2 n\rceil - (n - 1) additions when nn is a power of two: not work-efficient.
  • Blelloch (1990): an upsweep (a reduction tree leaving partial sums at nodes, n−1n - 1 additions) and a downsweep distributing prefixes (n−1n - 1 additions and as many swaps). It takes 2log⁡2n2\log_2 n steps and O(n)\bigO(n) work, like the sequential loop, and yields the exclusive scan (yi=x1+⋯+xi−1y_i = x_1 + \dots + x_{i-1}).

For arrays larger than one block, each block scans its chunk, block sums are scanned and added back: three kernels. Merrill and Garland’s single-pass scan (2016), used by CUB and Thrust, does this in one kernel: each block publishes its partial sum and uses decoupled look-back at earlier block states rather than waiting for a second pass, moving only 2n2n global-memory elements, the minimum.

CodeBlelloch scan, level by level
Implement scan_blelloch(x) returning the exclusive scan of a NumPy array x with power-of-two length (y0=0y_0 = 0, yi=x0+⋯+xi−1y_i = x_0 + \dots + x_{i-1}) using Blelloch's algorithm. Each level of both sweeps must be one vectorized NumPy operation on that level's indices (simulating a step where all active threads work at once): no loops over elements, only levels. Also return the total addition count as (y, sumas).
import numpy as np

def scan_blelloch(x):
  y = np.concatenate([[0], np.cumsum(x)[:-1]]).astype(float)
  return y, 0
Shift+Enter to run

Tensor Cores

Since Volta (2017), each NVIDIA SM has units dedicated to one task: multiplying small matrices.

Input formats differ in bits allocated to exponent (range) and mantissa (precision). In IEEE 754 format notation, u=2−(p+1)u = 2^{-(p+1)} is the unit roundoff of a format with pp mantissa bits:

FormatBits (sign, exponent, mantissa)uuMaximum finite
FP321, 8, 232−24≈6.0×10−82^{-24} \approx 6.0 \times 10^{-8}3.4×10383.4 \times 10^{38}
TF321, 8, 10 (19 useful bits in a 32-bit container)2−11≈4.9×10−42^{-11} \approx 4.9 \times 10^{-4}FP32’s
FP161, 5, 102−11≈4.9×10−42^{-11} \approx 4.9 \times 10^{-4}65504
BF161, 8, 72−8≈3.9×10−32^{-8} \approx 3.9 \times 10^{-3}FP32’s
FP8 E4M31, 4, 32−42^{-4}448
FP8 E5M21, 5, 22−32^{-3}57344

TF32 is not a storage format: tensors remain float32 in memory and the Tensor Core rounds inputs to 10 mantissa bits on reading. It has FP32 range (no new overflow) and FP16 precision. BF16 makes the same tradeoff in 16 bits: FP32 range for only 7 mantissa bits.

Error, predicted and measured

How much error does matmul with low-bit inputs and FP32 accumulation introduce? A simple model predicts it nearly exactly. The product of two 11-bit mantissas (10 plus the implicit bit) fits in 22 bits, so is exact in FP32; FP32 accumulation adds errors of order 2−242^{-24}, negligible versus 2−112^{-11}. Thus all error comes from rounding inputs and, if the result is stored in the same 16-bit format (as a @ b does with float16 or bfloat16 tensors), rounding output too. With TF32 output remains float32.

Rounding x=m⋅2ex = m \cdot 2^e, with m∈[1,2)m \in [1, 2), to pp mantissa bits incurs absolute error that for generic data behaves uniformly on [−2e−p−1,2e−p−1][-2^{e-p-1}, 2^{e-p-1}], with root mean square 2e−p/122^{e-p}/\sqrt{12}. Relative error has root mean square 2−p12E[m−2]\frac{2^{-p}}{\sqrt{12}}\sqrt{\E[m^{-2}]}. For data whose mantissas follow Benford’s logarithmic law (density 1/(mln⁡2)1/(m \ln 2) on [1,2)[1, 2), a good approximation for Gaussian data), E[m−2]=1ln⁡2∫12m−3 ⁣dm=38ln⁡2≈0.541\E[m^{-2}] = \frac{1}{\ln 2}\int_1^2 m^{-3} \dd m = \frac{3}{8 \ln 2} \approx 0.541. Each aikbkja_{ik}b_{kj} term accumulates errors from two independent inputs, and if terms are independent and similarly sized, the product’s relative error (in Frobenius norm) has the same root mean square as one term:

∥C^−C∥F∥C∥F≈2⋅2−p12⋅0.541≈{2.93×10−4p=10 (TF32, FP16)2.35×10−3p=7 (BF16)\frac{\norm{\hat{\mat{C}} - \mat{C}}_F}{\norm{\mat{C}}_F} \approx \sqrt{2} \cdot \frac{2^{-p}}{\sqrt{12}} \cdot \sqrt{0.541} \approx \begin{cases} 2.93 \times 10^{-4} & p = 10 \text{ (TF32, FP16)} \\ 2.35 \times 10^{-3} & p = 7 \text{ (BF16)} \end{cases}

Output rounding is a third independent error with the same relative root mean square (C\mat{C} inputs also have “generic” mantissas), so with 16-bit output factor 2\sqrt{2} becomes 3\sqrt{3}: 3.59×10−43.59 \times 10^{-4} in FP16 and 2.87×10−32.87 \times 10^{-3} in BF16.

[ ]Tensor Core precision: prediction and measurementLocal GPU
pred = {p: math.sqrt(2) * 2**-p / math.sqrt(12) * math.sqrt(3 / (8 * math.log(2))) for p in (10, 7)}
print(f"predicción, dos entradas redondeadas: p = 10 -> {pred[10]:.3e},  p = 7 -> {pred[7]:.3e}")
print(f"y con la salida también en 16 bits:   p = 10 -> {pred[10] * math.sqrt(1.5):.3e},  p = 7 -> {pred[7] * math.sqrt(1.5):.3e}")
for nombre, dt, tf in [("float32 (sin TF32)", torch.float32, False), ("TF32", torch.float32, True),
                       ("float16", torch.float16, False), ("bfloat16", torch.bfloat16, False)]:
    print(f"{nombre:20s} error relativo de A @ B: {con_torch(dt, tf)[1]:.3e}")
for dt in (torch.float16, torch.bfloat16):   # solo el redondeo de las entradas, producto exacto en float64
    Ar, Br = A.to(dt).double(), B.to(dt).double()
    print(f"entradas redondeadas a {str(dt):15s} y producto exacto: {((Ar @ Br - REF64).norm() / REF64.norm()).item():.3e}")
print()
print("allow_tf32 en matmul:", torch.backends.cuda.matmul.allow_tf32, "| en cuDNN (convoluciones):", torch.backends.cudnn.allow_tf32,
      "| float32_matmul_precision:", torch.get_float32_matmul_precision())
for nombre in ("torch.backends.cuda.matmul.fp32_precision", "torch.backends.cudnn.conv.fp32_precision"):
    try:
        print(nombre, "=", eval(nombre))
    except AttributeError:
        print(nombre, "no existe en esta versión de PyTorch")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The model is accurate to three figures. With rounded inputs and exact product in float64, error is 2.937×10−42.937 \times 10^{-4} with 10 mantissa bits and 2.348×10−32.348 \times 10^{-3} with 7, versus predictions 2.932×10−42.932 \times 10^{-4} and 2.346×10−32.346 \times 10^{-3}. On Tensor Cores, TF32 gives 2.938×10−42.938 \times 10^{-4}: exactly input-rounding error, so FP32 accumulation adds nothing visible. float16 and bfloat16 give 3.592×10−43.592 \times 10^{-4} and 2.873×10−32.873 \times 10^{-3}, predictions with 3\sqrt{3}: the third rounding stores the result in 16 bits. Without TF32 the float32 product has error 8.1×10−78.1 \times 10^{-7}, about 360 times smaller than TF32.

The last lines show switches in your PyTorch version: allow_tf32 is False for matmul and True for cuDNN convolutions, and in the newer interface ieee and tf32. These defaults differ.

TF32 in PyTorch: where it activates without being requested

PyTorch has different switches for matrix products and cuDNN convolutions, with differing defaults (CUDA semantics):

  • torch.backends.cuda.matmul.allow_tf32 controls matmul in float32. Since PyTorch 1.12 it defaults to False. torch.set_float32_matmul_precision("high") enables it (TF32) and "highest" disables it; "medium" also allows internal BF16.
  • torch.backends.cudnn.allow_tf32 controls cuDNN convolutions and defaults to True: an float32 convolutional network already uses TF32 on Ampere and later GPUs.
  • Recent versions add a finer interface, torch.backends.cuda.matmul.fp32_precision and torch.backends.cudnn.conv.fp32_precision (with values such as "ieee" and "tf32"), printed by the cell if present.

Mixed-precision training with autocast, FP32 master weights and loss scaling is covered in mixed precision. Here the prior concern is knowing each product’s precision.

Conjugate gradient that stops converging

Conjugate gradient solves Ax=b\mat{A}\vb{x} = \vb{b} with symmetric positive-definite A\mat{A} using only Ap\mat{A}\vb{p} products. If those products use TF32, each has relative error of order 10−410^{-4}, and true residual b−Ax^\vb{b} - \mat{A}\hat{\vb{x}} cannot fall much below that. The cell checks this on GPU with eight systems at once (an n×8n \times 8 matmul cuBLAS does execute on Tensor Cores) and with one (a matrix–vector product that does not):

[ ]Conjugate gradient with and without TF32Local GPU
def gc(A_op, Bm, tol=1e-6, maxit=1000):
    """GC sobre las columnas de Bm a la vez; para cuando el residuo recursivo de todas baja de tol."""
    X = torch.zeros_like(Bm); R = Bm.clone(); P = R.clone(); rr = (R * R).sum(0); nb = Bm.norm(dim=0)
    for it in range(1, maxit + 1):
        AP = A_op(P)
        alfa = rr / (P * AP).sum(0)
        X += alfa * P; R -= alfa * AP
        rr2 = (R * R).sum(0)
        if ((rr2.sqrt() / nb) < tol).all():
            break
        P = R + (rr2 / rr) * P; rr = rr2
    return it, (rr2.sqrt() / nb).max().item(), X

m = 2048
gg = torch.Generator(device="cuda").manual_seed(3)
Q, _ = torch.linalg.qr(torch.randn(m, m, device="cuda", dtype=torch.float64, generator=gg))
lam = torch.logspace(0, 2, m, device="cuda", dtype=torch.float64)                 # autovalores de 1 a 100
S64 = (Q * lam) @ Q.T; S = S64.float(); del Q
Bm = torch.randn(m, 8, device="cuda", generator=gg)
def verdadero(X, Bc):                                   # residuo verdadero, calculado en float64
    return ((Bc.double() - S64 @ X.double()).norm(dim=0) / Bc.double().norm(dim=0)).max().item()
print(f"{'':30s} {'iter.':>5s} {'residuo recursivo':>18s} {'residuo verdadero':>18s}")
for tf in (False, True):
    torch.backends.cuda.matmul.allow_tf32 = tf
    for nombre, cols in (("8 sistemas (matmul)", Bm), ("1 sistema (matriz x vector)", Bm[:, :1].contiguous())):
        it, rec, X = gc(lambda P: S @ P, cols)
        print(f"{('TF32 ' if tf else 'FP32 ') + nombre:30s} {it:5d} {rec:18.1e} {verdadero(X, cols):18.1e}")
torch.backends.cuda.matmul.allow_tf32 = False
amp = (lam.max() * X.double().norm(dim=0) / cols.double().norm(dim=0)).max().item()
print(f"||A|| ||x|| / ||b|| = {amp:.0f}:  u(float32) * {amp:.0f} = {2**-24 * amp:.1e},  u(TF32) * {amp:.0f} = {2**-11 * amp:.1e}")
del S, S64
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All four runs stop at 72 iterations with recursive residual 10−610^{-6}: by the method’s own account, all converged. True residual computed in float64 tells another story. In FP32 it is 3.1×10−63.1 \times 10^{-6}, the precision’s own limit: uFP32 ∥A∥∥x^∥/∥b∥=2.0×10−6u_{\text{FP32}}\,\norm{\mat{A}}\norm{\hat{\vb{x}}}/\norm{\vb{b}} = 2.0 \times 10^{-6} with factor 34 printed by the cell. With TF32 and eight systems it is 2.5×10−32.5 \times 10^{-3}, about 800 times worse, with nothing in the iterations revealing it: recurrence r←r−α Ap\vb{r} \leftarrow \vb{r} - \alpha\,\mat{A}\vb{p} uses the same inexact products and keeps falling as if exact. With one system, matrix–vector multiplication does not use Tensor Cores and TF32 changes nothing (2.5×10−62.5 \times 10^{-6} in both cases).

The bound using uTF32u_{\text{TF32}}, 1.6×10−21.6 \times 10^{-2}, is pessimistic by a factor of 6: uu is each rounding’s worst case, typical error for a product with TF32 inputs is the measured 2.9×10−42.9 \times 10^{-4}, and errors from different terms partly cancel. But order of magnitude rules: if you require residual 10−510^{-5}, FP32 provides it and TF32 cannot.

Fused kernels

An elementwise operation on NN float32 numbers reads and writes 8N8N bytes for a handful of flops per element: intensity is tenths of a flop per byte, a hundred times below the GPU balance point. Time is dominated by moving bytes. A chain of four as four kernels writes each intermediate result to global memory for the next kernel to reread: four times the necessary traffic. This is PyTorch’s operator fusion from the kernel writer’s perspective.

Bias, GELU, dropout and residual addition

A transformer’s linear-layer output passes through y=dropout⁡p(GELU⁡(x+b))+r\vb{y} = \operatorname{dropout}_p(\operatorname{GELU}(\vb{x} + \vb{b})) + \vb{r}. In PyTorch eager mode these are four kernels. Counting global-memory bytes with NN elements, bias dd and ss bytes per number:

KernelReadsWrites
t1=x+b\vb{t}_1 = \vb{x} + \vb{b}s(N+d)s(N + d)sNsN
t2=GELU⁡(t1)\vb{t}_2 = \operatorname{GELU}(\vb{t}_1)sNsNsNsN
t3=dropout⁡(t2)\vb{t}_3 = \operatorname{dropout}(\vb{t}_2)sNsNsNsN and mask, NN bytes
y=t3+r\vb{y} = \vb{t}_3 + \vb{r}2sN2sNsNsN

In total 9sN+N+sd9sN + N + sd bytes versus 3sN+sd3sN + sd for the fused kernel, which reads x\vb{x}, b\vb{b} and r\vb{r} and writes y\vb{y}: with s=4s = 4 and d≪Nd \ll N, ratio 37/12≈3.137/12 \approx 3.1. Fused dropout neither reads nor writes a mask: it generates one using a counter-based generator, Philox4x32-10, turning element index and seed into four 32-bit random integers. Backward only needs another call with the same counter. Each thread processes four consecutive elements with vectorized float4 loads, one Philox call for all four.

[ ]A fused Philox kernel: bias, GELU, dropout and residualLocal GPU
FUSIONADO = r'''
__device__ __forceinline__ uint4 philox4x32_10(uint4 c, uint2 k) {
    #pragma unroll
    for (int r = 0; r < 10; ++r) {                       // 10 rondas de Philox4x32 (Salmon et al., 2011)
        unsigned hi0 = __umulhi(0xD2511F53u, c.x), lo0 = 0xD2511F53u * c.x;
        unsigned hi1 = __umulhi(0xCD9E8D57u, c.z), lo1 = 0xCD9E8D57u * c.z;
        c = make_uint4(hi1 ^ c.y ^ k.x, lo1, hi0 ^ c.w ^ k.y, lo0);
        k.x += 0x9E3779B9u; k.y += 0xBB67AE85u;
    }
    return c;
}
extern "C" __global__ void philox_prueba(const unsigned* e, unsigned* s) {
    uint4 r = philox4x32_10(make_uint4(e[0], e[1], e[2], e[3]), make_uint2(e[4], e[5]));
    s[0] = r.x; s[1] = r.y; s[2] = r.z; s[3] = r.w;
}
__device__ __forceinline__ float gelu(float v) { return 0.5f * v * (1.0f + erff(v * 0.70710678118654752f)); }
__device__ __forceinline__ float drop(float v, unsigned r, float p, float esc) {
    return ((r >> 8) * (1.0f / 16777216.0f) >= p) ? v * esc : 0.0f;   // u uniforme en [0, 1) con 24 bits
}
extern "C" __global__ void sesgo_gelu_dropout_residuo(const float4* x, const float4* b, const float4* res, float4* y,
                                                     int n4, int d4, float p, int semilla) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i >= n4) return;
    uint4 r = philox4x32_10(make_uint4(i, 0, 0, 0), make_uint2((unsigned)semilla, 0u));
    float4 v = x[i], bb = b[i % d4], rr = res[i];
    float esc = 1.0f / (1.0f - p);
    v.x = drop(gelu(v.x + bb.x), r.x, p, esc) + rr.x;
    v.y = drop(gelu(v.y + bb.y), r.y, p, esc) + rr.y;
    v.z = drop(gelu(v.z + bb.z), r.z, p, esc) + rr.z;
    v.w = drop(gelu(v.w + bb.w), r.w, p, esc) + rr.w;
    y[i] = v;
}'''
# 1) Philox contra los vectores de prueba conocidos de Random123 (contador, clave -> salida)
k_kat = Kernel(FUSIONADO, "philox_prueba")
kat = [([0] * 6, "6627e8d5 e169c58d bc57ac4c 9b00dbd8"),
       ([0xffffffff] * 6, "408f276d 41c83b0e a20bc7c6 6d5451fd"),
       ([0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0], "d16cfe09 94fdcceb 5001e420 24126ea1")]
for ent, esperado in kat:
    e = torch.tensor([v - 2**32 if v >= 2**31 else v for v in ent], dtype=torch.int32, device="cuda")
    s = torch.empty(4, dtype=torch.int32, device="cuda"); k_kat((1,), (1,), e, s)
    obtenido = " ".join(f"{v % 2**32:08x}" for v in s.tolist())
    assert obtenido == esperado, (obtenido, esperado)
print("Philox4x32-10 coincide con los tres vectores de prueba de Random123")

# 2) el kernel fusionado frente a la cadena de PyTorch
import torch.nn.functional as F
filas, d = 8192, 4096                                    # N = 2^25 elementos, 128 MiB por tensor
g = torch.Generator(device="cuda").manual_seed(0)
x = torch.randn(filas, d, device="cuda", generator=g); res_ = torch.randn(filas, d, device="cuda", generator=g)
b = torch.randn(d, device="cuda", generator=g); y = torch.empty_like(x)
N = filas * d
k_fus = Kernel(FUSIONADO, "sesgo_gelu_dropout_residuo")
fusionado = lambda p=0.1, sem=1234: k_fus(((N // 4 + 255) // 256,), (256,), x, b, res_, y, N // 4, d // 4, p, sem)
def separado():
    return F.dropout(F.gelu(x + b), 0.1, training=True) + res_
fusionado(0.0); torch.cuda.synchronize()
print(f"p = 0: diferencia máxima con F.gelu(x + b) + r: {(y - (F.gelu(x + b) + res_)).abs().max().item():.1e}")
fusionado(0.1)
print(f"p = 0.1: fracción anulada {((y - res_) == 0).float().mean().item():.4f}")
t_sep, t_fus = tiempo_gpu(separado), tiempo_gpu(fusionado)
print(f"cuatro kernels de PyTorch: {t_sep * 1e3:.2f} ms;  fusionado a mano: {t_fus * 1e3:.2f} ms ({12 * N / t_fus / 1e9:.0f} GB/s útiles)")
try:
    separado_c = torch.compile(separado)
    separado_c()
    t_c = tiempo_gpu(separado_c)
    print(f"torch.compile de la cadena: {t_c * 1e3:.2f} ms")
except Exception as e:                                   # sin Triton (o en una versión rota), no hay compilación
    t_c = float("nan"); print("torch.compile no disponible aquí:", type(e).__name__)
print(f"cociente separado / fusionado: {t_sep / t_fus:.2f}  (el modelo de bytes predice {37 / 12:.2f})")
diminuto = torch.zeros(1024, device="cuda")
def cien():
    for _ in range(100): diminuto.add_(1.0)
print(f"coste mínimo de un kernel lanzado desde Python: {tiempo_gpu(cien, rep=5) / 100 * 1e6:.1f} µs")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

First, correctness. Philox matches published Random123 test vectors, so it is the actual generator, not an approximation. With p=0p = 0 the kernel reproduces F.gelu(x + b) + r without difference, and with p=0.1p = 0.1 zeros exactly the requested fraction (0.1000).

Next, time. Four PyTorch kernels take 5.55 ms and the fused one 1.81 ms: ratio 3.08, as predicted by the byte model. The fused kernel moves its 12N12N bytes at 223 GB/s, the vector-add ceiling: no headroom remains. torch.compile generates its own Triton kernel for the chain and takes 2.19 ms, comparable to yours (1.79–2.19 ms in test runs): automatic fusion recovers nearly all the gain without writing CUDA. The last line is minimum launch cost from Python, 14.3 µs: that would dominate small tensors.

InteractiveFusion timeline
4 kernelsx + bGELUdropout+ residual1 kernelfused0.00 ns1.47 ms2.95 ms4.42 ms5.90 ms
t = 0.00 ns
  • global memory read
  • write
  • time measured in the lab
The separate chain moves 3.08 times as many bytes as the fused kernel, and because all kernels are memory-bound, time falls by almost the same proportion. This is the argument behind FlashAttention: do not materialize in global memory what you can consume in registers or shared memory.
Show
2^25
Bytes moved: separate1.16 GiB
Bytes moved: fused384 MiB
Model time (sep. / fused)5.90 ms / 1.90 ms
Predicted speedup3.11×
Measured (sep. / fused)5.55 ms / 1.81 ms
Measured with torch.compile2.19 ms
Bytes moved at cursor (sep. / fused)0 B / 0 B
The bias → GELU → dropout → residual-add chain as four kernels (red) and one fused kernel (green) on the same timeline. Each bar is a kernel: light shows global-memory reads, dark writes. The model uses lab-measured bandwidth and minimum kernel cost; dashed lines are measured times for N = 2^25 in float32. Play and inspect bytes moved at the cursor. Switch to bf16, remove the dropout mask and lower N to 2^14: what dominates?

Row-wise softmax in one kernel

Row softmax, yj=exj−m/∑kexk−my_j = e^{x_j - m}/\sum_k e^{x_k - m} with m=max⁡kxkm = \max_k x_k, needs two reductions (maximum and sum) before writing anything. Expressed as PyTorch operations (max, subtraction, exp, sum, division), it takes five kernels and 8N8N numbers of traffic. A fused kernel with one block per row can read the row, reduce in shared memory and write: 2N2N numbers if the row is read twice from cache.

The trick enabling one read is Milakov and Gimelshein’s online softmax (2018): maintain partial maximum mm and partial sum ℓ=∑exk−m\ell = \sum e^{x_k - m} together, updating on a new xx value:

m′=max⁡(m,x),ℓ′=ℓ em−m′+ex−m′.m' = \max(m, x), \qquad \ell' = \ell\, e^{m - m'} + e^{x - m'}.

Two pairs (m1,ℓ1)(m_1, \ell_1) and (m2,ℓ2)(m_2, \ell_2) from different chunks combine the same way: m=max⁡(m1,m2)m = \max(m_1, m_2), ℓ=ℓ1em1−m+ℓ2em2−m\ell = \ell_1 e^{m_1 - m} + \ell_2 e^{m_2 - m}. This operation is associative, so fits a shuffle tree. Applied to attention-matrix blocks, it gives FlashAttention’s online softmax.

Triton, the language by Tillet, Kung and Cox (2019), lets you express this by blocks: describe what a program does with a whole data block (load a row, reduce, write) and the compiler distributes work across threads, coalesces access and manages shared memory. This is what torch.compile generates internally, as seen in m00, and is studied in depth in the Triton programming model.

[ ]Row softmax: five kernels, handwritten, Triton and torch.compileLocal GPU
SOFTMAX = r'''
__device__ __forceinline__ void combina(float& m, float& s, float m2, float s2) {   // (m, l) asociativo
    float mm = fmaxf(m, m2);
    s = (s == 0.0f ? 0.0f : s * __expf(m - mm)) + (s2 == 0.0f ? 0.0f : s2 * __expf(m2 - mm));
    m = mm;
}
extern "C" __global__ void softmax_filas(const float* x, float* y, int d) {
    const float* fila = x + (size_t)blockIdx.x * d;
    float* sal = y + (size_t)blockIdx.x * d;
    const float MENOS_INF = __int_as_float(0xff800000);                              // -inf (NVRTC no trae math.h)
    float m = MENOS_INF, s = 0.0f;
    for (int j = threadIdx.x; j < d; j += blockDim.x) combina(m, s, fila[j], 1.0f);  // en línea: una lectura
    for (int o = 16; o > 0; o >>= 1)
        combina(m, s, __shfl_xor_sync(0xffffffff, m, o), __shfl_xor_sync(0xffffffff, s, o));
    __shared__ float sm[32], ss[32];
    int w = threadIdx.x >> 5, l = threadIdx.x & 31;
    if (l == 0) { sm[w] = m; ss[w] = s; }
    __syncthreads();
    if (w == 0) {
        m = (l < (blockDim.x >> 5)) ? sm[l] : MENOS_INF; s = (l < (blockDim.x >> 5)) ? ss[l] : 0.0f;
        for (int o = 16; o > 0; o >>= 1)
            combina(m, s, __shfl_xor_sync(0xffffffff, m, o), __shfl_xor_sync(0xffffffff, s, o));
        if (l == 0) { sm[0] = m; ss[0] = s; }
    }
    __syncthreads();
    m = sm[0]; float inv = 1.0f / ss[0];
    for (int j = threadIdx.x; j < d; j += blockDim.x) sal[j] = __expf(fila[j] - m) * inv;   // segunda lectura: de L2
}'''
filas, d = 4096, 4096
xs = torch.randn(filas, d, device="cuda", generator=g) * 4; ys = torch.empty_like(xs)
k_sm = Kernel(SOFTMAX, "softmax_filas")
def softmax_separada(z):
    m = z.max(dim=1, keepdim=True).values; e = torch.exp(z - m); return e / e.sum(dim=1, keepdim=True)
tiempos = {"cinco kernels": tiempo_gpu(lambda: softmax_separada(xs)),
           "torch.softmax": tiempo_gpu(lambda: torch.softmax(xs, dim=1)),
           "a mano (en línea)": tiempo_gpu(lambda: k_sm((filas,), (256,), xs, ys, d))}
print(f"error del kernel a mano: {(ys - torch.softmax(xs, 1)).abs().max().item():.1e}")
try:
    os.environ["TRITON_DISABLE_LINE_INFO"] = "1"         # sin información de líneas: ptxas falla si la ruta del código no es ASCII
    import triton, triton.language as tl
    @triton.jit
    def softmax_triton(X, Y, d, BLOQUE: tl.constexpr):
        fila = tl.program_id(0)                          # un programa por fila: todo el bloque de columnas a la vez
        cols = tl.arange(0, BLOQUE)
        z = tl.load(X + fila * d + cols, mask=cols < d, other=-float("inf"))
        z = z - tl.max(z, axis=0)
        e = tl.exp(z)
        tl.store(Y + fila * d + cols, e / tl.sum(e, axis=0), mask=cols < d)
    lanzar_triton = lambda: softmax_triton[(filas,)](xs, ys, d, BLOQUE=triton.next_power_of_2(d), num_warps=8)
    lanzar_triton()
    print(f"error de Triton: {(ys - torch.softmax(xs, 1)).abs().max().item():.1e}")
    tiempos["Triton"] = tiempo_gpu(lanzar_triton)
    sm_c = torch.compile(softmax_separada); sm_c(xs)
    tiempos["torch.compile"] = tiempo_gpu(lambda: sm_c(xs))
except Exception as e:
    print("Triton o torch.compile no disponibles aquí:", type(e).__name__, str(e)[:300])
for nombre, t in tiempos.items():
    print(f"{nombre:18s} {t * 1e3:6.3f} ms   {8 * filas * d / t / 1e9:5.0f} GB/s útiles (leer y escribir una vez)")
del xs, ys, x, res_, y
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The five PyTorch kernels achieve 51 GB/s “useful” (counting only one input read and output write): they move four times the necessary bytes and take 3.7 times longer than the hand-written kernel (2.63 versus 0.71 ms). Your online kernel, torch.softmax, Triton’s and torch.compile all land between 190 and 231 GB/s, near the memory ceiling: once fused, softmax has little more to gain, and differences among the four are on the order of run-to-run variation. A row’s second read comes nearly free from cache because a row of 4096 float32 occupies 16 KiB. The Triton kernel, describing the operation by blocks in a dozen lines, matches the hand-written ones.

From here to FlashAttention

Standard attention computes S=QK⊤\mat{S} = \mat{Q}\mat{K}\T, of N×NN \times N for sequence length NN, writes it to global memory, rereads it for softmax, writes P\mat{P} and reads it for O=PV\mat{O} = \mat{P}\mat{V}. Dao, Fu, Ermon, Rudra and Ré (FlashAttention, 2022) reorganize it with exactly this lesson’s two ideas: Q\mat{Q}, K\mat{K} and V\mat{V} tiles fitting in shared memory, and online softmax allowing O\mat{O} accumulation without materializing S\mat{S} or P\mat{P}. Their theorem 2 gives global-memory accesses: Θ(Nd+N2)\Theta(Nd + N^2) for standard attention and Θ(N2d2/M)\Theta(N^2 d^2 / M) for FlashAttention, with dd head dimension and MM fast-memory size (d≤M≤Ndd \le M \le Nd). In figure 2, GPT-2 medium (1024-token sequences, 64-dimensional heads, 16 heads, batch 64) on an A100 uses 66.6 GFLOP and moves 40.3 GB in 41.7 ms for standard attention (forward and backward), while FlashAttention does more computation, 75.2 GFLOP (recomputing S\mat{S} in backward instead of storing it), but moves 4.4 GB and takes 7.3 ms. Fewer bytes beat fewer flops.

Profiling: from timeline to kernel

Optimizing without measurement is guessing. Profiling has two scales, each answering a different question.

  • Which kernels consume time, and are there gaps between them? The timeline: torch.profiler, used in profiler traces, and Nsight Systems (nsys), which adds CPU activity, copies, streams and CUDA API calls. Find tiny kernels that do not amortize launch, unnecessary synchronizations (.item() in the loop) and copies that do not overlap.
  • Why does this kernel take its time? Kernel analysis: Nsight Compute (ncu) repeats it while reading SM hardware counters and compares achieved performance with hardware potential.

Stall reasons are the most direct diagnostic. The most common, according to the Nsight Compute profiling guide:

CauseWhat the warp waits forTypical indication
long_scoreboardresult of an L1TEX operation (global, local or texture memory)unhidden global-memory latency: low occupancy or little per-thread parallelism
lg_throttlespace in the L1 queue for global or local memory instructionstoo many small memory instructions: vectorize loads
short_scoreboardresult of an MIO operation such as a shared-memory readdependency on shared-memory reads (or special functions)
mio_throttlespace in the MIO queue (shared memory, special functions, dynamic branches)saturated shared memory or bank conflicts
barrierother block warps at an __syncthreads()imbalanced work before barrier or very large blocks
math_pipe_throttlea busy compute unitkernel is compute-bound: desirable in matmul
not_selectednothing: it was ready and the scheduler chose anotherplenty of warps; not a problem

The lesson’s results let you form hypotheses that ncu confirms or refutes. The T=32T = 32 tiled kernel should show barrier stalls (1024 threads waiting each phase) and shared-memory stalls (mio_throttle or short_scoreboard), with high shared-memory and low FMA throughput. Register tiling should shift the weight toward math_pipe_throttle and not_selected. Unpadded transpose should show bank conflicts in the shared-memory section even if time is unchanged, because DRAM is its bottleneck.

Commands from a terminal with the lab environment active:

# línea temporal de todo el programa (Nsight Systems): abre el .nsys-rep con la interfaz gráfica
nsys profile -t cuda,nvtx,osrt -o traza python entrena.py
# análisis completo de los kernels cuyo nombre empiece por mm_ (Nsight Compute), cinco lanzamientos como mucho
ncu --set full -k regex:^mm_ -c 5 -o informe python laboratorio.py
ncu --import informe.ncu-rep --page details      # o ábrelo en ncu-ui

ncu repeats each kernel many times to read all counters (with --set full, dozens of passes): a kernel modifying inputs, such as one accumulating with atomics, is profiled on different data each pass, and the report is slow to generate. Filter kernels with -k and limit count with -c. Windows requires an additional step, the last common mistake in this lesson.

The cell below does two things without installing anything else. It asks the driver your kernels’ theoretical occupancy, as Nsight Compute calculates from requested registers and shared memory, and profiles several training steps of a transformer MLP block with torch.profiler to divide GPU time between matmuls and the rest.

[ ]Theoretical occupancy and a training timelineLocal GPU
print(f"{'kernel':34s} {'hilos/bloque':>12s} {'regs/hilo':>9s} {'compartida':>10s} {'bloques/SM':>10s} {'ocupación':>9s}")
candidatos = [("mm_ingenuo", k_ing, 256)] + [(f"mm_tiles T={T}", k_tiles[T], T * T) for T in (8, 16, 32)] + \
             [(f"mm_registros {BM}, {TM}x{TM}, relleno {r}", k_reg[(BM, TM, r)], BM * BM // (TM * TM)) for (BM, TM, r) in k_reg]
for nombre, k, h in candidatos:
    bl = k.bloques_por_sm(h)
    print(f"{nombre:34s} {h:12d} {k.registros():9d} {k.smem_estatica():9d}B {bl:10d} {bl * h / 1536:9.0%}")

import torch.nn as nn
from torch.profiler import profile, ProfilerActivity
torch.manual_seed(0)
mlp = nn.Sequential(nn.Linear(1024, 4096), nn.GELU(), nn.Dropout(0.1), nn.Linear(4096, 1024)).cuda()
opt = torch.optim.AdamW(mlp.parameters(), lr=1e-3)
xb, yb = torch.randn(8192, 1024, device="cuda"), torch.randn(8192, 1024, device="cuda")
def paso():
    opt.zero_grad(set_to_none=True)
    F.mse_loss(mlp(xb), yb).backward()
    opt.step()
for _ in range(3): paso()                               # calentamiento: handles de cuBLAS, selección de algoritmos
torch.cuda.synchronize()
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
    for _ in range(5): paso()
    torch.cuda.synchronize()
por_clase, n_kernels = {"matmul": 0.0, "resto": 0.0}, 0
for ev in prof.events():
    if ev.device_type == torch.autograd.DeviceType.CUDA:
        nm = ev.name.lower()
        es_mm = any(s in nm for s in ("gemm", "xmma", "cutlass", "s1688", "s16816", "sgemm"))
        por_clase["matmul" if es_mm else "resto"] += ev.device_time
        n_kernels += 1
tot = sum(por_clase.values())
print(f"\n5 pasos: {n_kernels} kernels, {tot / 1e3:.1f} ms de GPU; matmuls {por_clase['matmul'] / tot:.0%}, resto {por_clase['resto'] / tot:.0%}")
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=8, max_name_column_width=40))
del mlp, opt, xb, yb
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The occupancy table is what Nsight Compute would calculate, with a surprise. The 8×88 \times 8 register-tiling kernel requests 126 registers per thread, so only two 256-thread blocks fit per SM: 33% occupancy, the lowest of all, and its unpadded version was your fastest (6634 GFLOP/s). 4×44 \times 4 (48 registers, 83%) and tiled versions (100%) have much higher occupancy yet lower throughput. Each 8×88 \times 8 thread has 64 independent FMA per step: it finds latency-hiding parallelism within the thread rather than in warp count. This is Volkov’s “better performance at lower occupancy”: occupancy is a means, not an end.

In MLP block training (batch 8192, 1024→4096→10241024 \to 4096 \to 1024), five steps launch 155 kernels and matmuls take 79% of GPU time, above the motivating BERT’s 61% because here there is no attention or normalization, only two huge linear layers. Kernel names in the table reveal much: ampere_sgemm_128x64_tn or ampere_sgemm_64x64_nn are float32 matmuls without Tensor Cores (sgemm), with block tiles 128×64128 \times 64 or 64×6464 \times 64 like yours, and transposed or nontransposed matrices (t, n) depending on forward or gradient. These Ampere-generation kernels are also used by cuBLAS on Ada. Enable TF32 or autocast and others appear.

Massive Monte Carlo on the GPU

A Monte Carlo estimator with NN samples has typical error σ/N\sigma/\sqrt{N}: gaining one digit requires a hundredfold increase in samples. A GPU generates and processes hundreds of millions of samples per second, but computation needs three precautions:

  • Parallel reproducible generators. PyTorch’s CUDA generator is Philox4x32-10, the same counter-based generator just implemented: every number is a pure function of seed and position, so thousands of threads generate their parts without coordination and the complete sequence is reproducible. torch.Generator(device="cuda").manual_seed(s) sets the seed; each call advances an internal offset.
  • Batches fitting in 8 GB. 10910^9 normals in float32 occupy 4 GB, and every intermediate operation creates another tensor of the same size. Process 2242^{24}-sample batches (64 MiB per tensor) and accumulate only sums.
  • Careful accumulation. Each batch is tree-reduced (torch.sum) and batch sums accumulated in float64. Then float32 generation precision suffices: rounding error is well below Monte Carlo error.

The example is European call pricing in the Black–Scholes model, which has a closed formula to check results: with ST=S0exp⁡((r−σ2/2)T+σTZ)S_T = S_0 \exp((r - \sigma^2/2)T + \sigma\sqrt{T}Z) and Z∼N(0,1)Z \sim \Normal(0, 1), price is e−rTE[max⁡(ST−K,0)]e^{-rT}\E[\max(S_T - K, 0)]. Quantitative finance’s Monte Carlo pricing uses exactly this pattern, and GPU scientific simulations of multilevel Monte Carlo or finite-difference stencils reuse the same pieces: counter-based generation, bounded batches, tree reductions and shared-memory tiles.

[ ]Monte Carlo with 10^9 Philox samples in float32 and float64Local GPU
S0, K_, r_, sig, Tm = 100.0, 110.0, 0.05, 0.2, 1.0
Phi = lambda z: 0.5 * (1 + math.erf(z / math.sqrt(2)))
d1 = (math.log(S0 / K_) + (r_ + sig**2 / 2) * Tm) / (sig * math.sqrt(Tm)); d2 = d1 - sig * math.sqrt(Tm)
exacto = S0 * Phi(d1) - K_ * math.exp(-r_ * Tm) * Phi(d2)

def mc_call(N, lote, dt, semilla):
    g = torch.Generator(device="cuda"); g.manual_seed(semilla)
    s1 = torch.zeros((), dtype=torch.float64, device="cuda"); s2 = torch.zeros_like(s1)
    s32 = torch.zeros((), dtype=torch.float32, device="cuda")       # acumulador entre lotes en float32, para comparar
    a, b = (r_ - sig**2 / 2) * Tm, sig * math.sqrt(Tm)
    for i in range(0, N, lote):
        z = torch.randn(min(lote, N - i), device="cuda", dtype=dt, generator=g)
        pago = torch.clamp(S0 * torch.exp(a + b * z) - K_, min=0)
        s1 += pago.sum(dtype=torch.float64); s2 += (pago * pago).sum(dtype=torch.float64); s32 += pago.float().sum()
    media = s1.item() / N
    D = math.exp(-r_ * Tm)
    return D * media, D * math.sqrt((s2.item() / N - media**2) / N), D * s32.item() / N

print(f"precio exacto (Black-Scholes): {exacto:.6f}")
for dt in (torch.float32, torch.float64):
    torch.cuda.synchronize(); t0 = time.perf_counter()
    v, et, v32 = mc_call(10**9, 1 << 24, dt, semilla=7)
    torch.cuda.synchronize(); t = time.perf_counter() - t0
    print(f"{str(dt):14s} {v:.6f} ± {et:.6f}  (error {v - exacto:+.6f} = {(v - exacto) / et:+.2f} errores típicos)  "
          f"{t:5.2f} s, {1e9 / t / 1e6:5.0f} M muestras/s;  acumulando en float32 entre lotes: {v32:.6f}")
v1, v2 = mc_call(10**8, 1 << 24, torch.float32, 7)[0], mc_call(10**8, 1 << 24, torch.float32, 7)[0]
v3 = mc_call(10**8, 1 << 22, torch.float32, 7)[0]
print(f"misma semilla y lote, dos veces: {'idénticos' if v1 == v2 else 'distintos'};  con otro tamaño de lote: {v3:.6f} frente a {v1:.6f}")
print(torch.cuda.memory_summary(abbreviated=True).splitlines()[5:9])
torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The exact price is 6.040088. With 10910^9 samples in float32, the estimate is 6.039973±0.0003686.039973 \pm 0.000368, 0.31 standard errors from exact: expected for correct Monte Carlo. In float64 it is 6.039767, 0.87 standard errors away: different 10910^9 normals (the generator produces different numbers per precision), equally valid. float32 rounding is invisible: far below Monte Carlo error 3.7×10−43.7 \times 10^{-4}. Accumulating between batches in float32 (6.039974) does not matter here either: only 60 batch sums. Tree reduction inside each batch protects accuracy; accumulate in float64 anyway, because smaller batches or 101210^{12} samples would matter.

float32 processes about 2000 million samples per second and float64 640 million: 3.1 times less, far from the factor 40 between cuBLAS peaks, because generation and memory traffic matter as much as arithmetic here. The same seed and batch size yield identical results; another batch size yields another value (6.039859 versus 6.039830): each generator call consumes a Philox sequence segment dependent on requested tensor size, so reproducing a result requires fixing batch size too. Peak PyTorch memory was 1088 MiB, well below 8 GiB.

Your RTX 4060 roofline

You now have everything needed to draw your GPU roofline using your numbers and place each lesson kernel on it.

The ceilings are yours. Global memory: 212 GB/s from vector addition with n=226n = 2^{26}. Compute: cuBLAS GFLOP/s with n=2048n = 2048 in each precision, your best measurement rather than manufacturer peak. Shared memory: both microbenchmark ceilings, 3.6 TB/s with 4-byte reads and 6.6 TB/s with 16-byte reads. Each point’s intensity comes from an explicit byte model:

  • Vector addition: 1/121/12 flops per byte.
  • Matmul relative to global memory: at minimum each matrix crosses DRAM once, 3n2s3n^2 s bytes for 2n32n^3 flops, or 2n/(3s)2n/(3s): 341 flops per byte in float32 and TF32, 683 in 16-bit and 171 in float64 with n=2048n = 2048. All matmuls share this value because it is a problem bound, not kernel bound.
  • Matmul relative to shared memory (or L1): bytes each FMA needs from it, from the reads-per-FMA theorem. 0.250.25 flops per byte for naive and tiled versions reading 4 bytes at a time; 1 and 2 for 4×44 \times 4 and 8×88 \times 8 register tiling reading contiguous 16-byte groups.
  • Row softmax: 5 operations per element (maximum, subtraction, exponential, sum and multiplication by inverse) and 8N8N numbers of traffic in five kernels, 5/325/32 flops per byte, versus 2N2N in the fused version, 5/85/8. GFLOP/s is those 5N5N operations divided by measured time.

With global memory, a one-level roofline does not explain your matmuls: all lie far right of the float32 balance point (31 flops per byte), so all should reach peak, yet they range from 541 to 6634 GFLOP/s. Shared memory orders them. Naive and tiled versions sit at 0.250.25 flops per byte with a 900 GFLOP/s ceiling and reach 60–81%. Register tiling moves them to 1 and 2 flops per byte, where the ceiling is 6.6 TFLOP/s or compute peak, achieving 6.5 to 9 times the T=16T = 16 tiled kernel. Both softmaxes instead stay on the global-memory diagonal (96% and 89% of ceiling): fusion does not change the ceiling, but quadruples intensity and performance. Read-only kernels can exceed vector-add throughput slightly (torch.sum achieved 241 GB/s), so such a point may lie just above the line.

InteractiveYour RTX 4060 roofline
1/321/81/2283212851220481101001 T10 T100 Tflops per byte of global memoryGFLOP/s (1 T = 1000)float64float32float16additionnaivetiles 16registers 4×4registers 8×8cuBLAS float16cuBLAS float64softmax ×5fused softmax
  • global memory ceiling
  • memory (vector addition)
  • custom matmuls
  • cuBLAS
  • softmax
If each matrix crosses global memory once, any float32 matmul with n = 2048 performs n/6 = 341 flops per byte: far to the right of the ridge point. According to this roofline, all your matmuls should reach the peak, yet mm_tiles T = 16 reaches 11% of its ceiling. Global memory is not the bottleneck: switch to “Shared memory”.
Intensity relative to
Compute ceilings (cuBLAS, measured)
Global bandwidth (vector addition)212 GB/s
Ridge point at float3231 flops/B
Intensity of mm_tiles T = 16341.3 flops/B
Measured729 GFLOP/s
Ceiling at this intensity6.66 TFLOP/s
Fraction of ceiling11 %
Lab-measured ceilings: global-memory bandwidth (vector addition) and cuBLAS peaks in float64, float32, TF32, float16 and bfloat16; with “Shared memory”, both bank-microbenchmark bandwidths (16-byte reads solid, 4-byte reads dashed). Points are lesson kernels at their intensity and measured GFLOP/s. Start with global memory: all matmuls have the same intensity yet very different performance. Switch to shared memory to see why. Toggle each precision ceiling.

Common mistakes

Exercises

NumericVector-add arithmetic intensity
What is arithmetic intensity in flops per global-memory byte for vector addition z=x+y\vb{z} = \vb{x} + \vb{y} with large-length nn float32 vectors?
NumericOccupancy of the 32 tile
The T=32T = 32 tiled kernel uses 32×3232 \times 32-thread blocks, 8 KiB shared memory and 38 registers per thread (per the lab driver). An RTX 4060 SM supports at most 1536 threads, 24 blocks, 65536 registers and 100 KiB shared memory. What is theoretical occupancy as a percentage?
NumericA stride of six
A warp's 32 threads read 4-byte shared-memory words at index 6ℓ6\ell, with ℓ=0,…,31\ell = 0, \dots, 31. How many passes does the access need?
NumericChain bytes in bf16
The bias → GELU → dropout → residual-add chain runs in bfloat16 (s=2s = 2 bytes) over NN elements with d≪Nd \ll N. Four separate kernels move 9sN+N9sN + N bytes (dropout stores one mask byte per element), and the fused version regenerating the mask moves 3sN3sN. What is separate-to-fused byte ratio?
QuizConjugate gradient and TF32
You solve eight systems Ax=b\mat{A}\vb{x} = \vb{b} simultaneously on GPU with conjugate gradient in float32, with symmetric positive-definite A\mat{A} of condition number 10210^2, requiring relative residual 10−510^{-5}. After enabling torch.backends.cuda.matmul.allow_tf32 = True, the method's computed residual falls to 10−610^{-6}, but the true residual ∥b−Ax^∥/∥b∥\norm{\vb{b} - \mat{A}\hat{\vb{x}}}/\norm{\vb{b}} stays around 10−310^{-3}. Why?
CodeOne-dimensional register tiling
Write CUDA code in FUENTE for kernel mm_ejercicio(const float* A, const float* B, float* C, int n) and in lanzar(k, A, B, C, n) the launch call with your grid and block, so for n=2048n = 2048 it is at least 2 times faster than tiled kernel mm_tiles with T=16T = 16 (the test takes the median of three interleaved measurements), and relative error versus the float64 product is below 10−510^{-5}. You may assume nn is divisible by 64. Starter code is the tiled kernel itself, insufficient by definition. Use one-dimensional register tiling: each thread computes one column of TM=8TM = 8 elements of C\mat{C} and for each kk reads one shared-memory B\mat{B} value reused in its 8 products (do not copy the lab's 2D kernel). You have Kernel, tiempo_gpu and TILES from prior cells.
FUENTE = TILES.replace("mm_tiles", "mm_ejercicio")

def lanzar(k, A, B, C, n):
  k((n // 16, n // 16), (16, 16), A, B, C, n)

DEFINES = {"T": 16}
Shift+Enter to run

Summary

Key idea
A kernel performs well when data fetched from slow memory is reused many times from fast memory: shared-memory tiles, register tiles, Tensor Cores fed by both, and fused kernels that do not write what nobody reads. Measure which ceiling limits you before optimizing: your GPU’s multilevel roofline tells you.
  • Shared-memory tiling divides matmul’s global-memory requests by TT, but large GPU caches make this insufficient: each FMA still needs two operands from L1 or shared memory. Register tiling divides that need by 2 TM TN/(TM+TN)2\,TM\,TN/(TM + TN) (8 with 8×88 \times 8), bringing a kernel near cuBLAS.
  • Shared memory has 32 banks; an ss-stride access needs gcd⁡(s,32)\gcd(s, 32) passes. A padding column fixes tile columns, but correct padding depends on the pattern, and conflict costs time only when shared memory is the bottleneck.
  • Reductions use trees (shared memory and warp shuffles), faster and more accurate than sequential summation. Atomics make results arrival-order dependent: do not compare bit for bit. Scans have work-efficient (Blelloch) and single-pass (decoupled look-back) versions.
  • Tensor Cores multiply fragments with low-bit inputs and FP32 accumulation. Error is dominated by input rounding (u=2−11u = 2^{-11} in TF32 and FP16, 2−82^{-8} in BF16) and, for 16-bit output, output rounding; a three-line model predicts it to three figures. TF32 is enabled separately for matmul and convolution, and suffices to break an iterative method requiring 10−610^{-6}.
  • An elementwise-operation chain is memory-bound: fusing it into a kernel reading once and writing once speeds it in proportion to bytes saved. Online softmax fuses two reductions in one pass, and with tiles gives FlashAttention.
  • Profile at two scales: timelines (torch.profiler, Nsight Systems) show kernels and gaps; Nsight Compute shows why a kernel takes time (throughput versus maximum, theoretical and achieved occupancy, stall reasons).
  • An 10910^9-sample Monte Carlo fits in 8 GB in batches, with reproducible Philox and tree-reduced batch sums accumulated in float64.

In the next lesson, mixed precision with iterative refinement answers the question left open by conjugate gradient: how to exploit Tensor Core speed without giving up float64 precision. In the inference module you will write these kernels in Triton, from tiled matmul to FlashAttention, and tiled attention explains every line of its algorithm.