

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







			def      UpperCamelCase		(    self      ,      lowercase      ,      lowercase      ,      lowercase       )  ->						int:
							'''simple docstring'''






							return None

class 					a__						:
			"""simple docstring"""







			def      UpperCamelCase		(    self      ,      lowercase      ,      lowercase      ,      lowercase      ,      lowercase       )  ->						Optional[Any]:
							'''simple docstring'''






							return None

class 					a__						(					unittest.TestCase			):
			"""simple docstring"""







			__lowerCamelCase        =       [
			    # (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       )  ->						Union[str, Any]:
							'''simple docstring'''






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


			@require_torch
			@slow
			def      UpperCamelCase		(    self       )  ->						Optional[int]:
							'''simple docstring'''






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


			@require_torch
			@slow
			def      UpperCamelCase		(    self       )  ->						Dict:
							'''simple docstring'''






							from transformers import BertModel

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

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


			@require_tf
			@slow
			def      UpperCamelCase		(    self       )  ->						Union[str, Any]:
							'''simple docstring'''






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

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


			@require_torch
			@slow
			def      UpperCamelCase		(    self       )  ->						Tuple:
							'''simple docstring'''






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

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


			def      UpperCamelCase		(    self      ,      lowercase      ,      lowercase      ,      lowercase      ,      lowercase=None      ,      **lowercase       )  ->						str:
							'''simple docstring'''






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

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

											# Export
											convert(lowercase      ,      lowercase      ,      lowercase      ,      lowercase      ,      lowercase      ,      **lowercase       )

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


			@require_torch
			@require_tokenizers
			@slow
			def      UpperCamelCase		(    self       )  ->						Optional[Any]:
							'''simple docstring'''






							from transformers import BertModel

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


			@require_tf
			@require_tokenizers
			@slow
			def      UpperCamelCase		(    self       )  ->						int:
							'''simple docstring'''






							from transformers import TFBertModel

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


			def      UpperCamelCase		(    self      ,      lowercase      ,      lowercase      ,      lowercase       )  ->						Optional[Any]:
							'''simple docstring'''






							A__        =			FeatureExtractionPipeline(lowercase      ,      lowercase       )

							A__        =			["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"]
							A__    ,				A__    ,				A__    ,				A__        =			infer_shapes(lowercase      ,      lowercase       )

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

							# 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       )  ->						Dict:
							'''simple docstring'''






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

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

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

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

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

							# Should have exactly the one arg (all before the one not provided "some_other_args")
							self.assertEqual(len(lowercase       )      ,      1       )
							self.assertEqual(len(lowercase       )      ,      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       )  ->						Optional[Any]:
							'''simple docstring'''






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




def 					lowerCAmelCase__							(	SCREAMING_SNAKE_CASE_:							int      )			->      int:




				'''simple docstring'''





				if divisor % 5 == 0 or divisor % 2 == 0:
								return 0
				A__        =			1
				A__        =			1
				while repunit:
								A__        =			(1_0 * repunit + 1) % divisor
								repunit_index += 1
				return repunit_index



def 					lowerCAmelCase__							(	SCREAMING_SNAKE_CASE_:							int = 1_0_0_0_0_0_0      )			->      int:




				'''simple docstring'''





				A__        =			limit - 1
				if divisor % 2 == 0:
								divisor += 1
				while least_divisible_repunit(SCREAMING_SNAKE_CASE_      ) <= limit:
								divisor += 2
				return divisor


if __name__ == "__main__":
	print(f"""{solution() = }""")

