(self, hidden_states, encoder_states, cross_mask)
| 106 | return tensor.permute(0, 2, 1, 3) |
| 107 | |
| 108 | def forward(self, hidden_states, encoder_states, cross_mask): |
| 109 | # hidden_states: [b, s, h] |
| 110 | # ltor_mask: [1, 1, s, s] |
| 111 | |
| 112 | # Attention heads. [b, s, hp] |
| 113 | mixed_query_layer = self.query(hidden_states) |
| 114 | mixed_x_layer = self.key_value(encoder_states) |
| 115 | (mixed_key_layer, mixed_value_layer) = split_tensor_along_last_dim(mixed_x_layer, 2) |
| 116 | |
| 117 | # Reshape and transpose [b, np, s, hn] |
| 118 | query_layer = self._transpose_for_scores(mixed_query_layer) |
| 119 | key_layer = self._transpose_for_scores(mixed_key_layer) |
| 120 | value_layer = self._transpose_for_scores(mixed_value_layer) |
| 121 | # Raw attention scores. [b, np, s, s] |
| 122 | attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) |
| 123 | attention_scores = attention_scores / math.sqrt( |
| 124 | self.hidden_size_per_attention_head) |
| 125 | if cross_mask is not None: |
| 126 | # Apply the left to right attention mask. |
| 127 | attention_scores = torch.mul(attention_scores, cross_mask) - \ |
| 128 | 10000.0 * (1.0 - cross_mask) |
| 129 | |
| 130 | # Attention probabilities. [b, np, s, s] |
| 131 | attention_probs = torch.nn.Softmax(dim=-1)(attention_scores) |
| 132 | # This is actually dropping out entire tokens to attend to, which might |
| 133 | # seem a bit unusual, but is taken from the original Transformer paper. |
| 134 | with get_cuda_rng_tracker().fork(): |
| 135 | attention_probs = self.attention_dropout(attention_probs) |
| 136 | |
| 137 | # Context layer. |
| 138 | # [b, np, s, hn] |
| 139 | context_layer = torch.matmul(attention_probs, value_layer) |
| 140 | # [b, s, np, hn] |
| 141 | context_layer = context_layer.permute(0, 2, 1, 3).contiguous() |
| 142 | new_context_layer_shape = context_layer.size()[:-2] + \ |
| 143 | (self.hidden_size_per_partition,) |
| 144 | # [b, s, hp] |
| 145 | context_layer = context_layer.view(*new_context_layer_shape) |
| 146 | |
| 147 | # Output. [b, s, h] |
| 148 | output = self.dense(context_layer) |
| 149 | output = self.output_dropout(output) |
| 150 | |
| 151 | return output |
| 152 | |
| 153 | |
| 154 | class ParallelSelfAttention(torch.nn.Module): |
nothing calls this directly
no test coverage detected