






import warnings
from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


snake_case__      :	List[str]       	=      logging.get_logger(__name__)

snake_case__      :	Union[str, Any]       	=      {
    """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""",
    # See all BART models at https://huggingface.co/models?filter=bart
}


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   "bart"
  A_						=   ["past_key_values"]
  A_						=   {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}




  def __init__(     self		,		_UpperCAmelCase=50265		,		_UpperCAmelCase=1024		,		_UpperCAmelCase=12		,		_UpperCAmelCase=4096		,		_UpperCAmelCase=16		,		_UpperCAmelCase=12		,		_UpperCAmelCase=4096		,		_UpperCAmelCase=16		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase="gelu"		,		_UpperCAmelCase=1024		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=False		,		_UpperCAmelCase=True		,		_UpperCAmelCase=3		,		_UpperCAmelCase=1		,		_UpperCAmelCase=0		,		_UpperCAmelCase=2		,		_UpperCAmelCase=True		,		_UpperCAmelCase=2		,		_UpperCAmelCase=2		,		**_UpperCAmelCase		,		)			-> Tuple:
     UpperCamelCase_									=     vocab_size
     UpperCamelCase_									=     max_position_embeddings
     UpperCamelCase_									=     d_model
     UpperCamelCase_									=     encoder_ffn_dim
     UpperCamelCase_									=     encoder_layers
     UpperCamelCase_									=     encoder_attention_heads
     UpperCamelCase_									=     decoder_ffn_dim
     UpperCamelCase_									=     decoder_layers
     UpperCamelCase_									=     decoder_attention_heads
     UpperCamelCase_									=     dropout
     UpperCamelCase_									=     attention_dropout
     UpperCamelCase_									=     activation_dropout
     UpperCamelCase_									=     activation_function
     UpperCamelCase_									=     init_std
     UpperCamelCase_									=     encoder_layerdrop
     UpperCamelCase_									=     decoder_layerdrop
     UpperCamelCase_									=     classifier_dropout
     UpperCamelCase_									=     use_cache
     UpperCamelCase_									=     encoder_layers
     UpperCamelCase_									=     scale_embedding  # scale factor will be sqrt(d_model) if True

     super().__init__(
         num_labels=_UpperCAmelCase		,		pad_token_id=_UpperCAmelCase		,		bos_token_id=_UpperCAmelCase		,		eos_token_id=_UpperCAmelCase		,		is_encoder_decoder=_UpperCAmelCase		,		decoder_start_token_id=_UpperCAmelCase		,		forced_eos_token_id=_UpperCAmelCase		,		**_UpperCAmelCase		,		)

     # ensure backward compatibility for BART CNN models
     if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated'		,		_UpperCAmelCase ):
        UpperCamelCase_									=     self.bos_token_id
        warnings.warn(
            f"""Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. """
            'The config can simply be saved and uploaded again to be fixed.' )




