

"""simple docstring"""





import collections
import inspect
import unittest

from transformers import SwinConfig
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_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel
				from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor

class     __a   :

			"""simple docstring"""

			def __init__(							self     :					List[Any]						,  lowercase_     :					int						,  lowercase_     :					Tuple=13						,  lowercase_     :					List[str]=32						,  lowercase_     :					Dict=2						,  lowercase_     :					List[Any]=3						,  lowercase_     :					List[str]=16						,  lowercase_     :					Union[str, Any]=[1, 2, 1]						,  lowercase_     :					Optional[int]=[2, 2, 4]						,  lowercase_     :					List[str]=2						,  lowercase_     :					List[str]=2.0						,  lowercase_     :					Union[str, Any]=True						,  lowercase_     :					Tuple=0.0						,  lowercase_     :					str=0.0						,  lowercase_     :					List[Any]=0.1						,  lowercase_     :					int="gelu"						,  lowercase_     :					int=False						,  lowercase_     :					int=True						,  lowercase_     :					Any=0.0_2						,  lowercase_     :					List[Any]=1e-5						,  lowercase_     :					str=True						,  lowercase_     :					str=None						,  lowercase_     :					Tuple=True						,  lowercase_     :					List[str]=10						,  lowercase_     :					List[Any]=8						,  lowercase_     :					int=["stage1", "stage2"]						,  lowercase_     :					List[str]=[1, 2]						,  ):
								UpperCamelCase__		:    List[str]         =parent
								UpperCamelCase__		:    Any         =batch_size
								UpperCamelCase__		:    int         =image_size
								UpperCamelCase__		:    str         =patch_size
								UpperCamelCase__		:    List[Any]         =num_channels
								UpperCamelCase__		:    Dict         =embed_dim
								UpperCamelCase__		:    Tuple         =depths
								UpperCamelCase__		:    List[Any]         =num_heads
								UpperCamelCase__		:    Union[str, Any]         =window_size
								UpperCamelCase__		:    Dict         =mlp_ratio
								UpperCamelCase__		:    Optional[int]         =qkv_bias
								UpperCamelCase__		:    Tuple         =hidden_dropout_prob
								UpperCamelCase__		:    Dict         =attention_probs_dropout_prob
								UpperCamelCase__		:    int         =drop_path_rate
								UpperCamelCase__		:    Tuple         =hidden_act
								UpperCamelCase__		:    str         =use_absolute_embeddings
								UpperCamelCase__		:    Union[str, Any]         =patch_norm
								UpperCamelCase__		:    str         =layer_norm_eps
								UpperCamelCase__		:    Tuple         =initializer_range
								UpperCamelCase__		:    List[str]         =is_training
								UpperCamelCase__		:    int         =scope
								UpperCamelCase__		:    int         =use_labels
								UpperCamelCase__		:    Any         =type_sequence_label_size
								UpperCamelCase__		:    Tuple         =encoder_stride
								UpperCamelCase__		:    str         =out_features
								UpperCamelCase__		:    Tuple         =out_indices






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								UpperCamelCase__		:    Union[str, Any]         =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

								UpperCamelCase__		:    Optional[Any]         =None
								if self.use_labels:
													UpperCamelCase__		:    Dict         =ids_tensor([self.batch_size]						,  self.type_sequence_label_size						)

								UpperCamelCase__		:    Dict         =self.get_config()

								return config, pixel_values, labels






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								return SwinConfig(
								    image_size=self.image_size						,  patch_size=self.patch_size						,  num_channels=self.num_channels						,  embed_dim=self.embed_dim						,  depths=self.depths						,  num_heads=self.num_heads						,  window_size=self.window_size						,  mlp_ratio=self.mlp_ratio						,  qkv_bias=self.qkv_bias						,  hidden_dropout_prob=self.hidden_dropout_prob						,  attention_probs_dropout_prob=self.attention_probs_dropout_prob						,  drop_path_rate=self.drop_path_rate						,  hidden_act=self.hidden_act						,  use_absolute_embeddings=self.use_absolute_embeddings						,  path_norm=self.patch_norm						,  layer_norm_eps=self.layer_norm_eps						,  initializer_range=self.initializer_range						,  encoder_stride=self.encoder_stride						,  out_features=self.out_features						,  out_indices=self.out_indices						,  )






			def    _lowerCAmelCase			(							self     :					Optional[Any]						,  lowercase_     :					Optional[Any]						,  lowercase_     :					List[Any]						,  lowercase_     :					Optional[int]						):
								UpperCamelCase__		:    Optional[Any]         =SwinModel(config=lowercase_						)
								model.to(lowercase_						)
								model.eval()
								UpperCamelCase__		:    List[Any]         =model(lowercase_						)

								UpperCamelCase__		:    List[Any]         =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
								UpperCamelCase__		:    Tuple         =int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

								self.parent.assertEqual(result.last_hidden_state.shape						,  (self.batch_size, expected_seq_len, expected_dim)						)






			def    _lowerCAmelCase			(							self     :					str						,  lowercase_     :					int						,  lowercase_     :					List[Any]						,  lowercase_     :					Tuple						):
								UpperCamelCase__		:    List[str]         =SwinBackbone(config=lowercase_						)
								model.to(lowercase_						)
								model.eval()
								UpperCamelCase__		:    Union[str, Any]         =model(lowercase_						)

								# verify hidden states
								self.parent.assertEqual(len(result.feature_maps						)						,  len(config.out_features						)						)
								self.parent.assertListEqual(list(result.feature_maps[0].shape						)						,  [self.batch_size, model.channels[0], 16, 16]						)

								# verify channels
								self.parent.assertEqual(len(model.channels						)						,  len(config.out_features						)						)

								# verify backbone works with out_features=None
								UpperCamelCase__		:    Dict         =None
								UpperCamelCase__		:    Any         =SwinBackbone(config=lowercase_						)
								model.to(lowercase_						)
								model.eval()
								UpperCamelCase__		:    str         =model(lowercase_						)

								# verify feature maps
								self.parent.assertEqual(len(result.feature_maps						)						,  1						)
								self.parent.assertListEqual(list(result.feature_maps[0].shape						)						,  [self.batch_size, model.channels[-1], 4, 4]						)

								# verify channels
								self.parent.assertEqual(len(model.channels						)						,  1						)






			def    _lowerCAmelCase			(							self     :					Tuple						,  lowercase_     :					Optional[int]						,  lowercase_     :					Union[str, Any]						,  lowercase_     :					Optional[Any]						):
								UpperCamelCase__		:    str         =SwinForMaskedImageModeling(config=lowercase_						)
								model.to(lowercase_						)
								model.eval()
								UpperCamelCase__		:    Any         =model(lowercase_						)
								self.parent.assertEqual(
								    result.logits.shape						,  (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

								# test greyscale images
								UpperCamelCase__		:    Dict         =1
								UpperCamelCase__		:    Any         =SwinForMaskedImageModeling(lowercase_						)
								model.to(lowercase_						)
								model.eval()

								UpperCamelCase__		:    List[str]         =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
								UpperCamelCase__		:    Union[str, Any]         =model(lowercase_						)
								self.parent.assertEqual(result.logits.shape						,  (self.batch_size, 1, self.image_size, self.image_size)						)






			def    _lowerCAmelCase			(							self     :					List[Any]						,  lowercase_     :					Union[str, Any]						,  lowercase_     :					List[str]						,  lowercase_     :					List[Any]						):
								UpperCamelCase__		:    int         =self.type_sequence_label_size
								UpperCamelCase__		:    Dict         =SwinForImageClassification(lowercase_						)
								model.to(lowercase_						)
								model.eval()
								UpperCamelCase__		:    List[str]         =model(lowercase_						,  labels=lowercase_						)
								self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.type_sequence_label_size)						)

								# test greyscale images
								UpperCamelCase__		:    List[str]         =1
								UpperCamelCase__		:    Optional[int]         =SwinForImageClassification(lowercase_						)
								model.to(lowercase_						)
								model.eval()

								UpperCamelCase__		:    Tuple         =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
								UpperCamelCase__		:    Union[str, Any]         =model(lowercase_						)
								self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.type_sequence_label_size)						)






			def    _lowerCAmelCase			(							self     :					Tuple						):
								UpperCamelCase__		:    Union[str, Any]         =self.prepare_config_and_inputs()
								(
								    (
								    UpperCamelCase__
								)  ,			(
								    UpperCamelCase__
								)  ,			(
								    UpperCamelCase__
								)  ,			
								)		:    Dict         =config_and_inputs
								UpperCamelCase__		:    Union[str, Any]         ={'''pixel_values''': pixel_values}
								return config, inputs_dict



