| 76 | return out |
| 77 | |
| 78 | class AttentionWithBias(nn.Module): |
| 79 | def __init__(self, d_in=256, d_bias=128, n_head=8, d_hidden=32): |
| 80 | super(AttentionWithBias, self).__init__() |
| 81 | self.norm_in = nn.LayerNorm(d_in) |
| 82 | self.norm_bias = nn.LayerNorm(d_bias) |
| 83 | # |
| 84 | self.to_q = nn.Linear(d_in, n_head*d_hidden, bias=False) |
| 85 | self.to_k = nn.Linear(d_in, n_head*d_hidden, bias=False) |
| 86 | self.to_v = nn.Linear(d_in, n_head*d_hidden, bias=False) |
| 87 | self.to_b = nn.Linear(d_bias, n_head, bias=False) |
| 88 | self.to_g = nn.Linear(d_in, n_head*d_hidden) |
| 89 | self.to_out = nn.Linear(n_head*d_hidden, d_in) |
| 90 | |
| 91 | self.scaling = 1/math.sqrt(d_hidden) |
| 92 | self.h = n_head |
| 93 | self.dim = d_hidden |
| 94 | |
| 95 | self.reset_parameter() |
| 96 | |
| 97 | def reset_parameter(self): |
| 98 | # query/key/value projection: Glorot uniform / Xavier uniform |
| 99 | nn.init.xavier_uniform_(self.to_q.weight) |
| 100 | nn.init.xavier_uniform_(self.to_k.weight) |
| 101 | nn.init.xavier_uniform_(self.to_v.weight) |
| 102 | |
| 103 | # bias: normal distribution |
| 104 | self.to_b = init_lecun_normal(self.to_b) |
| 105 | |
| 106 | # gating: zero weights, one biases (mostly open gate at the begining) |
| 107 | nn.init.zeros_(self.to_g.weight) |
| 108 | nn.init.ones_(self.to_g.bias) |
| 109 | |
| 110 | # to_out: right before residual connection: zero initialize -- to make it sure residual operation is same to the Identity at the begining |
| 111 | nn.init.zeros_(self.to_out.weight) |
| 112 | nn.init.zeros_(self.to_out.bias) |
| 113 | |
| 114 | def forward(self, x, bias): |
| 115 | B, L = x.shape[:2] |
| 116 | # |
| 117 | x = self.norm_in(x) |
| 118 | bias = self.norm_bias(bias) |
| 119 | # |
| 120 | query = self.to_q(x).reshape(B, L, self.h, self.dim) |
| 121 | key = self.to_k(x).reshape(B, L, self.h, self.dim) |
| 122 | value = self.to_v(x).reshape(B, L, self.h, self.dim) |
| 123 | bias = self.to_b(bias) # (B, L, L, h) |
| 124 | gate = torch.sigmoid(self.to_g(x)) |
| 125 | # |
| 126 | key = key * self.scaling |
| 127 | attn = einsum('bqhd,bkhd->bqkh', query, key) |
| 128 | attn = attn + bias |
| 129 | attn = F.softmax(attn, dim=-2) |
| 130 | # |
| 131 | out = einsum('bqkh,bkhd->bqhd', attn, value).reshape(B, L, -1) |
| 132 | out = gate * out |
| 133 | # |
| 134 | out = self.to_out(out) |
| 135 | return out |