SwiGLU(Swish-Gated Linear Unit)是一种结合了Swish激活函数和GLU(Gated Linear Unit)门控机制的激活函数,广泛应用于现代大型语言模型中
Swish 激活函数是一种平滑的、非单调的激活函数,由 Google Brain 团队在 2017 年提出。它结合了 ReLU 的非线性特性与 Sigmoid 函数的平滑特性,旨在解决 ReLU 在某些情况下的局限性,例如梯度消失和“死亡神经元”问题。
Swish 的数学表达式为:
Swish ( x ) = x ⋅ σ ( β x ) \text{Swish}(x) = x \cdot \sigma(\beta x) Swish(x)=x⋅σ(βx)
其中:
当 β = 1 \beta = 1 β=1 时,Swish 函数可以简化为:
$$\text{Swish}(x) = x \cdot \sigma(x) $$
平滑性:
非单调性:
自门控特性:
可学习的参数:
训练稳定性:
性能提升:
适用于深度网络:
计算复杂度:
可能的过拟合:
SiLU(Sigmoid Linear Unit):
Swish-1、Swish-β:
以下是一个基于 PyTorch 的 Swish 激活函数的实现:
import torch
import torch.nn as nn
import torch.nn.functional as F
class Swish(nn.Module):
def __init__(self, beta=1.0):
super(Swish, self).__init__()
self.beta = beta
def forward(self, x):
return x * torch.sigmoid(self.beta * x)
# 使用 SiLU(Swish-1)作为激活函数
class SiLU(nn.Module):
def forward(self, x):
return x * torch.sigmoid(x)
Swish 的平滑性和非单调性使其在训练深度神经网络时表现出色,尤其是在处理复杂数据集和长距离依赖关系时。它在许多现代深度学习模型中被广泛使用,例如 Transformer、BERT 和一些大型语言模型。
通过上述介绍,可以更好地理解 Swish 激活函数的特性及其在深度学习中的重要性。
即门控线性单元,是一种引入了门控机制的激活函数,广泛应用于深度学习模型中,尤其是在处理序列数据和自然语言处理任务时表现出色。
GLU 的核心思想是将输入数据通过两个线性变换,其中一个变换的结果通过 Sigmoid 函数进行非线性处理,另一个保持线性,然后两者逐元素相乘。其数学表达式为:
GLU ( x ) = σ ( W 1 x + b 1 ) ⊙ ( W 2 x + b 2 ) \text{GLU}(x) = \sigma(W_1 x + b_1) \odot (W_2 x + b_2) GLU(x)=σ(W1x+b1)⊙(W2x+b2)
其中:
线性变换:
门控机制:
输出:
选择性信息传递:
非线性增强:
高效计算:
并行处理能力:
GLU 的变体通过替换 Sigmoid 激活函数来进一步优化性能,常见的变体包括:
以下是一个基于 PyTorch 的 GLU 实现示例:
import torch
import torch.nn as nn
import torch.nn.functional as F
class GLU(nn.Module):
def __init__(self, input_dim, output_dim):
super(GLU, self).__init__()
self.linear1 = nn.Linear(input_dim, output_dim)
self.linear2 = nn.Linear(input_dim, output_dim)
def forward(self, x):
gate = torch.sigmoid(self.linear1(x)) # 门控信号
linear = self.linear2(x) # 线性信号
return gate * linear # 逐元素相乘
一种结合了 Swish 激活函数 和 GLU(Gated Linear Unit) 特点的激活函数,广泛应用于现代深度学习模型中,尤其是在大型语言模型(如 LLaMA 和 PaLM)中表现出色。
SwiGLU 的数学表达式为:
SwiGLU ( x ) = Swish ( Linear 1 ( x ) ) ⊗ Linear 2 ( x ) \text{SwiGLU}(x) = \text{Swish}(\text{Linear}_1(x)) \otimes \text{Linear}_2(x) SwiGLU(x)=Swish(Linear1(x))⊗Linear2(x)
其中:
线性变换:
门控机制:
输出:
平滑非线性:
门控特性:
高效计算:
性能提升:
SwiGLU 广泛应用于以下领域:
以下是一个基于 PyTorch 的 SwiGLU 实现示例:
import torch
import torch.nn as nn
import torch.nn.functional as F
class SwiGLU(nn.Module):
def __init__(self, input_dim, hidden_dim):
super(SwiGLU, self).__init__()
self.linear1 = nn.Linear(input_dim, hidden_dim)
self.linear2 = nn.Linear(input_dim, hidden_dim)
self.swish = nn.SiLU() # 使用内置的 Swish 激活函数
def forward(self, x):
return self.linear1(x) * self.swish(self.linear2(x))
# 示例输入
x = torch.randn(4, 128) # Batch size 4, input dimension 128
model = SwiGLU(input_dim=128, hidden_dim=256)
output = model(x)
print(output.shape) # 输出维度为 (4, 256)
SwiGLU 通过结合 Swish 的平滑非线性特性和 GLU 的门控机制,提供了一种高效的激活函数,适用于需要复杂非线性转换的任务,如自然语言处理和计算机视觉。