Spaces:
				
			
			
	
			
			
					
		Running
		
	
	
	
			
			
	
	
	
	
		
		
					
		Running
		
	Upload models/transformer2d.py
Browse files- models/transformer2d.py +229 -0
    	
        models/transformer2d.py
    ADDED
    
    | @@ -0,0 +1,229 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            import torch
         | 
| 2 | 
            +
            import torch.nn.functional as F
         | 
| 3 | 
            +
            from torch import nn
         | 
| 4 | 
            +
            import copy, math
         | 
| 5 | 
            +
            from models.position_encoding import build_position_encoding
         | 
| 6 | 
            +
             | 
| 7 | 
            +
             | 
| 8 | 
            +
            class TransformerEncoder(nn.Module):
         | 
| 9 | 
            +
             | 
| 10 | 
            +
                def __init__(self, enc_layer, num_layers, use_dense_pos=False):
         | 
| 11 | 
            +
                    super().__init__()
         | 
| 12 | 
            +
                    self.layers = nn.ModuleList([copy.deepcopy(enc_layer) for i in range(num_layers)])
         | 
| 13 | 
            +
                    self.num_layers = num_layers
         | 
| 14 | 
            +
                    self.use_dense_pos = use_dense_pos
         | 
| 15 | 
            +
             | 
| 16 | 
            +
                def forward(self, src, pos, padding_mask=None):
         | 
| 17 | 
            +
                    if self.use_dense_pos:
         | 
| 18 | 
            +
                        ## pos encoding at each MH-Attention block (q,k)
         | 
| 19 | 
            +
                        output, pos_enc = src, pos
         | 
| 20 | 
            +
                        for layer in self.layers:
         | 
| 21 | 
            +
                            output, att_map = layer(output, pos_enc, padding_mask)
         | 
| 22 | 
            +
                    else:
         | 
| 23 | 
            +
                        ## pos encoding at input only (q,k,v)
         | 
| 24 | 
            +
                        output, pos_enc = src + pos, None
         | 
| 25 | 
            +
                        for layer in self.layers:
         | 
| 26 | 
            +
                            output, att_map = layer(output, pos_enc, padding_mask)
         | 
| 27 | 
            +
                    return output, att_map
         | 
| 28 | 
            +
             | 
| 29 | 
            +
             | 
| 30 | 
            +
            class EncoderLayer(nn.Module):
         | 
| 31 | 
            +
             | 
| 32 | 
            +
                def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu",
         | 
| 33 | 
            +
                            use_dense_pos=False):
         | 
| 34 | 
            +
                    super().__init__()
         | 
| 35 | 
            +
                    self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
         | 
| 36 | 
            +
                    # Implementation of Feedforward model
         | 
| 37 | 
            +
                    self.linear1 = nn.Linear(d_model, dim_feedforward)
         | 
| 38 | 
            +
                    self.dropout = nn.Dropout(dropout)
         | 
| 39 | 
            +
                    self.linear2 = nn.Linear(dim_feedforward, d_model)
         | 
| 40 | 
            +
             | 
| 41 | 
            +
                    self.norm1 = nn.LayerNorm(d_model)
         | 
| 42 | 
            +
                    self.norm2 = nn.LayerNorm(d_model)
         | 
| 43 | 
            +
                    self.dropout1 = nn.Dropout(dropout)
         | 
| 44 | 
            +
                    self.dropout2 = nn.Dropout(dropout)
         | 
| 45 | 
            +
             | 
| 46 | 
            +
                    self.activation = _get_activation_fn(activation)
         | 
| 47 | 
            +
             | 
| 48 | 
            +
                def with_pos_embed(self, tensor, pos):
         | 
| 49 | 
            +
                    return tensor if pos is None else tensor + pos
         | 
| 50 | 
            +
             | 
| 51 | 
            +
                def forward(self, src, pos, padding_mask):
         | 
| 52 | 
            +
                    q = k = self.with_pos_embed(src, pos)
         | 
| 53 | 
            +
                    src2, attn = self.self_attn(q, k, value=src, key_padding_mask=padding_mask)
         | 
