100 days of CUDA challenge
Hi, I'm Pavel. I'm spending 100 days learning CUDA by writing GPU code every day and sharing what I figure out as I go. Most days, I'm solving kernel problems on LeetGPU or reading my way through Programming Massively Parallel Processors. I turn the useful bits into notes and animations to help them stick.
If you want to join the challenge, the rules come from hkproj/100-days-of-gpu.
Progress
Day 1
- learned that:
- CUDA stands for Compute Unified Device Architecture.
- the CUDA compiler is called NVCC (NVIDIA CUDA Compiler).
- CUDA is a platform with different levels of abstraction, either by language (e.g. python, c++, ptx) or by libraries. NVIDIA has put a ton of work into developing libraries to make developers' lives easier, for example:
- cuBLAS linear algebra
- cuFFT fast fourier transform
- cuDNN neural networks
- cuRAND random numbers
- found the NVIDIA accelerated-computing-hub resource, plenty of courses to choose from, thinking of doing the Python ones.
- watched the video What's CUDA All About Anyway?, a really great introduction to CUDA.
- created my first two CUDA kernels:
Day 2
-
learned about the CUDA execution hierarchy: grid -> block -> thread:

// blockDim.x = 4, blockDim.y = 3 → 12 threads per block dim3 block(4, 3); // gridDim.x = 2, gridDim.y = 2 → 4 blocks dim3 grid(2, 2); // 48 threads total kernel<<<grid, block>>>();// 0 .. 7 int col = blockIdx.x * blockDim.x + threadIdx.x; // 0 .. 5 int row = blockIdx.y * blockDim.y + threadIdx.y; // 0 .. 47, unique // gridDim.x * blockDim.x is the total grid width in threads (8 here) int index = row * (gridDim.x * blockDim.x) + col;
- grid limits in all three dimensions: x <= 2^32-1, y <= 65535, z <= 65535, if you do the math that is about 18.9 sextillion threads in total. which is pretty crazy number when you think about it... practical speaking in an RTX 5090 the max number of threads running at once is given by Num. SMs x 2048 around 348,160 threads, so is not like you can run all those threads :)
- also block size limits in all three dimensions is as follow: x <= 1024, y <= 1024, z <= 64. important that x * y * z <= 1024, so the max number of threads per block is cap to 1024.
- looked into how CUDA compilation works: it separates the program into host and device paths.

- solved my first easy problem on LeetGPU, a matrix transpose kernel, hmm starting to understand the indices joggling of CUDA:
Day 3
-
solved another easy LeetGPU problem, matmul, this one took longer than expected. the sequential version has three nested loops, in CUDA the two outer loops go to the threads, leaving only the inner dot-product loop. the tricky part is the array flattening part, really easy to mess up, i guess it gets better with practice.

Matrix multiplication: row of A · column of B.

Same thing with flattened arrays.
- since my matmul implementation is quite naive, i got curious about how this is done efficiently. i found this great article, more fun for later :)
- https://siboehm.com/articles/22/CUDA-MMM
- ran across Flynn's taxonomy, nice for perspective, i knew SIMD from CPU land but never the full taxonomy:
- https://en.wikipedia.org/wiki/Flynn%27s_taxonomy
- also learned how the CUDA software model maps onto the actual hardware, nice mental model to keep in mind:

Day 4
- learned a bit about warps:
- the hardware splits each CUDA block into warps of 32 threads.
- a warp is always (at least until now) 32 threads, even a block with a single thread takes up a full warp.
- resources like shared memory are allocated per warp, not per thread.
- all 32 threads execute the same instruction together at the same time, so if a conditional (like
if) splits them into different paths, each path runs one after the other, that's warp divergence, and it's slow and not cool...
- solved three LeetGPU problems: Color Inversion, RGB to Grayscale and Reverse Array.
-
the problems were mostly image transformations tasks. the images were given as a flatten array, for both problems once you extract the indices as follow, the calculations were easy.
int channels = 4; int pixel = blockDim.x * blockIdx.x + threadIdx.x; if (pixel < width * height) { int idx = pixel * channels; ... }
- watched the video Unlocking GPU Performance with CUDA Tile:
- highly recommended, really insightful Q&A session.
- in short with cuTile we can program on tiles of data, the compiler handles the threads for you.
- this is different than traditional SIMT, where the developer is in charge of the threads.
- https://www.youtube.com/watch?v=uiIdk61UxEs
Day 5
- optimized the LeetGPU problem matrix add with
float4each thread now reads and writes 4 floats at once, so 4x fewer memory instructions
- solved the LeetGPU problems 1D Convolution, ReLU and Leaky ReLU.
- continued learning about warps:
-
learned about branch efficiency, a simple metric for measuring warp divergence:
- during execution, warps pass through different states in the SM: - active: assigned to the SM, registers and memory allocated - selected: actively executing instructions - stalled: not ready to execute, waiting on something (memory load, barrier, etc.) - eligible: ready to execute, waiting for the schedulerbranch efficiency = (num. branches - num. divergent branches) / (num. branches)
-
here is the SM warp scheduler in action:

-
read a bit about latency:

Day 06
- solved the LeetGPU problems: Rainbow Table, Copy Matrix, SiLU, SwiGLU, Value Clipping and Interleave Arrays. nearly done with all the easy problems.
- did a few variants of Copy Matrix and Interleave Arrays with vectorized loads/stores (
float4,float2) to reduce the number of memory instructions.
-
learned about the GPU memory hierarchy and the relative latency of each level. here is what it looks like on an H100:


-
watched the video "Interview with NVIDIA CUDA Architect Stephen Jones", thanks to the youtube algorithm for this one. it's an informal discussion about CUDA, really helpful!
- https://www.youtube.com/watch?v=dNUMNifgExs
-
finally got the 5th Edition of Programming Massively Parallel Processors! took some time to deliver since it was not available on amazon.de and had to be ordered from the US. in the coming days i will go through the chapters and share my learnings:

Day 07
- solved the LeetGPU problems: GEGLU and Sigmoid. with this, all the LeetGPU easy problems are done! :)
-
half way through the first chapter of Programming Massively Parallel Processors, taking notes along the way and will post them once i'm done. the book also has a youtube channel, worth a look:
- https://www.youtube.com/@pmpp-book
-
ran into the course "Heterogeneous Parallel Programming" by Prof. Wen-mei Hwu, one of the authors of the book. thinking of using it as supplementary material:
- https://www.youtube.com/watch?v=kZy4JD8Z6KA&list=PLzn6LN6WhlN06hIOA_ge6SrgdeSiuf9Tb&index=1
Day 08
-
solved my first LeetGPU medium problem: Reduction. this was a nice one, until now i was only doing transformations, where the output has the same number of elements as the input. reductions are a bit more tricky, all the threads have to cooperate to produce a single value. first time i actually needed
__shared__,__syncthreads()andatomicAdd, here is an animation how the process actually looks:
- finished chapter 1 of Programming Massively Parallel Processors, my notes are here: chapter 1
-
found another really nice CUDA course by Bob Crovella from NVIDIA, the explanations are excellent:
- https://www.youtube.com/watch?v=OsK8YFHTtNs&list=PL6RdenZrxrw-zNX7uuGppWETdxt_JxdMj&index=1
Day 09
- solved two more LeetGPU medium problems: Dot Product and Softmax.
- dot product was basically yesterday's Reduction problem again.
-
the softmax one was more interesting, i ended up using three kernels: global max (for avoiding overflow), sum of
exp(x - max), then the final calculation.
- til: there's no
atomicMaxfor floats, had to hack around it withatomicCAS, pretty ugly stuff... need to re-do the softmax at some point.
- started chapter 2 of Programming Massively Parallel Processors, should finish it tomorrow.
Day 10
- solved two more LeetGPU medium problems: Count Array Element and Mean Squared Error. both are variations of the Reduction problem from day 8, this pattern is used in many problems.
- finished chapter 2 of Programming Massively Parallel Processors.
Day 11
-
solved three more LeetGPU medium problems: 2D Convolution, Gaussian Blur and Jacobi Stencil. nothing super special about these, but they demand being extremely careful with the indices and boundary conditions. i'm starting to feel comfortable with row-major indexing. would like to try optimized versions of these later, currently my solutions are not optimized at all.

- read the article A Gentle Introduction to CUDA PTX, indeed a really "gentle" introduction to PTX: it covers the basic instructions, where PTX fits in the CUDA compilation pipeline, and the cli commands to inspect and work with it. highly recommended. it also links to the Inline PTX Assembly docs, which teach you how to inline PTX in your kernels. i'm not at that level of ninja yet, but soon ;)
- started chapter 3 of Programming Massively Parallel Processors. i've already picked up some of the chapter concepts by doing LeetGPU problems, but it's good to take a step back and revisit them properly.
Day 12
- solved two more LeetGPU medium problems: Count 2D Array Element and Count 3D Array Element. more indexing practice on top of day 10's reduction pattern.
- learned about warp-level primitives: threads in the same warp can read each other's registers with
__shfl_down_sync, no shared memory needed. used it in a new version of Reduce.
- learned about memory coalescing, how the gpu merges a warps loads into one request and fetches as few 128-byte segments as possible.
-
learned about shared memory bank conflicts: shared memory
__shared__is split into 32 banks, and when threads in a warp hit different words in the same bank the access becomes sequential, one thread at a time.
Day 13
-
solved another LeetGPU medium problem: Prefix Sum. the trickiest one so far... i was not able to solve it on my own, i watched the lectures Prefix Sum Scan Part 1 & Part 2.

-
til:
- the prefix sum is part of a problem family called "Scan". the name comes from the scan operator in Ken Iverson's APL (1962): https://en.wikipedia.org/wiki/APL_(programming_language)
- many libraries implement scan operations: CUB ->
BlockScanandDeviceScan, Thrust ->inclusive_scan, C++17 ->std::inclusive_scan, and MPI ->MPI_Scan.
Day 14
- solved two more LeetGPU medium problems: Softmax Attention and GEMM (FP16).
- the GEMM (General matrix multiply) one is a naive implementation of matmul (for now), the problem requires to use
halfprecision, but you need to make sure all calculations are done infloatto avoid rounding errors.
-
the softmax attention solution i came up with is 3 kernels: (1) the portion that multiplies the queries (Q) by the keys transpose (K^T), (2) the softmax part, and (3) finally a matmul with the values (V). technically i could have used the same matrix multiplication kernel for both 1 and 3, but then a memory allocation would be needed for K^T, so i decided to just keep those two separated.

