






from __future__ import annotations

import unittest

from transformers import MobileBertConfig, is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
    import tensorflow as tf

    from transformers import (
        TF_MODEL_FOR_PRETRAINING_MAPPING,
        TFMobileBertForMaskedLM,
        TFMobileBertForMultipleChoice,
        TFMobileBertForNextSentencePrediction,
        TFMobileBertForPreTraining,
        TFMobileBertForQuestionAnswering,
        TFMobileBertForSequenceClassification,
        TFMobileBertForTokenClassification,
        TFMobileBertModel,
    )

@require_tf
class 		_snake_case  (  _lowerCAmelCase   ,    _lowerCAmelCase   ,    unittest.TestCase					):
   _lowercase		:    Any			     =							(
       (
           TFMobileBertModel,
           TFMobileBertForMaskedLM,
           TFMobileBertForNextSentencePrediction,
           TFMobileBertForPreTraining,
           TFMobileBertForQuestionAnswering,
           TFMobileBertForSequenceClassification,
           TFMobileBertForTokenClassification,
           TFMobileBertForMultipleChoice,
       )
       if is_tf_available()
       else ()
   )
   _lowercase		:    Any			     =							(
       {
           'feature-extraction': TFMobileBertModel,
           'fill-mask': TFMobileBertForMaskedLM,
           'question-answering': TFMobileBertForQuestionAnswering,
           'text-classification': TFMobileBertForSequenceClassification,
           'token-classification': TFMobileBertForTokenClassification,
           'zero-shot': TFMobileBertForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   _lowercase		:    Optional[Any]			     =							False
   _lowercase		:    Dict			     =							False






   def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a=False)      ->       List[Any]:
      SCREAMING_SNAKE_CASE						= super()._prepare_for_class(_lowerCAmelCase		,					_lowerCAmelCase		,					return_labels=_lowerCAmelCase)

      if return_labels:
         if model_class in get_values(_lowerCAmelCase):
            SCREAMING_SNAKE_CASE						= tf.zeros(self.model_tester.batch_size		,					dtype=tf.intaa)

      return inputs_dict

   class 		_snake_case  (  _lowerCAmelCase					):






      def __init__(       self		,					a		,					a=13		,					a=7		,					a=True		,					a=True		,					a=True		,					a=True		,					a=99		,					a=32		,					a=32		,					a=2		,					a=4		,					a=37		,					a="gelu"		,					a=0.1		,					a=0.1		,					a=512		,					a=16		,					a=2		,					a=0.02		,					a=3		,					a=4		,					a=None		,					)      ->       Tuple:
         SCREAMING_SNAKE_CASE						= parent
         SCREAMING_SNAKE_CASE						= batch_size
         SCREAMING_SNAKE_CASE						= seq_length
         SCREAMING_SNAKE_CASE						= is_training
         SCREAMING_SNAKE_CASE						= use_input_mask
         SCREAMING_SNAKE_CASE						= use_token_type_ids
         SCREAMING_SNAKE_CASE						= use_labels
         SCREAMING_SNAKE_CASE						= vocab_size
         SCREAMING_SNAKE_CASE						= hidden_size
         SCREAMING_SNAKE_CASE						= num_hidden_layers
         SCREAMING_SNAKE_CASE						= num_attention_heads
         SCREAMING_SNAKE_CASE						= intermediate_size
         SCREAMING_SNAKE_CASE						= hidden_act
         SCREAMING_SNAKE_CASE						= hidden_dropout_prob
         SCREAMING_SNAKE_CASE						= attention_probs_dropout_prob
         SCREAMING_SNAKE_CASE						= max_position_embeddings
         SCREAMING_SNAKE_CASE						= type_vocab_size
         SCREAMING_SNAKE_CASE						= type_sequence_label_size
         SCREAMING_SNAKE_CASE						= initializer_range
         SCREAMING_SNAKE_CASE						= num_labels
         SCREAMING_SNAKE_CASE						= num_choices
         SCREAMING_SNAKE_CASE						= scope
         SCREAMING_SNAKE_CASE						= embedding_size






      def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
         SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size)

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

         SCREAMING_SNAKE_CASE						= None
         if self.use_token_type_ids:
            SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size, self.seq_length]		,					self.type_vocab_size)

         SCREAMING_SNAKE_CASE						= None
         SCREAMING_SNAKE_CASE						= None
         SCREAMING_SNAKE_CASE						= None
         if self.use_labels:
            SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size]		,					self.type_sequence_label_size)
            SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size, self.seq_length]		,					self.num_labels)
            SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size]		,					self.num_choices)

         SCREAMING_SNAKE_CASE						= MobileBertConfig(
             vocab_size=self.vocab_size		,					hidden_size=self.hidden_size		,					num_hidden_layers=self.num_hidden_layers		,					num_attention_heads=self.num_attention_heads		,					intermediate_size=self.intermediate_size		,					hidden_act=self.hidden_act		,					hidden_dropout_prob=self.hidden_dropout_prob		,					attention_probs_dropout_prob=self.attention_probs_dropout_prob		,					max_position_embeddings=self.max_position_embeddings		,					type_vocab_size=self.type_vocab_size		,					initializer_range=self.initializer_range		,					embedding_size=self.embedding_size		,					)

         return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels






      def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       Dict:
         SCREAMING_SNAKE_CASE						= TFMobileBertModel(config=_lowerCAmelCase)
         SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)

         SCREAMING_SNAKE_CASE						= [input_ids, input_mask]
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)

         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)

         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		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       Dict:
         SCREAMING_SNAKE_CASE						= TFMobileBertForMaskedLM(config=_lowerCAmelCase)
         SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)
         self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.seq_length, self.vocab_size))






      def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       Union[str, Any]:
         SCREAMING_SNAKE_CASE						= TFMobileBertForNextSentencePrediction(config=_lowerCAmelCase)
         SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)
         self.parent.assertEqual(result.logits.shape		,					(self.batch_size, 2))






      def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       Optional[int]:
         SCREAMING_SNAKE_CASE						= TFMobileBertForPreTraining(config=_lowerCAmelCase)
         SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)
         self.parent.assertEqual(
             result.prediction_logits.shape		,					(self.batch_size, self.seq_length, self.vocab_size))
         self.parent.assertEqual(result.seq_relationship_logits.shape		,					(self.batch_size, 2))






      def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       str:
         SCREAMING_SNAKE_CASE						= self.num_labels
         SCREAMING_SNAKE_CASE						= TFMobileBertForSequenceClassification(config=_lowerCAmelCase)
         SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)
         self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.num_labels))






      def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       int:
         SCREAMING_SNAKE_CASE						= self.num_choices
         SCREAMING_SNAKE_CASE						= TFMobileBertForMultipleChoice(config=_lowerCAmelCase)
         SCREAMING_SNAKE_CASE						= tf.tile(tf.expand_dims(_lowerCAmelCase		,					1)		,					(1, self.num_choices, 1))
         SCREAMING_SNAKE_CASE						= tf.tile(tf.expand_dims(_lowerCAmelCase		,					1)		,					(1, self.num_choices, 1))
         SCREAMING_SNAKE_CASE						= tf.tile(tf.expand_dims(_lowerCAmelCase		,					1)		,					(1, self.num_choices, 1))
         SCREAMING_SNAKE_CASE						= {
             'input_ids': multiple_choice_inputs_ids,
             'attention_mask': multiple_choice_input_mask,
             'token_type_ids': multiple_choice_token_type_ids,
         }
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)
         self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.num_choices))






      def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       List[Any]:
         SCREAMING_SNAKE_CASE						= self.num_labels
         SCREAMING_SNAKE_CASE						= TFMobileBertForTokenClassification(config=_lowerCAmelCase)
         SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)
         self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.seq_length, self.num_labels))






      def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a		,					a		,					a		,					a		,					a)      ->       Any:
         SCREAMING_SNAKE_CASE						= TFMobileBertForQuestionAnswering(config=_lowerCAmelCase)
         SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)
         self.parent.assertEqual(result.start_logits.shape		,					(self.batch_size, self.seq_length))
         self.parent.assertEqual(result.end_logits.shape		,					(self.batch_size, self.seq_length))







      def    SCREAMING_SNAKE_CASE__    (       self)      ->       Tuple:
         SCREAMING_SNAKE_CASE						= self.prepare_config_and_inputs()
         (
             (
             SCREAMING_SNAKE_CASE						
         )				,						(
             SCREAMING_SNAKE_CASE						
         )				,						(
             SCREAMING_SNAKE_CASE						
         )				,						(
             SCREAMING_SNAKE_CASE						
         )				,						(
             SCREAMING_SNAKE_CASE						
         )				,						(
             SCREAMING_SNAKE_CASE						
         )				,						(
             SCREAMING_SNAKE_CASE						
         )				,												
         )						= config_and_inputs
         SCREAMING_SNAKE_CASE						= {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
         return config, inputs_dict






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
      SCREAMING_SNAKE_CASE						= TFMobileBertModelTest.TFMobileBertModelTester(self)
      SCREAMING_SNAKE_CASE						= ConfigTester(self		,					config_class=_lowerCAmelCase		,					hidden_size=37)






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       Tuple:
      self.config_tester.run_common_tests()






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       int:
      SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_model(*_lowerCAmelCase)






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
      SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_masked_lm(*_lowerCAmelCase)






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[Any]:
      SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_lowerCAmelCase)






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
      SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_lowerCAmelCase)






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       int:
      SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_pretraining(*_lowerCAmelCase)






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       Tuple:
      SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_question_answering(*_lowerCAmelCase)






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[str]:
      SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_lowerCAmelCase)






   def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[Any]:
      SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_token_classification(*_lowerCAmelCase)







   @slow
   def    SCREAMING_SNAKE_CASE__    (       self)      ->       Union[str, Any]:







      for model_name in ["google/mobilebert-uncased"]:
         SCREAMING_SNAKE_CASE						= TFMobileBertModel.from_pretrained(_lowerCAmelCase)
         self.assertIsNotNone(_lowerCAmelCase)



