I came across a different solution which uses backward function. It’s all about playing with backward's parameters. More information can be found here 1.3k. I am still looking for a better solution, if it exists.