Skip to content

PyTorch: Migrate deprecated Tensor .data to .detach()

The attribute .data was deprecated in PyTorch version v0.4.0 (see quoted changelog below), .detach() should be used instead.

.data was the primary way to get the underlying Tensor from a Variable. [...] However, .data can be unsafe in some cases. Any changes on wouldn't be tracked by autograd, and the computed gradients would be incorrect if x is needed in a backward pass.

A safer alternative is to use x.detach(), which also returns a Tensor that shares data with requires_grad=False, but will have its in-place changes reported by autograd if x is needed in backward.

Additionally, .data is not officially documented, whereas .detach() is, and can break in future releases.

Edited by rodrigobdz

Merge request reports