- finished chapter 3 of Programming Massively Parallel Processors, link to my notes: chapter 3
- started chapter 4. in the next few days i'll revisit some of my LeetGPU solutions and optimize them with what i've learned from the book.
Day 15
- no new problems today, i revisited the LeetGPU GEMM problem. i wanted to improve the naive implementation from yesterday, and i found this blog post by Simon Boehm: How to Optimize a CUDA Matmul Kernel for cuBLAS-like Performance: a Worklog.
- it's an excellent step-by-step guide, going from a naive GEMM kernel to something close to cuBLAS, explaining the decisions behind each optimization, highly recommended!
- i had the time to apply the first two optimizations from the article: GEMM - Global Memory Coalescing and GEMM - Shared Memory Caching, which took the naive solution from 26 ms to 6.85 ms. still a long way to go... the top solutions in LeetGPU are in the 0.15 - 0.60 ms range.
Day 16
- solved another LeetGPU problem: Subarray Sum, the problem is interesting enough so i ended up implementing it in three different ways. the first approach calculates the prefix sum and uses the generated array to compute the answer. it is a bit of overkill, but it gives O(1) queries once the prefix sum array is pre-calculated with a kernel. the other two approaches are classical reductions, we just need to make sure any value we consider is within the range [S, E], otherwise we assign a 0 to the new input array.
- read a few more pages of Programming Massively Parallel Processors, almost done with chapter 4.
Day 17
- solved the 2D version of yesterday's problem: 2D Subarray Sum, again with three implementations at different levels of optimization: subarray_sum_2d, subarray_sum_2d_2 and subarray_sum_2d_3.
-
finished chapter 4 of Programming Massively Parallel Processors, link to my notes: chapter 4

Day 18
- solved the LeetGPU Dot Product (FP16) problem and tried to optimize it as much as possible using warp shuffles and vectorized
float4loads: vectorized version.
- i'm still amazed by how much effort it takes to write a performant dot product. the end result is pretty much unreadable to someone with no CUDA experience. a few things make it feel "magical". for instance,
__shfl_down_syncis really weird. it blows my mind that you can copy a value directly from another thread's register in the same warp.
- it also takes some effort not to mess up the indices once you start vectorizing (
float4,half2, ...). you have to read more data at a time, so your loop conditions change, and you also have to take care of boundary conditions because the data size is not always a multiple of the vector size.
Day 19
- solved two more LeetGPU problems: 3D Subarray Sum and 2D Max Pooling. i need to revisit max pooling, my solution feels quite naive and probably has plenty of room for optimization.
- started chapter 5 of Programming Massively Parallel Processors. i should finish it tomorrow.
- found this amazing resource: CUDA Operations Optimization Guides. it has lots of nice tutorials on CUDA kernel optimizations. it takes you from the naive solution to the optimized one.

Day 20
- solved the LeetGPU RMS Normalization problem. another reduction problem. i can see why reductions (or scans) are a must-have in any library that goals is to ease the implementation of kernels, these kinds of problems are everywhere, they are a fundamental building block.
- still reading chapter 5 of PMPP. today i came across the concept of computational intensity (FLOP/B) and how to determine whether a program is compute-bound or memory-bound.
Day 21
- solved in two different ways the LeetGPU Cross Entropy Loss problem. the first one keeps the sum of the exp. in an additional array and then uses a warp reduction. the second solution avoids the extra memory by doing all the operations with warp shuffles. i learned about
__shfl_sync, which allows threads within a warp to share register values, super useful for broadcasting a value to all threads in the warp. cross_entropy_loss and cross_entropy_loss_2.
- finished chapter 5 of PMPP. there were so many learnings in this chapter. i think the main highlight is that GPUs gives you more control over memory than CPUs through the use of shared memory. on a CPU, you can only lay out your data access pattern, but you have no control over what enters the cache or not. also, for GPUs it's really important to keep an eye on how much register and shared memory your threads use. if this is above the average for the target hardware, you may run into occupancy issues because there aren't enough resources to allocate all 2048 threads in the SM. link to my notes: chapter 5
Day 22
-
solved the LeetGPU 3D Convolution problem. this one is not too different from 2D Convolution, but it adds a depth dimension. so row-major indexes are given by the expression:
(depth + d) * (input_rows * input_cols) + (row + r) * input_cols + (col + c)
- as usual with these kind of problems, you need to be really organized, it helps to have clear variables, otherwise it's easy to mess up.
- started chapter 6 of PMPP. this is a good one, the whole chapter is about optimizations techniques: memory coaslecing, loop unrolling, etc.
- today i reached the top 100 on LeetGPU after solving 39/98 tasks. the remaining problems are not trivial, and i'll probably need to first master more parallel building blocks. in PMPP, those start in chapter 7 and include techniques such as histograms, filtering, merging, sorting, etc.
Day 23
- solved the LeetGPU Histogramming problem in two ways. the first is a naive solution that uses
atomicAddto update the histogram in global memory directly, this solution suffers of contention since all threads try to store the bin frequencies in the same global array, which is slow. the second solution uses privatization, each block builds a private histogram in shared memory and then merges it into the global histogram, reducing contention and improving performance.
- still reading chapter 6 of PMPP.
Day 24
- solved the LeetGPU Monte Carlo Integration problem in three slightly different ways. it is another reduction problem: we just need to sum all the sampled values and multiply the result by
(b - a) / n_samples.
- the first solution is a classical shared memory reduction, the second uses warp shuffles to skip one of the thread synchronizations (__syncthreads), and the third moves the final scaling step into a separate kernel so it is executed only once, thus minimizing the repeated instructions in each thread.
- still reading chapter 6 of PMPP, currently in section 6.6, today i learned a bit about thread coarsening, memory coalescing, bank conflicts and corner turning.
Day 25
- solved the LeetGPU Matrix Power problem. this was an interesting one for me because i had solved it sequentially for competitive programming contests. the approach is not too different this time, except the matmul itself runs in parallel with a CUDA kernel. one cool thing i learned back then is that this problem has an O(log P) solution, a trick that can be used for many surprising problems, like calculating Fibonacci numbers in O(log N) time. i found that super cool when i first encountered it. here is the fibonnaci matrix power, in case you're curious: https://algomaster.io/learn/dsa/matrix-exponentiation
- anyway... i implemented three versions: a naive solution with a not-so-optimized matmul, a tiled matmul, and a tiled version using the O(log P) trick. since P <= 20 the O(log P) does not help much, but for larger powers the performance improvement should start to show.
- finished chapter 6 of PMPP, link to my notes: PMPP - Chapter 6
Day 26
- solved the LeetGPU Attention with Linear Biases problem. ALiBi (Attention with Linear Biases) is a way to give a transformer information about where tokens are relative to each other without using traditional positional embeddings. the implementation is not too difficult: for each attention element
(i, j), we just need to computealpha * (i - j)and add it to the current attention score. the termalpha * (i - j)is the linear position bias. in case you would like to learn more, here is the link to the paper: https://arxiv.org/pdf/2108.12409
- started chapter 7 of PMPP, the first chapter in part 2 of the book. this part focuses on parallel patterns, starting with convolutions, i can't wait to deep dive!
Day 27
- solved the LeetGPU Batched Matrix Multiplication problem. all the matmul problems so far were multiplying just two matrices, but in this case, we are given batches of matrices and have to store all the results in a row-major 1D array. a good guiding principle is to first try the stupidest solution that comes to mind, so that once the problem is solved, you can focus on optimizing it.
- ok, maybe it should be possible to run the matmul kernel once per batch, hmm but hold on, cowboy... the maximum number of batches is 128, and the kernel launch overhead may be significant (yeah, kernel launches are not free), which would probably make that solution quite slow.
-
a better approach is to process the entire batch in a single kernel by treating the batch index as a sort of "depth" dimension. this is exactly what we did on Day 22 when solving the 3D Convolution problem. in this case, the indices for each matrix are given by the formulas:
A[batch * (M * K) + row * K + k] B[batch * (K * N) + k * N + col] C[batch * (M * N) + row * N + col]
- still reading chapter 7 of PMPP: convolutions.
Day 28
- solved the LeetGPU Rotary Positional Embeddings problem. RoPE gives transformers a sense of token order. it does this by rotating the query (Q) and key (K) vectors according to each token's position. you can learn more about RoPE here: https://arxiv.org/pdf/2104.09864.
- so at first, i thought i just needed to precompute
rotate_halfin a temporary array, thus transforming the problem into a simple element-wise calculation. however, the performance test usesM = 1,048,576andD = 128. creating a temporary array would add an unnecessary allocation and another pass over the data, not to mention the extra complexity.
-
fortunately, none of that is needed. we can calculate
rotate_halfdirectly, one element at a time. for each output element, we find its rotated pair by checking whetherjis in the first or second half of the row, then adding or subtractingD / 2. ifjis in the first half, we also negate the current query value value:rotHalf = j < halfD ? -Q[i * D + j + halfD] : Q[i * D + j - halfD]
Day 29
- solved the LeetGPU Weight Dequantization problem. The idea of Weight Dequantization is to turn compact low precision weights (like int4 or int8) back into approximate versions of their original values (fp16 or fp32) using a scale matrix. this is useful for LLM inference, since quantized models use less GPU memory while keeping the weights "reasonably" close to the originals.
-
this problem felt like it was misclassified. it should be an easy task, not a medium one. the problem already explains how to calculate the row and column, so the solution comes down to these two lines:
int S_COLS = (N + TILE_SIZE - 1) / TILE_SIZE; Y[i * N + j] = X[i * N + j] * S[row * S_COLS + col];
Day 30
- solved the LeetGPU Causal Depthwise Conv1D problem. a causal depthwise 1D convolution gives a sequence model local context from the recent past. causal here means each output can only use the current and previous positions, never future ones, while depthwise means every feature channel (
D) gets its own small convolution kernel.
-
the key to these problems is learning how to translate the math into code. if you've been following my series, you'll recognize the same 3D row-major indexing pattern from days 22 and 27, this time with dimensions
B x L x D. once that pattern becomes familiar, the translation is straightforward. solving lots of these problems helps make the indexing feel natural and effortless. in short... the solution comes down to these few lines (see below). note that i moved thel - k >= 0check into the loop condition. there is no reason to keep looping oncel - kbecomes negative because all remainingxinput values are treated as zero, so they cannot change the sum.float sum = bias[d]; for (int k = 0; k < K && l - k >= 0; ++k) { sum += weight[d * K + k] * x[b * (L * D) + (l - k) * D + d]; } output[b * (L * D) + l * D + d] = sum;
Day 31
-
solved the LeetGPU SwiGLU MLP Block problem. SwiGLU is used in the MLP blocks of models like LLaMA and Mistral. in short, the SwiGLU MLP transforms each token's features independently, adding nonlinearities that helps the model to learn more complex patterns, the calculation looks like this:
output = (SiLU(X * W_gate) ⊙ (X * W_up)) * W_down
- this problem has quite a few steps, so i kept the first version simple: one kernel per step and a few temporary buffers. definitely not optimized yet... i'll come back with a faster version soon. if you're curious, here is the paper: GLU Variants Improve Transformer.
- i also started a new series called CUDA 101. i'm planning to create highly visual content to help others (and myself) learn CUDA. these posts will take a bit more effort and excalidraw-maxxing... but i'm having a lot of fun creating them!
Day 32
-
solved the LeetGPU LoRA Linear problem. LoRA (Low-Rank Adaptation) is a technique for fine-tuning large models more efficiently. instead of updating the original weight matrix
W, it freezes it and learns two smaller matrices,AandB. the calculation looks like this:output = xW^T + lora_scale * (xA^T) B^T
- i followed the equation pretty much line by line: again there is plenty of room to optimize here, fuse kernels, more efficient matmul and remove temporary buffers. if you're curious, here is the LoRA paper: LoRA: Low-Rank Adaptation of Large Language Models.
- i have a few LeetGPU solutions that need some serious optimization, so starting tomorrow, i'm taking a break from solving new problems to focus on improving some of the ones i've already solved.
- i'm almost done with chapter 7 of PMPP and should finish it today.
Day 33
- no new problems today. i went back to optimize the solutions from the last two days. the SwiGLU MLP Block dropped from 431.44 ms to 308.38 ms, while LoRA Linear went from 82.20 ms to 42.10 ms. the biggest win in both came from replacing the naive matmuls with tiled versions. this lets threads reuse the same values instead of fetching them from global memory over and over again.
-
i also experimented with vectorized loads, but they did not improve the overall performance much. for SwiGLU's SiLU step, i tried the faster approximate exponential and division intrinsics:
z[i] *= __fdividef(1.0f, 1.0f + __expf(-z[i]));i compiled both versions and checked the PTX and SASS. the intrinsic version generated fewer instructions, but it still barely moved the overall runtime. the SiLU step is tiny compared with the three matmuls, so this was another nice reminder to optimize where the program actually spends its time... ;)
-
here are the commands i used to inspect both compiler outputs. change
sm_120to match your GPU's compute capability:# generate and print PTX nvcc -arch=sm_120 -O3 --ptx day33/swiglu_mlp_2.cu -o /tmp/swiglu.ptx less /tmp/swiglu.ptx # generate a cubin and disassemble it to SASS nvcc -arch=sm_120 -O3 --cubin day33/swiglu_mlp_2.cu -o /tmp/swiglu.cubin cuobjdump --dump-sass /tmp/swiglu.cubin | less
Day 34
- solved the LeetGPU Multi-Head Attention problem. multi-head attention was introduced in the famous Attention Is All You Need paper.
-
so for this one it really helps to write down each matrix operation and the shape of its output, we implemented attention on Day 29, but the multi-head thing add some "spiciness", which make it quite easy to mess up, i spent some time debugging the row major indices. the calculation looks like this:
d_k = d_model / h head_i = softmax(Q_i @ K_i^T / sqrt(d_k)) @ V_i -> N x d_k output = Concat(head_1, ..., head_h) -> N x d_model
- the solution uses three kernels: one for
Q @ K^T, one for softmax, and one for multiplying the result byV. just like on Day 29, we avoid unnecessary allocations by readingKin transposed order instead of actually transposing it.
- wrote a new CUDA 101 post about
__syncthreads()vs.__syncwarp(): https://x.com/pavelsimo/status/2090771328466812967?s=20
Day 35
- solved the LeetGPU Attention with Sinks problem. attention sinks are token positions that consistently receive much more attention than the rest, even when they contain little or no useful information. usually these sinks tend to emerge naturally in the first few tokens. in the paper Efficient Streaming Language Models with Attention Sinks, the authors found that a sliding window stops working well once it moves past those first tokens. the fix is to choose a few of the first tokens as sinks and always include them in attention while the rest of the window moves forward.
- for most part the implementation is regular attention (see Days 14 and 34), except that we exclude parts of the score matrix before applying softmax. each token can attend to the sink tokens and the recent tokens inside the sliding window. all other positions are masked out. there are a couple of ways to do this: skip those scores with an
ifcondition, like i did in my solution, or set them to-INFso softmax turns them into zeros later on.
Day 36
- solved the LeetGPU FP16 Batched Matrix Multiplication problem. this one is pretty much the same problem we solved on Day 27, except inputs and outputs are in fp16. as usual with this kind of problem, arithmetic is done in single precision and the final result must be converted back to fp16 to prevent rounding errors.
- finished chapter 7 of PMPP, this one was all about convolutions. the main example moves input matrix tiles into shared memory to improve the conv. performance, pretty much the same trick as tiled matmul. i used that optimization to rewrite my Day 11 2D Convolution solution.
- the funny part? it did not get any faster... my guess is that the naive kernel already had nicely coalesced reads. i want to run both versions through NVIDIA Nsight and see where the time is actually going. something for later.
Day 37
- solved the LeetGPU Decaying Causal Attention problem. this one is pretty much traditional attention (see Days 14 and 34), except we add a decay mask. the decay mask blocks future tokens and gradually reduces the weight of older ones, so they matter less and less. it was introduced in the Retentive Network paper.
-
the expression powf(gamma, row - k) takes care of the decay:
for (int k = 0; k <= row; ++k) { sum += powf(gamma, row - k) * A[row * K + k] * B[k * N + col]; }
-
the interesting bit is this loop in the final matmul. k <= row means each row stops at its own position, which gives us this triangle:

