File size: 2,366 Bytes
8246b15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Exact duplication-tiling ("widening") and its inverse for plain MLP policies. numpy only, no training.

widen:  hidden layer i (not input, not output) gets k copies of every unit.
        rows of W_i tiled k times; columns of W_{i+1} tiled k times and divided by k.
shrink: merge groups of identical units: average rows of W_i, sum columns of W_{i+1}.
        Exact only when the groups really are identical copies (i.e. on a widened net).
Run `python widen_mlp_numpy.py` for a self-test (random MLP, tanh and swish).
"""
import numpy as np

def widen(Ws, bs, k):
    """Ws[i]: (out_i, in_i). Returns widened lists. Input size and output size are unchanged."""
    n = len(Ws); W2, b2 = [], []
    for i, (W, b) in enumerate(zip(Ws, bs)):
        if i < n - 1: W = np.tile(W, (k, 1)); b = np.tile(b, k)      # rows tiled (units copied)
        if i > 0: W = np.tile(W, (1, k)) / k                         # columns tiled and divided by k
        W2.append(W); b2.append(b)
    return W2, b2

def shrink(Ws, bs, k):
    """Inverse of widen for a net that was widened by k (copies are consecutive blocks of the tiling)."""
    n = len(Ws); W2, b2 = [], []
    for i, (W, b) in enumerate(zip(Ws, bs)):
        if i < n - 1: h = W.shape[0] // k; W = W.reshape(k, h, -1).mean(0); b = b.reshape(k, h).mean(0)
        if i > 0: h = W.shape[1] // k; W = W.reshape(W.shape[0], k, h).sum(1)
        W2.append(W); b2.append(b)
    return W2, b2

def forward(Ws, bs, x, act):
    for i, (W, b) in enumerate(zip(Ws, bs)):
        x = x @ W.T + b
        if i < len(Ws) - 1: x = act(x)
    return x

ACTS = {'tanh': np.tanh, 'swish': lambda z: z / (1 + np.exp(-z))}

if __name__ == '__main__':
    rng = np.random.default_rng(0)
    dims = [8, 64, 64, 4]
    Ws = [rng.normal(0, 0.3, (dims[i+1], dims[i])) for i in range(3)]; bs = [rng.normal(0, 0.1, dims[i+1]) for i in range(3)]
    X = rng.normal(size=(20000, 8))
    for name, act in ACTS.items():
        for k in (2, 3, 4):
            Wk, bk = widen(Ws, bs, k)
            gap = np.abs(forward(Ws, bs, X, act) - forward(Wk, bk, X, act)).max()
            Wr, br = shrink(Wk, bk, k)
            rt = max(np.abs(a - b).max() for a, b in zip(Ws + bs, Wr + br))
            print(f'{name} k={k}: params {sum(w.size for w in Ws)} -> {sum(w.size for w in Wk)}, max output gap {gap:.2e}, round-trip max weight error {rt:.2e}')