Added caching for values and grads