

'''simple docstring'''







import unittest

from transformers import BertGenerationConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import BertGenerationDecoder, BertGenerationEncoder


class        A__   :



    def __init__(       self		,					UpperCamelCase__		,					UpperCamelCase__=13		,					UpperCamelCase__=7		,					UpperCamelCase__=True		,					UpperCamelCase__=True		,					UpperCamelCase__=99		,					UpperCamelCase__=32		,					UpperCamelCase__=5		,					UpperCamelCase__=4		,					UpperCamelCase__=37		,					UpperCamelCase__="gelu"		,					UpperCamelCase__=0.1		,					UpperCamelCase__=0.1		,					UpperCamelCase__=50		,					UpperCamelCase__=0.02		,					UpperCamelCase__=True		,					UpperCamelCase__=None		,					)    ->   str:





           '''simple docstring'''
           A_						       =   parent
           A_						       =   batch_size
           A_						       =   seq_length
           A_						       =   is_training
           A_						       =   use_input_mask
           A_						       =   vocab_size
           A_						       =   hidden_size
           A_						       =   num_hidden_layers
           A_						       =   num_attention_heads
           A_						       =   intermediate_size
           A_						       =   hidden_act
           A_						       =   hidden_dropout_prob
           A_						       =   attention_probs_dropout_prob
           A_						       =   max_position_embeddings
           A_						       =   initializer_range
           A_						       =   use_labels
           A_						       =   scope



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size							)

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

           if self.use_labels:
                  A_						       =   ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size							)

           A_						       =   self.get_config()

           return config, input_ids, input_mask, token_labels



    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           return BertGenerationConfig(
               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		,					is_decoder=UpperCamelCase__		,					initializer_range=self.initializer_range		,					)



    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           (
               (
               A_
           )       ,      (
               A_
           )       ,      (
               A_
           )       ,      (
               A_
           )       ,      
           )						       =   self.prepare_config_and_inputs()

           A_						       =   True
           A_						       =   floats_tensor([self.batch_size, self.seq_length, self.hidden_size]							)
           A_						       =   ids_tensor([self.batch_size, self.seq_length]		,					vocab_size=2							)

           return (
               config,
               input_ids,
               input_mask,
               token_labels,
               encoder_hidden_states,
               encoder_attention_mask,
           )



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					**UpperCamelCase__		,					)    ->   Optional[int]:





           '''simple docstring'''
           A_						       =   BertGenerationEncoder(config=UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()
           A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__							)
           A_						       =   model(UpperCamelCase__							)
           self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					**UpperCamelCase__		,					)    ->   Optional[Any]:





           '''simple docstring'''
           A_						       =   True
           A_						       =   BertGenerationEncoder(config=UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()
           A_						       =   model(
               UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					encoder_hidden_states=UpperCamelCase__		,					encoder_attention_mask=UpperCamelCase__		,					)
           A_						       =   model(
               UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					encoder_hidden_states=UpperCamelCase__		,					)
           self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					**UpperCamelCase__		,					)    ->   Tuple:





           '''simple docstring'''
           A_						       =   True
           A_						       =   True
           A_						       =   BertGenerationDecoder(config=UpperCamelCase__							).to(UpperCamelCase__							).eval()

           # first forward pass
           A_						       =   model(
               UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					encoder_hidden_states=UpperCamelCase__		,					encoder_attention_mask=UpperCamelCase__		,					use_cache=UpperCamelCase__		,					)
           A_						       =   outputs.past_key_values

           # create hypothetical multiple next token and extent to next_input_ids
           A_						       =   ids_tensor((self.batch_size, 3)		,					config.vocab_size							)
           A_						       =   ids_tensor((self.batch_size, 3)		,					vocab_size=2							)

           # append to next input_ids and
           A_						       =   torch.cat([input_ids, next_tokens]		,					dim=-1							)
           A_						       =   torch.cat([input_mask, next_mask]		,					dim=-1							)

           A_						       =   model(
               UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					encoder_hidden_states=UpperCamelCase__		,					encoder_attention_mask=UpperCamelCase__		,					output_hidden_states=UpperCamelCase__		,					)["""hidden_states"""][0]
           A_						       =   model(
               UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					encoder_hidden_states=UpperCamelCase__		,					encoder_attention_mask=UpperCamelCase__		,					past_key_values=UpperCamelCase__		,					output_hidden_states=UpperCamelCase__		,					)["""hidden_states"""][0]

           # select random slice
           A_						       =   ids_tensor((1,)		,					output_from_past.shape[-1]							).item()
           A_						       =   output_from_no_past[:, -3:, random_slice_idx].detach()
           A_						       =   output_from_past[:, :, random_slice_idx].detach()

           self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]							)

           # test that outputs are equal for slice
           self.parent.assertTrue(torch.allclose(UpperCamelCase__		,					UpperCamelCase__		,					atol=1e-3							)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					*UpperCamelCase__		,					)    ->   Any:





           '''simple docstring'''
           A_						       =   BertGenerationDecoder(UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()
           A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					labels=UpperCamelCase__							)
           self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.seq_length, self.vocab_size)							)







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





           '''simple docstring'''
           A_       ,      A_       ,      A_       ,      A_						       =   self.prepare_config_and_inputs()
           A_						       =   {"""input_ids""": input_ids, """attention_mask""": input_mask}
           return config, inputs_dict


