Measure warp divergence from branch outcomes

Why it matters Kernel authors arrange branches by warp so attention masks and top-k do not halve throughput.

Threads in a 32-thread warp run in lockstep. If they take different branches, the warp runs both paths.

Write warp_efficiency(taken, warp=32). taken is a boolean list, one per thread (length a multiple of warp). For each warp, the number of passes is 2 if both True and False appear, else 1. Return (passes_total, efficiency) where efficiency = number of warps / passes_total.

Signaturedef warp_efficiency(taken, warp=32)

Example

64 threads where the first warp is all True and the second is mixed gives passes 3 and efficiency 2/3.

Understand the idea

On a GPU, threads run in groups called warps, usually 32 threads, that execute the same instruction together. If some threads in a warp take an if branch and others do not, the warp has to run both paths one after the other, with half the threads idle each time. A warp whose threads all agree needs only one pass. Worked example with warp = 4: taken = [F, F, F, F, T, F, F, F, T, T, F, F]. Warp 0 is all False, 1 pass. Warp 1 is mixed, 2 passes. Warp 2 is mixed, 2 passes. passes_total = 5 and efficiency = 3 warps / 5 passes = 0.6. Rule: split taken into consecutive chunks of size warp; a chunk costs 2 passes if it contains both True and False, else 1; efficiency = number of warps / passes_total. A warp that is all True is not divergent, only a mixed one is. Used in: reasoning about CUDA kernel performance, such as why branching on threadIdx in multiples of 32 or sorting work by type keeps warps uniform.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplewarp_efficiency([True] * 32 + [True, False] * 16)
  • Sample 2: uniformwarp_efficiency([False] * 64)
  • Test 3: thread id branchwarp_efficiency([i % 64 < 32 for i in range(128)])
  • Test 4: odd evenwarp_efficiency([i % 2 == 0 for i in range(96)])