"""simple docstring"""


import unittest

from transformers import BigBirdConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
    import jax

    from transformers.models.big_bird.modeling_flax_big_bird import (
        FlaxBigBirdForCausalLM,
        FlaxBigBirdForMaskedLM,
        FlaxBigBirdForMultipleChoice,
        FlaxBigBirdForPreTraining,
        FlaxBigBirdForQuestionAnswering,
        FlaxBigBirdForSequenceClassification,
        FlaxBigBirdForTokenClassification,
        FlaxBigBirdModel,
    )


class 							a					(		unittest.TestCase ):


    def __init__(       self						:	Optional[int] ,					__lowerCAmelCase						:	List[Any] ,					__lowerCAmelCase						:	Optional[Any]=2 ,					__lowerCAmelCase						:	List[str]=56 ,					__lowerCAmelCase						:	Optional[int]=True ,					__lowerCAmelCase						:	Tuple=True ,					__lowerCAmelCase						:	Any=True ,					__lowerCAmelCase						:	List[Any]=True ,					__lowerCAmelCase						:	Dict=99 ,					__lowerCAmelCase						:	int=32 ,					__lowerCAmelCase						:	int=2 ,					__lowerCAmelCase						:	Dict=2 ,					__lowerCAmelCase						:	List[str]=7 ,					__lowerCAmelCase						:	Dict="gelu_new" ,					__lowerCAmelCase						:	Optional[Any]=0.1 ,					__lowerCAmelCase						:	Any=0.1 ,					__lowerCAmelCase						:	Optional[int]=512 ,					__lowerCAmelCase						:	Optional[int]=16 ,					__lowerCAmelCase						:	List[str]=2 ,					__lowerCAmelCase						:	Union[str, Any]=0.02 ,					__lowerCAmelCase						:	List[Any]=4 ,					__lowerCAmelCase						:	int="block_sparse" ,					__lowerCAmelCase						:	List[Any]=True ,					__lowerCAmelCase						:	int=False ,					__lowerCAmelCase						:	List[Any]=2 ,					__lowerCAmelCase						:	int=3 ,					):
      _UpperCAmelCase    			=   parent
      _UpperCAmelCase    			=   batch_size
      _UpperCAmelCase    			=   seq_length
      _UpperCAmelCase    			=   is_training
      _UpperCAmelCase    			=   use_attention_mask
      _UpperCAmelCase    			=   use_token_type_ids
      _UpperCAmelCase    			=   use_labels
      _UpperCAmelCase    			=   vocab_size
      _UpperCAmelCase    			=   hidden_size
      _UpperCAmelCase    			=   num_hidden_layers
      _UpperCAmelCase    			=   num_attention_heads
      _UpperCAmelCase    			=   intermediate_size
      _UpperCAmelCase    			=   hidden_act
      _UpperCAmelCase    			=   hidden_dropout_prob
      _UpperCAmelCase    			=   attention_probs_dropout_prob
      _UpperCAmelCase    			=   max_position_embeddings
      _UpperCAmelCase    			=   type_vocab_size
      _UpperCAmelCase    			=   type_sequence_label_size
      _UpperCAmelCase    			=   initializer_range
      _UpperCAmelCase    			=   num_choices

      _UpperCAmelCase    			=   rescale_embeddings
      _UpperCAmelCase    			=   attention_type
      _UpperCAmelCase    			=   use_bias
      _UpperCAmelCase    			=   block_size
      _UpperCAmelCase    			=   num_random_blocks


    def   lowerCAmelCase_	(       self						:	int       ):
      _UpperCAmelCase    			=   ids_tensor([self.batch_size, self.seq_length] ,					self.vocab_size       )

      _UpperCAmelCase    			=   None
      if self.use_attention_mask:
        _UpperCAmelCase    			=   random_attention_mask([self.batch_size, self.seq_length]       )

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

      _UpperCAmelCase    			=   BigBirdConfig(
          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 ,					is_decoder=lowerCamelCase_ ,					initializer_range=self.initializer_range ,					attention_type=self.attention_type ,					block_size=self.block_size ,					num_random_blocks=self.num_random_blocks ,					use_bias=self.use_bias ,					rescale_embeddings=self.rescale_embeddings ,					)

      return config, input_ids, token_type_ids, attention_mask


    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      _UpperCAmelCase    			=   self.prepare_config_and_inputs()
      _UpperCAmelCase    			=   config_and_inputs
      _UpperCAmelCase    			=   {
          '''input_ids''': input_ids,
          '''token_type_ids''': token_type_ids,
          '''attention_mask''': attention_mask,
      }
      return config, inputs_dict



