Commit 8e05749
Fix integer overflow bug in triu/tril for large diagonal values (pytorch#153240)
This PR fixes a bug in the implementation of `apply_triu_tril_single` where using extremely large values for the diagonal argument (e.g. `diagonal=9223372036854775807`) could result in integer overflow and incorrect results. The masking logic is re-written to avoid this issue by always iterating over all columns, ensuring correctness even for large or extreme diagonal values.
Example of the original incorrect behavior:
```python
a = torch.ones(5,5)
torch.triu(a, 9223372036854775807)
# Before:
# tensor([[0., 0., 0., 0., 0.],
# [1., 1., 1., 1., 1.],
# [1., 1., 1., 1., 1.],
# [1., 1., 1., 1., 1.],
# [1., 1., 1., 1., 1.]])
```
The new implementation guards against overflow and produces correct results for all valid input values.
Pull Request resolved: pytorch#153240
Approved by: https://github.com/albanD1 parent b334a5a commit 8e05749
2 files changed
Lines changed: 34 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
52 | 52 | | |
53 | 53 | | |
54 | 54 | | |
| 55 | + | |
55 | 56 | | |
56 | 57 | | |
57 | 58 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
9840 | 9840 | | |
9841 | 9841 | | |
9842 | 9842 | | |
| 9843 | + | |
| 9844 | + | |
| 9845 | + | |
| 9846 | + | |
| 9847 | + | |
| 9848 | + | |
| 9849 | + | |
| 9850 | + | |
| 9851 | + | |
| 9852 | + | |
| 9853 | + | |
| 9854 | + | |
| 9855 | + | |
| 9856 | + | |
| 9857 | + | |
| 9858 | + | |
| 9859 | + | |
| 9860 | + | |
| 9861 | + | |
| 9862 | + | |
| 9863 | + | |
| 9864 | + | |
| 9865 | + | |
| 9866 | + | |
| 9867 | + | |
| 9868 | + | |
| 9869 | + | |
| 9870 | + | |
| 9871 | + | |
| 9872 | + | |
| 9873 | + | |
| 9874 | + | |
| 9875 | + | |
9843 | 9876 | | |
9844 | 9877 | | |
9845 | 9878 | | |
| |||
0 commit comments