iTranslated by AI
Building Custom CUDA Kernels for LLMs
This article is the 21st entry for the LLM/LLM Utilization Advent Calendar 2025.
Introduction
PyTorch is a Python library for machine learning and deep learning developed by Meta. By using PyTorch, users can build a wide variety of neural network models, ranging from image classification models and reinforcement learning models to large language models (LLMs) and diffusion models.
Furthermore, PyTorch implements optimized processing for various processors such as CPUs, TPUs, and GPUs, allowing users to easily switch between them. For instance, if you want to perform inference for a large language model on a GPU, you would write the code as shown below. In this way, users can execute operations using the GPU simply by attaching .to("cuda") to the input tensor and the model instance. In processing using the GPU, CUDA functions are executed.
# Define the input tensor
x = torch.randn([1,256],dtype=torch.float32)
# Define the model
model = GPT2()
""" Inference using CPU """
y = model(x)
""" Inference using GPU """
# By simply attaching .to("cuda") to x and model, calculation on the GPU is possible
x = x.to("cuda")
model = model.to("cuda")
y = model(x)
So, what kind of CUDA functions are executed on the GPU when performing operations using PyTorch? In this article, we will take a GPT2 model as our subject and implement the CUDA functions executed inside the model from scratch. Through this, we will deepen our understanding of the CUDA functions running inside PyTorch.
The structure of the GPT2 model we will create in this article is as follows.

