
"""simple docstring"""






import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union




class      _SCREAMING_SNAKE_CASE   (     enum.Enum				):
			UpperCAmelCase_    :Dict												=		"timm"
			UpperCAmelCase_    :Union[str, Any]												=		"transformers"






def 		_snake_case			(      lowercase__						:    Optional[Iterable[str]] ,	lowercase__						:    Optional[Iterable[int]] ,	lowercase__						:    Optional[Iterable[str]]						)    ->							List[str]:


			'''simple docstring'''





			if stage_names is None:
						raise ValueError("""Stage_names must be set for transformers backbones"""						)

			if out_features is not None:
						if not isinstance(lowercase__ ,	(list,)						):
									raise ValueError(f"""out_features must be a list {type(lowercase__						)}"""						)
						if any(feat not in stage_names for feat in out_features						):
									raise ValueError(f"""out_features must be a subset of stage_names: {stage_names} got {out_features}"""						)

			if out_indices is not None:
						if not isinstance(lowercase__ ,	(list, tuple)						):
									raise ValueError(f"""out_indices must be a list or tuple, got {type(lowercase__						)}"""						)
						if any(idx >= len(lowercase__						) for idx in out_indices						):
									raise ValueError("""out_indices must be valid indices for stage_names {stage_names}, got {out_indices}"""						)

			if out_features is not None and out_indices is not None:
						if len(lowercase__						) != len(lowercase__						):
									raise ValueError("""out_features and out_indices should have the same length if both are set"""						)
						if out_features != [stage_names[idx] for idx in out_indices]:
									raise ValueError("""out_features and out_indices should correspond to the same stages if both are set"""						)






def 		_snake_case			(      lowercase__						:    Optional[List[str]] ,	lowercase__						:    Optional[Union[List[int], Tuple[int]]] ,	lowercase__						:    List[str] ,	)    ->							List[Any]:


			'''simple docstring'''





			if out_indices is None and out_features is None:
						lowerCAmelCase_       :Union[str, Any]     	=    [len(lowercase__						) - 1]
						lowerCAmelCase_       :Any     	=    [stage_names[-1]]
			elif out_indices is None and out_features is not None:
						lowerCAmelCase_       :str     	=    [stage_names.index(lowercase__						) for layer in out_features]
			elif out_features is None and out_indices is not None:
						lowerCAmelCase_       :Any     	=    [stage_names[idx] for idx in out_indices]
			return out_features, out_indices






def 		_snake_case			(      lowercase__						:    Optional[List[str]] ,	lowercase__						:    Optional[Union[List[int], Tuple[int]]] ,	lowercase__						:    List[str] ,	)    ->							Tuple[List[str], List[int]]:


			'''simple docstring'''





			verify_out_features_out_indices(out_features=lowercase__ ,	out_indices=lowercase__ ,	stage_names=lowercase__						)
			lowerCAmelCase_	,			lowerCAmelCase_       :Union[str, Any]     	=    _align_output_features_output_indices(
			    out_features=lowercase__ ,	out_indices=lowercase__ ,	stage_names=lowercase__						)
			# Verify that the aligned out_features and out_indices are valid
			verify_out_features_out_indices(out_features=lowercase__ ,	out_indices=lowercase__ ,	stage_names=lowercase__						)
			return output_features, output_indices




