Fix torch.range Deprecation in PyTorch

Fix torch.range Deprecation in PyTorch

While generating sequences of numbers in PyTorch, you might encounter a deprecation warning when using the torch.range function. Earlier versions of PyTorch allowed developers to rely on torch.range to create evenly spaced values between two endpoints. However, its behavior differs from Python's built-in range, which has caused confusion and subtle bugs - particularly around whether the ending value should be included. To make sequence generation more predictable and consistent, PyTorch now recommends using torch.arange instead.

Consider the following example that still relies on torch.range:

import torch

start = 0
end = 5
x = torch.range(start, end)
print(x) # tensor([0., 1., 2., 3., 4., 5.])

Running this code produces the following deprecation warning:

UserWarning: torch.range is deprecated and will be removed in a future release because its behavior is inconsistent with Python's range builtin. Instead, use torch.arange, which produces values in [start, end).

To fix the deprecation warning, replace torch.range with torch.arange. Since torch.arange excludes the upper bound by default, the end value must be adjusted if you want to preserve the original output:

import torch

start = 0
end = 5
x = torch.arange(start, end + 1)
print(x) # tensor([0., 1., 2., 3., 4., 5.])

Leave a Comment

Cancel reply

Your email address will not be published.