


"""simple docstring"""




from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import tensorflow as tf

					from transformers import TFCvtForImageClassification, TFCvtModel
					from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor




class 			__snake_case   (lowerCAmelCase__  ):




							def   __a   (     self:    Dict   ):
										__lowerCamelCase          =      self.config_class(**self.inputs_dict   )
										self.parent.assertTrue(hasattr(snake_case_     ,							"""embed_dim"""   )   )
										self.parent.assertTrue(hasattr(snake_case_     ,							"""num_heads"""   )   )




class 			__snake_case   :




							def __init__(     self:    int     ,							A_:    Dict     ,							A_:    List[Any]=13     ,							A_:    List[Any]=64     ,							A_:    Dict=3     ,							A_:    Union[str, Any]=[16, 48, 96]     ,							A_:    Optional[Any]=[1, 3, 6]     ,							A_:    Optional[Any]=[1, 2, 10]     ,							A_:    Any=[7, 3, 3]     ,							A_:    List[Any]=[4, 2, 2]     ,							A_:    Union[str, Any]=[2, 1, 1]     ,							A_:    Any=[2, 2, 2]     ,							A_:    List[Any]=[False, False, True]     ,							A_:    Optional[Any]=[0.0, 0.0, 0.0]     ,							A_:    int=0.02     ,							A_:    List[Any]=1E-12     ,							A_:    List[str]=True     ,							A_:    int=True     ,							A_:    Any=2     ,							):
										__lowerCamelCase          =      parent
										__lowerCamelCase          =      batch_size
										__lowerCamelCase          =      image_size
										__lowerCamelCase          =      patch_sizes
										__lowerCamelCase          =      patch_stride
										__lowerCamelCase          =      patch_padding
										__lowerCamelCase          =      is_training
										__lowerCamelCase          =      use_labels
										__lowerCamelCase          =      num_labels
										__lowerCamelCase          =      num_channels
										__lowerCamelCase          =      embed_dim
										__lowerCamelCase          =      num_heads
										__lowerCamelCase          =      stride_kv
										__lowerCamelCase          =      depth
										__lowerCamelCase          =      cls_token
										__lowerCamelCase          =      attention_drop_rate
										__lowerCamelCase          =      initializer_range
										__lowerCamelCase          =      layer_norm_eps




							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:
													# create a random int32 tensor of given shape
													__lowerCamelCase          =      ids_tensor([self.batch_size]     ,							self.num_labels   )

										__lowerCamelCase          =      self.get_config()
										return config, pixel_values, labels




							def   __a   (     self:    str   ):
										return CvtConfig(
										    image_size=self.image_size     ,							num_labels=self.num_labels     ,							num_channels=self.num_channels     ,							embed_dim=self.embed_dim     ,							num_heads=self.num_heads     ,							patch_sizes=self.patch_sizes     ,							patch_padding=self.patch_padding     ,							patch_stride=self.patch_stride     ,							stride_kv=self.stride_kv     ,							depth=self.depth     ,							cls_token=self.cls_token     ,							attention_drop_rate=self.attention_drop_rate     ,							initializer_range=self.initializer_range     ,							)




							def   __a   (     self:    Union[str, Any]     ,							A_:    int     ,							A_:    Optional[int]     ,							A_:    Dict   ):
										__lowerCamelCase          =      TFCvtModel(config=snake_case_   )
										__lowerCamelCase          =      model(snake_case_     ,							training=snake_case_   )
										__lowerCamelCase          =      (self.image_size, self.image_size)
										__lowerCamelCase     ,__lowerCamelCase          =      image_size[0], image_size[1]
										for i in range(len(self.depth   )   ):
													__lowerCamelCase          =      floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
													__lowerCamelCase          =      floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
										self.parent.assertEqual(result.last_hidden_state.shape     ,							(self.batch_size, self.embed_dim[-1], height, width)   )




							def   __a   (     self:    List[str]     ,							A_:    List[Any]     ,							A_:    Union[str, Any]     ,							A_:    Any   ):
										__lowerCamelCase          =      self.num_labels
										__lowerCamelCase          =      TFCvtForImageClassification(snake_case_   )
										__lowerCamelCase          =      model(snake_case_     ,							labels=snake_case_     ,							training=snake_case_   )
										self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)   )




							def   __a   (     self:    Union[str, Any]   ):
										__lowerCamelCase          =      self.prepare_config_and_inputs()
										__lowerCamelCase     ,__lowerCamelCase     ,__lowerCamelCase          =      config_and_inputs
										__lowerCamelCase          =      {"""pixel_values""": pixel_values}
										return config, inputs_dict




