File size: 8,519 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""NumPy translation of DGL's SIGN and FeedForwardNet (Apache-2.0).

Source: vendor/dgl_sign/sign.py, commit recorded in vendor/SOURCES.json.
Adam arithmetic follows PyTorch v1.5.0; its license and reference source are
in vendor/pytorch_reference/. Both upstream source copies are unmodified.
Weights are stored transposed relative to torch.nn.Linear. No feature
standardization, label propagation, ridge term, or extra feature is added.
"""
from __future__ import annotations

import numpy as np


class Parameter:
    def __init__(self, value):
        self.value = np.asarray(value, dtype=np.float32)
        self.grad = np.zeros_like(self.value)


class Linear:
    def __init__(self, in_size, out_size, rng):
        # nn.init.xavier_uniform_(weight, gain=calculate_gain("relu"))
        bound = np.sqrt(12.0 / (in_size + out_size))
        self.weight = Parameter(rng.uniform(-bound, bound, (in_size, out_size)))
        self.bias = Parameter(np.zeros(out_size, dtype=np.float32))

    def forward(self, x, training, rng):
        return x @ self.weight.value + self.bias.value, x if training else None

    def backward(self, grad, cache):
        self.weight.grad += cache.T @ grad
        self.bias.grad += grad.sum(axis=0)
        return grad @ self.weight.value.T

    def parameters(self, prefix):
        return [(prefix + ".weight", self.weight), (prefix + ".bias", self.bias)]


class PReLU:
    def __init__(self):
        # torch.nn.PReLU() has one learned scalar, initialized to 0.25.
        self.weight = Parameter(np.array([0.25], dtype=np.float32))

    def forward(self, x, training, rng):
        return np.where(x > 0, x, self.weight.value * x), x if training else None

    def backward(self, grad, cache):
        positive = cache > 0
        self.weight.grad[0] += np.sum(grad * np.where(positive, 0, cache))
        return grad * np.where(positive, np.float32(1), self.weight.value)

    def parameters(self, prefix):
        return [(prefix + ".weight", self.weight)]


class Dropout:
    def __init__(self, probability):
        self.probability = probability

    def forward(self, x, training, rng):
        if not training or self.probability == 0:
            return x, None
        # Inverted Bernoulli dropout, just as torch.nn.Dropout.
        mask = (rng.random(x.shape, dtype=np.float32) >= self.probability)
        return x * mask / np.float32(1 - self.probability), mask

    def backward(self, grad, cache):
        if cache is None:
            return grad
        return grad * cache / np.float32(1 - self.probability)


class FeedForwardNet:
    def __init__(self, in_feats, hidden, out_feats, n_layers, dropout, rng):
        sizes = [in_feats] + [hidden] * (n_layers - 1) + [out_feats]
        self.layers = [Linear(a, b, rng) for a, b in zip(sizes, sizes[1:])]
        self.prelu = PReLU() if n_layers > 1 else None
        self.dropout = Dropout(dropout)

    def forward(self, x, training, rng):
        caches = []
        for index, layer in enumerate(self.layers):
            x, linear_cache = layer.forward(x, training, rng)
            prelu_cache = drop_cache = None
            if index < len(self.layers) - 1:
                x, prelu_cache = self.prelu.forward(x, training, rng)
                x, drop_cache = self.dropout.forward(x, training, rng)
            caches.append((linear_cache, prelu_cache, drop_cache))
        return x, caches if training else None

    def backward(self, grad, caches):
        for index in range(len(self.layers) - 1, -1, -1):
            linear_cache, prelu_cache, drop_cache = caches[index]
            if index < len(self.layers) - 1:
                grad = self.dropout.backward(grad, drop_cache)
                grad = self.prelu.backward(grad, prelu_cache)
            grad = self.layers[index].backward(grad, linear_cache)
        return grad

    def parameters(self, prefix):
        result = []
        for index, layer in enumerate(self.layers):
            result.extend(layer.parameters(prefix + f".layers.{index}"))
        if self.prelu is not None:
            result.extend(self.prelu.parameters(prefix + ".prelu"))
        return result


class SIGN:
    def __init__(self, in_feats, hidden, out_feats, num_hops, n_layers,
                 dropout, input_drop, seed=0):
        self.rng = np.random.default_rng(seed)
        self.hidden = hidden
        self.prelu = PReLU()
        self.dropout = Dropout(dropout)
        self.input_drop = Dropout(input_drop)
        self.inception_ffs = [
            FeedForwardNet(in_feats, hidden, hidden, n_layers, dropout, self.rng)
            for _ in range(num_hops)
        ]
        self.project = FeedForwardNet(num_hops * hidden, hidden, out_feats,
                                      n_layers, dropout, self.rng)
        self._parameters = self.prelu.parameters("prelu")
        for index, branch in enumerate(self.inception_ffs):
            self._parameters.extend(branch.parameters(f"inception_ffs.{index}"))
        self._parameters.extend(self.project.parameters("project"))

    def named_parameters(self):
        return self._parameters

    def zero_grad(self):
        for _, parameter in self._parameters:
            parameter.grad.fill(0)

    def forward(self, feats, training=False):
        # Match the upstream ordering: apply all input dropouts first.
        inputs = [self.input_drop.forward(x, training, self.rng) for x in feats]
        hidden, branch_caches = [], []
        for (x, _), branch in zip(inputs, self.inception_ffs):
            x, cache = branch.forward(x, training, self.rng)
            hidden.append(x)
            branch_caches.append(cache)
        x, prelu_cache = self.prelu.forward(np.concatenate(hidden, axis=1),
                                           training, self.rng)
        x, drop_cache = self.dropout.forward(x, training, self.rng)
        logits, project_cache = self.project.forward(x, training, self.rng)
        cache = (branch_caches, prelu_cache, drop_cache, project_cache)
        return logits, cache if training else None

    def backward(self, grad, cache):
        branch_caches, prelu_cache, drop_cache, project_cache = cache
        grad = self.project.backward(grad, project_cache)
        grad = self.dropout.backward(grad, drop_cache)
        grad = self.prelu.backward(grad, prelu_cache)
        for index, (branch, branch_cache) in enumerate(zip(self.inception_ffs,
                                                          branch_caches)):
            branch.backward(grad[:, index * self.hidden:(index + 1) * self.hidden],
                            branch_cache)

    def state_dict(self):
        return {name: p.value.copy() for name, p in self._parameters}

    def load_state_dict(self, state):
        for name, parameter in self._parameters:
            parameter.value[:] = state[name]


def cross_entropy(logits, labels, denominator=None):
    """Mean cross entropy and its gradient; optional logical batch denominator."""
    shifted = logits - logits.max(axis=1, keepdims=True)
    exp = np.exp(shifted)
    totals = exp.sum(axis=1, keepdims=True)
    count = len(labels) if denominator is None else denominator
    rows = np.arange(len(labels))
    loss = np.sum(np.log(totals[:, 0]) - shifted[rows, labels]) / count
    gradient = exp / totals
    gradient[rows, labels] -= 1
    gradient /= np.float32(count)
    return float(loss), gradient


class Adam:
    """torch.optim.Adam defaults: lr=.001, betas=(.9,.999), eps=1e-8, wd=0."""
    def __init__(self, model, lr=0.001, beta1=0.9, beta2=0.999, eps=1e-8):
        self.parameters = model.named_parameters()
        self.lr, self.beta1, self.beta2, self.eps = lr, beta1, beta2, eps
        self.first = [np.zeros_like(p.value) for _, p in self.parameters]
        self.second = [np.zeros_like(p.value) for _, p in self.parameters]
        self.steps = 0

    def step(self):
        self.steps += 1
        correction1 = 1 - self.beta1 ** self.steps
        correction2 = 1 - self.beta2 ** self.steps
        for (_, parameter), first, second in zip(self.parameters, self.first,
                                                  self.second):
            first *= self.beta1
            first += np.float32(1 - self.beta1) * parameter.grad
            second *= self.beta2
            second += np.float32(1 - self.beta2) * parameter.grad ** 2
            denom = np.sqrt(second) / np.float32(np.sqrt(correction2)) + self.eps
            parameter.value -= np.float32(self.lr / correction1) * first / denom