@require_flax
class 							a					(		lowerCAmelCase_						,				unittest.TestCase ):
    _snake_case  :	Optional[int]  				=				(
        (
            FlaxBigBirdForCausalLM,
            FlaxBigBirdModel,
            FlaxBigBirdForPreTraining,
            FlaxBigBirdForMaskedLM,
            FlaxBigBirdForMultipleChoice,
            FlaxBigBirdForQuestionAnswering,
            FlaxBigBirdForSequenceClassification,
            FlaxBigBirdForTokenClassification,
        )
        if is_flax_available()
        else ()
    )

    _snake_case  :	int  				=				False
    _snake_case  :	Any  				=				False


    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      _UpperCAmelCase    			=   FlaxBigBirdModelTester(self       )


    @slow
    # copied from `test_modeling_flax_common` because it takes much longer than other models
    def   lowerCAmelCase_	(       self						:	Tuple       ):
      super().test_from_pretrained_save_pretrained()


    @slow
    # copied from `test_modeling_flax_common` because it takes much longer than other models
    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      super().test_from_pretrained_with_no_automatic_init()


    @slow
    # copied from `test_modeling_flax_common` because it takes much longer than other models
    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      super().test_no_automatic_init()


    @slow
    # copied from `test_modeling_flax_common` because it takes much longer than other models
    def   lowerCAmelCase_	(       self						:	Dict       ):
      super().test_hidden_states_output()


    @slow
    def   lowerCAmelCase_	(       self						:	str       ):



      for model_class_name in self.all_model_classes:
        _UpperCAmelCase    			=   model_class_name.from_pretrained("""google/bigbird-roberta-base"""       )
        self.assertIsNotNone(lowerCamelCase_       )


    def   lowerCAmelCase_	(       self						:	List[Any]       ):



      if self.test_attn_probs:
        super().test_attention_outputs()


    @slow
    # copied from `test_modeling_flax_common` because it takes much longer than other models
    def   lowerCAmelCase_	(       self						:	List[str]       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        with self.subTest(model_class.__name__       ):
          _UpperCAmelCase    			=   self._prepare_for_class(lowerCamelCase_ ,					lowerCamelCase_       )
          _UpperCAmelCase    			=   model_class(lowerCamelCase_       )

          @jax.jit
          def model_jitted(__lowerCAmelCase						:	Any ,					__lowerCAmelCase						:	Optional[Any]=None ,					**__lowerCAmelCase						:	str       ):
            return model(input_ids=lowerCamelCase_ ,					attention_mask=lowerCamelCase_ ,					**lowerCamelCase_       )

          with self.subTest("""JIT Enabled"""       ):
            _UpperCAmelCase    			=   model_jitted(**lowerCamelCase_       ).to_tuple()

          with self.subTest("""JIT Disabled"""       ):
            with jax.disable_jit():
              _UpperCAmelCase    			=   model_jitted(**lowerCamelCase_       ).to_tuple()

          self.assertEqual(len(lowerCamelCase_       ) ,					len(lowerCamelCase_       )       )
          for jitted_output, output in zip(lowerCamelCase_ ,					lowerCamelCase_       ):
            self.assertEqual(jitted_output.shape ,					output.shape       )


    def   lowerCAmelCase_	(       self						:	Any ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	Dict ,					__lowerCAmelCase						:	str ,					__lowerCAmelCase						:	List[Any]=1e-5 ,					__lowerCAmelCase						:	List[Any]="outputs" ,					__lowerCAmelCase						:	int=None       ):



      if name.startswith("""outputs.attentions"""       ):
        return
      else:
        super().check_pt_flax_outputs(lowerCamelCase_ ,					lowerCamelCase_ ,					lowerCamelCase_ ,					lowerCamelCase_ ,					lowerCamelCase_ ,					lowerCamelCase_       )

'''simple docstring'''

import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


UpperCamelCase__  :						str					=      get_tests_dir('fixtures')


class 					_lowercase						(   unittest.TestCase ):
      '''simple docstring'''


      def 		lowerCAmelCase__       (					self				)      ->      int:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[int] 					=	mock.Mock()
         UpperCAmelCase__				:					Dict 					=	500
         UpperCAmelCase__				:					Optional[int] 					=	{}
         UpperCAmelCase__				:					List[str] 					=	HTTPError
         UpperCAmelCase__				:					Tuple 					=	{}

         # Download this model to make sure it's in the cache.
         UpperCAmelCase__				:					Any 					=	ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit'''				)
         # Under the mock environment we get a 500 error when trying to reach the model.
         with mock.patch('''requests.Session.request'''       ,return_value=lowerCamelCase_				) as mock_head:
            UpperCAmelCase__				:					Tuple 					=	ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit'''				)
            # This check we did call the fake head request
            mock_head.assert_called()




      def 		lowerCAmelCase__       (					self				)      ->      Tuple:



         '''simple docstring'''



         UpperCAmelCase__				:					Dict 					=	ViTImageProcessor.from_pretrained(
             '''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'''				)




      def 		lowerCAmelCase__       (					self				)      ->      Union[str, Any]:



         '''simple docstring'''



         with self.assertRaises(lowerCamelCase_				):
            # config is in subfolder, the following should not work without specifying the subfolder
            UpperCAmelCase__				:					int 					=	AutoImageProcessor.from_pretrained('''hf-internal-testing/stable-diffusion-all-variants'''				)

         UpperCAmelCase__				:					Optional[Any] 					=	AutoImageProcessor.from_pretrained(
             '''hf-internal-testing/stable-diffusion-all-variants'''       ,subfolder='''feature_extractor'''				)

         self.assertIsNotNone(lowerCamelCase_				)