- notice how the loop never reaches the empty black squares. those are scores for future tokens, and k <= row keeps them out completely.
Day 38
-
another day, another attention problem. i really can't get enough of these :) this time i solved the LeetGPU Grouped Query Attention problem. according to my research GQA is basically the middle ground between Multi-Head Attention (MHA) and Multi-Query Attention (MQA). the diagram below explains it best:

- as the diagram shows, GQA splits the query heads into groups and gives each group its own pair. a pretty nice compromise between performance and KV cache size. you can check out the paper here: GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints.
-
when i first saw this problem, i thought: great, another index soup... now we have query heads, K/V heads, and groups on top of the usual matrix indices. turns out the host (CPU realm) can prepare the data nicely before we launch the kernels. the trick is to offset a few pointers so they match the heads we're currently processing. the kernels can then treat them as regular matrices with the dimensions they already expect:
float scale = 1.0 / sqrt(head_dim); int group_size = num_q_heads / num_kv_heads; for (int head_idx = 0; head_idx < num_q_heads; ++head_idx) { int kv_head_idx = head_idx / group_size; const float *q = Q + head_idx * seq_len * head_dim; const float *k = K + kv_head_idx * seq_len * head_dim; const float *v = V + kv_head_idx * seq_len * head_dim; // matmul, softmax, matmul... }
- note: no data gets copied here. we're only changing where each pointer starts. from there, the kernels can pretend they're doing regular attention. much cleaner.
Day 39
-
solved the LeetGPU Batch Normalization problem. so the goal of batch normalization is to make neural networks train faster and more reliably by keeping their activations on a stable scale. the image below shows how it works. and if you're curious, here is the original paper: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift.

- so this problem requires us to calculate the mean and variance. both are reduction operations, which means they take a bunch of values and produce a single value. whenever you see this kind of operation, it screams
__shfl_down_sync,__syncthreads(), and all that good stuff :)
-
clearly the biggest challenge is figuring out how to calculate
column_meanorcolumn_var. in our case, each kernel needs to output a vector ofCvalues, one per feature, which we can use later for normalization. the good news is that once you get one working, the other follows pretty much the same reduction pattern. the sequence of kernel calls looks something like this:column_mean<<<C, threads>>>(input, mean, N, C, alpha); column_var<<<C, threads>>>(input, mean, var, N, C, alpha); batch_norm<<<blocks, threads>>>(input, gamma, beta, mean, var, output, N, C, eps);
Day 40
- solved the LeetGPU Fused Residual Addition and RMS Normalization problem. RMSNorm was introduced in the paper Root Mean Square Layer Normalization. the goal is the same as Batch Normalization keep activations on a stable scale.
- this problem is really similar to yesterday Batch Normalization (see day 39). the main difference is the direction of the reduction: yesterday each block reduced a feature column across
Nrows. today each block reduces a token row across itsCfeatures (see image below).
-
the sequence of kernel calls looks as follow:
matadd<<<grid, threads>>>(x, residual, Z, N, C); row_rms<<<N, threads.x * threads.y>>>(Z, N, C, rms, eps); norm<<<grid, threads>>>(Z, rms, weight, out, N, C);
Day 41
-
continuing with the normalization theme, today i solved the LeetGPU Layer Normalization problem. if this looks familiar, that's because it is pretty close to the Batch Normalization problem from Day 39. the difference is which direction we reduce. BatchNorm calculates the mean and variance for each feature across the batch (columns), while LayerNorm calculates them for each sample across its features (rows). the image below shows the difference in more detail.

-
probably not a surprise the implementation follows the same reduction pattern as the last two days. one kernel calculates the mean of each row, another calculates the variance, and the final kernel normalizes every value and applies the learnable weight and bias:
row_mean<<<N, nthreads>>>(input, mean, N, C); row_var<<<N, nthreads>>>(input, mean, var, N, C); layer_norm<<<grid, threads>>>(input, weight, bias, output, mean, var, N, C, eps);
- if you're curious, here is the original paper for Layer Normalization.
Day 42
- solved the LeetGPU Parallel Merge problem. i had seen the sequential version before in competitive programming, so it was fun to revisit it with CUDA. the usual approach uses two pointers, one for each sorted array. compare the current values, write the smaller one to the output, then move that pointer forward. simple, and
O(M + N), but very sequential: every step depends on the one before it. that is a bad fit for a GPU, where we want a lot of threads doing useful work at the same time. if you haven't seen the two-pointer version before, this explanation is pretty good: Merge Two Sorted Arrays.
- so the key insight to solve this problem is if you can figure out where each element will land in the output array, you can divide the task for each thread. is not too hard to see if each thread iterates until it find a suitable position for it's element this will be really expensive, but actually we don't need to do that, since both list are sorted we can use binary search to find where the element should land. see the image below for the complete explanation.
- i tried two versions. the first one uses two kernels, one for merging the elements in
Aand another for the elements inB. both kernels were almost identical, so in the second version i combined them into a single kernel withM + Nthreads. the firstMhandleA, and the rest handleB. same idea, just one kernel launch instead of two.
-
in case you're wondering?
lower_boundandupper_boundare two flavours of binary search. the links below have a really nice explanation. i uselower_boundforAandupper_boundforBso equal values don't try to write to the same output position.- lower bound: https://www.geeksforgeeks.org/dsa/implement-lower-bound/
- upper bound: https://www.geeksforgeeks.org/dsa/implement-upper-bound/

- in case you're curious, there's an even better algorithm than the scatter-based approach: Merge Path - A Visually Intuitive Approach to Parallel Merging.
Day 43
- solved the LeetGPU Softmax Attention Backward problem. after solving so many attention forward passes, it was finally time to go backwards :) so given the gradient of the output
dO, the goal is to calculate the gradients for all three inputs:dQ,dK, anddV.
-
the math is not too bad, but there's a lot of juggling with matrix dimensions, quite easy to mess up. i added comments with the output shape after every step, that helped a lot. here is the full backward pass:
P = softmax(Q @ K^T / sqrt(d)) dV = P^T @ dO dP = dO @ V^T dS = P * (dP - rowsum(P * dP)) / sqrt(d) dQ = dS @ K dK = dS^T @ Q
- i wrote two versions. the first uses naive matmuls and recalculates
rowsum(P * dP)for every element ofdS. that means repeating the same reductionNtimes per row... not the must "ideal", quite slow in fact...
-
the second version calculates the sum once per row, stores it in
D, and lets everydSthread reuseD[i]. it also replaces the naive matmul kernel with a tiled version. the runtime difference is pretty noticeable: the naive version took 791 ms, while the second took only 77 ms (LeetGPU perf. test). precomputing the row sum made the biggest difference.
Day 44
- solved the LeetGPU Stream Compaction problem. given a float array, the goal is to keep only the positive values and pack them together without any gaps while preserving their relative order.
- it turns out the solution is a variation of the Prefix Sum problem from Day 13, but there is a trick to it (as always...).
- once you see the "trick", it should be clear what to do: create an array and mark every positive value with a
1, run a prefix sum on that array, then useprefix_sums[i] - 1as the position where each positive value lands in the output. see the image below.

