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.
Below is a compact, fully-vectorised solution that works on CPU or GPU and does not use any Python loops.
It behaves like torch.roll (positive shifts move elements to the right) but the shift amount is allowed to vary for every row / pixel / location:
python
import torch
def roll_last_dim(values: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
"""
Circularly shift a 3-D tensor along its last (innermost) dimension
with a per-location shift amount.
Parameters
----------
values : (*, K) tensor # typically (N, M, K); must be one dim
# larger than `offsets`
offsets : (*) tensor # typically (N, M); integer shifts.
# Positive = shift right (torch.roll convention)
Returns
-------
rolled : (*, K) tensor # same shape as `values`
"""
if values.ndim != offsets.ndim + 1:
raise ValueError("`offsets` must have one fewer dimension than `values`")
K = values.size(-1) # length of innermost dimension
offsets = offsets.to(torch.long) # gather() requires Long indices
# 1. build a base index [0, 1, 2, ..., K-1]
base_idx = torch.arange(K, device=values.device)
# 2. broadcast it to the shape (*, K)
base_idx = base_idx.view(*(1,)*offsets.ndim, K) # (1,1,…,K)
base_idx = base_idx.expand(*offsets.shape, K) # (*,K)
# 3. subtract the shift (roll right = pick element to the left)
gather_idx = (base_idx - offsets.unsqueeze(-1)) % K # still shape (*,K)
# 4. pick the desired values
rolled = torch.gather(values, -1, gather_idx)
return rolled
Usage example
python
N, M, K = 2, 3, 5
vals = torch.arange(N*M*K).reshape(N, M, K)
shifts = torch.tensor([[0, 1, 2],
[3, 4, -1]]) # shape (N, M)
out = roll_last_dim(vals, shifts)
print("original:\n", vals)
print("shifts:\n", shifts)
print("rolled:\n", out)
Why it works
base_idx is [0 … K-1] replicated for every (N, M) location.
For a positive shift s, element at output index j should come from
input index j-s (torch.roll semantics), hence base_idx - offsets.
Modular arithmetic (% K) implements wrap-around.
torch.gather grabs all elements in one go, so the operation is fully
vectorised and differentiable.
The function is O(N M K) like a regular roll, supports autograd, and works
on either CPU or CUDA tensors without modification.