


"""simple docstring"""







import argparse
import os

import numpy as np
import tensorflow as tf
import torch

from transformers import BertModel




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value")

					__SCREAMING_SNAKE_CASE		     =       (
					    ("layer.", "layer_"),
					    ("word_embeddings.weight", "word_embeddings"),
					    ("position_embeddings.weight", "position_embeddings"),
					    ("token_type_embeddings.weight", "token_type_embeddings"),
					    (".", "/"),
					    ("LayerNorm/weight", "LayerNorm/gamma"),
					    ("LayerNorm/bias", "LayerNorm/beta"),
					    ("weight", "kernel"),
					)

					if not os.path.isdir(UpperCamelCase__     ):
										os.makedirs(UpperCamelCase__     )

					__SCREAMING_SNAKE_CASE		     =       model.state_dict()

					def to_tf_var_name(lowerCAmelCase_     ):
										for patt, repl in iter(UpperCamelCase__     ):
															__SCREAMING_SNAKE_CASE		     =       name.replace(UpperCamelCase__						,		UpperCamelCase__     )
										return f"""bert/{name}"""

					def create_tf_var(lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_     ):
										__SCREAMING_SNAKE_CASE		     =       tf.dtypes.as_dtype(tensor.dtype     )
										__SCREAMING_SNAKE_CASE		     =       tf.get_variable(dtype=UpperCamelCase__						,		shape=tensor.shape						,		name=UpperCamelCase__						,		initializer=tf.zeros_initializer()     )
										session.run(tf.variables_initializer([tf_var]     )     )
										session.run(UpperCamelCase__     )
										return tf_var

					tf.reset_default_graph()
					with tf.Session() as session:
										for var_name in state_dict:
															__SCREAMING_SNAKE_CASE		     =       to_tf_var_name(UpperCamelCase__     )
															__SCREAMING_SNAKE_CASE		     =       state_dict[var_name].numpy()
															if any(x in var_name for x in tensors_to_transpose     ):
																				__SCREAMING_SNAKE_CASE		     =       torch_tensor.T
															__SCREAMING_SNAKE_CASE		     =       create_tf_var(tensor=UpperCamelCase__						,		name=UpperCamelCase__						,		session=UpperCamelCase__     )
															tf.keras.backend.set_value(UpperCamelCase__						,		UpperCamelCase__     )
															__SCREAMING_SNAKE_CASE		     =       session.run(UpperCamelCase__     )
															print(f"""Successfully created {tf_name}: {np.allclose(UpperCamelCase__						,		UpperCamelCase__     )}"""     )

										__SCREAMING_SNAKE_CASE		     =       tf.train.Saver(tf.trainable_variables()     )
										saver.save(UpperCamelCase__						,		os.path.join(UpperCamelCase__						,		model_name.replace("-"						,		"_"     ) + ".ckpt"     )     )




def      UpperCAmelCase__ (lowerCAmelCase_=None     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       argparse.ArgumentParser()
					parser.add_argument("--model_name"						,		type=UpperCamelCase__						,		required=UpperCamelCase__						,		help="model name e.g. bert-base-uncased"     )
					parser.add_argument(
					    "--cache_dir"						,		type=UpperCamelCase__						,		default=UpperCamelCase__						,		required=UpperCamelCase__						,		help="Directory containing pytorch model"     )
					parser.add_argument("--pytorch_model_path"						,		type=UpperCamelCase__						,		required=UpperCamelCase__						,		help="/path/to/<pytorch-model-name>.bin"     )
					parser.add_argument("--tf_cache_dir"						,		type=UpperCamelCase__						,		required=UpperCamelCase__						,		help="Directory in which to save tensorflow model"     )
					__SCREAMING_SNAKE_CASE		     =       parser.parse_args(UpperCamelCase__     )

					__SCREAMING_SNAKE_CASE		     =       BertModel.from_pretrained(
					    pretrained_model_name_or_path=args.model_name						,		state_dict=torch.load(args.pytorch_model_path     )						,		cache_dir=args.cache_dir						,		)

					convert_pytorch_checkpoint_to_tf(model=UpperCamelCase__						,		ckpt_dir=args.tf_cache_dir						,		model_name=args.model_name     )


if __name__ == "__main__":
		main()









"""simple docstring"""







import unittest

from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
		from PIL import Image
else:




		class 				UpperCamelCase_			:

			"""simple docstring"""





			@staticmethod
			def 						UpperCAmelCase_   (				*UpperCAmelCase__    :       List[Any]    ,    **UpperCAmelCase__    :       Optional[Any]     ) ->			Optional[int]:
								pass




@is_pipeline_test
@require_torch
@require_vision
class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	snake_case__       :						List[Any]					      =    MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING




	def 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       Optional[int]     ) ->			str:
						__SCREAMING_SNAKE_CASE		     =       pipeline("visual-question-answering"    ,    model="hf-internal-testing/tiny-vilt-random-vqa"     )
						__SCREAMING_SNAKE_CASE		     =       [
						    {
						        "image": Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     ),
						        "question": "How many cats are there?",
						    },
						    {
						        "image": "./tests/fixtures/tests_samples/COCO/000000039769.png",
						        "question": "How many cats are there?",
						    },
						]
						return vqa_pipeline, examples




	def 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       Any     ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline(UpperCAmelCase__    ,    top_k=1     )
						self.assertEqual(
						    UpperCAmelCase__    ,    [
						        [{"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}],
						        [{"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}],
						    ]    ,    )




	@require_torch
	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       pipeline("visual-question-answering"    ,    model="hf-internal-testing/tiny-vilt-random-vqa"     )
						__SCREAMING_SNAKE_CASE		     =       "./tests/fixtures/tests_samples/COCO/000000039769.png"
						__SCREAMING_SNAKE_CASE		     =       "How many cats are there?"

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline(image=UpperCAmelCase__    ,    question="How many cats are there?"    ,    top_k=2     )
						self.assertEqual(
						    UpperCAmelCase__    ,    [{"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}, {"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}]     )

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline({"image": image, "question": question}    ,    top_k=2     )
						self.assertEqual(
						    UpperCAmelCase__    ,    [{"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}, {"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}]     )




	@slow
	@require_torch
	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       pipeline("visual-question-answering"    ,    model="dandelin/vilt-b32-finetuned-vqa"     )
						__SCREAMING_SNAKE_CASE		     =       "./tests/fixtures/tests_samples/COCO/000000039769.png"
						__SCREAMING_SNAKE_CASE		     =       "How many cats are there?"

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline(image=UpperCAmelCase__    ,    question=UpperCAmelCase__    ,    top_k=2     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__    ,    decimals=4     )    ,    [{"score": 0.8_799, "answer": "2"}, {"score": 0.296, "answer": "1"}]     )

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline({"image": image, "question": question}    ,    top_k=2     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__    ,    decimals=4     )    ,    [{"score": 0.8_799, "answer": "2"}, {"score": 0.296, "answer": "1"}]     )

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline(
						    [{"image": image, "question": question}, {"image": image, "question": question}]    ,    top_k=2     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__    ,    decimals=4     )    ,    [[{"score": 0.8_799, "answer": "2"}, {"score": 0.296, "answer": "1"}]] * 2    ,    )




	@require_tf
	@unittest.skip("Visual question answering not implemented in TF"     )
	def 						UpperCAmelCase_   (				self    :       str     ) ->			Optional[Any]:
						pass
