Translate your python script using C++ like functions like put_, narrow testing it (to making sure it works) than just go to C++ replicating everything.
I must admit that I’m not using stack overflow as a source of PyTorch advice much but would venture that the average person answering here (heavily skewed towards ptrblck and alband) is more involved in PyTorch than the average stackoverflower - point in case: as noticed by in the comments to that answer, the code piece does have at least one important typo (Tensor vs. tensor) leading to non-working code.
Back in the day when I re-implemented torch::bilinear in C++, one could not assign to the result of a function call but had to assign it to a temporary variable first. That is probably more than 2 years now, so it might have changed, but this is why I would use copy. In Python it’s impossible to assign to a function call result, too, so copy_ does work better with the golden tip, too.