Day 45
- solved the LeetGPU Linear Self-Attention problem. "traditional" softmax attention compares every token with every other token, building an
M x Mscore matrix. that makes both time and memory grow quadratically with the sequence length, which can become a bottleneck for long sequences.
- linear self-attention on the other hand replaces softmax with a feature map, in this case
phi(x) = ELU(x) + 1. without softmax in the middle (yay!), we can use the associative property of matrix multiplication to calculatephi(K)^T @ Vfirst and completely avoid materializing the hugeM x Mattention matrix. for more details check out the paper Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention.
-
my solution pretty much follows the formula. what confused me at first was the final division: we have an
M x dmatrix on top and anM x 1vector at the bottom. i'm used to thesqrt(d)scalar in vanilla attention, so this looked a bit weird. regardless once is translated to code that part is quite simple:__global__ void linear_attn(const float *qktv, const float *qkj, float *output, int M, int d) { ///... if (i < M && j < d) { output[i * d + j] = qktv[i * d + j] / qkj[i]; } }
-
personally i found all these matrix shapes much easier to follow visually. the image below puts linear self-Attention next to regular softmax attention, so you can get a better sense of the big picture:

Day 46
- solved the LeetGPU Sparse Matrix-Vector Multiplication problem in two ways.
- the first is a naive approach. each thread handles one row and loops through every column, zeros included. it works in LeetGPU because the M and N limits are pretty low.
- the second packs the non-zero values with their column indices, so we only multiply the non-zero values. the issue is that it uses tons of memory.
- i want to optimize this one properly, so i'll give it another try alongside tomorrow's problem.
Day 47
- solved the LeetGPU INT8 KV-Cache Attention problem. this one is just like the problem Grouped Query Attention from Day 38. exactly the same trick again: loop through the heads (on the host), move the pointers to the current matrices, and let the kernels deal with the remaining dimensions. the only new bit is dequantizing the INT8 keys and values with their scales before running regular attention.
- i also revisited yesterday's Sparse Matrix-Vector Multiplication problem. i did a bit of research and learned there are three common ways to store sparse matrices to speed up matmul: CSR (Compressed Sparse Row), COO (Coordinate List), and CSC (Compressed Sparse Column). i'll save the details for another post, because it turns out none of them were needed here... :D
-
the input is a regular dense matrix, for sparse matmul to work its magic we would have to first convert the input matrix into a more "convenient" data structure. the problem is that this conversion has a cost, and for this particular problem, it dominates the runtime. in the end, a simple warp reduction is the way to go, with one warp per row, ran much faster. yes, it still multiplies all the zeros, but who cares? is faster... :) we can even ignore the
nnzparameter completely!
Day 48
- solved the LeetGPU Causal Self-Attention problem. this is pretty similar to the causal part of Day 37: each token can only attend to itself and the tokens before it, never to future tokens. that's what "causal" means here, no cheating... :) for more details, check out the paper Attention Is All You Need.
- so this problem is regular softmax attention with a small twist: set every score above the diagonal to
-INF. when softmax appliesexp(x), those masked scores becomeexp(-INF) = 0, which means future tokens receive no attention at all... the image below makes the whole thing much easier to see.
-
for the CUDA kernel implementation i added a masking option to the matmul. it uses a C++ template flag, so at compile time i get two versions: one with masking and one without. so the regular matmul doesn't pay for a masking check it never uses.

Day 49
- solved the LeetGPU Sliding Window Self-Attention problem. in Sliding Window Self-Attention each token only pays attention to itself and a few neighbors on either side. i added an image below to make it easier to picture. if you're curious about the details, check out the paper Longformer: The Long-Document Transformer.
-
with this one, my first thought was, well, it looks like a variation of yesterday's problem (see Day 48), just with a different mask, something like this:
C[i * N + j] = (j < i - window_size || j > i + window_size) ? -INF : sum;
- i wrote the first solution, and it worked, but... it took around 300 ms on the LeetGPU perf. test. out of all the Tesla T4 submissions, mine was the slowest. nice... :)
- as usual, there must be a "trick". then i looked at the window size again: it was pretty small. to be exact,
MAX_WINDOW_SIZEis 32. and here i was, allocating a wholeM x Mattention matrix for just for a few useful scores per token. so it was clear we could skip most of that work by only looking inside that smaller window.
- so i wrote a second version with one thread per token. each thread computes scores only inside its window, applies softmax, then combines the corresponding
Vvectors using those weights. no huge attention matrix, all in one kernel. megakernel? :D
-
anyway, much better perf. around 3ms for the perf. test. link to the code below.

Day 50
- finally, day 50! it's been a long way to get here, and we're still only halfway through. i have learned a lot so far, and i can't wait to see the progress at the end of day 100. thank you to everyone following along and supporting me. it means a lot!
-
anyway... back to CUDA! today i solved the LeetGPU Multi-Head Cross-Attention problem. in the Multi-Head Cross-Attention the "cross" part means
Qcomes from one sequence andKandVcome from another. think of a decoder looking at the encoder's output to decide what to generate next. each head can pay attention to different relationships, then we combine the results. this multi-head version was introduced in the paper Attention Is All You Need.
- this problem is really similar to INT8 KV-Cache Attention from Day 47. ignoring the int8 part, the main difference is how the input data is organized in memory. for that problem, the order is
(H, M, D): allMtokens for head 0, then head 1, and so on. quite convenient: just jump toh * (M * D)to pick a head.
-
for the Multi-Head Cross-Attention problem, the heads are in the middle,
(M, H, D): all heads for token 0, then token 1, and so on... so a head starts ath * D, but its next token isH * Delements away. we need to make sure the matmul uses that stride so we get the correct results. the diagram below may help to visualize:
Day 51
- solved the LeetGPU INT8 Quantized MatMul problem. at first glance, the formula looks pretty scary, but when you look a little closer and it's just a matmul with scaling, round, and clamp. nothing too crazy... :)
- if you're not familiar with clamp, it takes three values,
x,lo, andhi, and keepsxwithin[lo, hi]. anything belowlobecomeslo, anything abovehibecomeshi, and the rest stays as is. here, the INT8 range is[-128, 127].
- i spent a bit of time debugging a rounding error. i was doing
(sum * scale_A * scale_B) / scale_C, and the floating-point intermediates were changing my final rounded result. at the end the fix was to calculatescale_B / scale_Cfirst, multiply byscale_A, then apply that scale to sum. this avoids the larger intermediate values i had before. this is one of those situations math on paper is fine, but you get different results depending on how you operate your floating points values.
Day 52
- solved the LeetGPU Sparse Matrix-Dense Matrix Multiplication problem. this one felt a bit like cheating... the problem says "sparse", but regular dense matmul turned out to be faster. zeros included... :)
- same lesson as Day 47: the input comes in a dense format, so before taking advantage of sparsity, we have to scan the whole matrix and pack the non-zero values into a sparse format. that conversion has a cost, and here it can eat up the savings from skipping zeros.
- a bit of a shame. maybe LeetGPU should rework this problem and provide the matrix in a sparse format from the start, so we actually get to focus on sparse matmul.
Day 53
-
solved the LeetGPU INT4 Weight-Only Quantized MatMul problem. this one is about building a W4A16 matmul. in case you're wondering what the h*ll that means, it's just shorthand for 4-bit weights and 16-bit activations. the weights come packed in INT4, the activations are FP16, and the calculation looks like this:
y = x @ dequantize(w, scales)^T x - FP16 w - INT4
- if you want to learn more, check out NVIDIA explanation of weight-only quantization.
- we've seen similar problems on Day 47 and Day 51, where we stored data in a "smaller" type to save memory. then, we convert the weights back to floats when it's time to do the math. we unpack the weights and apply their scales to get back something close to the original values. that's dequantization. after that, we multiply as usual.
- the problem explains this process with a new matrix
W, but we don't need to build that matrix... we can convert the weights on the fly as we multiply, so there's no need to materializeWin gpu memory (yay!).
-
btw, in case you're wondering a nibble is 4 bits (half a byte). each byte has two nibbles, so we can pack two INT4 weights into one byte.