@require_tf
class 			__snake_case   (lowerCAmelCase__			,		lowerCAmelCase__			,		unittest.TestCase  ):
							__a					 =       (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
							__a					 =       (
							    {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
							    if is_tf_available()
							    else {}
							)
							__a					 =       False
							__a					 =       False
							__a					 =       False
							__a					 =       False
							__a					 =       False




							def   __a   (     self:    Dict   ):
										__lowerCamelCase          =      TFCvtModelTester(self   )
										__lowerCamelCase          =      TFCvtConfigTester(self     ,							config_class=snake_case_     ,							has_text_modality=snake_case_     ,							hidden_size=37   )




							def   __a   (     self:    Any   ):
										self.config_tester.create_and_test_config_common_properties()
										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()




							@unittest.skip(reason="""Cvt does not output attentions"""   )
							def   __a   (     self:    List[Any]   ):
										pass




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




							@unittest.skip(reason="""Cvt does not support input and output embeddings"""   )
							def   __a   (     self:    Optional[int]   ):
										pass




							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""   )   ) == 0     ,							reason="""TF does not support backprop for grouped convolutions on CPU."""     ,							)
							def   __a   (     self:    Union[str, Any]   ):
										super().test_dataset_conversion()




							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""   )   ) == 0     ,							reason="""TF does not support backprop for grouped convolutions on CPU."""     ,							)
							@slow
							def   __a   (     self:    str   ):
										super().test_keras_fit()




							@unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"""   )
							def   __a   (     self:    Dict   ):
										__lowerCamelCase          =      tf.keras.mixed_precision.Policy("""mixed_float16"""   )
										tf.keras.mixed_precision.set_global_policy(snake_case_   )
										super().test_keras_fit()
										tf.keras.mixed_precision.set_global_policy("""float32"""   )




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

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

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




							def   __a   (     self:    Optional[Any]   ):

										def check_hidden_states_output(A_:    Dict     ,							A_:    str     ,							A_:    List[str]   ):
													__lowerCamelCase          =      model_class(snake_case_   )

													__lowerCamelCase          =      model(**self._prepare_for_class(snake_case_     ,							snake_case_   )   )
													__lowerCamelCase          =      outputs.hidden_states

													__lowerCamelCase          =      len(self.model_tester.depth   )
													self.assertEqual(len(snake_case_   )     ,							snake_case_   )

													# verify the first hidden states (first block)
													self.assertListEqual(
													    list(hidden_states[0].shape[-3:]   )     ,							[
													        self.model_tester.embed_dim[0],
													        self.model_tester.image_size // 4,
													        self.model_tester.image_size // 4,
													    ]     ,							)

										__lowerCamelCase     ,__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													__lowerCamelCase          =      True
													check_hidden_states_output(snake_case_     ,							snake_case_     ,							snake_case_   )

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													__lowerCamelCase          =      True

													check_hidden_states_output(snake_case_     ,							snake_case_     ,							snake_case_   )




							def   __a   (     self:    Optional[int]   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*snake_case_   )




							def   __a   (     self:    Dict   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*snake_case_   )




							@slow
							def   __a   (     self:    int   ):

										for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__lowerCamelCase          =      TFCvtModel.from_pretrained(snake_case_   )
													self.assertIsNotNone(snake_case_   )





def       a_ (	):
			__lowerCamelCase          =      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
			return image




@require_tf
@require_vision
class 			__snake_case   (unittest.TestCase  ):




							@cached_property
							def   __a   (     self:    Union[str, Any]   ):
										return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )




							@slow
							def   __a   (     self:    List[str]   ):
										__lowerCamelCase          =      TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

										__lowerCamelCase          =      self.default_image_processor
										__lowerCamelCase          =      prepare_img()
										__lowerCamelCase          =      image_processor(images=snake_case_     ,							return_tensors="""tf"""   )

										# forward pass
										__lowerCamelCase          =      model(**snake_case_   )

										# verify the logits
										__lowerCamelCase          =      tf.TensorShape((1, 10_00)   )
										self.assertEqual(outputs.logits.shape     ,							snake_case_   )

										__lowerCamelCase          =      tf.constant([0.9_285, 0.9_015, -0.3_150]   )
										self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,							snake_case_     ,							atol=1E-4   )   )








import doctest
from collections import deque

import numpy as np
class 						lowerCamelCase_							:



					'''simple docstring'''







					def __init__(					self    ) ->      None:







								'''simple docstring'''

								__lowercase			       = [2, 1, 2, -1]
								__lowercase			       = [1, 2, 3, 4]






					def A   (					self    ) ->      list[float]:







								'''simple docstring'''

								__lowercase			       = len(self.first_signal    )
								__lowercase			       = len(self.second_signal    )

								__lowercase			       = max(snake_case_			,							snake_case_    )

								# create a zero matrix of max_length x max_length
								__lowercase			       = [[0] * max_length for i in range(snake_case_    )]

								# fills the smaller signal with zeros to make both signals of same length
								if length_first_signal < length_second_signal:
											self.first_signal += [0] * (max_length - length_first_signal)
								elif length_first_signal > length_second_signal:
											self.second_signal += [0] * (max_length - length_second_signal)
								for i in range(snake_case_    ):
											__lowercase			       = deque(self.second_signal    )
											rotated_signal.rotate(snake_case_    )
											for j, item in enumerate(snake_case_    ):
														matrix[i][j] += item

        # multiply the matrix with the first signal
								__lowercase			       = np.matmul(np.transpose(snake_case_    )			,							np.transpose(self.first_signal    )    )

								# rounding-off to two decimal places
								return [round(snake_case_			,							2    ) for i in final_signal]


if __name__ == "__main__":
	doctest.testmod()


