



'''simple docstring'''

from __future__ import annotations

import os
import tempfile
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import is_tensorflow_text_available, is_tf_available
from transformers.testing_utils import require_tensorflow_text, require_tf, slow

from ..test_modeling_tf_common import floats_tensor
from .test_framework_agnostic import GenerationIntegrationTestsMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    AutoTokenizer,
		    TFAutoModelForCausalLM,
		    TFAutoModelForSeqaSeqLM,
		    TFAutoModelForSpeechSeqaSeq,
		    TFAutoModelForVisionaSeq,
		    TFBartForConditionalGeneration,
		    TFLogitsProcessorList,
		    TFMinLengthLogitsProcessor,
		    tf_top_k_top_p_filtering,
		)

if is_tensorflow_text_available():
		import tensorflow_text as text



@require_tf
class 		lowerCamelCase__      (						unittest.TestCase     ):




					'''simple docstring'''



					def 						__UpperCAmelCase     (  self				:	List[Any]					)  ->       Tuple:



						'''simple docstring'''





						_lowercase					:       Tuple       =		tf.convert_to_tensor(
						    [
						        [
						            8.2_22_09_91,  # 3rd highest value; idx. 0
						            -0.5_62_00_44,
						            5.23_22_97_52,
						            4.0_38_63_93,
						            -6.8_79_83_78,
						            -0.54_78_58_02,
						            -3.2_01_21_53,
						            2.92_77_71_76,
						            1.88_17_19_53,
						            7.35_34_12_76,  # 5th highest value; idx. 9
						            8.43_20_78_33,  # 2nd highest value; idx. 10
						            -9.85_71_18_36,
						            -5.96_20_92_36,
						            -1.13_03_91_61,
						            -7.1_11_52_94,
						            -0.8_36_96_33,
						            -5.3_18_64_08,
						            7.06_42_74_07,
						            0.81_36_93_44,
						            -0.82_02_38_17,
						            -5.9_17_97_96,
						            0.58_81_34_43,
						            -6.99_77_84_38,
						            4.71_55_11_89,
						            -0.18_77_16_37,
						            7.44_02_07_59,  # 4th highest value; idx. 25
						            9.38_45_09_87,  # 1st highest value; idx. 26
						            2.12_66_29_41,
						            -9.32_56_20_38,
						            2.35_65_25_22,
						        ],  # cummulative prob of 5 highest values <= 0.6
						        [
						            0.58_42_55_18,
						            4.53_13_92_38,
						            -5.57_51_04_64,
						            -6.28_03_06_99,
						            -7.19_52_95_03,
						            -4.02_12_25_51,
						            1.39_33_70_37,
						            -6.06_70_70_57,
						            1.59_48_05_17,
						            -9.64_31_19,
						            0.03_90_77_99,
						            0.67_23_17_62,
						            -8.88_20_67_26,
						            6.27_11_59_22,  # 4th highest value; idx. 13
						            2.28_52_07_23,
						            4.82_76_75_06,
						            4.30_42_13_68,
						            8.8_27_53_13,  # 2nd highest value; idx. 17
						            5.44_02_99_58,  # 5th highest value; idx. 18
						            -4.4_73_57_94,
						            7.38_57_95_36,  # 3rd highest value; idx. 20
						            -2.91_05_16_63,
						            2.61_94_60_77,
						            -2.5_67_47_62,
						            -9.48_95_93_02,
						            -4.02_92_26_45,
						            -1.35_41_69_18,
						            9.67_70_23_23,  # 1st highest value; idx. 27
						            -5.89_47_85_53,
						            1.85_37_04_67,
						        ],  # cummulative prob of 5 highest values <= 0.6
						    ]     ,  dtype=tf.floataa     ,  )

						_lowercase					:       List[Any]       =		tf.convert_to_tensor(
						    [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]]     ,  dtype=tf.intaa     ,  )  # expected non filtered idx as noted above

						_lowercase					:       List[Any]       =		tf.convert_to_tensor(
						    [8.22_20_99, 7.3_53_41_26, 8.43_20_78, 7.4_40_20_75, 9.3_84_51, 6.27_11_59, 8.82_75_31, 5.4_40_29_95, 7.3_85_79_56, 9.67_70_23]     ,  dtype=tf.floataa     ,  )  # expected non filtered values as noted above

						_lowercase					:       Optional[int]       =		tf_top_k_top_p_filtering(UpperCamelCase_     ,  top_k=10     ,  top_p=0.6     ,  min_tokens_to_keep=4					)

						_lowercase					:       Tuple       =		output[output != -float('inf'					)]
						_lowercase					:       Union[str, Any]       =		tf.cast(
						    tf.where(tf.not_equal(UpperCamelCase_     ,  tf.constant(-float('inf'					)     ,  dtype=tf.floataa					)					)					)     ,  dtype=tf.intaa     ,  )

						tf.debugging.assert_near(UpperCamelCase_     ,  UpperCamelCase_     ,  rtol=1E-12					)
						tf.debugging.assert_equal(UpperCamelCase_     ,  UpperCamelCase_					)






