





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

    '''simple docstring'''


    def __init__(		self			,		A			,		A=13			,		A=32			,		A=1			,		A=3			,		A=16			,		A=[1, 2, 1]			,		A=[2, 2, 4]			,		A=2			,		A=2.0			,		A=True			,		A=0.0			,		A=0.0			,		A=0.1			,		A="gelu"			,		A=False			,		A=True			,		A=0.02			,		A=1e-5			,		A=True			,		A=None			,		A=False			,		A=2			,		)		->       str:
        _SCREAMING_SNAKE_CASE     =      parent
        _SCREAMING_SNAKE_CASE     =      batch_size
        _SCREAMING_SNAKE_CASE     =      image_size
        _SCREAMING_SNAKE_CASE     =      patch_size
        _SCREAMING_SNAKE_CASE     =      num_channels
        _SCREAMING_SNAKE_CASE     =      embed_dim
        _SCREAMING_SNAKE_CASE     =      depths
        _SCREAMING_SNAKE_CASE     =      num_heads
        _SCREAMING_SNAKE_CASE     =      window_size
        _SCREAMING_SNAKE_CASE     =      mlp_ratio
        _SCREAMING_SNAKE_CASE     =      qkv_bias
        _SCREAMING_SNAKE_CASE     =      hidden_dropout_prob
        _SCREAMING_SNAKE_CASE     =      attention_probs_dropout_prob
        _SCREAMING_SNAKE_CASE     =      drop_path_rate
        _SCREAMING_SNAKE_CASE     =      hidden_act
        _SCREAMING_SNAKE_CASE     =      use_absolute_embeddings
        _SCREAMING_SNAKE_CASE     =      patch_norm
        _SCREAMING_SNAKE_CASE     =      layer_norm_eps
        _SCREAMING_SNAKE_CASE     =      initializer_range
        _SCREAMING_SNAKE_CASE     =      is_training
        _SCREAMING_SNAKE_CASE     =      scope
        _SCREAMING_SNAKE_CASE     =      use_labels
        _SCREAMING_SNAKE_CASE     =      upscale

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


    def       snake_case_(		self	)		->       Union[str, Any]:
        _SCREAMING_SNAKE_CASE     =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

        _SCREAMING_SNAKE_CASE     =      self.get_config()

        return config, pixel_values, labels


    def       snake_case_(		self	)		->       Dict:
        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			,		A			,		A			,		A	)		->       Dict:
        _SCREAMING_SNAKE_CASE     =      SwinaSRModel(config=A	)
        model.to(A	)
        model.eval()
        _SCREAMING_SNAKE_CASE     =      model(A	)

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


    def       snake_case_(		self			,		A			,		A			,		A	)		->       Any:
        _SCREAMING_SNAKE_CASE     =      SwinaSRForImageSuperResolution(A	)
        model.to(A	)
        model.eval()
        _SCREAMING_SNAKE_CASE     =      model(A	)

        _SCREAMING_SNAKE_CASE     =      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	)		->       List[Any]:
        _SCREAMING_SNAKE_CASE     =      self.prepare_config_and_inputs()
        _SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE     =      config_and_inputs
        _SCREAMING_SNAKE_CASE     =      {"""pixel_values""": pixel_values}
        return config, inputs_dict




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

    '''simple docstring'''
    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	)		->       int:
        _SCREAMING_SNAKE_CASE     =      SwinaSRModelTester(self	)
        _SCREAMING_SNAKE_CASE     =      ConfigTester(self			,		config_class=A			,		embed_dim=37	)


    def       snake_case_(		self	)		->       List[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       snake_case_(		self	)		->       Union[str, Any]:
        _SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A	)


    def       snake_case_(		self	)		->       Dict:
        _SCREAMING_SNAKE_CASE     =      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       snake_case_(		self	)		->       Optional[int]:
        pass


    @unittest.skip(reason="""Swin2SR does not use inputs_embeds"""	)
    def       snake_case_(		self	)		->       Any:
        pass


    @unittest.skip(reason="""Swin2SR does not support training yet"""	)
    def       snake_case_(		self	)		->       Optional[Any]:
        pass


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


    def       snake_case_(		self	)		->       Any:
        _SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs_for_common()

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


    def       snake_case_(		self	)		->       Optional[Any]:
        _SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs_for_common()

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

            _SCREAMING_SNAKE_CASE     =      ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]			,		A	)


    @slow
    def       snake_case_(		self	)		->       Union[str, Any]:
        for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _SCREAMING_SNAKE_CASE     =      SwinaSRModel.from_pretrained(A	)
            self.assertIsNotNone(A	)


    def       snake_case_(		self	)		->       List[str]:
        _SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs_for_common()

        _SCREAMING_SNAKE_CASE     =      _config_zero_init(A	)
        for model_class in self.all_model_classes:
            _SCREAMING_SNAKE_CASE     =      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       snake_case_(		self	)		->       Any:
        _SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs_for_common()
        _SCREAMING_SNAKE_CASE     =      True

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

            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            _SCREAMING_SNAKE_CASE     =      True
            _SCREAMING_SNAKE_CASE     =      config.window_size**2
            _SCREAMING_SNAKE_CASE     =      model_class(A	)
            model.to(A	)
            model.eval()
            with torch.no_grad():
                _SCREAMING_SNAKE_CASE     =      model(**self._prepare_for_class(A			,		A	)	)
            _SCREAMING_SNAKE_CASE     =      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]			,		)
            _SCREAMING_SNAKE_CASE     =      len(A	)

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

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

            _SCREAMING_SNAKE_CASE     =      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  a_					(    unittest.TestCase	):

    '''simple docstring'''


    def       snake_case_(		self	)		->       List[Any]:
        _SCREAMING_SNAKE_CASE     =      SwinaSRImageProcessor()
        _SCREAMING_SNAKE_CASE     =      SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""	).to(A	)

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

        # forward pass
        with torch.no_grad():
            _SCREAMING_SNAKE_CASE     =      model(**A	)

        # verify the logits
        _SCREAMING_SNAKE_CASE     =      torch.Size([1, 3, 976, 1296]	)
        self.assertEqual(outputs.reconstruction.shape			,		A	)
        _SCREAMING_SNAKE_CASE     =      torch.tensor(
            [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]]	).to(A	)
        self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]			,		A			,		atol=1e-4	)	)










