To modify the ChebyKANLayer to handle inputs with additional dimensions (similar to how nn.Linear operates on the last dimension), you'll need to adjust the reshaping and tensor operations to be more flexible. This involves:
-
Avoiding Fixed Reshaping: Instead of using view and expand, utilize unsqueeze and broadcasting to handle arbitrary batch dimensions.
-
Adjusting the Einstein Summation (einsum): Update the einsum equation to accommodate additional leading dimensions by using ellipsis (...).
Here's the revised code with these modifications:
import torch
import torch.nn as nn
class ChebyKANLayer(nn.Module):
def __init__(self, input_dim, output_dim, degree):
super(ChebyKANLayer, self).__init__()
self.inputdim = input_dim
self.outdim = output_dim
self.degree = degree
# Initialize Chebyshev coefficients with shape (input_dim, output_dim, degree + 1)
self.cheby_coeffs = nn.Parameter(torch.empty(input_dim, output_dim, degree + 1))
nn.init.xavier_normal_(self.cheby_coeffs, gain=1 / (input_dim * (degree + 1)))
# Register arange as a buffer to ensure it's moved with the model's device and dtype
self.register_buffer("arange", torch.arange(0, degree + 1, 1, dtype=torch.float32))
def forward(self, x):
"""
Args:
x: Tensor of shape (..., input_dim)
Returns:
y: Tensor of shape (..., output_dim)
"""
# Ensure x is within [-1, 1] using tanh
x = torch.tanh(x) # Shape: (..., input_dim)
# Apply arccos to normalize input for Chebyshev polynomials
x = torch.acos(x) # Shape: (..., input_dim)
# Multiply by arange to get x * [0, 1, ..., degree]
# This broadcasts arange to the last dimension
x = x.unsqueeze(-1) * self.arange # Shape: (..., input_dim, degree + 1)
# Apply cosine to compute Chebyshev polynomials
x = torch.cos(x) # Shape: (..., input_dim, degree + 1)
# Perform the einsum operation to compute the weighted sum
# "...id" corresponds to all leading dimensions, input_dim, degree + 1
# "iod" corresponds to input_dim, output_dim, degree + 1
# The resulting shape is (..., output_dim)
y = torch.einsum("...id,iod->...o", x, self.cheby_coeffs)
return y
Detailed Explanation:
-
Handling Arbitrary Batch Dimensions:
- Before: The original code uses
x.view((-1, self.inputdim, 1)).expand(-1, -1, self.degree + 1), which flattens all leading dimensions into one and then expands. This approach doesn't generalize well to inputs with multiple leading dimensions.
- After: Using
x.unsqueeze(-1) adds a new dimension at the end without altering the existing batch structure. Multiplying by self.arange leverages broadcasting to replicate the range across the new dimension.
-
Flexible Einstein Summation (einsum):
- Before: The original
einsum equation "bid,iod->bo" assumes fixed dimensions, which breaks when additional batch dimensions are present.
- After: The updated equation
"…id,iod->…o" uses ellipsis (...) to represent any number of leading dimensions, ensuring that the operation is applied correctly regardless of the input's shape.
-
Preserving Data Types and Devices:
- The
arange buffer is registered with a specified dtype (torch.float32) to ensure compatibility during operations. This buffer will automatically move to the appropriate device (CPU or GPU) when the model is moved.
-
Usage Example:
Here's how you might use the modified ChebyKANLayer in a model:
# Define layer dimensions
input_dim = 128
output_dim = 64
degree = 3
# Instantiate the layer
cheby_layer = ChebyKANLayer(input_dim, output_dim, degree)
# Example input with additional dimensions, e.g., (batch_size, height, width, input_dim)
x = torch.randn(32, 28, 28, input_dim)
# Forward pass
y = cheby_layer(x) # Output shape: (32, 28, 28, output_dim)
This revised implementation ensures that ChebyKANLayer behaves similarly to nn.Linear, supporting inputs with arbitrary leading dimensions and applying the Chebyshev polynomial transformation across the last dimension.