


from __future__ import annotations

from abc import abstractmethod
from collections.abc import Iterable
from typing import Generic, Protocol, TypeVar

class 						UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     @abstractmethod
     def __lt__( self       :       T	,      UpperCamelCase       :       T		):





            """simple docstring"""



            pass




     @abstractmethod
     def __gt__( self       :       T	,      UpperCamelCase       :       T		):





            """simple docstring"""



            pass




     @abstractmethod
     def __eq__( self       :       T	,      UpperCamelCase       :       object		):





            """simple docstring"""



            pass




UpperCamelCase__				       =			TypeVar('T', bound=Comparable)

class 						UpperCAmelCase__   (      Generic[T]		):



     '''simple docstring'''




     def __init__( self       :       Any		):





            """simple docstring"""



            _lowercase					:				list[T]           =			[]
            _lowercase					:				int           =			0




     def __repr__( self       :       List[str]		):





            """simple docstring"""



            return str(self.h		)




     def   lowerCAmelCase_   ( self       :       Optional[Any]	,      UpperCamelCase       :       int		):





            """simple docstring"""



            if child_idx > 0:
                   return (child_idx - 1) // 2
            return None




     def   lowerCAmelCase_   ( self       :       str	,      UpperCamelCase       :       int		):





            """simple docstring"""



            _lowercase					:				str           =			2 * parent_idx + 1
            if left_child_index < self.heap_size:
                   return left_child_index
            return None




     def   lowerCAmelCase_   ( self       :       Union[str, Any]	,      UpperCamelCase       :       int		):





            """simple docstring"""



            _lowercase					:				Optional[int]           =			2 * parent_idx + 2
            if right_child_index < self.heap_size:
                   return right_child_index
            return None




     def   lowerCAmelCase_   ( self       :       Tuple	,      UpperCamelCase       :       int		):





            """simple docstring"""



            if index < self.heap_size:
                   _lowercase					:				int           =			index
                   _lowercase					:				Any           =			self.left_child_idx(UpperCamelCase		)
                   _lowercase					:				Union[str, Any]           =			self.right_child_idx(UpperCamelCase		)
                   # check which child is larger than its parent
                   if left_child is not None and self.h[left_child] > self.h[violation]:
                          _lowercase					:				List[str]           =			left_child
                   if right_child is not None and self.h[right_child] > self.h[violation]:
                          _lowercase					:				Union[str, Any]           =			right_child
                   # if violation indeed exists
                   if violation != index:
                          # swap to fix the violation
                          _lowercase       ,	_lowercase					:				List[Any]           =			self.h[index], self.h[violation]
                          # fix the subsequent violation recursively if any
                          self.max_heapify(UpperCamelCase		)




     def   lowerCAmelCase_   ( self       :       str	,      UpperCamelCase       :       Iterable[T]		):





            """simple docstring"""



            _lowercase					:				List[str]           =			list(UpperCamelCase		)
            _lowercase					:				List[str]           =			len(self.h		)
            if self.heap_size > 1:
                   # max_heapify from right to left but exclude leaves (last level)
                   for i in range(self.heap_size // 2 - 1	,      -1	,      -1		):
                          self.max_heapify(UpperCamelCase		)




     def   lowerCAmelCase_   ( self       :       int		):





            """simple docstring"""



            if self.heap_size >= 2:
                   _lowercase					:				Dict           =			self.h[0]
                   _lowercase					:				List[str]           =			self.h.pop(-1		)
                   self.heap_size -= 1
                   self.max_heapify(0		)
                   return me
            elif self.heap_size == 1:
                   self.heap_size -= 1
                   return self.h.pop(-1		)
            else:
                   raise Exception('''Empty heap'''		)




     def   lowerCAmelCase_   ( self       :       Any	,      UpperCamelCase       :       T		):





            """simple docstring"""



            self.h.append(UpperCamelCase		)
            _lowercase					:				List[Any]           =			(self.heap_size - 1) // 2
            self.heap_size += 1
            while idx >= 0:
                   self.max_heapify(UpperCamelCase		)
                   _lowercase					:				Union[str, Any]           =			(idx - 1) // 2




     def   lowerCAmelCase_   ( self       :       str		):





            """simple docstring"""



            _lowercase					:				List[str]           =			self.heap_size
            for j in range(size - 1	,      0	,      -1		):
                   _lowercase       ,	_lowercase					:				Optional[Any]           =			self.h[j], self.h[0]
                   self.heap_size -= 1
                   self.max_heapify(0		)
            _lowercase					:				Any           =			size


if __name__ == "__main__":
   import doctest

   # run doc test
   doctest.testmod()

   # demo
   for unsorted in [
       [0],
       [2],
       [3, 5],
       [5, 3],
       [5, 5],
       [0, 0, 0, 0],
       [1, 1, 1, 1],
       [2, 2, 3, 5],
       [0, 2, 2, 3, 5],
       [2, 5, 3, 0, 2, 3, 0, 3],
       [6, 1, 2, 7, 9, 3, 4, 5, 10, 8],
       [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5],
       [-45, -2, -5],
   ]:
      print(F"""unsorted array: {unsorted}""")

      UpperCamelCase__				       =			Heap()
      heap.build_max_heap(unsorted)
      print(F"""after build heap: {heap}""")

      print(F"""max value: {heap.extract_max()}""")
      print(F"""after max value removed: {heap}""")

      heap.insert(100)
      print(F"""after new value 100 inserted: {heap}""")

      heap.heap_sort()
      print(F"""heap-sorted array: {heap}\n""")



import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase__				       =			logging.get_logger(__name__)

UpperCamelCase__				       =			{
    'facebook/sam-vit-huge': 'https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json',
    'facebook/sam-vit-large': 'https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json',
    'facebook/sam-vit-base': 'https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json',
}

class 						UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def __init__( self       :       List[Any]	,      UpperCamelCase       :       Optional[Any]=2_56	,      UpperCamelCase       :       str=10_24	,      UpperCamelCase       :       Any=16	,      UpperCamelCase       :       Optional[Any]=16	,      UpperCamelCase       :       Union[str, Any]=4	,      UpperCamelCase       :       str="gelu"	,      UpperCamelCase       :       Dict=1E-6	,      **UpperCamelCase       :       Tuple	,      ):





            """simple docstring"""



            super().__init__(**UpperCamelCase		)
            _lowercase					:				Union[str, Any]           =			hidden_size
            _lowercase					:				Optional[Any]           =			image_size
            _lowercase					:				Tuple           =			patch_size
            _lowercase					:				List[str]           =			image_size // patch_size
            _lowercase					:				Optional[Any]           =			mask_input_channels
            _lowercase					:				str           =			num_point_embeddings
            _lowercase					:				List[Any]           =			hidden_act
            _lowercase					:				Union[str, Any]           =			layer_norm_eps




class 						UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def __init__( self       :       Optional[int]	,      UpperCamelCase       :       str=2_56	,      UpperCamelCase       :       int="relu"	,      UpperCamelCase       :       Any=20_48	,      UpperCamelCase       :       List[Any]=2	,      UpperCamelCase       :       Union[str, Any]=8	,      UpperCamelCase       :       List[str]=2	,      UpperCamelCase       :       Any=3	,      UpperCamelCase       :       List[Any]=3	,      UpperCamelCase       :       int=2_56	,      UpperCamelCase       :       List[str]=1E-6	,      **UpperCamelCase       :       Tuple	,      ):





            """simple docstring"""



            super().__init__(**UpperCamelCase		)
            _lowercase					:				List[Any]           =			hidden_size
            _lowercase					:				Optional[int]           =			hidden_act
            _lowercase					:				Union[str, Any]           =			mlp_dim
            _lowercase					:				Optional[int]           =			num_hidden_layers
            _lowercase					:				List[str]           =			num_attention_heads
            _lowercase					:				Dict           =			attention_downsample_rate
            _lowercase					:				Optional[Any]           =			num_multimask_outputs
            _lowercase					:				Optional[Any]           =			iou_head_depth
            _lowercase					:				Dict           =			iou_head_hidden_dim
            _lowercase					:				List[str]           =			layer_norm_eps




class 						UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def __init__( self       :       List[str]	,      UpperCamelCase       :       Union[str, Any]=7_68	,      UpperCamelCase       :       Optional[Any]=2_56	,      UpperCamelCase       :       Optional[Any]=12	,      UpperCamelCase       :       Dict=12	,      UpperCamelCase       :       Dict=3	,      UpperCamelCase       :       Optional[int]=10_24	,      UpperCamelCase       :       Any=16	,      UpperCamelCase       :       Union[str, Any]="gelu"	,      UpperCamelCase       :       int=1E-06	,      UpperCamelCase       :       Tuple=0.0	,      UpperCamelCase       :       List[str]=1E-10	,      UpperCamelCase       :       List[Any]=True	,      UpperCamelCase       :       Any=4.0	,      UpperCamelCase       :       str=True	,      UpperCamelCase       :       Optional[int]=True	,      UpperCamelCase       :       Optional[int]=14	,      UpperCamelCase       :       Any=[2, 5, 8, 11]	,      UpperCamelCase       :       Tuple=1_28	,      UpperCamelCase       :       str=None	,      **UpperCamelCase       :       int	,      ):





            """simple docstring"""



            super().__init__(**UpperCamelCase		)

            _lowercase					:				Union[str, Any]           =			hidden_size
            _lowercase					:				Optional[int]           =			output_channels
            _lowercase					:				Dict           =			num_hidden_layers
            _lowercase					:				str           =			num_attention_heads
            _lowercase					:				Dict           =			num_channels
            _lowercase					:				List[Any]           =			image_size
            _lowercase					:				int           =			patch_size
            _lowercase					:				Optional[Any]           =			hidden_act
            _lowercase					:				Any           =			layer_norm_eps
            _lowercase					:				Any           =			attention_dropout
            _lowercase					:				Optional[int]           =			initializer_range
            _lowercase					:				List[str]           =			qkv_bias
            _lowercase					:				Optional[Any]           =			mlp_ratio
            _lowercase					:				Optional[Any]           =			use_abs_pos
            _lowercase					:				List[Any]           =			use_rel_pos
            _lowercase					:				str           =			window_size
            _lowercase					:				Tuple           =			global_attn_indexes
            _lowercase					:				List[Any]           =			num_pos_feats
            _lowercase					:				int           =			int(hidden_size * mlp_ratio		) if mlp_dim is None else mlp_dim




class 						UpperCAmelCase__   (      A_		):



     '''simple docstring'''
     UpperCAmelCase_         =  '''sam'''
     UpperCAmelCase_         =  True




     def __init__( self       :       Tuple	,      UpperCamelCase       :       Tuple=None	,      UpperCamelCase       :       Any=None	,      UpperCamelCase       :       Tuple=None	,      UpperCamelCase       :       Dict=0.02	,      **UpperCamelCase       :       Union[str, Any]	,      ):





            """simple docstring"""



            super().__init__(**UpperCamelCase		)
            _lowercase					:				Optional[int]           =			vision_config if vision_config is not None else {}
            _lowercase					:				Any           =			prompt_encoder_config if prompt_encoder_config is not None else {}
            _lowercase					:				Optional[Any]           =			mask_decoder_config if mask_decoder_config is not None else {}

            if isinstance(UpperCamelCase	,      UpperCamelCase		):
                   _lowercase					:				Dict           =			vision_config.to_dict()
            if isinstance(UpperCamelCase	,      UpperCamelCase		):
                   _lowercase					:				List[str]           =			prompt_encoder_config.to_dict()
            if isinstance(UpperCamelCase	,      UpperCamelCase		):
                   _lowercase					:				Optional[int]           =			mask_decoder_config.to_dict()

            _lowercase					:				Union[str, Any]           =			SamVisionConfig(**UpperCamelCase		)
            _lowercase					:				Optional[Any]           =			SamPromptEncoderConfig(**UpperCamelCase		)
            _lowercase					:				List[Any]           =			SamMaskDecoderConfig(**UpperCamelCase		)
            _lowercase					:				Union[str, Any]           =			initializer_range




     def   lowerCAmelCase_   ( self       :       Union[str, Any]		):





            """simple docstring"""



            _lowercase					:				List[Any]           =			copy.deepcopy(self.__dict__		)
            _lowercase					:				int           =			self.vision_config.to_dict()
            _lowercase					:				Optional[int]           =			self.prompt_encoder_config.to_dict()
            _lowercase					:				List[Any]           =			self.mask_decoder_config.to_dict()
            _lowercase					:				List[Any]           =			self.__class__.model_type
            return output