Assume I am using pytorch framework and I have two tensors; a 2D offset tensor and a 3D value tensor. I would like to perform a roll with wrap-around along the innermost dimension of the 3D value tensor. The amount of roll required is specified in the 2D offset tensor. Can you write a function in python that implement this?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a PyTorch function that performs a roll operation on a 3D tensor using offset values from a 2D tensor:
python
import torch
def roll_with_offset(value_tensor, offset_tensor):
"""
Roll a 3D tensor along its innermost dimension using offsets from a 2D tensor.
Args:
value_tensor: 3D tensor of shape (A, B, C)
offset_tensor: 2D tensor of shape (A, B) specifying roll amounts
Returns:
3D tensor of same shape as value_tensor with rolled values
"""
A, B, C = value_tensor.shape
assert offset_tensor.shape == (A, B), f"Offset tensor shape {offset_tensor.shape} doesn't match expected {(A, B)}"
# Create base indices for the innermost dimension
base_indices = torch.arange(C, device=value_tensor.device).expand(A, B, C)
# Apply offset (we subtract because rolling right means taking from left positions)
offset_expanded = offset_tensor.unsqueeze(-1).expand(A, B, C)
# Calculate source indices with wrap-around
source_indices = (base_indices - offset_expanded) % C
# Use gather to select elements
rolled_tensor = torch.gather(value_tensor, dim=2, index=source_indices)
return rolled_tensor
# Example usage
if __name__ == "__main__":
# Create example tensors
value_tensor = torch.tensor([
[[1, 2, 3, 4],
[5, 6, 7, 8]],
[[9, 10, 11, 12],
[13, 14, 15, 16]]
], dtype=torch.float32) # Shape: (2, 2, 4)
offset_tensor = torch.tensor([
[1, 2],
[0, 3]
]) # Shape: (2, 2)
result = roll_with_offset(value_tensor, offset_tensor)
print("Original tensor:")
print(value_tensor)
print("\nOffset tensor:")
print(offset_tensor)
print("\nRolled tensor:")
print(result)
# Expected output:
# [1,2,3,4] rolled by 1 -> [4,1,2,3]
# [5,6,7,8] rolled by 2 -> [7,8,5,6]
# [9,10,11,12] rolled by 0 -> [9,10,11,12]
# [13,14,15,16] rolled by 3 -> [14,15,16,13]
The function works by:
Creating base indices: A tensor with indices 0, 1, 2, ..., C-1 for each position in the 3D tensor
Applying offsets: Subtracting the offset values (because rolling right means taking elements from left positions)
Handling wrap-around: Using modulo operation to ensure indices stay within bounds
Gathering elements: Using torch.gather to efficiently select elements from the calculated source indices
The positive offset values will roll elements to the right (with wrap-around), and negative offsets will roll to the left. The function is fully vectorized and should be efficient for large tensors.