@require_tf
class 		lowerCamelCase__      (						unittest.TestCase	,   A     ):




					'''simple docstring'''



					if is_tf_available():
										A_						    =						{
										    """AutoModelForCausalLM""": TFAutoModelForCausalLM,
										    """AutoModelForSpeechSeq2Seq""": TFAutoModelForSpeechSeqaSeq,
										    """AutoModelForSeq2SeqLM""": TFAutoModelForSeqaSeqLM,
										    """AutoModelForVision2Seq""": TFAutoModelForVisionaSeq,
										    """LogitsProcessorList""": TFLogitsProcessorList,
										    """MinLengthLogitsProcessor""": TFMinLengthLogitsProcessor,
										    """create_tensor_fn""": tf.convert_to_tensor,
										    """floats_tensor""": floats_tensor,
										    """return_tensors""": """tf""",
										}




					@slow
					def 						__UpperCAmelCase     (  self				:	str					)  ->       int:



						'''simple docstring'''





						_lowercase					:       Optional[int]       =		TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'					)
						_lowercase					:       Dict       =		2
						_lowercase					:       Tuple       =		2



						class 		lowerCamelCase__      (						tf.Module     ):




											'''simple docstring'''



											def __init__(  self				:	Dict     ,  UpperCamelCase_				:	int					)  ->       Union[str, Any]:



												'''simple docstring'''





												super(UpperCamelCase_     ,  self					).__init__()
												_lowercase					:       List[str]       =		model




											@tf.function(
											    input_signature=(
											        tf.TensorSpec((None, input_length)     ,  tf.intaa     ,  name='input_ids'					),
											        tf.TensorSpec((None, input_length)     ,  tf.intaa     ,  name='attention_mask'					),
											    )     ,  jit_compile=UpperCamelCase_     ,  )
											def 						__UpperCAmelCase     (  self				:	Union[str, Any]     ,  UpperCamelCase_				:	str     ,  UpperCamelCase_				:	Optional[Any]					)  ->       List[Any]:



												'''simple docstring'''





												_lowercase					:       List[Any]       =		self.model.generate(
												    input_ids=UpperCamelCase_     ,  attention_mask=UpperCamelCase_     ,  max_new_tokens=UpperCamelCase_     ,  return_dict_in_generate=UpperCamelCase_     ,  )
												return {"sequences": outputs["sequences"]}






						_lowercase					:       int       =		[[2, 0], [102, 103]]
						_lowercase					:       int       =		[[1, 0], [1, 1]]
						_lowercase					:       str       =		DummyModel(model=UpperCamelCase_					)
						with tempfile.TemporaryDirectory() as tmp_dir:
							tf.saved_model.save(UpperCamelCase_     ,  UpperCamelCase_     ,  signatures={'serving_default': dummy_model.serving}					)
							_lowercase					:       int       =		tf.saved_model.load(UpperCamelCase_					).signatures['serving_default']
							for batch_size in range(1     ,  len(UpperCamelCase_					) + 1					):
								_lowercase					:       List[str]       =		{
								    'input_ids': tf.constant(dummy_input_ids[:batch_size]					),
								    'attention_mask': tf.constant(dummy_attention_masks[:batch_size]					),
								}
								_lowercase					:       Optional[int]       =		serving_func(**UpperCamelCase_					)['sequences']
								_lowercase					:       List[str]       =		test_model.generate(**UpperCamelCase_     ,  max_new_tokens=UpperCamelCase_					)
								tf.debugging.assert_equal(UpperCamelCase_     ,  UpperCamelCase_					)




					@slow
					def 						__UpperCAmelCase     (  self				:	int					)  ->       List[str]:



						'''simple docstring'''





						_lowercase					:       List[Any]       =		TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'					)
						_lowercase					:       Any       =		1
						_lowercase					:       List[str]       =		2



						class 		lowerCamelCase__      (						tf.Module     ):




											'''simple docstring'''



											def __init__(  self				:	str     ,  UpperCamelCase_				:	Tuple					)  ->       List[str]:



												'''simple docstring'''





												super(UpperCamelCase_     ,  self					).__init__()
												_lowercase					:       List[str]       =		model




											@tf.function(
											    input_signature=(
											        tf.TensorSpec((batch_size, None)     ,  tf.intaa     ,  name='input_ids'					),
											        tf.TensorSpec((batch_size, None)     ,  tf.intaa     ,  name='attention_mask'					),
											    )     ,  jit_compile=UpperCamelCase_     ,  )
											def 						__UpperCAmelCase     (  self				:	Dict     ,  UpperCamelCase_				:	List[Any]     ,  UpperCamelCase_				:	List[Any]					)  ->       Any:



												'''simple docstring'''





												_lowercase					:       List[Any]       =		self.model.generate(
												    input_ids=UpperCamelCase_     ,  attention_mask=UpperCamelCase_     ,  max_new_tokens=UpperCamelCase_     ,  return_dict_in_generate=UpperCamelCase_     ,  )
												return {"sequences": outputs["sequences"]}






						_lowercase					:       int       =		[[2], [102, 103]]
						_lowercase					:       Optional[Any]       =		[[1], [1, 1]]
						_lowercase					:       Tuple       =		DummyModel(model=UpperCamelCase_					)
						with tempfile.TemporaryDirectory() as tmp_dir:
							tf.saved_model.save(UpperCamelCase_     ,  UpperCamelCase_     ,  signatures={'serving_default': dummy_model.serving}					)
							_lowercase					:       Optional[Any]       =		tf.saved_model.load(UpperCamelCase_					).signatures['serving_default']
							for input_row in range(len(UpperCamelCase_					)					):
								_lowercase					:       int       =		{
								    'input_ids': tf.constant([dummy_input_ids[input_row]]					),
								    'attention_mask': tf.constant([dummy_attention_masks[input_row]]					),
								}
								_lowercase					:       Any       =		serving_func(**UpperCamelCase_					)['sequences']
								_lowercase					:       int       =		test_model.generate(**UpperCamelCase_     ,  max_new_tokens=UpperCamelCase_					)
								tf.debugging.assert_equal(UpperCamelCase_     ,  UpperCamelCase_					)




					@slow
					@require_tensorflow_text
					def 						__UpperCAmelCase     (  self				:	Optional[int]					)  ->       Union[str, Any]:



						'''simple docstring'''





						with tempfile.TemporaryDirectory() as tmp_dir:
							# file needed to load the TF tokenizer
							hf_hub_download(repo_id='google/flan-t5-small'     ,  filename='spiece.model'     ,  local_dir=UpperCamelCase_					)



							class 		lowerCamelCase__      (						tf.keras.layers.Layer     ):




												'''simple docstring'''



												def __init__(  self				:	Optional[int]					)  ->       List[Any]:



													'''simple docstring'''





													super().__init__()
													_lowercase					:       List[Any]       =		text.SentencepieceTokenizer(
													    model=tf.io.gfile.GFile(os.path.join(UpperCamelCase_     ,  'spiece.model'					)     ,  'rb'					).read()					)
													_lowercase					:       int       =		TFAutoModelForSeqaSeqLM.from_pretrained('hf-internal-testing/tiny-random-t5'					)




												def 						__UpperCAmelCase     (  self				:	Optional[Any]     ,  UpperCamelCase_				:	Any     ,  *UpperCamelCase_				:	Optional[int]     ,  **UpperCamelCase_				:	int					)  ->       str:



													'''simple docstring'''





													_lowercase					:       Dict       =		self.tokenizer.tokenize(UpperCamelCase_					)
													_lowercase  ,    _lowercase					:       Any       =		text.pad_model_inputs(
													    UpperCamelCase_     ,  max_seq_length=64     ,  pad_value=self.model.config.pad_token_id					)
													_lowercase					:       Union[str, Any]       =		self.model.generate(input_ids=UpperCamelCase_     ,  attention_mask=UpperCamelCase_					)
													return self.tokenizer.detokenize(UpperCamelCase_					)






							_lowercase					:       Optional[int]       =		CompleteSentenceTransformer()
							_lowercase					:       Dict       =		tf.keras.layers.Input(shape=(1,)     ,  dtype=tf.string     ,  name='inputs'					)
							_lowercase					:       Optional[int]       =		complete_model(UpperCamelCase_					)
							_lowercase					:       Dict       =		tf.keras.Model(UpperCamelCase_     ,  UpperCamelCase_					)
							keras_model.save(UpperCamelCase_					)




					def 						__UpperCAmelCase     (  self				:	int					)  ->       List[Any]:



						'''simple docstring'''





						_lowercase					:       Any       =		{
						    'do_sample': True,
						    'num_beams': 1,
						    'top_p': 0.7,
						    'top_k': 10,
						    'temperature': 0.7,
						}
						_lowercase					:       List[Any]       =		14

						_lowercase					:       Union[str, Any]       =		AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'					)
						_lowercase					:       int       =		'Hello, my dog is cute and'
						_lowercase					:       str       =		tokenizer(UpperCamelCase_     ,  return_tensors='tf'					)
						_lowercase					:       List[Any]       =		TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'					)

						_lowercase					:       List[Any]       =		638
						# forces the generation to happen on CPU, to avoid GPU-related quirks
						with tf.device(':/CPU:0'					):
							tf.random.set_seed(0					)
							_lowercase					:       Tuple       =		model.generate(**UpperCamelCase_     ,  eos_token_id=UpperCamelCase_     ,  **UpperCamelCase_					)
						self.assertTrue(expectation == len(generated_tokens[0]					)					)

						_lowercase					:       Union[str, Any]       =		[638, 198]
						with tf.device(':/CPU:0'					):
							tf.random.set_seed(0					)
							_lowercase					:       Tuple       =		model.generate(**UpperCamelCase_     ,  eos_token_id=UpperCamelCase_     ,  **UpperCamelCase_					)
						self.assertTrue(expectation == len(generated_tokens[0]					)					)




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



						'''simple docstring'''





						_lowercase					:       Dict       =		AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-bart'					)
						_lowercase					:       List[str]       =		'Hugging Face is a technology company based in New York and Paris.'
						_lowercase					:       List[Any]       =		bart_tokenizer(UpperCamelCase_     ,  return_tensors='tf'					).input_ids
						_lowercase					:       Any       =		TFBartForConditionalGeneration.from_pretrained('hf-internal-testing/tiny-random-bart'					)
						_lowercase					:       List[str]       =		bart_model.generate(UpperCamelCase_					).numpy()



						class 		lowerCamelCase__      (						A     ):




											'''simple docstring'''



											def 						__UpperCAmelCase     (  self				:	Tuple     ,  UpperCamelCase_				:	Optional[int]     ,  UpperCamelCase_				:	Union[str, Any]=None     ,  **UpperCamelCase_				:	List[str]					)  ->       Tuple:



												'''simple docstring'''





												return super().call(UpperCamelCase_     ,  **UpperCamelCase_					)






						_lowercase					:       int       =		FakeBart.from_pretrained('hf-internal-testing/tiny-random-bart'					)
						_lowercase					:       int       =		bart_model.generate(UpperCamelCase_     ,  foo='bar'					).numpy()
						self.assertTrue(np.array_equal(UpperCamelCase_     ,  UpperCamelCase_					)					)



						class 		lowerCamelCase__      (						bart_model.model.encoder.__class__     ):




											'''simple docstring'''



											def 						__UpperCAmelCase     (  self				:	Dict     ,  UpperCamelCase_				:	int     ,  **UpperCamelCase_				:	Dict					)  ->       Any:



												'''simple docstring'''





												return super().call(UpperCamelCase_     ,  **UpperCamelCase_					)






						_lowercase					:       Union[str, Any]       =		FakeEncoder(bart_model.config     ,  bart_model.model.shared					)
						_lowercase					:       List[str]       =		fake_encoder

						# Normal generation still works (the output will be different because the encoder weights are different)
						_lowercase					:       Any       =		bart_model.generate(UpperCamelCase_					).numpy()
						with self.assertRaises(UpperCamelCase_					):
							# FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo"
							bart_model.generate(UpperCamelCase_     ,  foo='bar'					)





