Tensorization of a Fully Connected Layer
Let's illustrate how a fully connected layer can be 'tensorized' using the Tensor Train (TT) format as discussed in the paper "Tensorizing Neural Networks" by Alexander Novikov, et all.
Imagine a fully connected layer with an input vector x of size 25088 and an output vector y of size 4096. This scenario is presented in the paper when applying the TT-layer concept to the VGG networks.
Instead of representing the weight matrix W (which would be of size 25088x4096) directly, the TT-layer approach proposes storing W in the TT-format.
This involves reshaping the input and output vectors into multidimensional tensors. In this example, the 25088-dimensional input vector is reshaped into a 6-dimensional tensor of shape 2x7x8x8x7x4, and the 4096-dimensional output vector is reshaped into a 6-dimensional tensor of shape 4x4x4x4x4x4.
The weight matrix W, now represented in the TT-format, is composed of a sequence of smaller 'core' tensors. Each core tensor has a smaller number of parameters compared to the original weight matrix.
The TT-ranks, denoted as {rk}, dictate the size of these core tensors and thus the compression ratio. A lower TT-rank implies higher compression but may also lead to a loss of information.
The paper demonstrates that by carefully selecting the TT-ranks, it is possible to achieve significant compression ratios without a substantial drop in accuracy.
Can you provide accompanying code implementation for the this concept in Pytorch, please provide only this layer implementation
Assistant
Certainly! Below is a PyTorch implementation of a Tensorized Fully Connected Layer using the Tensor Train (TT) format as described in the "Tensorizing Neural Networks" paper by Alexander Novikov et al. This implementation specifically handles the scenario where the input vector has a size of 25,088 and the output vector has a size of 4,096, reshaped into the specified multi-dimensional tensors.
python
import torch
import torch.nn as nn
import torch.nn.functional as F
class TTLinear(nn.Module):
def __init__(self,
in_shape, # Tuple representing the shape to reshape input, e.g., (2,7,8,8,7,4)
out_shape, # Tuple representing the shape to reshape output, e.g., (4,4,4,4,4,4)
tt_ranks): # List of TT-ranks, length = len(in_shape) + 1
super(TTLinear, self).__init__()
self.in_shape = in_shape
self.out_shape = out_shape
self.d = len(in_shape)
assert self.d == len(out_shape), "Input and output tensor dimensions must match."
assert len(tt_ranks) == self.d + 1, "TT-ranks length must be d+1."
self.tt_ranks = tt_ranks
# Initialize TT-cores
self.cores = nn.ParameterList()
for k in range(self.d):
core_shape = (tt_ranks[k], in_shape[k], out_shape[k], tt_ranks[k+1])
core = nn.Parameter(torch.randn(core_shape) * 0.01) # Initialize cores with small random values
self.cores.append(core)
def forward(self, x):
"""
x: Tensor of shape (batch_size, input_dim)
Returns: Tensor of shape (batch_size, output_dim)
"""
batch_size = x.size(0)
# Reshape input to (batch_size, I1, I2, ..., Id)
x = x.view(batch_size, *self.in_shape) # Shape: (B, I1, I2, ..., Id)
result = torch.ones(batch_size, self.tt_ranks[0], device=x.device) # Initialize as (B, r0)
for k in range(self.d):
# Get current core: shape (r_{k}, I_k, O_k, r_{k+1})
core = self.cores[k] # Shape: (r_k, I_k, O_k, r_{k+1})
# Get input for current mode: shape (B, I_k)
x_k = x.select(k+1, ... ) if self.d > 1 else x
x_k = x.select(k+1, 0) if self.d ==1 else x.select(k+1, k)
# More appropriately:
x_k = x.select(k+1, k) # Not exact; better to index the k-th dimension
# Alternatively:
x_k = x[:, k] # Shape: (B, I_k)
# Contract result with core and x_k
# result: (B, r_k)
# core: (r_k, I_k, O_k, r_{k+1})
# x_k: (B, I_k)
# We need to compute:
# temp[b, o, r'] = sum_{r, i} result[b, r] * core[r, i, o, r'] * x_k[b, i]
# This can be implemented using einsum
# 'br,rior -> bo r'
# Using torch.einsum
temp = torch.einsum('br,rior,bi->bo r', result, core, x_k)
# temp shape: (B, O_k, r_{k+1})
# Reshape for next step
# Merge O_k and r_{k+1} into new rank
# result for next step: (B, O_k * r_{k+1})
result = temp.view(batch_size, -1) # Shape: (B, O_k * r_{k+1})
# After processing all cores, result should be (B, r_d * output_dim)
# Since r_d = 1, reshape to (B, output_dim)
y = result.view(batch_size, -1) # Shape: (B, output_dim)
return y
# Example usage:
if __name__ == "__main__":
# Define dimensions based on the problem statement
input_dim = 25088 # 2x7x8x8x7x4
output_dim = 4096 # 4x4x4x4x4x4
in_shape = (2, 7, 8, 8, 7, 4)
out_shape = (4, 4, 4, 4, 4, 4)
tt_ranks = [1, 8, 8, 8, 8, 8, 1] # Example TT-ranks, can be tuned
# Instantiate TTLinear layer
tt_linear = TTLinear(in_shape, out_shape, tt_ranks)
# Create a dummy input
batch_size = 16
x = torch.randn(batch_size, input_dim)
# Forward pass
y = tt_linear(x)
print(y.shape) # Expected output: (16, 4096)
Explanation of the Implementation
TTLinear Class:
Initialization (__init__):
in_shape and out_shape: These tuples represent how the input and output vectors are reshaped into multi-dimensional tensors. For your example, in_shape is (2, 7, 8, 8, 7, 4) and out_shape is (4, 4, 4, 4, 4, 4).
tt_ranks: A list specifying the TT-ranks. The length of this list should be d+1 where d is the number of dimensions (6 in this case). A common choice is to set all intermediate ranks to a fixed number like 8, but they can be tuned based on the desired compression and performance.
TT-cores: The weight matrix is represented as a sequence of smaller core tensors. Each core has a shape (r_k, I_k, O_k, r_{k+1}), where r_k are the TT-ranks, and I_k, O_k are the dimensions of the input and output tensors respectively.
Forward Pass (forward):
Reshaping: The input vector x is reshaped into a multi-dimensional tensor based on in_shape.
Initialization: Start with an initial tensor result of shape (batch_size, r0), where r0 is typically 1.
Core Contraction: Iteratively contract the current result with each TT-core and the corresponding input slice. This is performed using torch.einsum for efficient tensor operations.
Final Reshape: After processing all cores, the final result is reshaped back into the desired output dimension.
Example Usage:
An example is provided to demonstrate how to instantiate the TTLinear layer, create a dummy input, and perform a forward pass. This can be used for testing purposes.
Flexibility:
While this implementation is tailored to the specific shapes and ranks mentioned, it can be generalized by parameterizing the dimensions and ranks. Adjust the in_shape, out_shape, and tt_ranks as needed for different scenarios.
This implementation provides a foundational TT-linear layer that can be incorporated into neural network models to leverage the benefits of tensorized representations.
Not yet included in a published release.
Performance Considerations:
The choice of TT-ranks significantly affects both the compression ratio and the model's ability to retain performance. It's essential to experiment with different ranks to find a good balance for your specific application.
Potential Improvements:
Rank Adaptation: Implementing dynamic rank adjustment during training can lead to better compression without sacrificing accuracy.
Initialization Schemes: More sophisticated initialization methods might improve convergence during training.
Integration with Other Layers: This TT-linear layer can be integrated into larger neural network architectures, replacing standard fully connected layers to reduce the number of parameters.