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

Add energy derivatives to README #145

Merged
merged 3 commits into from
Aug 16, 2024
Merged
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
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,47 @@ to return forces.
torch_force.setOutputsForces(True)
```

Computing energy derivatives with respect to global parameters
--------------------------------------------------------------

TorchForce can compute derivatives of the energy with respect to global parameters.. In order to do so the global parameters must be registered as energy derivatives. This is done by calling `addEnergyParameterDerivative()` for each parameter.

The parameter derivatives can be queried by calling `getEnergyParameterDerivatives()` on the `State` object returned by `Context.getState()`. The result is a dictionary with the parameter names as keys and the derivatives as values.

```python
import torch as pt
from openmmtorch import TorchForce
import openmm as mm


class ForceWithParameters(pt.nn.Module):

def __init__(self):
super(ForceWithParameters, self).__init__()

def forward(self, positions: pt.Tensor, k: pt.Tensor) -> pt.Tensor:
return k * pt.sum(positions**2)


numParticles = 10
system = mm.System()
for _ in range(numParticles):
system.addParticle(1.0)

model = pt.jit.script(ForceWithParameters())
tforce = TorchForce(model)
tforce.setOutputsForces(False)
tforce.addGlobalParameter("k", 2.0)
tforce.addEnergyParameterDerivative("k")
system.addForce(tforce)
context = mm.Context(system, mm.VerletIntegrator(1.0))
context.setPositions(pt.rand(numParticles, 3).numpy())
state = context.getState(getParameterDerivatives=True)
dEdk = state.getEnergyParameterDerivatives()["k"]
```



Recording the model into a CUDA graph
-------------------------------------

Expand Down
Loading