codingutf8 the huggingface inc team 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 table transformer model configuration from collections import ordereddict from typing import mapping from packaging import version from configurationutils import pretrainedconfig from onnx import onnxconfig from utils import logging from auto import configmapping logger logging getloggername tabletransformerpretrainedconfigarchivemap microsofttabletransformerdetection https huggingface comicrosofttabletransformerdetectionresolvemainconfig json class tabletransformerconfigpretrainedconfig r this is the configuration class to store the configuration of a tabletransformermodel it is used to instantiate a table transformer 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 table transformer microsofttabletransformerdetectionhttps huggingface comicrosofttabletransformerdetection architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args usetimmbackbone bool optional defaults to true whether or not to use the timm library for the backbone if set to false will use the autobackbone api backboneconfig pretrainedconfig or dict optional the configuration of the backbone model only used in case usetimmbackbone is set to false in which case it will default to resnetconfig numchannels int optional defaults to 3 the number of input channels numqueries int optional defaults to 100 number of object queries i e detection slots this is the maximal number of objects tabletransformermodel can detect in a single image for coco we recommend 100 queries dmodel int optional defaults to 256 dimension of the layers encoderlayers int optional defaults to 6 number of encoder layers decoderlayers int optional defaults to 6 number of decoder layers encoderattentionheads int optional defaults to 8 number of attention heads for each attention layer in the transformer encoder decoderattentionheads int optional defaults to 8 number of attention heads for each attention layer in the transformer decoder decoderffndim int optional defaults to 2048 dimension of the intermediate often named feedforward layer in decoder encoderffndim int optional defaults to 2048 dimension of the intermediate often named feedforward layer in decoder activationfunction str or function optional defaults to relu the nonlinear activation function function or string in the encoder and pooler if string gelu relu silu and gelunew are supported dropout float optional defaults to 0 1 the dropout probability for all fully connected layers in the embeddings encoder and pooler attentiondropout float optional defaults to 0 0 the dropout ratio for the attention probabilities activationdropout float optional defaults to 0 0 the dropout ratio for activations inside the fully connected layer initstd float optional defaults to 0 02 the standard deviation of the truncatednormalinitializer for initializing all weight matrices initxavierstd float optional defaults to 1 the scaling factor used for the xavier initialization gain in the hm attention map module encoderlayerdrop float optional defaults to 0 0 the layerdrop probability for the encoder see the layerdrop papersee https arxiv orgabs1909 11556 for more details decoderlayerdrop float optional defaults to 0 0 the layerdrop probability for the decoder see the layerdrop papersee https arxiv orgabs1909 11556 for more details auxiliaryloss bool optional defaults to false whether auxiliary decoding losses loss at each decoder layer are to be used positionembeddingtype str optional defaults to sine type of position embeddings to be used on top of the image features one of sine or learned backbone str optional defaults to resnet50 name of convolutional backbone to use in case usetimmbackbone true supports any convolutional backbone from the timm package for a list of all available models see this pagehttps rwightman github iopytorchimagemodelsloadapretrainedmodel usepretrainedbackbone bool optional defaults to true whether to use pretrained weights for the backbone only supported when usetimmbackbone true dilation bool optional defaults to false whether to replace stride with dilation in the last convolutional block dc5 only supported when usetimmbackbone true classcost float optional defaults to 1 relative weight of the classification error in the hungarian matching cost bboxcost float optional defaults to 5 relative weight of the l1 error of the bounding box coordinates in the hungarian matching cost gioucost float optional defaults to 2 relative weight of the generalized iou loss of the bounding box in the hungarian matching cost masklosscoefficient float optional defaults to 1 relative weight of the focal loss in the panoptic segmentation loss dicelosscoefficient float optional defaults to 1 relative weight of the dicef1 loss in the panoptic segmentation loss bboxlosscoefficient float optional defaults to 5 relative weight of the l1 bounding box loss in the object detection loss gioulosscoefficient float optional defaults to 2 relative weight of the generalized iou loss in the object detection loss eoscoefficient float optional defaults to 0 1 relative classification weight of the noobject class in the object detection loss examples python from transformers import tabletransformermodel tabletransformerconfig initializing a table transformer microsofttabletransformerdetection style configuration configuration tabletransformerconfig initializing a model from the microsofttabletransformerdetection style configuration model tabletransformermodelconfiguration accessing the model configuration configuration model config modeltype tabletransformer keystoignoreatinference pastkeyvalues attributemap hiddensize dmodel numattentionheads encoderattentionheads copied from transformers models detr configurationdetr detrconfig init def init self usetimmbackbonetrue backboneconfignone numchannels3 numqueries100 encoderlayers6 encoderffndim2048 encoderattentionheads8 decoderlayers6 decoderffndim2048 decoderattentionheads8 encoderlayerdrop0 0 decoderlayerdrop0 0 isencoderdecodertrue activationfunctionrelu dmodel256 dropout0 1 attentiondropout0 0 activationdropout0 0 initstd0 02 initxavierstd1 0 auxiliarylossfalse positionembeddingtypesine backboneresnet50 usepretrainedbackbonetrue dilationfalse classcost1 bboxcost5 gioucost2 masklosscoefficient1 dicelosscoefficient1 bboxlosscoefficient5 gioulosscoefficient2 eoscoefficient0 1 kwargs if backboneconfig is not none and usetimmbackbone raise valueerroryou can t specify both backboneconfig and usetimmbackbone if not usetimmbackbone if backboneconfig is none logger infobackboneconfig is none initializing the config with the default resnet backbone backboneconfig configmappingresnetoutfeaturesstage4 elif isinstancebackboneconfig dict backbonemodeltype backboneconfig getmodeltype configclass configmappingbackbonemodeltype backboneconfig configclass fromdictbackboneconfig set timm attributes to none dilation backbone usepretrainedbackbone none none none self usetimmbackbone usetimmbackbone self backboneconfig backboneconfig self numchannels numchannels self numqueries numqueries self dmodel dmodel self encoderffndim encoderffndim self encoderlayers encoderlayers self encoderattentionheads encoderattentionheads self decoderffndim decoderffndim self decoderlayers decoderlayers self decoderattentionheads decoderattentionheads self dropout dropout self attentiondropout attentiondropout self activationdropout activationdropout self activationfunction activationfunction self initstd initstd self initxavierstd initxavierstd self encoderlayerdrop encoderlayerdrop self decoderlayerdrop decoderlayerdrop self numhiddenlayers encoderlayers self auxiliaryloss auxiliaryloss self positionembeddingtype positionembeddingtype self backbone backbone self usepretrainedbackbone usepretrainedbackbone self dilation dilation hungarian matcher self classcost classcost self bboxcost bboxcost self gioucost gioucost loss coefficients self masklosscoefficient masklosscoefficient self dicelosscoefficient dicelosscoefficient self bboxlosscoefficient bboxlosscoefficient self gioulosscoefficient gioulosscoefficient self eoscoefficient eoscoefficient super initisencoderdecoderisencoderdecoder kwargs property def numattentionheadsself int return self encoderattentionheads property def hiddensizeself int return self dmodel copied from transformers models detr configurationdetr detronnxconfig class tabletransformeronnxconfigonnxconfig torchonnxminimumversion version parse1 11 property def inputsself mappingstr mappingint str return ordereddict pixelvalues 0 batch 1 numchannels 2 height 3 width pixelmask 0 batch property def atolforvalidationself float return 1e5 property def defaultonnxopsetself int return 12 coding utf 8 the huggingface inc team 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 table transformer model configuration this is the configuration class to store the configuration of a tabletransformermodel it is used to instantiate a table transformer 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 table transformer microsoft table transformer detection https huggingface co microsoft table transformer detection architecture configuration objects inherit from pretrainedconfig and can be used to control the model outputs read the documentation from pretrainedconfig for more information args use_timm_backbone bool optional defaults to true whether or not to use the timm library for the backbone if set to false will use the autobackbone api backbone_config pretrainedconfig or dict optional the configuration of the backbone model only used in case use_timm_backbone is set to false in which case it will default to resnetconfig num_channels int optional defaults to 3 the number of input channels num_queries int optional defaults to 100 number of object queries i e detection slots this is the maximal number of objects tabletransformermodel can detect in a single image for coco we recommend 100 queries d_model int optional defaults to 256 dimension of the layers encoder_layers int optional defaults to 6 number of encoder layers decoder_layers int optional defaults to 6 number of decoder layers encoder_attention_heads int optional defaults to 8 number of attention heads for each attention layer in the transformer encoder decoder_attention_heads int optional defaults to 8 number of attention heads for each attention layer in the transformer decoder decoder_ffn_dim int optional defaults to 2048 dimension of the intermediate often named feed forward layer in decoder encoder_ffn_dim int optional defaults to 2048 dimension of the intermediate often named feed forward layer in decoder activation_function str or function optional defaults to relu the non linear activation function function or string in the encoder and pooler if string gelu relu silu and gelu_new are supported dropout float optional defaults to 0 1 the dropout probability for all fully connected layers in the embeddings encoder and pooler attention_dropout float optional defaults to 0 0 the dropout ratio for the attention probabilities activation_dropout float optional defaults to 0 0 the dropout ratio for activations inside the fully connected layer init_std float optional defaults to 0 02 the standard deviation of the truncated_normal_initializer for initializing all weight matrices init_xavier_std float optional defaults to 1 the scaling factor used for the xavier initialization gain in the hm attention map module encoder_layerdrop float optional defaults to 0 0 the layerdrop probability for the encoder see the layerdrop paper see https arxiv org abs 1909 11556 for more details decoder_layerdrop float optional defaults to 0 0 the layerdrop probability for the decoder see the layerdrop paper see https arxiv org abs 1909 11556 for more details auxiliary_loss bool optional defaults to false whether auxiliary decoding losses loss at each decoder layer are to be used position_embedding_type str optional defaults to sine type of position embeddings to be used on top of the image features one of sine or learned backbone str optional defaults to resnet50 name of convolutional backbone to use in case use_timm_backbone true supports any convolutional backbone from the timm package for a list of all available models see this page https rwightman github io pytorch image models load a pretrained model use_pretrained_backbone bool optional defaults to true whether to use pretrained weights for the backbone only supported when use_timm_backbone true dilation bool optional defaults to false whether to replace stride with dilation in the last convolutional block dc5 only supported when use_timm_backbone true class_cost float optional defaults to 1 relative weight of the classification error in the hungarian matching cost bbox_cost float optional defaults to 5 relative weight of the l1 error of the bounding box coordinates in the hungarian matching cost giou_cost float optional defaults to 2 relative weight of the generalized iou loss of the bounding box in the hungarian matching cost mask_loss_coefficient float optional defaults to 1 relative weight of the focal loss in the panoptic segmentation loss dice_loss_coefficient float optional defaults to 1 relative weight of the dice f 1 loss in the panoptic segmentation loss bbox_loss_coefficient float optional defaults to 5 relative weight of the l1 bounding box loss in the object detection loss giou_loss_coefficient float optional defaults to 2 relative weight of the generalized iou loss in the object detection loss eos_coefficient float optional defaults to 0 1 relative classification weight of the no object class in the object detection loss examples python from transformers import tabletransformermodel tabletransformerconfig initializing a table transformer microsoft table transformer detection style configuration configuration tabletransformerconfig initializing a model from the microsoft table transformer detection style configuration model tabletransformermodel configuration accessing the model configuration configuration model config copied from transformers models detr configuration_detr detrconfig __init__ set timm attributes to none hungarian matcher loss coefficients copied from transformers models detr configuration_detr detronnxconfig
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


