That is probably making more sense as i+h or j+w never exceeds original height or width and those are only a proportion of original sizes.
Although the code I provided needs few other fixes, for instance it uses external libraries that need to be replaced by torch for working on tensors.
Good luck