CUDA Networks
Functions
matrix_softmax.cu File Reference

Implementation of the softmax function for matrices. More...

#include "matrix.h"
#include <cuda_runtime.h>
#include <cfloat>
Include dependency graph for matrix_softmax.cu:

Go to the source code of this file.

Functions

__global__ void softmaxKernel (const double *input, double *output, int rows, int cols)
 CUDA kernel for applying the softmax function column-wise. More...
 

Detailed Description

Implementation of the softmax function for matrices.

Definition in file matrix_softmax.cu.

Function Documentation

◆ softmaxKernel()

__global__ void softmaxKernel ( const double *  input,
double *  output,
int  rows,
int  cols 
)

CUDA kernel for applying the softmax function column-wise.

Parameters
inputPointer to the input matrix data.
outputPointer to the output matrix data.
rowsNumber of rows in the matrix.
colsNumber of columns in the matrix.

Definition at line 17 of file matrix_softmax.cu.

17  {
18  // Calculate the column index
19  int col = blockIdx.x * blockDim.x + threadIdx.x;
20 
21  // Check if the column is within bounds
22  if (col < cols) {
23  // Initialize maximum value to negative infinity
24  double max_val = -DBL_MAX;
25 
26  // Find the maximum value in the column
27  for (int row = 0; row < rows; ++row) {
28  max_val = fmax(max_val, input[row * cols + col]);
29  }
30 
31  // Initialize sum of exponentials
32  double sum_exp = 0.0;
33 
34  // Calculate the sum of exponentials
35  for (int row = 0; row < rows; ++row) {
36  sum_exp += exp(input[row * cols + col] - max_val);
37  }
38 
39  // Add a small epsilon to avoid division by zero
40  sum_exp += 1e-15;
41 
42  // Apply softmax function
43  for (int row = 0; row < rows; ++row) {
44  output[row * cols + col] = exp(input[row * cols + col] - max_val) / sum_exp;
45  }
46  }
47 }