'''simple docstring'''

def lowerCamelCase						(					__lowerCamelCase			:   int ,	__lowerCamelCase			:   int ,	__lowerCamelCase			:   int ,	__lowerCamelCase			:   int   )						->int:
    return len_board * len_board_column * row + column





def lowerCamelCase						(					__lowerCamelCase			:   list[list[str]] ,	__lowerCamelCase			:   str ,	__lowerCamelCase			:   int ,	__lowerCamelCase			:   int ,	__lowerCamelCase			:   int ,	__lowerCamelCase			:   set[int] ,	)						->bool:

    if board[row][column] != word[word_index]:
        return False

    if word_index == len(__lowerCamelCase   ) - 1:
        return True

    _SCREAMING_SNAKE_CASE     =      [(0, 1), (0, -1), (-1, 0), (1, 0)]
    _SCREAMING_SNAKE_CASE     =      len(__lowerCamelCase   )
    _SCREAMING_SNAKE_CASE     =      len(board[0]   )
    for direction in traverts_directions:
        _SCREAMING_SNAKE_CASE     =      row + direction[0]
        _SCREAMING_SNAKE_CASE     =      column + direction[1]
        if not (0 <= next_i < len_board and 0 <= next_j < len_board_column):
            continue

        _SCREAMING_SNAKE_CASE     =      get_point_key(__lowerCamelCase ,	__lowerCamelCase ,	__lowerCamelCase ,	__lowerCamelCase   )
        if key in visited_points_set:
            continue

        visited_points_set.add(__lowerCamelCase   )
        if exits_word(__lowerCamelCase ,	__lowerCamelCase ,	__lowerCamelCase ,	__lowerCamelCase ,	word_index + 1 ,	__lowerCamelCase   ):
            return True

        visited_points_set.remove(__lowerCamelCase   )

    return False





def lowerCamelCase						(					__lowerCamelCase			:   list[list[str]] ,	__lowerCamelCase			:   str   )						->bool:
    _SCREAMING_SNAKE_CASE     =      (
        """The board should be a non empty matrix of single chars strings."""
    )

    _SCREAMING_SNAKE_CASE     =      len(__lowerCamelCase   )
    if not isinstance(__lowerCamelCase ,	__lowerCamelCase   ) or len(__lowerCamelCase   ) == 0:
        raise ValueError(__lowerCamelCase   )

    for row in board:
        if not isinstance(__lowerCamelCase ,	__lowerCamelCase   ) or len(__lowerCamelCase   ) == 0:
            raise ValueError(__lowerCamelCase   )

        for item in row:
            if not isinstance(__lowerCamelCase ,	__lowerCamelCase   ) or len(__lowerCamelCase   ) != 1:
                raise ValueError(__lowerCamelCase   )

    # Validate word
    if not isinstance(__lowerCamelCase ,	__lowerCamelCase   ) or len(__lowerCamelCase   ) == 0:
        raise ValueError(
            """The word parameter should be a string of length greater than 0."""   )

    _SCREAMING_SNAKE_CASE     =      len(board[0]   )
    for i in range(__lowerCamelCase   ):
        for j in range(__lowerCamelCase   ):
            if exits_word(
                __lowerCamelCase ,	__lowerCamelCase ,	__lowerCamelCase ,	__lowerCamelCase ,	0 ,	{get_point_key(__lowerCamelCase ,	__lowerCamelCase ,	__lowerCamelCase ,	__lowerCamelCase   )}   ):
                return True

    return False


if __name__ == "__main__":
      import doctest

      doctest.testmod()



