A two-layer MLP. This uses a fully-connected layer to encode the input, then applies a non-linearity, then uses another fully-connected layer to decode back to the initial dimension, and finally applies (optional) dropout. :param in_features: size of input layer :param hidden_f
| 57 | |
| 58 | |
| 59 | class MLP(nn.Module): |
| 60 | """A two-layer MLP. |
| 61 | |
| 62 | This uses a fully-connected layer to encode the input, then applies a non-linearity, |
| 63 | then uses another fully-connected layer to decode back to the initial dimension, and |
| 64 | finally applies (optional) dropout. |
| 65 | |
| 66 | :param in_features: size of input layer |
| 67 | :param hidden_features: size of hidden layer |
| 68 | :param activation: activation function to use after the expansion; default: GELU |
| 69 | :param dropout: amount of dropout |
| 70 | :param bias: whether to use bias in the layers |
| 71 | """ |
| 72 | |
| 73 | in_features: int |
| 74 | hidden_features: int |
| 75 | activation: Callable |
| 76 | dropout: float |
| 77 | bias: bool |
| 78 | |
| 79 | def __init__( |
| 80 | self, |
| 81 | in_features: int, |
| 82 | hidden_features: int, |
| 83 | activation: Optional[Callable] = None, |
| 84 | dropout: float = 0.0, |
| 85 | bias: bool = True, |
| 86 | ): |
| 87 | super().__init__() |
| 88 | |
| 89 | self.in_features = in_features |
| 90 | self.hidden_features = hidden_features |
| 91 | self.activation = activation if activation is not None else nn.GELU() |
| 92 | self.dropout = dropout |
| 93 | self.bias = bias |
| 94 | |
| 95 | self.encoder = nn.Linear(in_features, hidden_features, bias=bias) |
| 96 | self.decoder = nn.Linear(hidden_features, in_features, bias=bias) |
| 97 | self.dropout_layer = nn.Dropout(dropout) if dropout > 0 else None |
| 98 | |
| 99 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 100 | x = self.encoder(x) |
| 101 | x = self.activation(x) |
| 102 | x = self.decoder(x) |
| 103 | if self.dropout_layer is not None: |
| 104 | x = self.dropout_layer(x) |
| 105 | return x |
| 106 | |
| 107 | |
| 108 | class SelfAttention(nn.Module): |