68. Sigmoid Activation easy

Write a GPU program that applies the sigmoid activation function element-wise to a vector of 32-bit floating point numbers. For each element x in the input vector X, compute sigmoid(x) = 1 / (1 + exp(-x)) and store the result in the output vector Y. The sigmoid function maps any real number to the range (0, 1).

Implementation Requirements

  • External libraries are not permitted
  • The solve function signature must remain unchanged
  • The final result must be stored in vector Y

Example 1:

Input:  X = [0.0, 1.0, -1.0, 2.0]
Output: Y = [0.5, 0.7311, 0.2689, 0.8808]

Example 2:

Input:  X = [0.5, -0.5, 3.0, -3.0]
Output: Y = [0.6225, 0.3775, 0.9526, 0.0474]

Constraints

  • 1 ≤ N ≤ 100,000,000
  • Input values are finite 32-bit floating point numbers
  • Performance is measured with N = 50,000,000

Starter code (CUDA)

#include <cuda_runtime.h>
#include <math.h>

__global__ void sigmoid_kernel(const float* X, float* Y, int N) {}

// X, Y are device pointers (i.e. pointers to memory on the GPU)
extern "C" void solve(const float* X, float* Y, int N) {
    int threadsPerBlock = 256;
    int blocksPerGrid = (N + threadsPerBlock - 1) / threadsPerBlock;

    sigmoid_kernel<<<blocksPerGrid, threadsPerBlock>>>(X, Y, N);
    cudaDeviceSynchronize();
}

Solve it on your GPU

From LeetGPU, CC BY-NC-ND 4.0.