Skip to content

Commit

Permalink
Handle negative values for dim input in pad_across_processes (#3114)
Browse files Browse the repository at this point in the history
* Handle negative values for dim

* Add tests for negative dimension
  • Loading branch information
mariusarvinte authored Oct 8, 2024
1 parent 127818f commit ae9cb6e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/accelerate/utils/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,8 +652,11 @@ def _pad_across_processes(tensor, dim=0, pad_index=0, pad_first=False):
CannotPadNestedTensorWarning,
)
return tensor
if dim >= len(tensor.shape):
if dim >= len(tensor.shape) or dim < -len(tensor.shape):
return tensor
# Convert negative dimensions to non-negative
if dim < 0:
dim += len(tensor.shape)

# Gather all sizes
size = torch.tensor(tensor.shape, device=tensor.device)[None]
Expand Down
9 changes: 9 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,15 @@ def test_pad_across_processes(self):
nt2 = pad_across_processes(nt)
assert nt is nt2

# Basic functionality
tensor = torch.randn(4, 3, 100)
padded_tensor = pad_across_processes(tensor, dim=-1)
assert padded_tensor.shape[-1] == 100

# dim = -4 is out of bounds
padded_tensor = pad_across_processes(tensor, dim=-4)
assert padded_tensor is tensor

def test_slice_and_concatenate(self):
# First base case: 2 processes, batch size of 1
num_processes = 2
Expand Down

0 comments on commit ae9cb6e

Please sign in to comment.