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
- 09SIMT GPU architectureCUDA execution modelGPU memory hierarchyMemory coalescingOccupancy and latency hidingCUDA streams and copy-compute overlapLoop tiling (blocking)Roofline modelBLAS, LAPACK and the SciPy stackIEEE 754 and deep learning formatsRecursive and pairwise summationMonte Carlo error and confidence intervalsCounter-based RNGs
- 00PyTorch tensorDevice placement and CPU-GPU transfersOperator fusiontorch.profiler traces
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 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.
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())npm run lab and open the connection link.Theoretical bandwidth follows the usual formula: GDDR6 transfers two data items per clock cycle, so GB/s. That is the manufacturer’s memory ceiling; what matters is what you reach.
Vector addition: the memory ceiling
in float32 performs 1 flop per element and moves 12 bytes (two 4-byte reads and one write): arithmetic intensity 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.
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, znpm run lab and open the connection link.While the three vectors fit in 32 MiB L2 ( and , 12 and 24 MiB), the kernel exceeds 900 GB/s: L2 serves over four times faster than DRAM. With it drops to 165 GB/s because each launch moves only 3 MiB and fixed launch cost matters. From (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 , 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 element, with 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 (broadcast) and 32 consecutive elements of an 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 numbers from global memory for flops, and the whole kernel requests : each element of and is requested times. If every request went to DRAM, intensity would be 2 flops per 8 bytes, , and with the kernel would take s. Reuse is enormous and unused: all threads in a block row read the same row.
The solution is the CPU’s one level lower. An -thread block computes an tile of and traverses the product in phases: each phase threads cooperatively load one tile and one tile into shared memory (each thread fetches one element of each), synchronize, and each thread accumulates its 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 , not only multiples of . 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 blocks, each traversing phases. Each phase loads numbers (one tile and one tile), totaling . The kernel performs flops with requested bytes, or flops per byte. Both -float tiles occupy bytes.
∎Tile size has two bounds. , because a block cannot exceed 1024 threads, so with one element per thread. Shared memory per block and per SM is finite: with 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 (1024 threads per block) only one block fits per SM and occupancy falls to 67%; with six 256-thread blocks fit, 100%.
What your GPU measures
Time to measure. The cell compiles naive and tiled versions with , runs them with , checks error against a product in float64 and asks the driver for registers per thread and blocks fitting per SM.
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%}")npm run lab and open the connection link.All four kernels are correct and share error from summing 2048 products in float32. The driver confirms occupancy calculations: 67% with (one 1024-thread block per SM) and 100% with the others; with 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, is slower (541), and and 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 bytes GB in 26.1 ms, 2.6 TB/s, twelve times DRAM capability. Almost no request reaches DRAM. Caches serve them: in an -thread block, a warp’s 32 threads request the same (one transaction), and all 8 warps request the same row segment, retained in SM L1; neighboring blocks reuse what remains in 32 MiB L2, fitting and (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 , one ) 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, flops per byte, their bottleneck. The bank-conflict section measures shared-memory throughput for 4-byte reads and shows 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 there are four times more blocks, each with two warps, and each 8-FMA phase pays loads, two barriers and loop overhead; with the block’s 1024 threads wait at every barrier for the slowest and only one block fits per SM. 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 (in 4-byte words) lives in bank . 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 and go to the same bank if and only if . With , that is equivalent to and, since and are coprime, to . The classes modulo each contain elements, so each used bank receives threads. Their addresses differ because . There is conflict if and only if , that is, is even.
∎The important case is reading a column of a row-major -float tile: thread reads tile[ℓ][c] at word . 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.
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:
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 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.
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, Mtnpm 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 : a two-way conflict is free (101%), and from four ways performance resembles (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 kernels (one element per thread) are limited by operand delivery from L1 and shared memory, not global memory.
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 element but a small block, retaining reused values in registers. At each step, the thread reads values from an tile column and from an tile row from shared memory, and performs FMA without rereading: the outer product of two small vectors.
Proof
At each step the thread performs 4-byte reads and FMA, or flops. Reads per FMA are and intensity . Substitution gives the three cases.
∎Moving from to multiplies shared-memory intensity eightfold. The cost is registers: accumulators plus operands are 80 floats per thread with , 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 tile of in steps loads numbers from global memory per phase and performs flops: flops per byte, 32 with . In the kernel below, each 256-thread block computes an tile and each thread an tile.
A loading detail explains constant RELLENO. The tile is stored transposed, As[k][r], so a thread’s reads are contiguous. While loading, consecutive warp threads read by rows (coalesced) and write As with varying fastest: thread writes word with and ( is the warp). Without padding, is divisible by 32 and bank is : only four banks for 32 threads, an 8-way conflict (the conflict-degree cell’s last pattern). With padding 4, bank is and traverses 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.
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}")npm run lab and open the connection link.The jump matches the theorem. With per thread, 4750 and 5054 GFLOP/s (without padding and with padding 4); with , 6634 and 4916: 6.5 to 9.1 times the tiled kernel. The best reaches cuBLAS in float32 (6658). Error remains because each is still summed in the same order.
Two details deserve attention. The 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 values of As and 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 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 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 add s[t] += s[t + p] and 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 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 is exactly pairwise summation: relative error is bounded by times (to first order), versus for sequential summation. The actual reduction is hybrid: with total threads, each sequentially sums about elements, then the tree combines partials, making the bound order . With and 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: and 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.
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, xcnpm 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 and , below float32 unit roundoff (). 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 , 50% error. Beyond , 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 for every . 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 , each with adds . It takes steps but additions when is a power of two: not work-efficient.
- Blelloch (1990): an upsweep (a reduction tree leaving partial sums at nodes, additions) and a downsweep distributing prefixes ( additions and as many swaps). It takes steps and work, like the sequential loop, and yields the exclusive scan ().
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 global-memory elements, the minimum.
scan_blelloch(x) returning the exclusive scan of a NumPy array x with power-of-two length (, ) 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, 0Tensor 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, is the unit roundoff of a format with mantissa bits:
| Format | Bits (sign, exponent, mantissa) | Maximum finite | |
|---|---|---|---|
| FP32 | 1, 8, 23 | ||
| TF32 | 1, 8, 10 (19 useful bits in a 32-bit container) | FP32’s | |
| FP16 | 1, 5, 10 | 65504 | |
| BF16 | 1, 8, 7 | FP32’s | |
| FP8 E4M3 | 1, 4, 3 | 448 | |
| FP8 E5M2 | 1, 5, 2 | 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 , negligible versus . 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 , with , to mantissa bits incurs absolute error that for generic data behaves uniformly on , with root mean square . Relative error has root mean square . For data whose mantissas follow Benford’s logarithmic law (density on , a good approximation for Gaussian data), . Each 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:
Output rounding is a third independent error with the same relative root mean square ( inputs also have “generic” mantissas), so with 16-bit output factor becomes : in FP16 and in BF16.
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")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 with 10 mantissa bits and with 7, versus predictions and . On Tensor Cores, TF32 gives : exactly input-rounding error, so FP32 accumulation adds nothing visible. float16 and bfloat16 give and , predictions with : the third rounding stores the result in 16 bits. Without TF32 the float32 product has error , 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_tf32controls matmul infloat32. Since PyTorch 1.12 it defaults toFalse.torch.set_float32_matmul_precision("high")enables it (TF32) and"highest"disables it;"medium"also allows internal BF16.torch.backends.cudnn.allow_tf32controls cuDNN convolutions and defaults toTrue: anfloat32convolutional network already uses TF32 on Ampere and later GPUs.- Recent versions add a finer interface,
torch.backends.cuda.matmul.fp32_precisionandtorch.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 with symmetric positive-definite using only products. If those products use TF32, each has relative error of order , and true residual cannot fall much below that. The cell checks this on GPU with eight systems at once (an matmul cuBLAS does execute on Tensor Cores) and with one (a matrix–vector product that does not):
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, S64npm run lab and open the connection link.All four runs stop at 72 iterations with recursive residual : by the method’s own account, all converged. True residual computed in float64 tells another story. In FP32 it is , the precision’s own limit: with factor 34 printed by the cell. With TF32 and eight systems it is , about 800 times worse, with nothing in the iterations revealing it: recurrence 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 ( in both cases).
The bound using , , is pessimistic by a factor of 6: is each rounding’s worst case, typical error for a product with TF32 inputs is the measured , and errors from different terms partly cancel. But order of magnitude rules: if you require residual , FP32 provides it and TF32 cannot.
Fused kernels
An elementwise operation on float32 numbers reads and writes 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 . In PyTorch eager mode these are four kernels. Counting global-memory bytes with elements, bias and bytes per number:
| Kernel | Reads | Writes |
|---|---|---|
| and mask, bytes | ||
In total bytes versus for the fused kernel, which reads , and and writes : with and , ratio . 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.
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")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 the kernel reproduces F.gelu(x + b) + r without difference, and with 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 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.
Row-wise softmax in one kernel
Row softmax, with , needs two reductions (maximum and sum) before writing anything. Expressed as PyTorch operations (max, subtraction, exp, sum, division), it takes five kernels and numbers of traffic. A fused kernel with one block per row can read the row, reduce in shared memory and write: 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 and partial sum together, updating on a new value:
Two pairs and from different chunks combine the same way: , . 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.
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_, ynpm 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 , of for sequence length , writes it to global memory, rereads it for softmax, writes and reads it for . Dao, Fu, Ermon, Rudra and Ré (FlashAttention, 2022) reorganize it with exactly this lesson’s two ideas: , and tiles fitting in shared memory, and online softmax allowing accumulation without materializing or . Their theorem 2 gives global-memory accesses: for standard attention and for FlashAttention, with head dimension and fast-memory size (). 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 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:
| Cause | What the warp waits for | Typical indication |
|---|---|---|
long_scoreboard | result of an L1TEX operation (global, local or texture memory) | unhidden global-memory latency: low occupancy or little per-thread parallelism |
lg_throttle | space in the L1 queue for global or local memory instructions | too many small memory instructions: vectorize loads |
short_scoreboard | result of an MIO operation such as a shared-memory read | dependency on shared-memory reads (or special functions) |
mio_throttle | space in the MIO queue (shared memory, special functions, dynamic branches) | saturated shared memory or bank conflicts |
barrier | other block warps at an __syncthreads() | imbalanced work before barrier or very large blocks |
math_pipe_throttle | a busy compute unit | kernel is compute-bound: desirable in matmul |
not_selected | nothing: it was ready and the scheduler chose another | plenty of warps; not a problem |
The lesson’s results let you form hypotheses that ncu confirms or refutes. The 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.
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, ybnpm run lab and open the connection link.The occupancy table is what Nsight Compute would calculate, with a surprise. The 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). (48 registers, 83%) and tiled versions (100%) have much higher occupancy yet lower throughput. Each 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, ), 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 or 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 samples has typical error : 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. normals in
float32occupy 4 GB, and every intermediate operation creates another tensor of the same size. Process -sample batches (64 MiB per tensor) and accumulate only sums. - Careful accumulation. Each batch is tree-reduced (
torch.sum) and batch sums accumulated infloat64. Thenfloat32generation 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 and , price is . 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.
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()npm run lab and open the connection link.The exact price is 6.040088. With samples in float32, the estimate is , 0.31 standard errors from exact: expected for correct Monte Carlo. In float64 it is 6.039767, 0.87 standard errors away: different normals (the generator produces different numbers per precision), equally valid. float32 rounding is invisible: far below Monte Carlo error . 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 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 . Compute: cuBLAS GFLOP/s with 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: flops per byte.
- Matmul relative to global memory: at minimum each matrix crosses DRAM once, bytes for flops, or : 341 flops per byte in
float32and TF32, 683 in 16-bit and 171 infloat64with . 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. flops per byte for naive and tiled versions reading 4 bytes at a time; 1 and 2 for and register tiling reading contiguous 16-byte groups.
- Row softmax: 5 operations per element (maximum, subtraction, exponential, sum and multiplication by inverse) and numbers of traffic in five kernels, flops per byte, versus in the fused version, . GFLOP/s is those 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 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 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.
Common mistakes
Exercises
float32 vectors?bfloat16 ( bytes) over elements with . Four separate kernels move bytes (dropout stores one mask byte per element), and the fused version regenerating the mask moves . What is separate-to-fused byte ratio?float32, with symmetric positive-definite of condition number , requiring relative residual . After enabling torch.backends.cuda.matmul.allow_tf32 = True, the method's computed residual falls to , but the true residual stays around . Why?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 it is at least 2 times faster than tiled kernel mm_tiles with (the test takes the median of three interleaved measurements), and relative error versus the float64 product is below . You may assume 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 elements of and for each reads one shared-memory 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}Summary
- Shared-memory tiling divides matmul’s global-memory requests by , but large GPU caches make this insufficient: each FMA still needs two operands from L1 or shared memory. Register tiling divides that need by (8 with ), bringing a kernel near cuBLAS.
- Shared memory has 32 banks; an -stride access needs 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 ( in TF32 and FP16, 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 .
- 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 -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.