Created with some modifications by referring to rasbt/LLMs-from-scratch
This article covers the following contents:
- How to implement the forward and backward pass CUDA functions for each layer of the GPT2 model from scratch
- How to create a custom PyTorch class and execute CUDA kernels from it
- How to train the self-made GPT2 model using a Japanese dataset
Related Information
This section describes the related information necessary for creating the CUDA functions for the GPT2 model.
CUDA
CUDA is a programming language that NVIDIA GPUs can process.
CUDA is a C++ extension, and it can be used by adding a few lines to a C++ CMakeLists file.
An example of CUDA is as follows. You can see that it has a syntax similar to C++.
__global__ void AddKernel(float *a, const float *b, float *c, int numElements)
{
int i = blockDim.x * blockIdx.x + threadIdx.x;
if (i < numElements) {
c[i] = a[i] + b[i];
}
}
The AddKernel function above is a CUDA kernel function. Functions with the __global__ qualifier are called CUDA kernels.
CUDA kernels are invoked from C++ code on the host (CPU) side using special syntax. For example, it looks like this:
torch::Tensor Add(torch::Tensor &a, torch::Tensor &b)
{
int numElements = a.numel();
a = a.contiguous();
b = b.contiguous();
float* a_ptr = (float*)a.data_ptr();
float* b_ptr = (float*)b.data_ptr();
auto options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA, 0);
torch::Tensor c = torch::empty_like(a, options);
float* c_ptr = (float*)c.data_ptr();
// Launch the Vector Add CUDA Kernel
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
AddKernel<<<blocksPerGrid, threadsPerBlock>>>(a_ptr, b_ptr, c_ptr, numElements);
return c;
}
CUDA Libraries
Similar to standard libraries in C++ such as vector.h or iostream.h, CUDA also has standard libraries. Some examples are as follows:
| Library Name | Content | Import |
|---|---|---|
| cuRAND | High-speed random number generation on GPU | #include <curand_kernel.h> |
| cuFFT | High-speed FFT and inverse transform on GPU | #include <cufft.h> |
| cuBLASLt | Linear algebra operations on GPU | <cublasLt.h> |
In this article, we will use cuRAND and cuBLASLt.
pybind
We will design the custom CUDA kernels to be called and executed from Python.
While it is possible to build, train, and run inference on models using only C++ and CUDA, it is more convenient to be able to execute custom CUDA kernels from Python in order to use matplotlib for graph visualization or to reuse existing training scripts written in Python. Therefore, we will use pybind to enable the execution of CUDA kernels from Python.
Detailed steps are as follows. Here, as an example, we describe how to call the aforementioned AddKernel function from Python.
First, create a pybind_connection.cpp file with the following definition:
#include <cuda_runtime.h>
#include <cuda_bf16.h>
#include <torch/extension.h>
#include <pybind11/pybind11.h>
#include "add.h"
py::object AddWrapper(py::handle a, py::handle b)
{
torch::Tensor a_tsr = a.cast<torch::Tensor>();
torch::Tensor b_tsr = b.cast<torch::Tensor>();
torch::Tensor out_tsr;
out_tsr = Add(a_tsr, b_tsr);
return py::cast(std::move(out_tsr));
}
PYBIND11_MODULE(add_kernel_lib, m)
{
m.doc() = "self-made torch kernel library";
m.def("add_kernel",&AddWrapper,py::arg("a"),py::arg("b"));
}
Also, write the following CMakeLists. It includes the add.cu file containing the AddKernel function and pybind_connection.cpp.
cmake_minimum_required(VERSION 3.12)
project(add_kernel_lib)
set(CMAKE_CXX_STANDARD 17)
find_package(CUDA REQUIRED)
find_package(PythonInterp 3.10 REQUIRED)
find_package(PythonLibs 3.10 REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
find_package(Torch REQUIRED)
find_library(TORCH_PYTHON_LIBRARY torch_python PATH "${TORCH_INSTALL_PREFIX}/lib")
include_directories(
${PYTHON_INCLUDE_DIRS}
./pybind11/include
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}
)
link_directories(/usr/local/cuda/lib64)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS} -Wall -g")
# Basically, you only need to change this part.
# Include add.cu and pybind_connection.cpp, and build as .so (SHARED)
cuda_add_library(add_kernel_lib SHARED
add.cu
pybind_connection.cpp
)
target_link_libraries(add_kernel_lib
${PYTHON_LIBRARIES}
cudart
${TORCH_LIBRARIES}
${TORCH_PYTHON_LIBRARY}
)
# add_compile_definitions(INFO=1)
set_target_properties(add_kernel_lib PROPERTIES PREFIX "")
# set_property(TARGET gpu_library PROPERTY CXX_STANDARD 17)
Then, use the following command to make add.cu and pytorch_connection.cpp based on the CMakeLists.txt description and generate the shared library add_kernel_lib.so.
source ../../.venv/bin/activate
mkdir -p build
cd build
export _GLIBCXX_USE_CXX11_ABI=1
export CMAKE_POLICY_VERSION_MINIMUM=3.5
cmake .. -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CUDA_ARCHITECTURES=89 \
-DCMAKE_PREFIX_PATH=$PWD/../libtorch \
-DCMAKE_CXX_FLAGS="-std=c++17"
make
By importing the created shared library as from add_kernel_lib import add_kernel, you can call the functions included in the library from Python.
import torch
from build.add_kernel_lib import add_kernel
a = torch.Tensor([3,4]).to(torch.float32).to("cuda")
b = torch.Tensor([2,3]).to(torch.float32).to("cuda")
c = add_kernel(a,b)
print(f"a: {a}")
print(f"b: {b}")
print(f"a+b = {c}")
By executing the add_cuda function, the AddKernel function is executed in the following invocation order:
(python) add_cuda -> (pybind_Connection.cpp) AddWrapper -> (add.cu) Add -> AddKernel
Libtorch
Libtorch is the C++ version of PyTorch. You can use it by downloading the latest package from here and linking it within CMakeLists.
An usage example is as follows. It can be used in almost the same way as the Python version of PyTorch.
#include <torch/torch.h>
#include <iostream>
using namespace std;
int main(void)
{
torch::Tensor x = torch::rand({1,256});
cout << x << endl;
return 0;
}
Backpropagation and Computational Graphs
In training neural network models, an evaluation metric called a loss function is used. For example, the MSELoss function, which is one such function, calculates the mean squared error between the model's output
In the case of MSELoss, the larger the value of the loss output by the loss function, the greater the difference between the model's output and the ground truth, while a smaller value indicates that the output is closer to the ground truth. In other words, the loss function is an indicator of how much the current neural network differs from the training data.
During training, the values of the learnable parameters that make up the model are updated so that the loss becomes as small as possible. Backpropagation is one of the methods used for training neural networks. By using the chain rule, gradients of the loss are calculated in reverse order from the output layer to the input layer to determine the gradient of each learnable parameter with respect to the loss. The obtained gradient indicates how a minute change in that parameter affects the loss. By updating the parameter in the direction of decreasing the loss if the gradient is positive, or increasing it if the gradient is negative, the loss can be reduced, bringing the model's output closer to the ground truth.
The chain rule states that "when differentiating a composite function consisting of multiple functions, the derivative of the composite function is given by the product of the derivatives of each function that composes it." For example, if there are two functions
By using the chain rule, it is possible to calculate the gradient values of each learning parameter with respect to the loss. The figure below illustrates a flow of training using the expression of a computational graph. The circles in the computational graph are called nodes, and the lines are called edges. In the figure below, W and b are learnable parameters, and L is loss. As shown, by using the chain rule, the gradient value of W, b,

Computational graphs follow specific rules, allowing values to be solved base on rules after passing through nodes for gradients that have been backpropagated. For example, the rules for the + node representing addition and the x node representing multiplication are shown in the figure. Using computational graphs in this way makes it relatively easy to calculate the gradient values of training parameters with respect to loss. Some of the CUDA kernels introduced later calculate the gradient values of training parameters using computational graphs.

The flow of calculation from the input layer to the output layer of the model is called forward propagation, and the flow of gradients based on the chain rule from the output to the input layer is called backpropagation.
Creating the Base CUDA Kernels
In this section, we will implement the base kernels and Python classes for building the GPT2 model. The heading for each section represents the Python class name, and each section is composed of forward, backward, and Python implementations. The forward part describes the processing executed during forward propagation, and backward describes the processing executed during backpropagation.
1. Linear
Linear is a function that applies an Affine linear transformation to the input x.
The Affine transformation is as follows, where W is weight and b is bias.
Weights and biases are learnable parameters. During training, the gradient values obtained through backpropagation are used to update the values of the weights and biases.
forward
Perform the Affine transformation mentioned above. First, calculate the inner product x and W using the Matmul function. Then, if a bias is defined (not None), add the bias. The content of the MatmulKernel, which is the main body of the Matmul function, will be described later.
backward
The implementation details for backward are as follows. If output_mask[0]=1, the gradient of x, dx, is calculated from the inner product of the backpropagated gradient dout and weight. If output_mask[1]=1, the inner product of dout and x is calculated, and the resulting column-wise values are summed using the SumBatchwise() function to calculate the weight gradient dweight. If output_mask[2]=1, the row-wise values of dout are summed using the SumColumnwise() function to calculate the bias gradient dbias.
During training, dweight is used to update weight, and dbias is used to update bias. Update formulas such as SGD or AdamW (described later) are used for this.
CUDA Kernels required for forward and backward
In addition to the Add operation, the forward and backward processes described above require Sub, Mul, Matmul, SumColumnwise, and SumRowwise functions. We will explain the main CUDA kernels for each.
The SubKernel, which is the main body of the Sub function, is as follows. It calculates the difference between each element of the tensors.
The MulKernel, which is the main body of the Mul function, is as follows. It calculates the product (Hadamard product) between each element of the tensors.
The MatmulKernel, which is the main body of the Matmul function, is as follows. It calculates the inner product of tensor a and tensor b.
The SumRowwiseKernel, which is the main body of the SumRowwise function, is as follows. It sums tensor a row-wise.
The SumColumnwiseKernel, which is the main body of the SumColumnwise function, is as follows. It sums tensor a column-wise.
python
The implementation of the Linear class in Python is as follows. By using pybind, executing linear_forward calls the LinearForward function, and executing linear_backward calls the LinearBackward function.
In PyTorch, by registering forward() and backward() functions using the class func(torch.autograd.Function): notation, when loss.backward() is executed, the backward() function is automatically called in sequence from the output layer to the input layer, executing backpropagation.
2. GELU
GELU (Gaussian Error Linear Unit) is one of the activation functions. Activation functions allow for the addition of non-linearity to the intermediate values of a model, enabling the output of more complex values and improving the overall performance of the model.
forward
According to arXiv:1606.08415, the calculation method for GELU is as follows:
The erf in equation (1) is the error function, which is defined in equation (2) (reference).
According to Abramowitz and Stegun, the error function in equation (2) can be approximated by equation (3) (reference 1, reference 2).
Also,
From equations (1) and (3), the CUDA kernel is as follows:
backward
The derivative calculation formula for
In this case,
Also,
The CUDA kernel is as follows. Multiplying the gradient backpropagated (grad) by the derivative formula above yields the gradient passed through GELU (out). cdf is pdf is
python
The implementation of the Gelu class in Python is as follows. By using pybind, executing gelu_forward calls the GeluForward function (which wraps GeluForwardKernel), and executing gelu_backward calls the GeluBackward function (which wraps GeluBackwardKernel).
3. Dropout
Dropout refers to an operation performed during training where elements of the tensor (activations) propagating through the model are randomly selected and set to 0 if their values are below a threshold. This has the effect of suppressing overfitting. During inference, since all elements are transmitted, each element's output is multiplied by the proportion that was not erased during training.
forward
First, let's implement it in Python to verify the processing content. The implementation in Python is as follows:
def forward(self, x, train_flg=True):
# Randomly erase neurons
if self.training: # During training
self.mask = np.random.rand(*x.shape) > self.dropout_ratio
return x * self.mask
else: # During test (inference)
return x * (1 - self.dropout_ratio)
We create a tensor of random numbers with the same shape as x, and create a mask tensor that is 1 if the value is greater than the dropout_ratio, and 0 otherwise. During training (when model.train() is called), we multiply the x tensor by the mask tensor to zero out the parts of the x tensor where the mask tensor is 0. During testing, we multiply by the ratio that was not erased during training (1 - self.dropout_ratio) and output it.
Here, we perform the 1/(1 - self.dropout_ratio) calculation during training as follows. This allows us to simply return x as-is during inference, enabling more efficient inference processing.
def forward(self, x, train_flg=True):
# Randomly erase neurons
if self.training: # During training
self.mask = np.random.rand(*x.shape) > self.dropout_ratio
return x * self.mask / (1 - self.dropout_ratio)
else: # During test (inference)
return x
Implementing this process in CUDA looks like this:
As mentioned above, cuRAND is a CUDA standard library for random number generation. We generate a random number random using curand_init and curand_uniform provided by cuRAND (reference). curand_init initializes the state of the random number generator, and curand_uniform generates the random number. By changing the offset value of curand_init, we switch which random number sequence is used from the generated ones. If the generated random number random is greater than the dropout_ratio value, the mask array is set to 1, otherwise it is set to 0. Then, if the mask is 0, we perform the process of setting x to 0.
backward
The backward process is as follows. For the backpropagated gradient values, values where the mask was 1 during the forward pass remain unchanged, and values where the mask was 0 are set to 0.
python
The implementation of the Dropout class in Python is as follows. Through pybind, executing dropout_forward calls the DropoutForward function (which wraps DropoutForwardKernel), and executing dropout_backward calls the DropoutBackward function (which wraps DropoutBackwardKernel).
4. Layer Norm
For Layer Norm, this article uses Dynamic Tanh (DyT).
DyT is a technique introduced in 2025 by Kaiming He, Yann LeCun, and others, which replaces the LayerNorm layer with a scaled tanh function. In Python, DyT can be implemented with very little code (9 lines) and achieves performance equal to or better than LayerNorm and RMSNorm. Additionally, in an H100 environment, DyT has been confirmed to operate faster than RMSNorm.
Since it is easy to implement, we use DyT as the LayerNorm in this article.
Forward
According to arXiv:2503.10622, the Python implementation for the forward pass is as follows:
class DyT(nn.Module):
def __init__(self, num_features, alpha_init_value=0.5):
super().__init__()
self.alpha = nn.Parameter(torch.ones(1) * alpha_init_value)
self.weight = nn.Parameter(torch.ones(num_features))
self.bias = nn.Parameter(torch.zeros(num_features))
def forward(self, x):
x = torch.tanh(self.alpha * x)
return x * self.weight + self.bias
The CUDA code is as follows. In CUDA, trigonometric function processing such as tanf() and cosf() can be used without additional header files.
backward
Using a computation graph, we verify the flow of the backward pass and the gradients for x, α, γ, and β. The blue lines represent the flow of the backward process.

