





"""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  _a						:






				def __init__( self		:    List[Any], lowerCAmelCase__		:    List[Any], lowerCAmelCase__		:    Tuple=1_3, lowerCAmelCase__		:    Optional[Any]=3_2, lowerCAmelCase__		:    Tuple=1, lowerCAmelCase__		:    Tuple=3, lowerCAmelCase__		:    str=1_6, lowerCAmelCase__		:    List[str]=[1, 2, 1], lowerCAmelCase__		:    Optional[int]=[2, 2, 4], lowerCAmelCase__		:    List[Any]=2, lowerCAmelCase__		:    int=2.0, lowerCAmelCase__		:    List[Any]=True, lowerCAmelCase__		:    Optional[Any]=0.0, lowerCAmelCase__		:    Dict=0.0, lowerCAmelCase__		:    Any=0.1, lowerCAmelCase__		:    Optional[Any]="gelu", lowerCAmelCase__		:    List[Any]=False, lowerCAmelCase__		:    Dict=True, lowerCAmelCase__		:    List[str]=0.02, lowerCAmelCase__		:    Union[str, Any]=1e-5, lowerCAmelCase__		:    Any=True, lowerCAmelCase__		:    str=None, lowerCAmelCase__		:    int=False, lowerCAmelCase__		:    List[Any]=2, )	->      int:




										'''simple docstring'''



										_UpperCamelCase			:					Tuple     =    parent
										_UpperCamelCase			:					List[str]     =    batch_size
										_UpperCamelCase			:					Union[str, Any]     =    image_size
										_UpperCamelCase			:					Any     =    patch_size
										_UpperCamelCase			:					List[Any]     =    num_channels
										_UpperCamelCase			:					Dict     =    embed_dim
										_UpperCamelCase			:					Tuple     =    depths
										_UpperCamelCase			:					Dict     =    num_heads
										_UpperCamelCase			:					Dict     =    window_size
										_UpperCamelCase			:					int     =    mlp_ratio
										_UpperCamelCase			:					Any     =    qkv_bias
										_UpperCamelCase			:					List[Any]     =    hidden_dropout_prob
										_UpperCamelCase			:					Optional[Any]     =    attention_probs_dropout_prob
										_UpperCamelCase			:					List[str]     =    drop_path_rate
										_UpperCamelCase			:					List[str]     =    hidden_act
										_UpperCamelCase			:					Union[str, Any]     =    use_absolute_embeddings
										_UpperCamelCase			:					Union[str, Any]     =    patch_norm
										_UpperCamelCase			:					Dict     =    layer_norm_eps
										_UpperCamelCase			:					str     =    initializer_range
										_UpperCamelCase			:					List[Any]     =    is_training
										_UpperCamelCase			:					Union[str, Any]     =    scope
										_UpperCamelCase			:					Optional[Any]     =    use_labels
										_UpperCamelCase			:					Any     =    upscale

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






				def 				snake_case	( self		:    Optional[Any]							)	->      Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase			:					Tuple     =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

										_UpperCamelCase			:					int     =    None
										if self.use_labels:
																_UpperCamelCase			:					str     =    ids_tensor([self.batch_size], self.type_sequence_label_size							)

										_UpperCamelCase			:					List[Any]     =    self.get_config()

										return config, pixel_values, labels






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




										'''simple docstring'''



										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 				snake_case	( self		:    Any, lowerCAmelCase__		:    str, lowerCAmelCase__		:    Tuple, lowerCAmelCase__		:    str							)	->      List[str]:




										'''simple docstring'''



										_UpperCamelCase			:					Dict     =    SwinaSRModel(config=lowerCAmelCase__							)
										model.to(lowerCAmelCase__							)
										model.eval()
										_UpperCamelCase			:					str     =    model(lowerCAmelCase__							)

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






				def 				snake_case	( self		:    str, lowerCAmelCase__		:    Union[str, Any], lowerCAmelCase__		:    str, lowerCAmelCase__		:    Optional[Any]							)	->      Optional[int]:




										'''simple docstring'''



										_UpperCamelCase			:					Union[str, Any]     =    SwinaSRForImageSuperResolution(lowerCAmelCase__							)
										model.to(lowerCAmelCase__							)
										model.eval()
										_UpperCamelCase			:					int     =    model(lowerCAmelCase__							)

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






				def 				snake_case	( self		:    Dict							)	->      List[Any]:




										'''simple docstring'''



										_UpperCamelCase			:					List[str]     =    self.prepare_config_and_inputs()
										_UpperCamelCase   ,							_UpperCamelCase   ,							_UpperCamelCase			:					Dict     =    config_and_inputs
										_UpperCamelCase			:					Optional[int]     =    {'''pixel_values''': pixel_values}
										return config, inputs_dict




@require_torch
class  _a						(      _lowerCAmelCase	,				_lowerCAmelCase	,				unittest.TestCase				):
				UpperCamelCase								=    (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
				UpperCamelCase								=    {'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

				UpperCamelCase								=    False
				UpperCamelCase								=    False
				UpperCamelCase								=    False
				UpperCamelCase								=    False
				UpperCamelCase								=    False






				def 				snake_case	( self		:    Tuple							)	->      Optional[int]:




										'''simple docstring'''



										_UpperCamelCase			:					int     =    SwinaSRModelTester(self							)
										_UpperCamelCase			:					Dict     =    ConfigTester(self, config_class=lowerCAmelCase__, embed_dim=3_7							)






				def 				snake_case	( self		:    Any							)	->      Optional[Any]:




										'''simple docstring'''



										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 				snake_case	( self		:    List[str]							)	->      Dict:




										'''simple docstring'''



										_UpperCamelCase			:					int     =    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase__							)






				def 				snake_case	( self		:    List[Any]							)	->      Union[str, Any]:




										'''simple docstring'''



										_UpperCamelCase			:					str     =    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_super_resolution(*lowerCAmelCase__							)






				@unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.'''							)
				def 				snake_case	( self		:    Optional[int]							)	->      int:




										'''simple docstring'''



										pass






				@unittest.skip(reason='''Swin2SR does not use inputs_embeds'''							)
				def 				snake_case	( self		:    Optional[Any]							)	->      Dict:




										'''simple docstring'''



										pass






				@unittest.skip(reason='''Swin2SR does not support training yet'''							)
				def 				snake_case	( self		:    int							)	->      List[Any]:




										'''simple docstring'''



										pass






				@unittest.skip(reason='''Swin2SR does not support training yet'''							)
				def 				snake_case	( self		:    Dict							)	->      Union[str, Any]:




										'''simple docstring'''



										pass






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




										'''simple docstring'''



										_UpperCamelCase   ,							_UpperCamelCase			:					str     =    self.model_tester.prepare_config_and_inputs_for_common()

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






				def 				snake_case	( self		:    int							)	->      str:




										'''simple docstring'''



										_UpperCamelCase   ,							_UpperCamelCase			:					List[Any]     =    self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																_UpperCamelCase			:					Optional[int]     =    model_class(lowerCAmelCase__							)
																_UpperCamelCase			:					str     =    inspect.signature(model.forward							)
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																_UpperCamelCase			:					List[Any]     =    [*signature.parameters.keys()]

																_UpperCamelCase			:					Any     =    ['''pixel_values''']
																self.assertListEqual(arg_names[:1], lowerCAmelCase__							)






				@slow
				def 				snake_case	( self		:    Dict							)	->      Union[str, Any]:




										'''simple docstring'''



										for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCamelCase			:					Optional[Any]     =    SwinaSRModel.from_pretrained(lowerCAmelCase__							)
																self.assertIsNotNone(lowerCAmelCase__							)






				def 				snake_case	( self		:    List[Any]							)	->      List[str]:




										'''simple docstring'''



										_UpperCamelCase   ,							_UpperCamelCase			:					str     =    self.model_tester.prepare_config_and_inputs_for_common()

										_UpperCamelCase			:					Union[str, Any]     =    _config_zero_init(lowerCAmelCase__							)
										for model_class in self.all_model_classes:
																_UpperCamelCase			:					List[Any]     =    model_class(config=lowerCAmelCase__							)
																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 				snake_case	( self		:    Union[str, Any]							)	->      int:




										'''simple docstring'''



										_UpperCamelCase   ,							_UpperCamelCase			:					Optional[int]     =    self.model_tester.prepare_config_and_inputs_for_common()
										_UpperCamelCase			:					Optional[Any]     =    True

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

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

																self.assertListEqual(
																    list(attentions[0].shape[-3:]							), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], )
																_UpperCamelCase			:					Optional[Any]     =    len(lowerCAmelCase__							)

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

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

																_UpperCamelCase			:					List[str]     =    outputs.attentions

																self.assertEqual(len(lowerCAmelCase__							), lowerCAmelCase__							)

																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  _a						(      unittest.TestCase				):






				def 				snake_case	( self		:    Optional[Any]							)	->      Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase			:					Tuple     =    SwinaSRImageProcessor()
										_UpperCamelCase			:					Optional[Any]     =    SwinaSRForImageSuperResolution.from_pretrained('''caidas/swin2SR-classical-sr-x2-64'''							).to(lowerCAmelCase__							)

										_UpperCamelCase			:					Tuple     =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							)
										_UpperCamelCase			:					Tuple     =    processor(images=lowerCAmelCase__, return_tensors='''pt'''							).to(lowerCAmelCase__							)

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

										# verify the logits
										_UpperCamelCase			:					str     =    torch.Size([1, 3, 9_7_6, 1_2_9_6]							)
										self.assertEqual(outputs.reconstruction.shape, lowerCAmelCase__							)
										_UpperCamelCase			:					Any     =    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(lowerCAmelCase__							)
										self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3], lowerCAmelCase__, atol=1e-4							)							)










"""simple docstring"""




from sklearn.metrics import mean_absolute_error

import datasets


UpperCamelCase_           ="""\
@article{scikit-learn,
 title={Scikit-learn: Machine Learning in {P}ython},
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
 journal={Journal of Machine Learning Research},
 volume={12},
 pages={2825--2830},
 year={2011}
}
"""

UpperCamelCase_           ="""\
Mean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual
values.
"""


UpperCamelCase_           ="""
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

                 \"raw_values\" : Returns a full set of errors in case of multioutput input.

                 \"uniform_average\" : Errors of all outputs are averaged with uniform weight.

