zzqsb's picture
Release the REE tasks and dataset card.
7f50cd1
Raw History Blame Contribute Delete
8.52 kB
"""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