table_att_head.py 10.8 KB
Newer Older
M
MissPenguin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import paddle
import paddle.nn as nn
文幕地方's avatar
文幕地方 已提交
21
from paddle import ParamAttr
M
MissPenguin 已提交
22 23 24
import paddle.nn.functional as F
import numpy as np

文幕地方's avatar
文幕地方 已提交
25 26
from .rec_att_head import AttentionGRUCell

M
refine  
MissPenguin 已提交
27

文幕地方's avatar
文幕地方 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40
def get_para_bias_attr(l2_decay, k):
    if l2_decay > 0:
        regularizer = paddle.regularizer.L2Decay(l2_decay)
        stdv = 1.0 / math.sqrt(k * 1.0)
        initializer = nn.initializer.Uniform(-stdv, stdv)
    else:
        regularizer = None
        initializer = None
    weight_attr = ParamAttr(regularizer=regularizer, initializer=initializer)
    bias_attr = ParamAttr(regularizer=regularizer, initializer=initializer)
    return [weight_attr, bias_attr]


M
MissPenguin 已提交
41
class TableAttentionHead(nn.Layer):
42 43 44 45 46
    def __init__(self,
                 in_channels,
                 hidden_size,
                 loc_type,
                 in_max_len=488,
文幕地方's avatar
文幕地方 已提交
47
                 max_text_length=800,
文幕地方's avatar
fix bug  
文幕地方 已提交
48
                 out_channels=30,
文幕地方's avatar
文幕地方 已提交
49
                 loc_reg_num=4,
50
                 **kwargs):
M
MissPenguin 已提交
51 52 53
        super(TableAttentionHead, self).__init__()
        self.input_size = in_channels[-1]
        self.hidden_size = hidden_size
文幕地方's avatar
fix bug  
文幕地方 已提交
54
        self.out_channels = out_channels
55
        self.max_text_length = max_text_length
M
MissPenguin 已提交
56 57

        self.structure_attention_cell = AttentionGRUCell(
文幕地方's avatar
fix bug  
文幕地方 已提交
58 59
            self.input_size, hidden_size, self.out_channels, use_gru=False)
        self.structure_generator = nn.Linear(hidden_size, self.out_channels)
M
MissPenguin 已提交
60 61
        self.loc_type = loc_type
        self.in_max_len = in_max_len
62

M
MissPenguin 已提交
63 64 65 66
        if self.loc_type == 1:
            self.loc_generator = nn.Linear(hidden_size, 4)
        else:
            if self.in_max_len == 640:
文幕地方's avatar
文幕地方 已提交
67
                self.loc_fea_trans = nn.Linear(400, self.max_text_length + 1)
M
MissPenguin 已提交
68
            elif self.in_max_len == 800:
文幕地方's avatar
文幕地方 已提交
69
                self.loc_fea_trans = nn.Linear(625, self.max_text_length + 1)
M
MissPenguin 已提交
70
            else:
文幕地方's avatar
文幕地方 已提交
71
                self.loc_fea_trans = nn.Linear(256, self.max_text_length + 1)
文幕地方's avatar
fix bug  
文幕地方 已提交
72
            self.loc_generator = nn.Linear(self.input_size + hidden_size,
文幕地方's avatar
文幕地方 已提交
73
                                           loc_reg_num)
74

M
MissPenguin 已提交
75 76 77 78
    def _char_to_onehot(self, input_char, onehot_dim):
        input_ont_hot = F.one_hot(input_char, onehot_dim)
        return input_ont_hot

M
refine  
MissPenguin 已提交
79
    def forward(self, inputs, targets=None):
M
MissPenguin 已提交
80 81 82 83 84 85
        # if and else branch are both needed when you want to assign a variable
        # if you modify the var in just one branch, then the modification will not work.
        fea = inputs[-1]
        if len(fea.shape) == 3:
            pass
        else:
86
            last_shape = int(np.prod(fea.shape[2:]))  # gry added
M
MissPenguin 已提交
87 88 89
            fea = paddle.reshape(fea, [fea.shape[0], fea.shape[1], last_shape])
            fea = fea.transpose([0, 2, 1])  # (NTC)(batch, width, channels)
        batch_size = fea.shape[0]