Returns:
    mae : mean absolute error.
        If multioutput is \"raw_values\", then mean absolute error is returned for each output separately. If multioutput is \"uniform_average\" or an ndarray of weights, then the weighted average of all output errors is returned.
        MAE output is non-negative floating point. The best value is 0.0.
Examples:

    >>> mae_metric = datasets.load_metric(\"mae\")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mae': 0.5}

    If you're using multi-dimensional lists, then set the config as follows :

    >>> mae_metric = datasets.load_metric(\"mae\", \"multilist\")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mae': 0.75}
    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput='raw_values')
    >>> print(results)
    {'mae': array([0.5, 1. ])}
"""




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,				_KWARGS_DESCRIPTION				)
class  _a						(      datasets.Metric				):






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




										'''simple docstring'''



										return datasets.MetricInfo(
										    description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features(self._get_feature_types()							), reference_urls=[
										        '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html'''
										    ], )






				def 				snake_case	( self		:    Dict							)	->      Union[str, Any]:




										'''simple docstring'''



										if self.config_name == "multilist":
																return {
																    "predictions": datasets.Sequence(datasets.Value('''float'''							)							),
																    "references": datasets.Sequence(datasets.Value('''float'''							)							),
																}
										else:
																return {
																    "predictions": datasets.Value('''float'''							),
																    "references": datasets.Value('''float'''							),
																}






				def 				snake_case	( self		:    List[Any], lowerCAmelCase__		:    Dict, lowerCAmelCase__		:    Union[str, Any], lowerCAmelCase__		:    Tuple=None, lowerCAmelCase__		:    Tuple="uniform_average"							)	->      Optional[int]:




										'''simple docstring'''



										_UpperCamelCase			:					List[str]     =    mean_absolute_error(lowerCAmelCase__, lowerCAmelCase__, sample_weight=lowerCAmelCase__, multioutput=lowerCAmelCase__							)

										return {"mae": mae_score}