@require_tf
class 		_snake_case  (  unittest.TestCase					):






   @slow
   def    SCREAMING_SNAKE_CASE__    (       self)      ->       Any:
      SCREAMING_SNAKE_CASE						= TFMobileBertForPreTraining.from_pretrained('google/mobilebert-uncased')
      SCREAMING_SNAKE_CASE						= tf.constant([[0, 1, 2, 3, 4, 5]])
      SCREAMING_SNAKE_CASE						= model(_lowerCAmelCase)[0]

      SCREAMING_SNAKE_CASE						= [1, 6, 3_0522]
      self.assertEqual(output.shape		,					_lowerCAmelCase)

      SCREAMING_SNAKE_CASE						= tf.constant(
          [
              [
                  [-4.5_91_95_47, -9.24_82_95, -9.64_52_56],
                  [-6.7_30_61_75, -6.44_02_84, -6.6_05_28_37],
                  [-7.2_74_35_06, -6.7_84_79_15, -6.02_46_73],
              ]
          ])
      tf.debugging.assert_near(output[:, :3, :3]		,					_lowerCAmelCase		,					atol=1E-4)












from __future__ import annotations

import time

a_		:						Tuple             =    list[tuple[int, int]]

a_		:						Optional[int]             =    [
    [0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 0, 0, 0],  # 0 are free path whereas 1's are obstacles
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [1, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
]

a_		:						Dict             =    [[-1, 0], [0, -1], [1, 0], [0, 1]]  # up, left, down, right

class 		_snake_case  :






			def __init__(       self		,					a		,					a		,					a		,					a		,					a)      ->       int:
						SCREAMING_SNAKE_CASE						= pos_x
						SCREAMING_SNAKE_CASE						= pos_y
						SCREAMING_SNAKE_CASE						= (pos_y, pos_x)
						SCREAMING_SNAKE_CASE						= goal_x
						SCREAMING_SNAKE_CASE						= goal_y
						SCREAMING_SNAKE_CASE						= parent



class 		_snake_case  :






			def __init__(       self		,					a		,					a)      ->       Dict:
						SCREAMING_SNAKE_CASE						= Node(start[1]		,					start[0]		,					goal[1]		,					goal[0]		,					a)
						SCREAMING_SNAKE_CASE						= Node(goal[1]		,					goal[0]		,					goal[1]		,					goal[0]		,					a)

						SCREAMING_SNAKE_CASE						= [self.start]
						SCREAMING_SNAKE_CASE						= False






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Path | None:
						while self.node_queue:
									SCREAMING_SNAKE_CASE						= self.node_queue.pop(0)

									if current_node.pos == self.target.pos:
												SCREAMING_SNAKE_CASE						= True
												return self.retrace_path(a)

									SCREAMING_SNAKE_CASE						= self.get_successors(a)

									for node in successors:
												self.node_queue.append(a)

						if not self.reached:
									return [self.start.pos]
						return None






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       list[Node]:
						SCREAMING_SNAKE_CASE						= []
						for action in delta:
									SCREAMING_SNAKE_CASE						= parent.pos_x + action[1]
									SCREAMING_SNAKE_CASE						= parent.pos_y + action[0]
									if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(a) - 1):
												continue

									if grid[pos_y][pos_x] != 0:
												continue

									successors.append(
									    Node(a		,					a		,					self.target.pos_y		,					self.target.pos_x		,					a))
						return successors







			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       Path:
						SCREAMING_SNAKE_CASE						= node
						SCREAMING_SNAKE_CASE						= []
						while current_node is not None:
									path.append((current_node.pos_y, current_node.pos_x))
									SCREAMING_SNAKE_CASE						= current_node.parent
						path.reverse()
						return path



