





from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
				import tensorflow as tf

				from transformers import TFBlipTextModel
				from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST







class   _UpperCamelCase  :







					'''simple docstring'''

					def __init__(						self    :  List[Any] ,					__lowercase    :  Optional[int] ,					__lowercase    :  List[str]=12 ,					__lowercase    :  List[Any]=7 ,					__lowercase    :  Dict=True ,					__lowercase    :  str=True ,					__lowercase    :  Union[str, Any]=True ,					__lowercase    :  Optional[int]=99 ,					__lowercase    :  str=32 ,					__lowercase    :  List[Any]=32 ,					__lowercase    :  Optional[Any]=2 ,					__lowercase    :  Any=4 ,					__lowercase    :  List[str]=37 ,					__lowercase    :  List[Any]=0.1 ,					__lowercase    :  Any=0.1 ,					__lowercase    :  str=5_12 ,					__lowercase    :  Optional[int]=0.02 ,					__lowercase    :  Tuple=0 ,					__lowercase    :  Dict=None ,					):






						'''simple docstring'''







						UpperCAmelCase_								=     parent
						UpperCAmelCase_								=     batch_size
						UpperCAmelCase_								=     seq_length
						UpperCAmelCase_								=     is_training
						UpperCAmelCase_								=     use_input_mask
						UpperCAmelCase_								=     use_labels
						UpperCAmelCase_								=     vocab_size
						UpperCAmelCase_								=     hidden_size
						UpperCAmelCase_								=     projection_dim
						UpperCAmelCase_								=     num_hidden_layers
						UpperCAmelCase_								=     num_attention_heads
						UpperCAmelCase_								=     intermediate_size
						UpperCAmelCase_								=     dropout
						UpperCAmelCase_								=     attention_dropout
						UpperCAmelCase_								=     max_position_embeddings
						UpperCAmelCase_								=     initializer_range
						UpperCAmelCase_								=     scope
						UpperCAmelCase_								=     bos_token_id





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     ids_tensor([self.batch_size, self.seq_length] ,					self.vocab_size		)

						UpperCAmelCase_								=     None
						if self.use_input_mask:
							UpperCAmelCase_								=     random_attention_mask([self.batch_size, self.seq_length]		)

						if input_mask is not None:
							UpperCAmelCase_								=     input_mask.numpy()
							UpperCAmelCase_								=     input_mask.shape
							UpperCAmelCase_								=     np.random.randint(1 ,					seq_length - 1 ,					size=(batch_size,)		)
							for batch_idx, start_index in enumerate(__lowercase		):
								UpperCAmelCase_								=     1
								UpperCAmelCase_								=     0

						UpperCAmelCase_								=     self.get_config()

						return config, input_ids, tf.convert_to_tensor(__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						return BlipTextConfig(
						    vocab_size=self.vocab_size ,					hidden_size=self.hidden_size ,					projection_dim=self.projection_dim ,					num_hidden_layers=self.num_hidden_layers ,					num_attention_heads=self.num_attention_heads ,					intermediate_size=self.intermediate_size ,					dropout=self.dropout ,					attention_dropout=self.attention_dropout ,					max_position_embeddings=self.max_position_embeddings ,					initializer_range=self.initializer_range ,					bos_token_id=self.bos_token_id ,					)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[str] ,					__lowercase    :  str ,					__lowercase    :  Dict ,					__lowercase    :  int		):






						'''simple docstring'''







						UpperCAmelCase_								=     TFBlipTextModel(config=__lowercase		)
						UpperCAmelCase_								=     model(__lowercase ,					attention_mask=__lowercase ,					training=__lowercase		)
						UpperCAmelCase_								=     model(__lowercase ,					training=__lowercase		)
						self.parent.assertEqual(result.last_hidden_state.shape ,					(self.batch_size, self.seq_length, self.hidden_size)		)
						self.parent.assertEqual(result.pooler_output.shape ,					(self.batch_size, self.hidden_size)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.prepare_config_and_inputs()
						UpperCAmelCase_								=     config_and_inputs
						UpperCAmelCase_								=     {'input_ids': input_ids, 'attention_mask': input_mask}
						return config, inputs_dict







@require_tf
class   _UpperCamelCase  (       A_						,       unittest.TestCase  ):







					'''simple docstring'''

					lowerCamelCase     :     str			    =       (TFBlipTextModel,) if is_tf_available() else ()
					lowerCamelCase     :     List[str]			    =       False
					lowerCamelCase     :     Optional[int]			    =       False
					lowerCamelCase     :     List[Any]			    =       False





					def        SCREAMING_SNAKE_CASE							(						self    :  Tuple		):






						'''simple docstring'''







						UpperCAmelCase_								=     BlipTextModelTester(self		)
						UpperCAmelCase_								=     ConfigTester(self ,					config_class=__lowercase ,					hidden_size=37		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						self.config_tester.run_common_tests()





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[int]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any]		):






						'''simple docstring'''







						pass





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						pass





					@unittest.skip(reason="""Blip does not use inputs_embeds"""		)
					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[int]		):






						'''simple docstring'''







						pass





					@unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""		)
					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						pass





					@unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""		)
					def        SCREAMING_SNAKE_CASE							(						self    :  Dict		):






						'''simple docstring'''







						pass





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  Dict		):






						'''simple docstring'''







						for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							UpperCAmelCase_								=     TFBlipTextModel.from_pretrained(__lowercase		)
							self.assertIsNotNone(__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any] ,					__lowercase    :  Any=True		):






						'''simple docstring'''







						super().test_pt_tf_model_equivalence(allow_missing_keys=__lowercase		)








