factoring out the gradient calculation under its own interface.