Thank you so much for the hint. I implemented a function as below. loss_and_gradients is a numpy function which computes both the loss and gradients w.r.t to input. Once the function is called in the forward path, it computes the gradients as well. Do I have to call loss_and_gradients function in the backward path again? I need the gradient only w.r.t to  input, and not the other input values (i.e. imgL, cost, imgD).
class MyCustomLoss(Function):
    
    @staticmethod
    def forward(self, input, imgL, cost, imgD):
        self.loss, self.gradients = loss_and_gradients(imgL, cost, imgD, input)
        return self.loss
    
    @staticmethod
    def backward(self, grad_output):
       return self.gradients, None, None, None