Hi DeepLearner17,
Please go through the link for a tutorial on creating a custom autograd function. 2
The example you have provided need to return a grad_input which would be required for layer3 to calculate its gradient. In the sense that, grad_output would be in R^{m}. You will need to transform it to R^{n} and return that for gradient to pass through.
Alternatively, Pytorch was built to mimic Numpy to a great degree, so almost any method written using numpy can be converted to their equivalent in Pytorch, which will enable the gradient to flow automatically.