Skip to content

Commit

Permalink
Support jit hessian (#397)
Browse files Browse the repository at this point in the history
* Support jit hessian

* fix

* fix
  • Loading branch information
zasdfgbnm authored and farhadrgh committed Nov 22, 2019
1 parent f2b9ac8 commit 9833dd6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
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

0 comments on commit 9833dd6

Please sign in to comment.