


"""simple docstring"""




import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
    datefmt='%m/%d/%Y %H:%M:%S',
    level=logging.INFO,
)
__magic_name__	:   Any          =							logging.getLogger(__name__)

__magic_name__	:   str          =							int(1_0_0_0_0)  # Hardcoded max length to avoid infinite loop

__magic_name__	:   List[Any]          =							{
    'gpt2': (GPTaLMHeadModel, GPTaTokenizer),
    'ctrl': (CTRLLMHeadModel, CTRLTokenizer),
    'openai-gpt': (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    'xlnet': (XLNetLMHeadModel, XLNetTokenizer),
    'transfo-xl': (TransfoXLLMHeadModel, TransfoXLTokenizer),
    'xlm': (XLMWithLMHeadModel, XLMTokenizer),
    'gptj': (GPTJForCausalLM, AutoTokenizer),
    'bloom': (BloomForCausalLM, BloomTokenizerFast),
    'llama': (LlamaForCausalLM, LlamaTokenizer),
    'opt': (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
__magic_name__	:   Any          =							'In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>'





def 			a_   (  lowercase__   :Optional[Any]    ):
			np.random.seed(args.seed    )
			torch.manual_seed(args.seed    )
			if args.n_gpu > 0:
						torch.cuda.manual_seed_all(args.seed    )





def 			a_   (  lowercase__   :List[str], lowercase__   :Tuple, lowercase__   :Optional[int], lowercase__   :Dict    ):
			if args.temperature > 0.7:
						logger.info("""CTRL typically works better with lower temperatures (and lower top_k)."""    )

			__lowerCamelCase     :   int        =			tokenizer.encode(UpperCamelCase__, add_special_tokens=UpperCamelCase__    )
			if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()    ):
						logger.info("""WARNING! You are not starting your generation from a control code so you won't get good results"""    )
			return prompt_text





def 			a_   (  lowercase__   :Optional[Any], lowercase__   :List[str], lowercase__   :Optional[int], lowercase__   :List[str]    ):
			# kwargs = {"language": None, "mask_token_id": None}

			# Set the language
			__lowerCamelCase     :   Union[str, Any]        =			hasattr(model.config, """use_lang_emb"""    ) and model.config.use_lang_emb
			if hasattr(model.config, """lang2id"""    ) and use_lang_emb:
						__lowerCamelCase     :   Optional[Any]        =			model.config.langaid.keys()
						if args.xlm_language in available_languages:
									__lowerCamelCase     :   Tuple        =			args.xlm_language
						else:
									__lowerCamelCase     :   Optional[int]        =			None
									while language not in available_languages:
												__lowerCamelCase     :   Tuple        =			input("""Using XLM. Select language in """ + str(list(UpperCamelCase__    )    ) + """ >>> """    )

						__lowerCamelCase     :   List[Any]        =			model.config.langaid[language]
						# kwargs["language"] = tokenizer.lang2id[language]

			# TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
			# XLM masked-language modeling (MLM) models need masked token
			# is_xlm_mlm = "mlm" in args.model_name_or_path
			# if is_xlm_mlm:
			#     kwargs["mask_token_id"] = tokenizer.mask_token_id

			return prompt_text





def 			a_   (  lowercase__   :Optional[Any], lowercase__   :Any, lowercase__   :Dict, lowercase__   :List[Any]    ):
			__lowerCamelCase     :   List[Any]        =			args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
			__lowerCamelCase     :   Optional[int]        =			prefix + prompt_text
			return prompt_text





def 			a_   (  lowercase__   :Union[str, Any], lowercase__   :List[str], lowercase__   :List[str], lowercase__   :Tuple    ):
			__lowerCamelCase     :   Optional[Any]        =			args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
			__lowerCamelCase     :   Any        =			prefix + prompt_text
			return prompt_text


__magic_name__	:   int          =							{
    'ctrl': prepare_ctrl_input,
    'xlm': prepare_xlm_input,
    'xlnet': prepare_xlnet_input,
    'transfo-xl': prepare_transfoxl_input,
}





def 			a_   (  lowercase__   :Dict, lowercase__   :int    ):
			if length < 0 and max_sequence_length > 0:
						__lowerCamelCase     :   Optional[int]        =			max_sequence_length
			elif 0 < max_sequence_length < length:
						__lowerCamelCase     :   Tuple        =			max_sequence_length  # No generation bigger than model size
			elif length < 0:
						__lowerCamelCase     :   Optional[Any]        =			MAX_LENGTH  # avoid infinite loop
			return length





def 			a_   (  lowercase__   :Tuple    ):
			__lowerCamelCase     :   Dict        =			None
			if hasattr(UpperCamelCase__, """hidden_size"""    ):
						__lowerCamelCase     :   str        =			model_config.hidden_size
			elif hasattr(UpperCamelCase__, """n_embed"""    ):
						__lowerCamelCase     :   List[str]        =			model_config.n_embed
			elif hasattr(UpperCamelCase__, """n_embd"""    ):
						__lowerCamelCase     :   Optional[Any]        =			model_config.n_embd

			__lowerCamelCase     :   Optional[Any]        =			None
			if hasattr(UpperCamelCase__, """num_attention_heads"""    ):
						__lowerCamelCase     :   Tuple        =			model_config.num_attention_heads
			elif hasattr(UpperCamelCase__, """n_head"""    ):
						__lowerCamelCase     :   Any        =			model_config.n_head

			if embedding_size is None or num_head is None or num_head == 0:
						raise ValueError("""Check the model config"""    )

			__lowerCamelCase     :   int        =			int(embedding_size / num_head    )
			if hasattr(UpperCamelCase__, """n_layer"""    ):
						__lowerCamelCase     :   Tuple        =			model_config.n_layer
			elif hasattr(UpperCamelCase__, """num_hidden_layers"""    ):
						__lowerCamelCase     :   str        =			model_config.num_hidden_layers
			else:
						raise ValueError("""Number of hidden layers couldn't be determined from the model config"""    )

			return num_layer, num_head, num_embedding_size_per_head





def 			a_   (  lowercase__   :Optional[int], lowercase__   :Dict, lowercase__   :Tuple    ):
			__lowerCamelCase     :   Optional[int]        =			sparse_model_config(model.config    )
			if model.config.model_type == "bloom":
						__lowerCamelCase     :   Any        =			tuple(
						    (
						        torch.empty(int(num_attention_heads * batch_size    ), UpperCamelCase__, UpperCamelCase__    )
						        .to(model.dtype    )
						        .to(model.device    ),
						        torch.empty(int(num_attention_heads * batch_size    ), UpperCamelCase__, UpperCamelCase__    )
						        .to(model.dtype    )
						        .to(model.device    ),
						    )
						    for _ in range(UpperCamelCase__    )    )
			else:
						__lowerCamelCase     :   Union[str, Any]        =			tuple(
						    (
						        torch.empty(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__    )
						        .to(model.dtype    )
						        .to(model.device    ),
						        torch.empty(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__    )
						        .to(model.dtype    )
						        .to(model.device    ),
						    )
						    for _ in range(UpperCamelCase__    )    )
			return past_key_values





def 			a_   (  lowercase__   :Optional[Any], lowercase__   :List[str], lowercase__   :Any    ):
			__lowerCamelCase     :   List[str]        =			len(UpperCamelCase__    )
			__lowerCamelCase     :   Tuple        =			tokenizer.batch_encode_plus(UpperCamelCase__, return_tensors="""pt"""    )
			__lowerCamelCase     :   Any        =			dummy_input.to(model.device    )
			if model.config.use_cache:
						__lowerCamelCase     :   Tuple        =			generate_past_key_values(UpperCamelCase__, UpperCamelCase__, 1    )
			__lowerCamelCase     :   Any        =			torch.cat(
			    [
			        torch.zeros(dummy_input["""attention_mask"""].shape[0], 1    )
			        .to(dummy_input["""attention_mask"""].dtype    )
			        .to(model.device    ),
			        dummy_input["""attention_mask"""],
			    ], -1, )
			return dummy_input




class  __snake_case      (lowerCamelCase     ):
							__a				   =					('''_optimized''', '''_default''')




							def __init__(    self:						Any    ,       A_:						Tuple    ,       A_:						Dict      ):
										__lowerCamelCase     :   Optional[int]        =			optimized
										__lowerCamelCase     :   Optional[Any]        =			default




							def __call__(    self:						Optional[Any]    ,       *A_:						str    ,       **A_:						int      ):
										if kwargs["past_key_values"] is None and self._default.config.use_cache:
													__lowerCamelCase     :   Optional[Any]        =			generate_past_key_values(self._default    ,       kwargs["""input_ids"""].shape[0]    ,       0      )
										kwargs.pop("""position_ids"""    ,       __lowerCamelCase      )
										for k in list(kwargs.keys()      ):
													if kwargs[k] is None or isinstance(kwargs[k]    ,       __lowerCamelCase      ):
																kwargs.pop(__lowerCamelCase      )
										__lowerCamelCase     :   List[Any]        =			self._optimized(**__lowerCamelCase      )
										__lowerCamelCase     :   Any        =			outputs[0]
										__lowerCamelCase     :   Any        =			outputs[1]
										__lowerCamelCase     :   Tuple        =			CausalLMOutputWithPast(
										    loss=__lowerCamelCase    ,       logits=__lowerCamelCase    ,       past_key_values=__lowerCamelCase    ,       hidden_states=__lowerCamelCase    ,       attentions=__lowerCamelCase    ,       )
										return fixed_output




							def __getattr__(    self:						Optional[Any]    ,       A_:						List[Any]      ):
										return getattr(self._default    ,       __lowerCamelCase      )




							def      __a      (    self:						Optional[int]    ,       A_:						str    ,       A_:						List[str]=None    ,       A_:						List[str]=None    ,       A_:						str=None    ,       **A_:						Optional[Any]      ):
										return self._default.prepare_inputs_for_generation(
										    __lowerCamelCase    ,       past_key_values=__lowerCamelCase    ,       inputs_embeds=__lowerCamelCase    ,       use_cache=__lowerCamelCase    ,       **__lowerCamelCase      )




							def      __a      (    self:						Dict    ,       A_:						Tuple    ,       A_:						Optional[Any]      ):
										return self._default._reorder_cache(__lowerCamelCase    ,       __lowerCamelCase      )





def 			a_   (  ):
			__lowerCamelCase     :   Union[str, Any]        =			argparse.ArgumentParser()
			parser.add_argument(
			    """--model_type""", default=UpperCamelCase__, type=UpperCamelCase__, required=UpperCamelCase__, help="""Model type selected in the list: """ + """, """.join(MODEL_CLASSES.keys()    ), )
			parser.add_argument(
			    """--model_name_or_path""", default=UpperCamelCase__, type=UpperCamelCase__, required=UpperCamelCase__, help="""Path to pre-trained model or shortcut name selected in the list: """ + """, """.join(MODEL_CLASSES.keys()    ), )

			parser.add_argument("""--prompt""", type=UpperCamelCase__, default=""""""    )
			parser.add_argument("""--length""", type=UpperCamelCase__, default=20    )
			parser.add_argument("""--stop_token""", type=UpperCamelCase__, default=UpperCamelCase__, help="""Token at which text generation is stopped"""    )

			parser.add_argument(
			    """--temperature""", type=UpperCamelCase__, default=1.0, help="""temperature of 1.0 has no effect, lower tend toward greedy sampling""", )
			parser.add_argument(
			    """--repetition_penalty""", type=UpperCamelCase__, default=1.0, help="""primarily useful for CTRL model; in that case, use 1.2"""    )
			parser.add_argument("""--k""", type=UpperCamelCase__, default=0    )
			parser.add_argument("""--p""", type=UpperCamelCase__, default=0.9    )

			parser.add_argument("""--prefix""", type=UpperCamelCase__, default="""""", help="""Text added prior to input."""    )
			parser.add_argument("""--padding_text""", type=UpperCamelCase__, default="""""", help="""Deprecated, the use of `--prefix` is preferred."""    )
			parser.add_argument("""--xlm_language""", type=UpperCamelCase__, default="""""", help="""Optional language when used with the XLM model."""    )

			parser.add_argument("""--seed""", type=UpperCamelCase__, default=42, help="""random seed for initialization"""    )
			parser.add_argument("""--no_cuda""", action="""store_true""", help="""Avoid using CUDA when available"""    )
			parser.add_argument("""--num_return_sequences""", type=UpperCamelCase__, default=1, help="""The number of samples to generate."""    )
			parser.add_argument(
			    """--fp16""", action="""store_true""", help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""", )
			parser.add_argument("""--jit""", action="""store_true""", help="""Whether or not to use jit trace to accelerate inference"""    )
			__lowerCamelCase     :   Union[str, Any]        =			parser.parse_args()

			__lowerCamelCase     :   List[str]        =			torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""    )
			__lowerCamelCase     :   Any        =			0 if args.no_cuda else torch.cuda.device_count()

			logger.warning(f'device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}'    )

			set_seed(UpperCamelCase__    )

			# Initialize the model and tokenizer
			try:
						__lowerCamelCase     :   Tuple        =			args.model_type.lower()
						__lowerCamelCase     :   str        =			MODEL_CLASSES[args.model_type]
			except KeyError:
						raise KeyError("""the model {} you specified is not supported. You are welcome to add it and open a PR :)"""    )

			__lowerCamelCase     :   Tuple        =			tokenizer_class.from_pretrained(args.model_name_or_path    )
			if tokenizer.pad_token is None:
						__lowerCamelCase     :   str        =			tokenizer.eos_token
			__lowerCamelCase     :   Union[str, Any]        =			model_class.from_pretrained(args.model_name_or_path    )
			model.to(args.device    )

			if args.fpaa:
						model.half()
			__lowerCamelCase     :   Dict        =			getattr(model.config, """max_position_embeddings""", 0    )
			__lowerCamelCase     :   List[Any]        =			adjust_length_to_model(args.length, max_sequence_length=UpperCamelCase__    )
			logger.info(UpperCamelCase__    )

			__lowerCamelCase     :   List[Any]        =			args.prompt if args.prompt else input("""Model prompt >>> """    )

			# Different models need different input formatting and/or extra arguments
			__lowerCamelCase     :   List[str]        =			args.model_type in PREPROCESSING_FUNCTIONS.keys()
			if requires_preprocessing:
						__lowerCamelCase     :   List[Any]        =			PREPROCESSING_FUNCTIONS.get(args.model_type    )
						__lowerCamelCase     :   Tuple        =			prepare_input(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__    )

						if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
									__lowerCamelCase     :   Tuple        =			{"add_space_before_punct_symbol": True}
						else:
									__lowerCamelCase     :   Dict        =			{}

						__lowerCamelCase     :   List[Any]        =			tokenizer.encode(
						    UpperCamelCase__, add_special_tokens=UpperCamelCase__, return_tensors="""pt""", **UpperCamelCase__    )
			else:
						__lowerCamelCase     :   int        =			args.prefix if args.prefix else args.padding_text
						__lowerCamelCase     :   Any        =			tokenizer.encode(prefix + prompt_text, add_special_tokens=UpperCamelCase__, return_tensors="""pt"""    )
			__lowerCamelCase     :   str        =			encoded_prompt.to(args.device    )

			if encoded_prompt.size()[-1] == 0:
						__lowerCamelCase     :   Union[str, Any]        =			None
			else:
						__lowerCamelCase     :   Any        =			encoded_prompt

			if args.jit:
						__lowerCamelCase     :   Union[str, Any]        =			["enable jit"]
						__lowerCamelCase     :   List[Any]        =			prepare_jit_inputs(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__    )
						torch._C._jit_set_texpr_fuser_enabled(UpperCamelCase__    )
						__lowerCamelCase     :   Union[str, Any]        =			False
						if hasattr(UpperCamelCase__, """forward"""    ):
									__lowerCamelCase     :   List[Any]        =			inspect.signature(model.forward    )
						else:
									__lowerCamelCase     :   Union[str, Any]        =			inspect.signature(model.__call__    )
						__lowerCamelCase     :   str        =			tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(UpperCamelCase__, UpperCamelCase__    ) is not None    )
						__lowerCamelCase     :   Any        =			torch.jit.trace(UpperCamelCase__, UpperCamelCase__, strict=UpperCamelCase__    )
						__lowerCamelCase     :   Dict        =			torch.jit.freeze(traced_model.eval()    )
						traced_model(*UpperCamelCase__    )
						traced_model(*UpperCamelCase__    )

						__lowerCamelCase     :   int        =			_ModelFallbackWrapper(UpperCamelCase__, UpperCamelCase__    )

			__lowerCamelCase     :   Union[str, Any]        =			model.generate(
			    input_ids=UpperCamelCase__, max_length=args.length + len(encoded_prompt[0]    ), temperature=args.temperature, top_k=args.k, top_p=args.p, repetition_penalty=args.repetition_penalty, do_sample=UpperCamelCase__, num_return_sequences=args.num_return_sequences, )

			# Remove the batch dimension when returning multiple sequences
			if len(output_sequences.shape    ) > 2:
						output_sequences.squeeze_()

			__lowerCamelCase     :   List[str]        =			[]

			for generated_sequence_idx, generated_sequence in enumerate(UpperCamelCase__    ):
						print(f'=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==='    )
						__lowerCamelCase     :   Optional[Any]        =			generated_sequence.tolist()

						# Decode text
						__lowerCamelCase     :   List[Any]        =			tokenizer.decode(UpperCamelCase__, clean_up_tokenization_spaces=UpperCamelCase__    )

						# Remove all text after the stop token
						__lowerCamelCase     :   int        =			text[: text.find(args.stop_token    ) if args.stop_token else None]

						# Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
						__lowerCamelCase     :   int        =			(
						    prompt_text + text[len(tokenizer.decode(encoded_prompt[0], clean_up_tokenization_spaces=UpperCamelCase__    )    ) :]
						)

						generated_sequences.append(UpperCamelCase__    )
						print(UpperCamelCase__    )

			return generated_sequences


if __name__ == "__main__":
					main()








"""simple docstring"""




import inspect
import unittest

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

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 SwinaSRForImageSuperResolution, SwinaSRModel
					from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
					from PIL import Image

					from transformers import SwinaSRImageProcessor




class  __snake_case      :




							def __init__(    self:						str    ,       A_:						str    ,       A_:						int=13    ,       A_:						Any=32    ,       A_:						int=1    ,       A_:						Dict=3    ,       A_:						Union[str, Any]=16    ,       A_:						List[str]=[1, 2, 1]    ,       A_:						Dict=[2, 2, 4]    ,       A_:						List[Any]=2    ,       A_:						List[Any]=2.0    ,       A_:						str=True    ,       A_:						Dict=0.0    ,       A_:						Optional[Any]=0.0    ,       A_:						Tuple=0.1    ,       A_:						str="gelu"    ,       A_:						Optional[Any]=False    ,       A_:						Dict=True    ,       A_:						Tuple=0.02    ,       A_:						List[Any]=1E-5    ,       A_:						Dict=True    ,       A_:						Any=None    ,       A_:						Optional[Any]=False    ,       A_:						Optional[int]=2    ,       ):
										__lowerCamelCase        =			parent
										__lowerCamelCase        =			batch_size
										__lowerCamelCase        =			image_size
										__lowerCamelCase        =			patch_size
										__lowerCamelCase        =			num_channels
										__lowerCamelCase        =			embed_dim
										__lowerCamelCase        =			depths
										__lowerCamelCase        =			num_heads
										__lowerCamelCase        =			window_size
										__lowerCamelCase        =			mlp_ratio
										__lowerCamelCase        =			qkv_bias
										__lowerCamelCase        =			hidden_dropout_prob
										__lowerCamelCase        =			attention_probs_dropout_prob
										__lowerCamelCase        =			drop_path_rate
										__lowerCamelCase        =			hidden_act
										__lowerCamelCase        =			use_absolute_embeddings
										__lowerCamelCase        =			patch_norm
										__lowerCamelCase        =			layer_norm_eps
										__lowerCamelCase        =			initializer_range
										__lowerCamelCase        =			is_training
										__lowerCamelCase        =			scope
										__lowerCamelCase        =			use_labels
										__lowerCamelCase        =			upscale

										# here we set some attributes to make tests pass
										__lowerCamelCase        =			len(A_      )
										__lowerCamelCase        =			embed_dim
										__lowerCamelCase        =			(image_size // patch_size) ** 2




							def      __a      (    self:						Tuple      ):
										__lowerCamelCase        =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

										__lowerCamelCase        =			self.get_config()

										return config, pixel_values, labels




							def      __a      (    self:						int      ):
										return SwinaSRConfig(
										    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    ,       upscale=self.upscale    ,       )




							def      __a      (    self:						str    ,       A_:						str    ,       A_:						Optional[int]    ,       A_:						List[str]      ):
										__lowerCamelCase        =			SwinaSRModel(config=A_      )
										model.to(A_      )
										model.eval()
										__lowerCamelCase        =			model(A_      )

										self.parent.assertEqual(
										    result.last_hidden_state.shape    ,       (self.batch_size, self.embed_dim, self.image_size, self.image_size)      )




							def      __a      (    self:						Any    ,       A_:						Tuple    ,       A_:						Any    ,       A_:						Dict      ):
										__lowerCamelCase        =			SwinaSRForImageSuperResolution(A_      )
										model.to(A_      )
										model.eval()
										__lowerCamelCase        =			model(A_      )

										__lowerCamelCase        =			self.image_size * self.upscale
										self.parent.assertEqual(
										    result.reconstruction.shape    ,       (self.batch_size, self.num_channels, expected_image_size, expected_image_size)      )




							def      __a      (    self:						Tuple      ):
										__lowerCamelCase        =			self.prepare_config_and_inputs()
										__lowerCamelCase    ,__lowerCamelCase    ,__lowerCamelCase        =			config_and_inputs
										__lowerCamelCase        =			{"""pixel_values""": pixel_values}
										return config, inputs_dict




@require_torch
class  __snake_case      (lowerCamelCase ,		lowerCamelCase ,		unittest.TestCase     ):
							__a				   =					(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
							__a				   =					{'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

							__a				   =					False
							__a				   =					False
							__a				   =					False
							__a				   =					False
							__a				   =					False




							def      __a      (    self:						List[str]      ):
										__lowerCamelCase        =			SwinaSRModelTester(self      )
										__lowerCamelCase        =			ConfigTester(self    ,       config_class=A_    ,       embed_dim=37      )




							def      __a      (    self:						Optional[Any]      ):
										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      __a      (    self:						Tuple      ):
										__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*A_      )




							def      __a      (    self:						Any      ):
										__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_super_resolution(*A_      )




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




							@unittest.skip(reason="""Swin2SR does not use inputs_embeds"""      )
							def      __a      (    self:						str      ):
										pass




							@unittest.skip(reason="""Swin2SR does not support training yet"""      )
							def      __a      (    self:						int      ):
										pass




							@unittest.skip(reason="""Swin2SR does not support training yet"""      )
							def      __a      (    self:						Optional[int]      ):
										pass




							def      __a      (    self:						List[Any]      ):
										__lowerCamelCase    ,__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs_for_common()

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




							def      __a      (    self:						Optional[Any]      ):
										__lowerCamelCase    ,__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs_for_common()

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

													__lowerCamelCase        =			["""pixel_values"""]
													self.assertListEqual(arg_names[:1]    ,       A_      )




							@slow
							def      __a      (    self:						List[Any]      ):
										for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__lowerCamelCase        =			SwinaSRModel.from_pretrained(A_      )
													self.assertIsNotNone(A_      )




							def      __a      (    self:						Optional[int]      ):
										__lowerCamelCase    ,__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs_for_common()

										__lowerCamelCase        =			_config_zero_init(A_      )
										for model_class in self.all_model_classes:
													__lowerCamelCase        =			model_class(config=A_      )
													for name, param in model.named_parameters():
																if "logit_scale" in name:
																			continue
																if 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'    ,       )




							def      __a      (    self:						Any      ):
										__lowerCamelCase    ,__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs_for_common()
										__lowerCamelCase        =			True

										for model_class in self.all_model_classes:
													__lowerCamelCase        =			True
													__lowerCamelCase        =			False
													__lowerCamelCase        =			True
													__lowerCamelCase        =			model_class(A_      )
													model.to(A_      )
													model.eval()
													with torch.no_grad():
																__lowerCamelCase        =			model(**self._prepare_for_class(A_    ,       A_      )      )
													__lowerCamelCase        =			outputs.attentions
													__lowerCamelCase        =			len(self.model_tester.depths      )
													self.assertEqual(len(A_      )    ,       A_      )

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

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

													# Check attention is always last and order is fine
													__lowerCamelCase        =			True
													__lowerCamelCase        =			True
													__lowerCamelCase        =			model_class(A_      )
													model.to(A_      )
													model.eval()
													with torch.no_grad():
																__lowerCamelCase        =			model(**self._prepare_for_class(A_    ,       A_      )      )

													self.assertEqual(out_len + 1    ,       len(A_      )      )

													__lowerCamelCase        =			outputs.attentions

													self.assertEqual(len(A_      )    ,       A_      )

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




@require_vision
@require_torch
@slow
class  __snake_case      (unittest.TestCase     ):




							def      __a      (    self:						List[Any]      ):
										__lowerCamelCase        =			SwinaSRImageProcessor()
										__lowerCamelCase        =			SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""      ).to(A_      )

										__lowerCamelCase        =			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
										__lowerCamelCase        =			processor(images=A_    ,       return_tensors="""pt"""      ).to(A_      )

										# forward pass
										with torch.no_grad():
													__lowerCamelCase        =			model(**A_      )

										# verify the logits
										__lowerCamelCase        =			torch.Size([1, 3, 9_76, 12_96]      )
										self.assertEqual(outputs.reconstruction.shape    ,       A_      )
										__lowerCamelCase        =			torch.tensor(
										    [[0.5_458, 0.5_546, 0.5_638], [0.5_526, 0.5_565, 0.5_651], [0.5_396, 0.5_426, 0.5_621]]      ).to(A_      )
										self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]    ,       A_    ,       atol=1E-4      )      )