Day 54
- solved the LeetGPU Group Normalization problem. this one was tough for me. i had to read the description several times to decode the math. i'm not sure how this is a medium problem... this is a hard for sure!
- Group Normalization is a normalization technique for neural networks that helps keep activations on a consistent scale during training. for each sample, we split the channels into groups, then normalize each group using its own mean and variance. if you're curious, here is the original paper: Group Normalization.
-
this problem is really similar to Layer Normalization from Day 41. back then we needed a mean and variance for each row, now we need them for each group. with
Nsamples andGgroups per sample, we end up with twoN x Gmatrices: one for the means and one for the variances. then, for each group, we just use the corresponding mean and variance to normalize its values.
Day 55
- solved the LeetGPU BFS Shortest Path problem. this was a fun one! i've solved many BFS problems in the past, but never a parallel one.
-
my version goes level by level. at each depth, i launch
N x Mthreads, one per grid cell. each thread checks whether its cell is at the current depth (a.k.a. "frontier"). if it is, it visits the unvisited neighbors, otherwise, it just returns. so even though i launch threads for the whole grid, only the current "frontier" has any work to do:depth 0: launch N*M threads → only the start cell does useful work depth 1: launch N*M threads → only the frontier at depth 1 works depth 2: launch N*M threads → only the frontier at depth 2 works depth 3: launch N*M threads → only the frontier at depth 3 works ...
- pretty simple, but we're checking the whole grid at every level. that means
O(V x L)total work, whereV = N x MandLis the number of depth levels (L) processed. lots of threads showing up just to find out they have nothing to do...
- now comes the "funny" part... normal BFS (the one that runs in CPU land) has complexity
O(V + E). since each cell has at most 4 neighbors,E <= 4, so the complexity simplifies toO(V),E(edges) is just too small to care. that means it might be faster to copy the grid from the device to the host, run BFS there, and then copy the result back to the device. i felt a bit too lazy to try that, though, so i kept my super duper slow kernel solution instead. maybe another day :)
Day 56
- solved the LeetGPU Nearest Neighbor problem. i wrote three versions, starting with the dumbest solution i could think of and optimizing from there.
- i started with one thread per point. each thread checks all the other points and keeps the closest one. on paper that's
O(N^2), plenty of repeated work. but here's the thing i didn't notice at first. allNthreads run at the same time, so the GPU is basically waiting for a single thread to finish itsNiterations. the time actually ends up closer toO(N).
- the catch is that this only works while all the threads fit on the GPU in one go. the input sizes in LeetGPU's perf. test are actually quite low (N <= 10,000), so the naive approach did just fine, taking around 1.09 ms.
- next, i tried casting the points to
float3in the second version, so i could read the three coordinates together and keep my own point in registers instead of re-reading it every iteration. that brought the time down to 0.71 ms, about 35% faster for a couple of lines changed.
- for the third version, i added tiles (just like in tiled matmul). each block loads a chunk of points into shared memory, and all its threads reuse those points before loading the next chunk. we're still checking every point, but we save a lot of repeated reads from global memory. this one took 0.37 ms on the perf. test, about 48% less time than the second version and 66% less than the first. it ranked #3 on the H100 leaderboard!
- one thing that keeps working well: start simple, then win smaller battles until the perf. is where you want it. here, adding tiles to the naive approach was enough to get really good results. no fancy algorithm needed... just give those threads some fast shared memory :)
Day 57
-
solved the LeetGPU All-Pairs Shortest Paths problem. in this one we use the Floyd-Warshall algorithm to find the shortest distances between every pair of vertices in a graph. the idea is pretty simple. for each intermediate vertex
k, check whether going fromitojthroughkis cheaper than the best route we already know (the one at dist[i][j]):dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
- basically, "can i get there faster with a stop along the way?" repeat that for every
k, and we have all the shortest distances. the usual CPU version has three nested loops,O(N^3). for the CUDA kernel, i parallelize the two inner loops: each thread handles one(i, j)pair, so many pairs get updated at the same time. we're still doingO(N^3)total work, but the GPU divides that work across its threads.
- unfortunately we can't just parallelize all three loops and call it a day... each round of
kdepends on the distances from the previous round. if one block moves on tok + 1while another is still updatingk, it can read unfinished results.
- which is why we keep the
kloop on the host and run the kernels one after another, one for eachk, wherek <= N.
Day 58
- solved the LeetGPU Max Subarray Sum problem. for this problem we need to find the largest sum of
window_sizeconsecutive elements. i wrote four different versions for this one.
- i started with the naive version: each thread handles a starting index
iand loops fromitoi + window_size - 1, adding up the values to get that subarray's sum. then it usesatomicMaxto keep the largest sum for all windows. even when neighboring windows overlap, each thread calculates its sum from scratch... that'sO(window_size)work per window, with lots of repeated additions. this one took 2.55 ms.
-
next, i used prefix sums, where each entry stores the sum so far. for a window starting at
i, its last index isj = i + window_size - 1, and its sum is:sum = prefix_sum[j] - (i > 0 ? prefix_sum[i - 1] : 0);
- this is
O(1)per window once the prefix sums are ready. less work in theory, but this one took 4.79 ms, slower than the naive version! building the prefix sums with a single thread dominated the runtime... :)
- so in the third version, i made the prefix sum parallel too. each block computes its own prefix sums, then we add the sum of all elements in the blocks before it. the window calculation stays the same, but properly parallelizing the prefix sum brought the time down to just 0.65 ms.
- then i wondered if we could run even faster by reducing the number of
atomicMaxcalls. for the fourth version, i tried the idea of privatization. so each warp finds its maximum and stores it in shared memory, then we reduce those values to one maximum per block. now each block makes just oneatomicMaxcall to update the final answer. i ran my own tests and it does help for large values ofN, but on LeetGPU perf. test this one took 0.97 ms, slower than version three... :(
Day 59
- solved the LeetGPU Token Embedding Layer problem. this is the input embedding layer used in transformer models like BERT: https://arxiv.org/pdf/1810.04805.
-
for each token, we look up its token and position embeddings, add them together, and apply layer normalization. see image below:

- this one is extremely similar to Group Normalization from Day 54. we already did the mean, variance, and normalization part there, including the scale and shift at the end. this time we do it for each token's embedding vector instead of each group of channels. so once we add the token and position embeddings, we already know how to do the rest.
- group normalization was difficult for me back on day 54, but what i learned then made this problem feel easier this time around. that's what i like about doing this every day. what you learn from one problem helps you solve the next, and little by little, you build a solid foundation to take on harder problems.
Day 60
- solved the LeetGPU PPO Clipped Surrogate Loss problem. PPO stands for Proximal Policy Optimization, from the paper Proximal Policy Optimization Algorithms.
- this is the first of several reinforcement learning problems that i'll like to solve from the LeetGPU challenges.
- in the "real world", PPO can be used to train robots through trial and error. for example, OpenAI used it to teach a robotic hand to manipulate objects, training in simulation before transferring what it learned to a physical robot.
-
this problem is mostly following the formula: we calculate the probability ratio between the current and old policies, clip it (or clamp it, same thing), multiply both versions by the advantage, and take the smaller value. the loss is the negative mean over all tokens. see the image below for the steps.

- one important part is the mean calculation. we've seen how to implement that several times before, like in Group Normalization on Day 54 and Token Embedding Layer on Day 59, which we did yesterday. the only difference here is that we add all the PPO "stuff" before summing everything up.
Day 61
-
solved the LeetGPU DPO Sequence Loss problem. DPO stands for Direct Preference Optimization. if you're curious, check out the paper Direct Preference Optimization: Your Language Model is Secretly a Reward Model.

- in the "real world", DPO can be used to fine-tune a chatbot using human preferences. imagine two answers to the same question: one is clear and helpful, the other is confusing. we label the first as preferred and the second as rejected, then train the model to favor the preferred answer. basically, learning from examples.
- this one is really similar to the PPO problem from yesterday: follow the formula, do some arithmetic, and calculate the mean. we've done this a few times already, so nothing too crazy.
-
there was one gotcha, though: softplus. i started with a naive version
logf(1.0f + expf(z))and ran into numerical stability issues. after a bit of research, i found this more stable way to calculate it: https://stackoverflow.com/questions/44230635/avoid-overflow-with-softplus-function-in-pythonfmaxf(x, 0.0f) + log1pf(expf(-fabsf(x)))
Day 62
- solved the LeetGPU GRPO Surrogate Loss problem. we continue with the RL problems as planned.
- GRPO stands for Group Relative Policy Optimization, introduced by the DeepSeek team in DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models.
- GRPO can be used to train language models to solve math problems, like DeepSeek did with DeepSeekMath. imagine asking the model the same question several times and scoring each answer. we compare the reward for each answer against the rest of the group, then train the model to favor the better ones. that's where the "group relative" part comes from.
-
this problem is a bit more difficult than the DPO problem from yesterday, but the same ideas apply: follow the formula, do some arithmetic, and calculate the mean. there are some simililarities with PPO from Day 60, for instance the clipping (clamp) part. see the image below for the steps.

- just in case you don't know, a "surrogate" is just a fancy word for a substitute, something you use in place of the real thing. here the "real thing" is the expected reward (how good the answers from the model are on average), which you can't take a gradient through directly, so you optimize a substitute that moves in the same direction. so for example, you can't directly measure how happy a customer is, so you measure instead if they come back. repeat visits are not happiness, but they kind of move in the same direction.
Day 63
- solved the LeetGPU Parallel Reverse Scan (GAE) problem. continuing with the RL theme!
- this one took me a while... i struggled a bit to translate the math into something i could actually implement. anyway, it happens...
- so GAE stands for Generalized Advantage Estimation, from the paper High-Dimensional Continuous Control Using Generalized Advantage Estimation. remember the advantage we used in PPO on Day 60? GAE is one way to calculate it.
- GAE looks at later rewards to help judge earlier actions. think of a robot taking a step, staying balanced, and earning rewards (points, btc?) as it keeps walking. if that works, the earlier step gets some credit as well.
- the code starts by calculating all the temporal-difference errors (
delta) in parallel, one thread per step. eachdelta[t]only needs the reward and the values attandt + 1, we get this from the input so not dependencies there.
-
once the
deltavalues are ready, we combine them into advantages each one sums the current error and the discounted errors after it.
Day 64
- solved the LeetGPU Linear Recurrence problem. this kind of recurrence is a core building block of State Space Models (SSMs) such as Mamba, S4, and H3. if you're curious, check out the paper Mamba: Linear-Time Sequence Modeling with Selective State Spaces.
-
here, we start with the expression:
h[t] = a[t] * h[t - 1] + x[t]
-
expanding the first few steps makes it easier to see what's happening:
h[0] = x[0] h[1] = x[1] + a[1] * x[0] h[2] = x[2] + a[2] * x[1] + a[2] * a[1] * x[0] h[3] = x[3] + a[3] * x[2] + a[3] * a[2] * x[1] + a[3] * a[2] * a[1] * x[0]
- each result includes the current input plus earlier inputs multiplied by the coefficients along the way. so we don't need to calculate all those products separately, though. the previous result already contains the work we've done so far.
- for the kernel implementation, each sequence in the batch runs on its own thread.
Bis the batch size, or number of sequences. each thread processes its sequence in order, since each step needs the previous result. a good thing is the sequences are independent of one another, so they can run in parallel.
Day 65
- solved the LeetGPU Vision Transformer Patch Embedding problem. this is a new problem on LeetGPU, and at the time of writing this post, i'm the only one who has solved it. pretty cool :)
- patch embedding is the step that turns an image into a sequence of tokens for a Vision Transformer (ViT). we split the image into patches, flatten each patch and project it into an embedding, put a learned
cls_tokenat the beginning, and add position embeddings. if you're curious, check out the original paper An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale.
- this one was a real index nightmare... i struggled to translate the math in the description into code. which pixel do i read from this patch, and where does the result go? the n + 1 thing, etc... anyway, getting those indices right took a while.
- in case you don't know,
cls_tokenmeans classification token. think of it as a place to collect information about the whole image. we put it before the patches, and later the transformer fills it with information that helps the model decide what the image shows, like a cat or a dog.
Day 66
- solved the LeetGPU Multi-Head Latent Attention Decode problem. this is the attention variant used in DeepSeek-V2/V3. if you're curious, check out the paper DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model.
-
so the idea is to compress the keys and values into one latent vector per position that all heads share, along with a small rotary key. that's a lot less to keep in the KV cache during inference:

- as usual the implementation had a lot of math. luckily, the problem breaks it down into steps. also it helps we learned how to handle the pointer arithmetic for multiple heads back in on Day 34, there was a lot of that in this problem.
- another thing i hadn't seen in a problem before: the input vectors were concatenated. each row of
qcontainsq_nopefollowed byq_pe, and each row ofkv_cachecontainscfollowed byk_pe. we need to read the right slice of each row, with the proper stride. as you probably know, more offsets, more chances to mess up. i struggled with this one because of that :)
- ah one more thing... i claimed in the past that i had solved all attention problems on LeetGPU. this one was added recently, and there are only two submissions so far, including mine.
Day 67
- solved the LeetGPU MoE Top-K Gating problem. for those who don't know, MoE stands for Mixture of Experts, and top-k gating is how many of these models pick which experts handle each token. each MoE layer has a small learned router, usually just a single linear layer, that multiplies the tokens hidden state by a weight matrix to get one score (logit) per expert. top-k gating then picks the
kexperts with the highest scores. if you're curious, check out the paper Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer.
- i was short on time today, so i went with a naive solution. the constraints are quite low,
E <= 256andk <= E, so i figured a simple approach should do just fine for now.
- for the top-k part, each thread handles one token. it scans the experts to find the largest logit, saves its value and index, then repeats until it has all
k. once that's done, a separate softmax kernel turns those top values into weights.
-
i'll revisit this one. i have an idea to parallelize the top-k selection with a block reduction, but it will take some time to get the implementation right... leaving that for another day :)

