2023-02-28 10:07:24 +00:00
|
|
|
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
2021-12-21 04:19:52 +00:00
|
|
|
import torch
|
|
|
|
|
|
|
|
###### BIAS GELU FUSION/ NO AUTOGRAD ################
|
|
|
|
# 1/sqrt(2*pi)-> 0.3989423
|
|
|
|
# 1/sqrt(2) -> 0.70710678
|
|
|
|
# sqrt(2/pi) -> 0.79788456
|
|
|
|
# this function is tanh approximation of gelu
|
|
|
|
# actual gelu is:
|
|
|
|
# x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
|
|
|
|
|
2022-05-13 10:03:11 +00:00
|
|
|
|
2021-12-21 04:19:52 +00:00
|
|
|
@torch.jit.script
|
|
|
|
def bias_gelu(bias, y):
|
|
|
|
x = bias + y
|
2022-05-13 10:03:11 +00:00
|
|
|
return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))
|
|
|
|
|
2021-12-21 04:19:52 +00:00
|
|
|
|
|
|
|
# gradient of tanh approximation of gelu
|
|
|
|
# gradient of actual gelu is:
|
|
|
|
# 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
|
|
|
|
@torch.jit.script
|
|
|
|
def bias_gelu_back(g, bias, y):
|
|
|
|
x = bias + y
|
|
|
|
tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
|
|
|
|
# sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
|
|
|
|
ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh_out)
|
2022-05-13 10:03:11 +00:00
|
|
|
return ff * g
|
|
|
|
|
2021-12-21 04:19:52 +00:00
|
|
|
|
|
|
|
class GeLUFunction(torch.autograd.Function):
|
2022-05-13 10:03:11 +00:00
|
|
|
|
2021-12-21 04:19:52 +00:00
|
|
|
@staticmethod
|
|
|
|
# bias is an optional argument
|
|
|
|
def forward(ctx, input, bias):
|
|
|
|
ctx.save_for_backward(input, bias)
|
|
|
|
return bias_gelu(bias, input)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def backward(ctx, grad_output):
|
|
|
|
input, bias = ctx.saved_tensors
|
|
|
|
tmp = bias_gelu_back(grad_output, bias, input)
|
|
|
|
return tmp, tmp
|
|
|
|
|
2022-05-13 10:03:11 +00:00
|
|
|
|
|
|
|
bias_gelu_impl = GeLUFunction.apply
|