update loss function and gradient