





'''simple docstring'''




import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import CvtForImageClassification, CvtModel
  from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor







class   A_	(  lowerCAmelCase_			):




 def      lowercase	(					self       :    Optional[int]    ):
      _UpperCAmelCase     							=   self.config_class(**self.inputs_dict    )
      self.parent.assertTrue(hasattr(snake_case_	,			"embed_dim"    )    )
      self.parent.assertTrue(hasattr(snake_case_	,			"num_heads"    )    )







class   A_	:




 def __init__(					self       :    Any	,			snake_case_       :    Tuple	,			snake_case_       :    List[Any]=1_3	,			snake_case_       :    Any=6_4	,			snake_case_       :    str=3	,			snake_case_       :    List[str]=[1_6, 4_8, 9_6]	,			snake_case_       :    Union[str, Any]=[1, 3, 6]	,			snake_case_       :    List[Any]=[1, 2, 1_0]	,			snake_case_       :    Union[str, Any]=[7, 3, 3]	,			snake_case_       :    Optional[Any]=[4, 2, 2]	,			snake_case_       :    str=[2, 1, 1]	,			snake_case_       :    List[Any]=[2, 2, 2]	,			snake_case_       :    str=[False, False, True]	,			snake_case_       :    Union[str, Any]=[0.0, 0.0, 0.0]	,			snake_case_       :    List[str]=0.0_2	,			snake_case_       :    List[Any]=1e-12	,			snake_case_       :    Any=True	,			snake_case_       :    Tuple=True	,			snake_case_       :    str=2	,			):
      _UpperCAmelCase     							=   parent
      _UpperCAmelCase     							=   batch_size
      _UpperCAmelCase     							=   image_size
      _UpperCAmelCase     							=   patch_sizes
      _UpperCAmelCase     							=   patch_stride
      _UpperCAmelCase     							=   patch_padding
      _UpperCAmelCase     							=   is_training
      _UpperCAmelCase     							=   use_labels
      _UpperCAmelCase     							=   num_labels
      _UpperCAmelCase     							=   num_channels
      _UpperCAmelCase     							=   embed_dim
      _UpperCAmelCase     							=   num_heads
      _UpperCAmelCase     							=   stride_kv
      _UpperCAmelCase     							=   depth
      _UpperCAmelCase     							=   cls_token
      _UpperCAmelCase     							=   attention_drop_rate
      _UpperCAmelCase     							=   initializer_range
      _UpperCAmelCase     							=   layer_norm_eps




 def      lowercase	(					self       :    List[str]    ):
      _UpperCAmelCase     							=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

      _UpperCAmelCase     							=   None
      if self.use_labels:
           _UpperCAmelCase     							=   ids_tensor([self.batch_size]	,			self.num_labels    )

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




 def      lowercase	(					self       :    Any    ):
      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      lowercase	(					self       :    Union[str, Any]	,			snake_case_       :    Union[str, Any]	,			snake_case_       :    int	,			snake_case_       :    Tuple    ):
      _UpperCAmelCase     							=   CvtModel(config=snake_case_    )
      model.to(snake_case_    )
      model.eval()
      _UpperCAmelCase     							=   model(snake_case_    )
      _UpperCAmelCase     							=   (self.image_size, self.image_size)
      _UpperCAmelCase							,  _UpperCAmelCase     							=   image_size[0], image_size[1]
      for i in range(len(self.depth    )    ):
           _UpperCAmelCase     							=   floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
           _UpperCAmelCase     							=   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      lowercase	(					self       :    List[Any]	,			snake_case_       :    Union[str, Any]	,			snake_case_       :    Any	,			snake_case_       :    int    ):
      _UpperCAmelCase     							=   self.num_labels
      _UpperCAmelCase     							=   CvtForImageClassification(snake_case_    )
      model.to(snake_case_    )
      model.eval()
      _UpperCAmelCase     							=   model(snake_case_	,			labels=snake_case_    )
      self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)    )




 def      lowercase	(					self       :    Any    ):
      _UpperCAmelCase     							=   self.prepare_config_and_inputs()
      _UpperCAmelCase							,  _UpperCAmelCase							,  _UpperCAmelCase     							=   config_and_inputs
      _UpperCAmelCase     							=   {"pixel_values": pixel_values}
      return config, inputs_dict







