Can you provide code in C for the GELU activation function?
- User
Can you provide code in C for the GELU activation function?
- Assistant
Sure! The Gausian Error Linear Unit (GELU) activation function is given by the formula:
gelu(x) = x * Φ(x)where
Φ(x)is the cumulative distribution function of the standard Gaussian distribution. A commonly used approximation of the GELU function is given by:gelu(x) ≈ 0.5 * x * (1 + tanh(sqrt(2 / π) * (x + 0.044715 * pow(x, 3))))Here's a simple implementation of the GELU activation function using this approximation in C:
#include <stdio.h> #include <math.h> double gelu(double x) { double cdf = 0.5 * (1.0 + tanh(sqrt(2.0 / M_PI) * (x + 0.044715 * pow(x, 3)))); return x * cdf; } int main() { // Example usage double input = 0.5; // Replace this with your input double output = gelu(input); printf("GELU(%f) = %f\n", input, output); return 0; }In the code,
geluis a function that calculates the GELU activation for a given inputx. The resulting GELU activated value is then printed out in themainfunction.Make sure to compile this C program with
-lmto link the math library, because it uses math functions like , , and . - User
Can you also provide code in C to calculate the derivate of the GELU activation function?
- Assistant
Sure! The derivative of the GELU activation function can be computed by taking the derivative of its approximation formula. Here's the derivative of the approximate GELU:
d/dx gelu(x) ≈ 0.5 * tanh(sqrt(2 / π) * (x + 0.044715 * x^3)) + (0.5 * x * (1 - tanh^2(sqrt(2 / π) * (x + 0.044715 * x^3))) * ((sqrt(2 / π) * (1 + 3 * 0.044715 * x^2))) + 0.5I'll provide C code for computing the derivative of the GELU activation function using this formula:
#include <stdio.h> #include <math.h> double gelu_derivative(double x) { double sqrt_2_over_pi = sqrt(2.0 / M_PI); double tanh_arg = sqrt_2_over_pi * (x + 0.044715 * pow(x, 3)); double tanh_res = tanh(tanh_arg); double sech2 = 1.0 - tanh_res * tanh_res; // sech^2 = 1 - tanh^2 double first_term = 0.5 * tanh_res; double second_term = 0.5 * x * sech2 * (sqrt_2_over_pi * (1.0 + 3.0 * 0.044715 * pow(x, 2))); return first_term + second_term + 0.5; } int main() { // Example usage double input = 0.5; // Replace this with your input double output_derivative = gelu_derivative(input); printf("GELU'(%f) = %f\n", input, output_derivative); return 0; }