Implement gradient checking code