model.py 1.54 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
import torch
import torchani
import os


def celu(x, alpha):
    return torch.where(x > 0, x, alpha * (torch.exp(x/alpha)-1))


class AtomicNetwork(torch.nn.Module):

12
    def __init__(self):
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
        super(AtomicNetwork, self).__init__()
        self.output_length = 1
        self.layer1 = torch.nn.Linear(384, 128)
        self.layer2 = torch.nn.Linear(128, 128)
        self.layer3 = torch.nn.Linear(128, 64)
        self.layer4 = torch.nn.Linear(64, 1)

    def forward(self, aev):
        y = aev
        y = self.layer1(y)
        y = celu(y, 0.1)
        y = self.layer2(y)
        y = celu(y, 0.1)
        y = self.layer3(y)
        y = celu(y, 0.1)
        y = self.layer4(y)
        return y


def get_or_create_model(filename, benchmark=False,
                        device=torchani.default_device):
    aev_computer = torchani.SortedAEV(benchmark=benchmark, device=device)
35
    prepare = torchani.PrepareInput(aev_computer.species, aev_computer.device)
36
37
38
39
    model = torchani.models.CustomModel(
        reducer=torch.sum,
        benchmark=benchmark,
        per_species={
40
41
42
43
            'C': AtomicNetwork(),
            'H': AtomicNetwork(),
            'N': AtomicNetwork(),
            'O': AtomicNetwork(),
44
        })
45
46
47
48
49
50
51

    class Flatten(torch.nn.Module):

        def forward(self, x):
            return x.flatten()

    model = torch.nn.Sequential(prepare, aev_computer, model, Flatten())
52
53
54
55
56
    if os.path.isfile(filename):
        model.load_state_dict(torch.load(filename))
    else:
        torch.save(model.state_dict(), filename)
    return model.to(device)