| 54 | 
            +
                    src = src + self.dropout1(src2)
         | 
| 55 | 
            +
                    src = self.norm1(src)
         | 
| 56 | 
            +
                    src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
         | 
| 57 | 
            +
                    src = src + self.dropout2(src2)
         | 
| 58 | 
            +
                    src = self.norm2(src)
         | 
| 59 | 
            +
                    return src, attn
         | 
| 60 | 
            +
             | 
| 61 | 
            +
             | 
| 62 | 
            +
            class TransformerDecoder(nn.Module):
         | 
| 63 | 
            +
             | 
| 64 | 
            +
                def __init__(self, dec_layer, num_layers, use_dense_pos=False, return_intermediate=False):
         | 
| 65 | 
            +
                    super().__init__()
         | 
| 66 | 
            +
                    self.layers = nn.ModuleList([copy.deepcopy(dec_layer) for i in range(num_layers)])
         | 
| 67 | 
            +
                    self.num_layers = num_layers
         | 
| 68 | 
            +
                    self.use_dense_pos = use_dense_pos
         | 
| 69 | 
            +
                    self.return_intermediate = return_intermediate
         | 
| 70 | 
            +
             | 
| 71 | 
            +
                def forward(self, tgt, tgt_pos, memory, memory_pos, 
         | 
| 72 | 
            +
                            tgt_padding_mask, src_padding_mask, tgt_attn_mask=None):
         | 
| 73 | 
            +
                    intermediate = []
         | 
| 74 | 
            +
                    if self.use_dense_pos:
         | 
| 75 | 
            +
                        ## pos encoding at each MH-Attention block (q,k)
         | 
| 76 | 
            +
                        output = tgt
         | 
| 77 | 
            +
                        tgt_pos_enc, memory_pos_enc = tgt_pos, memory_pos
         | 
| 78 | 
            +
                        for layer in self.layers:
         | 
| 79 | 
            +
                            output, att_map = layer(output, tgt_pos_enc, memory, memory_pos_enc, 
         | 
| 80 | 
            +
                                            tgt_padding_mask, src_padding_mask, tgt_attn_mask)
         | 
| 81 | 
            +
                            if self.return_intermediate:
         | 
| 82 | 
            +
                                intermediate.append(output)
         | 
| 83 | 
            +
                    else:
         | 
| 84 | 
            +
                        ## pos encoding at input only (q,k,v)
         | 
| 85 | 
            +
                        output = tgt + tgt_pos
         | 
| 86 | 
            +
                        tgt_pos_enc, memory_pos_enc = None, None
         | 
| 87 | 
            +
                        for layer in self.layers:
         | 
| 88 | 
            +
                            output, att_map = layer(output, tgt_pos_enc, memory, memory_pos_enc, 
         | 
| 89 | 
            +
                                            tgt_padding_mask, src_padding_mask, tgt_attn_mask)
         | 
| 90 | 
            +
                            if self.return_intermediate:
         | 
| 91 | 
            +
                                intermediate.append(output)
         | 
| 92 | 
            +
             | 
| 93 | 
            +
                    if self.return_intermediate:
         | 
| 94 | 
            +
                        return torch.stack(intermediate)
         | 
| 95 | 
            +
                    return output, att_map
         | 
| 96 | 
            +
             | 
| 97 | 
            +
             | 
| 98 | 
            +
            class DecoderLayer(nn.Module):
         | 
| 99 | 
            +
             | 
| 100 | 
            +
                def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu",
         | 
| 101 | 
            +
                             use_dense_pos=False):
         | 
| 102 | 
            +
                    super().__init__()
         | 
| 103 | 
            +
                    self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
         | 
| 104 | 
            +
                    self.corr_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
         | 
| 105 | 
            +
                    # Implementation of Feedforward model
         | 
| 106 | 
            +
                    self.linear1 = nn.Linear(d_model, dim_feedforward)
         | 
| 107 | 
            +
                    self.dropout = nn.Dropout(dropout)
         | 
| 108 | 
            +
                    self.linear2 = nn.Linear(dim_feedforward, d_model)
         | 
| 109 | 
            +
             | 
