vqa_layoutlm.py 5.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 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 os
from paddle import nn

from paddlenlp.transformers import LayoutXLMModel, LayoutXLMForTokenClassification, LayoutXLMForRelationExtraction
from paddlenlp.transformers import LayoutLMModel, LayoutLMForTokenClassification
文幕地方's avatar
文幕地方 已提交
24
from paddlenlp.transformers import LayoutLMv2Model, LayoutLMv2ForTokenClassification, LayoutLMv2ForRelationExtraction
25 26 27

__all__ = ["LayoutXLMForSer", 'LayoutLMForSer']

文幕地方's avatar
文幕地方 已提交
28 29
pretrained_model_dict = {
    LayoutXLMModel: 'layoutxlm-base-uncased',
文幕地方's avatar
文幕地方 已提交
30 31
    LayoutLMModel: 'layoutlm-base-uncased',
    LayoutLMv2Model: 'layoutlmv2-base-uncased'
文幕地方's avatar
文幕地方 已提交
32 33
}

34 35 36 37 38 39

class NLPBaseModel(nn.Layer):
    def __init__(self,
                 base_model_class,
                 model_class,
                 type='ser',
文幕地方's avatar
文幕地方 已提交
40
                 pretrained=True,
41 42 43 44 45
                 checkpoints=None,
                 **kwargs):
        super(NLPBaseModel, self).__init__()
        if checkpoints is not None:
            self.model = model_class.from_pretrained(checkpoints)
46 47
        elif isinstance(pretrained, (str, )) and os.path.exists(pretrained):
            self.model = model_class.from_pretrained(pretrained)
48
        else:
文幕地方's avatar
文幕地方 已提交
49
            pretrained_model_name = pretrained_model_dict[base_model_class]
50
            if pretrained is True:
文幕地方's avatar
文幕地方 已提交
51 52 53 54 55 56
                base_model = base_model_class.from_pretrained(
                    pretrained_model_name)
            else:
                base_model = base_model_class(
                    **base_model_class.pretrained_init_configuration[
                        pretrained_model_name])
57 58 59 60 61 62 63 64
            if type == 'ser':
                self.model = model_class(
                    base_model, num_classes=kwargs['num_classes'], dropout=None)
            else:
                self.model = model_class(base_model, dropout=None)
        self.out_channels = 1


文幕地方's avatar
文幕地方 已提交
65
class LayoutLMForSer(NLPBaseModel):
文幕地方's avatar
文幕地方 已提交
66
    def __init__(self, num_classes, pretrained=True, checkpoints=None,
67
                 **kwargs):
文幕地方's avatar
文幕地方 已提交
68 69 70 71 72 73 74 75 76 77 78
        super(LayoutLMForSer, self).__init__(
            LayoutLMModel,
            LayoutLMForTokenClassification,
            'ser',
            pretrained,
            checkpoints,
            num_classes=num_classes)

    def forward(self, x):
        x = self.model(
            input_ids=x[0],
79 80 81
            bbox=x[1],
            attention_mask=x[2],
            token_type_ids=x[3],
文幕地方's avatar
文幕地方 已提交
82 83 84 85 86 87 88 89 90 91 92
            position_ids=None,
            output_hidden_states=False)
        return x


class LayoutLMv2ForSer(NLPBaseModel):
    def __init__(self, num_classes, pretrained=True, checkpoints=None,
                 **kwargs):
        super(LayoutLMv2ForSer, self).__init__(
            LayoutLMv2Model,
            LayoutLMv2ForTokenClassification,
93
            'ser',
文幕地方's avatar
文幕地方 已提交
94
            pretrained,
95 96 97 98 99 100
            checkpoints,
            num_classes=num_classes)

    def forward(self, x):
        x = self.model(
            input_ids=x[0],
101 102 103 104
            bbox=x[1],
            attention_mask=x[2],
            token_type_ids=x[3],
            image=x[4],
105 106 107
            position_ids=None,
            head_mask=None,
            labels=None)
108 109
        if not self.training:
            return x
110 111 112
        return x[0]


文幕地方's avatar
文幕地方 已提交
113
class LayoutXLMForSer(NLPBaseModel):
文幕地方's avatar
文幕地方 已提交
114
    def __init__(self, num_classes, pretrained=True, checkpoints=None,
115
                 **kwargs):
文幕地方's avatar
文幕地方 已提交
116 117 118
        super(LayoutXLMForSer, self).__init__(
            LayoutXLMModel,
            LayoutXLMForTokenClassification,
119
            'ser',
文幕地方's avatar
文幕地方 已提交
120
            pretrained,
121 122 123 124 125
            checkpoints,
            num_classes=num_classes)

    def forward(self, x):
        x = self.model(
文幕地方's avatar
文幕地方 已提交
126 127 128 129 130 131 132 133
            input_ids=x[0],
            bbox=x[1],
            attention_mask=x[2],
            token_type_ids=x[3],
            image=x[4],
            position_ids=None,
            head_mask=None,
            labels=None)
134 135
        if not self.training:
            return x
文幕地方's avatar
文幕地方 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148
        return x[0]


class LayoutLMv2ForRe(NLPBaseModel):
    def __init__(self, pretrained=True, checkpoints=None, **kwargs):
        super(LayoutLMv2ForRe, self).__init__(LayoutLMv2Model,
                                              LayoutLMv2ForRelationExtraction,
                                              're', pretrained, checkpoints)

    def forward(self, x):
        x = self.model(
            input_ids=x[0],
            bbox=x[1],
149 150 151
            attention_mask=x[2],
            token_type_ids=x[3],
            image=x[4],
文幕地方's avatar
文幕地方 已提交
152 153
            position_ids=None,
            head_mask=None,
154
            labels=None,
文幕地方's avatar
文幕地方 已提交
155 156
            entities=x[5],
            relations=x[6])
157 158 159 160
        return x


class LayoutXLMForRe(NLPBaseModel):
文幕地方's avatar
文幕地方 已提交
161 162 163 164
    def __init__(self, pretrained=True, checkpoints=None, **kwargs):
        super(LayoutXLMForRe, self).__init__(LayoutXLMModel,
                                             LayoutXLMForRelationExtraction,
                                             're', pretrained, checkpoints)
165 166 167 168 169

    def forward(self, x):
        x = self.model(
            input_ids=x[0],
            bbox=x[1],
170 171 172
            attention_mask=x[2],
            token_type_ids=x[3],
            image=x[4],
173 174
            position_ids=None,
            head_mask=None,
175
            labels=None,
176 177 178
            entities=x[5],
            relations=x[6])
        return x