@is_staging_test
class 					_lowercase						(   unittest.TestCase ):
      '''simple docstring'''


      @classmethod
      def 		lowerCAmelCase__       (					cls				)      ->      Optional[Any]:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[int] 					=	TOKEN
         HfFolder.save_token(lowerCamelCase_				)




      @classmethod
      def 		lowerCAmelCase__       (					cls				)      ->      List[str]:



         '''simple docstring'''



         try:
            delete_repo(token=cls._token       ,repo_id='''test-image-processor'''				)
         except HTTPError:
            pass

         try:
            delete_repo(token=cls._token       ,repo_id='''valid_org/test-image-processor-org'''				)
         except HTTPError:
            pass

         try:
            delete_repo(token=cls._token       ,repo_id='''test-dynamic-image-processor'''				)
         except HTTPError:
            pass




      def 		lowerCAmelCase__       (					self				)      ->      Union[str, Any]:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[Any] 					=	ViTImageProcessor.from_pretrained(lowerCamelCase_				)
         image_processor.push_to_hub('''test-image-processor'''       ,use_auth_token=self._token				)

         UpperCAmelCase__				:					Any 					=	ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)

         # Reset repo
         delete_repo(token=self._token       ,repo_id='''test-image-processor'''				)

         # Push to hub via save_pretrained
         with tempfile.TemporaryDirectory() as tmp_dir:
            image_processor.save_pretrained(
                lowerCamelCase_       ,repo_id='''test-image-processor'''       ,push_to_hub=lowerCamelCase_       ,use_auth_token=self._token				)

         UpperCAmelCase__				:					List[Any] 					=	ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)




      def 		lowerCAmelCase__       (					self				)      ->      List[Any]:



         '''simple docstring'''



         UpperCAmelCase__				:					Union[str, Any] 					=	ViTImageProcessor.from_pretrained(lowerCamelCase_				)
         image_processor.push_to_hub('''valid_org/test-image-processor'''       ,use_auth_token=self._token				)

         UpperCAmelCase__				:					Any 					=	ViTImageProcessor.from_pretrained('''valid_org/test-image-processor'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)

         # Reset repo
         delete_repo(token=self._token       ,repo_id='''valid_org/test-image-processor'''				)

         # Push to hub via save_pretrained
         with tempfile.TemporaryDirectory() as tmp_dir:
            image_processor.save_pretrained(
                lowerCamelCase_       ,repo_id='''valid_org/test-image-processor-org'''       ,push_to_hub=lowerCamelCase_       ,use_auth_token=self._token				)

         UpperCAmelCase__				:					Any 					=	ViTImageProcessor.from_pretrained('''valid_org/test-image-processor-org'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)




      def 		lowerCAmelCase__       (					self				)      ->      str:



         '''simple docstring'''



         CustomImageProcessor.register_for_auto_class()
         UpperCAmelCase__				:					List[str] 					=	CustomImageProcessor.from_pretrained(lowerCamelCase_				)

         image_processor.push_to_hub('''test-dynamic-image-processor'''       ,use_auth_token=self._token				)

         # This has added the proper auto_map field to the config
         self.assertDictEqual(
             image_processor.auto_map       ,{'''AutoImageProcessor''': '''custom_image_processing.CustomImageProcessor'''}       ,)

         UpperCAmelCase__				:					Any 					=	AutoImageProcessor.from_pretrained(
             f'''{USER}/test-dynamic-image-processor'''       ,trust_remote_code=lowerCamelCase_				)
         # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
         self.assertEqual(new_image_processor.__class__.__name__       ,'''CustomImageProcessor'''				)