class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  @property
  def    _UpperCAmelCase     (     self )			-> Mapping[str, Mapping[int, str]]:




     if self.task in ["default", "seq2seq-lm"]:
        UpperCamelCase_									=     OrderedDict(
            [
                ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
                ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
            ] )

        if self.use_past:
           UpperCamelCase_									=     {0: 'batch'}
           UpperCamelCase_									=     {0: 'batch', 1: 'past_decoder_sequence + sequence'}
        else:
           UpperCamelCase_									=     {0: 'batch', 1: 'decoder_sequence'}
           UpperCamelCase_									=     {0: 'batch', 1: 'decoder_sequence'}

        if self.use_past:
           self.fill_with_past_key_values_(_UpperCAmelCase		,		direction='inputs' )
     elif self.task == "causal-lm":
        # TODO: figure this case out.
        UpperCamelCase_									=     OrderedDict(
            [
                ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
                ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
            ] )
        if self.use_past:
           UpperCamelCase_		,      UpperCamelCase_									=     self.num_layers
           for i in range(_UpperCAmelCase ):
              UpperCamelCase_									=     {0: 'batch', 2: 'past_sequence + sequence'}
              UpperCamelCase_									=     {0: 'batch', 2: 'past_sequence + sequence'}
     else:
        UpperCamelCase_									=     OrderedDict(
            [
                ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
                ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
                ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}),
                ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}),
            ] )

     return common_inputs




  @property
  def    _UpperCAmelCase     (     self )			-> Mapping[str, Mapping[int, str]]:




     if self.task in ["default", "seq2seq-lm"]:
        UpperCamelCase_									=     super().outputs
     else:
        UpperCamelCase_									=     super(_UpperCAmelCase		,		self ).outputs
        if self.use_past:
           UpperCamelCase_		,      UpperCamelCase_									=     self.num_layers
           for i in range(_UpperCAmelCase ):
              UpperCamelCase_									=     {0: 'batch', 2: 'past_sequence + sequence'}
              UpperCamelCase_									=     {0: 'batch', 2: 'past_sequence + sequence'}
     return common_outputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = False		,		_UpperCAmelCase = None		,		)			-> Mapping[str, Any]:
     UpperCamelCase_									=     self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
         _UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )

     # Generate decoder inputs
     UpperCamelCase_									=     seq_length if not self.use_past else 1
     UpperCamelCase_									=     self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
         _UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )
     UpperCamelCase_									=     {f"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
     UpperCamelCase_									=     dict(**_UpperCAmelCase		,		**_UpperCAmelCase )

     if self.use_past:
        if not is_torch_available():
           raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' )
        else:
           import torch
        UpperCamelCase_		,      UpperCamelCase_									=     common_inputs['input_ids'].shape
        UpperCamelCase_									=     common_inputs['decoder_input_ids'].shape[1]
        UpperCamelCase_		,      UpperCamelCase_									=     self.num_attention_heads
        UpperCamelCase_									=     (
            batch,
            num_encoder_attention_heads,
            encoder_seq_length,
            self._config.hidden_size // num_encoder_attention_heads,
        )
        UpperCamelCase_									=     decoder_seq_length + 3
        UpperCamelCase_									=     (
            batch,
            num_decoder_attention_heads,
            decoder_past_length,
            self._config.hidden_size // num_decoder_attention_heads,
        )

        UpperCamelCase_									=     torch.cat(
            [common_inputs['decoder_attention_mask'], torch.ones(_UpperCAmelCase		,		_UpperCAmelCase )]		,		dim=1 )

        UpperCamelCase_									=     []
        # If the number of encoder and decoder layers are present in the model configuration, both are considered
        UpperCamelCase_		,      UpperCamelCase_									=     self.num_layers
        UpperCamelCase_									=     min(_UpperCAmelCase		,		_UpperCAmelCase )
        UpperCamelCase_									=     max(_UpperCAmelCase		,		_UpperCAmelCase ) - min_num_layers
        UpperCamelCase_									=     'encoder' if num_encoder_layers > num_decoder_layers else 'decoder'

        for _ in range(_UpperCAmelCase ):
           common_inputs["past_key_values"].append(
               (
                   torch.zeros(_UpperCAmelCase ),
                   torch.zeros(_UpperCAmelCase ),
                   torch.zeros(_UpperCAmelCase ),
                   torch.zeros(_UpperCAmelCase ),
               ) )
        # TODO: test this.
        UpperCamelCase_									=     encoder_shape if remaining_side_name == 'encoder' else decoder_shape
        for _ in range(_UpperCAmelCase		,		_UpperCAmelCase ):
           common_inputs["past_key_values"].append((torch.zeros(_UpperCAmelCase ), torch.zeros(_UpperCAmelCase )) )
     return common_inputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = False		,		_UpperCAmelCase = None		,		)			-> Mapping[str, Any]:
     UpperCamelCase_									=     self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
         _UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )

     if self.use_past:
        if not is_torch_available():
           raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' )
        else:
           import torch
        UpperCamelCase_		,      UpperCamelCase_									=     common_inputs['input_ids'].shape
        # Not using the same length for past_key_values
        UpperCamelCase_									=     seqlen + 2
        UpperCamelCase_		,      UpperCamelCase_									=     self.num_layers
        UpperCamelCase_		,      UpperCamelCase_									=     self.num_attention_heads
        UpperCamelCase_									=     (
            batch,
            num_encoder_attention_heads,
            past_key_values_length,
            self._config.hidden_size // num_encoder_attention_heads,
        )

        UpperCamelCase_									=     common_inputs['attention_mask'].dtype
        UpperCamelCase_									=     torch.cat(
            [common_inputs['attention_mask'], torch.ones(_UpperCAmelCase		,		_UpperCAmelCase		,		dtype=_UpperCAmelCase )]		,		dim=1 )
        UpperCamelCase_									=     [
            (torch.zeros(_UpperCAmelCase ), torch.zeros(_UpperCAmelCase )) for _ in range(_UpperCAmelCase )
        ]
     return common_inputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = False		,		_UpperCAmelCase = None		,		)			-> Mapping[str, Any]:
     UpperCamelCase_									=     compute_effective_axis_dimension(
         _UpperCAmelCase		,		fixed_dimension=OnnxConfig.default_fixed_batch		,		num_token_to_add=0 )

     # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
     UpperCamelCase_									=     tokenizer.num_special_tokens_to_add(_UpperCAmelCase )
     UpperCamelCase_									=     compute_effective_axis_dimension(
         _UpperCAmelCase		,		fixed_dimension=OnnxConfig.default_fixed_sequence		,		num_token_to_add=_UpperCAmelCase )

     # Generate dummy inputs according to compute batch and sequence
     UpperCamelCase_									=     [' '.join([tokenizer.unk_token] ) * seq_length] * batch_size
     UpperCamelCase_									=     dict(tokenizer(_UpperCAmelCase		,		return_tensors=_UpperCAmelCase ) )
     return common_inputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = -1		,		_UpperCAmelCase = False		,		_UpperCAmelCase = None		,		)			-> Mapping[str, Any]:




     if self.task in ["default", "seq2seq-lm"]:
        UpperCamelCase_									=     self._generate_dummy_inputs_for_default_and_seqaseq_lm(
            _UpperCAmelCase		,		batch_size=_UpperCAmelCase		,		seq_length=_UpperCAmelCase		,		is_pair=_UpperCAmelCase		,		framework=_UpperCAmelCase )

     elif self.task == "causal-lm":
        UpperCamelCase_									=     self._generate_dummy_inputs_for_causal_lm(
            _UpperCAmelCase		,		batch_size=_UpperCAmelCase		,		seq_length=_UpperCAmelCase		,		is_pair=_UpperCAmelCase		,		framework=_UpperCAmelCase )
     else:
        UpperCamelCase_									=     self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            _UpperCAmelCase		,		batch_size=_UpperCAmelCase		,		seq_length=_UpperCAmelCase		,		is_pair=_UpperCAmelCase		,		framework=_UpperCAmelCase )

     return common_inputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[Any]:




     if self.task in ["default", "seq2seq-lm"]:
        UpperCamelCase_									=     super()._flatten_past_key_values_(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )
     else:
        UpperCamelCase_									=     super(_UpperCAmelCase		,		self )._flatten_past_key_values_(
            _UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )










import inspect
import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import ViTMSNForImageClassification, ViTMSNModel
 from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor


class 						_a       :






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=30		,		_UpperCAmelCase=2		,		_UpperCAmelCase=3		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=32		,		_UpperCAmelCase=5		,		_UpperCAmelCase=4		,		_UpperCAmelCase=37		,		_UpperCAmelCase="gelu"		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=10		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=None		,		)			-> Optional[Any]:
     UpperCamelCase_									=     parent
     UpperCamelCase_									=     batch_size
     UpperCamelCase_									=     image_size
     UpperCamelCase_									=     patch_size
     UpperCamelCase_									=     num_channels
     UpperCamelCase_									=     is_training
     UpperCamelCase_									=     use_labels
     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_									=     type_sequence_label_size
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     scope

     # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
     UpperCamelCase_									=     (image_size // patch_size) ** 2
     UpperCamelCase_									=     num_patches + 1




  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_									=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

     UpperCamelCase_									=     None
     if self.use_labels:
        UpperCamelCase_									=     ids_tensor([self.batch_size]		,		self.type_sequence_label_size )

     UpperCamelCase_									=     self.get_config()

     return config, pixel_values, labels




  def    _UpperCAmelCase     (     self )			-> int:
     return ViTMSNConfig(
         image_size=self.image_size		,		patch_size=self.patch_size		,		num_channels=self.num_channels		,		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		,		initializer_range=self.initializer_range		,		)




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Any:
     UpperCamelCase_									=     ViTMSNModel(config=_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.last_hidden_state.shape		,		(self.batch_size, self.seq_length, self.hidden_size) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> str:
     UpperCamelCase_									=     self.type_sequence_label_size
     UpperCamelCase_									=     ViTMSNForImageClassification(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase		,		labels=_UpperCAmelCase )
     print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}' )
     print('Labels: {labels}' )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size) )

     # test greyscale images
     UpperCamelCase_									=     1
     UpperCamelCase_									=     ViTMSNForImageClassification(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()

     UpperCamelCase_									=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size) )




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     config_and_inputs
     UpperCamelCase_									=     {'pixel_values': pixel_values}
     return config, inputs_dict