@require_torch
class     __a   (      snake_case__,    snake_case__,    unittest.TestCase    ):

			"""simple docstring"""

			SCREAMING_SNAKE_CASE_						     =						(
			    (
			        SwinModel,
			        SwinBackbone,
			        SwinForImageClassification,
			        SwinForMaskedImageModeling,
			    )
			    if is_torch_available()
			    else ()
			)
			SCREAMING_SNAKE_CASE_						     =						(
			    {'feature-extraction': SwinModel, 'image-classification': SwinForImageClassification}
			    if is_torch_available()
			    else {}
			)
			SCREAMING_SNAKE_CASE_						     =						True

			SCREAMING_SNAKE_CASE_						     =						False
			SCREAMING_SNAKE_CASE_						     =						False
			SCREAMING_SNAKE_CASE_						     =						False






			def    _lowerCAmelCase			(							self     :					int						):
								UpperCamelCase__		:    Tuple         =SwinModelTester(self						)
								UpperCamelCase__		:    Any         =ConfigTester(self						,  config_class=lowercase_						,  embed_dim=37						)






			def    _lowerCAmelCase			(							self     :					Any						):
								self.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()






			def    _lowerCAmelCase			(							self     :					str						):
								return






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								UpperCamelCase__		:    List[Any]         =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowercase_						)






			@unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.'''						)
			def    _lowerCAmelCase			(							self     :					Union[str, Any]						):
								pass






			def    _lowerCAmelCase			(							self     :					int						):
								super().test_training_gradient_checkpointing()






			def    _lowerCAmelCase			(							self     :					Tuple						):
								UpperCamelCase__		:    Union[str, Any]         =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_backbone(*lowercase_						)






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								UpperCamelCase__		:    Dict         =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_						)






			def    _lowerCAmelCase			(							self     :					Tuple						):
								UpperCamelCase__		:    Union[str, Any]         =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowercase_						)






			@unittest.skip(reason='''Swin does not use inputs_embeds'''						)
			def    _lowerCAmelCase			(							self     :					Optional[Any]						):
								pass






			@unittest.skip(reason='''Swin Transformer does not use feedforward chunking'''						)
			def    _lowerCAmelCase			(							self     :					List[str]						):
								pass






			def    _lowerCAmelCase			(							self     :					Any						):
								UpperCamelCase__  ,			UpperCamelCase__		:    Dict         =self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													UpperCamelCase__		:    Dict         =model_class(lowercase_						)
													self.assertIsInstance(model.get_input_embeddings()						,  (nn.Module)						)
													UpperCamelCase__		:    Union[str, Any]         =model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowercase_						,  nn.Linear						)						)






			def    _lowerCAmelCase			(							self     :					List[Any]						):
								UpperCamelCase__  ,			UpperCamelCase__		:    Dict         =self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													UpperCamelCase__		:    List[str]         =model_class(lowercase_						)
													UpperCamelCase__		:    str         =inspect.signature(model.forward						)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													UpperCamelCase__		:    Union[str, Any]         =[*signature.parameters.keys()]

													UpperCamelCase__		:    Optional[int]         =['''pixel_values''']
													self.assertListEqual(arg_names[:1]						,  lowercase_						)






			def    _lowerCAmelCase			(							self     :					str						):
								UpperCamelCase__  ,			UpperCamelCase__		:    Any         =self.model_tester.prepare_config_and_inputs_for_common()
								UpperCamelCase__		:    int         =True

								for model_class in self.all_model_classes:
													UpperCamelCase__		:    List[Any]         =True
													UpperCamelCase__		:    Optional[int]         =False
													UpperCamelCase__		:    str         =True
													UpperCamelCase__		:    Union[str, Any]         =model_class(lowercase_						)
													model.to(lowercase_						)
													model.eval()
													with torch.no_grad():
																		UpperCamelCase__		:    Optional[Any]         =model(**self._prepare_for_class(lowercase_						,  lowercase_						)						)
													UpperCamelCase__		:    List[str]         =outputs.attentions
													UpperCamelCase__		:    List[str]         =len(self.model_tester.depths						)
													self.assertEqual(len(lowercase_						)						,  lowercase_						)

													# check that output_attentions also work using config
													del inputs_dict["output_attentions"]
													UpperCamelCase__		:    List[Any]         =True
													UpperCamelCase__		:    Tuple         =config.window_size**2
													UpperCamelCase__		:    List[str]         =model_class(lowercase_						)
													model.to(lowercase_						)
													model.eval()
													with torch.no_grad():
																		UpperCamelCase__		:    Any         =model(**self._prepare_for_class(lowercase_						,  lowercase_						)						)
													UpperCamelCase__		:    str         =outputs.attentions
													self.assertEqual(len(lowercase_						)						,  lowercase_						)

													self.assertListEqual(
													    list(attentions[0].shape[-3:]						)						,  [self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,  )
													UpperCamelCase__		:    int         =len(lowercase_						)

													# Check attention is always last and order is fine
													UpperCamelCase__		:    List[str]         =True
													UpperCamelCase__		:    Dict         =True
													UpperCamelCase__		:    Tuple         =model_class(lowercase_						)
													model.to(lowercase_						)
													model.eval()
													with torch.no_grad():
																		UpperCamelCase__		:    Optional[int]         =model(**self._prepare_for_class(lowercase_						,  lowercase_						)						)

													# also another +1 for reshaped_hidden_states
													UpperCamelCase__		:    List[str]         =1 if model_class.__name__ == '''SwinBackbone''' else 2
													self.assertEqual(out_len + added_hidden_states						,  len(lowercase_						)						)

													UpperCamelCase__		:    Tuple         =outputs.attentions

													self.assertEqual(len(lowercase_						)						,  lowercase_						)

													self.assertListEqual(
													    list(self_attentions[0].shape[-3:]						)						,  [self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,  )






			def    _lowerCAmelCase			(							self     :					Optional[int]						,  lowercase_     :					Any						,  lowercase_     :					Union[str, Any]						,  lowercase_     :					List[Any]						,  lowercase_     :					Union[str, Any]						):
								UpperCamelCase__		:    Tuple         =model_class(lowercase_						)
								model.to(lowercase_						)
								model.eval()

								with torch.no_grad():
													UpperCamelCase__		:    Dict         =model(**self._prepare_for_class(lowercase_						,  lowercase_						)						)

								UpperCamelCase__		:    Tuple         =outputs.hidden_states

								UpperCamelCase__		:    str         =getattr(
								    self.model_tester						,  '''expected_num_hidden_layers'''						,  len(self.model_tester.depths						) + 1						)
								self.assertEqual(len(lowercase_						)						,  lowercase_						)

								# Swin has a different seq_length
								UpperCamelCase__		:    Union[str, Any]         =(
								    config.patch_size
								    if isinstance(config.patch_size						,  collections.abc.Iterable						)
								    else (config.patch_size, config.patch_size)
								)

								UpperCamelCase__		:    Optional[int]         =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]						)						,  [num_patches, self.model_tester.embed_dim]						,  )

								if not model_class.__name__ == "SwinBackbone":
													UpperCamelCase__		:    Union[str, Any]         =outputs.reshaped_hidden_states
													self.assertEqual(len(lowercase_						)						,  lowercase_						)

													UpperCamelCase__  ,			UpperCamelCase__  ,			UpperCamelCase__  ,			UpperCamelCase__		:    Tuple         =reshaped_hidden_states[0].shape
													UpperCamelCase__		:    List[Any]         =(
													    reshaped_hidden_states[0].view(lowercase_						,  lowercase_						,  height * width						).permute(0						,  2						,  1						)
													)
													self.assertListEqual(
													    list(reshaped_hidden_states.shape[-2:]						)						,  [num_patches, self.model_tester.embed_dim]						,  )






			def    _lowerCAmelCase			(							self     :					Tuple						):
								UpperCamelCase__  ,			UpperCamelCase__		:    str         =self.model_tester.prepare_config_and_inputs_for_common()

								UpperCamelCase__		:    Any         =(
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size						,  collections.abc.Iterable						)
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)

								for model_class in self.all_model_classes:
													UpperCamelCase__		:    Dict         =True
													self.check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													UpperCamelCase__		:    Union[str, Any]         =True

													self.check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						)






			def    _lowerCAmelCase			(							self     :					Optional[Any]						):
								UpperCamelCase__  ,			UpperCamelCase__		:    Union[str, Any]         =self.model_tester.prepare_config_and_inputs_for_common()
								UpperCamelCase__		:    str         =3

								UpperCamelCase__		:    int         =(
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size						,  collections.abc.Iterable						)
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)
								UpperCamelCase__		:    str         =(
								    config.patch_size
								    if isinstance(config.patch_size						,  collections.abc.Iterable						)
								    else (config.patch_size, config.patch_size)
								)

								UpperCamelCase__		:    int         =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
								UpperCamelCase__		:    Union[str, Any]         =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

								for model_class in self.all_model_classes:
													UpperCamelCase__		:    Optional[Any]         =True
													self.check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_						,  (padded_height, padded_width)						)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													UpperCamelCase__		:    Optional[Any]         =True
													self.check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_						,  (padded_height, padded_width)						)






			@slow
			def    _lowerCAmelCase			(							self     :					Tuple						):
								for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													UpperCamelCase__		:    Union[str, Any]         =SwinModel.from_pretrained(lowercase_						)
													self.assertIsNotNone(lowercase_						)






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								UpperCamelCase__  ,			UpperCamelCase__		:    List[str]         =self.model_tester.prepare_config_and_inputs_for_common()

								UpperCamelCase__		:    str         =_config_zero_init(lowercase_						)
								for model_class in self.all_model_classes:
													UpperCamelCase__		:    Optional[Any]         =model_class(config=lowercase_						)
													for name, param in model.named_parameters():
																		if "embeddings" not in name and param.requires_grad:
																							self.assertIn(
																							    ((param.data.mean() * 1e9).round() / 1e9).item()						,  [0.0, 1.0]						,  msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''						,  )



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

			"""simple docstring"""

			@cached_property
			def    _lowerCAmelCase			(							self     :					Optional[Any]						):
								return (
								    AutoImageProcessor.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''						)
								    if is_vision_available()
								    else None
								)






			@slow
			def    _lowerCAmelCase			(							self     :					int						):
								UpperCamelCase__		:    Optional[Any]         =SwinForImageClassification.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''						).to(lowercase_						)
								UpperCamelCase__		:    int         =self.default_image_processor

								UpperCamelCase__		:    Dict         =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
								UpperCamelCase__		:    List[Any]         =image_processor(images=lowercase_						,  return_tensors='''pt'''						).to(lowercase_						)

								# forward pass
								with torch.no_grad():
													UpperCamelCase__		:    Optional[int]         =model(**lowercase_						)

								# verify the logits
								UpperCamelCase__		:    Dict         =torch.Size((1, 1000)						)
								self.assertEqual(outputs.logits.shape						,  lowercase_						)
								UpperCamelCase__		:    Union[str, Any]         =torch.tensor([-0.0_9_4_8, -0.6_4_5_4, -0.0_9_2_1]						).to(lowercase_						)
								self.assertTrue(torch.allclose(outputs.logits[0, :3]						,  lowercase_						,  atol=1e-4						)						)



@require_torch
class     __a   (      unittest.TestCase,    snake_case__    ):

			"""simple docstring"""

			SCREAMING_SNAKE_CASE_						     =						(SwinBackbone,) if is_torch_available() else ()
			SCREAMING_SNAKE_CASE_						     =						SwinConfig






			def    _lowerCAmelCase			(							self     :					Dict						):
								UpperCamelCase__		:    List[Any]         =SwinModelTester(self						)





"""simple docstring"""





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

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


_SCREAMING_SNAKE_CASE       :  Any        = logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE       :  Optional[int]        = {
    """facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json""",
    # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
}

class     __a   (      snake_case__    ):

			"""simple docstring"""

			SCREAMING_SNAKE_CASE_						     =						'blenderbot'
			SCREAMING_SNAKE_CASE_						     =						['past_key_values']
			SCREAMING_SNAKE_CASE_						     =						{'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}






			def __init__(							self     :					Dict						,  lowercase_     :					Any=8008						,  lowercase_     :					Dict=128						,  lowercase_     :					Tuple=2						,  lowercase_     :					List[Any]=1_0240						,  lowercase_     :					Optional[int]=32						,  lowercase_     :					Optional[Any]=24						,  lowercase_     :					str=1_0240						,  lowercase_     :					Tuple=32						,  lowercase_     :					Optional[int]=0.0						,  lowercase_     :					Optional[int]=0.0						,  lowercase_     :					str=True						,  lowercase_     :					List[str]=True						,  lowercase_     :					Union[str, Any]="gelu"						,  lowercase_     :					List[str]=2560						,  lowercase_     :					Any=0.1						,  lowercase_     :					List[Any]=0.0						,  lowercase_     :					Any=0.0						,  lowercase_     :					Union[str, Any]=0.0_2						,  lowercase_     :					Any=1						,  lowercase_     :					Optional[int]=False						,  lowercase_     :					int=0						,  lowercase_     :					Optional[int]=1						,  lowercase_     :					Any=2						,  lowercase_     :					Any=3						,  lowercase_     :					Dict=2						,  **lowercase_     :					Optional[int]						,  ):
								UpperCamelCase__		:    int         =vocab_size
								UpperCamelCase__		:    List[Any]         =max_position_embeddings
								UpperCamelCase__		:    List[Any]         =d_model
								UpperCamelCase__		:    Union[str, Any]         =encoder_ffn_dim
								UpperCamelCase__		:    Optional[Any]         =encoder_layers
								UpperCamelCase__		:    List[str]         =encoder_attention_heads
								UpperCamelCase__		:    Optional[Any]         =decoder_ffn_dim
								UpperCamelCase__		:    Dict         =decoder_layers
								UpperCamelCase__		:    int         =decoder_attention_heads
								UpperCamelCase__		:    List[Any]         =dropout
								UpperCamelCase__		:    Optional[int]         =attention_dropout
								UpperCamelCase__		:    List[Any]         =activation_dropout
								UpperCamelCase__		:    Dict         =activation_function
								UpperCamelCase__		:    Optional[int]         =init_std
								UpperCamelCase__		:    Optional[int]         =encoder_layerdrop
								UpperCamelCase__		:    Tuple         =decoder_layerdrop
								UpperCamelCase__		:    List[str]         =use_cache
								UpperCamelCase__		:    int         =encoder_layers
								UpperCamelCase__		:    str         =scale_embedding  # scale factor will be sqrt(d_model) if True

								super().__init__(
								    pad_token_id=lowercase_						,  bos_token_id=lowercase_						,  eos_token_id=lowercase_						,  is_encoder_decoder=lowercase_						,  decoder_start_token_id=lowercase_						,  encoder_no_repeat_ngram_size=lowercase_						,  forced_eos_token_id=lowercase_						,  **lowercase_						,  )



class     __a   (      snake_case__    ):

			"""simple docstring"""

			@property
			def    _lowerCAmelCase			(							self     :					List[Any]						):
								if self.task in ["default", "seq2seq-lm"]:
													UpperCamelCase__		:    List[str]         =OrderedDict(
													    [
													        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
													        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
													    ]						)
													if self.use_past:
																		UpperCamelCase__		:    Any         ={0: '''batch'''}
																		UpperCamelCase__		:    Optional[Any]         ={0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
													else:
																		UpperCamelCase__		:    Optional[Any]         ={0: '''batch''', 1: '''decoder_sequence'''}
																		UpperCamelCase__		:    List[str]         ={0: '''batch''', 1: '''decoder_sequence'''}
													if self.use_past:
																		self.fill_with_past_key_values_(lowercase_						,  direction='''inputs'''						)
								elif self.task == "causal-lm":
													UpperCamelCase__		:    Optional[Any]         =OrderedDict(
													    [
													        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
													        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
													    ]						)
													if self.use_past:
																		UpperCamelCase__  ,			UpperCamelCase__		:    str         =self.num_layers
																		for i in range(lowercase_						):
																							UpperCamelCase__		:    Optional[int]         ={0: '''batch''', 2: '''past_sequence + sequence'''}
																							UpperCamelCase__		:    Dict         ={0: '''batch''', 2: '''past_sequence + sequence'''}
								else:
													UpperCamelCase__		:    Any         =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
			# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
			def    _lowerCAmelCase			(							self     :					Tuple						):
								if self.task in ["default", "seq2seq-lm"]:
													UpperCamelCase__		:    List[Any]         =super().outputs
								else:
													UpperCamelCase__		:    List[str]         =super(lowercase_						,  self						).outputs
													if self.use_past:
																		UpperCamelCase__  ,			UpperCamelCase__		:    int         =self.num_layers
																		for i in range(lowercase_						):
																							UpperCamelCase__		:    Dict         ={0: '''batch''', 2: '''past_sequence + sequence'''}
																							UpperCamelCase__		:    Dict         ={0: '''batch''', 2: '''past_sequence + sequence'''}
								return common_outputs






			def    _lowerCAmelCase			(							self     :					Optional[int]						,  lowercase_     :					PreTrainedTokenizer						,  lowercase_     :					int = -1						,  lowercase_     :					int = -1						,  lowercase_     :					bool = False						,  lowercase_     :					Optional[TensorType] = None						,  ):
								UpperCamelCase__		:    List[Any]         =self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
								    lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						)
								# Generate decoder inputs
								UpperCamelCase__		:    List[Any]         =seq_length if not self.use_past else 1
								UpperCamelCase__		:    int         =self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
								    lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						)
								UpperCamelCase__		:    str         ={f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
								UpperCamelCase__		:    str         =dict(**lowercase_						,  **lowercase_						)

								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__		:    Optional[int]         =common_inputs['''input_ids'''].shape
													UpperCamelCase__		:    Any         =common_inputs['''decoder_input_ids'''].shape[1]
													UpperCamelCase__  ,			UpperCamelCase__		:    Union[str, Any]         =self.num_attention_heads
													UpperCamelCase__		:    Any         =(
													    batch,
													    num_encoder_attention_heads,
													    encoder_seq_length,
													    self._config.hidden_size // num_encoder_attention_heads,
													)
													UpperCamelCase__		:    Tuple         =decoder_seq_length
													UpperCamelCase__		:    Optional[Any]         =(
													    batch,
													    num_decoder_attention_heads,
													    decoder_past_length,
													    self._config.hidden_size // num_decoder_attention_heads,
													)
													UpperCamelCase__		:    Union[str, Any]         =torch.cat(
													    [common_inputs['''decoder_attention_mask'''], torch.ones(lowercase_						,  lowercase_						)]						,  dim=1						)
													UpperCamelCase__		:    Any         =[]
													UpperCamelCase__  ,			UpperCamelCase__		:    Union[str, Any]         =self.num_layers

													for _ in range(lowercase_						):
																		common_inputs["past_key_values"].append(
																		    (
																		        torch.zeros(lowercase_						),
																		        torch.zeros(lowercase_						),
																		        torch.zeros(lowercase_						),
																		        torch.zeros(lowercase_						),
																		    )						)
								return common_inputs






			def    _lowerCAmelCase			(							self     :					Tuple						,  lowercase_     :					PreTrainedTokenizer						,  lowercase_     :					int = -1						,  lowercase_     :					int = -1						,  lowercase_     :					bool = False						,  lowercase_     :					Optional[TensorType] = None						,  ):
								UpperCamelCase__		:    str         =self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
								    lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						)

								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__		:    Tuple         =common_inputs['''input_ids'''].shape
													UpperCamelCase__		:    List[Any]         =seqlen
													UpperCamelCase__  ,			UpperCamelCase__		:    Any         =self.num_layers
													UpperCamelCase__  ,			UpperCamelCase__		:    Tuple         =self.num_attention_heads
													UpperCamelCase__		:    Optional[int]         =(
													    batch,
													    num_encoder_attention_heads,
													    past_key_values_length,
													    self._config.hidden_size // num_encoder_attention_heads,
													)
													UpperCamelCase__		:    Union[str, Any]         =common_inputs['''attention_mask'''].dtype
													UpperCamelCase__		:    int         =torch.cat(
													    [common_inputs['''attention_mask'''], torch.ones(lowercase_						,  lowercase_						,  dtype=lowercase_						)]						,  dim=1						)
													UpperCamelCase__		:    List[str]         =[
													    (torch.zeros(lowercase_						), torch.zeros(lowercase_						)) for _ in range(lowercase_						)
													]
								return common_inputs






			def    _lowerCAmelCase			(							self     :					Tuple						,  lowercase_     :					PreTrainedTokenizer						,  lowercase_     :					int = -1						,  lowercase_     :					int = -1						,  lowercase_     :					bool = False						,  lowercase_     :					Optional[TensorType] = None						,  ):
								# Copied from OnnxConfig.generate_dummy_inputs
								# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
								# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
								UpperCamelCase__		:    str         =compute_effective_axis_dimension(
								    lowercase_						,  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__		:    Union[str, Any]         =tokenizer.num_special_tokens_to_add(lowercase_						)
								UpperCamelCase__		:    str         =compute_effective_axis_dimension(
								    lowercase_						,  fixed_dimension=OnnxConfig.default_fixed_sequence						,  num_token_to_add=lowercase_						)

								# Generate dummy inputs according to compute batch and sequence
								UpperCamelCase__		:    Union[str, Any]         =[''' '''.join([tokenizer.unk_token]						) * seq_length] * batch_size
								UpperCamelCase__		:    Tuple         =dict(tokenizer(lowercase_						,  return_tensors=lowercase_						)						)
								return common_inputs






			def    _lowerCAmelCase			(							self     :					int						,  lowercase_     :					PreTrainedTokenizer						,  lowercase_     :					int = -1						,  lowercase_     :					int = -1						,  lowercase_     :					bool = False						,  lowercase_     :					Optional[TensorType] = None						,  ):
								if self.task in ["default", "seq2seq-lm"]:
													UpperCamelCase__		:    Tuple         =self._generate_dummy_inputs_for_default_and_seqaseq_lm(
													    lowercase_						,  batch_size=lowercase_						,  seq_length=lowercase_						,  is_pair=lowercase_						,  framework=lowercase_						)

								elif self.task == "causal-lm":
													UpperCamelCase__		:    Union[str, Any]         =self._generate_dummy_inputs_for_causal_lm(
													    lowercase_						,  batch_size=lowercase_						,  seq_length=lowercase_						,  is_pair=lowercase_						,  framework=lowercase_						)
								else:
													UpperCamelCase__		:    Optional[int]         =self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
													    lowercase_						,  batch_size=lowercase_						,  seq_length=lowercase_						,  is_pair=lowercase_						,  framework=lowercase_						)

								return common_inputs






			def    _lowerCAmelCase			(							self     :					List[str]						,  lowercase_     :					int						,  lowercase_     :					Union[str, Any]						,  lowercase_     :					Optional[Any]						,  lowercase_     :					List[Any]						):
								if self.task in ["default", "seq2seq-lm"]:
													UpperCamelCase__		:    Optional[int]         =super()._flatten_past_key_values_(lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						)
								else:
													UpperCamelCase__		:    Optional[int]         =super(lowercase_						,  self						)._flatten_past_key_values_(
													    lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						)






			def    _lowerCAmelCase			(							self     :					List[str]						,  lowercase_     :					Mapping[str, Mapping[int, str]]						,  lowercase_     :					str						):
								if direction not in ["inputs", "outputs"]:
													raise ValueError(f'''direction must either be "inputs" or "outputs", but {direction} was given'''						)

								UpperCamelCase__		:    Optional[int]         ='''past_key_values''' if direction == '''inputs''' else '''present'''
								UpperCamelCase__  ,			UpperCamelCase__		:    Optional[int]         =self.num_layers

								UpperCamelCase__		:    List[str]         ='''past_encoder_sequence'''
								UpperCamelCase__		:    Optional[int]         ='''past_decoder_sequence''' if direction == '''inputs''' else '''past_decoder_sequence + sequence'''

								for i in range(lowercase_						):
													UpperCamelCase__		:    Tuple         ={0: '''batch''', 2: decoder_sequence}
													UpperCamelCase__		:    Union[str, Any]         ={0: '''batch''', 2: decoder_sequence}
													UpperCamelCase__		:    str         ={0: '''batch''', 2: encoder_sequence}
													UpperCamelCase__		:    List[Any]         ={0: '''batch''', 2: encoder_sequence}


