codingutf8 2010 the microsoft research asia layoutlm team s 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 orglicenseslicense2 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 layoutlm model configuration from collections import ordereddict from typing import any list mapping optional from import pretrainedconfig pretrainedtokenizer from onnx import onnxconfig patchingspec from utils import tensortype istorchavailable logging logger logging getloggername layoutlmpretrainedconfigarchivemap microsoftlayoutlmbaseuncased https huggingface comicrosoftlayoutlmbaseuncasedresolvemainconfig json microsoftlayoutlmlargeuncased https huggingface comicrosoftlayoutlmlargeuncasedresolvemainconfig json class layoutlmconfigpretrainedconfig r this is the configuration class to store the configuration of a layoutlmmodel it is used to instantiate a layoutlm model according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the layoutlm microsoftlayoutlmbaseuncasedhttps huggingface comicrosoftlayoutlmbaseuncased architecture configuration objects inherit from bertconfig and can be used to control the model outputs read the documentation from bertconfig for more information args vocabsize int optional defaults to 30522 vocabulary size of the layoutlm model defines the different tokens that can be represented by the inputsids passed to the forward method of layoutlmmodel hiddensize int optional defaults to 768 dimensionality of the encoder layers and the pooler layer numhiddenlayers int optional defaults to 12 number of hidden layers in the transformer encoder numattentionheads int optional defaults to 12 number of attention heads for each attention layer in the transformer encoder intermediatesize int optional defaults to 3072 dimensionality of the intermediate i e feedforward layer in the transformer encoder hiddenact str or function optional defaults to gelu the nonlinear activation function function or string in the encoder and pooler if string gelu relu silu and gelunew are supported hiddendropoutprob float optional defaults to 0 1 the dropout probability for all fully connected layers in the embeddings encoder and pooler attentionprobsdropoutprob float optional defaults to 0 1 the dropout ratio for the attention probabilities maxpositionembeddings int optional defaults to 512 the maximum sequence length that this model might ever be used with typically set this to something large just in case e g 512 or 1024 or 2048 typevocabsize int optional defaults to 2 the vocabulary size of the tokentypeids passed into layoutlmmodel initializerrange float optional defaults to 0 02 the standard deviation of the truncatednormalinitializer for initializing all weight matrices layernormeps float optional defaults to 1e12 the epsilon used by the layer normalization layers padtokenid int optional defaults to 0 the value used to pad inputids positionembeddingtype str optional defaults to absolute type of position embedding choose one of absolute relativekey relativekeyquery for positional embeddings use absolute for more information on relativekey please refer to selfattention with relative position representations shaw et al https arxiv orgabs1803 02155 for more information on relativekeyquery please refer to method 4 in improve transformer models with better relative position embeddings huang et al https arxiv orgabs2009 13658 usecache bool optional defaults to true whether or not the model should return the last keyvalues attentions not used by all models only relevant if config isdecodertrue max2dpositionembeddings int optional defaults to 1024 the maximum value that the 2d position embedding might ever used typically set this to something large just in case e g 1024 examples python from transformers import layoutlmconfig layoutlmmodel initializing a layoutlm configuration configuration layoutlmconfig initializing a model with random weights from the configuration model layoutlmmodelconfiguration accessing the model configuration configuration model config modeltype layoutlm def init self vocabsize30522 hiddensize768 numhiddenlayers12 numattentionheads12 intermediatesize3072 hiddenactgelu hiddendropoutprob0 1 attentionprobsdropoutprob0 1 maxpositionembeddings512 typevocabsize2 initializerrange0 02 layernormeps1e12 padtokenid0 positionembeddingtypeabsolute usecachetrue max2dpositionembeddings1024 kwargs super initpadtokenidpadtokenid kwargs self vocabsize vocabsize self hiddensize hiddensize self numhiddenlayers numhiddenlayers self numattentionheads numattentionheads self hiddenact hiddenact self intermediatesize intermediatesize self hiddendropoutprob hiddendropoutprob self attentionprobsdropoutprob attentionprobsdropoutprob self maxpositionembeddings maxpositionembeddings self typevocabsize typevocabsize self initializerrange initializerrange self layernormeps layernormeps self positionembeddingtype positionembeddingtype self usecache usecache self max2dpositionembeddings max2dpositionembeddings class layoutlmonnxconfigonnxconfig def init self config pretrainedconfig task str default patchingspecs listpatchingspec none super initconfig tasktask patchingspecspatchingspecs self max2dpositions config max2dpositionembeddings 1 property def inputsself mappingstr mappingint str return ordereddict inputids 0 batch 1 sequence bbox 0 batch 1 sequence attentionmask 0 batch 1 sequence tokentypeids 0 batch 1 sequence def generatedummyinputs self tokenizer pretrainedtokenizer batchsize int 1 seqlength int 1 ispair bool false framework optionaltensortype none mappingstr any inputdict super generatedummyinputs tokenizer batchsizebatchsize seqlengthseqlength ispairispair frameworkframework generate a dummy bbox box 48 84 73 128 if not framework tensortype pytorch raise notimplementederrorexporting layoutlm to onnx is currently only supported for pytorch if not istorchavailable raise valueerrorcannot generate dummy inputs without pytorch installed import torch batchsize seqlength inputdictinputids shape inputdictbbox torch tensorbox seqlength tilebatchsize 1 1 return inputdict coding utf 8 2010 the microsoft research asia layoutlm team s 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 layoutlm model configuration this is the configuration class to store the configuration of a layoutlmmodel it is used to instantiate a layoutlm model according to the specified arguments defining the model architecture instantiating a configuration with the defaults will yield a similar configuration to that of the layoutlm microsoft layoutlm base uncased https huggingface co microsoft layoutlm base uncased architecture configuration objects inherit from bertconfig and can be used to control the model outputs read the documentation from bertconfig for more information args vocab_size int optional defaults to 30522 vocabulary size of the layoutlm model defines the different tokens that can be represented by the inputs_ids passed to the forward method of layoutlmmodel hidden_size int optional defaults to 768 dimensionality of the encoder layers and the pooler layer num_hidden_layers int optional defaults to 12 number of hidden layers in the transformer encoder num_attention_heads int optional defaults to 12 number of attention heads for each attention layer in the transformer encoder intermediate_size int optional defaults to 3072 dimensionality of the intermediate i e feed forward layer in the transformer encoder hidden_act str or function optional defaults to gelu the non linear activation function function or string in the encoder and pooler if string gelu relu silu and gelu_new are supported hidden_dropout_prob float optional defaults to 0 1 the dropout probability for all fully connected layers in the embeddings encoder and pooler attention_probs_dropout_prob float optional defaults to 0 1 the dropout ratio for the attention probabilities max_position_embeddings int optional defaults to 512 the maximum sequence length that this model might ever be used with typically set this to something large just in case e g 512 or 1024 or 2048 type_vocab_size int optional defaults to 2 the vocabulary size of the token_type_ids passed into layoutlmmodel initializer_range float optional defaults to 0 02 the standard deviation of the truncated_normal_initializer for initializing all weight matrices layer_norm_eps float optional defaults to 1e 12 the epsilon used by the layer normalization layers pad_token_id int optional defaults to 0 the value used to pad input_ids position_embedding_type str optional defaults to absolute type of position embedding choose one of absolute relative_key relative_key_query for positional embeddings use absolute for more information on relative_key please refer to self attention with relative position representations shaw et al https arxiv org abs 1803 02155 for more information on relative_key_query please refer to method 4 in improve transformer models with better relative position embeddings huang et al https arxiv org abs 2009 13658 use_cache bool optional defaults to true whether or not the model should return the last key values attentions not used by all models only relevant if config is_decoder true max_2d_position_embeddings int optional defaults to 1024 the maximum value that the 2d position embedding might ever used typically set this to something large just in case e g 1024 examples python from transformers import layoutlmconfig layoutlmmodel initializing a layoutlm configuration configuration layoutlmconfig initializing a model with random weights from the configuration model layoutlmmodel configuration accessing the model configuration configuration model config generate inputs to provide to the onnx exporter for the specific framework args tokenizer the tokenizer associated with this model configuration batch_size the batch size int to export the model for 1 means dynamic axis seq_length the sequence length int to export the model for 1 means dynamic axis is_pair indicate if the input is a pair sentence 1 sentence 2 framework the framework optional the tokenizer will generate tensor for returns mapping str tensor holding the kwargs to provide to the model s forward function generate a dummy bbox
from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PretrainedConfig, PreTrainedTokenizer
from ...onnx import OnnxConfig, PatchingSpec
from ...utils import TensorType, is_torch_available, logging