90

M
MissPenguin 已提交
91 92
        hidden = paddle.zeros((batch_size, self.hidden_size))
        output_hiddens = []
M
refine  
MissPenguin 已提交
93
        if self.training and targets is not None:
M
MissPenguin 已提交
94
            structure = targets[0]
文幕地方's avatar
文幕地方 已提交
95
            for i in range(self.max_text_length + 1):
M
MissPenguin 已提交
96
                elem_onehots = self._char_to_onehot(
文幕地方's avatar
fix bug  
文幕地方 已提交
97
                    structure[:, i], onehot_dim=self.out_channels)
M
MissPenguin 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
                (outputs, hidden), alpha = self.structure_attention_cell(
                    hidden, fea, elem_onehots)
                output_hiddens.append(paddle.unsqueeze(outputs, axis=1))
            output = paddle.concat(output_hiddens, axis=1)
            structure_probs = self.structure_generator(output)
            if self.loc_type == 1:
                loc_preds = self.loc_generator(output)
                loc_preds = F.sigmoid(loc_preds)
            else:
                loc_fea = fea.transpose([0, 2, 1])
                loc_fea = self.loc_fea_trans(loc_fea)
                loc_fea = loc_fea.transpose([0, 2, 1])
                loc_concat = paddle.concat([output, loc_fea], axis=2)
                loc_preds = self.loc_generator(loc_concat)
                loc_preds = F.sigmoid(loc_preds)
        else:
            temp_elem = paddle.zeros(shape=[batch_size], dtype="int32")
            structure_probs = None
            loc_preds = None
            elem_onehots = None
            outputs = None
            alpha = None
文幕地方's avatar
文幕地方 已提交
120
            max_text_length = paddle.to_tensor(self.max_text_length)
M
MissPenguin 已提交
121
            i = 0
文幕地方's avatar
文幕地方 已提交
122
            while i < max_text_length + 1:
M
MissPenguin 已提交
123
                elem_onehots = self._char_to_onehot(
文幕地方's avatar
fix bug  
文幕地方 已提交
124
                    temp_elem, onehot_dim=self.out_channels)
M
MissPenguin 已提交
125 126 127 128 129 130
                (outputs, hidden), alpha = self.structure_attention_cell(
                    hidden, fea, elem_onehots)
                output_hiddens.append(paddle.unsqueeze(outputs, axis=1))
                structure_probs_step = self.structure_generator(outputs)
                temp_elem = structure_probs_step.argmax(axis=1, dtype="int32")
                i += 1
131

M
MissPenguin 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144
            output = paddle.concat(output_hiddens, axis=1)
            structure_probs = self.structure_generator(output)
            structure_probs = F.softmax(structure_probs)
            if self.loc_type == 1:
                loc_preds = self.loc_generator(output)
                loc_preds = F.sigmoid(loc_preds)
            else:
                loc_fea = fea.transpose([0, 2, 1])
                loc_fea = self.loc_fea_trans(loc_fea)
                loc_fea = loc_fea.transpose([0, 2, 1])
                loc_concat = paddle.concat([output, loc_fea], axis=2)
                loc_preds = self.loc_generator(loc_concat)
                loc_preds = F.sigmoid(loc_preds)
145
        return {'structure_probs': structure_probs, 'loc_preds': loc_preds}
文幕地方's avatar
文幕地方 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168


class SLAHead(nn.Layer):
    def __init__(self,
                 in_channels,
                 hidden_size,
                 out_channels=30,
                 max_text_length=500,
                 loc_reg_num=4,
                 fc_decay=0.0,
                 **kwargs):
        """
        @param in_channels: input shape
        @param hidden_size: hidden_size for RNN and Embedding
        @param out_channels: num_classes to rec
        @param max_text_length: max text pred
        """
        super().__init__()
        in_channels = in_channels[-1]
        self.hidden_size = hidden_size
        self.max_text_length = max_text_length
        self.emb = self._char_to_onehot
        self.num_embeddings = out_channels
文幕地方's avatar
文幕地方 已提交
169
        self.loc_reg_num = loc_reg_num