Day 68
- solved the LeetGPU Top-p Sampling problem. top-p (or nucleus) sampling is one way a language model picks its next token. if you're curious, check out the paper The Curious Case of Neural Text Degeneration.
- getting the random part right took a while... according to my research LeetGPU judge uses PyTorch's sampler, which calls
exponential_()with Philox on CUDA. so i thought well why not cuRAND? sadly external libraries aren't allowed, so after some rand function hunting, i ended up with matching implementation ofphilox_uniform.
-
once the randomness was sorted out, the rest was just following the steps: softmax, sort, keep the nucleus, renormalize, and sample.

Day 69
- solved the LeetGPU Top K Selection problem. there are many dimensions to this one.
- every time we encounter a problem with precise step by step instructions, we should ask ourselves: should we do exactly what the statement is telling us to do, or is there "more" to this? usually, following the steps blindly is the way to go, but for some problems, the really interesting gains come from noticing some underlying characteristic of the data and doing something a bit more clever.
- what do i mean by this? today i just sorted the elements and took the top
k. that's fine, as long as the sorting algorithm is fast enough. i initially tried rank sort. i was in a bit of a rush and didn't read the constraints: sinceN <= 100,000,000. anO(N^2)algorithm would do up to10^16comparisons, or 10 quadrillion... probably too slow :) next, i implemented bitonic sort, withO(N log^2 N)total work, and that was enough to pass the LeetGPU perf. tests.
- but can we do better? yes, because the problem isn't asking us to sort all the numbers; it's ONLY asking for the top
k. so if we can figure out how to find those elements without doing a full sort, we can cut out unnecessary work and get better performance. one hint is how perf. is measured for this problem:N = 50,000,000,k = 100. note how smallkis. this is the key.
- that said, i have another problem to revisit...
Day 70
- solved the LeetGPU Multi-Agent Simulation problem. i think this one should be a medium, not a hard.
- for this problem, each agent has a position and a velocity, and we update the movement based on the average velocity of nearby neighbors.
- today i want to do something a bit different: walk through the three solutions and each optimization along the way. i think seeing how we get there is more useful than just presenting the most optimized version.
- let's start with the first solution. each thread handles one agent
iand loops over all the other agents (i != j). it checks which ones are close enough, averages the velocities of those neighbors, and updates the velocity and position of agenti. if there are no neighbors, the velocity stays the same. this solution took around 0.88 ms on the perf. test, this is the baseline, it does not get slower than this.
- now, we're checking every agent against every other agent, so that's still
O(N^2)total work. but remember those threads can run in parallel! if they could all run at the same time, we'd only have to wait for oneO(N)loop to finish. of course, the GPU can only run so many threads at once... asNgrows, some have to wait.
- the second solution is almost the same, but uses
float4to load the four values for each agent (x,y,vx,vy) together instead of four separate scalar reads. we also write the result as afloat4. same calculations, just changing how we move the data. this brought the time down to 0.60 ms, about 47% faster than the first solution.
- the third solution was really nice because we already used this idea on Day 56. each block loads a tile of 256 agents into shared memory, waits until the data is ready, and then all threads in the block reuse that tile to check for neighbors. before loading the next tile, we synchronize again so nobody overwrites data another thread is still using. we're still checking every other agent. each block loads a chunk of agents into shared memory once, then all threads in the block reuse that data. that brought the time down to 0.29 ms, about 107% faster than the second version. compared with the original 0.88 ms, that is roughly a 3x speedup.
Day 71
- solved the LeetGPU GPT-2 Transformer Block problem. this one is not a problem, it's a complete project :D just to give you an idea of the size, the implementation ended up at 344 lines, 7 kernels and 2 device functions...
- we have to implement the forward pass of a GPT-2 transformer block. no ready made layers to call here... layer norm, GELU, matrix multiplications, softmax, residual additions, we have to put all of it together ourselves.
- this was a nice way to apply what we've learned so far. we've already solved most of these pieces as separate problems, and all that practice came in handy here. i can imagine trying this when i first started the CUDA journey... probably would have been way too overwhelming. now it's still a lot of work, but at least i recognize the pieces.
- the most challenging part was multi-head attention. in previous problems, the head data was already laid out nicely for us to use. here, we first calculate
Q,K, andVtogether in one big projection, then have to figure out where each head starts and how far to jump to reach the next token. getting the offsets and strides right took some work.
- the GEMM work from Day 14 and Day 15 was useful here too. there are a lot of matrix multiplications followed by a bias vector addition, so having a GEMM kernel that can do both saves us from calling an addition kernel.
- i allocated a lot of intermediate buffers. there's probably plenty of room to combine operations, reuse memory, and avoid writing some of those intermediate results (avoid materialization). but this problem was already long "enough", so today i focused on getting the whole thing working. this one as well would be cool to revisit for optimization at some point... the list keeps growing :)
-
here are all the related papers to this problem:
Day 72
- solved the LeetGPU Adder Transformer Inference problem. a transformer to add two numbers... yeah, you heard that right, like
3 + 5 = 8. here's a sample PyTorch implementation if you're curious.
- i struggled with this one... barely finished an unoptimized version in time. to make my life easier, i used a single kernel with all the operations as device functions. there's more work we could parallelize, but with so much going on, this was the quickest way to get it working.
- i really liked seeing a simplified transformer from start to end, one of my favorite problems in LeetGPU so far. highly recommended :)
-
so this time i only parallelized across the examples in the batch, one thread per prompt. each thread loops through the decode steps, runs the transformer on the current sequence, and picks the token with the highest logit (
argmax). then append that token to the sequence and repeat, so each step builds on the previous one.
Day 73
- solved the LeetGPU Sorting problem. the constraints were high enough that an
O(N^2)sort would definitely time out, so i used bitonic sort, which isO(N log^2 N). i also explored library implementations and wrote alternatives using Thrust and CUB radix sort.
- i have time to revisited Adder Transformer Inference and added a KV cache. the time went from 18.5 ms to 2.50 ms, a 7.4x speedup.
- each prompt in the batch now goes through two phases: prefill and decode. during prefill, i calculate
Q,K, andVfor the input tokens once and store them. then decode generates one token at a time, calculates the values for the new token, and extends the cache (by adding the new token to the cache). in yesterday version we recalculated everything for the whole sequence at every step... now i only calculate what changes and reuse the rest.
Day 74
- solved the LeetGPU Variable-Length Causal Attention problem. this is a new one, and at the time of writing, we're the only ones who have solved it :)
- according to the problem statement, inference engines such as vLLM use this idea to handle prompts of different lengths together. instead of adding empty slots to make every prompt the same length, we pack them one after another.
cu_seqlenstells us where each prompt starts and ends. this avoids wasted work on padding. it also reduces the overhead of launching new kernels, since several prompts can be bundled together.
-
the mask blocks future tokens and tokens from other sequences. we set their scores to
-INF, so they get zero weight after softmax, see image below.int seq_start = cu_seqlens[seq]; int seq_end = cu_seqlens[seq + 1]; C[i * N + j] = j >= seq_start && j < seq_end && j <= i ? value : -INFINITY;
- i have to revisit this problem at some point. pretty sure materializing the complete attention matrix just to mask out a bunch of cells (mark them as
-INF) is not the way to go...
Day 75
- solved the LeetGPU Min-P Sampling problem. according to the problem statment this is a logit-filtering primitive used in modern LLM inference tools such as vLLM, Hugging Face TGI, and llama.cpp to filter out unlikely tokens before sampling.
- i used a single kernel for this one. i started with softmax, filtered out the tokens below the threshold, then added an extra step to renormalize what's left. the image below shows the steps.
- btw... remember our top-p sampling on Day 68? both do a similar thing: filter out unlikely tokens before sampling. our top-p solution needed sorting, but min-p doesn't, so it's simpler and easier to parallelize :)
-
if you want to learn more, check out the paper Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs.

Day 76
- solved the LeetGPU SSM Selective Scan problem. SSM stands for State Space Model, and selective scan is the core operation in Mamba-style sequence models.
-
remember the Linear Recurrence from Day 64? same basic idea here. we go through the sequence while keeping a small memory of what we've seen so far. at each step, we take the previous state,
h[t - 1](our old memory), and mix some of it with the current input to get the new state,h[t]. the "selective" part means the input can influence what gets remembered or forgotten.// how much old memory to keep float A_hat = expf(delta[btd] * A[dn]); // how much new input to add float B_hat = delta[btd] * B[btn]; // mix old memory with the current input h = A_hat * h + B_hat * u[btd];
- following the formula was enough to get this one working, but i'm not happy with my implementation yet. every time i have to use
atomicAdd, i feel like i'm missing some warp shuffle magic somewhere :) adding this one to the list of problems to revisit...
-
if you want to learn more, check out the paper Mamba: Linear-Time Sequence Modeling with Selective State Spaces.

Day 77
- solved the LeetGPU Fused QKV Projection with RoPE and KV Cache Update problem. not the best name... basically, we have to prepare new tokens for attention and update the KV cache while "roping" as we go.
- this one was really difficult for me... we already did RoPE on Day 28, but i struggled with all the offsets and getting the data into the shape it needed to be in. i haven't done this much pointer arithmetic in a while. i added an image below so you can get a sense of what i mean.
- then there's the output... three places to write to, each with different pointer offsets. Q goes into
Q_outafter RoPE, while K and V go intoK_cacheandV_cache. K gets RoPE too... but V is copied as is.
-
for the kernel, i split the RoPE and cache update in a 2D grid of
(batch, head). each block handles one sequence and either a Q head or a K/V head. the threads work on pairs of elements,jandj + D/2. it looks something like this:thread 0 → RoPE (0, 64) thread 1 → RoPE (1, 65) thread 2 → RoPE (2, 66) ... thread 63 → RoPE (63, 127)
- i think getting comfortable with these sorts of problems takes a lot of practice implementing papers and going from math to code. sometimes i think the world would be a better place if papers just wrote C code instead of math... but that's a discussion for another day :)
- the problem recommends two papers if you want to learn more: RoFormer: Enhanced Transformer with Rotary Position Embedding for RoPE and GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints for reducing the number of KV heads.

