






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     _lowerCAmelCase:





       """simple docstring"""







       def       _a   ( self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase							):
         return None







class     _lowerCAmelCase:





       """simple docstring"""







       def       _a   ( self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase							):
         return None







class     _lowerCAmelCase(	unittest.TestCase ):





       """simple docstring"""







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





       @require_tf
       @slow
       def       _a   ( self							):
         for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
           self._test_export(_lowerCamelCase  ,      'tf'  ,      1_2  ,      **_lowerCamelCase							)





       @require_torch
       @slow
       def       _a   ( self							):
         for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
           self._test_export(_lowerCamelCase  ,      'pt'  ,      1_2  ,      **_lowerCamelCase							)





       @require_torch
       @slow
       def       _a   ( self							):
         from transformers import BertModel

         UpperCamelCase_: Dict   				=    ['[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()
           UpperCamelCase_: List[Any]   				=    BertTokenizerFast(vocab_file.name							)

         with TemporaryDirectory() as bert_save_dir:
           UpperCamelCase_: Dict   				=    BertModel(BertConfig(vocab_size=len(_lowerCamelCase							)							)							)
           model.save_pretrained(_lowerCamelCase							)
           self._test_export(_lowerCamelCase  ,      'pt'  ,      1_2  ,      _lowerCamelCase							)





       @require_tf
       @slow
       def       _a   ( self							):
         for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
           UpperCamelCase_: Any   				=    self._test_export(_lowerCamelCase  ,      'tf'  ,      1_2  ,      **_lowerCamelCase							)
           UpperCamelCase_: List[Any]   				=    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       _a   ( self							):
         for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
           UpperCamelCase_: Any   				=    self._test_export(_lowerCamelCase  ,      'pt'  ,      1_2  ,      **_lowerCamelCase							)
           UpperCamelCase_: Optional[int]   				=    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       _a   ( self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase=None  ,      **_lowerCamelCase							):
         try:
           # Compute path
           with TemporaryDirectory() as tempdir:
             UpperCamelCase_: Optional[Any]   				=    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       _a   ( self							):
         from transformers import BertModel

         UpperCamelCase_: Optional[Any]   				=    BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random'							)							)
         UpperCamelCase_: str   				=    BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random'							)
         self._test_infer_dynamic_axis(_lowerCamelCase  ,      _lowerCamelCase  ,      'pt'							)





       @require_tf
       @require_tokenizers
       @slow
       def       _a   ( self							):
         from transformers import TFBertModel

         UpperCamelCase_: Optional[Any]   				=    TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random'							)							)
         UpperCamelCase_: Tuple   				=    BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random'							)
         self._test_infer_dynamic_axis(_lowerCamelCase  ,      _lowerCamelCase  ,      'tf'							)





       def       _a   ( self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase							):
         UpperCamelCase_: Any   				=    FeatureExtractionPipeline(_lowerCamelCase  ,      _lowerCamelCase							)

         UpperCamelCase_: Optional[Any]   				=    ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1']
         UpperCamelCase_				,UpperCamelCase_				,UpperCamelCase_				,UpperCamelCase_: Dict   				=    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       _a   ( self							):
         UpperCamelCase_: Dict   				=    ['input_ids', 'attention_mask', 'token_type_ids']
         UpperCamelCase_: Tuple   				=    {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]}
         UpperCamelCase_				,UpperCamelCase_: List[str]   				=    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)
         UpperCamelCase_				,UpperCamelCase_: Tuple   				=    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       _a   ( self							):
         UpperCamelCase_: Any   				=    generate_identified_filename(Path('/home/something/my_fake_model.onnx'							)  ,      '-test'							)
         self.assertEqual('/home/something/my_fake_model-test.onnx'  ,      generated.as_posix()							)







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


A_		:		Tuple		     =			{
    'configuration_funnel': ['FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FunnelConfig'],
    'convert_funnel_original_tf_checkpoint_to_pytorch': [],
    'tokenization_funnel': ['FunnelTokenizer'],
}

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_		:		List[str]		     =			['FunnelTokenizerFast']

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_		:		List[str]		     =			[
       'FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST',
       'FunnelBaseModel',
       'FunnelForMaskedLM',
       'FunnelForMultipleChoice',
       'FunnelForPreTraining',
       'FunnelForQuestionAnswering',
       'FunnelForSequenceClassification',
       'FunnelForTokenClassification',
       'FunnelModel',
       'FunnelPreTrainedModel',
       'load_tf_weights_in_funnel',
   ]

try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A_		:		str		     =			[
       'TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST',
       'TFFunnelBaseModel',
       'TFFunnelForMaskedLM',
       'TFFunnelForMultipleChoice',
       'TFFunnelForPreTraining',
       'TFFunnelForQuestionAnswering',
       'TFFunnelForSequenceClassification',
       'TFFunnelForTokenClassification',
       'TFFunnelModel',
       'TFFunnelPreTrainedModel',
   ]


if TYPE_CHECKING:
   from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig
   from .tokenization_funnel import FunnelTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_funnel_fast import FunnelTokenizerFast

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_funnel import (
          FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
          FunnelBaseModel,
          FunnelForMaskedLM,
          FunnelForMultipleChoice,
          FunnelForPreTraining,
          FunnelForQuestionAnswering,
          FunnelForSequenceClassification,
          FunnelForTokenClassification,
          FunnelModel,
          FunnelPreTrainedModel,
          load_tf_weights_in_funnel,
      )

   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_tf_funnel import (
          TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFFunnelBaseModel,
          TFFunnelForMaskedLM,
          TFFunnelForMultipleChoice,
          TFFunnelForPreTraining,
          TFFunnelForQuestionAnswering,
          TFFunnelForSequenceClassification,
          TFFunnelForTokenClassification,
          TFFunnelModel,
          TFFunnelPreTrainedModel,
      )

else:
   import sys

   A_		:		Any		     =			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)