




# Copyright 2021 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.

import argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


lowerCamelCase							:						List[Any]					       =  [
    "EAGER",
    "AOT_EAGER",
    "INDUCTOR",
    "NVFUSER",
    "AOT_NVFUSER",
    "AOT_CUDAGRAPHS",
    "OFI",
    "FX2TRT",
    "ONNXRT",
    "IPEX",
]

def      _SCREAMING_SNAKE_CASE     (				lowercase      :			Dict      ,				lowercase      :			Any=None      ,				lowercase      :			Optional[int]=None      ,				lowercase      :			Optional[int]=None	):


      '''simple docstring'''



      lowerCamelCase_							=       True
      while ask_again:
            lowerCamelCase_							=       input(lowercase	)
            try:
                  if default is not None and len(lowercase	) == 0:
                        return default
                  return convert_value(lowercase	) if convert_value is not None else result
            except Exception:
                  if error_message is not None:
                        print(lowercase	)

def      _SCREAMING_SNAKE_CASE     (				lowercase      :			Optional[int]      ,				lowercase      :			List[str]=[]      ,				lowercase      :			Dict=None      ,				lowercase      :			int=0	):


      '''simple docstring'''



      lowerCamelCase_							=       BulletMenu(lowercase      ,				lowercase	)
      lowerCamelCase_							=       menu.run(default_choice=lowercase	)
      return convert_value(lowercase	) if convert_value is not None else result

def      _SCREAMING_SNAKE_CASE     (				lowercase      :			Optional[Any]	):


      '''simple docstring'''



      lowerCamelCase_							=       int(lowercase	)
      return ComputeEnvironment(['LOCAL_MACHINE', 'AMAZON_SAGEMAKER'][value]	)

def      _SCREAMING_SNAKE_CASE     (				lowercase      :			Any	):


      '''simple docstring'''



      lowerCamelCase_							=       int(lowercase	)
      return DistributedType(['NO', 'MULTI_CPU', 'MULTI_XPU', 'MULTI_GPU', 'MULTI_NPU', 'TPU'][value]	)

def      _SCREAMING_SNAKE_CASE     (				lowercase      :			Dict	):


      '''simple docstring'''



      lowerCamelCase_							=       int(lowercase	)
      return DynamoBackend(DYNAMO_BACKENDS[value]	).value

def      _SCREAMING_SNAKE_CASE     (				lowercase      :			List[Any]	):


      '''simple docstring'''



      lowerCamelCase_							=       int(lowercase	)
      return PrecisionType(['no', 'fp16', 'bf16', 'fp8'][value]	)

def      _SCREAMING_SNAKE_CASE     (				lowercase      :			str	):


      '''simple docstring'''



      lowerCamelCase_							=       int(lowercase	)
      return SageMakerDistributedType(['NO', 'DATA_PARALLEL', 'MODEL_PARALLEL'][value]	)

def      _SCREAMING_SNAKE_CASE     (				lowercase      :			Optional[Any]	):


      '''simple docstring'''



      return {"yes": True, "no": False}[value.lower()]







class     A(		argparse.RawDescriptionHelpFormatter  ):



 '''simple docstring'''


 def 							a__					(							self   :    List[str]		,				A_   :    Tuple		,				A_   :    Optional[int]		,				A_   :    Union[str, Any]		,				A_   :    Any    )  ->      Dict:

       """simple docstring"""






       lowerCamelCase_							=       super()._format_usage(A_		,				A_		,				A_		,				A_    )
       lowerCamelCase_							=       usage.replace('<command> [<args>] '		,				''    )
       return usage







from importlib import import_module

from .logging import get_logger


_lowerCAmelCase:						str   				=       get_logger(__name__)




class       lowercase_					:





				def __init__(				self       ,  lowercase_       ,  lowercase_=None)  -> Tuple:
											a__      =attrs or []
											if module is not None:
																		for key in module.__dict__:
																									if key in attrs or not key.startswith('__'):
																																setattr(self       ,  lowercase_       ,  getattr(lowercase_       ,  lowercase_))
											a__      =module._original_module if isinstance(lowercase_       ,  _PatchedModuleObj) else module







class       lowercase_					:
				snake_case	    =[]





				def __init__(				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_=None)  -> List[str]:
											a__      =obj
											a__      =target
											a__      =new
											a__      =target.split('.')[0]
											a__      ={}
											a__      =attrs or []





				def __enter__(				self)  -> Optional[int]:
											*a__    ,     a__      =self.target.split('.')

											# Patch modules:
											# it's used to patch attributes of submodules like "os.path.join";
											# in this case we need to patch "os" and "os.path"

											for i in range(len(lowercase_)):
																		try:
																									a__      =import_module('.'.join(submodules[: i + 1]))
																		except ModuleNotFoundError:
																									continue
																		# We iterate over all the globals in self.obj in case we find "os" or "os.path"
																		for attr in self.obj.__dir__():
																									a__      =getattr(self.obj       ,  lowercase_)
																									# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
																									# This allows to patch renamed modules like "from os import path as ospath".
																									if obj_attr is submodule or (
																									    (isinstance(lowercase_       ,  _PatchedModuleObj) and obj_attr._original_module is submodule)
																									):
																																a__      =obj_attr
																																# patch at top level
																																setattr(self.obj       ,  lowercase_       ,  _PatchedModuleObj(lowercase_       ,  attrs=self.attrs))
																																a__      =getattr(self.obj       ,  lowercase_)
																																# construct lower levels patches
																																for key in submodules[i + 1 :]:
																																							setattr(lowercase_       ,  lowercase_       ,  _PatchedModuleObj(getattr(lowercase_       ,  lowercase_       ,  lowercase_)       ,  attrs=self.attrs))
																																							a__      =getattr(lowercase_       ,  lowercase_)
																																# finally set the target attribute
																																setattr(lowercase_       ,  lowercase_       ,  self.new)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

											if submodules:  # if it's an attribute of a submodule like "os.path.join"
																		try:
																									a__      =getattr(import_module('.'.join(lowercase_))       ,  lowercase_)
																		except (AttributeError, ModuleNotFoundError):
																									return
																		# We iterate over all the globals in self.obj in case we find "os.path.join"
																		for attr in self.obj.__dir__():
																									# We don't check for the name of the global, but rather if its value *is* "os.path.join".
																									# This allows to patch renamed attributes like "from os.path import join as pjoin".
																									if getattr(self.obj       ,  lowercase_) is attr_value:
																																a__      =getattr(self.obj       ,  lowercase_)
																																setattr(self.obj       ,  lowercase_       ,  self.new)
											elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																		a__      =globals()['__builtins__'][target_attr]
																		setattr(self.obj       ,  lowercase_       ,  self.new)
											else:
																		raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule.""")





				def __exit__(				self       ,  *lowercase_)  -> str:
											for attr in list(self.original):
																		setattr(self.obj       ,  lowercase_       ,  self.original.pop(lowercase_))





				def 						__UpperCamelCase    (				self)  -> Any:
											self.__enter__()
											self._active_patches.append(self)





				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											try:
																		self._active_patches.remove(self)
											except ValueError:
																		# If the patch hasn't been started this will fail
																		return None

											return self.__exit__()

