File size: 8,855 Bytes
29f689c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import math

import torch
import torch.nn as nn
import torch.nn.functional as F


class SAREncoder(nn.Module):

    def __init__(self,
                 enc_bi_rnn=False,
                 enc_drop_rnn=0.1,
                 in_channels=512,
                 d_enc=512,
                 **kwargs):
        super().__init__()

        # LSTM Encoder
        if enc_bi_rnn:
            bidirectional = True
        else:
            bidirectional = False

        hidden_size = d_enc

        self.rnn_encoder = nn.LSTM(input_size=in_channels,
                                   hidden_size=hidden_size,
                                   num_layers=2,
                                   dropout=enc_drop_rnn,
                                   bidirectional=bidirectional,
                                   batch_first=True)

        # global feature transformation
        encoder_rnn_out_size = hidden_size * (int(enc_bi_rnn) + 1)
        self.linear = nn.Linear(encoder_rnn_out_size, encoder_rnn_out_size)

    def forward(self, feat):

        h_feat = feat.shape[2]
        feat_v = F.max_pool2d(feat,
                              kernel_size=(h_feat, 1),
                              stride=1,
                              padding=0)
        feat_v = feat_v.squeeze(2)
        feat_v = feat_v.permute(0, 2, 1).contiguous()  # bsz * W * C

        holistic_feat = self.rnn_encoder(feat_v)[0]  # bsz * T * hidden_size

        valid_hf = holistic_feat[:, -1, :]  # bsz * hidden_size

        holistic_feat = self.linear(valid_hf)  # bsz * C

        return holistic_feat