class      _SCREAMING_SNAKE_CASE   :
			UpperCAmelCase_    :Optional[BackboneType]												=		None






			def 					__lowerCAmelCase					(   self			,  __A			)     ->	None:
						if getattr(self			,  """_backbone"""			,  __A			) is None:
									raise ValueError("""self._backbone must be set before calling _init_timm_backbone"""			)

						# These will diagree with the defaults for the transformers models e.g. for resnet50
						# the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
						# the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
						lowerCAmelCase_       :int     	=    [stage["""module"""] for stage in self._backbone.feature_info.info]
						lowerCAmelCase_       :Optional[int]     	=    [stage["""num_chs"""] for stage in self._backbone.feature_info.info]
						lowerCAmelCase_       :str     	=    self._backbone.feature_info.out_indices
						lowerCAmelCase_       :Dict     	=    self._backbone.feature_info.module_name()

						# We verify the out indices and out features are valid
						verify_out_features_out_indices(
						    out_features=__A			,  out_indices=__A			,  stage_names=self.stage_names			)
						lowerCAmelCase_	,			lowerCAmelCase_       :Tuple     	=    out_features, out_indices






			def 					__lowerCAmelCase					(   self			,  __A			)     ->	None:
						lowerCAmelCase_       :List[str]     	=    getattr(__A			,  """stage_names"""			)
						lowerCAmelCase_       :Dict     	=    getattr(__A			,  """out_features"""			,  __A			)
						lowerCAmelCase_       :int     	=    getattr(__A			,  """out_indices"""			,  __A			)

						lowerCAmelCase_       :Optional[int]     	=    stage_names
						lowerCAmelCase_	,			lowerCAmelCase_       :Tuple     	=    get_aligned_output_features_output_indices(
						    out_features=__A			,  out_indices=__A			,  stage_names=__A			)
						# Number of channels for each stage. This is set in the transformer backbone model init
						lowerCAmelCase_       :Union[str, Any]     	=    None






			def 					__lowerCAmelCase					(   self			,  __A			)     ->	None:
						lowerCAmelCase_       :Optional[Any]     	=    config

						lowerCAmelCase_       :Union[str, Any]     	=    getattr(__A			,  """use_timm_backbone"""			,  __A			)
						lowerCAmelCase_       :Optional[int]     	=    BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

						if self.backbone_type == BackboneType.TIMM:
									self._init_timm_backbone(__A			)
						elif self.backbone_type == BackboneType.TRANSFORMERS:
									self._init_transformers_backbone(__A			)
						else:
									raise ValueError(f"""backbone_type {self.backbone_type} not supported."""			)






			@property
			def 					__lowerCAmelCase					(   self			)     ->	Tuple:
						return self._out_features






			@out_features.setter
			def 					__lowerCAmelCase					(   self			,  __A			)     ->	str:
						lowerCAmelCase_	,			lowerCAmelCase_       :str     	=    get_aligned_output_features_output_indices(
						    out_features=__A			,  out_indices=__A			,  stage_names=self.stage_names			)






			@property
			def 					__lowerCAmelCase					(   self			)     ->	Optional[Any]:
						return self._out_indices






			@out_indices.setter
			def 					__lowerCAmelCase					(   self			,  __A			)     ->	List[str]:
						lowerCAmelCase_	,			lowerCAmelCase_       :int     	=    get_aligned_output_features_output_indices(
						    out_features=__A			,  out_indices=__A			,  stage_names=self.stage_names			)






			@property
			def 					__lowerCAmelCase					(   self			)     ->	str:
						# the current backbones will output the number of channels for each stage
						# even if that stage is not in the out_features list.
						return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names			)}






			@property
			def 					__lowerCAmelCase					(   self			)     ->	List[str]:
						return [self.out_feature_channels[name] for name in self.out_features]






			def 					__lowerCAmelCase					(   self			,  *__A			,  **__A			)     ->	str:
						lowerCAmelCase_       :Union[str, Any]     	=    dict(inspect.signature(self.forward			).parameters			)
						lowerCAmelCase_       :str     	=    {k: v for k, v in kwargs.items() if k in signature}
						return self(*__A			,  **__A			)






			def 					__lowerCAmelCase					(   self			,  __A			,  __A = None			,  __A = None			,  __A = None			,  )     ->	int:
						raise NotImplementedError("""This method should be implemented by the derived class."""			)






			def 					__lowerCAmelCase					(   self			)     ->	int:
						lowerCAmelCase_       :Dict     	=    super().to_dict()
						lowerCAmelCase_       :int     	=    output.pop("""_out_features"""			)
						lowerCAmelCase_       :List[str]     	=    output.pop("""_out_indices"""			)
						return output




class      _SCREAMING_SNAKE_CASE   :






			@property
			def 					__lowerCAmelCase					(   self			)     ->	int:
						return self._out_features






			@out_features.setter
			def 					__lowerCAmelCase					(   self			,  __A			)     ->	str:
						lowerCAmelCase_	,			lowerCAmelCase_       :Tuple     	=    get_aligned_output_features_output_indices(
						    out_features=__A			,  out_indices=__A			,  stage_names=self.stage_names			)






			@property
			def 					__lowerCAmelCase					(   self			)     ->	Optional[Any]:
						return self._out_indices






			@out_indices.setter
			def 					__lowerCAmelCase					(   self			,  __A			)     ->	str:
						lowerCAmelCase_	,			lowerCAmelCase_       :Any     	=    get_aligned_output_features_output_indices(
						    out_features=__A			,  out_indices=__A			,  stage_names=self.stage_names			)






			def 					__lowerCAmelCase					(   self			)     ->	Tuple:
						lowerCAmelCase_       :str     	=    super().to_dict()
						lowerCAmelCase_       :Dict     	=    output.pop("""_out_features"""			)
						lowerCAmelCase_       :List[str]     	=    output.pop("""_out_indices"""			)
						return output








"""simple docstring"""






from ...configuration_utils import PretrainedConfig
from ...utils import is_detectrona_available, logging


__UpperCAmelCase 					=    logging.get_logger(__name__)

__UpperCAmelCase 					=    {
    'layoutlmv2-base-uncased': 'https://huggingface.co/microsoft/layoutlmv2-base-uncased/resolve/main/config.json',
    'layoutlmv2-large-uncased': 'https://huggingface.co/microsoft/layoutlmv2-large-uncased/resolve/main/config.json',
    # See all LayoutLMv2 models at https://huggingface.co/models?filter=layoutlmv2
}

# soft dependency
if is_detectrona_available():
				import detectrona




