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

Support jit hessian #397

Merged
merged 6 commits into from
Nov 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import unittest
import torch
import torchani


Expand All @@ -9,6 +10,9 @@ def testChemicalSymbolsToInts(self):
self.assertEqual(len(str2i), 6)
self.assertListEqual(str2i('BACCC').tolist(), [1, 0, 2, 2, 2])

def testHessianJIT(self):
torch.jit.script(torchani.utils.hessian)


if __name__ == '__main__':
unittest.main()
13 changes: 10 additions & 3 deletions torchani/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,13 @@ def __len__(self):
return len(self.rev_species)


def hessian(coordinates, energies=None, forces=None):
def _get_derivatives_not_none(x: Tensor, y: Tensor, retain_graph: Optional[bool] = None, create_graph: bool = False) -> Tensor:
ret = torch.autograd.grad([y.sum()], [x], retain_graph=retain_graph, create_graph=create_graph)[0]
assert ret is not None
return ret


def hessian(coordinates: Tensor, energies: Optional[Tensor] = None, forces: Optional[Tensor] = None) -> Tensor:
"""Compute analytical hessian from the energy graph or force graph.

Arguments:
Expand All @@ -263,11 +269,12 @@ def hessian(coordinates, energies=None, forces=None):
if energies is not None and forces is not None:
raise ValueError('Energies or forces can not be specified at the same time')
if forces is None:
forces = -torch.autograd.grad(energies.sum(), coordinates, create_graph=True)[0]
assert energies is not None
forces = -_get_derivatives_not_none(coordinates, energies, create_graph=True)
flattened_force = forces.flatten(start_dim=1)
force_components = flattened_force.unbind(dim=1)
return -torch.stack([
torch.autograd.grad(f.sum(), coordinates, retain_graph=True)[0].flatten(start_dim=1)
_get_derivatives_not_none(coordinates, f, retain_graph=True).flatten(start_dim=1)
for f in force_components
], dim=1)

Expand Down