class SARDecoder(nn.Module):

    def __init__(self,
                 in_channels,
                 out_channels,
                 max_len=25,
                 enc_bi_rnn=False,
                 enc_drop_rnn=0.1,
                 dec_bi_rnn=False,
                 dec_drop_rnn=0.0,
                 pred_dropout=0.1,
                 pred_concat=True,
                 mask=True,
                 use_lstm=True,
                 **kwargs):
        super(SARDecoder, self).__init__()

        self.num_classes = out_channels
        self.start_idx = out_channels - 2
        self.padding_idx = out_channels - 1
        self.end_idx = 0
        self.max_seq_len = max_len + 1
        self.pred_concat = pred_concat
        self.mask = mask
        enc_dim = in_channels
        d = in_channels
        embedding_dim = in_channels
        dec_dim = in_channels
        self.use_lstm = use_lstm
        if use_lstm:
            # encoder module
            self.encoder = SAREncoder(enc_bi_rnn=enc_bi_rnn,
                                      enc_drop_rnn=enc_drop_rnn,
                                      in_channels=in_channels,
                                      d_enc=enc_dim)

        # decoder module

        # 2D attention layer
        self.conv1x1_1 = nn.Linear(dec_dim, d)
        self.conv3x3_1 = nn.Conv2d(in_channels,
                                   d,
                                   kernel_size=3,
                                   stride=1,
                                   padding=1)
        self.conv1x1_2 = nn.Linear(d, 1)

        # Decoder input embedding
        self.embedding = nn.Embedding(self.num_classes,
                                      embedding_dim,
                                      padding_idx=self.padding_idx)

        self.rnndecoder = nn.LSTM(input_size=embedding_dim,
                                  hidden_size=dec_dim,
                                  num_layers=2,
                                  dropout=dec_drop_rnn,
                                  bidirectional=dec_bi_rnn,
                                  batch_first=True)

        # Prediction layer
        self.pred_dropout = nn.Dropout(pred_dropout)
        if pred_concat:
            fc_in_channel = in_channels + in_channels + dec_dim
        else:
            fc_in_channel = in_channels
        self.prediction = nn.Linear(fc_in_channel, self.num_classes)
        self.softmax = nn.Softmax(dim=-1)

    def _2d_attation(self, feat, tokens, data, training):

        Hidden_state = self.rnndecoder(tokens)[0]
        attn_query = self.conv1x1_1(Hidden_state)
        bsz, seq_len, _ = attn_query.size()
        attn_query = attn_query.unsqueeze(-1).unsqueeze(-1)
        # bsz * seq_len+1 * attn_size * 1 * 1
        attn_key = self.conv3x3_1(feat).unsqueeze(1)
        # bsz * 1 * attn_size * h * w

        attn_weight = torch.tanh(torch.add(attn_key, attn_query, alpha=1))
        attn_weight = attn_weight.permute(0, 1, 3, 4, 2).contiguous()
        attn_weight = self.conv1x1_2(attn_weight)

        _, T, h, w, c = attn_weight.size()

        if self.mask:
            valid_ratios = data[-1]
            # cal mask of attention weight
            attn_mask = torch.zeros_like(attn_weight)
            for i, valid_ratio in enumerate(valid_ratios):
                valid_width = min(w, math.ceil(w * valid_ratio))
                attn_mask[i, :, :, valid_width:, :] = 1
            attn_weight = attn_weight.masked_fill(attn_mask.bool(),
                                                  float('-inf'))

        attn_weight = attn_weight.view(bsz, T, -1)
        attn_weight = F.softmax(attn_weight, dim=-1)
        attn_weight = attn_weight.view(bsz, T, h, w,
                                       c).permute(0, 1, 4, 2, 3).contiguous()
        # bsz, T, 1, h, w
        # bsz, 1, f_c ,h, w
        attn_feat = torch.sum(torch.mul(feat.unsqueeze(1), attn_weight),
                              (3, 4),
                              keepdim=False)
        return [Hidden_state, attn_feat]

    def forward_train(self, feat, holistic_feat, data):

        max_len = data[1].max()
        label = data[0][:, :1 + max_len]  # label
        label_embedding = self.embedding(label)
        holistic_feat = holistic_feat.unsqueeze(1)
        tokens = torch.cat((holistic_feat, label_embedding), dim=1)

        Hidden_state, attn_feat = self._2d_attation(feat,
                                                    tokens,
                                                    data,
                                                    training=self.training)

        bsz, seq_len, f_c = Hidden_state.size()
        # linear transformation
        if self.pred_concat:
            f_c = holistic_feat.size(-1)
            holistic_feat = holistic_feat.expand(bsz, seq_len, f_c)
            preds = self.prediction(
                torch.cat((Hidden_state, attn_feat, holistic_feat), 2))
        else:
            preds = self.prediction(attn_feat)
        # bsz * (seq_len + 1) * num_classes
        preds = self.pred_dropout(preds)
        return preds[:, 1:, :]

    def forward_test(self, feat, holistic_feat, data=None):
        bsz = feat.shape[0]
        seq_len = self.max_seq_len
        holistic_feat = holistic_feat.unsqueeze(1)
        tokens = torch.full((bsz, ),
                            self.start_idx,
                            device=feat.device,
                            dtype=torch.long)
        outputs = []
        tokens = self.embedding(tokens)
        tokens = tokens.unsqueeze(1).expand(-1, seq_len, -1)
        tokens = torch.cat((holistic_feat, tokens), dim=1)
        for i in range(1, seq_len + 1):
            Hidden_state, attn_feat = self._2d_attation(feat,
                                                        tokens,
                                                        data=data,
                                                        training=self.training)
            if self.pred_concat:
                f_c = holistic_feat.size(-1)
                holistic_feat = holistic_feat.expand(bsz, seq_len + 1, f_c)
                preds = self.prediction(
                    torch.cat((Hidden_state, attn_feat, holistic_feat), 2))
            else:
                preds = self.prediction(attn_feat)
            # bsz * (seq_len + 1) * num_classes
            char_output = preds[:, i, :]
            char_output = F.softmax(char_output, -1)
            outputs.append(char_output)
            _, max_idx = torch.max(char_output, dim=1, keepdim=False)
            char_embedding = self.embedding(max_idx)
            if (i < seq_len):
                tokens[:, i + 1, :] = char_embedding
                if (tokens == self.end_idx).any(dim=-1).all():
                    break
        outputs = torch.stack(outputs, 1)

        return outputs

    def forward(self, feat, data=None):
        if self.use_lstm:
            holistic_feat = self.encoder(feat)  # bsz c
        else:
            holistic_feat = F.adaptive_avg_pool2d(feat, (1, 1)).squeeze()

        if self.training:
            preds = self.forward_train(feat, holistic_feat, data=data)
        else:
            preds = self.forward_test(feat, holistic_feat, data=data)
            # (bsz, seq_len, num_classes)
        return preds