Write an efficient cuda kernel for self attention.
- User
Write an efficient cuda kernel for self attention.
- Assistant
Write an efficient cuda kernel for self attention.
Certainly! Below is an example of an efficient CUDA kernel for computing self-attention. The kernel is designed to compute the self-attention mechanism used in transformer models, as described in the "Attention is All You Need" paper.
The self-attention operation can be summarized by the following steps:
The CUDA kernel leverages shared memory and parallel reduction techniques to ensure efficiency.
// Includes
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
#include <cstdio>
#include <cmath>
// Constants
#define TILE_DIM 32
#define SCALAR_TYPE float
#define EPSILON 1e-6
// CUDA kernel for self-attention
__global__ void self_attention_kernel(
const SCALAR_TYPE* __restrict__ queries, // [batch_size, seq_len, head_dim]
const SCALAR_TYPE* __restrict__ keys, // [batch_size, seq_len, head_dim]
const SCALAR_TYPE* __restrict__ values, // [batch_size, seq_len, head_dim]
SCALAR_TYPE* __restrict__ output, // [batch_size, seq_len, head_dim]
int batch_size,
int seq_len,
int head_dim)
{
extern __shared__ SCALAR_TYPE shared_mem[];
SCALAR_TYPE* q_smem = shared_mem; // [head_dim]
SCALAR_TYPE* k_smem = &shared_mem[head_dim]; // [head_dim]
SCALAR_TYPE* v_smem = &shared_mem[2 * head_dim]; // [head_dim]
SCALAR_TYPE* attn_scores_smem = &shared_mem[3 * head_dim]; // [seq_len]
SCALAR_TYPE* attn_softmax_smem = &shared_mem[3 * head_dim + seq_len];// [seq_len]
int batch_idx = blockIdx.z;
int seq_q_idx = blockIdx.y * blockDim.y + threadIdx.y;
int seq_kv_idx = blockIdx.x * blockDim.x + threadIdx.x;
int head_dim_idx = threadIdx.x;
if (seq_q_idx >= seq_len || seq_kv_idx >= seq_len || head_dim_idx >= head_dim)
return;
// Load query vector into shared memory
int q_idx = batch_idx * seq_len * head_dim + seq_q_idx * head_dim + head_dim_idx;
q_smem[head_dim_idx] = queries[q_idx];
__syncthreads();
// Compute attention scores
SCALAR_TYPE attn_score = 0.0f;
for (int i = 0; i < head_dim; i += TILE_DIM)
{
int k_idx = batch_idx * seq_len * head_dim + seq_kv_idx * head_dim + (i + threadIdx.x);
if ((i + threadIdx.x) < head_dim)
k_smem[threadIdx.x] = keys[k_idx];
else
k_smem[threadIdx.x] = 0.0f;
__syncthreads();
// Dot product between query and key
if ((i + threadIdx.x) < head_dim)
attn_score += q_smem[i + threadIdx.x] * k_smem[threadIdx.x];
__syncthreads();
}
// Scale attention scores
attn_score /= sqrtf((SCALAR_TYPE)head_dim + EPSILON);
// Store raw attention scores
if (head_dim_idx == 0)
attn_scores_smem[seq_kv_idx] = attn_score;
__syncthreads();
// Compute softmax
// Step 1: Find max for numerical stability
SCALAR_TYPE max_score = -INFINITY;
if (head_dim_idx == 0)
{
for (int i = 0; i < seq_len; ++i)
{
if (attn_scores_smem[i] > max_score)
max_score = attn_scores_smem[i];
}
}
__syncthreads();
max_score = __shfl_sync(0xffffffff, max_score, 0);
// Step 2: Exponentiate and sum
SCALAR_TYPE sum_exp = 0.0f;
if (head_dim_idx == 0)
{
for (int i = 0; i < seq_len; ++i)
{
SCALAR_TYPE exp_score = expf(attn_scores_smem[i] - max_score);
attn_softmax_smem[i] = exp_score;
sum_exp += exp_score;
}
}
__syncthreads();
sum_exp = __shfl_sync(0xffffffff, sum_exp, 0);
// Step 3: Normalize to get softmax probabilities
if (head_dim_idx == 0)
{
for (int i = 0; i < seq_len; ++i)
{
attn_softmax_smem[i] /= (sum_exp + EPSILON);
}
}
__syncthreads();
// Compute weighted sum of values
SCALAR_TYPE output_value = 0.0f;
for (int i = 0; i < seq_len; ++i)
{
// Load value vector
int v_idx = batch_idx * seq_len * head_dim + i * head_dim + head_dim_idx;
if (head_dim_idx < head_dim)
v_smem[head_dim_idx] = values[v_idx];
else
v_smem[head_dim_idx] = 0.0f;
__syncthreads();
// Multiply by attention weight
output_value += attn_softmax_smem[i] * v_smem[head_dim_idx];
__syncthreads();
}
// Write the output
int out_idx = batch_idx * seq_len * head_dim + seq_q_idx * head_dim + head_dim_idx;
output[out_idx] = output_value;
}
// Host code to launch the kernel
void launch_self_attention(
const SCALAR_TYPE* queries, // Device pointer
const SCALAR_TYPE* keys, // Device pointer
const SCALAR_TYPE* values, // Device pointer
SCALAR_TYPE* output, // Device pointer
int batch_size,
int seq_len,
int head_dim)
{
dim3 blockDim(TILE_DIM, 1, 1);
dim3 gridDim((seq_len + TILE_DIM - 1) / TILE_DIM,
(seq_len + TILE_DIM - 1) / TILE_DIM,
batch_size);
size_t shared_mem_size = (3 * head_dim + 2 * seq_len) * sizeof(SCALAR_TYPE);
self_attention_kernel<<<gridDim, blockDim, shared_mem_size>>>(
queries, keys, values, output, batch_size, seq_len, head_dim);
cudaDeviceSynchronize();
}
// Example usage
int main()
{
// Set parameters
int batch_size = 2;
int seq_len = 64;
int head_dim = 64;
size_t total_elements = batch_size * seq_len * head_dim;
size_t total_size = total_elements * sizeof(SCALAR_TYPE);
// Allocate host memory
SCALAR_TYPE* h_queries = (SCALAR_TYPE*)malloc(total_size);
SCALAR_TYPE* h_keys = (SCALAR_TYPE*)malloc(total_size);
SCALAR_TYPE* h_values = (SCALAR_TYPE*)malloc(total_size);
SCALAR_TYPE* h_output = (SCALAR_TYPE*)malloc(total_size);
// Initialize inputs
for (size_t i = 0; i < total_elements; ++i)
{
h_queries[i] = static_cast<SCALAR_TYPE>(rand()) / RAND_MAX;
h_keys[i] = static_cast<SCALAR_TYPE>(rand()) / RAND_MAX;
h_values[i] = static_cast<SCALAR_TYPE>(rand()) / RAND_MAX;
}
// Allocate device memory
SCALAR_TYPE* d_queries;
SCALAR_TYPE* d_keys;
SCALAR_TYPE* d_values;
SCALAR_TYPE* d_output;
cudaMalloc(&d_queries, total_size);
cudaMalloc(&d_keys, total_size);
cudaMalloc(&d_values, total_size);
cudaMalloc(&d_output, total_size);
// Copy data to device
cudaMemcpy(d_queries, h_queries, total_size, cudaMemcpyHostToDevice);
cudaMemcpy(d_keys, h_keys, total_size, cudaMemcpyHostToDevice);
cudaMemcpy(d_values, h_values, total_size, cudaMemcpyHostToDevice);
// Launch kernel
launch_self_attention(d_queries, d_keys, d_values, d_output, batch_size, seq_len, head_dim);
// Copy result back to host
cudaMemcpy(h_output, d_output, total_size, cudaMemcpyDeviceToHost);
// Clean up
cudaFree(d_queries);
cudaFree(d_keys);
cudaFree(d_values);
cudaFree(d_output);
free(h_queries);
free(h_keys);
free(h_values);
free(h_output);
return 0;
}
float in this case). It can be changed to double if higher precision is required.The kernel uses shared memory to:
launch_self_attentionlaunch_self_attention function with the allocated device pointers and tensor dimensions.TILE_DIM may yield better performance. Profiling with different values is recommended.double precision or mixed-precision techniques.seq_len and head_dim are appropriate for your specific use case. Padding may be necessary for sequences of different lengths.To compile the code, use the NVIDIA CUDA compiler nvcc:
nvcc -o self_attention self_attention.cu
After compilation, run the executable:
./self_attention
This implementation provides a foundation for computing self-attention on the GPU using CUDA. Further optimizations can be made based on specific hardware characteristics and application requirements.