

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

  def __init__(				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE=12 ,					_SCREAMING_SNAKE_CASE=7 ,					_SCREAMING_SNAKE_CASE=True ,					_SCREAMING_SNAKE_CASE=True ,					_SCREAMING_SNAKE_CASE=True ,					_SCREAMING_SNAKE_CASE=99 ,					_SCREAMING_SNAKE_CASE=32 ,					_SCREAMING_SNAKE_CASE=32 ,					_SCREAMING_SNAKE_CASE=2 ,					_SCREAMING_SNAKE_CASE=4 ,					_SCREAMING_SNAKE_CASE=37 ,					_SCREAMING_SNAKE_CASE=0.1 ,					_SCREAMING_SNAKE_CASE=0.1 ,					_SCREAMING_SNAKE_CASE=512 ,					_SCREAMING_SNAKE_CASE=0.02 ,					_SCREAMING_SNAKE_CASE=0 ,					_SCREAMING_SNAKE_CASE=None ,					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  int           =     parent
        SCREAMING_SNAKE_CASE_				:  str           =     batch_size
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     seq_length
        SCREAMING_SNAKE_CASE_				:  Any           =     is_training
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     use_input_mask
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     use_labels
        SCREAMING_SNAKE_CASE_				:  List[str]           =     vocab_size
        SCREAMING_SNAKE_CASE_				:  int           =     hidden_size
        SCREAMING_SNAKE_CASE_				:  str           =     projection_dim
        SCREAMING_SNAKE_CASE_				:  Any           =     num_hidden_layers
        SCREAMING_SNAKE_CASE_				:  Any           =     num_attention_heads
        SCREAMING_SNAKE_CASE_				:  Dict           =     intermediate_size
        SCREAMING_SNAKE_CASE_				:  int           =     dropout
        SCREAMING_SNAKE_CASE_				:  List[str]           =     attention_dropout
        SCREAMING_SNAKE_CASE_				:  Dict           =     max_position_embeddings
        SCREAMING_SNAKE_CASE_				:  str           =     initializer_range
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     scope
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     bos_token_id

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Dict           =     ids_tensor([self.batch_size, self.seq_length] ,					self.vocab_size					)

        SCREAMING_SNAKE_CASE_				:  Dict           =     None
        if self.use_input_mask:
              SCREAMING_SNAKE_CASE_				:  int           =     random_attention_mask([self.batch_size, self.seq_length]					)

        if input_mask is not None:
              SCREAMING_SNAKE_CASE_				:  int           =     input_mask.numpy()
              SCREAMING_SNAKE_CASE_       ,						SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     input_mask.shape
              SCREAMING_SNAKE_CASE_				:  Optional[int]           =     np.random.randint(1 ,					seq_length - 1 ,					size=(batch_size,)					)
              for batch_idx, start_index in enumerate(A_					):
                    SCREAMING_SNAKE_CASE_				:  Optional[int]           =     1
                    SCREAMING_SNAKE_CASE_				:  Any           =     0

        SCREAMING_SNAKE_CASE_				:  Dict           =     self.get_config()

        return config, input_ids, tf.convert_to_tensor(A_					)

  def  UpperCAmelCase    (				self					):





        """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  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  int           =     TFBlipTextModel(config=A_					)
        SCREAMING_SNAKE_CASE_				:  int           =     model(A_ ,					attention_mask=A_ ,					training=A_					)
        SCREAMING_SNAKE_CASE_				:  List[str]           =     model(A_ ,					training=A_					)
        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					):





        """simple docstring"""







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





@require_tf
class  _A		(  _lowercase   ,     unittest.TestCase):
  SCREAMING_SNAKE_CASE    :      Tuple       =  (TFBlipTextModel,) if is_tf_available() else ()
  SCREAMING_SNAKE_CASE    :      Any       =  False
  SCREAMING_SNAKE_CASE    :      Any       =  False
  SCREAMING_SNAKE_CASE    :      List[str]       =  False

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     BlipTextModelTester(self					)
        SCREAMING_SNAKE_CASE_				:  str           =     ConfigTester(self ,					config_class=A_ ,					hidden_size=37					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        self.config_tester.run_common_tests()

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Dict           =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A_					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        pass

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        pass

  @unittest.skip(reason='Blip does not use inputs_embeds'					)
  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        pass

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





        """simple docstring"""







        pass

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





        """simple docstring"""







        pass

  @slow
  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE_				:  List[Any]           =     TFBlipTextModel.from_pretrained(A_					)
              self.assertIsNotNone(A_					)



  def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE=True					):





        """simple docstring"""







        super().test_pt_tf_model_equivalence(allow_missing_keys=A_					)









import unittest

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device


if is_torch_available():
    import torch

    from transformers import AutoModelForImageClassification

if is_vision_available():
    from transformers import AutoImageProcessor
@require_torch
@require_vision
class  _A		(  unittest.TestCase):

  @slow
  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  List[str]           =     AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip'					)
        SCREAMING_SNAKE_CASE_				:  Any           =     AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip'					)
        model.to(_SCREAMING_SNAKE_CASE					)

        from datasets import load_dataset

        SCREAMING_SNAKE_CASE_				:  str           =     load_dataset('nielsr/rvlcdip-demo'					)

        SCREAMING_SNAKE_CASE_				:  List[Any]           =     dataset['train'][0]['image'].convert('RGB'					)

        SCREAMING_SNAKE_CASE_				:  List[Any]           =     image_processor(_SCREAMING_SNAKE_CASE ,					return_tensors='pt'					).to(_SCREAMING_SNAKE_CASE					)

        # forward pass
        with torch.no_grad():
              SCREAMING_SNAKE_CASE_				:  int           =     model(**_SCREAMING_SNAKE_CASE					)
              SCREAMING_SNAKE_CASE_				:  Any           =     outputs.logits

        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     torch.Size((1, 16)					)
        self.assertEqual(logits.shape ,					_SCREAMING_SNAKE_CASE					)

        SCREAMING_SNAKE_CASE_				:  List[str]           =     torch.tensor(
            [-0.4158, -0.4092, -0.4347] ,					device=_SCREAMING_SNAKE_CASE ,					dtype=torch.float ,					)
        self.assertTrue(torch.allclose(logits[0, :3] ,					_SCREAMING_SNAKE_CASE ,					atol=1e-4					)					)






