|
| 1 | +"""Credit: mostly based on Ilya's excellent implementation here: https://github.com/ikostrikov/pytorch-flows""" |
| 2 | +import numpy as np |
| 3 | +import torch |
| 4 | +import torch.nn as nn |
| 5 | +from torch.nn import functional as F |
| 6 | + |
| 7 | + |
| 8 | +class InverseAutoregressiveFlow(nn.Module): |
| 9 | + """Inverse Autoregressive Flows with LSTM-type update. One block. |
| 10 | + |
| 11 | + Eq 11-14 of https://arxiv.org/abs/1606.04934 |
| 12 | + """ |
| 13 | + def __init__(self, num_input, num_hidden, num_context): |
| 14 | + super().__init__() |
| 15 | + self.made = MADE(num_input=num_input, num_output=num_input * 2, |
| 16 | + num_hidden=num_hidden, num_context=num_context) |
| 17 | + # init such that sigmoid(s) is close to 1 for stability |
| 18 | + self.sigmoid_arg_bias = nn.Parameter(torch.ones(num_input) * 2) |
| 19 | + self.sigmoid = nn.Sigmoid() |
| 20 | + self.log_sigmoid = nn.LogSigmoid() |
| 21 | + |
| 22 | + def forward(self, input, context=None): |
| 23 | + m, s = torch.chunk(self.made(input, context), chunks=2, dim=-1) |
| 24 | + s = s + self.sigmoid_arg_bias |
| 25 | + sigmoid = self.sigmoid(s) |
| 26 | + z = sigmoid * input + (1 - sigmoid) * m |
| 27 | + return z, -self.log_sigmoid(s) |
| 28 | + |
| 29 | + |
| 30 | +class FlowSequential(nn.Sequential): |
| 31 | + """Forward pass.""" |
| 32 | + |
| 33 | + def forward(self, input, context=None): |
| 34 | + total_log_prob = torch.zeros_like(input, device=input.device) |
| 35 | + for block in self._modules.values(): |
| 36 | + input, log_prob = block(input, context) |
| 37 | + total_log_prob += log_prob |
| 38 | + return input, total_log_prob |
| 39 | + |
| 40 | + |
| 41 | +class MaskedLinear(nn.Module): |
| 42 | + """Linear layer with some input-output connections masked.""" |
| 43 | + def __init__(self, in_features, out_features, mask, context_features=None, bias=True): |
| 44 | + super().__init__() |
| 45 | + self.linear = nn.Linear(in_features, out_features, bias) |
| 46 | + self.register_buffer("mask", mask) |
| 47 | + if context_features is not None: |
| 48 | + self.cond_linear = nn.Linear(context_features, out_features, bias=False) |
| 49 | + |
| 50 | + def forward(self, input, context=None): |
| 51 | + output = F.linear(input, self.mask * self.linear.weight, self.linear.bias) |
| 52 | + if context is None: |
| 53 | + return output |
| 54 | + else: |
| 55 | + return output + self.cond_linear(context) |
| 56 | + |
| 57 | + |
| 58 | +class MADE(nn.Module): |
| 59 | + """Implements MADE: Masked Autoencoder for Distribution Estimation. |
| 60 | +
|
| 61 | + Follows https://arxiv.org/abs/1502.03509 |
| 62 | +
|
| 63 | + This is used to build MAF: Masked Autoregressive Flow (https://arxiv.org/abs/1705.07057). |
| 64 | + """ |
| 65 | + def __init__(self, num_input, num_output, num_hidden, num_context): |
| 66 | + super().__init__() |
| 67 | + # m corresponds to m(k), the maximum degree of a node in the MADE paper |
| 68 | + self._m = [] |
| 69 | + self._masks = [] |
| 70 | + self._build_masks(num_input, num_output, num_hidden, num_layers=3) |
| 71 | + self._check_masks() |
| 72 | + modules = [] |
| 73 | + self.input_context_net = MaskedLinear(num_input, num_hidden, self._masks[0], num_context) |
| 74 | + modules.append(nn.ReLU()) |
| 75 | + modules.append(MaskedLinear(num_hidden, num_hidden, self._masks[1], context_features=None)) |
| 76 | + modules.append(nn.ReLU()) |
| 77 | + modules.append(MaskedLinear(num_hidden, num_output, self._masks[2], context_features=None)) |
| 78 | + self.net = nn.Sequential(*modules) |
| 79 | + |
| 80 | + def _build_masks(self, num_input, num_output, num_hidden, num_layers): |
| 81 | + """Build the masks according to Eq 12 and 13 in the MADE paper.""" |
| 82 | + rng = np.random.RandomState(0) |
| 83 | + # assign input units a number between 1 and D |
| 84 | + self._m.append(np.arange(1, num_input + 1)) |
| 85 | + for i in range(1, num_layers + 1): |
| 86 | + # randomly assign maximum number of input nodes to connect to |
| 87 | + if i == num_layers: |
| 88 | + # assign output layer units a number between 1 and D |
| 89 | + m = np.arange(1, num_input + 1) |
| 90 | + assert num_output % num_input == 0, "num_output must be multiple of num_input" |
| 91 | + self._m.append(np.hstack([m for _ in range(num_output // num_input)])) |
| 92 | + else: |
| 93 | + # assign hidden layer units a number between 1 and D-1 |
| 94 | + self._m.append(rng.randint(1, num_input, size=num_hidden)) |
| 95 | + #self._m.append(np.arange(1, num_hidden + 1) % (num_input - 1) + 1) |
| 96 | + if i == num_layers: |
| 97 | + mask = self._m[i][None, :] > self._m[i - 1][:, None] |
| 98 | + else: |
| 99 | + # input to hidden & hidden to hidden |
| 100 | + mask = self._m[i][None, :] >= self._m[i - 1][:, None] |
| 101 | + # need to transpose for torch linear layer, shape (num_output, num_input) |
| 102 | + self._masks.append(torch.from_numpy(mask.astype(np.float32).T)) |
| 103 | + |
| 104 | + def _check_masks(self): |
| 105 | + """Check that the connectivity matrix between layers is lower triangular.""" |
| 106 | + # (num_input, num_hidden) |
| 107 | + prev = self._masks[0].t() |
| 108 | + for i in range(1, len(self._masks)): |
| 109 | + # num_hidden is second axis |
| 110 | + prev = prev @ self._masks[i].t() |
| 111 | + final = prev.numpy() |
| 112 | + num_input = self._masks[0].shape[1] |
| 113 | + num_output = self._masks[-1].shape[0] |
| 114 | + assert final.shape == (num_input, num_output) |
| 115 | + if num_output == num_input: |
| 116 | + assert np.triu(final).all() == 0 |
| 117 | + else: |
| 118 | + for submat in np.split(final, |
| 119 | + indices_or_sections=num_output // num_input, |
| 120 | + axis=1): |
| 121 | + assert np.triu(submat).all() == 0 |
| 122 | + |
| 123 | + def forward(self, input, context=None): |
| 124 | + # first hidden layer receives input and context |
| 125 | + hidden = self.input_context_net(input, context) |
| 126 | + # rest of the network is conditioned on both input and context |
| 127 | + return self.net(hidden) |
| 128 | + |
| 129 | + |
| 130 | + |
| 131 | +class Reverse(nn.Module): |
| 132 | + """ An implementation of a reversing layer from |
| 133 | + Density estimation using Real NVP |
| 134 | + (https://arxiv.org/abs/1605.08803). |
| 135 | +
|
| 136 | + From https://github.com/ikostrikov/pytorch-flows/blob/master/main.py |
| 137 | + """ |
| 138 | + |
| 139 | + def __init__(self, num_input): |
| 140 | + super(Reverse, self).__init__() |
| 141 | + self.perm = np.array(np.arange(0, num_input)[::-1]) |
| 142 | + self.inv_perm = np.argsort(self.perm) |
| 143 | + |
| 144 | + def forward(self, inputs, context=None, mode='forward'): |
| 145 | + if mode == "forward": |
| 146 | + return inputs[:, :, self.perm], torch.zeros_like(inputs, device=inputs.device) |
| 147 | + elif mode == "inverse": |
| 148 | + return inputs[:, :, self.inv_perm], torch.zeros_like(inputs, device=inputs.device) |
| 149 | + else: |
| 150 | + raise ValueError("Mode must be one of {forward, inverse}.") |
| 151 | + |
| 152 | + |
0 commit comments