





'''simple docstring'''




import functools
import gc
import inspect

import torch

from .imports import is_npu_available, is_xpu_available







def _lowerCAmelCase     (      *_lowerCAmelCase    )->     Optional[Any]:
 if not isinstance(_lowerCAmelCase       ,    _lowerCAmelCase    ):
  __UpperCAmelCase					=   list(_lowerCAmelCase    )
 for i in range(len(_lowerCAmelCase    )    ):
  __UpperCAmelCase					=   None
 gc.collect()
 if is_xpu_available():
  torch.xpu.empty_cache()
 elif is_npu_available():
  torch.npu.empty_cache()
 else:
  torch.cuda.empty_cache()
 return objects







def _lowerCAmelCase     (      _lowerCAmelCase    )->     bool:
 __UpperCAmelCase					=   [
     'CUDA out of memory.',  # CUDA OOM
     'cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.',  # CUDNN SNAFU
     'DefaultCPUAllocator: can\'t allocate memory',  # CPU OOM
 ]
 if isinstance(_lowerCAmelCase       ,    _lowerCAmelCase    ) and len(exception.args    ) == 1:
  return any(err in exception.args[0] for err in _statements    )
 return False







def _lowerCAmelCase     (      _lowerCAmelCase = None       ,    _lowerCAmelCase = 1_28    )->     Dict:
 if function is None:
  return functools.partial(_lowerCAmelCase       ,    starting_batch_size=_lowerCAmelCase    )

 __UpperCAmelCase					=   starting_batch_size

 def decorator(*_lowerCAmelCase       ,    **_lowerCAmelCase    ):
  nonlocal batch_size
  gc.collect()
  if is_xpu_available():
   torch.xpu.empty_cache()
  elif is_npu_available():
   torch.npu.empty_cache()
  else:
   torch.cuda.empty_cache()
  __UpperCAmelCase					=   list(inspect.signature(_lowerCAmelCase    ).parameters.keys()    )
  # Guard against user error
  if len(_lowerCAmelCase    ) < (len(_lowerCAmelCase    ) + 1):
   __UpperCAmelCase					=   ', '.join([F'{arg}={value}' for arg, value in zip(params[1:]       ,    args[1:]    )]    )
   raise TypeError(
       F'Batch size was passed into `{function.__name__}` as the first argument when called.'
       F'Remove this as the decorator already does so: `{function.__name__}({arg_str})`'    )
  while True:
   if batch_size == 0:
    raise RuntimeError('No executable batch size found, reached zero.'    )
   try:
    return function(_lowerCAmelCase       ,    *_lowerCAmelCase       ,    **_lowerCAmelCase    )
   except Exception as e:
    if should_reduce_batch_size(_lowerCAmelCase    ):
     gc.collect()
     if is_xpu_available():
      torch.xpu.empty_cache()
     elif is_npu_available():
      torch.npu.empty_cache()
     else:
      torch.cuda.empty_cache()
     batch_size //= 2
    else:
     raise

 return decorator












'''simple docstring'''




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


_A:					Tuple							=				logging.get_logger(__name__)






class UpperCAmelCase							(		UpperCAmelCase_							):
    _A :			List[Any]						   =       """timm_backbone"""



    def __init__(  self     ,			__A=None     ,			__A=3     ,			__A=True     ,			__A=True     ,			__A=None     ,			**__A     ,			):
     super().__init__(**__A					)
     __UpperCAmelCase					=   backbone
     __UpperCAmelCase					=   num_channels
     __UpperCAmelCase					=   features_only
     __UpperCAmelCase					=   use_pretrained_backbone
     __UpperCAmelCase					=   True
     __UpperCAmelCase					=   out_indices if out_indices is not None else (-1,)





