Skip to content

Commit e6d97ff

Browse files
[PyTorch] Fix cross_entropy_forward stride guard for non-contiguous input (NVIDIA#2746)
* Fix cross_entropy_forward stride guard for non-contiguous input Signed-off-by: Bias92 <pewpewplay315@gmail.com> * Add regression test for non-contiguous transposed input Signed-off-by: Bias92 <pewpewplay315@gmail.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Signed-off-by: Bias92 <pewpewplay315@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent f64941a commit e6d97ff

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

‎tests/pytorch/test_parallel_cross_entropy.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,24 @@ def test_ignore_idx_reduced_loss(self):
167167
reduce_loss=True,
168168
ignore_idx=True,
169169
)
170+
171+
172+
def test_non_contiguous_transposed_input():
173+
"""Regression test: stride(-2) != shape[-1] should not produce wrong results."""
174+
s, b, v = 4, 2, 8
175+
torch.manual_seed(42)
176+
logits = torch.randn(s, b, v, device="cuda")
177+
target = torch.randint(0, v, (b, s), device="cuda")
178+
179+
logits_transposed = logits.transpose(0, 1) # stride(-2) != shape[-1]
180+
logits_contiguous = logits_transposed.contiguous()
181+
182+
assert logits_transposed.stride(-1) == 1
183+
assert logits_transposed.stride(-2) != logits_transposed.shape[-1]
184+
185+
loss_t = parallel_cross_entropy(logits_transposed, target, 0.0, False, None)
186+
loss_c = parallel_cross_entropy(logits_contiguous, target, 0.0, False, None)
187+
188+
assert torch.allclose(
189+
loss_t, loss_c
190+
), f"Non-contiguous transposed input gave wrong results: {loss_t} vs {loss_c}"

‎transformer_engine/pytorch/triton/cross_entropy.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def cross_entropy_forward(
4949
n_non_ignore = torch.zeros(1, dtype=torch.int64, device=_input.device)
5050

5151
# ensure _input and target are contiguous in the last dimension
52-
if _input.stride(-1) != 1:
52+
if _input.stride(-1) != 1 or _input.stride(-2) != _input.shape[-1]:
5353
_input = _input.contiguous()
5454
if target.stride(-1) != 1:
5555
target = target.contiguous()

0 commit comments

Comments
 (0)