@require_torch
class        A__   (   _snake_case    ,    _snake_case    ,    _snake_case    ,    unittest.TestCase      ):
    lowercase						       =		(BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
    lowercase						       =		(BertGenerationDecoder,) if is_torch_available() else ()
    lowercase						       =		(
        {"feature-extraction": BertGenerationEncoder, "text-generation": BertGenerationDecoder}
        if is_torch_available()
        else {}
    )



    def        snake_case_      (       self							)    ->   List[str]:





           '''simple docstring'''
           A_						       =   BertGenerationEncoderTester(self							)
           A_						       =   ConfigTester(self		,					config_class=UpperCamelCase__		,					hidden_size=37							)



    def        snake_case_      (       self							)    ->   List[str]:





           '''simple docstring'''
           self.config_tester.run_common_tests()



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





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_       ,      A_       ,      A_       ,      A_						       =   self.model_tester.prepare_config_and_inputs()
           A_						       =   """bert"""
           self.model_tester.create_and_check_model(UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)



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





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs_for_decoder()
           self.model_tester.create_and_check_model_as_decoder(*UpperCamelCase__							)



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





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs_for_decoder()
           self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           # This regression test was failing with PyTorch < 1.3
           (
               (
               A_
           )       ,      (
               A_
           )       ,      (
               A_
           )       ,      (
               A_
           )       ,      (
               A_
           )       ,      (
               A_
           )       ,      
           )						       =   self.model_tester.prepare_config_and_inputs_for_decoder()

           A_						       =   None

           self.model_tester.create_and_check_model_as_decoder(
               UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					)



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs_for_decoder()
           self.model_tester.create_and_check_for_causal_lm(*UpperCamelCase__							)







    @slow
    def        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           A_						       =   BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""							)
           self.assertIsNotNone(UpperCamelCase__							)


@require_torch
class        A__   (   unittest.TestCase      ):



    @slow
    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""							)
           A_						       =   torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]]							)
           with torch.no_grad():
                  A_						       =   model(UpperCamelCase__							)[0]
           A_						       =   torch.Size([1, 8, 1024]							)
           self.assertEqual(output.shape		,					UpperCamelCase__							)
           A_						       =   torch.tensor(
               [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]]							)
           self.assertTrue(torch.allclose(output[:, :3, :3]		,					UpperCamelCase__		,					atol=1e-4							)							)


@require_torch
class        A__   (   unittest.TestCase      ):



    @slow
    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           A_						       =   BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""							)
           A_						       =   torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]]							)
           with torch.no_grad():
                  A_						       =   model(UpperCamelCase__							)[0]
           A_						       =   torch.Size([1, 8, 50358]							)
           self.assertEqual(output.shape		,					UpperCamelCase__							)
           A_						       =   torch.tensor(
               [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]]							)
           self.assertTrue(torch.allclose(output[:, :3, :3]		,					UpperCamelCase__		,					atol=1e-4							)							)



'''simple docstring'''







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		,					UpperCamelCase__		,					UpperCamelCase__=12		,					UpperCamelCase__=7		,					UpperCamelCase__=True		,					UpperCamelCase__=True		,					UpperCamelCase__=True		,					UpperCamelCase__=99		,					UpperCamelCase__=32		,					UpperCamelCase__=32		,					UpperCamelCase__=2		,					UpperCamelCase__=4		,					UpperCamelCase__=37		,					UpperCamelCase__=0.1		,					UpperCamelCase__=0.1		,					UpperCamelCase__=512		,					UpperCamelCase__=0.02		,					UpperCamelCase__=0		,					UpperCamelCase__=None		,					)    ->   Union[str, Any]:





           '''simple docstring'''
           A_						       =   parent
           A_						       =   batch_size
           A_						       =   seq_length
           A_						       =   is_training
           A_						       =   use_input_mask
           A_						       =   use_labels
           A_						       =   vocab_size
           A_						       =   hidden_size
           A_						       =   projection_dim
           A_						       =   num_hidden_layers
           A_						       =   num_attention_heads
           A_						       =   intermediate_size
           A_						       =   dropout
           A_						       =   attention_dropout
           A_						       =   max_position_embeddings
           A_						       =   initializer_range
           A_						       =   scope
           A_						       =   bos_token_id



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size							)

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

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

           A_						       =   self.get_config()

           return config, input_ids, tf.convert_to_tensor(UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Optional[int]:





           '''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        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   int:





           '''simple docstring'''
           A_						       =   TFBlipTextModel(config=UpperCamelCase__							)
           A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					training=UpperCamelCase__							)
           A_						       =   model(UpperCamelCase__		,					training=UpperCamelCase__							)
           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        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           A_						       =   self.prepare_config_and_inputs()
           A_       ,      A_       ,      A_						       =   config_and_inputs
           A_						       =   {"""input_ids""": input_ids, """attention_mask""": input_mask}
           return config, inputs_dict


@require_tf
class        A__   (   _snake_case    ,    unittest.TestCase      ):
    lowercase						       =		(TFBlipTextModel,) if is_tf_available() else ()
    lowercase						       =		False
    lowercase						       =		False
    lowercase						       =		False



    def        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           A_						       =   BlipTextModelTester(self							)
           A_						       =   ConfigTester(self		,					config_class=UpperCamelCase__		,					hidden_size=37							)



    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           self.config_tester.run_common_tests()



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase__							)



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





           '''simple docstring'''
           pass



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





           '''simple docstring'''
           pass



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





           '''simple docstring'''
           pass



    @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""							)
    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           pass



    @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""							)
    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           pass



    @slow
    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  A_						       =   TFBlipTextModel.from_pretrained(UpperCamelCase__							)
                  self.assertIsNotNone(UpperCamelCase__							)







    def        snake_case_      (       self		,					UpperCamelCase__=True							)    ->   str:





           '''simple docstring'''
           super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase__							)