'''simple docstring'''

import argparse

import requests
import torch
from PIL import Image
from torchvision.transforms import Compose, Normalize, Resize, ToTensor

from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor







def 						__UpperCamelCase				(							_lowercase					) ->			Tuple:
	_lowercase					:       Tuple       =		SwinaSRConfig()

	if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url:
		_lowercase					:       Optional[Any]       =		4
	elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url:
		_lowercase					:       Tuple       =		4
		_lowercase					:       Union[str, Any]       =		48
		_lowercase					:       Any       =		'pixelshuffle_aux'
	elif "Swin2SR_Lightweight_X2_64" in checkpoint_url:
		_lowercase					:       Dict       =		[6, 6, 6, 6]
		_lowercase					:       Optional[int]       =		60
		_lowercase					:       List[str]       =		[6, 6, 6, 6]
		_lowercase					:       Dict       =		'pixelshuffledirect'
	elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url:
		_lowercase					:       str       =		4
		_lowercase					:       str       =		'nearest+conv'
	elif "Swin2SR_Jpeg_dynamic" in checkpoint_url:
		_lowercase					:       str       =		1
		_lowercase					:       Tuple       =		1
		_lowercase					:       Dict       =		126
		_lowercase					:       Optional[int]       =		7
		_lowercase					:       List[Any]       =		2_5_5.0
		_lowercase					:       Tuple       =		''

	return config