logger = logging.get_logger(__name__)

TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "microsoft/table-transformer-detection": (
        "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"
    ),
}


class TableTransformerConfig(PretrainedConfig):
    r

    model_type = "table-transformer"
    keys_to_ignore_at_inference = ["past_key_values"]
    attribute_map = {
        "hidden_size": "d_model",
        "num_attention_heads": "encoder_attention_heads",
    }

    
    def __init__(
        self,
        use_timm_backbone=True,
        backbone_config=None,
        num_channels=3,
        num_queries=100,
        encoder_layers=6,
        encoder_ffn_dim=2048,
        encoder_attention_heads=8,
        decoder_layers=6,
        decoder_ffn_dim=2048,
        decoder_attention_heads=8,
        encoder_layerdrop=0.0,
        decoder_layerdrop=0.0,
        is_encoder_decoder=True,
        activation_function="relu",
        d_model=256,
        dropout=0.1,
        attention_dropout=0.0,
        activation_dropout=0.0,
        init_std=0.02,
        init_xavier_std=1.0,
        auxiliary_loss=False,
        position_embedding_type="sine",
        backbone="resnet50",
        use_pretrained_backbone=True,
        dilation=False,
        class_cost=1,
        bbox_cost=5,
        giou_cost=2,
        mask_loss_coefficient=1,
        dice_loss_coefficient=1,
        bbox_loss_coefficient=5,
        giou_loss_coefficient=2,
        eos_coefficient=0.1,
        **kwargs,
    ):
        if backbone_config is not None and use_timm_backbone:
            raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`.")

        if not use_timm_backbone:
            if backbone_config is None:
                logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
                backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
            elif isinstance(backbone_config, dict):
                backbone_model_type = backbone_config.get("model_type")
                config_class = CONFIG_MAPPING[backbone_model_type]
                backbone_config = config_class.from_dict(backbone_config)
            
            dilation, backbone, use_pretrained_backbone = None, None, None

        self.use_timm_backbone = use_timm_backbone
        self.backbone_config = backbone_config
        self.num_channels = num_channels
        self.num_queries = num_queries
        self.d_model = d_model
        self.encoder_ffn_dim = encoder_ffn_dim
        self.encoder_layers = encoder_layers
        self.encoder_attention_heads = encoder_attention_heads
        self.decoder_ffn_dim = decoder_ffn_dim
        self.decoder_layers = decoder_layers
        self.decoder_attention_heads = decoder_attention_heads
        self.dropout = dropout
        self.attention_dropout = attention_dropout
        self.activation_dropout = activation_dropout
        self.activation_function = activation_function
        self.init_std = init_std
        self.init_xavier_std = init_xavier_std
        self.encoder_layerdrop = encoder_layerdrop
        self.decoder_layerdrop = decoder_layerdrop
        self.num_hidden_layers = encoder_layers
        self.auxiliary_loss = auxiliary_loss
        self.position_embedding_type = position_embedding_type
        self.backbone = backbone
        self.use_pretrained_backbone = use_pretrained_backbone
        self.dilation = dilation
        
        self.class_cost = class_cost
        self.bbox_cost = bbox_cost
        self.giou_cost = giou_cost
        
        self.mask_loss_coefficient = mask_loss_coefficient
        self.dice_loss_coefficient = dice_loss_coefficient
        self.bbox_loss_coefficient = bbox_loss_coefficient
        self.giou_loss_coefficient = giou_loss_coefficient
        self.eos_coefficient = eos_coefficient
        super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)

    @property
    def num_attention_heads(self) -> int:
        return self.encoder_attention_heads

    @property
    def hidden_size(self) -> int:
        return self.d_model



class TableTransformerOnnxConfig(OnnxConfig):
    torch_onnx_minimum_version = version.parse("1.11")

    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        return OrderedDict(
            [
                ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
                ("pixel_mask", {0: "batch"}),
            ]
        )

    @property
    def atol_for_validation(self) -> float:
        return 1e-5

    @property
    def default_onnx_opset(self) -> int:
        return 12