
new eras don't come about because of swords, they're created by the people who wield them
Berlin, Germany
Joined August 2011
- Tweets790
- Following1.1K
- Followers1.9K
- Likes5.6K
Pinned Tweet
i’m documenting my 100 Days of CUDA journey.
my progress so far beautifully organized in one place, with notes, visual explanations, and links to the code.
if you’re learning CUDA or GPU programming, follow along:
pavelsimo.github.io/100-days…
Day 34/100 of Inference Engineering
> today we continue with chapter 4 of cuda for llms: "training and verifying neural nets in raw cuda".
> so now that we have a python baseline implementation, we're ready for the next part backpropagation.
> but... before diving in backpropagation, let's make sure the neural network basics are clear.
> let's imagine for a second a graph with nodes and edges. if you have trouble to imagining it... all good, see image below :)
> the network neurons are the nodes. this includes the input, the hidden state, and the output.
> the weight matrices are the edges of that graph. why is that the case? you can think of a matrix as a mapping between rows and columns: each cell is a weight connecting two neurons.
> how about activations? those are usually nonlinear functions applied to each neuron element by element. they are usually applied to the hidden states (intermediate nodes) to stop stacked layers from collapsing into a single linear layer.
> for a multilayer perceptron, when we say it has two layers, that means it has two weight matrices (w1, w2).
> ok... so now that we know how a network is put together, how do we figure out which weights to change? that's where backpropagation comes in.
> backpropagation is a elegant application of the calculus chain rule.
> the chain rule let us calculate how any given weight affects the final loss by "propagating" the gradient backward.
> backpropagation is basically how a neural network assigns blame for a bad guess...
> starting from the final error, the loss, it works "backward" layer by layer, using the values it saved on the way forward, to figure out exactly which way to nudge every weight so next time around the model can make better guesses.
> for example in z = 2*w1 + 3*w2 + 1, dz/dw1 = 2 tells us how z changes when only w1 changes. basically, if we increase w1 by 1, z goes up by 2, assuming w2 stays the same.
> our multilayer perceptron (mlp) it uses two linear layers, a linear layer is of the form Y = XW + B, for those kind of layers the gradients are given by formulas below, we can use those to calculate our backward pass.
dL/dW = X^T @ (dL/dY)
dL/db = sum(dL/dY, axis=0)
dL/dX = (dL/dY) @ W^T
> finally, during training is really important to monitor the "magnitude" of your gradients.
> if they become really big (exploding) or really small (vanishing), they can "mess up" the learning process. you can do this with code, makes a lot of sense to check as training progress.
> this is fine for today, we're not done with backpropagation... we will continue tomorrow, stay around!
Day 33/100 of Inference Engineering
> today i continue with chapter 4 of cuda for llms: "training and verifying neural nets in raw cuda".
> the main focus today was the python baseline implementation.
> i followed the code in the book, and since i wanted to learn a bit from what was written, i rewrote it by hand.
> this is a bit waste of time... but doing that you're forced to pay more attention when writing each line.
> nevertheless, a lot of what is in there is boiler plate... once you write once is pretty much the same each time.
> the script has four main parts: load data, build the model, train, and evaluate.
> so the sequence of steps goes as follow:
> first, we load the mnist images and labels. the book provided a script to download a dataset of 10,000 images.
> we don't use the image as they are we first normalize them using the following code:
mean, std = 0.1307, 0.3081
X_train = (X_train - mean) / std
X_test = (X_test - mean) / std
> so here subtracting the mean centers the pixel values around zero, and dividing by the std dev. puts them on a "nice" scale. this helps keep training stable...
> second, we build the mlp. we take each 28 x 28 image and flatten it into 784 pixel values. these go through a hidden layer with 128 neurons, then relu... and finally an output layer that gives us 10 scores, one for each digit.
class MLP(nn.Module):
def __init__(self, in_features, hidden_features, num_classes):
super(MLP, self).__init__()
self.fc1 = nn.Linear(in_features, hidden_features)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_features, num_classes)
def forward(self, x):
x = x.reshape(x.shape[0], 28 * 28)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
> third, we implement the training loop to calculate the loss for each batch.
> we use the sgd optimizer to update the weights, with a learning rate of 0.01.
> in case you don't know, sgd (stochastic gradient descent) uses the gradients to nudge the weights in a direction that should reduce the loss. the learning rate, 0.01 here, controls how big each step is.
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
> finally, we check the model on the test images with gradients turned off. this is because we don't need to run the backward pass for making predictions... the highest score gives us the predicted digit, which we compare with the label to calculate accuracy.
> ah, important... pytorch has model.eval(), which puts the network in evaluation mode (for doing inference), and model.train(), which puts the model in training mode. see the image below to understand the differences.
> if you would like to check out the code, go to my repo below.
Pavel Simó retweeted
How to actually read an LLM's name
Model names like Qwen3.8-27B-Instruct-UD-Q4_K_M.gguf can look like a random string of letters. Each part answers a practical question about the file, and once you can read them, picking the right download gets much easier.
Here's that name, read left to right.
The first three parts tell you which model you're getting:
↳ Qwen3.8 is the model family and its version.
↳ 27B means 27 billion parameters, the numbers the model learned during training. More parameters usually means a more capable model that needs more memory.
↳ Instruct means it was trained further to follow instructions, which is what you want for chatting. Base means it only learned from raw text, FP8 means each number is stored in 8 bits, and a date code marks the release.
The rest only matters when you run the model on your own machine. At full 16-bit precision, a 27B model needs over 50 GB of memory, so people publish compressed versions that store each number in fewer bits and give up a little quality for a much smaller file.
↳ UD is Unsloth Dynamic. Unsloth is an open-source project that publishes many of these files on Hugging Face, and its Dynamic method compresses the most sensitive parts of the model less.
↳ Q4 means about 4 bits per number.
↳ K means llama.cpp's k-quants, which group numbers into small blocks that share one scale so they stay accurate at low bit counts.
↳ M is the medium mix, which keeps some sensitive parts at 6 bits. The S (small) mix keeps everything at 4.
↳ .gguf is the file format that llama.cpp, LM Studio and Ollama load.
That puts Q4_K_M closer to 5 bits per number, about a third of the original. Unsloth's file is a little over half the size of the 8-bit version.
Mixture of Experts models add an "A" part for active parameters. Qwen3.8-2.4T-A95B is split into 512 smaller sub-networks called experts, and for every token (a word or piece of a word) a router picks 10 of them, plus 1 shared expert that every token goes through.
All 512 experts stay in memory, so you still need room for the full 2.4T parameters. Only those 11 experts run on each token, though, so each token takes about as much work as it would on a 95B model.
Some names leave out the size, like Thinking Machines' Inkling 2 Mini, and you only find it on the model card.
With these parts decoded, the file list on any model page tells you which download fits your machine.
Reading the name tells you what each file is. Picking the one that runs well on your machine also depends on your memory speed and runtime settings, and I recently wrote a detailed guide on how to choose the right model for your machine.
The article is quoted below.
really nice post about independent thread scheduling:
Most of us while learning CUDA are taught that all 32 threads in an NVIDIA warp execute together but apparently since the Volta architecture the GPU actually maintains a separate program counter and call stack for every individual thread.
This is something called Independent Thread Scheduling.
So let me put some light on what exactly changed here.
Before volta all 32 threads within a warp shared a single program counter. A program counter basically keeps track of which instruction needs to be executed next.
Now lets say we have a warp of 32 threads and somewhere in our kernel we have an if else condition where
Threads 0-15 → execute condition A
Threads 16-31 → execute condition B
Since the entire warp shares a single program counter, the gpu executes one branch while masking out the threads belonging to the other branch and then executes the other branch.
This is what we call warp divergence.
Now with volta NVIDIA changed how the execution state of these threads is maintained.
Instead of having a single program counter for the entire warp each thread gets its own program counter and call stack.
So threads within the same warp can now be at different points of execution and the GPU can suspend or resume execution at an individual thread level.
But does this mean all 32 threads can now execute 32 completely different instructions simultaneously?
Nope.
The gpu still groups active threads from the same warp that can execute the same instruction together. Warp divergence can still cost us performance.
Now one of the problems that comes with this change is that we can no longer assume that threads within a warp will automatically reach the same instruction together.
Lets say thread 0 writes a value into shared memory and thread 1 needs to read that value in its next instruction.
If we dont explicitly synchronize them there is no guarantee that thread 0 has finished writing before thread 1 tries to read it.
and this is exactly why some older CUDA kernels which relied on implicit warp synchronization had to be modified for volta and newer architectures.
CUDA provides __syncwarp() which allows us to explicitly synchronize the participating threads within a warp and also ensures proper memory ordering between them.
Image source: Farkhor, Per-thread program counters: a tale of two registers, (Medium Blog)
Pavel Simó retweeted
writing amd gemm kernels on mi300x
currently at 10 kernels, for today experimented a bunch with larger loads, padding and increasing lds reads and registers reads.
you should find all the code here - github.com/JINO-ROHIT/kernel…
writing amd gemm kernels on mi300x
on the last kernel we did a local prefetch, the limitation of directly loading into lds is the amount of data tile you can process at one time. we had to reduce the tile size from 256x256 to 128x128 to make this work.
in the previous kernel, the direct copy moves two FP16 values per lane from global memory to LDS. In this kernel, each lane loads eight consecutive values along K into VGPRs (16 bytes), then writes them to LDS.
all the amd kernels with progression here - github.com/JINO-ROHIT/kernel…
Day 33/100 of Inference Engineering
> today i continue with chapter 4 of cuda for llms: "training and verifying neural nets in raw cuda".
> the main focus today was the python baseline implementation.
> i followed the code in the book, and since i wanted to learn a bit from what was written, i rewrote it by hand.
> this is a bit waste of time... but doing that you're forced to pay more attention when writing each line.
> nevertheless, a lot of what is in there is boiler plate... once you write once is pretty much the same each time.
> the script has four main parts: load data, build the model, train, and evaluate.
> so the sequence of steps goes as follow:
> first, we load the mnist images and labels. the book provided a script to download a dataset of 10,000 images.
> we don't use the image as they are we first normalize them using the following code:
mean, std = 0.1307, 0.3081
X_train = (X_train - mean) / std
X_test = (X_test - mean) / std
> so here subtracting the mean centers the pixel values around zero, and dividing by the std dev. puts them on a "nice" scale. this helps keep training stable...
> second, we build the mlp. we take each 28 x 28 image and flatten it into 784 pixel values. these go through a hidden layer with 128 neurons, then relu... and finally an output layer that gives us 10 scores, one for each digit.
class MLP(nn.Module):
def __init__(self, in_features, hidden_features, num_classes):
super(MLP, self).__init__()
self.fc1 = nn.Linear(in_features, hidden_features)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_features, num_classes)
def forward(self, x):
x = x.reshape(x.shape[0], 28 * 28)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
> third, we implement the training loop to calculate the loss for each batch.
> we use the sgd optimizer to update the weights, with a learning rate of 0.01.
> in case you don't know, sgd (stochastic gradient descent) uses the gradients to nudge the weights in a direction that should reduce the loss. the learning rate, 0.01 here, controls how big each step is.
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
> finally, we check the model on the test images with gradients turned off. this is because we don't need to run the backward pass for making predictions... the highest score gives us the predicted digit, which we compare with the label to calculate accuracy.
> ah, important... pytorch has model.eval(), which puts the network in evaluation mode (for doing inference), and model.train(), which puts the model in training mode. see the image below to understand the differences.
> if you would like to check out the code, go to my repo below.
Day 32/100 of Inference Engineering
> today i started chapter 4 of cuda for llms: "training and verifying neural nets in raw cuda".
> from what i can see, this is where the meat of the book starts. this chapter should take a little bit longer since there are a few hands-on exercises. anyway... it does not make sense to speedrun the book!
> since we are going to implement a neural network from scratch in cuda, we need a way to verify that what we implement is correct. the book recommends creating a sample pytorch implementation as baseline.
> this makes a lot of sense, pytorch is battle tested library, if our solution output similar values we can be pretty confident it works.
> so the first part of the chapter is how to implement a multilayer perceptron (mlp) for mnist.
> mnist if you never heard of is kind of the "hello world" of computer vision, you are given 28 x 28 pixel images with handwritten digits, and the goal is to predict the actual digit it represents (0-9).
> one of the challenges when doing this kind of multi-language implementations is to make sure the different versions can be compare.
> the book explains that to compare among different implementations, for example pytorch, numpy, c and cuda, we should consider the following:
> first, we replace the default pytorch weight initialization with our own "kaiming he" initialization. this way, all four implementations initialize their weights the same way.
> then we compare the loss curves. the weights won't match exactly because each version uses a different random number generator... even with the same initialization scheme.
> if you're wondering what is kaiming he? it is a weight initialization scheme that helps prevent vanishing and exploding gradients during training.
> "exploding" here means the gradients get so large that each update changes the weights too much, making training unstable.
> finally, we need a training loop that also tracks how long each part takes: the forward pass, calculating the loss, and computing the gradients...
> alright, let's leave here today... tomorrow we will focus on the implementation. i will try to break down the most important parts of the pytorch baseline implementation.
Pavel Simó retweeted
reading about minimax sparse attention
arxiv.org/pdf/2606.13392
Pavel Simó retweeted
CUDA GEMM explained through profiling
the kernel has the familiar ingredients:
> shared-memory tiling
> register blocking
> coalesced input loads
> 16 output accumulators per thread
60 small shape/pattern/kernel checks passed.
on my RTX 4060 Laptop, for 1024×1024×1024:
> my kernel: 1.005 ms
> cuBLAS: 0.360 ms
> pedantic FP32 comparison
roughly 2.8× slower in that run.
then Nsight reported 85.1% “compute throughput”.
looking closer:
> load/store pipeline: 85.1%
> FMA pipeline: 22.1%
> DRAM throughput: 4.7%
the aggregate number alone doesn't explain where the work is going. so the scheduler added another clue:
> achieved occupancy: 69.8%
> no eligible warp: 51.8% of scheduler cycles
occupancy tells me how many warps are resident. eligibility tells me whether they can issue their next instruction.
having work resident doesn't guarantee that work is ready.
Nsight also flagged MIO queue throttling—pressure on an instruction queue that includes shared-memory operations.
shared-memory instruction pressure is a hypothesis worth investigating. the exact cause still needs source-level evidence.
fewer or wider shared-memory loads are one experiment to test, while watching register use, occupancy, and elapsed time.
these are initial measurements with uncontrolled clocks and repeated buffers. profiler captures are separate from benchmark timings.
my takeaway: an optimization should target a specific resource, carry a testable hypothesis and earn its place through measured latency.
Day 32/100 of Inference Engineering
> today i started chapter 4 of cuda for llms: "training and verifying neural nets in raw cuda".
> from what i can see, this is where the meat of the book starts. this chapter should take a little bit longer since there are a few hands-on exercises. anyway... it does not make sense to speedrun the book!
> since we are going to implement a neural network from scratch in cuda, we need a way to verify that what we implement is correct. the book recommends creating a sample pytorch implementation as baseline.
> this makes a lot of sense, pytorch is battle tested library, if our solution output similar values we can be pretty confident it works.
> so the first part of the chapter is how to implement a multilayer perceptron (mlp) for mnist.
> mnist if you never heard of is kind of the "hello world" of computer vision, you are given 28 x 28 pixel images with handwritten digits, and the goal is to predict the actual digit it represents (0-9).
> one of the challenges when doing this kind of multi-language implementations is to make sure the different versions can be compare.
> the book explains that to compare among different implementations, for example pytorch, numpy, c and cuda, we should consider the following:
> first, we replace the default pytorch weight initialization with our own "kaiming he" initialization. this way, all four implementations initialize their weights the same way.
> then we compare the loss curves. the weights won't match exactly because each version uses a different random number generator... even with the same initialization scheme.
> if you're wondering what is kaiming he? it is a weight initialization scheme that helps prevent vanishing and exploding gradients during training.
> "exploding" here means the gradients get so large that each update changes the weights too much, making training unstable.
> finally, we need a training loop that also tracks how long each part takes: the forward pass, calculating the loss, and computing the gradients...
> alright, let's leave here today... tomorrow we will focus on the implementation. i will try to break down the most important parts of the pytorch baseline implementation.
Day 31/100 of Inference Engineering
> today i finished chapter 3 of cuda for llms: "naive kernels".
> continuing with the fundamental operations, we have softmax.
> softmax is a normalization method. its goal is to take arbitrary real valued scores (logits) and transform them into probabilities, where each element is between 0 and 1.
> when implementing softmax, you have to be careful when calling exp with large values, because this can cause overflow.
> so you want a softmax that is "numerically stable", a fancy way to say you want a softmax that works... :)
> how do you make softmax numerically stable? find the largest input value, then subtract it from each input before calling exp, like this exp(val - max_val). this avoids overflow without changing the final probabilities.
> then we have convolutions...
> convolution is a downsampling operation that helps neural networks find patterns in the given data, edges, textures, etc.
> convolutions come in multiple dimensions: 1d, 2d, 3d, etc.
> the way convolutions work is by sliding a filter (a.k.a. the kernel) across the given input. at each position, you need to compute the dot product between the filter and the region that overlaps with the filter.
> finally, we have max pooling. this one is just like a convolution, but instead of computing a dot product, you just take the largest value in each window.
> one more thing... if you want to learn more, i recommend trying the leegpu problems: 1d convolution, 2d convolution, 3d convolution, max pooling, and softmax, since those are the most relevant to this chapter. in my 100 days cuda series there are explanations in case you get stuck.
> try working through each problem before looking at the solution. even if your code is a bit messy, figuring it out yourself helps the ideas stick. then, when you compare your solution with the "real" solution, you can spot simpler ways to do things and understand why they work.
> remmeber... never, never, never let someone spoil a nice problem for you, always try on your own first! that grinding is the best opportunity to take your thinking to the next level.
just put together all the leetgpu solutions from my 100 Days of CUDA series in one nicely organized repo:
github.com/pavelsimo/leetgpu
i’m documenting my 100 Days of CUDA journey.
my progress so far beautifully organized in one place, with notes, visual explanations, and links to the code.
if you’re learning CUDA or GPU programming, follow along:
pavelsimo.github.io/100-days…
Day 31/100 of Inference Engineering
> today i finished chapter 3 of cuda for llms: "naive kernels".
> continuing with the fundamental operations, we have softmax.
> softmax is a normalization method. its goal is to take arbitrary real valued scores (logits) and transform them into probabilities, where each element is between 0 and 1.
> when implementing softmax, you have to be careful when calling exp with large values, because this can cause overflow.
> so you want a softmax that is "numerically stable", a fancy way to say you want a softmax that works... :)
> how do you make softmax numerically stable? find the largest input value, then subtract it from each input before calling exp, like this exp(val - max_val). this avoids overflow without changing the final probabilities.
> then we have convolutions...
> convolution is a downsampling operation that helps neural networks find patterns in the given data, edges, textures, etc.
> convolutions come in multiple dimensions: 1d, 2d, 3d, etc.
> the way convolutions work is by sliding a filter (a.k.a. the kernel) across the given input. at each position, you need to compute the dot product between the filter and the region that overlaps with the filter.
> finally, we have max pooling. this one is just like a convolution, but instead of computing a dot product, you just take the largest value in each window.
> one more thing... if you want to learn more, i recommend trying the leegpu problems: 1d convolution, 2d convolution, 3d convolution, max pooling, and softmax, since those are the most relevant to this chapter. in my 100 days cuda series there are explanations in case you get stuck.
> try working through each problem before looking at the solution. even if your code is a bit messy, figuring it out yourself helps the ideas stick. then, when you compare your solution with the "real" solution, you can spot simpler ways to do things and understand why they work.
> remmeber... never, never, never let someone spoil a nice problem for you, always try on your own first! that grinding is the best opportunity to take your thinking to the next level.
Day 30/100 of Inference Engineering
> today i started chapter 3 of cuda for llms: "naive kernels".
> this chapter is an introduction to many fundamental operations in deep learning, the goal of the author is not optimize kernels, is guide us to write simple and correct kernels first.
> the book explains that writing "correct" cuda kernels is not a trivial task... i agree with this statement. remember: "good programming is hard, bad programming is easy," -- mike acton.
> writing programs that makes a gpu go brrr is not easy, which is why is fun :)
> the author suggest that it helps to first write a cpu version that you can use to verify the results of your kernel(s).
> so... first implement on cpu, then implement on gpu, finally verify...
> the first of the fundamental operations is matrix transpose.
> a matrix transpose is really just a data reshaping operation, this means the same physical memory can be interpreted with different logical layouts.
> this is super useful because, when multiplying against a matrix transpose, you don't need to actually materialize the transpose, but instead navigate the indexes in a different order. the image below should make this clear.
> if you don't know what i mean by materializing the matrix, it means actually allocating a matrix in vram using cudamalloc. remember what we learned about the memory pyramid? this means going all the way down in the pyramid, which is not cheap...
> the second fundamental operation is gemm, which stands for general matrix multiply.
> gemm is the main resposible for all the cat generated videos you see on your X feed :)
> joke aside... this operation is at the heart of modern deep learning. from mlps, attention, etc.
> for gemm, there is a naming convention for the matrices: K is the dimension that both matrix A and matrix B share.
A -> M x K
B -> K x N
C -> M x N
> in simple terms gemm, is just take a row from A and a column from B, compute their dot product, and put the result in the matching cell of C. we repeat this for every row and column pair and we're done...
> for the cpu version we need two outer loops for the (row, col) pairs, for the cuda kernel we can do this with our besty the global indices:
int col = blockIdx.x * blockDim.x + threadIdx.x;
int row = blockIdx.y * blockDim.y + threadIdx.y;
> the cool thing about the kernel is that all cells are computed in parallel, see the power? instead of having one cpu thread loop and calculate the dot products for all cells...
Pavel Simó retweeted
Paper copies of Inference Engineering are back in stock!
baseten.co/inference-enginee…
I'll also be giving away copies in person all week at AWS re:Invent, stop by the Baseten booth in the expo hall.
Pavel Simó retweeted
CUDA GEMV example explained
first basics:
GEMV multiplies a matrix by a vector.
think of one token's activations passing through a linear layer:
y[n] = sum(W[n,k] * x[k])
each output is one dot product.
a warp is 32 threads. each thread's position inside it is called a lane.
let's dig into a kernel -
store W row-major as [N,K].
give one warp an output row:
lane = threadIdx.x & 31
row = blockIdx.x * 4 + (threadIdx.x >> 5)
with 128 threads per block, that's four warps computing four outputs.
> split the row
each lane starts at its own column and advances by 32:
for (k = lane; k < K; k += 32)
sum = fmaf(W[row*K + k], x[k], sum)
lane 0 handles columns 0, 32, 64...
lane 1 handles columns 1, 33, 65...
neighboring lanes read neighboring weights.
> keep partial sums in registers
each lane accumulates its own slice.
we now have 32 partial answers for one output.
> combine them
shuffle down by:
16 → 8 → 4 → 2 → 1
at each step, lanes add values obtained from other lanes.
after the reduction, lane 0 holds the complete dot product and writes it.
no shared memory is needed for this version.
> trace actual numbers
constructed example:
K = 64
x = all ones
one weight row = [1, 2, ..., 64]
lane 0 accumulates 1 + 33 = 34
lane 1 accumulates 2 + 34 = 36
...
lane 31 accumulates 32 + 64 = 96
the warp combines:
34 + 36 + ... + 96 = 2080
that's also 1 + 2 + ... + 64.
same dot product, distributed across 32 lanes.
>to handle the edges: if K is smaller than 32, lanes without elements still participate in the reduction with zero.
don't casually return those lanes before a full-warp shuffle.
> verify before claiming performance
this baseline includes CPU-reference checks, cuBLAS comparison, and CUDA-event timing.
compilation and GPU validation are still pending.
the mental model: one warp owns an output; its lanes divide the input row.
Pavel Simó retweeted
I think nowdays understanding LLM's are super important, this video is really a gem for getting this.
absolutely worth it and give a watch [gradually understand every single concepts].
this covers tokenization, data engineering, pretraining, scaling laws, supervised fine-tuning etc. [a lott of stuffs]

