def 						__UpperCamelCase				(							_lowercase,				_lowercase					) ->			str:
	if "patch_embed.proj" in name and "layers" not in name:
		_lowercase					:       Tuple       =		name.replace('patch_embed.proj',				'embeddings.patch_embeddings.projection'					)
	if "patch_embed.norm" in name:
		_lowercase					:       Union[str, Any]       =		name.replace('patch_embed.norm',				'embeddings.patch_embeddings.layernorm'					)
	if "layers" in name:
		_lowercase					:       Tuple       =		name.replace('layers',				'encoder.stages'					)
	if "residual_group.blocks" in name:
		_lowercase					:       str       =		name.replace('residual_group.blocks',				'layers'					)
	if "attn.proj" in name:
		_lowercase					:       str       =		name.replace('attn.proj',				'attention.output.dense'					)
	if "attn" in name:
		_lowercase					:       List[Any]       =		name.replace('attn',				'attention.self'					)
	if "norm1" in name:
		_lowercase					:       List[str]       =		name.replace('norm1',				'layernorm_before'					)
	if "norm2" in name:
		_lowercase					:       Tuple       =		name.replace('norm2',				'layernorm_after'					)
	if "mlp.fc1" in name:
		_lowercase					:       int       =		name.replace('mlp.fc1',				'intermediate.dense'					)
	if "mlp.fc2" in name:
		_lowercase					:       List[str]       =		name.replace('mlp.fc2',				'output.dense'					)
	if "q_bias" in name:
		_lowercase					:       Optional[Any]       =		name.replace('q_bias',				'query.bias'					)
	if "k_bias" in name:
		_lowercase					:       str       =		name.replace('k_bias',				'key.bias'					)
	if "v_bias" in name:
		_lowercase					:       int       =		name.replace('v_bias',				'value.bias'					)
	if "cpb_mlp" in name:
		_lowercase					:       Any       =		name.replace('cpb_mlp',				'continuous_position_bias_mlp'					)
	if "patch_embed.proj" in name:
		_lowercase					:       Union[str, Any]       =		name.replace('patch_embed.proj',				'patch_embed.projection'					)

	if name == "norm.weight":
		_lowercase					:       Union[str, Any]       =		'layernorm.weight'
	if name == "norm.bias":
		_lowercase					:       List[Any]       =		'layernorm.bias'

	if "conv_first" in name:
		_lowercase					:       Tuple       =		name.replace('conv_first',				'first_convolution'					)

	if (
	    "upsample" in name
	    or "conv_before_upsample" in name
	    or "conv_bicubic" in name
	    or "conv_up" in name
	    or "conv_hr" in name
	    or "conv_last" in name
	    or "aux" in name
	):
		# heads
		if "conv_last" in name:
			_lowercase					:       List[str]       =		name.replace('conv_last',				'final_convolution'					)
		if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]:
			if "conv_before_upsample.0" in name:
				_lowercase					:       Union[str, Any]       =		name.replace('conv_before_upsample.0',				'conv_before_upsample'					)
			if "upsample.0" in name:
				_lowercase					:       str       =		name.replace('upsample.0',				'upsample.convolution_0'					)
			if "upsample.2" in name:
				_lowercase					:       Union[str, Any]       =		name.replace('upsample.2',				'upsample.convolution_1'					)
			_lowercase					:       Optional[int]       =		'upsample.' + name
		elif config.upsampler == "pixelshuffledirect":
			_lowercase					:       Optional[Any]       =		name.replace('upsample.0.weight',				'upsample.conv.weight'					)
			_lowercase					:       str       =		name.replace('upsample.0.bias',				'upsample.conv.bias'					)
		else:
			pass
	else:
		_lowercase					:       Tuple       =		'swin2sr.' + name

	return name







