The code might be alright, but I’m unfamiliar with the use case.
It seems you are trying to maximize the intermediate activation by optimizing the input tensor?
Do you have any references, why a random input tensor would not be the result, i.e. should the input tensor learn some structure for this task?