





"""simple docstring"""
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       a							:



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  return None







class       a							:



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  return None







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



 @require_tf
 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






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



 @require_torch
 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






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



 @require_torch
 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  from transformers import BertModel

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

  with TemporaryDirectory() as bert_save_dir:
   lowerCAmelCase    				= BertModel(BertConfig(vocab_size=len(_snake_case     )     )     )
   model.save_pretrained(_snake_case     )
   self._test_export(_snake_case				,       'pt'				,       12				,       _snake_case     )



 @require_tf
 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
   lowerCAmelCase    				= self._test_export(_snake_case				,       'tf'				,       12				,       **_snake_case     )
   lowerCAmelCase    				= quantize(Path(_snake_case     )     )

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



 @require_torch
 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
   lowerCAmelCase    				= self._test_export(_snake_case				,       'pt'				,       12				,       **_snake_case     )
   lowerCAmelCase    				= quantize(_snake_case     )

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



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case=None				,       **_snake_case     ):







  """simple docstring"""






  try:
   # Compute path
   with TemporaryDirectory() as tempdir:
    lowerCAmelCase    				= Path(_snake_case     ).joinpath('model.onnx'     )

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

   # Export
   convert(_snake_case				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case				,       **_snake_case     )

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



 @require_torch
 @require_tokenizers
 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  from transformers import BertModel

  lowerCAmelCase    				= BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random'     )     )
  lowerCAmelCase    				= BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random'     )
  self._test_infer_dynamic_axis(_snake_case				,       _snake_case				,       'pt'     )



 @require_tf
 @require_tokenizers
 @slow
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  from transformers import TFBertModel

  lowerCAmelCase    				= TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random'     )     )
  lowerCAmelCase    				= BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random'     )
  self._test_infer_dynamic_axis(_snake_case				,       _snake_case				,       'tf'     )



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= FeatureExtractionPipeline(_snake_case				,       _snake_case     )

  lowerCAmelCase    				= ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1']
  lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase    				= infer_shapes(_snake_case				,       _snake_case     )

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

  # 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    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= ['input_ids', 'attention_mask', 'token_type_ids']
  lowerCAmelCase    				= {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]}
  lowerCAmelCase				,lowerCAmelCase    				= ensure_valid_input(FuncContiguousArgs()				,       _snake_case				,       _snake_case     )

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

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

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

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

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

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



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






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









from timeit import timeit

lowerCamelCase		   =			{
    'MALAYALAM': True,
    'String': False,
    'rotor': True,
    'level': True,
    'A': True,
    'BB': True,
    'ABC': False,
    'amanaplanacanalpanama': True,  # "a man a plan a canal panama"
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =0
       _lowerCamelCase			:						Union[str, Any]            =len(SCREAMING_SNAKE_CASE__	) - 1
       while start_i < end_i:
              if s[start_i] == s[end_i]:
                     start_i += 1
                     end_i -= 1
              else:
                     return False
       return True




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						List[str]            =len(SCREAMING_SNAKE_CASE__	) // 2
       _lowerCamelCase			:						Optional[Any]            =len(SCREAMING_SNAKE_CASE__	)

       # We need to traverse till half of the length of string
       # as we can get access of the i'th last element from
       # i'th index.
       # eg: [0,1,2,3,4,5] => 4th index can be accessed
       # with the help of 1st index (i==n-i-1)
       # where n is length of string
       return all(s[i] == s[n - i - 1] for i in range(SCREAMING_SNAKE_CASE__	)	)




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       if len(SCREAMING_SNAKE_CASE__	) <= 2:
              return True
       if s[0] == s[len(SCREAMING_SNAKE_CASE__	) - 1]:
              return is_palindrome_recursive(s[1:-1]	)
       else:
              return False




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       return s == s[::-1]




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =F'''all({name}(key) is value for key, value in test_data.items())'''
       _lowerCamelCase			:						List[Any]            =F'''from __main__ import test_data, {name}'''
       _lowerCamelCase			:						Any            =500_000
       _lowerCamelCase			:						Dict            =timeit(stmt=SCREAMING_SNAKE_CASE__						,     setup=SCREAMING_SNAKE_CASE__						,     number=SCREAMING_SNAKE_CASE__	)
       print(F'''{name:<35} finished {number:,} runs in {result:.5f} seconds'''	)


if __name__ == "__main__":
 for key, value in test_data.items():
  assert is_palindrome(key) is is_palindrome_recursive(key)
  assert is_palindrome(key) is is_palindrome_slice(key)
  print(F"""{key:21} {value}""")
 print('a man a plan a canal panama')

 # finished 500,000 runs in 0.46793 seconds
 benchmark_function('is_palindrome_slice')
 # finished 500,000 runs in 0.85234 seconds
 benchmark_function('is_palindrome')
 # finished 500,000 runs in 1.32028 seconds
 benchmark_function('is_palindrome_recursive')
 # finished 500,000 runs in 2.08679 seconds
 benchmark_function('is_palindrome_traversal')