def 						__UpperCamelCase				(							_lowercase,				_lowercase					) ->			List[str]:
	for key in orig_state_dict.copy().keys():
		_lowercase					:       int       =		orig_state_dict.pop(_lowercase					)

		if "qkv" in key:
			_lowercase					:       Tuple       =		key.split('.'					)
			_lowercase					:       Optional[Any]       =		int(key_split[1]					)
			_lowercase					:       Any       =		int(key_split[4]					)
			_lowercase					:       Optional[Any]       =		config.embed_dim

			if "weight" in key:
				_lowercase					:       Optional[int]       =		val[:dim, :]
				_lowercase					:       int       =		val[dim : dim * 2, :]
				_lowercase					:       int       =		val[-dim:, :]
			else:
				_lowercase					:       Optional[Any]       =		val[:dim]
				_lowercase					:       Tuple       =		val[dim : dim * 2]
				_lowercase					:       List[str]       =		val[-dim:]
			pass
		else:
			_lowercase					:       List[Any]       =		val

	return orig_state_dict







def 						__UpperCamelCase				(							_lowercase,				_lowercase,				_lowercase					) ->			Union[str, Any]:
	_lowercase					:       Optional[Any]       =		get_config(_lowercase					)
	_lowercase					:       Union[str, Any]       =		SwinaSRForImageSuperResolution(_lowercase					)
	model.eval()

	_lowercase					:       List[Any]       =		torch.hub.load_state_dict_from_url(_lowercase,				map_location='cpu'					)
	_lowercase					:       Any       =		convert_state_dict(_lowercase,				_lowercase					)
	_lowercase  ,    _lowercase					:       str       =		model.load_state_dict(_lowercase,				strict=_lowercase					)

	if len(_lowercase					) > 0:
		raise ValueError('Missing keys when converting: {}'.format(_lowercase					)					)
	for key in unexpected_keys:
		if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key):
			raise ValueError(f'''Unexpected key {key} in state_dict'''					)

    # verify values
	_lowercase					:       str       =		'https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true'
	_lowercase					:       Any       =		Image.open(requests.get(_lowercase,				stream=_lowercase					).raw					).convert('RGB'					)
	_lowercase					:       Tuple       =		SwinaSRImageProcessor()
	# pixel_values = processor(image, return_tensors="pt").pixel_values

	_lowercase					:       Tuple       =		126 if 'Jpeg' in checkpoint_url else 256
	_lowercase					:       List[str]       =		Compose(
	    [
	        Resize((image_size, image_size)					),
	        ToTensor(),
	        Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6],				std=[0.2_2_9, 0.2_2_4, 0.2_2_5]					),
	    ]					)
	_lowercase					:       Optional[Any]       =		transforms(_lowercase					).unsqueeze(0					)

	if config.num_channels == 1:
		_lowercase					:       Any       =		pixel_values[:, 0, :, :].unsqueeze(1					)

	_lowercase					:       Optional[int]       =		model(_lowercase					)

	# assert values
	if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url:
		_lowercase					:       Any       =		torch.Size([1, 3, 512, 512]					)
		_lowercase					:       Tuple       =		torch.tensor(
		    [[-0.7_0_8_7, -0.7_1_3_8, -0.6_7_2_1], [-0.8_3_4_0, -0.8_0_9_5, -0.7_2_9_8], [-0.9_1_4_9, -0.8_4_1_4, -0.7_9_4_0]]					)
	elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url:
		_lowercase					:       Optional[Any]       =		torch.Size([1, 3, 1024, 1024]					)
		_lowercase					:       int       =		torch.tensor(
		    [[-0.7_7_7_5, -0.8_1_0_5, -0.8_9_3_3], [-0.7_7_6_4, -0.8_3_5_6, -0.9_2_2_5], [-0.7_9_7_6, -0.8_6_8_6, -0.9_5_7_9]]					)
	elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url:
		# TODO values didn't match exactly here
		_lowercase					:       Optional[int]       =		torch.Size([1, 3, 1024, 1024]					)
		_lowercase					:       Dict       =		torch.tensor(
		    [[-0.8_0_3_5, -0.7_5_0_4, -0.7_4_9_1], [-0.8_5_3_8, -0.8_1_2_4, -0.7_7_8_2], [-0.8_8_0_4, -0.8_6_5_1, -0.8_4_9_3]]					)
	elif "Swin2SR_Lightweight_X2_64" in checkpoint_url:
		_lowercase					:       List[str]       =		torch.Size([1, 3, 512, 512]					)
		_lowercase					:       int       =		torch.tensor(
		    [[-0.7_6_6_9, -0.8_6_6_2, -0.8_7_6_7], [-0.8_8_1_0, -0.9_9_6_2, -0.9_8_2_0], [-0.9_3_4_0, -1.0_3_2_2, -1.1_1_4_9]]					)
	elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url:
		_lowercase					:       Any       =		torch.Size([1, 3, 1024, 1024]					)
		_lowercase					:       Union[str, Any]       =		torch.tensor(
		    [[-0.5_2_3_8, -0.5_5_5_7, -0.6_3_2_1], [-0.6_0_1_6, -0.5_9_0_3, -0.6_3_9_1], [-0.6_2_4_4, -0.6_3_3_4, -0.6_8_8_9]]					)

	assert (
	    outputs.reconstruction.shape == expected_shape
	), f'''Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}'''
	assert torch.allclose(outputs.reconstruction[0, 0, :3, :3],				_lowercase,				atol=1E-3					)
	print('Looks ok!'					)

	_lowercase					:       List[str]       =		{
	    'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth': (
	        'swin2SR-classical-sr-x2-64'
	    ),
	    'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth': (
	        'swin2SR-classical-sr-x4-64'
	    ),
	    'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth': (
	        'swin2SR-compressed-sr-x4-48'
	    ),
	    'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth': (
	        'swin2SR-lightweight-x2-64'
	    ),
	    'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth': (
	        'swin2SR-realworld-sr-x4-64-bsrgan-psnr'
	    ),
	}
	_lowercase					:       int       =		url_to_name[checkpoint_url]

	if pytorch_dump_folder_path is not None:
		print(f'''Saving model {model_name} to {pytorch_dump_folder_path}'''					)
		model.save_pretrained(_lowercase					)
		print(f'''Saving image processor to {pytorch_dump_folder_path}'''					)
		processor.save_pretrained(_lowercase					)

	if push_to_hub:
		model.push_to_hub(f'''caidas/{model_name}'''					)
		processor.push_to_hub(f'''caidas/{model_name}'''					)


if __name__ == "__main__":
		_A				:    Dict     						=argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '''--checkpoint_url''',
		    default='''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''',
		    type=str,
		    help='''URL of the original Swin2SR checkpoint you\'d like to convert.''',
		)
		parser.add_argument(
		    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
		)
		parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the converted model to the hub.''')

		_A				:    int     						=parser.parse_args()
		convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
