


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






						'''simple docstring'''







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

										# here we set some attributes to make tests pass
										__magic_name__				:					Optional[Any]						       =       len(__UpperCamelCase     )
										__magic_name__				:					Union[str, Any]						       =       embed_dim
										__magic_name__				:					List[str]						       =       (image_size // patch_size) ** 2







						def lowerCAmelCase__ (  self:	Any     )							->	Optional[Any]:
										__magic_name__				:					Optional[int]						       =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

										__magic_name__				:					List[str]						       =       None
										if self.use_labels:
														__magic_name__				:					Tuple						       =       ids_tensor([self.batch_size]      ,							self.type_sequence_label_size     )

										__magic_name__				:					Union[str, Any]						       =       self.get_config()

										return config, pixel_values, labels







						def lowerCAmelCase__ (  self:	List[str]     )							->	Tuple:
										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 lowerCAmelCase__ (  self:	Optional[int]      ,							__UpperCamelCase:	List[str]      ,							__UpperCamelCase:	Dict      ,							__UpperCamelCase:	int     )							->	Tuple:
										__magic_name__				:					Union[str, Any]						       =       SwinaSRModel(config=__UpperCamelCase     )
										model.to(__UpperCamelCase     )
										model.eval()
										__magic_name__				:					List[Any]						       =       model(__UpperCamelCase     )

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







						def lowerCAmelCase__ (  self:	Any      ,							__UpperCamelCase:	Any      ,							__UpperCamelCase:	Union[str, Any]      ,							__UpperCamelCase:	Dict     )							->	str:
										__magic_name__				:					List[str]						       =       SwinaSRForImageSuperResolution(__UpperCamelCase     )
										model.to(__UpperCamelCase     )
										model.eval()
										__magic_name__				:					Dict						       =       model(__UpperCamelCase     )

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







						def lowerCAmelCase__ (  self:	Tuple     )							->	Optional[int]:
										__magic_name__				:					Optional[Any]						       =       self.prepare_config_and_inputs()
										__magic_name__       ,     __magic_name__       ,     __magic_name__				:					Any						       =       config_and_inputs
										__magic_name__				:					str						       =       {"pixel_values": pixel_values}
										return config, inputs_dict






@require_torch
class 		_snake_case    (				snake_case_  ,  snake_case_  ,  unittest.TestCase		):






						'''simple docstring'''







						__snake_case   =      (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
						__snake_case   =      {"feature-extraction": SwinaSRModel} if is_torch_available() else {}

						__snake_case   =      False
						__snake_case   =      False
						__snake_case   =      False
						__snake_case   =      False
						__snake_case   =      False







						def lowerCAmelCase__ (  self:	Dict     )							->	Dict:
										__magic_name__				:					Tuple						       =       SwinaSRModelTester(self     )
										__magic_name__				:					List[Any]						       =       ConfigTester(self      ,							config_class=__UpperCamelCase      ,							embed_dim=37     )







						def lowerCAmelCase__ (  self:	Union[str, Any]     )							->	Optional[int]:
										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:	List[Any]     )							->	Optional[Any]:
										__magic_name__				:					List[Any]						       =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__UpperCamelCase     )







						def lowerCAmelCase__ (  self:	Any     )							->	List[str]:
										__magic_name__				:					Tuple						       =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_super_resolution(*__UpperCamelCase     )







						@unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0."     )
						def lowerCAmelCase__ (  self:	Tuple     )							->	List[Any]:
										pass







						@unittest.skip(reason="Swin2SR does not use inputs_embeds"     )
						def lowerCAmelCase__ (  self:	List[str]     )							->	List[Any]:
										pass







						@unittest.skip(reason="Swin2SR does not support training yet"     )
						def lowerCAmelCase__ (  self:	Dict     )							->	Tuple:
										pass







						@unittest.skip(reason="Swin2SR does not support training yet"     )
						def lowerCAmelCase__ (  self:	int     )							->	Union[str, Any]:
										pass







						def lowerCAmelCase__ (  self:	Dict     )							->	Dict:
										__magic_name__       ,     __magic_name__				:					Optional[Any]						       =       self.model_tester.prepare_config_and_inputs_for_common()

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







						def lowerCAmelCase__ (  self:	Optional[Any]     )							->	Union[str, Any]:
										__magic_name__       ,     __magic_name__				:					List[str]						       =       self.model_tester.prepare_config_and_inputs_for_common()

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

														__magic_name__				:					Tuple						       =       ["pixel_values"]
														self.assertListEqual(arg_names[:1]      ,							__UpperCamelCase     )







						@slow
						def lowerCAmelCase__ (  self:	Dict     )							->	str:
										for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														__magic_name__				:					Dict						       =       SwinaSRModel.from_pretrained(__UpperCamelCase     )
														self.assertIsNotNone(__UpperCamelCase     )







						def lowerCAmelCase__ (  self:	Dict     )							->	Optional[int]:
										__magic_name__       ,     __magic_name__				:					Dict						       =       self.model_tester.prepare_config_and_inputs_for_common()

										__magic_name__				:					Optional[Any]						       =       _config_zero_init(__UpperCamelCase     )
										for model_class in self.all_model_classes:
														__magic_name__				:					Any						       =       model_class(config=__UpperCamelCase     )
														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 lowerCAmelCase__ (  self:	Optional[Any]     )							->	int:
										__magic_name__       ,     __magic_name__				:					List[Any]						       =       self.model_tester.prepare_config_and_inputs_for_common()
										__magic_name__				:					Any						       =       True

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

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

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

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

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

														__magic_name__				:					Tuple						       =       outputs.attentions

														self.assertEqual(len(__UpperCamelCase     )      ,							__UpperCamelCase     )

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






						'''simple docstring'''







						def lowerCAmelCase__ (  self:	List[Any]     )							->	Optional[Any]:
										__magic_name__				:					Optional[int]						       =       SwinaSRImageProcessor()
										__magic_name__				:					List[Any]						       =       SwinaSRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x2-64"     ).to(__UpperCamelCase     )

										__magic_name__				:					Optional[Any]						       =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
										__magic_name__				:					Dict						       =       processor(images=__UpperCamelCase      ,							return_tensors="pt"     ).to(__UpperCamelCase     )

										# forward pass
										with torch.no_grad():
														__magic_name__				:					Optional[Any]						       =       model(**__UpperCamelCase     )

										# verify the logits
										__magic_name__				:					List[str]						       =       torch.Size([1, 3, 976, 1296]     )
										self.assertEqual(outputs.reconstruction.shape      ,							__UpperCamelCase     )
										__magic_name__				:					List[str]						       =       torch.tensor(
										    [[0.5_4_5_8, 0.5_5_4_6, 0.5_6_3_8], [0.5_5_2_6, 0.5_5_6_5, 0.5_6_5_1], [0.5_3_9_6, 0.5_4_2_6, 0.5_6_2_1]]     ).to(__UpperCamelCase     )
										self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]      ,							__UpperCamelCase      ,							atol=1E-4     )     )