Day 78
- solved the LeetGPU K-Means Clustering problem. this one was a bit easier than the last few days...
- the k-means algorithm helps to finds groups in unlabeled data by clustering points around one or more centroids. it's useful for data segmentation in general: image compression or just finding patterns in a bunch of raw data.
-
my solution loops for
max_iterations. in each step runs three kernels as follow:for (int step = 0; step < max_iterations; ++step) { // assign each point to its nearest centroid assign_labels<<<blocks_1, threads>>>(...); // sum the coordinates and count the points in each cluster accumulate<<<blocks_1, threads>>>(...); // update each centroid using the sums and counts update_centroids<<<blocks_2, threads>>>(...); }
-
please refer to the image below so you can see how all fits together.

Day 79
- solved the LeetGPU Beam Search Step problem. The goal of the beam search algorithm is to keep the
kbest unfinished sequences, called beams (crazy name...), as it generates text. each beam has a total score from adding up the token log-probabilities (the higher the better). this problem focus in one step, for each batch item: try allVnext tokens for each beam, add the beam and token scores, and keep the bestkof thosek * Vcandidates.
- i implemented two solutions. the first one used rank sort for simplicity, but with vocabulary size
V <= 100,000, comparing allk * Vcandidates against each other was too slow... it timed out. another downside is that it needs several temp. buffers, then extra copies to move the topkresults from the sorted buffers into the output.
- in the second solution, i turned rank sort into top-k by stopping early. as soon as a thread finds
kcandidates it stops. that one ran within the time constraints. also we got rid of all the temp. buffers.
-
my current solution it's still too slow... i want to learn a bit more on how to do top-k efficiently. we already did Top K Selection on Day 69, where i tried both rank sort and bitonic sort. i'll revisit both problems.

Day 80
- solved the LeetGPU Ordinary Least Squares problem. the goal is to find the coefficient vector
betaso thatX @ betais as close as possible to the target valuesy, basically minimizing the sum of squared errors.
- i ended up using gaussian elimination for this one. i found a cpu reference implementation and turned it into three kernels. once you realize the problem is "just" solving a system of linear equations, we now only need to ensure the algorithm is right.
-
the closed-form solution usually has a matrix inverse in it. computing matrix inverse is a bit problematic, and if not careful is easy to introduce numerical errors, so i tried to avoid doing it that. what is the alternative then? if we assume X^T @ X is invertible, we can multiply both sides by X^T @ X and get rid of the inverse:
beta = (X^T @ X)^(-1) @ X^T @ y (X^T @ X) @ beta = (X^T @ X) @ (X^T @ X)^(-1) @ X^T @ y (X^T @ X) @ beta = X^T @ y A @ beta = b, where A = X^T @ X and b = X^T @ y
-
so now the problem becomes solving for
betainA @ beta = b, and this can be done with gaussian elimination. here are the three kernel calls in the implementation:// build the augmented matrix [X^T @ X | X^T @ y] build_matrix<<<blocks, threads>>>(X, y, M, n_samples, n_features); // swap pivot rows and eliminate entries below the diagonal forward_elimination<<<1, 256>>>(M, n_features); // solve for beta from the last row up, substituting the coefficients already found back_substitution<<<1, 1>>>(M, beta, n_features);

Day 81
- solved the LeetGPU Speculative Decoding Verification problem. medium difficulty! i don't think so. i struggled with this one... there are tons of math to decode, and the algorithm is not trivial to implement (at least not for me...)
- the goal of speculative decoding verification is to generate tokens faster. it goes like this, a small model guesses tokens, and a bigger model checks those guesses. we keep tokens up to the first rejection. if there is a rejection... we pick a replacement. if every guess passes, we append a "bonus" token.
- my solution uses two kernels,
acceptance_probfinds the first rejection.resamplecopies accepted tokens, samples a replacement or bonus token, and zeros the remaining slots. see the image below.
- worth mention, a CDF (cumulative distribution function) is just a running sum of probabilities. we pick the first token where that sum reaches a random value between 0 and 1. probabilities
[0.2, 0.3, 0.5]become[0.2, 0.5, 1.0], so0.4picks token 1.
-
if you want to learn more, check out the paper Fast Inference from Transformers via Speculative Decoding.

Day 82
- solved the LeetGPU Logistic Regression problem. logistic regression is basically a yes/no classifier. for each sample we compute a score
z = X @ beta, and then use a sigmoid function to convert into probabilities[0, 1]. what we're looking for is abetathat gets those probabilities as close as possible to the labelsy.
- my first attempt was using gradient descent, but even after 1M iterations it was not converging to the expected answer of the LeetGPU judge. the updates got so tiny that they basically couldn't change beta due to float precision limits, and doing more iterations didn't really help.
- after a bit of research, i learned about the newton method. instead of using a fixed learning rate, it uses the curvature (how fast the gradient changes) to choose the step size in each direction, so it converges in less iterations. each step solves a system of linear equations, and it has the exact same
A @ beta = bshape from Day 80, so we can reuse the same gaussian elimination kernels to solve fordelta:)
-
currently there's still a lot of room to optimize the second solution. i used super dumb kernels with just 1 block and 1 thread to build the newton system and update
beta. definitely another problem i want to revisit...
Day 83
- solved the LeetGPU Block-Sparse KV Selection Attention problem. according to the problem statement, this technique is used in sparse attention inference kernels such as NSA and Quest. this problem is really hard... it's just notation nightmare. the whole block thing was so confusing...
- the idea here is that reading the whole KV cache gets expensive as the context grows. so is better to split it into blocks and only consider the most relevant to the current query. less data to read, less to do...
-
i split the work into a few steps. here's is the sequence of kernel calls.
// score each block using Q and the average of its keys compute_scores<<<grid_1, threads>>>(...); // keep the highest-scoring blocks for each head select_top_blocks<<<num_heads, 1>>>(...); // compute Q @ K^T / sqrt(head_dim), one call per head for (int h = 0; h < num_heads; ++h) { matmul<<<grid_2, tile>>>(...); } // set scores outside the selected blocks to -INF mask_skipped_blocks<<<grid_1, threads>>>(...); // turn scores into probabilities. masked positions become zero softmax<<<num_heads, threads, threads * sizeof(float)>>>(...); // compute the weighted sum of V, one call per head for (int h = 0; h < num_heads; ++h) { matmul<<<grid_3, tile>>>(...); }
- my implementation still computes all the QK scores (so much for sparse...) before masking, and the final matmul still reads all of V. so there's room to optimize... i probably can use the list of top blocks to skip the ones i don't need, using indices, but i ran out of energy before doing that... more to revisit :)
-
if you want to learn more, check out the paper Quest: Query-Aware Sparsity for Efficient Long-Context LLM Inference.

Day 84
- solved the LeetGPU Non-Maximum Suppression problem. finally a "hard" problem that is actually a medium... :)
- you can think of NMS as a sort of post-processing step that many YOLO implementations use to remove duplicate boxes around the same object. YOLO here means "You Only Look Once"... not to be confused with "You Only Live Once" (i prefer the latter).
- i'm really glad i encountered this one. i played with YOLO models before, so it's nice to understand this step. from what i read, some newer models like YOLOv10 are moving away from NMS, learning to produce one prediction per object without this cleanup step.
- for this one, we just need to follow the algorithm described in the problem statement. see the image below for more details.
-
i used three kernels: one to sort the scores, one to initialize the
keeparray, and one to suppress overlapping boxes. here's the sequence:// sort scores in descending order, keeping their original indices rank_sort<<<blocks, threads>>>(...); // initialize every keep flag to 1 fill<<<blocks, threads>>>(keep, 1, N); // visit boxes in descending score order, skipping suppressed ones for (int i = 0; i < N; ++i) { // ... // suppress boxes according to the rules supress_boxes<<<blocks, threads>>>(...); }
-
just in case you're wondering... why write a kernel just to fill an array with 1s?
cudaMemsetfills bytes, so it works fine for0and-1in our 32-bit integer array:0x00000000 gives 0 0xFFFFFFFF gives -1
-
passing
1fills each byte with0x01, giving us0x01010101. that is16843009, a "bit" more than1! so, the fill kernel writes an actual1.
Day 85
- it's been a long journey to this point, and there are still 15 days left... for these last few days, i want to try a few different things.
- so far we've solved 100 problems on LeetGPU in this series, and we're now in LeetGPU top 6. not that the ranking means much, but 84 days ago i couldn't even write a hello CUDA kernel. i'm happy with the progress!
- now i feel comfortable writing simple kernels, but to get to the next level i need to spend more time profiling and optimizing. you know, all that fancy arithmetic intensity analysis, SOL (speed of light), comparing against cuBLAS... the stuff we all love.
- today i spent some time putting together a CUDA bench with the help of claude, just some code to help me easily measure performance and plot some graphs. i have something running that checks correctness and measures basic performance metrics. i'll keep adding to it as i go, and once i'm happy with it i'll publish the repo.
- so i went back to one of the first problem we solved in this series: matrix transpose (Day 2), and tested four versions on my RTX 5090. the first one, the baseline, took 237.8 µs.
- then tiling with shared memory got me down to 206.5 µs, about 1.15x faster.
- i also tried padding (204.0 µs) and XOR swizzling (204.1 µs) to avoid bank conflicts. padding was a touch ahead, about 1.17x faster and ~90% of copy bandwidth.
-
all three tiled versions were within 3%... basically tied :)

Day 86
- same as yesterday, we're focusing on optimization. today i revisited the softmax problem from Day 9, and the results were a bit counterintuitive...
- the baseline, v0, is the first softmax implementation i wrote. probably the ugliest implementation you can think of :) three kernels: find the maximum, sum
exp(x - max), then normalize. global atomics, many allocations, reading the whole input three times, computing the exponentials twice... plenty to improve.
-
well, here is the twist... it was actually quite fast for long inputs! roughly 6x faster than my online softmax version agaist the LeetGPU performance tests, with an even bigger gap at
N=32M. see the full results in the chart below.
- why was the baseline faster? it came down to how we split the work across blocks, or CTAs (Cooperative Thread Arrays), if you're fancy... :)
- my baseline solution (the stupid one) spreads work across many blocks, while v1 single-kernel and v2 online softmax launch just one. a block runs on one SM (Streaming Multiprocessor), leaving the other SMs with no work in those versions. so that extra parallelism paid off... the baseline even beat v3 cuDNN on the big input!
- at this point, it should be clear we have to keep the GPU doing brrr. so i gave those idle SMs some work to do... i created a new version, v4 online partials, which uses one kernel to compute partial max and sums, then another to merge those results and normalize the input across blocks. with more of the GPU working, it finally beats the baseline :)
- since you made it this far... have you realized that with CUDA (or parallel programming in general), you can take any problem that appears simple and make it infinitely more complicated? the fun never ends...
Day 87
- today i revisited 2D convolution from Day 11. so, in my original solution (the baseline, a.k.a. the dumb one), each thread computes one output by reading the input and kernel filter weights from global memory (yeah, you heard that right!). simple... but nearby threads read many of the same values over and over.
- for v1, i moved input tiles into shared memory so threads can reuse them, and put the kernel filter weights in constant memory so threads can share those reads too. this got me roughly 1.8x faster on the LeetGPU perf. test.
-
for v2, i kept that setup and added C++ templates for the kernel filter sizes (rows and cols) we already know, since the problem constraints say that kernel rows and cols must be <= 33. this helps the compiler unroll the loops and simplify the index math. it was roughly 1.9x faster than the baseline, basically tied with v1 on the LeetGPU perf. test. actually, it only really helps when the exact configuration of kernel rows and cols is known and the input is large enough for loop unrolling to work its magic.


