Pytorch assign in place mod Info

A torch.Tensor object used with a modify in place function in an assignment statement might unintentionally overwrite the values of the calling variable.

Detector ID
python/pytorch-assign-in-place-mod@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def pytorch_assign_in_place_mod_noncompliant():
2    import torch
3    x = torch.randn([2, 2])
4    y = torch.randn([2, 2])
5    # Noncompliant: in-place method is called as part of assignment statement.
6    z = x.add_(y)

Compliant example

1def pytorch_assign_in_place_mod_compliant():
2    import torch
3    x = torch.randn([2, 2])
4    y = torch.randn([2, 2])
5    # Compliant: in-place method is not called as part of assignment statement.
6    x.add_(y)
7    z = x