






"""simple docstring"""



from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


__A		:       List[Any]  				=		logging.get_logger(__name__)

__A		:       List[Any]  				=		{
    '''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''',
}





class 					_UpperCAmelCase       ( _A   ,						_A							):
					SCREAMING_SNAKE_CASE_		:				List[Any]							    =   "resnet"
					SCREAMING_SNAKE_CASE_		:				Tuple							    =   ["basic", "bottleneck"]




					def __init__(				self     :						Any    ,						A     :						Tuple=3    ,						A     :						str=64    ,						A     :						Tuple=[2_56, 5_12, 10_24, 20_48]    ,						A     :						List[Any]=[3, 4, 6, 3]    ,						A     :						Union[str, Any]="bottleneck"    ,						A     :						int="relu"    ,						A     :						List[Any]=False    ,						A     :						Tuple=None    ,						A     :						int=None    ,						**A     :						List[str]    ,						)  ->  List[Any]:
							super().__init__(**A   )
							if layer_type not in self.layer_types:
									raise ValueError(F'''layer_type={layer_type} is not one of {','.join(self.layer_types   )}'''   )
							lowercase_ : List[Any]							       =   num_channels
							lowercase_ : Tuple							       =   embedding_size
							lowercase_ : Dict							       =   hidden_sizes
							lowercase_ : Tuple							       =   depths
							lowercase_ : Optional[int]							       =   layer_type
							lowercase_ : str							       =   hidden_act
							lowercase_ : Dict							       =   downsample_in_first_stage
							lowercase_ : str							       =   ['''stem'''] + [F'''stage{idx}''' for idx in range(1    ,						len(A   ) + 1   )]
							lowercase_       ,					lowercase_ : List[str]							       =   get_aligned_output_features_output_indices(
							    out_features=A    ,						out_indices=A    ,						stage_names=self.stage_names   )





class 					_UpperCAmelCase       ( _A							):
					SCREAMING_SNAKE_CASE_		:				str							    =   version.parse("1.11"							)




					@property
					def   A  (				self     :						Any   )  ->  Mapping[str, Mapping[int, str]]:
							return OrderedDict(
							    [
							        ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
							    ]   )






					@property
					def   A  (				self     :						Union[str, Any]   )  ->  float:
							return 1e-3











"""simple docstring"""



# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
						import torch





class 					_UpperCAmelCase       ( TensorFormatter[Mapping, "torch.Tensor", Mapping]							):




					def __init__(				self     :						Any    ,						A     :						int=None    ,						**A     :						str   )  ->  Union[str, Any]:
							super().__init__(features=A   )
							lowercase_ : Union[str, Any]							       =   torch_tensor_kwargs
							import torch  # noqa import torch at initialization




					def   A  (				self     :						Dict    ,						A     :						int   )  ->  List[Any]:
							import torch

							if isinstance(A    ,						A   ) and column:
									if all(
									    isinstance(A    ,						torch.Tensor   ) and x.shape == column[0].shape and x.dtype == column[0].dtype
									    for x in column   ):
											return torch.stack(A   )
							return column




					def   A  (				self     :						int    ,						A     :						Any   )  ->  Optional[Any]:
							import torch

							if isinstance(A    ,						(str, bytes, type(A   ))   ):
									return value
							elif isinstance(A    ,						(np.character, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.character   ):
									return value.tolist()

							lowercase_ : Any							       =   {}

							if isinstance(A    ,						(np.number, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.integer   ):
									lowercase_ : Any							       =   {'''dtype''': torch.intaa}
							elif isinstance(A    ,						(np.number, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.floating   ):
									lowercase_ : Dict							       =   {'''dtype''': torch.floataa}
							elif config.PIL_AVAILABLE and "PIL" in sys.modules:
									import PIL.Image

									if isinstance(A    ,						PIL.Image.Image   ):
											lowercase_ : Dict							       =   np.asarray(A   )
							return torch.tensor(A    ,						**{**default_dtype, **self.torch_tensor_kwargs}   )




					def   A  (				self     :						Union[str, Any]    ,						A     :						Optional[int]   )  ->  str:
							import torch

							# support for torch, tf, jax etc.
							if hasattr(A    ,						'''__array__'''   ) and not isinstance(A    ,						torch.Tensor   ):
									lowercase_ : Optional[int]							       =   data_struct.__array__()
							# support for nested types like struct of list of struct
							if isinstance(A    ,						np.ndarray   ):
									if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
											return self._consolidate([self.recursive_tensorize(A   ) for substruct in data_struct]   )
							elif isinstance(A    ,						(list, tuple)   ):
									return self._consolidate([self.recursive_tensorize(A   ) for substruct in data_struct]   )
							return self._tensorize(A   )




					def   A  (				self     :						Dict    ,						A     :						dict   )  ->  Tuple:
							return map_nested(self._recursive_tensorize    ,						A    ,						map_list=A   )




					def   A  (				self     :						str    ,						A     :						pa.Table   )  ->  Mapping:
							lowercase_ : Optional[Any]							       =   self.numpy_arrow_extractor().extract_row(A   )
							lowercase_ : str							       =   self.python_features_decoder.decode_row(A   )
							return self.recursive_tensorize(A   )




					def   A  (				self     :						List[Any]    ,						A     :						pa.Table   )  ->  "torch.Tensor":
							lowercase_ : List[str]							       =   self.numpy_arrow_extractor().extract_column(A   )
							lowercase_ : str							       =   self.python_features_decoder.decode_column(A    ,						pa_table.column_names[0]   )
							lowercase_ : Optional[int]							       =   self.recursive_tensorize(A   )
							lowercase_ : Any							       =   self._consolidate(A   )
							return column






					def   A  (				self     :						List[str]    ,						A     :						pa.Table   )  ->  Mapping:
							lowercase_ : Optional[int]							       =   self.numpy_arrow_extractor().extract_batch(A   )
							lowercase_ : int							       =   self.python_features_decoder.decode_batch(A   )
							lowercase_ : Dict							       =   self.recursive_tensorize(A   )
							for column_name in batch:
									lowercase_ : Optional[Any]							       =   self._consolidate(batch[column_name]   )
							return batch



