Certainly! Below is the implementation of the GR-KAN (Group-Rational KAN) layer in PyTorch. This implementation follows the detailed explanation you provided, addressing computational efficiency, parameter overhead, and initialization stability through group-wise parameter sharing, rational activation functions, and variance-preserving initialization.
GR-KAN Layer Implementation in PyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F
class GR_KAN(nn.Module):
"""
Group-Rational KAN (GR-KAN) Layer.
Args:
input_dim (int): Number of input channels.
output_dim (int): Number of output channels.
group (int): Number of groups for parameter sharing.
m (int): Degree of the numerator polynomial in the rational function.
n (int): Degree of the denominator polynomial in the rational function.
"""
def __init__(self, input_dim, output_dim, group, m, n):
super(GR_KAN, self).__init__()
assert input_dim % group == 0, "input_dim must be divisible by group"
self.input_dim = input_dim
self.output_dim = output_dim
self.group = group
self.group_size = input_dim // group
self.m = m
self.n = n
self.epsilon = 1e-6 # Small constant to prevent division by zero
# Weight matrix W of shape (input_dim, output_dim)
self.W = nn.Parameter(torch.Tensor(input_dim, output_dim))
# Rational function coefficients for each group
# P_coeffs: Numerator coefficients of shape (group, m+1)
self.P_coeffs = nn.Parameter(torch.Tensor(group, m + 1))
# Q_coeffs: Denominator coefficients of shape (group, n+1)
self.Q_coeffs = nn.Parameter(torch.Tensor(group, n + 1))
# Initialize parameters
self.reset_parameters()
def reset_parameters(self):
# Initialize W using Xavier Uniform initialization
nn.init.xavier_uniform_(self.W)
# Initialize P_coeffs to represent F(x) = x
# Thus, P(x) = x => coefficients [0, 1, 0, ..., 0]
with torch.no_grad():
self.P_coeffs.zero_()
if self.m >= 1:
self.P_coeffs[:, 1] = 1.0 # Set the coefficient for x^1 to 1
# Initialize Q_coeffs to represent Q(x) = 1
# Thus, Q(x) = 1 => coefficients [1, 0, ..., 0]
with torch.no_grad():
self.Q_coeffs.zero_()
self.Q_coeffs[:, 0] = 1.0 # Set the constant term to 1
def forward(self, x):
"""
Forward pass of the GR-KAN layer.
Args:
x (torch.Tensor): Input tensor of shape (batch_size, input_dim).
Returns:
torch.Tensor: Output tensor of shape (batch_size, output_dim).
"""
batch_size = x.size(0) # Batch size
# Reshape x to (batch_size, group, group_size)
x = x.view(batch_size, self.group, self.group_size)
# Compute P(x) for each group using Horner's method
# P_coeffs: (group, m+1) => reversed for Horner's method
P_reversed = torch.flip(self.P_coeffs, dims=[1]) # (group, m+1)
P = P_reversed[:, 0].unsqueeze(0).unsqueeze(-1) # Initialize with highest degree coefficient
for coeff in P_reversed[:, 1:]:
P = P * x + coeff.unsqueeze(0).unsqueeze(-1)
# P shape: (batch_size, group, group_size)
# Compute Q(x) for each group using Horner's method
Q_reversed = torch.flip(self.Q_coeffs, dims=[1]) # (group, n+1)
Q = Q_reversed[:, 0].unsqueeze(0).unsqueeze(-1) # Initialize with highest degree coefficient
for coeff in Q_reversed[:, 1:]:
Q = Q * x + coeff.unsqueeze(0).unsqueeze(-1)
# Q shape: (batch_size, group, group_size)
# Ensure numerical stability by adding epsilon to Q
Q = Q + self.epsilon
# Compute F(x) = P(x) / Q(x)
F_x = P / Q # (batch_size, group, group_size)
# Reshape F_x back to (batch_size, input_dim)
F_x = F_x.view(batch_size, self.input_dim)
# Compute the final output Y = F(x) @ W
# F_x: (batch_size, input_dim)
# W: (input_dim, output_dim)
Y = torch.matmul(F_x, self.W) # (batch_size, output_dim)
return Y
# Example usage and test case
if __name__ == "__main__":
# Define input parameters
batch_size = 8
input_dim = 64
output_dim = 128
group = 16 # input_dim must be divisible by group
m = 2 # Degree of numerator
n = 2 # Degree of denominator
# Create a random input tensor
x = torch.randn(batch_size, input_dim)
# Initialize GR-KAN layer
gr_kan_layer = GR_KAN(input_dim=input_dim, output_dim=output_dim, group=group, m=m, n=n)
# Forward pass
output = gr_kan_layer(x)
# Print the output shape
print(f"Output shape: {output.shape}") # Expected: (8, 128)
Explanation of the Implementation
-
Initialization (__init__ and reset_parameters):
- Weight Matrix (
W): A learnable parameter of shape (input_dim, output_dim) initialized using Xavier Uniform initialization to facilitate better convergence.
- Rational Function Coefficients (
P_coeffs and Q_coeffs):
P_coeffs: Represents the numerator of the rational function. Initialized to represent the identity function ( F(x) = x ), where ( P(x) = x ). This is achieved by setting the coefficient of ( x^1 ) to 1 and all other coefficients to 0.
Q_coeffs: Represents the denominator of the rational function. Initialized to represent ( Q(x) = 1 ) by setting the constant term to 1 and all other coefficients to 0.
- Grouping: Ensures that the
input_dim is divisible by the number of groups, facilitating group-wise parameter sharing.
-
Forward Pass (forward method):
- Reshaping Input: The input tensor
x of shape (batch_size, input_dim) is reshaped to (batch_size, group, group_size) to facilitate group-wise operations.
- Polynomial Evaluation (Horner's Method):
- Numerator (
P(x)): For each group, the numerator polynomial is evaluated using Horner's method in a vectorized manner. This efficiently computes the polynomial ( P(x) = a_0 + a_1 x + \dots + a_m x^m ).
- Denominator (
Q(x)): Similarly, the denominator polynomial ( Q(x) = b_0 + b_1 x + \dots + b_n x^n ) is evaluated.
- Safe Division: To ensure numerical stability and prevent division by zero, a small constant
epsilon is added to the denominator ( Q(x) ).
- Rational Activation Function (
F(x)): Computed as ( F(x) = \frac{P(x)}{Q(x) + \epsilon} ).
- Reshaping and Linear Transformation: The activated tensor
F(x) is reshaped back to (batch_size, input_dim) and then linearly transformed using the weight matrix W to produce the final output of shape (batch_size, output_dim).
-
Usage Example:
Key Points:
- Group-Wise Parameter Sharing: By dividing the input channels into groups and sharing the rational function coefficients within each group, the model achieves significant reductions in parameter count and computational overhead.
- Rational Activation Functions: The use of rational functions ( F(x) = \frac{P(x)}{Q(x)} ) replaces traditional activation functions, offering greater flexibility and efficiency, especially when implemented using Horner's method.
- Variance-Preserving Initialization: The careful initialization of the numerator and denominator coefficients ensures that the variance of activations is preserved across layers, promoting stable and efficient training.
- Numerical Stability: The addition of a small constant
epsilon to the denominator prevents numerical instability due to division by values approaching zero.
This implementation should integrate seamlessly into transformer architectures like the Kolmogorov–Arnold Transformer (KAT) and can be utilized for tasks such as image recognition and object detection, benefiting from the scalability and performance improvements introduced by GR-KAN.