@require_torch
class 						_a       (  UpperCAmelCase__						,       UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





  A_						=   (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
  A_						=   (
      {"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification}
      if is_torch_available()
      else {}
  )

  A_						=   False
  A_						=   False
  A_						=   False
  A_						=   False




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     ViTMSNModelTester(self )
     UpperCamelCase_									=     ConfigTester(self		,		config_class=_UpperCAmelCase		,		has_text_modality=_UpperCAmelCase		,		hidden_size=37 )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     self.config_tester.run_common_tests()




  @unittest.skip(reason='ViTMSN does not use inputs_embeds' )
  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     pass




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        self.assertIsInstance(model.get_input_embeddings()		,		(nn.Module) )
        UpperCamelCase_									=     model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(_UpperCAmelCase		,		nn.Linear ) )




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        UpperCamelCase_									=     inspect.signature(model.forward )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        UpperCamelCase_									=     [*signature.parameters.keys()]

        UpperCamelCase_									=     ['pixel_values']
        self.assertListEqual(arg_names[:1]		,		_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase )




  @slow
  def    _UpperCAmelCase     (     self )			-> Dict:
     for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase_									=     ViTMSNModel.from_pretrained(_UpperCAmelCase )
        self.assertIsNotNone(_UpperCAmelCase )






def     _snake_case    ():
   UpperCamelCase_									=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
   return image


@require_torch
@require_vision
class 						_a       (  unittest.TestCase    ):






  """simple docstring"""





  @cached_property
  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     return ViTImageProcessor.from_pretrained('facebook/vit-msn-small' ) if is_vision_available() else None




  @slow
  def    _UpperCAmelCase     (     self )			-> List[str]:
     torch.manual_seed(2 )
     UpperCamelCase_									=     ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small' ).to(_UpperCAmelCase )

     UpperCamelCase_									=     self.default_image_processor
     UpperCamelCase_									=     prepare_img()
     UpperCamelCase_									=     image_processor(images=_UpperCAmelCase		,		return_tensors='pt' ).to(_UpperCAmelCase )

     # forward pass
     with torch.no_grad():
        UpperCamelCase_									=     model(**_UpperCAmelCase )

     # verify the logits
     UpperCamelCase_									=     torch.Size((1, 1000) )
     self.assertEqual(outputs.logits.shape		,		_UpperCAmelCase )

     UpperCamelCase_									=     torch.tensor([-0.0_8_0_3, -0.4_4_5_4, -0.2_3_7_5] ).to(_UpperCAmelCase )

     self.assertTrue(torch.allclose(outputs.logits[0, :3]		,		_UpperCAmelCase		,		atol=1e-4 ) )