Implementing this as a CUDA kernel yields the following:
python
The implementation of the DyT class in Python is as follows. Through pybind, executing dyt_forward calls the DytForward function (which wraps DytForwardKernel), and executing dyt_backward calls the DytBackward function (which wraps DytBackwardKernel).
5. embedding
Embedding performs the operation of converting a single token ID into a vector representation.
forward
First, let's explain the forward process. Embedding extracts the vector corresponding to the token ID from the weight tensor and returns it. The Python implementation for this is as follows:
import torch
# weight: embedding table (vocab_size=5, hidden_size=3)
weight = torch.tensor([
[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
[13,14,15]
])
# indices: indices to select
indices = torch.tensor([1, 3, 0])
# Realization of embedding process
selected_rows = weight.index_select(0, indices)
print(selected_rows)
"""
# Output result
tensor([[ 4, 5, 6],
[10, 11, 12],
[ 1, 2, 3]])
"""
In the GPT2 model, indices correspond to the input token ID sequence. For each row number in the weight, the embedding process returns the row vector corresponding to the index selected by the input token.
Implementing this in CUDA results in the following:
backward
Next, we implement the backward process.
In the padding_idx, the index is excluded from training. To exclude learnable parameters from training, we set their gradient values to 0. For example, in methods like SGD, weight updates during training are performed using formulas such as grad is 0,
The CUDA kernel for the backward process is as follows:
We simply add the values of each row of the incoming gradient (grad) to the row index of the weight gradient (out) indicated by each element of the indices used during the forward pass.
Writing to the same VRAM area at the same time may cause conflicts and result in incorrect updates. To prevent this, we assign separate threads (i) not by rows, but by columns of grad, calculating each part individually.
python
The implementation of the Embedding class in Python is as follows. Through pybind, executing embedding_forward calls the EmbeddingForward function (which wraps EmbeddingForwardKernel), and executing embedding_backward calls the EmbeddingBackward function (which wraps EmbeddingBackwardKernel).
7. Scaled Dot Product Attention
Scaled Dot Product Attention, also known as Self-Attention, calculates scaled dot-product attention for the query, key, and value tensors.
forward
The implementation of Scaled Dot Product Attention in Python is as follows:
def scaled_dot_product_attention(query, key, value, mask=None):
dim_k = key.size(-1)
scores = (query@key.transpose(-2,-1))
scores /= (dim_k**0.5)
if mask is not None:
scores = scores.masked_fill(mask==0,float("-inf"))
weights = F.softmax(scores, dim=-1)
out = weights @ value
return out,weights
Implementing this process using a CUDA kernel results in the following:
The DivideSqrtKsize function divides each element of w by sqrt(k.size(-1)). The CUDA kernel used within this function is as follows:
The MaskedFill function compares each element of w with each element of mask_cast, and replaces elements where mask_cast is 0 with -inf. The CUDA kernel used within this function is as follows:
The SoftmaxForward function performs the Softmax calculation represented by the following formula:
The implementation of the CUDA kernel is as follows:
backward
Using a computation graph, we confirm the flow of the backward process and the gradient values for @ represents the dot product, and * represents the Hadamard product.

Based on this diagram, we implement the Backward function. The implementation is as follows:
The SoftmaxBackward function performs the processing corresponding to the Backward of the Softmax function.
First, we provide the implementation in Python. The sft contains the calculation result of the Softmax function (the result of SoftmaxForwardKernel).
def softmax_backward_4d(sft,grad_out):
identity = torch.eye(sft.size(-1)).view(-1,sft.size(-1)**2)
identity = torch.cat([identity for i in range(int(sft.numel()/sft.size(-1)))], dim=0)
identity = identity.view(sft.size(0),sft.size(1),sft.size(2),-1)
d_sft = sft.unsqueeze(-2)
d_sft = d_sft.expand(-1,-1,-1,sft.size(3),-1)
d_sft = d_sft.reshape(sft.size(0),sft.size(1),sft.size(2),-1)
sft = sft.unsqueeze(-2)
d_sft = \
d_sft * identity - (sft.transpose(-1,-2) @ sft).view(sft.size(0),sft.size(1),sft.size(2),-1)
grad_out = grad_out.unsqueeze(-2)
grad_out = \
grad_out @ d_sft.view(d_sft.size(0),d_sft.size(1),d_sft.size(2),grad_out.size(-1),-1)
return grad_out.squeeze(-2)
The implementation in the CUDA kernel is as follows:
python
The Python implementation of the ScaledDotProductAttention class is as follows. Through pybind, executing sdpa_forward calls the SdpaForwardKernel (wrapped by the SdpaForward function), and executing sdpa_backward calls the SdpaBackward function.
Building the GPT2 Model
In this chapter, we use the base kernels created in the previous chapter to implement the layers that make up GPT2. Then, we combine them into a single GPT2 model.
1. Feed Forward Layer
The structure of the Feed Forward layer is as shown in the diagram below.

The Feed Forward layer can be described as follows, using the Python classes created in the previous chapter:
2. Masked Multi-Head Attention Layer
The structure of the Masked Multi-Head Attention layer is as shown in the diagram below.

The implementation in Python is as follows:
3. Decoder Block Layer
The structure of the Decoder Block layer is as shown in the diagram below.

The Decoder Block layer can be described as follows, using the created Python classes:
Here, we use custom functions called spy, fork, and add.
The spy function is as follows. This is a debugging function used to acquire (spy) the gradient values propagated during the backward propagation process.
The fork function is as follows. It is a function that creates a "branch node" in the computation graph. During the forward pass, it duplicates the input tensor x into two. During the backward pass, it adds the two propagated gradients together into one.
The add function is as follows. It is a function for adding two tensors. The AddKernel function described earlier is executed from the add_forward function.
4. LM Head Layer
The LM Head is simply a Linear layer. The Python implementation is as follows:
5. Embedding Layer
The structure of the Embedding layer is as shown in the diagram below.

The Python implementation is as follows:
Here, we use a custom function called batch_expand. This is a function for expanding the size of the batch dimension (0) of the tensor x.
6. GPT2 Model
We combine the Embedding layer, Decoder Block layer, LM Head layer, Layer Norm, and Dropout implemented so far to build the GPT2 model. The structure of the GPT2 model is as shown in the diagram below.

The Python implementation is as follows:
Creating CUDA Kernels Required for Training
1. CrossEntropyLoss
CrossEntropyLoss is one of the functions used to calculate the loss between predicted and target values. During training, we update the values of the learnable parameters in the model to reduce this loss.
In the PyTorch implementation, the formula for CrossEntropyLoss is as follows, representing the case when the PyTorch default setting of reduction==mean is used:
Here, the index n represents the number of data points, and C represents the number of dimensions.
forward
Since this is a bit difficult to understand, let's look at a Python implementation (Program A).
import torch.nn.functional as F
import torch
import torch.nn as nn
batch_size = 4
num_classes = 3
torch.manual_seed(42)
predictions = torch.randn(batch_size, num_classes)
print("Predictions:\n", predictions)
# Predictions:
# tensor([[ 0.3367, 0.1288, 0.2345],
# [ 0.2303, -1.1229, -0.1863],
# [ 2.2082, -0.6380, 0.4617],
# [ 0.2674, 0.5349, 0.8094]])
targets = torch.randint(0, num_classes, (batch_size,))
print("Targets:\n", targets)
# Targets:
# tensor([2, 1, 2, 0])
"""Confirmation of official implementation"""
loss = F.cross_entropy(predictions, targets)
print("Cross-entropy loss:", loss.item())
# Cross-entropy loss: 1.6134321689605713
"""Scratch implementation of cross entropy"""
log_probs = torch.log(torch.softmax(predictions, dim=1))
print("Log probs:\n", log_probs)
# Log probs:
# tensor([[-0.9988, -1.2067, -1.1011],
# [-0.6511, -2.0043, -1.0678],
# [-0.2090, -3.0552, -1.9555],
# [-1.3928, -1.1253, -0.8508]])
batch_size = predictions.size(0)
probabilities = torch.zeros(batch_size, device=predictions.device)
for i in range(batch_size):
# Extract values of log_probs at [i-th row, "targets[i]"-th column]
probabilities[i] = log_probs[i, targets[i]]
print("Probabilities:", probabilities)
# Probabilities: tensor([-1.1011, -2.0043, -1.9555, -1.3928])
loss = -probabilities.mean()
print("Cross-entropy loss:", loss.item())
# Cross-entropy loss: 1.6134321689605713
Note that CrossEntropyLoss has an argument called ignore_index. This setting specifies an index value for target data that should be excluded from the loss calculation. This is used, for example, when there is data that you intentionally want to exclude from training. Below is the Python implementation when ignore_idx=-1 is set.
import torch.nn.functional as F
import torch
import torch.nn as nn
batch_size = 4
num_classes = 3
ignore_index = -1
torch.manual_seed(42)
predictions = torch.randn(batch_size, num_classes)
print("Predictions:\n", predictions)
# Predictions:
# tensor([[ 0.3367, 0.1288, 0.2345],
# [ 0.2303, -1.1229, -0.1863],
# [ 2.2082, -0.6380, 0.4617],
# [ 0.2674, 0.5349, 0.8094]])
targets = torch.randint(0, num_classes, (batch_size,))
targets[3] = -1
print("Targets:\n", targets)
# Targets:
# tensor([2, 1, 2, -1])
"""Output confirmation of official implementation"""
loss = F.cross_entropy(predictions, targets, ignore_index=ignore_index)
print("Cross-entropy loss:", loss.item())
"""Scratch implementation of cross entropy"""
log_probs = torch.log(torch.softmax(predictions, dim=1))
print("Log probs:\n", log_probs)
# Log probs:
# tensor([[-0.9988, -1.2067, -1.1011],
# [-0.6511, -2.0043, -1.0678],
# [-0.2090, -3.0552, -1.9555],
# [-1.3928, -1.1253, -0.8508]])
batch_size = predictions.size(0)
probabilities = torch.zeros(batch_size, device=predictions.device)
ignore_cnt = 0
for i in range(batch_size):
# Extract values of log_probs at [i-th row, "targets[i]"-th column]
if targets[i] == ignore_index:
ignore_cnt+=1
continue
probabilities[i] = log_probs[i, targets[i]]
print("Probabilities:", probabilities)
# Probabilities: tensor([-1.1011, -2.0043, -1.9555, -1.3928])
loss = -1*probabilities.sum()/(probabilities.size(-1)-ignore_cnt)
print("Cross-entropy loss:", loss.item())
Based on this information, we implement CrossEntropyLoss as a CUDA kernel.
backward
Implementing the backward pass in Python results in the following:
import torch.nn.functional as F
import torch
import torch.nn as nn
batch_size = 5
num_classes = 3
torch.manual_seed(42)
x = torch.randn(batch_size,num_classes).requires_grad_(True)
torch.Tensor.retain_grad(x)
print("x:\n",x)
# x:
# tensor([[ 0.3367, 0.1288, 0.2345],
# [ 0.2303, -1.1229, -0.1863],
# [ 2.2082, -0.6380, 0.4617],
# [ 0.2674, 0.5349, 0.8094]])
targets = torch.randint(0, num_classes, (batch_size,))
print("Targets:\n", targets)
# Targets:
# tensor([2, 1, 2, 0])
loss = F.cross_entropy(x, targets)
print("Cross-entropy loss:", loss.item())
loss.backward()
print("x.grad",x.grad)
""" scratch """
# softmax
ex = torch.exp(x)
s = torch.sum(ex,dim=-1)
print("ex:\n",ex)
print("s:\n",s)
s = s.view(1,-1).T.expand(-1,num_classes)
print("s:\n",s)
y = ex/s
print("y:\n",y)
for i in range(batch_size):
y[i, targets[i]] -= 1
z = y/batch_size
print("z",z)
print(torch.allclose(x.grad,z,atol=1e-5))
Implementing this with a CUDA kernel results in the following. We use x that has already been exp(x)-ed in CrossEntropyLossForward.
python
The Python implementation of the CrossEntropyLoss function is as follows. Through pybind, executing cross_entropy_loss_forward calls the CrossEntropyLossForwardKernel (wrapped by the CrossEntropyLossForward function), and executing CrossEntropyLossBackwardKernel (wrapped by the CrossEntropyLossBackward function) is executed.
You can perform CrossEntropyLoss calculation by using cross_entropy() at the bottom.
2. AdamW
AdamW is one of the optimization functions used to update the learnable parameters within a neural network model. The calculation formula for AdamW is as follows (Reference). The learnable parameters are represented by
【AdamW】
input :
initialize :
for
return
Implementing this as a CUDA kernel results in the following. param receives the learnable parameter dparam receives the gradient value m is v is param is updated to
From Python, it is called and used as follows. Executing adamw_forward runs the AdamWKernel (via its wrapper function AdamW). In the part param.data, self.state[i]["m"], self.state[i]["v"] = adamw_forward, we receive adamw_forward, and by saving them in self.state[i]["m"] and self.state[i]["v"], we use them as
Testing the Outputs of Custom Functions
We determine whether the outputs of the custom CUDA kernels and the Python classes that execute them (forward() and backward()) are correct by checking whether they match the execution results of the corresponding functions in PyTorch.
For example, the custom Linear class is compared and verified against PyTorch's nn.Linear class. The test program is as follows. We use Python's unittest library to create the test code.
Besides this, we also perform comparisons with PyTorch for several other custom Python classes that will be explained in the future. They are all included in the tests/python folder of the public repository, and can be executed all at once by running the following command:
# The code is unittest, but it can be executed with the pytest command and the output is displayed cleanly
uv run pytest ./tests/python -v
# By passing log-level to pytest, you can control the output of the Python logger module
uv run pytest -log-cli-level=INFO ./tests/python -v
An example of the output when running the tests is as follows. You can see that all 39 test functions have passed.
========================================== test session starts ==========================================
platform linux -- Python 3.10.12, pytest-8.3.5, pluggy-1.5.0 -- /workspace/diy-torch-kernel/.venv/bin/python
cachedir: .pytest_cache
rootdir: /workspace/diy-torch-kernel
configfile: pyproject.toml
collected 39 items
tests/python/test_activation.py::TestGelu::test_backward PASSED [ 2%]
tests/python/test_activation.py::TestGelu::test_forward PASSED [ 5%]
tests/python/test_embedding.py::TestEmbedding::test_backward PASSED [ 7%]
tests/python/test_embedding.py::TestEmbedding::test_backward2 PASSED [ 10%]
/* omit */
tests/python/test_optim.py::TestAdamW::test_forward PASSED [ 94%]
tests/python/test_optim.py::TestSGD::test_forward PASSED [ 97%]
tests/python/test_optim.py::TestSGD::test_forward_momentum PASSED [100%]
===================================== 39 passed in 83.22s (0:01:23) =====================================
Training
Using the CUDA kernels created so far, we perform training of the GPT2 model.
Dataset
We use the following 0.9B dataset:
Download it using this script:
In the training script described later, the dataset is used by splitting it into training data : test data = 9:1.
Model Size
To reduce training time, we set the model size to 36M.
In terms of configuration, it is almost the same as rinna/japanese-gpt2-xsmall.
Tokenizer
The tokenizer is created using Sentencepiece.
Tokenizer training is performed with the following script. The training dataset used is the aforementioned ce-lery/wiki dataset.
Training Script
The training script is as follows.
It is created based on LLMs-from-scratch.
Training Results
The transition of loss during training is as shown in the diagram below.

The final train/eval loss values and training time are as follows:
Ep 1 (Step 305000): Train loss 4.330, Val loss 4.325
[66:40:45<00:00, 1.27it/s]
Note that the transition of loss when training a similar model in PyTorch was almost the same.
Conclusion
In this article, I built the CUDA kernels that run inside the GPT2 model from scratch. I also called the custom CUDA kernels from Python and performed model training. Although training time and memory consumption were inferior to PyTorch, results were obtained where the loss transitioned similarly.
This time, I was only able to show the transition of loss as a training result. The transition of loss when training in PyTorch and the inference results of the custom model are scheduled to be added to this page in the future.
In addition, I will implement improvements to the CUDA kernels and peripheral programs to improve training time and reduce memory consumption.
Discussion