fix bugs of calculating grad