Learn Before
Code
In-Place Tensor Operations via Slice Assignment
To prevent unnecessary memory allocations, the results of an operation can be assigned to a previously allocated tensor using slice notation. For example, if a tensor Z is initialized to have the same shape as Y using zeros_like, executing Z[:] = X + Y overwrites the existing values of Z with the newly computed elements. This ensures the update occurs in-place, keeping the memory address of Z unchanged.
0
1
Updated 2026-05-01
Tags
D2L
Dive into Deep Learning @ D2L