'''simple docstring'''







import json
import os
import unittest

from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import (
    VOCAB_FILES_NAMES,
    GPTNeoXJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 		_snake_case    (				snake_case_  ,  unittest.TestCase		):






						'''simple docstring'''







						__snake_case   =      GPTNeoXJapaneseTokenizer
						__snake_case   =      False
						__snake_case   =      {"do_clean_text": False, "add_prefix_space": False}







						def lowerCAmelCase__ (  self:	Any     )							->	List[str]:
										super().setUp()

										__magic_name__				:					Union[str, Any]						       =       [
										    "こん",
										    "こんに",
										    "にちは",
										    "ばんは",
										    "世界,㔺界",
										    "、",
										    "。",
										    "<BR>",
										    "<SP>",
										    "<TAB>",
										    "<URL>",
										    "<EMAIL>",
										    "<TEL>",
										    "<DATE>",
										    "<PRICE>",
										    "<BLOCK>",
										    "<KIGOU>",
										    "<U2000U2BFF>",
										    "<|emoji1|>",
										    "<unk>",
										    "<|startoftext|>",
										    "<|endoftext|>",
										]
										__magic_name__				:					List[str]						       =       {"emoji": {"\ud83d\ude00": "<|emoji1|>"}, "emoji_inv": {"<|emoji1|>": "\ud83d\ude00"}}  # 😀
										__magic_name__				:					str						       =       {"unk_token": "<unk>"}

										__magic_name__				:					Dict						       =       os.path.join(self.tmpdirname      ,							VOCAB_FILES_NAMES["vocab_file"]     )
										__magic_name__				:					Dict						       =       os.path.join(self.tmpdirname      ,							VOCAB_FILES_NAMES["emoji_file"]     )
										with open(self.vocab_file      ,							"w"      ,							encoding="utf-8"     ) as vocab_writer:
														vocab_writer.write("".join([x + "\n" for x in vocab_tokens]     )     )
										with open(self.emoji_file      ,							"w"     ) as emoji_writer:
														emoji_writer.write(json.dumps(__UpperCamelCase     )     )







						def lowerCAmelCase__ (  self:	Tuple      ,							**__UpperCamelCase:	str     )							->	Union[str, Any]:
										kwargs.update(self.special_tokens_map     )
										return GPTNeoXJapaneseTokenizer.from_pretrained(self.tmpdirname      ,							**__UpperCamelCase     )







						def lowerCAmelCase__ (  self:	List[str]      ,							__UpperCamelCase:	str     )							->	List[str]:
										__magic_name__				:					str						       =       "こんにちは、世界。 \nこんばんは、㔺界。😀"
										__magic_name__				:					str						       =       "こんにちは、世界。 \nこんばんは、世界。😀"
										return input_text, output_text







						def lowerCAmelCase__ (  self:	Union[str, Any]      ,							__UpperCamelCase:	List[Any]     )							->	Dict:
										__magic_name__       ,     __magic_name__				:					Union[str, Any]						       =       self.get_input_output_texts(__UpperCamelCase     )
										__magic_name__				:					List[Any]						       =       tokenizer.encode(__UpperCamelCase      ,							add_special_tokens=__UpperCamelCase     )
										__magic_name__				:					Optional[Any]						       =       tokenizer.decode(__UpperCamelCase      ,							clean_up_tokenization_spaces=__UpperCamelCase     )
										return text, ids







						def lowerCAmelCase__ (  self:	Optional[int]     )							->	Union[str, Any]:
										pass  # TODO add if relevant







						def lowerCAmelCase__ (  self:	str     )							->	List[str]:
										pass  # TODO add if relevant







						def lowerCAmelCase__ (  self:	str     )							->	str:
										pass  # TODO add if relevant







						def lowerCAmelCase__ (  self:	Union[str, Any]     )							->	Dict:
										__magic_name__				:					List[str]						       =       self.get_tokenizer()

										# Testing tokenization
										__magic_name__				:					Any						       =       "こんにちは、世界。　こんばんは、㔺界。"
										__magic_name__				:					Optional[int]						       =       ["こん", "にちは", "、", "世界", "。", "<SP>", "こん", "ばんは", "、", "㔺界", "。"]
										__magic_name__				:					List[Any]						       =       tokenizer.tokenize(__UpperCamelCase     )
										self.assertListEqual(__UpperCamelCase      ,							__UpperCamelCase     )

										# Testing conversion to ids without special tokens
										__magic_name__				:					int						       =       [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
										__magic_name__				:					str						       =       tokenizer.convert_tokens_to_ids(__UpperCamelCase     )
										self.assertListEqual(__UpperCamelCase      ,							__UpperCamelCase     )

										# Testing conversion to ids with special tokens
										__magic_name__				:					str						       =       tokens + [tokenizer.unk_token]
										__magic_name__				:					Tuple						       =       [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
										__magic_name__				:					Dict						       =       tokenizer.convert_tokens_to_ids(__UpperCamelCase     )
										self.assertListEqual(__UpperCamelCase      ,							__UpperCamelCase     )







						@slow
						def lowerCAmelCase__ (  self:	List[Any]     )							->	Union[str, Any]:
										__magic_name__				:					List[str]						       =       self.tokenizer_class.from_pretrained("abeja/gpt-neox-japanese-2.7b"     )

										__magic_name__				:					List[Any]						       =       tokenizer.encode("ありがとう。"      ,							add_special_tokens=__UpperCamelCase     )
										__magic_name__				:					Optional[Any]						       =       tokenizer.encode("どういたしまして。"      ,							add_special_tokens=__UpperCamelCase     )

										__magic_name__				:					List[Any]						       =       tokenizer.build_inputs_with_special_tokens(__UpperCamelCase     )
										__magic_name__				:					str						       =       tokenizer.build_inputs_with_special_tokens(__UpperCamelCase      ,							__UpperCamelCase     )

										assert encoded_sentence == ids_a
										assert encoded_pair == ids_a + ids_a







						def lowerCAmelCase__ (  self:	Tuple     )							->	Dict:
										# Intentionally convert some words to accommodate character fluctuations unique to Japanese
										pass







						def lowerCAmelCase__ (  self:	Dict     )							->	Optional[int]:
										# tokenizer has no padding token
										pass