





"""simple docstring"""
import copy

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


lowerCAmelCase:	Tuple							      =logging.get_logger(__name__)

lowerCAmelCase:	List[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__  (    __UpperCamelCase				):



   def __init__(       self      ,   snake_case=2_5_6      ,   snake_case=1_0_2_4      ,   snake_case=1_6      ,   snake_case=1_6      ,   snake_case=4      ,   snake_case="gelu"      ,   snake_case=1E-6      ,   **snake_case      ,   ) ->    List[Any]:







      """simple docstring"""
      super().__init__(**snake_case	)
      lowercase    :			Union[str, Any]  =       hidden_size
      lowercase    :			Optional[Any]  =       image_size
      lowercase    :			int  =       patch_size
      lowercase    :			Dict  =       image_size // patch_size
      lowercase    :			Any  =       mask_input_channels
      lowercase    :			int  =       num_point_embeddings
      lowercase    :			Union[str, Any]  =       hidden_act
      lowercase    :			Optional[int]  =       layer_norm_eps




class lowerCamelCase__  (    __UpperCamelCase				):



   def __init__(       self      ,   snake_case=2_5_6      ,   snake_case="relu"      ,   snake_case=2_0_4_8      ,   snake_case=2      ,   snake_case=8      ,   snake_case=2      ,   snake_case=3      ,   snake_case=3      ,   snake_case=2_5_6      ,   snake_case=1E-6      ,   **snake_case      ,   ) ->    Optional[Any]:







      """simple docstring"""
      super().__init__(**snake_case	)
      lowercase    :			List[str]  =       hidden_size
      lowercase    :			Optional[Any]  =       hidden_act
      lowercase    :			Optional[int]  =       mlp_dim
      lowercase    :			int  =       num_hidden_layers
      lowercase    :			Tuple  =       num_attention_heads
      lowercase    :			Optional[int]  =       attention_downsample_rate
      lowercase    :			Optional[Any]  =       num_multimask_outputs
      lowercase    :			Any  =       iou_head_depth
      lowercase    :			List[Any]  =       iou_head_hidden_dim
      lowercase    :			Optional[Any]  =       layer_norm_eps




class lowerCamelCase__  (    __UpperCamelCase				):



   def __init__(       self      ,   snake_case=7_6_8      ,   snake_case=2_5_6      ,   snake_case=1_2      ,   snake_case=1_2      ,   snake_case=3      ,   snake_case=1_0_2_4      ,   snake_case=1_6      ,   snake_case="gelu"      ,   snake_case=1E-06      ,   snake_case=0.0      ,   snake_case=1E-10      ,   snake_case=True      ,   snake_case=4.0      ,   snake_case=True      ,   snake_case=True      ,   snake_case=1_4      ,   snake_case=[2, 5, 8, 1_1]      ,   snake_case=1_2_8      ,   snake_case=None      ,   **snake_case      ,   ) ->    Union[str, Any]:







      """simple docstring"""
      super().__init__(**snake_case	)

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




class lowerCamelCase__  (    __UpperCamelCase				):
   __UpperCAmelCase        =					"""sam"""
   __UpperCAmelCase        =					True



   def __init__(       self      ,   snake_case=None      ,   snake_case=None      ,   snake_case=None      ,   snake_case=0.02      ,   **snake_case      ,   ) ->    Tuple:







      """simple docstring"""
      super().__init__(**snake_case	)
      lowercase    :			Any  =       vision_config if vision_config is not None else {}
      lowercase    :			Optional[int]  =       prompt_encoder_config if prompt_encoder_config is not None else {}
      lowercase    :			str  =       mask_decoder_config if mask_decoder_config is not None else {}

      if isinstance(snake_case      ,   snake_case	):
         lowercase    :			str  =       vision_config.to_dict()
      if isinstance(snake_case      ,   snake_case	):
         lowercase    :			Optional[int]  =       prompt_encoder_config.to_dict()
      if isinstance(snake_case      ,   snake_case	):
         lowercase    :			Optional[Any]  =       mask_decoder_config.to_dict()

      lowercase    :			Any  =       SamVisionConfig(**snake_case	)
      lowercase    :			Tuple  =       SamPromptEncoderConfig(**snake_case	)
      lowercase    :			List[str]  =       SamMaskDecoderConfig(**snake_case	)
      lowercase    :			List[str]  =       initializer_range





   def    _UpperCAmelCase	(       self	) ->    int:







      """simple docstring"""
      lowercase    :			Optional[int]  =       copy.deepcopy(self.__dict__	)
      lowercase    :			str  =       self.vision_config.to_dict()
      lowercase    :			List[Any]  =       self.prompt_encoder_config.to_dict()
      lowercase    :			Optional[Any]  =       self.mask_decoder_config.to_dict()
      lowercase    :			Tuple  =       self.__class__.model_type
      return output









"""simple docstring"""
import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
   import transformer_engine.pytorch as te




def 			__snake_case						(      __A ,__A=True ,__A=True ,__A=True    )		->				Union[str, Any]:
   if not is_fpa_available():
      raise ImportError("""Using `convert_model` requires transformer_engine to be installed."""    )
   for name, module in model.named_children():
      if isinstance(__A ,nn.Linear    ) and to_transformer_engine and _convert_linear:
         # Return early if the linear layer weights are not multiples of 16
         if any(p % 16 != 0 for p in module.weight.shape    ):
            return
         lowercase    :			Optional[int]  =       module.bias is not None
         lowercase    :			Union[str, Any]  =       te.Linear(
             module.in_features ,module.out_features ,bias=__A ,params_dtype=module.weight.dtype    )
         lowercase    :			Union[str, Any]  =       module.weight.data.clone()
         if has_bias:
            lowercase    :			Dict  =       module.bias.data.clone()

         setattr(__A ,__A ,__A    )
      elif isinstance(__A ,nn.LayerNorm    ) and to_transformer_engine and _convert_ln:
         lowercase    :			List[str]  =       te.LayerNorm(module.normalized_shape[0] ,eps=module.eps ,params_dtype=module.weight.dtype    )
         lowercase    :			Optional[Any]  =       module.weight.data.clone()
         lowercase    :			Any  =       module.bias.data.clone()

         setattr(__A ,__A ,__A    )
      elif isinstance(__A ,te.Linear    ) and not to_transformer_engine and _convert_linear:
         lowercase    :			Any  =       module.bias is not None
         lowercase    :			List[Any]  =       nn.Linear(
             module.in_features ,module.out_features ,bias=__A ,params_dtype=module.weight.dtype    )
         lowercase    :			Union[str, Any]  =       module.weight.data.clone()
         if has_bias:
            lowercase    :			Optional[Any]  =       module.bias.data.clone()

         setattr(__A ,__A ,__A    )
      elif isinstance(__A ,te.LayerNorm    ) and not to_transformer_engine and _convert_ln:
         lowercase    :			Any  =       nn.LayerNorm(module.normalized_shape[0] ,eps=module.eps ,params_dtype=module.weight.dtype    )
         lowercase    :			str  =       module.weight.data.clone()
         lowercase    :			List[str]  =       module.bias.data.clone()

         setattr(__A ,__A ,__A    )
      else:
         convert_model(
             __A ,to_transformer_engine=__A ,_convert_linear=_convert_linear ,_convert_ln=_convert_ln ,)







def 			__snake_case						(      __A    )		->				Union[str, Any]:
   if not is_fpa_available():
      raise ImportError("""Using `has_transformer_engine_layers` requires transformer_engine to be installed."""    )
   for m in model.modules():
      if isinstance(__A ,(te.LayerNorm, te.Linear)    ):
         return True
   return False


