learningmatter-mit / NeuralForceField

Neural Network Force Field based on PyTorch
MIT License
237 stars 50 forks source link

Variable referenced before assignment #11

Closed mhsiron closed 2 years ago

mhsiron commented 2 years ago

Energy grad referenced before assignment. Believe this should be the resulting forces from prediction variable.

simonaxelrod commented 2 years ago

Hey Martin - would you mind providing an example in which energy_grad was referenced before assignment? It seems like this would only happen if "energy_grad" were not in the model's predictions. Your fix assumes that "forces" is in the model's predictions, but by default the model predictions have the key "energy_grad", not "forces".

mhsiron commented 2 years ago

Hey @simonaxelrod perhaps ignore this PR! I think I must be confused what 'energy_grad' is.

Is energy_grad and forces uses equivalently in the code?

Prior to the PR the resulting 'forces' dictionary key is set to output from energy_grad, and the if statement prior checks to see if a 'forces' key exists in the properties. This is why I believed this should only run if the model included forces!

In the Dataset class the only requirement is nxyz and 'energy_grad' is not required.

Thanks for your time, and apologies for my confusion!

simonaxelrod commented 2 years ago

"energy_grad" stands for energy gradient, which is negative of the forces. If the model produces an energy and takes its gradient, then the model output will be a dictionary containing the keys "energy" and "energy_grad".

You can then make an ASE calculator with the model. You can ask the calculator to produce forces, in which case it will look for "energy_grad" in the model's output, and return its negative. If you ask ASE to produce forces, but the model doesn't compute the energy gradient, then you will get a "referenced before assignment" error, because "energy_grad" wasn't in the model output dictionary. Does that make sense?

Probably this happened because your model doesn't compute the gradient of the energy. This could be because of some model settings that turned the gradient calculation off. Maybe check that out and see if there's a setting that can be changed?