





import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory

from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
    convert,
    ensure_valid_input,
    generate_identified_filename,
    infer_shapes,
    quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow

class 	UpperCamelCase__				:



     '''simple docstring'''

     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any]		,lowerCamelCase__		:					Tuple		,lowerCamelCase__		:					Dict		,lowerCamelCase__		:					Tuple )  ->	Dict:




           '''simple docstring'''


           return None

class 	UpperCamelCase__				:



     '''simple docstring'''

     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					Union[str, Any]		,lowerCamelCase__		:					str		,lowerCamelCase__		:					Any		,lowerCamelCase__		:					Dict )  ->	List[Any]:




           '''simple docstring'''


           return None

class 	UpperCamelCase__				(   unittest.TestCase     ):



     '''simple docstring'''

     __snake_case					:			Optional[Any]				=    [
         # (model_name, model_kwargs)
         ("bert-base-cased", {}),
         ("gpt2", {"use_cache": False}),  # We don't support exporting GPT2 past keys anymore
     ]






     @require_tf
     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Any:




           '''simple docstring'''


           for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
                 self._test_export(lowerCamelCase__		,"""tf"""		,12		,**lowerCamelCase__ )






     @require_torch
     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	Tuple:




           '''simple docstring'''


           for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
                 self._test_export(lowerCamelCase__		,"""pt"""		,12		,**lowerCamelCase__ )






     @require_torch
     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any] )  ->	Dict:




           '''simple docstring'''


           from transformers import BertModel

           SCREAMING_SNAKE_CASE	=		["""[UNK]""", """[SEP]""", """[CLS]""", """[PAD]""", """[MASK]""", """some""", """other""", """words"""]
           with NamedTemporaryFile(mode="""w+t""" ) as vocab_file:
                 vocab_file.write("""\n""".join(lowerCamelCase__ ) )
                 vocab_file.flush()
                 SCREAMING_SNAKE_CASE	=		BertTokenizerFast(vocab_file.name )

           with TemporaryDirectory() as bert_save_dir:
                 SCREAMING_SNAKE_CASE	=		BertModel(BertConfig(vocab_size=len(lowerCamelCase__ ) ) )
                 model.save_pretrained(lowerCamelCase__ )
                 self._test_export(lowerCamelCase__		,"""pt"""		,12		,lowerCamelCase__ )






     @require_tf
     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Any:




           '''simple docstring'''


           for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
                 SCREAMING_SNAKE_CASE	=		self._test_export(lowerCamelCase__		,"""tf"""		,12		,**lowerCamelCase__ )
                 SCREAMING_SNAKE_CASE	=		quantize(Path(lowerCamelCase__ ) )

                 # Ensure the actual quantized model is not bigger than the original one
                 if quantized_path.stat().st_size >= Path(lowerCamelCase__ ).stat().st_size:
                       self.fail("""Quantized model is bigger than initial ONNX model""" )






     @require_torch
     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any] )  ->	Tuple:




           '''simple docstring'''


           for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
                 SCREAMING_SNAKE_CASE	=		self._test_export(lowerCamelCase__		,"""pt"""		,12		,**lowerCamelCase__ )
                 SCREAMING_SNAKE_CASE	=		quantize(lowerCamelCase__ )

                 # Ensure the actual quantized model is not bigger than the original one
                 if quantized_path.stat().st_size >= Path(lowerCamelCase__ ).stat().st_size:
                       self.fail("""Quantized model is bigger than initial ONNX model""" )






     def        SCREAMING_SNAKE_CASE__						(							self		:					Dict		,lowerCamelCase__		:					str		,lowerCamelCase__		:					Dict		,lowerCamelCase__		:					Any		,lowerCamelCase__		:					Optional[Any]=None		,**lowerCamelCase__		:					Optional[Any] )  ->	List[Any]:




           '''simple docstring'''


           try:
                 # Compute path
                 with TemporaryDirectory() as tempdir:
                       SCREAMING_SNAKE_CASE	=		Path(lowerCamelCase__ ).joinpath("""model.onnx""" )

                 # Remove folder if exists
                 if path.parent.exists():
                       path.parent.rmdir()

                 # Export
                 convert(lowerCamelCase__		,lowerCamelCase__		,lowerCamelCase__		,lowerCamelCase__		,lowerCamelCase__		,**lowerCamelCase__ )

                 return path
           except Exception as e:
                 self.fail(lowerCamelCase__ )






     @require_torch
     @require_tokenizers
     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any] )  ->	Dict:




           '''simple docstring'''


           from transformers import BertModel

           SCREAMING_SNAKE_CASE	=		BertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random""" ) )
           SCREAMING_SNAKE_CASE	=		BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random""" )
           self._test_infer_dynamic_axis(lowerCamelCase__		,lowerCamelCase__		,"""pt""" )






     @require_tf
     @require_tokenizers
     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	str:




           '''simple docstring'''


           from transformers import TFBertModel

           SCREAMING_SNAKE_CASE	=		TFBertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random""" ) )
           SCREAMING_SNAKE_CASE	=		BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random""" )
           self._test_infer_dynamic_axis(lowerCamelCase__		,lowerCamelCase__		,"""tf""" )






     def        SCREAMING_SNAKE_CASE__						(							self		:					Dict		,lowerCamelCase__		:					Dict		,lowerCamelCase__		:					List[str]		,lowerCamelCase__		:					Union[str, Any] )  ->	List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		FeatureExtractionPipeline(lowerCamelCase__		,lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		["""input_ids""", """token_type_ids""", """attention_mask""", """output_0""", """output_1"""]
           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		infer_shapes(lowerCamelCase__		,lowerCamelCase__ )

           # Assert all variables are present
           self.assertEqual(len(lowerCamelCase__ )		,len(lowerCamelCase__ ) )
           self.assertTrue(all(var_name in shapes for var_name in variable_names ) )
           self.assertSequenceEqual(variable_names[:3]		,lowerCamelCase__ )
           self.assertSequenceEqual(variable_names[3:]		,lowerCamelCase__ )

           # Assert inputs are {0: batch, 1: sequence}
           for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
                 self.assertDictEqual(shapes[var_name]		,{0: """batch""", 1: """sequence"""} )

           # Assert outputs are {0: batch, 1: sequence} and {0: batch}
           self.assertDictEqual(shapes["""output_0"""]		,{0: """batch""", 1: """sequence"""} )
           self.assertDictEqual(shapes["""output_1"""]		,{0: """batch"""} )






     def        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	str:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		["""input_ids""", """attention_mask""", """token_type_ids"""]
           SCREAMING_SNAKE_CASE	=		{"""input_ids""": [1, 2, 3, 4], """attention_mask""": [0, 0, 0, 0], """token_type_ids""": [1, 1, 1, 1]}
           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		ensure_valid_input(FuncContiguousArgs()		,lowerCamelCase__		,lowerCamelCase__ )

           # Should have exactly the same number of args (all are valid)
           self.assertEqual(len(lowerCamelCase__ )		,3 )

           # Should have exactly the same input names
           self.assertEqual(set(lowerCamelCase__ )		,set(lowerCamelCase__ ) )

           # Parameter should be reordered according to their respective place in the function:
           # (input_ids, token_type_ids, attention_mask)
           self.assertEqual(lowerCamelCase__		,(tokens["""input_ids"""], tokens["""token_type_ids"""], tokens["""attention_mask"""]) )

           # Generated args are interleaved with another args (for instance parameter "past" in GPT2)
           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		ensure_valid_input(FuncNonContiguousArgs()		,lowerCamelCase__		,lowerCamelCase__ )

           # Should have exactly the one arg (all before the one not provided "some_other_args")
           self.assertEqual(len(lowerCamelCase__ )		,1 )
           self.assertEqual(len(lowerCamelCase__ )		,1 )

           # Should have only "input_ids"
           self.assertEqual(inputs_args[0]		,tokens["""input_ids"""] )
           self.assertEqual(ordered_input_names[0]		,"""input_ids""" )






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Union[str, Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		generate_identified_filename(Path("""/home/something/my_fake_model.onnx""" )		,"""-test""" )
           self.assertEqual("""/home/something/my_fake_model-test.onnx"""		,generated.as_posix() )









import copy

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


SCREAMING_SNAKE_CASE_		     = logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_		     = {
    """ut/deta""": """https://huggingface.co/ut/deta/resolve/main/config.json""",
}

class 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     __snake_case					:			str				=    "deta"
     __snake_case					:			int				=    {
         "hidden_size": "d_model",
         "num_attention_heads": "encoder_attention_heads",
     }






     def __init__(							self		:					List[Any]		,lowerCamelCase__		:					Any=None		,lowerCamelCase__		:					Optional[int]=900		,lowerCamelCase__		:					Optional[Any]=2048		,lowerCamelCase__		:					Optional[Any]=6		,lowerCamelCase__		:					Dict=2048		,lowerCamelCase__		:					Optional[int]=8		,lowerCamelCase__		:					List[str]=6		,lowerCamelCase__		:					Union[str, Any]=1024		,lowerCamelCase__		:					str=8		,lowerCamelCase__		:					Union[str, Any]=0.0		,lowerCamelCase__		:					Dict=True		,lowerCamelCase__		:					Dict="relu"		,lowerCamelCase__		:					int=256		,lowerCamelCase__		:					Optional[Any]=0.1		,lowerCamelCase__		:					Dict=0.0		,lowerCamelCase__		:					Dict=0.0		,lowerCamelCase__		:					Dict=0.02		,lowerCamelCase__		:					List[Any]=1.0		,lowerCamelCase__		:					List[str]=True		,lowerCamelCase__		:					int=False		,lowerCamelCase__		:					int="sine"		,lowerCamelCase__		:					Any=5		,lowerCamelCase__		:					Optional[int]=4		,lowerCamelCase__		:					Optional[int]=4		,lowerCamelCase__		:					List[Any]=True		,lowerCamelCase__		:					Optional[int]=300		,lowerCamelCase__		:					Optional[Any]=True		,lowerCamelCase__		:					Optional[Any]=True		,lowerCamelCase__		:					Optional[int]=1		,lowerCamelCase__		:					Tuple=5		,lowerCamelCase__		:					Tuple=2		,lowerCamelCase__		:					Dict=1		,lowerCamelCase__		:					str=1		,lowerCamelCase__		:					List[Any]=5		,lowerCamelCase__		:					Tuple=2		,lowerCamelCase__		:					Union[str, Any]=0.1		,lowerCamelCase__		:					List[str]=0.25		,**lowerCamelCase__		:					int		,)  ->	List[Any]:




           '''simple docstring'''


           if backbone_config is None:
                 logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" )
                 SCREAMING_SNAKE_CASE	=		CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] )
           else:
                 if isinstance(lowerCamelCase__		,lowerCamelCase__ ):
                       SCREAMING_SNAKE_CASE	=		backbone_config.pop("""model_type""" )
                       SCREAMING_SNAKE_CASE	=		CONFIG_MAPPING[backbone_model_type]
                       SCREAMING_SNAKE_CASE	=		config_class.from_dict(lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		backbone_config
           SCREAMING_SNAKE_CASE	=		num_queries
           SCREAMING_SNAKE_CASE	=		max_position_embeddings
           SCREAMING_SNAKE_CASE	=		d_model
           SCREAMING_SNAKE_CASE	=		encoder_ffn_dim
           SCREAMING_SNAKE_CASE	=		encoder_layers
           SCREAMING_SNAKE_CASE	=		encoder_attention_heads
           SCREAMING_SNAKE_CASE	=		decoder_ffn_dim
           SCREAMING_SNAKE_CASE	=		decoder_layers
           SCREAMING_SNAKE_CASE	=		decoder_attention_heads
           SCREAMING_SNAKE_CASE	=		dropout
           SCREAMING_SNAKE_CASE	=		attention_dropout
           SCREAMING_SNAKE_CASE	=		activation_dropout
           SCREAMING_SNAKE_CASE	=		activation_function
           SCREAMING_SNAKE_CASE	=		init_std
           SCREAMING_SNAKE_CASE	=		init_xavier_std
           SCREAMING_SNAKE_CASE	=		encoder_layerdrop
           SCREAMING_SNAKE_CASE	=		auxiliary_loss
           SCREAMING_SNAKE_CASE	=		position_embedding_type
           # deformable attributes
           SCREAMING_SNAKE_CASE	=		num_feature_levels
           SCREAMING_SNAKE_CASE	=		encoder_n_points
           SCREAMING_SNAKE_CASE	=		decoder_n_points
           SCREAMING_SNAKE_CASE	=		two_stage
           SCREAMING_SNAKE_CASE	=		two_stage_num_proposals
           SCREAMING_SNAKE_CASE	=		with_box_refine
           SCREAMING_SNAKE_CASE	=		assign_first_stage
           if two_stage is True and with_box_refine is False:
                 raise ValueError("""If two_stage is True, with_box_refine must be True.""" )
           # Hungarian matcher
           SCREAMING_SNAKE_CASE	=		class_cost
           SCREAMING_SNAKE_CASE	=		bbox_cost
           SCREAMING_SNAKE_CASE	=		giou_cost
           # Loss coefficients
           SCREAMING_SNAKE_CASE	=		mask_loss_coefficient
           SCREAMING_SNAKE_CASE	=		dice_loss_coefficient
           SCREAMING_SNAKE_CASE	=		bbox_loss_coefficient
           SCREAMING_SNAKE_CASE	=		giou_loss_coefficient
           SCREAMING_SNAKE_CASE	=		eos_coefficient
           SCREAMING_SNAKE_CASE	=		focal_alpha
           super().__init__(is_encoder_decoder=lowerCamelCase__		,**lowerCamelCase__ )






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	int:




           '''simple docstring'''


           return self.encoder_attention_heads






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	int:




           '''simple docstring'''


           return self.d_model






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any] )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		copy.deepcopy(self.__dict__ )
           SCREAMING_SNAKE_CASE	=		self.backbone_config.to_dict()
           SCREAMING_SNAKE_CASE	=		self.__class__.model_type
           return output