class      _SCREAMING_SNAKE_CASE   (     A__				):
			UpperCAmelCase_    :Optional[int]												=		"layoutlmv2"






			def __init__(   self			,  __A=3_0522			,  __A=768			,  __A=12			,  __A=12			,  __A=3072			,  __A="gelu"			,  __A=0.1			,  __A=0.1			,  __A=512			,  __A=2			,  __A=0.0_2			,  __A=1E-12			,  __A=0			,  __A=1024			,  __A=128			,  __A=32			,  __A=True			,  __A=256			,  __A=64			,  __A=True			,  __A=[7, 7, 256]			,  __A=128			,  __A=128			,  __A=True			,  __A=True			,  __A=False			,  __A=None			,  **__A			,  )     ->	List[str]:
						super().__init__(
						    vocab_size=__A			,  hidden_size=__A			,  num_hidden_layers=__A			,  num_attention_heads=__A			,  intermediate_size=__A			,  hidden_act=__A			,  hidden_dropout_prob=__A			,  attention_probs_dropout_prob=__A			,  max_position_embeddings=__A			,  type_vocab_size=__A			,  initializer_range=__A			,  layer_norm_eps=__A			,  pad_token_id=__A			,  **__A			,  )
						lowerCAmelCase_       :Optional[Any]     	=    max_ad_position_embeddings
						lowerCAmelCase_       :Dict     	=    max_rel_pos
						lowerCAmelCase_       :str     	=    rel_pos_bins
						lowerCAmelCase_       :List[str]     	=    fast_qkv
						lowerCAmelCase_       :Union[str, Any]     	=    max_rel_ad_pos
						lowerCAmelCase_       :List[str]     	=    rel_ad_pos_bins
						lowerCAmelCase_       :Any     	=    convert_sync_batchnorm
						lowerCAmelCase_       :Dict     	=    image_feature_pool_shape
						lowerCAmelCase_       :str     	=    coordinate_size
						lowerCAmelCase_       :Tuple     	=    shape_size
						lowerCAmelCase_       :Tuple     	=    has_relative_attention_bias
						lowerCAmelCase_       :Union[str, Any]     	=    has_spatial_attention_bias
						lowerCAmelCase_       :int     	=    has_visual_segment_embedding
						lowerCAmelCase_       :Any     	=    (
						    detectrona_config_args if detectrona_config_args is not None else self.get_default_detectrona_config()
						)






			@classmethod
			def 					__lowerCAmelCase					(   self			)     ->	Optional[Any]:
						return {
						    "MODEL.MASK_ON": True,
						    "MODEL.PIXEL_STD": [5_7.3_7_5, 5_7.1_2_0, 5_8.3_9_5],
						    "MODEL.BACKBONE.NAME": "build_resnet_fpn_backbone",
						    "MODEL.FPN.IN_FEATURES": ["res2", "res3", "res4", "res5"],
						    "MODEL.ANCHOR_GENERATOR.SIZES": [[32], [64], [128], [256], [512]],
						    "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
						    "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 2000,
						    "MODEL.RPN.PRE_NMS_TOPK_TEST": 1000,
						    "MODEL.RPN.POST_NMS_TOPK_TRAIN": 1000,
						    "MODEL.POST_NMS_TOPK_TEST": 1000,
						    "MODEL.ROI_HEADS.NAME": "StandardROIHeads",
						    "MODEL.ROI_HEADS.NUM_CLASSES": 5,
						    "MODEL.ROI_HEADS.IN_FEATURES": ["p2", "p3", "p4", "p5"],
						    "MODEL.ROI_BOX_HEAD.NAME": "FastRCNNConvFCHead",
						    "MODEL.ROI_BOX_HEAD.NUM_FC": 2,
						    "MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION": 14,
						    "MODEL.ROI_MASK_HEAD.NAME": "MaskRCNNConvUpsampleHead",
						    "MODEL.ROI_MASK_HEAD.NUM_CONV": 4,
						    "MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION": 7,
						    "MODEL.RESNETS.DEPTH": 101,
						    "MODEL.RESNETS.SIZES": [[32], [64], [128], [256], [512]],
						    "MODEL.RESNETS.ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
						    "MODEL.RESNETS.OUT_FEATURES": ["res2", "res3", "res4", "res5"],
						    "MODEL.RESNETS.NUM_GROUPS": 32,
						    "MODEL.RESNETS.WIDTH_PER_GROUP": 8,
						    "MODEL.RESNETS.STRIDE_IN_1X1": False,
						}






			def 					__lowerCAmelCase					(   self			)     ->	List[Any]:
						lowerCAmelCase_       :Any     	=    detectrona.config.get_cfg()
						for k, v in self.detectrona_config_args.items():
									lowerCAmelCase_       :int     	=    k.split("""."""			)
									lowerCAmelCase_       :List[Any]     	=    detectrona_config
									for attribute in attributes[:-1]:
												lowerCAmelCase_       :List[Any]     	=    getattr(__A			,  __A			)
									setattr(__A			,  attributes[-1]			,  __A			)

						return detectrona_config