logger = logging.get_logger(__name__)

LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "microsoft/layoutlm-base-uncased": (
        "https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/config.json"
    ),
    "microsoft/layoutlm-large-uncased": (
        "https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/config.json"
    ),
}


class LayoutLMConfig(PretrainedConfig):
    r

    model_type = "layoutlm"

    def __init__(
        self,
        vocab_size=30522,
        hidden_size=768,
        num_hidden_layers=12,
        num_attention_heads=12,
        intermediate_size=3072,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=512,
        type_vocab_size=2,
        initializer_range=0.02,
        layer_norm_eps=1e-12,
        pad_token_id=0,
        position_embedding_type="absolute",
        use_cache=True,
        max_2d_position_embeddings=1024,
        **kwargs,
    ):
        super().__init__(pad_token_id=pad_token_id, **kwargs)
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.hidden_act = hidden_act
        self.intermediate_size = intermediate_size
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.max_position_embeddings = max_position_embeddings
        self.type_vocab_size = type_vocab_size
        self.initializer_range = initializer_range
        self.layer_norm_eps = layer_norm_eps
        self.position_embedding_type = position_embedding_type
        self.use_cache = use_cache
        self.max_2d_position_embeddings = max_2d_position_embeddings


class LayoutLMOnnxConfig(OnnxConfig):
    def __init__(
        self,
        config: PretrainedConfig,
        task: str = "default",
        patching_specs: List[PatchingSpec] = None,
    ):
        super().__init__(config, task=task, patching_specs=patching_specs)
        self.max_2d_positions = config.max_2d_position_embeddings - 1

    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        return OrderedDict(
            [
                ("input_ids", {0: "batch", 1: "sequence"}),
                ("bbox", {0: "batch", 1: "sequence"}),
                ("attention_mask", {0: "batch", 1: "sequence"}),
                ("token_type_ids", {0: "batch", 1: "sequence"}),
            ]
        )

    def generate_dummy_inputs(
        self,
        tokenizer: PreTrainedTokenizer,
        batch_size: int = -1,
        seq_length: int = -1,
        is_pair: bool = False,
        framework: Optional[TensorType] = None,
    ) -> Mapping[str, Any]:
        

        input_dict = super().generate_dummy_inputs(
            tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
        )

        
        box = [48, 84, 73, 128]

        if not framework == TensorType.PYTORCH:
            raise NotImplementedError("Exporting LayoutLM to ONNX is currently only supported for PyTorch.")

        if not is_torch_available():
            raise ValueError("Cannot generate dummy inputs without PyTorch installed.")
        import torch

        batch_size, seq_length = input_dict["input_ids"].shape
        input_dict["bbox"] = torch.tensor([*[box] * seq_length]).tile(batch_size, 1, 1)
        return input_dict