class 		_snake_case  :






			def __init__(       self		,					a		,					a)      ->       Tuple:
						SCREAMING_SNAKE_CASE						= BreadthFirstSearch(a		,					a)
						SCREAMING_SNAKE_CASE						= BreadthFirstSearch(a		,					a)
						SCREAMING_SNAKE_CASE						= False






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Path | None:
						while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
									SCREAMING_SNAKE_CASE						= self.fwd_bfs.node_queue.pop(0)
									SCREAMING_SNAKE_CASE						= self.bwd_bfs.node_queue.pop(0)

									if current_bwd_node.pos == current_fwd_node.pos:
												SCREAMING_SNAKE_CASE						= True
												return self.retrace_bidirectional_path(
												    a		,					a)

									SCREAMING_SNAKE_CASE						= current_bwd_node
									SCREAMING_SNAKE_CASE						= current_fwd_node

									SCREAMING_SNAKE_CASE						= {
									    self.fwd_bfs: self.fwd_bfs.get_successors(a),
									    self.bwd_bfs: self.bwd_bfs.get_successors(a),
									}

									for bfs in [self.fwd_bfs, self.bwd_bfs]:
												for node in successors[bfs]:
															bfs.node_queue.append(a)

						if not self.reached:
									return [self.fwd_bfs.start.pos]
						return None







			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a)      ->       Path:
						SCREAMING_SNAKE_CASE						= self.fwd_bfs.retrace_path(a)
						SCREAMING_SNAKE_CASE						= self.bwd_bfs.retrace_path(a)
						bwd_path.pop()
						bwd_path.reverse()
						SCREAMING_SNAKE_CASE						= fwd_path + bwd_path
						return path


if __name__ == "__main__":
				# all coordinates are given in format [y,x]
				import doctest

				doctest.testmod()
				a_		:						Union[str, Any]             =    (0, 0)
				a_		:						Any             =    (len(grid) - 1, len(grid[0]) - 1)
				for elem in grid:
								print(elem)

				a_		:						Optional[Any]             =    time.time()
				a_		:						Union[str, Any]             =    BreadthFirstSearch(init, goal)
				a_		:						Optional[Any]             =    bfs.search()
				a_		:						List[str]             =    time.time() - start_bfs_time

				print('Unidirectional BFS computation time : ', bfs_time)

				a_		:						Optional[int]             =    time.time()
				a_		:						Union[str, Any]             =    BidirectionalBreadthFirstSearch(init, goal)
				a_		:						List[Any]             =    bd_bfs.search()
				a_		:						List[str]             =    time.time() - start_bd_bfs_time

				print('Bidirectional BFS computation time : ', bd_bfs_time)




