

'''simple docstring'''



from __future__ import annotations

import unittest

from transformers import AlbertConfig, 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
   from transformers.models.albert.modeling_tf_albert import (
       TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFAlbertForMaskedLM,
       TFAlbertForMultipleChoice,
       TFAlbertForPreTraining,
       TFAlbertForQuestionAnswering,
       TFAlbertForSequenceClassification,
       TFAlbertForTokenClassification,
       TFAlbertModel,
   )

class 			SCREAMING_SNAKE_CASE					:




      def __init__(					self :		Dict     ,					snake_case :		Union[str, Any]     ,					snake_case :		Any=13     ,					snake_case :		List[str]=7     ,					snake_case :		Optional[Any]=True     ,					snake_case :		Optional[Any]=True     ,					snake_case :		Optional[int]=True     ,					snake_case :		Tuple=True     ,					snake_case :		Optional[int]=99     ,					snake_case :		Dict=16     ,					snake_case :		Tuple=32     ,					snake_case :		Optional[int]=2     ,					snake_case :		Optional[int]=4     ,					snake_case :		Tuple=37     ,					snake_case :		Dict="gelu"     ,					snake_case :		List[str]=0.1     ,					snake_case :		List[Any]=0.1     ,					snake_case :		Union[str, Any]=512     ,					snake_case :		Tuple=16     ,					snake_case :		Optional[Any]=2     ,					snake_case :		str=0.02     ,					snake_case :		List[Any]=3     ,					snake_case :		Optional[int]=4     ,					snake_case :		str=None     ,					):



          """simple docstring"""





          _snake_case : Dict												=		parent
          _snake_case : Optional[int]												=		13
          _snake_case : Dict												=		7
          _snake_case : Optional[int]												=		True
          _snake_case : Any												=		True
          _snake_case : Union[str, Any]												=		True
          _snake_case : str												=		True
          _snake_case : Optional[Any]												=		99
          _snake_case : Dict												=		16
          _snake_case : List[str]												=		32
          _snake_case : Dict												=		2
          _snake_case : Optional[int]												=		4
          _snake_case : int												=		37
          _snake_case : Dict												=		'gelu'
          _snake_case : int												=		0.1
          _snake_case : List[str]												=		0.1
          _snake_case : Union[str, Any]												=		512
          _snake_case : Tuple												=		16
          _snake_case : Optional[Any]												=		2
          _snake_case : str												=		0.02
          _snake_case : Dict												=		3
          _snake_case : int												=		4
          _snake_case : Union[str, Any]												=		None




      def 	__UpperCAmelCase			(					self :		int   ):



          """simple docstring"""





          _snake_case : Tuple												=		ids_tensor([self.batch_size, self.seq_length]     ,					self.vocab_size   )

          _snake_case : Union[str, Any]												=		None
          if self.use_input_mask:
              _snake_case : str												=		random_attention_mask([self.batch_size, self.seq_length]   )

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

          _snake_case : Optional[Any]												=		None
          _snake_case : str												=		None
          _snake_case : Union[str, Any]												=		None
          if self.use_labels:
              _snake_case : Tuple												=		ids_tensor([self.batch_size]     ,					self.type_sequence_label_size   )
              _snake_case : Optional[int]												=		ids_tensor([self.batch_size, self.seq_length]     ,					self.num_labels   )
              _snake_case : Tuple												=		ids_tensor([self.batch_size]     ,					self.num_choices   )

          _snake_case : str												=		AlbertConfig(
              vocab_size=self.vocab_size     ,					hidden_size=self.hidden_size     ,					embedding_size=self.embedding_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     ,					)

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




      def 	__UpperCAmelCase			(					self :		int     ,					snake_case :		Any     ,					snake_case :		Union[str, Any]     ,					snake_case :		Dict     ,					snake_case :		Dict     ,					snake_case :		Dict     ,					snake_case :		List[Any]     ,					snake_case :		int   ):



          """simple docstring"""





          _snake_case : Dict												=		TFAlbertModel(config=snake_case   )
          # inputs = {'input_ids': input_ids,
          #           'attention_mask': input_mask,
          #           'token_type_ids': token_type_ids}
          # sequence_output, pooled_output = model(**inputs)
          _snake_case : List[Any]												=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
          _snake_case : Optional[int]												=		model(snake_case   )

          _snake_case : Tuple												=		[input_ids, input_mask]
          _snake_case : str												=		model(snake_case   )

          _snake_case : Optional[int]												=		model(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 	__UpperCAmelCase			(					self :		Tuple     ,					snake_case :		int     ,					snake_case :		Dict     ,					snake_case :		Dict     ,					snake_case :		Dict     ,					snake_case :		Any     ,					snake_case :		Dict     ,					snake_case :		str   ):



          """simple docstring"""





          _snake_case : Optional[int]												=		self.num_labels
          _snake_case : List[str]												=		TFAlbertForPreTraining(config=snake_case   )
          _snake_case : Optional[Any]												=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
          _snake_case : Optional[int]												=		model(snake_case   )
          self.parent.assertEqual(result.prediction_logits.shape     ,					(self.batch_size, self.seq_length, self.vocab_size)   )
          self.parent.assertEqual(result.sop_logits.shape     ,					(self.batch_size, self.num_labels)   )




      def 	__UpperCAmelCase			(					self :		Optional[int]     ,					snake_case :		Optional[Any]     ,					snake_case :		Union[str, Any]     ,					snake_case :		List[str]     ,					snake_case :		Any     ,					snake_case :		Optional[int]     ,					snake_case :		Optional[Any]     ,					snake_case :		int   ):



          """simple docstring"""





          _snake_case : Tuple												=		TFAlbertForMaskedLM(config=snake_case   )
          _snake_case : Union[str, Any]												=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
          _snake_case : List[str]												=		model(snake_case   )
          self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.seq_length, self.vocab_size)   )




      def 	__UpperCAmelCase			(					self :		str     ,					snake_case :		Dict     ,					snake_case :		Any     ,					snake_case :		Dict     ,					snake_case :		int     ,					snake_case :		Dict     ,					snake_case :		str     ,					snake_case :		Tuple   ):



          """simple docstring"""





          _snake_case : Tuple												=		self.num_labels
          _snake_case : Any												=		TFAlbertForSequenceClassification(config=snake_case   )
          _snake_case : Tuple												=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
          _snake_case : str												=		model(snake_case   )
          self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.num_labels)   )




      def 	__UpperCAmelCase			(					self :		str     ,					snake_case :		str     ,					snake_case :		List[Any]     ,					snake_case :		Tuple     ,					snake_case :		Dict     ,					snake_case :		int     ,					snake_case :		List[str]     ,					snake_case :		Optional[Any]   ):



          """simple docstring"""





          _snake_case : Union[str, Any]												=		TFAlbertForQuestionAnswering(config=snake_case   )
          _snake_case : Dict												=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
          _snake_case : Any												=		model(snake_case   )
          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 	__UpperCAmelCase			(					self :		Tuple     ,					snake_case :		Tuple     ,					snake_case :		int     ,					snake_case :		List[str]     ,					snake_case :		int     ,					snake_case :		Optional[Any]     ,					snake_case :		Union[str, Any]     ,					snake_case :		Any   ):



          """simple docstring"""





          _snake_case : List[Any]												=		self.num_choices
          _snake_case : List[str]												=		TFAlbertForMultipleChoice(config=snake_case   )
          _snake_case : str												=		tf.tile(tf.expand_dims(snake_case     ,					1   )     ,					(1, self.num_choices, 1)   )
          _snake_case : Optional[Any]												=		tf.tile(tf.expand_dims(snake_case     ,					1   )     ,					(1, self.num_choices, 1)   )
          _snake_case : Dict												=		tf.tile(tf.expand_dims(snake_case     ,					1   )     ,					(1, self.num_choices, 1)   )
          _snake_case : Tuple												=		{
              'input_ids': multiple_choice_inputs_ids,
              'attention_mask': multiple_choice_input_mask,
              'token_type_ids': multiple_choice_token_type_ids,
          }
          _snake_case : Optional[Any]												=		model(snake_case   )
          self.parent.assertListEqual(list(result['logits'].shape   )     ,					[self.batch_size, self.num_choices]   )




      def 	__UpperCAmelCase			(					self :		Optional[int]     ,					snake_case :		Any     ,					snake_case :		Optional[int]     ,					snake_case :		Optional[int]     ,					snake_case :		Optional[int]     ,					snake_case :		Dict     ,					snake_case :		List[Any]     ,					snake_case :		Optional[int]   ):



          """simple docstring"""





          _snake_case : str												=		self.num_labels
          _snake_case : List[str]												=		TFAlbertForTokenClassification(config=snake_case   )
          _snake_case : List[str]												=		{
              'input_ids': input_ids,
              'attention_mask': input_mask,
              'token_type_ids': token_type_ids,
          }
          _snake_case : Dict												=		model(snake_case   )
          self.parent.assertListEqual(list(result['logits'].shape   )     ,					[self.batch_size, self.seq_length, self.num_labels]   )




      def 	__UpperCAmelCase			(					self :		Tuple   ):



          """simple docstring"""





          _snake_case : Dict												=		self.prepare_config_and_inputs()
          (
              _snake_case							
          ) : List[str]												=		config_and_inputs
          _snake_case : int												=		{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
          return config, inputs_dict



@require_tf
class 			SCREAMING_SNAKE_CASE					(							lowercase_      ,lowercase_      ,unittest.TestCase					):
      SCREAMING_SNAKE_CASE__ :				Tuple    =				(
          (
              TFAlbertModel,
              TFAlbertForPreTraining,
              TFAlbertForMaskedLM,
              TFAlbertForSequenceClassification,
              TFAlbertForQuestionAnswering,
              TFAlbertForTokenClassification,
              TFAlbertForMultipleChoice,
          )
          if is_tf_available()
          else ()
      )
      SCREAMING_SNAKE_CASE__ :				List[Any]    =				(
          {
              '''feature-extraction''': TFAlbertModel,
              '''fill-mask''': TFAlbertForMaskedLM,
              '''question-answering''': TFAlbertForQuestionAnswering,
              '''text-classification''': TFAlbertForSequenceClassification,
              '''token-classification''': TFAlbertForTokenClassification,
              '''zero-shot''': TFAlbertForSequenceClassification,
          }
          if is_tf_available()
          else {}
      )
      SCREAMING_SNAKE_CASE__ :				Optional[int]    =				False
      SCREAMING_SNAKE_CASE__ :				Optional[int]    =				False




      def 	__UpperCAmelCase			(					self :		Optional[Any]     ,					snake_case :		Any     ,					snake_case :		Optional[int]     ,					snake_case :		Optional[Any]=False   ):



          """simple docstring"""





          _snake_case : Optional[int]												=		super()._prepare_for_class(snake_case     ,					snake_case     ,					return_labels=snake_case   )

          if return_labels:
              if model_class in get_values(snake_case   ):
                  _snake_case : Any												=		tf.zeros(self.model_tester.batch_size     ,					dtype=tf.intaa   )

          return inputs_dict




      def 	__UpperCAmelCase			(					self :		List[Any]   ):



          """simple docstring"""





          _snake_case : List[str]												=		TFAlbertModelTester(self   )
          _snake_case : Tuple												=		ConfigTester(self     ,					config_class=snake_case     ,					hidden_size=37   )




      def 	__UpperCAmelCase			(					self :		Tuple   ):



          """simple docstring"""





          self.config_tester.run_common_tests()




      def 	__UpperCAmelCase			(					self :		Any   ):



          """simple docstring"""





          _snake_case : Optional[Any]												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_model(*snake_case   )




      def 	__UpperCAmelCase			(					self :		Any   ):



          """simple docstring"""





          _snake_case : Optional[int]												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_pretraining(*snake_case   )




      def 	__UpperCAmelCase			(					self :		int   ):



          """simple docstring"""





          _snake_case : Optional[int]												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_masked_lm(*snake_case   )




      def 	__UpperCAmelCase			(					self :		str   ):



          """simple docstring"""





          _snake_case : Union[str, Any]												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_multiple_choice(*snake_case   )




      def 	__UpperCAmelCase			(					self :		str   ):



          """simple docstring"""





          _snake_case : List[str]												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_sequence_classification(*snake_case   )




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



          """simple docstring"""





          _snake_case : Dict												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_question_answering(*snake_case   )




      @slow
      def 	__UpperCAmelCase			(					self :		Any   ):



          """simple docstring"""





          for model_name in TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _snake_case : Optional[int]												=		TFAlbertModel.from_pretrained(snake_case   )
              self.assertIsNotNone(snake_case   )



@require_tf
class 			SCREAMING_SNAKE_CASE					(							unittest.TestCase					):




      @slow
      def 	__UpperCAmelCase			(					self :		Union[str, Any]   ):



          """simple docstring"""





          _snake_case : Optional[Any]												=		TFAlbertForPreTraining.from_pretrained('albert-base-v2'   )
          _snake_case : Union[str, Any]												=		tf.constant([[0, 1, 2, 3, 4, 5]]   )
          _snake_case : List[str]												=		model(snake_case   )[0]

          _snake_case : Dict												=		[1, 6, 30000]
          self.assertEqual(output.shape     ,					snake_case   )

          _snake_case : Dict												=		tf.constant(
              [
                  [
                      [4.59_5668, 0.7446_2754, -1.81_8147],
                      [4.595_4347, 0.745_4184, -1.818_8258],
                      [4.595_4905, 0.744_8235, -1.818_2316],
                  ]
              ]   )
          tf.debugging.assert_near(output[:, :3, :3]     ,					snake_case     ,					atol=1e-4   )






'''simple docstring'''



from typing import List, Optional, Tuple, Union

from . import logging
from .import_utils import is_torch_available, is_torch_version


if is_torch_available():
   import torch

SCREAMING_SNAKE_CASE_    =   logging.get_logger(__name__)  # pylint: disable=invalid-name

try:
   from torch._dynamo import allow_in_graph as maybe_allow_in_graph
except (ImportError, ModuleNotFoundError):

   def   lowerCamelCase__       (      cls)		->    Optional[Any]:



       """simple docstring"""







       return cls

def   lowerCamelCase__       (      a__			,      a__ = None			,      a__ = None			,      a__ = None			,      a__ = None			,      )		->    Dict:



    """simple docstring"""







    _snake_case : Optional[Any]												=		device
    _snake_case : Any												=		shape[0]

    _snake_case : str												=		layout or torch.strided
    _snake_case : str												=		device or torch.device('cpu')

    if generator is not None:
        _snake_case : Any												=		generator.device.type if not isinstance(a__			,      a__) else generator[0].device.type
        if gen_device_type != device.type and gen_device_type == "cpu":
            _snake_case : Optional[Any]												=		'cpu'
            if device != "mps":
                logger.info(
                    F"""The passed generator was created on 'cpu' even though a tensor on {device} was expected."""
                    F""" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably"""
                    F""" slighly speed up this function by passing a generator that was created on the {device} device.""")
        elif gen_device_type != device.type and gen_device_type == "cuda":
            raise ValueError(F"""Cannot generate a {device} tensor from a generator of type {gen_device_type}.""")

    if isinstance(a__			,      a__):
        _snake_case : Any												=		(1,) + shape[1:]
        _snake_case : int												=		[
            torch.randn(a__			,      generator=generator[i]			,      device=a__			,      dtype=a__			,      layout=a__)
            for i in range(a__)
        ]
        _snake_case : Optional[int]												=		torch.cat(a__			,      dim=0).to(a__)
    else:
        _snake_case : Optional[Any]												=		torch.randn(a__			,      generator=a__			,      device=a__			,      dtype=a__			,      layout=a__).to(a__)

    return latents




def   lowerCamelCase__       (      a__)		->    Optional[Any]:



    """simple docstring"""







    if is_torch_version('<'			,      '2.0.0') or not hasattr(a__			,      '_dynamo'):
        return False
    return isinstance(a__			,      torch._dynamo.eval_frame.OptimizedModule)



