I need to interpolate some positional embeddings from shape (4096, hiddensize) to (5000,…
- User
I need to interpolate some positional embeddings from shape (4096, hidden_size) to (5000, hidden_size) is there easy way to do this in pytorch?
- Assistant
Yes, you can easily interpolate positional embeddings in PyTorch using the
torch.nn.functional.interpolatefunction. This function allows you to resize a tensor using different methods such as nearest-neighbor, linear, bilinear, etc.Here's an example on how to interpolate your embeddings from a shape of (4096, hidden_size) to (5000, hidden_size):
import torch import torch.nn.functional as F # Assuming you have some positional embeddings of shape (4096, hidden_size) hidden_size = 512 # Example hidden size embeddings = torch.randn(4096, hidden_size) # Add a batch dimension and channel dimension to make it compatible with interpolate function embeddings = embeddings.unsqueeze(0).permute(0, 2, 1) # Shape (1, hidden_size, 4096) # Interpolate to the new shape (1, hidden_size, 5000) new_length = 5000 interpolated_embeddings = F.interpolate(embeddings, size=new_length, mode='linear', align_corners=True) # Remove the added dimensions to get back to shape (5000, hidden_size) interpolated_embeddings = interpolated_embeddings.permute(0, 2, 1).squeeze(0) print("Original shape:", embeddings.shape) print("Interpolated shape:", interpolated_embeddings.shape) - User
look at the output? wtf... old_weights = self.model.transformer['wpe'].weight.data n_embd = old_weights.shape[-1]
print(old_weights.shape) upsample = torch.nn.Upsample(size=(new_block_size, n_embd), mode='linear') # new_weights = upsample(old_weights.unsqueeze(1)) old_weights_rshp = old_weights.unsqueeze(0).permute(0, 2, 1) #We add an extra dimension (required by the interpolation fucntion) and reverse order (required by interpolation function) new_weights = torch.nn.functional.interpolate(old_weights_rshp, size=new_block_size, mode='linear') new_weights = new_weights.permute(0, 2, 1).squeeze(0) #undo the extra dimension and restore the original order of the shape. print(new_weights.shape) print(f'✅ Adjusting positional embeddings length to {new_block_size} from the loaded block_size {old_length}.\n') new_wpe = torch.nn.Embedding(new_block_size, n_embd) # new_wpe.weight.data = new_weights # new_wpe.weight.data[old_length:] = self.model.transformer['wpe'].weight[0].view(1, -1).expand(new_block_size-old_length, -1) print('org',self.model.transformer['wpe'].weight[:3][:5]) print('new', new_wpe.weight[:3][:5]) - Assistant