- i was working on v3 with thread coarsening, but couldn't finish it in time. the idea is for each thread to compute several outputs instead of one. for example, a thread could compute four outputs and reuse data for those those calculations.
Day 88
- today i revisited dot product from Day 9. the baseline (v0) is the classic reduction in the books. we store the products
A[i] * B[i]in shared memory, then sum them, keeping threads in sync with__syncthreads(). thread 0 adds the sum from each block withatomicAdd.
- v1 is pretty similar to the previous solution, but uses
__shfl_down_syncto pass values between threads in a warp and sum them in registers. fewer shared memory loads and fewer synchronizations... but the difference from the baseline was within 3%, so tied :)
- for v2, i added vectorized
float4loads to read four values at a time. also within 3% of the baseline... another tie.
- i also tried v3 cuBLAS to have a reference point of what good should look like. it was slower on the smaller inputs and tied with the others at
N=16M.
-
hmm so no big speedup today... the profile points to reading data as the main bottleneck on the large input, so optimizing the reduction work didn't help much.


Day 89
- i wanted to continue profilemaxxing, but i didn't have time... life happened. so instead, i solved the LeetGPU Row-wise Argmax problem. the task is given a B x V matrix of logits, we need to find the index of the largest value in each row.
- we have seen this sort of reduction pattern in so many problems already... is like old movie by now...:) some examples: Layer Normalization on Day 41, Group Normalization on Day 54, etc. the idea is simple each thread computes a partial result, then we combine those results across all blocks.
- the twist here is that
warp_reduce_maxneeds to keep track of both the maximum value and its index. so we use__shfl_down_synctwice at each step, once for the values and once for the indexes. and whenever another thread has a larger value, we take both. see image below for more details.
-
since you've made it this far, here is a nugget of "wisdom": when do you know you understand an algorithm? for me, it's simple... when you can modify it as you like. this means you've internalized the underlying abstraction, and the new algorithm becomes a superpower for solving even more problems. let's take BFS as an example. you can use it to solve graph problems; that's the obvious use case (anyone can see that). but you can also use it to calculate the minimum number of moves a knight needs to reach a target cell. once you've learned the algorithm, you see it everywhere. your mind connects the dots, and you become neo looking at the matrix.

Day 90
- solved the LeetGPU Fused AdamW problem. this problem is misclassified... it's definitely an easy task.
- AdamW is the optimizer behind many modern LLM training runs (GPT, LLaMA, and friends). if you're wondering what an optimizer does... it uses gradients to decide how to update model parameters during training.
- so not much to say here... just follow the formula. if you want to learn more, check out the paper Decoupled Weight Decay Regularization.
- oh, almost forgot...
__restrict__makes a lot of sense here. we updateparams[n], write tom[n]andv[n], then useparams[n]again. since we know for sure the buffers don't overlap, but the poor compiler can't assume that. so__restrict__tells the compiler: "hey compiler, it's fine to keep the values in a register instead of loading them again".
- i'm still doing some profiling for the next post. turns out this takes more time than i expected...

Day 91
- solved the LeetGPU Scatter Add problem. according to the problem statement, this is the operation behind torch.index_add_, used to combine MoE outputs and aggregate messages in neural networks.
-
this one looked scary at first... a more detailed example would have helped. but once you decode the sum notation, the kernel is pretty simple. here's the idea:
for each (i, d), where 0 <= i < N and 0 <= d < D: m = index[i] atomicAdd(&output[m * D + d], src[i * D + d])
-
we use one thread per
(i, d)pair.atomicAddis needed because multiple threads can update the same output element at the same time. see image below for more details.
Day 92
-
solved the LeetGPU Grouped GEMM problem. for this one the idea is to bundle several independent matrix multiplications into one grouped GEMM call. grouped GEMM is a core building block of Mixture-of-Experts (MoE) inference. see the image below for an explanation of how it works.

- i tried three solutions and benchmarked them. the baseline (v0) copies the group offsets from device to host memory, then launches a tiled matmul for each group, one after another. pointer offsets select the inputs and output for each group, just like on Day 38 and Day 47. simple enough... but many groups mean many kernel launches, which is not good.
- for v1 single launch, i used
blockIdx.zto pick the current group. in this solution, one kernel launch handles all groups.
- for v2 streams, i kept one matmul launch per group of the baseline, but spread them across eight CUDA streams. since the groups are independent, we can run those matmuls in parallel, so we don't wait for the previous group to finish.
-
on the LeetGPU perf. test, all three were within 3%... basically tied :) on the larger cases, streams were roughly 10% faster than the baseline, while the single launch version got slower as the number of groups grew, likely because it launches many blocks that exit without doing any work.

Day 93
- solved the LeetGPU Split-KV Attention Reduction problem. to provide a bit of context... when an llm generates text one token at a time during decoding, it has to compute attention over a long KV cache. the problem is that this can be slow if the work can't be distributed across SMs. Split-KV helps solve that by breaking the cache into chunks, so multiple blocks can compute attention in parallel across more SMs. after that, we merge the partial attention outputs using log-sum-exp. by spreading the work across more of the GPU, decoding becomes faster.
- according to my research, this technique appeared for the first time in the blog post Flash-Decoding. this problem is about the final reduction part.
- so i didn't have time to optimize this properly, so i went with the first thing that came to mind :) follow your instincts, this is the way!
- my solution is just three simple kernels: find the maximum log-sum-exp per head (using the same reduction pattern as LayerNorm on Day 41), compute weights, then calculate the weighted average. see image below for more details.
-
anyway, i have a feeling this can be done in a single kernel without extra allocations. i'll revisit this one another day.

Day 94
- solved the LeetGPU Fused Residual Add and LayerNorm with Saved Statistics problem. this one is labeled "hard" but is actually a "medium"... we just need to add a residual and then apply the same layer normalization we used on Day 41.
- the "saved statistics" part means we have to return four outputs: the residual sum, the row means, the row reciprocal standard deviations (rstd), and the final normalized values. as usual, we kept it simple and created a kernel for each of those. see image below for a small example of the whole flow.
-
one obvious thing to try next is to combine these steps into a single kernel... the word "fused" in the title gave it away :) i'll revisit this one some other time.

Day 95
- solved the LeetGPU Integral Image problem. this one is basically a 2D prefix sum... each output cell stores the sum of the rectangle from the top-left corner to that cell, including the cell itself.
- not much time today, so kept it simple... one kernel computes cumulative sums across the rows, then another does the same down the columns. see image below for a small example of the two passes.
-
one more thing... if you look at the code
scan_colsis fine because the threads read values that sit next to each other in memory. butscan_rowsgives each thread a different row, so their reads are W floats apart at each step. that's not great for memory coalescing... we need to revisit this one.
Day 96
- solved the LeetGPU RMS Norm Backward problem. with this one, i experienced one of the greatest joys a programmer can feel while writing code by hand...the solution passes all the tests on the first try. considering this was a relatively long problem, that felt especially good, man AI is taking that away from us...
- so this is the backward pass of RMS Normalization, which we first solved on Day 20. given the gradient
dy, we need to compute the gradients for the input (dx) and the weights (dweight).
- not much to explain here... follow the formulas and keep track of which dimension you're reducing. i added an image below to make the steps easier to follow.
-
we've seen these kind of reductions plenty of times by now... if you would like a bit more of practice, check out problems: Batch Normalization on Day 39 and Layer Normalization on Day 41

Day 97
- solved the LeetGPU Multi-LoRA Batched Linear problem. we have seen LoRA (Low-Rank Adaptation) before on Day 32. this time around each token can use a different LoRA "adapter".
- so what exactly are those "adapters"? think of an adapter as a plugin that helps the model to specialize in a different topic, while the original model weights stay the same. for example we could have a LoRA adapters for python, cat memes, etc.
- this problem looked a bit "innocent" at first, but the constraints made it difficult to pass the perf. test with a naive solution. since i had some time, i tried four different versions: the first two timed out, the third passed but was really slow, and the fourth probably is what i should have been doing since the beginning... :)
- the first solution copies all the adapter ids to cpu memory, then launches separate matmuls for each token. simple enough... but that's a lot of kernel launches, timeout!
- for the second solution, i moved everything into one kernel, with one thread per token, and used a bunch of cpu-fashion device functions. fewer launches, but since each thread computes all the dot products with serial loops... too much work for one thread, timeout!
- the third solution computes
xWfor the whole batch in one tiled matmul, then handles the LoRA part for each token separately. better, but that CPU loop launching kernels per token is still there, this solution pass all the perf. test in around 235 ms.
- the fourth solution uses three kernels for the whole batch.
lora_down,matmul, andlora_up. everything stays on the gpu, with no memory copies back to the cpu. this one ran in 49 ms on the perf. test. see the image below for how it works.
-
if you want to learn more about LoRA, check out Punica: Multi-Tenant LoRA Serving, S-LoRA: Serving Thousands of Concurrent LoRA Adapters, and the original paper: LoRA: Low-Rank Adaptation of Large Language Models.

Day 98
- solved the LeetGPU Gated Attention problem. LeetGPU recently added many new attention problems. these are a lot of fun... you can focus on implementing algorithm first, then read the paper with a head start. less scary that way. :)
- gated attention adds a learned "gate" to attention. you can think of a gate as a matrix of values between 0 and 1 that controls how much of each attention output element we keep. a gate value of
0.8means we keep 80% of the corresponding output value, so the model can say "less of this, please..., more of that instead...".
- for the implementation, i reused the pointer trick from Day 38 and Day 50. move the pointers to the current head, and then the kernels can work with ordinary matrices. the rest is just a few pretty standard kernels: tiled matmul, row-wise softmax, sigmoid, and an elementwise matmul. see the image below for the full flow.
-
if you want to learn more, check out the paper Gated Attention for Large Language Models: Non-linearity, Sparsity, and Attention-Sink-Free.

Day 99
- solved the LeetGPU LayerNorm Backward problem. this is the backward pass of the Layer Normalization we solved on Day 41.
- this one is pretty similar to RMS Norm Backward on Day 96, just a bit more work because the formulas are a little bit more complicated... i kept the computation into separate kernels, so each step maps directly to the formulas.
- a nugget of "wisdom": start with simple kernels and get a working version first... then you'll have a better idea of which kernels to merge and which to keep separate. or, to put it another way: "premature kernel merging is the root of all evil."
-
clearly, we can optimize this even more by merging some of these kernels, for example we can calculate dgamma and dbeta in one pass. i'll leave that as an exercise for the reader... haha kidding, i will revisit this one as well at some point, stay around! :)

Day 100
- solved the LeetGPU Paged KV-Cache Attention problem. the idea of paged attention is to store the keys and values from previous tokens in fixed-size blocks instead of one big continuous chunk of memory. by doing this, we waste less GPU memory and can serve more sequences (users) at once.
-
we use a block table to find the keys and values for each token... is just a bit of index "pain", stay with me... :)
blk_logical = t / block_size blk_slot = t % block_size blk_physical = block_table[s * max_blocks_per_seq + blk_logical] blk_offset = blk_physical * (block_size * num_heads * head_dim) + blk_slot * (num_heads * head_dim) + h * head_dim k = K_cache + blk_offset v = V_cache + blk_offset
-
once you find the relevant blocks, it's the attention we have seen before... compute the scores, apply softmax, then use those weights to combine the values. see the image below for a small example of how it works.

- if you want to learn more, check out the paper Efficient Memory Management for Large Language Model Serving with PagedAttention.