import json
import os
import tempfile

import datasets
from utils import generate_example_dataset, get_duration


UpperCamelCase__   : Tuple					  = 5_00_00
UpperCamelCase__   : Any					  = 50_00

UpperCamelCase__  ,			UpperCamelCase__   : Tuple					  = os.path.split(__file__)
UpperCamelCase__   : Union[str, Any]					  = os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json"""))




@get_duration
def    A_(			A				,      A   ):
	for i in range(A   ):
		UpperCAmelCase_								=     dataset[i]




@get_duration
def    A_(			A				,      A				,      A   ):
	for i in range(0				,      len(A   )				,      A   ):
		UpperCAmelCase_								=     dataset[i : i + batch_size]




@get_duration
def    A_(			A				,      A				,      A   ):
	with dataset.formatted_as(type=A   ):
		for i in range(A   ):
			UpperCAmelCase_								=     dataset[i]




@get_duration
def    A_(			A				,      A				,      A				,      A   ):
	with dataset.formatted_as(type=A   ):
		for i in range(0				,      A				,      A   ):
			UpperCAmelCase_								=     dataset[i : i + batch_size]




def    A_(			):
	UpperCAmelCase_								=     {"""num examples""": SPEED_TEST_N_EXAMPLES}
	UpperCAmelCase_								=     [
	    (read, {"""length""": SMALL_TEST}),
	    (read, {"""length""": SPEED_TEST_N_EXAMPLES}),
	    (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10}),
	    (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 100}),
	    (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1000}),
	    (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}),
	    (read_formatted, {"""type""": """pandas""", """length""": SMALL_TEST}),
	    (read_formatted, {"""type""": """torch""", """length""": SMALL_TEST}),
	    (read_formatted, {"""type""": """tensorflow""", """length""": SMALL_TEST}),
	    (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10}),
	    (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1000}),
	]

	UpperCAmelCase_								=     [
	    (read, {"""length""": SMALL_TEST}),
	    (read, {"""length""": SPEED_TEST_N_EXAMPLES}),
	    (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10}),
	    (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 100}),
	    (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1000}),
	    (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}),
	    (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10}),
	    (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1000}),
	]
	with tempfile.TemporaryDirectory() as tmp_dir:
		print("""generating dataset"""   )
		UpperCAmelCase_								=     datasets.Features(
		    {"""list""": datasets.Sequence(datasets.Value("""float32"""   )   ), """numbers""": datasets.Value("""float32"""   )}   )
		UpperCAmelCase_								=     generate_example_dataset(
		    os.path.join(A				,      """dataset.arrow"""   )				,      A				,      num_examples=A				,      seq_shapes={"""list""": (100,)}				,      )
		print("""first set of iterations"""   )
		for func, kwargs in functions:
			print(func.__name__				,      str(A   )   )
			UpperCAmelCase_								=     func(A				,      **A   )

		print("""shuffling dataset"""   )
		UpperCAmelCase_								=     dataset.shuffle()
		print("""Second set of iterations (after shuffling"""   )
		for func, kwargs in functions_shuffled:
			print("""shuffled """				,      func.__name__				,      str(A   )   )
			UpperCAmelCase_								=     func(
			    A				,      **A   )

	with open(A				,      """wb"""   ) as f:
		f.write(json.dumps(A   ).encode("""utf-8"""   )   )


if __name__ == "__main__":  # useful to run the profiler
				benchmark_iterating()