文幕地方's avatar
文幕地方 已提交
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

        # structure
        self.structure_attention_cell = AttentionGRUCell(
            in_channels, hidden_size, self.num_embeddings)
        weight_attr, bias_attr = get_para_bias_attr(
            l2_decay=fc_decay, k=hidden_size)
        weight_attr1_1, bias_attr1_1 = get_para_bias_attr(
            l2_decay=fc_decay, k=hidden_size)
        weight_attr1_2, bias_attr1_2 = get_para_bias_attr(
            l2_decay=fc_decay, k=hidden_size)
        self.structure_generator = nn.Sequential(
            nn.Linear(
                self.hidden_size,
                self.hidden_size,
                weight_attr=weight_attr1_2,
                bias_attr=bias_attr1_2),
            nn.Linear(
                hidden_size,
                out_channels,
                weight_attr=weight_attr,
                bias_attr=bias_attr))
        # loc
        weight_attr1, bias_attr1 = get_para_bias_attr(
            l2_decay=fc_decay, k=self.hidden_size)
        weight_attr2, bias_attr2 = get_para_bias_attr(
            l2_decay=fc_decay, k=self.hidden_size)
        self.loc_generator = nn.Sequential(
            nn.Linear(
                self.hidden_size,
                self.hidden_size,
                weight_attr=weight_attr1,
                bias_attr=bias_attr1),
            nn.Linear(
                self.hidden_size,
                loc_reg_num,
                weight_attr=weight_attr2,
                bias_attr=bias_attr2),
            nn.Sigmoid())

    def forward(self, inputs, targets=None):
        fea = inputs[-1]
        batch_size = fea.shape[0]
        # reshape
        fea = paddle.reshape(fea, [fea.shape[0], fea.shape[1], -1])
        fea = fea.transpose([0, 2, 1])  # (NTC)(batch, width, channels)

        hidden = paddle.zeros((batch_size, self.hidden_size))
文幕地方's avatar
文幕地方 已提交
217 218
        structure_preds = paddle.zeros((batch_size, self.max_text_length + 1, self.num_embeddings))
        loc_preds = paddle.zeros((batch_size, self.max_text_length + 1, self.loc_reg_num))
219 220
        structure_preds.stop_gradient = True
        loc_preds.stop_gradient = True
文幕地方's avatar
文幕地方 已提交
221 222 223 224 225
        if self.training and targets is not None:
            structure = targets[0]
            for i in range(self.max_text_length + 1):
                hidden, structure_step, loc_step = self._decode(structure[:, i],
                                                                fea, hidden)
文幕地方's avatar
文幕地方 已提交
226 227
                structure_preds[:, i, :] = structure_step
                loc_preds[:, i, :] = loc_step
228
        else:
文幕地方's avatar
文幕地方 已提交
229 230 231 232 233 234 235 236
            pre_chars = paddle.zeros(shape=[batch_size], dtype="int32")
            max_text_length = paddle.to_tensor(self.max_text_length)
            # for export
            loc_step, structure_step = None, None
            for i in range(max_text_length + 1):
                hidden, structure_step, loc_step = self._decode(pre_chars, fea,
                                                                hidden)
                pre_chars = structure_step.argmax(axis=1, dtype="int32")
文幕地方's avatar
文幕地方 已提交
237 238
                structure_preds[:, i, :] = structure_step
                loc_preds[:, i, :] = loc_step
文幕地方's avatar
文幕地方 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        if not self.training:
            structure_preds = F.softmax(structure_preds)
        return {'structure_probs': structure_preds, 'loc_preds': loc_preds}

    def _decode(self, pre_chars, features, hidden):
        """
        Predict table label and coordinates for each step
        @param pre_chars: Table label in previous step
        @param features:
        @param hidden: hidden status in previous step
        @return:
        """
        emb_feature = self.emb(pre_chars)
        # output shape is b * self.hidden_size
        (output, hidden), alpha = self.structure_attention_cell(
            hidden, features, emb_feature)

        # structure
        structure_step = self.structure_generator(output)
        # loc
        loc_step = self.loc_generator(output)
        return hidden, structure_step, loc_step

    def _char_to_onehot(self, input_char):
        input_ont_hot = F.one_hot(input_char, self.num_embeddings)
        return input_ont_hot