| 110 | 
            +
                    self.norm1 = nn.LayerNorm(d_model)
         | 
| 111 | 
            +
                    self.norm2 = nn.LayerNorm(d_model)
         | 
| 112 | 
            +
                    self.norm3 = nn.LayerNorm(d_model)
         | 
| 113 | 
            +
                    self.dropout1 = nn.Dropout(dropout)
         | 
| 114 | 
            +
                    self.dropout2 = nn.Dropout(dropout)
         | 
| 115 | 
            +
                    self.dropout3 = nn.Dropout(dropout)
         | 
| 116 | 
            +
             | 
| 117 | 
            +
                    self.activation = _get_activation_fn(activation)
         | 
| 118 | 
            +
             | 
| 119 | 
            +
                def with_pos_embed(self, tensor, pos):
         | 
| 120 | 
            +
                    return tensor if pos is None else tensor + pos
         | 
| 121 | 
            +
             | 
| 122 | 
            +
                def forward(self, tgt, tgt_pos, memory, memory_pos, 
         | 
| 123 | 
            +
                            tgt_padding_mask, memory_padding_mask, tgt_attn_mask):
         | 
| 124 | 
            +
                    q = k = self.with_pos_embed(tgt, tgt_pos)
         | 
| 125 | 
            +
                    tgt2, attn = self.self_attn(q, k, value=tgt, key_padding_mask=tgt_padding_mask,
         | 
| 126 | 
            +
                                                attn_mask=tgt_attn_mask)
         | 
| 127 | 
            +
                    tgt = tgt + self.dropout1(tgt2)
         | 
| 128 | 
            +
                    tgt = self.norm1(tgt)
         | 
| 129 | 
            +
                    tgt2, attn = self.corr_attn(query=self.with_pos_embed(tgt, tgt_pos),
         | 
| 130 | 
            +
                                                key=self.with_pos_embed(memory, memory_pos),
         | 
| 131 | 
            +
                                                value=memory, key_padding_mask=memory_padding_mask)
         | 
| 132 | 
            +
                    tgt = tgt + self.dropout2(tgt2)
         | 
| 133 | 
            +
                    tgt = self.norm2(tgt)
         | 
| 134 | 
            +
                    tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
         | 
| 135 | 
            +
                    tgt = tgt + self.dropout3(tgt2)
         | 
| 136 | 
            +
                    tgt = self.norm3(tgt)
         | 
| 137 | 
            +
                    return tgt, attn
         | 
| 138 | 
            +
             | 
| 139 | 
            +
             | 
| 140 | 
            +
            def _get_activation_fn(activation):
         | 
| 141 | 
            +
                """Return an activation function given a string"""
         | 
| 142 | 
            +
                if activation == "relu":
         | 
| 143 | 
            +
                    return F.relu
         | 
| 144 | 
            +
                if activation == "gelu":
         | 
| 145 | 
            +
                    return F.gelu
         | 
| 146 | 
            +
                if activation == "glu":
         | 
| 147 | 
            +
                    return F.glu
         | 
| 148 | 
            +
                raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
         | 
| 149 | 
            +
             | 
| 150 | 
            +
             | 
| 151 | 
            +
             | 
| 152 | 
            +
            #-----------------------------------------------------------------------------------
         | 
| 153 | 
            +
            '''
         | 
| 154 | 
            +
            copy from the implementatoin of "attention-is-all-you-need-pytorch-master" by Yu-Hsiang Huang
         | 
| 155 | 
            +
            '''
         | 
| 156 | 
            +
             | 
| 157 | 
            +
            class MultiHeadAttention(nn.Module):
         | 
| 158 | 
            +
                ''' Multi-Head Attention module '''
         | 
| 159 | 
            +
             | 
| 160 | 
            +
                def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
         | 
| 161 | 
            +
                    super().__init__()
         | 
| 162 | 
            +
             | 
| 163 | 
            +
                    self.n_head = n_head
         | 
| 164 | 
            +
                    self.d_k = d_k
         | 
| 165 | 
            +
                    self.d_v = d_v
         | 
| 166 | 
            +
             | 
| 167 | 
            +
                    self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)
         | 
| 168 | 
            +
                    self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)
         | 
| 169 | 
            +
                    self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)
         | 
| 170 | 
            +
                    self.fc = nn.Linear(n_head * d_v, d_model, bias=False)
         | 
| 171 | 
            +
             | 
| 172 | 
            +
                    self.attention = ScaledDotProductAttention(temperature=d_k ** 0.5)
         | 
| 173 | 
            +
             | 
| 174 | 
            +
                    self.dropout = nn.Dropout(dropout)
         | 
| 175 | 
            +
                    self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
         | 
| 176 | 
            +
             | 
| 177 | 
            +
             | 
| 178 | 
            +
                def forward(self, q, k, v, mask=None):
         | 
| 179 | 
            +
             | 
| 180 | 
            +
                    d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
         | 
| 181 | 
            +
                    sz_b, len_q, len_k, len_v = q.size(0), q.size(1), k.size(1), v.size(1)
         | 
| 182 | 
            +
             | 
| 183 | 
            +
                    residual = q
         | 
| 184 | 
            +
             | 
| 185 | 
            +
                    # Pass through the pre-attention projection: b x lq x (n*dv)
         | 
| 186 | 
            +
                    # Separate different heads: b x lq x n x dv
         | 
| 187 | 
            +
                    q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
         | 
| 188 | 
            +
                    k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
         | 
| 189 | 
            +
                    v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
         | 
| 190 | 
            +
             | 
| 191 | 
            +
                    # Transpose for attention dot product: b x n x lq x dv
         | 
| 192 | 
            +
                    q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
         | 
| 193 | 
            +
             | 
| 194 | 
            +
                    if mask is not None:
         | 
| 195 | 
            +
                        mask = mask.unsqueeze(1)   # For head axis broadcasting.
         | 
| 196 | 
            +
             | 
| 197 | 
            +
                    q, attn = self.attention(q, k, v, mask=mask)
         | 
| 198 | 
            +
             | 
| 199 | 
            +
                    # Transpose to move the head dimension back: b x lq x n x dv
         | 
| 200 | 
            +
                    # Combine the last two dimensions to concatenate all the heads together: b x lq x (n*dv)
         | 
| 201 | 
            +
                    q = q.transpose(1, 2).contiguous().view(sz_b, len_q, -1)
         | 
| 202 | 
            +
                    q = self.dropout(self.fc(q))
         | 
| 203 | 
            +
                    q += residual
         | 
| 204 | 
            +
             | 
| 205 | 
            +
                    q = self.layer_norm(q)
         | 
| 206 | 
            +
             | 
| 207 | 
            +
                    return q, attn
         | 
| 208 | 
            +
             | 
| 209 | 
            +
             | 
| 210 | 
            +
             | 
| 211 | 
            +
            class ScaledDotProductAttention(nn.Module):
         | 
| 212 | 
            +
                ''' Scaled Dot-Product Attention '''
         | 
| 213 | 
            +
             | 
| 214 | 
            +
                def __init__(self, temperature, attn_dropout=0.1):
         | 
| 215 | 
            +
                    super().__init__()
         | 
| 216 | 
            +
                    self.temperature = temperature
         | 
| 217 | 
            +
                    self.dropout = nn.Dropout(attn_dropout)
         | 
| 218 | 
            +
             | 
| 219 | 
            +
                def forward(self, q, k, v, mask=None):
         | 
| 220 | 
            +
             | 
| 221 | 
            +
                    attn = torch.matmul(q / self.temperature, k.transpose(2, 3))
         | 
| 222 | 
            +
             | 
| 223 | 
            +
                    if mask is not None:
         | 
| 224 | 
            +
                        attn = attn.masked_fill(mask == 0, -1e9)
         | 
| 225 | 
            +
             | 
| 226 | 
            +
                    attn = self.dropout(F.softmax(attn, dim=-1))
         | 
| 227 | 
            +
                    output = torch.matmul(attn, v)
         | 
| 228 | 
            +
             | 
| 229 | 
            +
                    return output, attn
         | 
 
			