@require_torch
class   A_	(  lowerCAmelCase_							,						lowerCAmelCase_							,						unittest.TestCase			):
 _lowerCamelCase  : Any           =							(CvtModel, CvtForImageClassification) if is_torch_available() else ()
 _lowerCamelCase  : str           =							(
     {"""feature-extraction""": CvtModel, """image-classification""": CvtForImageClassification}
     if is_torch_available()
     else {}
 )

 _lowerCamelCase  : int           =							False
 _lowerCamelCase  : Dict           =							False
 _lowerCamelCase  : Optional[Any]           =							False
 _lowerCamelCase  : Optional[int]           =							False
 _lowerCamelCase  : Union[str, Any]           =							False




 def      lowercase	(					self       :    Tuple    ):
      _UpperCAmelCase     							=   CvtModelTester(self    )
      _UpperCAmelCase     							=   ConfigTester(self	,			config_class=snake_case_	,			has_text_modality=snake_case_	,			hidden_size=3_7    )




 def      lowercase	(					self       :    Any    ):
      self.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()




 def      lowercase	(					self       :    Optional[Any]    ):
      return




 @unittest.skip(reason="Cvt does not output attentions"    )
 def      lowercase	(					self       :    Tuple    ):
      pass




 @unittest.skip(reason="Cvt does not use inputs_embeds"    )
 def      lowercase	(					self       :    Optional[Any]    ):
      pass




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




 def      lowercase	(					self       :    str    ):
      _UpperCAmelCase							,  _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs_for_common()

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

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




 def      lowercase	(					self       :    List[str]    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case_    )




 def      lowercase	(					self       :    Optional[int]    ):
      def check_hidden_states_output(snake_case_       :    List[str]	,			snake_case_       :    Dict	,			snake_case_       :    int    ):
           _UpperCAmelCase     							=   model_class(snake_case_    )
           model.to(snake_case_    )
           model.eval()

           with torch.no_grad():
                _UpperCAmelCase     							=   model(**self._prepare_for_class(snake_case_	,			snake_case_    )    )

           _UpperCAmelCase     							=   outputs.hidden_states

           _UpperCAmelCase     							=   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,
               ]	,			)

      _UpperCAmelCase							,  _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           _UpperCAmelCase     							=   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"]
           _UpperCAmelCase     							=   True

           check_hidden_states_output(snake_case_	,			snake_case_	,			snake_case_    )




 def      lowercase	(					self       :    Dict    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*snake_case_    )




 @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."    )
 def      lowercase	(					self       :    Dict    ):
      pass




 @slow
 def      lowercase	(					self       :    Optional[int]    ):
      for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _UpperCAmelCase     							=   CvtModel.from_pretrained(snake_case_    )
           self.assertIsNotNone(snake_case_    )





def 	UpperCAmelCase_							(					)		->       Optional[int]:


     '''simple docstring'''



     _UpperCAmelCase     							=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
     return image







@require_torch
@require_vision
class   A_	(  unittest.TestCase			):




 @cached_property
 def      lowercase	(					self       :    Any    ):
      return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )




 @slow
 def      lowercase	(					self       :    Union[str, Any]    ):
      _UpperCAmelCase     							=   CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    ).to(snake_case_    )

      _UpperCAmelCase     							=   self.default_image_processor
      _UpperCAmelCase     							=   prepare_img()
      _UpperCAmelCase     							=   image_processor(images=snake_case_	,			return_tensors="pt"    ).to(snake_case_    )

      # forward pass
      with torch.no_grad():
           _UpperCAmelCase     							=   model(**snake_case_    )

      # verify the logits
      _UpperCAmelCase     							=   torch.Size((1, 1_0_0_0)    )
      self.assertEqual(outputs.logits.shape	,			snake_case_    )

      _UpperCAmelCase     							=   torch.tensor([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]    ).to(snake_case_    )

      self.assertTrue(torch.allclose(outputs.logits[0, :3]	,			snake_case_	,			atol=1e-4    )    )











'''simple docstring'''




from __future__ import annotations

from collections.abc import Callable
from typing import Any, Generic, TypeVar

__SCREAMING_SNAKE_CASE     :Optional[int]       =				TypeVar('''T''')







class   A_	(  Generic[T]			):




 def __init__(					self       :    List[Any]	,			snake_case_       :    list[T]	,			snake_case_       :    Callable[[T, T], T]    ):
      _UpperCAmelCase     							=   None

      _UpperCAmelCase     							=   len(snake_case_    )
      _UpperCAmelCase     							=   [any_type for _ in range(self.N    )] + arr
      _UpperCAmelCase     							=   fnc
      self.build()




 def      lowercase	(					self       :    List[Any]    ):
      for p in range(self.N - 1	,			0	,			-1    ):
           _UpperCAmelCase     							=   self.fn(self.st[p * 2]	,			self.st[p * 2 + 1]    )




 def      lowercase	(					self       :    Optional[Any]	,			snake_case_       :    int	,			snake_case_       :    T    ):
      p += self.N
      _UpperCAmelCase     							=   v
      while p > 1:
           _UpperCAmelCase     							=   p // 2
           _UpperCAmelCase     							=   self.fn(self.st[p * 2]	,			self.st[p * 2 + 1]    )




 def      lowercase	(					self       :    Any	,			snake_case_       :    int	,			snake_case_       :    int    ):  # noqa: E741
      _UpperCAmelCase							,  _UpperCAmelCase     							=   l + self.N, r + self.N

      _UpperCAmelCase     							=   None
      while l <= r:
           if l % 2 == 1:
                _UpperCAmelCase     							=   self.st[l] if res is None else self.fn(snake_case_	,			self.st[l]    )
           if r % 2 == 0:
                _UpperCAmelCase     							=   self.st[r] if res is None else self.fn(snake_case_	,			self.st[r]    )
           _UpperCAmelCase							,  _UpperCAmelCase     							=   (l + 1) // 2, (r - 1) // 2
      return res


if __name__ == "__main__":
  from functools import reduce

  __SCREAMING_SNAKE_CASE     :Union[str, Any]       =				[1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]

  __SCREAMING_SNAKE_CASE     :List[str]       =				{
      0: 7,
      1: 2,
      2: 6,
      3: -14,
      4: 5,
      5: 4,
      6: 7,
      7: -10,
      8: 9,
      9: 10,
      10: 12,
      11: 1,
  }

  __SCREAMING_SNAKE_CASE     :Any       =				SegmentTree(test_array, min)
  __SCREAMING_SNAKE_CASE     :Any       =				SegmentTree(test_array, max)
  __SCREAMING_SNAKE_CASE     :Any       =				SegmentTree(test_array, lambda a, b: a + b)
  def 	UpperCAmelCase_							(					)		->       None:


       '''simple docstring'''



       for i in range(len(__lowercase       )       ):
            for j in range(__lowercase			,     len(__lowercase       )       ):
                 _UpperCAmelCase     							=   reduce(__lowercase			,     test_array[i : j + 1]       )
                 _UpperCAmelCase     							=   reduce(__lowercase			,     test_array[i : j + 1]       )
                 _UpperCAmelCase     							=   reduce(lambda __lowercase			,     __lowercase       : a + b			,     test_array[i : j + 1]       )
                 assert min_range == min_segment_tree.query(__lowercase			,     __lowercase       )
                 assert max_range == max_segment_tree.query(__lowercase			,     __lowercase       )
                 assert sum_range == sum_segment_tree.query(__lowercase			,     __lowercase       )

  test_all_segments()

  for index, value in test_updates.items():
    __SCREAMING_SNAKE_CASE     :str       =				value
    min_segment_tree.update(index, value)
    max_segment_tree.update(index, value)
    sum_segment_tree.update(index, value)
    test_all_segments()




