




'''simple docstring'''



import copy

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


UpperCAmelCase_       :  Tuple      =		logging.get_logger(__name__)

UpperCAmelCase_       :  Any      =		{
    '''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     lowerCAmelCase   ( _a):


       def __init__(   self    ,  __SCREAMING_SNAKE_CASE=256    ,  __SCREAMING_SNAKE_CASE=1024    ,  __SCREAMING_SNAKE_CASE=16    ,  __SCREAMING_SNAKE_CASE=16    ,  __SCREAMING_SNAKE_CASE=4    ,  __SCREAMING_SNAKE_CASE="gelu"    ,  __SCREAMING_SNAKE_CASE=1E-6    ,  **__SCREAMING_SNAKE_CASE    ,  )      ->  Union[str, Any]:



            '''simple docstring'''




            super().__init__(**__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  hidden_size
            __snake_case    					=  image_size
            __snake_case    					=  patch_size
            __snake_case    					=  image_size // patch_size
            __snake_case    					=  mask_input_channels
            __snake_case    					=  num_point_embeddings
            __snake_case    					=  hidden_act
            __snake_case    					=  layer_norm_eps





class     lowerCAmelCase   ( _a):


       def __init__(   self    ,  __SCREAMING_SNAKE_CASE=256    ,  __SCREAMING_SNAKE_CASE="relu"    ,  __SCREAMING_SNAKE_CASE=2048    ,  __SCREAMING_SNAKE_CASE=2    ,  __SCREAMING_SNAKE_CASE=8    ,  __SCREAMING_SNAKE_CASE=2    ,  __SCREAMING_SNAKE_CASE=3    ,  __SCREAMING_SNAKE_CASE=3    ,  __SCREAMING_SNAKE_CASE=256    ,  __SCREAMING_SNAKE_CASE=1E-6    ,  **__SCREAMING_SNAKE_CASE    ,  )      ->  int:



            '''simple docstring'''




            super().__init__(**__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  hidden_size
            __snake_case    					=  hidden_act
            __snake_case    					=  mlp_dim
            __snake_case    					=  num_hidden_layers
            __snake_case    					=  num_attention_heads
            __snake_case    					=  attention_downsample_rate
            __snake_case    					=  num_multimask_outputs
            __snake_case    					=  iou_head_depth
            __snake_case    					=  iou_head_hidden_dim
            __snake_case    					=  layer_norm_eps





class     lowerCAmelCase   ( _a):


       def __init__(   self    ,  __SCREAMING_SNAKE_CASE=768    ,  __SCREAMING_SNAKE_CASE=256    ,  __SCREAMING_SNAKE_CASE=12    ,  __SCREAMING_SNAKE_CASE=12    ,  __SCREAMING_SNAKE_CASE=3    ,  __SCREAMING_SNAKE_CASE=1024    ,  __SCREAMING_SNAKE_CASE=16    ,  __SCREAMING_SNAKE_CASE="gelu"    ,  __SCREAMING_SNAKE_CASE=1E-06    ,  __SCREAMING_SNAKE_CASE=0.0    ,  __SCREAMING_SNAKE_CASE=1E-10    ,  __SCREAMING_SNAKE_CASE=True    ,  __SCREAMING_SNAKE_CASE=4.0    ,  __SCREAMING_SNAKE_CASE=True    ,  __SCREAMING_SNAKE_CASE=True    ,  __SCREAMING_SNAKE_CASE=14    ,  __SCREAMING_SNAKE_CASE=[2, 5, 8, 11]    ,  __SCREAMING_SNAKE_CASE=128    ,  __SCREAMING_SNAKE_CASE=None    ,  **__SCREAMING_SNAKE_CASE    ,  )      ->  Optional[int]:



            '''simple docstring'''




            super().__init__(**__SCREAMING_SNAKE_CASE  )

            __snake_case    					=  hidden_size
            __snake_case    					=  output_channels
            __snake_case    					=  num_hidden_layers
            __snake_case    					=  num_attention_heads
            __snake_case    					=  num_channels
            __snake_case    					=  image_size
            __snake_case    					=  patch_size
            __snake_case    					=  hidden_act
            __snake_case    					=  layer_norm_eps
            __snake_case    					=  attention_dropout
            __snake_case    					=  initializer_range
            __snake_case    					=  qkv_bias
            __snake_case    					=  mlp_ratio
            __snake_case    					=  use_abs_pos
            __snake_case    					=  use_rel_pos
            __snake_case    					=  window_size
            __snake_case    					=  global_attn_indexes
            __snake_case    					=  num_pos_feats
            __snake_case    					=  int(hidden_size * mlp_ratio  ) if mlp_dim is None else mlp_dim





class     lowerCAmelCase   ( _a):
       __lowercase  :      Optional[Any]        =			'sam'
       __lowercase  :      List[Any]        =			True


       def __init__(   self    ,  __SCREAMING_SNAKE_CASE=None    ,  __SCREAMING_SNAKE_CASE=None    ,  __SCREAMING_SNAKE_CASE=None    ,  __SCREAMING_SNAKE_CASE=0.02    ,  **__SCREAMING_SNAKE_CASE    ,  )      ->  Dict:



            '''simple docstring'''




            super().__init__(**__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  vision_config if vision_config is not None else {}
            __snake_case    					=  prompt_encoder_config if prompt_encoder_config is not None else {}
            __snake_case    					=  mask_decoder_config if mask_decoder_config is not None else {}

            if isinstance(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  ):
                 __snake_case    					=  vision_config.to_dict()
            if isinstance(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  ):
                 __snake_case    					=  prompt_encoder_config.to_dict()
            if isinstance(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  ):
                 __snake_case    					=  mask_decoder_config.to_dict()

            __snake_case    					=  SamVisionConfig(**__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  SamPromptEncoderConfig(**__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  SamMaskDecoderConfig(**__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  initializer_range




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



            '''simple docstring'''




            __snake_case    					=  copy.deepcopy(self.__dict__  )
            __snake_case    					=  self.vision_config.to_dict()
            __snake_case    					=  self.prompt_encoder_config.to_dict()
            __snake_case    					=  self.mask_decoder_config.to_dict()
            __snake_case    					=  self.__class__.model_type
            return output












'''simple docstring'''



from typing import Any

import numpy as np







def 			_UpperCamelCase (_lowerCamelCase							:     np.ndarray	)->   bool:




     '''simple docstring'''





     assert np.shape(_lowerCamelCase	)[0] == np.shape(_lowerCamelCase	)[1]

     # If matrix not symmetric, exit right away.
     if np.allclose(_lowerCamelCase   ,	matrix.T	) is False:
          return False

     # Get eigenvalues and eignevectors for a symmetric matrix.
     __snake_case					,    __snake_case    					=  np.linalg.eigh(_lowerCamelCase	)

     # Check sign of all eigenvalues.
     # np.all returns a value of type np.bool_
     return bool(np.all(eigen_values > 0	)	)







def 			_UpperCamelCase (_lowerCamelCase							:     int	)->   Any:




     '''simple docstring'''





     __snake_case    					=  np.random.randn(_lowerCamelCase   ,	_lowerCamelCase	)
     __snake_case    					=  np.dot(_lowerCamelCase   ,	random_matrix.T	)
     assert _is_matrix_spd(_lowerCamelCase	)
     return spd_matrix







def 			_UpperCamelCase (_lowerCamelCase							:     np.ndarray   ,	_lowerCamelCase							:     np.ndarray   ,	_lowerCamelCase							:     int = 10_00   ,	_lowerCamelCase							:     float = 1E-8   ,	)->   Any:




     '''simple docstring'''





     assert np.shape(_lowerCamelCase	)[0] == np.shape(_lowerCamelCase	)[1]
     assert np.shape(_lowerCamelCase	)[0] == np.shape(_lowerCamelCase	)[0]
     assert _is_matrix_spd(_lowerCamelCase	)

     # Initialize solution guess, residual, search direction.
     __snake_case    					=  np.zeros((np.shape(_lowerCamelCase	)[0], 1)	)
     __snake_case    					=  np.copy(_lowerCamelCase	)
     __snake_case    					=  np.copy(_lowerCamelCase	)

     # Set initial errors in solution guess and residual.
     __snake_case    					=  1E9
     __snake_case    					=  1E9
     __snake_case    					=  1E9

     # Set iteration counter to threshold number of iterations.
     __snake_case    					=  0

     while error > tol:
          # Save this value so we only calculate the matrix-vector product once.
          __snake_case    					=  np.dot(_lowerCamelCase   ,	_lowerCamelCase	)

          # The main algorithm.

          # Update search direction magnitude.
          __snake_case    					=  np.dot(ra.T   ,	_lowerCamelCase	) / np.dot(pa.T   ,	_lowerCamelCase	)
          # Update solution guess.
          __snake_case    					=  xa + alpha * pa
          # Calculate new residual.
          __snake_case    					=  ra - alpha * w
          # Calculate new Krylov subspace scale.
          __snake_case    					=  np.dot(r.T   ,	_lowerCamelCase	) / np.dot(ra.T   ,	_lowerCamelCase	)
          # Calculate new A conjuage search direction.
          __snake_case    					=  r + beta * pa

          # Calculate errors.
          __snake_case    					=  np.linalg.norm(r - ra	)
          __snake_case    					=  np.linalg.norm(x - xa	)
          __snake_case    					=  np.maximum(_lowerCamelCase   ,	_lowerCamelCase	)

          # Update variables.
          __snake_case    					=  np.copy(_lowerCamelCase	)
          __snake_case    					=  np.copy(_lowerCamelCase	)
          __snake_case    					=  np.copy(_lowerCamelCase	)

          # Update number of iterations.
          iterations += 1
          if iterations > max_iterations:
               break

     return x







def 			_UpperCamelCase ()->   None:




     '''simple docstring'''





     __snake_case    					=  3
     __snake_case    					=  _create_spd_matrix(_lowerCamelCase	)
     __snake_case    					=  np.random.randn(_lowerCamelCase   ,	1	)
     __snake_case    					=  np.dot(_lowerCamelCase   ,	_lowerCamelCase	)

     # Numpy solution.
     __snake_case    					=  np.linalg.solve(_lowerCamelCase   ,	_lowerCamelCase	)

     # Our implementation.
     __snake_case    					=  conjugate_gradient(_lowerCamelCase   ,	_lowerCamelCase	)

     # Ensure both solutions are close to x_true (and therefore one another).
     assert np.linalg.norm(x_numpy - x_true	) <= 1E-6
     assert np.linalg.norm(x_conjugate_gradient - x_true	) <= 1E-6


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     test_conjugate_gradient()






