
import contextlib
from multiprocessing import Pool, RLock

from tqdm.auto import tqdm

from ..utils import experimental, logging


__lowerCAmelCase					:			Optional[int]			      =		logging.get_logger(__name__)


class 						__lowerCAmelCase	:



      """simple docstring"""







      A__	:			Optional[Any]        =    None






@experimental
def     UpperCAmelCase_  (						__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	) ->						Optional[Any]:
    if ParallelBackendConfig.backend_name is None:
        return _map_with_multiprocessing_pool(
            __lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	)

    return _map_with_joblib(__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	)


def     UpperCAmelCase_  (						__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	) ->						str:
    __lowercase		:			Union[str, Any]	    =       num_proc if num_proc <= len(__lowerCAmelCase	) else len(__lowerCAmelCase	)
    __lowercase		:			Union[str, Any]	    =       []  # We organize the splits ourselve (contiguous splits)
    for index in range(__lowerCAmelCase	):
        __lowercase		:			int	    =       len(__lowerCAmelCase	) // num_proc
        __lowercase		:			Dict	    =       len(__lowerCAmelCase	) % num_proc
        __lowercase		:			str	    =       div * index + min(__lowerCAmelCase	,					__lowerCAmelCase	)
        __lowercase		:			Optional[Any]	    =       start + div + (1 if index < mod else 0)
        split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)	)

    if len(__lowerCAmelCase	) != sum(len(i[1]	) for i in split_kwds	):
        raise ValueError(
            F'Error dividing inputs iterable among processes. '
            F'Total number of objects {len(__lowerCAmelCase	)}, '
            F'length: {sum(len(i[1]	) for i in split_kwds	)}'	)

    logger.info(
        F'Spawning {num_proc} processes for {len(__lowerCAmelCase	)} objects in slices of {[len(i[1]	) for i in split_kwds]}'	)
    __lowercase		:			int	    =       None, None
    if not disable_tqdm:
        __lowercase		:			Dict	    =       (RLock(),), tqdm.set_lock
    with Pool(__lowerCAmelCase	,					initargs=__lowerCAmelCase	,					initializer=__lowerCAmelCase	) as pool:
        __lowercase		:			int	    =       pool.map(__lowerCAmelCase	,					__lowerCAmelCase	)
    logger.info(F'Finished {num_proc} processes'	)
    __lowercase		:			Dict	    =       [obj for proc_res in mapped for obj in proc_res]
    logger.info(F'Unpacked {len(__lowerCAmelCase	)} objects'	)

    return mapped


def     UpperCAmelCase_  (						__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase	) ->						int:
    # progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib,
    # and it requires monkey-patching joblib internal classes which is subject to change
    import joblib

    with joblib.parallel_backend(ParallelBackendConfig.backend_name	,					n_jobs=__lowerCAmelCase	):
        return joblib.Parallel()(
            joblib.delayed(__lowerCAmelCase	)((function, obj, types, None, True, None)	) for obj in iterable	)





@experimental
@contextlib.contextmanager
def     UpperCAmelCase_  (						__lowerCAmelCase	) ->						Dict:
    __lowercase		:			Tuple	    =       backend_name

    if backend_name == "spark":
        from joblibspark import register_spark

        register_spark()

        # TODO: call create_cache_and_write_probe if "download" in steps
        # TODO: raise NotImplementedError when Dataset.map etc is called

    try:
        yield
    finally:
        __lowercase		:			Optional[int]	    =       None




import warnings
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


__lowerCAmelCase					:			Union[str, Any]			      =		logging.get_logger(__name__)

__lowerCAmelCase					:			Optional[int]			      =		{
    "nvidia/segformer-b0-finetuned-ade-512-512": (
        "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json"
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}


class 						__lowerCAmelCase	(	lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			Dict        =    '''segformer'''




      def __init__(      self		:       Optional[Any]				,       _snake_case		:       List[str]=3				,       _snake_case		:       Union[str, Any]=4				,       _snake_case		:       str=[2, 2, 2, 2]				,       _snake_case		:       Dict=[8, 4, 2, 1]				,       _snake_case		:       List[Any]=[32, 64, 160, 256]				,       _snake_case		:       Dict=[7, 3, 3, 3]				,       _snake_case		:       List[Any]=[4, 2, 2, 2]				,       _snake_case		:       Tuple=[1, 2, 5, 8]				,       _snake_case		:       Optional[Any]=[4, 4, 4, 4]				,       _snake_case		:       Optional[int]="gelu"				,       _snake_case		:       Optional[int]=0.0				,       _snake_case		:       Optional[int]=0.0				,       _snake_case		:       int=0.1				,       _snake_case		:       Any=0.02				,       _snake_case		:       Optional[int]=0.1				,       _snake_case		:       Union[str, Any]=1E-6				,       _snake_case		:       Tuple=256				,       _snake_case		:       str=255				,       **_snake_case		:       Any				,       ):
          super().__init__(**_snake_case				)

          if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
              warnings.warn(
                  '''Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'''
                  ''' removed, as the behaviour will default to that of reshape_last_stage = True.'''				,       _snake_case				,       )

          __lowercase		:			Any	    =       num_channels
          __lowercase		:			Optional[Any]	    =       num_encoder_blocks
          __lowercase		:			List[str]	    =       depths
          __lowercase		:			str	    =       sr_ratios
          __lowercase		:			List[str]	    =       hidden_sizes
          __lowercase		:			List[str]	    =       patch_sizes
          __lowercase		:			Dict	    =       strides
          __lowercase		:			Optional[int]	    =       mlp_ratios
          __lowercase		:			List[str]	    =       num_attention_heads
          __lowercase		:			Optional[int]	    =       hidden_act
          __lowercase		:			List[Any]	    =       hidden_dropout_prob
          __lowercase		:			Optional[Any]	    =       attention_probs_dropout_prob
          __lowercase		:			List[Any]	    =       classifier_dropout_prob
          __lowercase		:			str	    =       initializer_range
          __lowercase		:			Optional[int]	    =       drop_path_rate
          __lowercase		:			List[str]	    =       layer_norm_eps
          __lowercase		:			List[str]	    =       decoder_hidden_size
          __lowercase		:			Union[str, Any]	    =       kwargs.get('''reshape_last_stage'''				,       _snake_case				)
          __lowercase		:			str	    =       semantic_loss_ignore_index






class 						__lowerCAmelCase	(	lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			Union[str, Any]        =    version.parse('''1.11'''      )




      @property
      def 		snake_case_			(      self		:       Dict				):
          return OrderedDict(
              [
                  ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
              ]				)




      @property
      def 		snake_case_			(      self		:       int				):
          return 1E-4




      @property
      def 		snake_case_			(      self		:       List[Any]				):
          return 12


