Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated code for Inverse Hessian Product #1

Open
lindsey98 opened this issue Jan 22, 2024 · 0 comments
Open

Updated code for Inverse Hessian Product #1

lindsey98 opened this issue Jan 22, 2024 · 0 comments

Comments

@lindsey98
Copy link
Owner

lindsey98 commented Jan 22, 2024

import torch

def inverse_hessian_product(loss_func, x, damping=0.01, iteration=5):

    x.requires_grad_(True)
    # Calculate the gradient of the loss with respect to the training data
    loss = loss_func(x)
    grad = torch.autograd.grad(loss, x, create_graph=True)[0]
    grad_norm = torch.norm(grad)
    cur_estimate = grad.clone()

    # Inverse Hessian product Update: gradient + (I - Hessian_at_x) * cur_estimate, where the cur_estimate is initialized as gradient
    for i in range(iteration):
        # Hessian * gradient
        _, hvp = torch.autograd.functional.hvp(loss_func, x, cur_estimate)
        hvp_norm = torch.norm(hvp, p='fro')
        cur_estimate = grad + (1-damping) * cur_estimate - (hvp / hvp_norm) * grad_norm

    return cur_estimate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant