

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







 """simple docstring"""







 def __init__(      self							:      Tuple, UpperCAmelCase__							:      List[Any], UpperCAmelCase__							:      Dict=1_2, UpperCAmelCase__							:      List[str]=7, UpperCAmelCase__							:      Union[str, Any]=True, UpperCAmelCase__							:      Any=True, UpperCAmelCase__							:      List[Any]=True, UpperCAmelCase__							:      Any=9_9, UpperCAmelCase__							:      Union[str, Any]=3_2, UpperCAmelCase__							:      Optional[int]=3_2, UpperCAmelCase__							:      Any=2, UpperCAmelCase__							:      Optional[Any]=4, UpperCAmelCase__							:      List[Any]=3_7, UpperCAmelCase__							:      List[Any]=0.1, UpperCAmelCase__							:      Tuple=0.1, UpperCAmelCase__							:      Optional[Any]=5_1_2, UpperCAmelCase__							:      Tuple=0.02, UpperCAmelCase__							:      Any=0, UpperCAmelCase__							:      Any=None, ):
    __lowercase								=						parent
    __lowercase								=						batch_size
    __lowercase								=						seq_length
    __lowercase								=						is_training
    __lowercase								=						use_input_mask
    __lowercase								=						use_labels
    __lowercase								=						vocab_size
    __lowercase								=						hidden_size
    __lowercase								=						projection_dim
    __lowercase								=						num_hidden_layers
    __lowercase								=						num_attention_heads
    __lowercase								=						intermediate_size
    __lowercase								=						dropout
    __lowercase								=						attention_dropout
    __lowercase								=						max_position_embeddings
    __lowercase								=						initializer_range
    __lowercase								=						scope
    __lowercase								=						bos_token_id


 def  _lowercase			(      self							:      Any     ):
    __lowercase								=						ids_tensor([self.batch_size, self.seq_length], self.vocab_size     )

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

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

    __lowercase								=						self.get_config()

    return config, input_ids, tf.convert_to_tensor(__SCREAMING_SNAKE_CASE     )


 def  _lowercase			(      self							:      Optional[Any]     ):
    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  _lowercase			(      self							:      Optional[Any], UpperCAmelCase__							:      Any, UpperCAmelCase__							:      Optional[int], UpperCAmelCase__							:      Any     ):
    __lowercase								=						TFBlipTextModel(config=__SCREAMING_SNAKE_CASE     )
    __lowercase								=						model(__SCREAMING_SNAKE_CASE, attention_mask=__SCREAMING_SNAKE_CASE, training=__SCREAMING_SNAKE_CASE     )
    __lowercase								=						model(__SCREAMING_SNAKE_CASE, training=__SCREAMING_SNAKE_CASE     )
    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  _lowercase			(      self							:      Any     ):
    __lowercase								=						self.prepare_config_and_inputs()
    __lowercase		,__lowercase		,__lowercase								=						config_and_inputs
    __lowercase								=						{"input_ids": input_ids, "attention_mask": input_mask}
    return config, inputs_dict







@require_tf
class  _lowerCAmelCase  (     lowerCAmelCase_					,unittest.TestCase       ):







 """simple docstring"""







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


 def  _lowercase			(      self							:      str     ):
    __lowercase								=						BlipTextModelTester(self     )
    __lowercase								=						ConfigTester(self, config_class=__SCREAMING_SNAKE_CASE, hidden_size=3_7     )


 def  _lowercase			(      self							:      Optional[Any]     ):
    self.config_tester.run_common_tests()


 def  _lowercase			(      self							:      Any     ):
    __lowercase								=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE     )


 def  _lowercase			(      self							:      Optional[int]     ):
    pass


 def  _lowercase			(      self							:      Union[str, Any]     ):
    pass


 @unittest.skip(reason="Blip does not use inputs_embeds"     )
 def  _lowercase			(      self							:      Union[str, Any]     ):
    pass


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


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


 @slow
 def  _lowercase			(      self							:      List[str]     ):

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



 def  _lowercase			(      self							:      Any, UpperCAmelCase__							:      str=True     ):
    super().test_pt_tf_model_equivalence(allow_missing_keys=__SCREAMING_SNAKE_CASE     )







"""simple docstring"""





import numpy

# List of input, output pairs
_a							=							(
    ((5, 2, 3), 15),
    ((6, 5, 9), 25),
    ((11, 12, 13), 41),
    ((1, 1, 1), 8),
    ((11, 12, 13), 41),
)
_a							=							(((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50))
_a							=							[2, 4, 1, 5]
_a							=							len(train_data)
_a							=							0.009




def   _A  (  UpperCamelCase_					:	str,      UpperCamelCase_					:	List[Any]="train")     ->						Optional[Any]:
   '''simple docstring'''


   return calculate_hypothesis_value(UpperCamelCase_,      UpperCamelCase_) - output(
       UpperCamelCase_,      UpperCamelCase_)




def   _A  (  UpperCamelCase_					:	List[Any])     ->						Union[str, Any]:
   '''simple docstring'''


   __lowercase								=						0
   for i in range(len(UpperCamelCase_) - 1):
      hyp_val += data_input_tuple[i] * parameter_vector[i + 1]
   hyp_val += parameter_vector[0]
   return hyp_val




def   _A  (  UpperCamelCase_					:	Dict,      UpperCamelCase_					:	Optional[int])     ->						Dict:
   '''simple docstring'''


   if data_set == "train":
      return train_data[example_no][1]
   elif data_set == "test":
      return test_data[example_no][1]
   return None




def   _A  (  UpperCamelCase_					:	Dict,      UpperCamelCase_					:	List[str])     ->						int:
   '''simple docstring'''


   if data_set == "train":
      return _hypothesis_value(train_data[example_no][0])
   elif data_set == "test":
      return _hypothesis_value(test_data[example_no][0])
   return None




def   _A  (  UpperCamelCase_					:	Any,      UpperCamelCase_					:	Tuple=m)     ->						int:
   '''simple docstring'''


   __lowercase								=						0
   for i in range(UpperCamelCase_):
      if index == -1:
         summation_value += _error(UpperCamelCase_)
      else:
         summation_value += _error(UpperCamelCase_) * train_data[i][0][index]
   return summation_value




def   _A  (  UpperCamelCase_					:	str)     ->						str:
   '''simple docstring'''


   __lowercase								=						summation_of_cost_derivative(UpperCamelCase_,      UpperCamelCase_) / m
   return cost_derivative_value




def   _A  (  )     ->						List[str]:
   '''simple docstring'''


   global parameter_vector
   # Tune these values to set a tolerance value for predicted output
   __lowercase								=						0.000_002
   __lowercase								=						0
   __lowercase								=						0
   while True:
      j += 1
      __lowercase								=						[0, 0, 0, 0]
      for i in range(0,      len(UpperCamelCase_)):
         __lowercase								=						get_cost_derivative(i - 1)
         __lowercase								=						(
             parameter_vector[i] - LEARNING_RATE * cost_derivative
         )
      if numpy.allclose(
          UpperCamelCase_,      UpperCamelCase_,      atol=UpperCamelCase_,      rtol=UpperCamelCase_,      ):
         break
      __lowercase								=						temp_parameter_vector
   print(("Number of iterations:", j))




def   _A  (  )     ->						int:
   '''simple docstring'''


   for i in range(len(UpperCamelCase_)):
      print(("Actual output value:", output(UpperCamelCase_,      "test")))
      print(("Hypothesis output:", calculate_hypothesis_value(UpperCamelCase_,      "test")))


if __name__ == "__main__":
   run_gradient_descent()
   print('\nTesting gradient descent for a linear hypothesis function.\n')
   test_gradient_descent()




