





'''simple docstring'''


import functools
import gc
import inspect

import torch

from .imports import is_npu_available, is_xpu_available
def 							UpperCAmelCase_  (						*__lowerCamelCase : Union[str, Any]			):
   if not isinstance(__lowerCamelCase     ,__lowerCamelCase			):
      lowercase_      :int         =			list(__lowerCamelCase			)
   for i in range(len(__lowerCamelCase			)			):
      lowercase_      :List[str]         =			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 							UpperCAmelCase_  (						__lowerCamelCase : Exception			):
   lowercase_      :Any         =			[
       "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 							UpperCAmelCase_  (						__lowerCamelCase : callable = None     ,__lowerCamelCase : int = 1_28			):
   if function is None:
      return functools.partial(__lowerCamelCase     ,starting_batch_size=__lowerCamelCase			)

   lowercase_      :Optional[Any]         =			starting_batch_size

   def decorator(*__lowerCamelCase : Any     ,**__lowerCamelCase : int			):
      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()
      lowercase_      :str         =			list(inspect.signature(__lowerCamelCase			).parameters.keys()			)
      # Guard against user error
      if len(__lowerCamelCase			) < (len(__lowerCamelCase			) + 1):
         lowercase_      :Optional[Any]         =			", ".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'''


# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowerCAmelCase :					Dict 							={
    '''configuration_xmod''': [
        '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''XmodConfig''',
        '''XmodOnnxConfig''',
    ],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase :					Union[str, Any] 							=[
     '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''XmodForCausalLM''',
     '''XmodForMaskedLM''',
     '''XmodForMultipleChoice''',
     '''XmodForQuestionAnswering''',
     '''XmodForSequenceClassification''',
     '''XmodForTokenClassification''',
     '''XmodModel''',
     '''XmodPreTrainedModel''',
 ]

if TYPE_CHECKING:
 from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_xmod import (
      XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
      XmodForCausalLM,
      XmodForMaskedLM,
      XmodForMultipleChoice,
      XmodForQuestionAnswering,
      XmodForSequenceClassification,
      XmodForTokenClassification,
      XmodModel,
      XmodPreTrainedModel,
  )

else:
 import sys

 lowerCAmelCase :					Optional[Any] 							=_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


