Closed JinyinZha closed 1 year ago
Could you please provide a minimum reproducer code? As long as your model takes positions as inputs and outputs energies and optionally forces it should be fine.
class Packed_Encoder(nn.Module):
def __init__(self,encoder,angle_ids):
super(Packed_Encoder, self).__init__()
self.encoder = encoder# a MLP network that output a 1x2 tensor
self.angle_ids = angle_ids
def forward(self,x):
x = self.get_angle(x)
print("x",x)
return self.encoder(x)
def get_angle(self,x):
return x
angle_ids = self.angle_ids
print(x.shape,"x.shape")
if len(x.shape) == 2:
x = x.reshape(1,-1,3)
return x[0,0,0:2]
a1 = (x[:,angle_ids[:,1],:] - x[:,angle_ids[:,0],:]).reshape(-1,len(angle_ids[:,0]),3)
a2 = (x[:,angle_ids[:,2],:] - x[:,angle_ids[:,1],:]).reshape(-1,len(angle_ids[:,0]),3)
a3 = (x[:,angle_ids[:,3],:] - x[:,angle_ids[:,2],:]).reshape(-1,len(angle_ids[:,0]),3)
print("a1",a1)
v1 = torch.cross(a1, a2)
v2 = torch.cross(a2, a3)
print("v1",v1)
sign = torch.sign(torch.sum(v1 * a3,dim=2))
print("sign",sign)
porm = - sign * sign + sign + 1
cos = torch.sum(v1*v2,dim=2) / ((torch.sum(v1*v1,dim=2)**0.5) * (torch.sum(v2*v2,dim=2))**0.5)
print("cos0",cos)
for i in range(cos.shape[0]):
for j in range(cos.shape[1]):
if cos[i][j] > 1:
cos[i][j] = 1
elif cos[i][j] < -1:
cos[i][j] = -1
print("cos",cos)
return torch.arccos(cos) * porm
Looking at the particular error, it seems like your model is not returning forces explicitly. This makes openmm-torch automatically compute them by calling backwards on your model. The error you post seems to indicate that your model cannot be backpropagated. I can think of a number of reasons why this would happen:
I would say the eror in your network stems from this:
self.encoder = encoder# a MLP network that output a 1x2 tensor
Your network is supposed to return only one number, the energy. This is consistent with the pytorch error, since grad expects a scalar, but you have a 1x2 tensor if the comment is to be trusted.
You are right! I have successfully fixed the problem. Thanks a lot~
I am trying to use openmm-torch to add several force to dihedrals. (Namely, the force is in form of F(φ1,φ2,...φn,ψ1,ψ2,...,ψn)) However openmm-torch was made for a force in the form of F(x1,x2,...xn)), where x is the coordinate of atom. I attempted to add an additional part converting x into dihedrals in the network structure, and then input dihedrals into my network. However, it turns out that the grad is reduced.
If the additional conversion is changed to directly " return x" (where x is the input, namely no changes), the code could run well (Indeed, I changed my network to fit the dimension of input. ) I found any calculations to the input of forward function would cause this error.
I am wondering whether my attempt could be realized. If could, then how? I am looking forward to your answer. Thank you~