





"""simple docstring"""



from importlib import import_module

from .logging import get_logger


a_					=     get_logger(__name__)






class 						__snake_case   :





 """simple docstring"""


 def __init__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase=None    ):



     '''simple docstring'''




     __A       :		int							=	attrs or []
     if module is not None:
         for key in module.__dict__:
             if key in attrs or not key.startswith('''__'''    ):
                 setattr(self   ,		__lowerCamelCase   ,		getattr(__lowerCamelCase   ,		__lowerCamelCase    )    )
     __A       :		List[Any]							=	module._original_module if isinstance(__lowerCamelCase   ,		_PatchedModuleObj    ) else module






class 						__snake_case   :





 """simple docstring"""


 _lowerCamelCase								=	[]

 def __init__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase=None    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	obj
     __A       :		List[Any]							=	target
     __A       :		Optional[Any]							=	new
     __A       :		List[str]							=	target.split('''.'''    )[0]
     __A       :		Tuple							=	{}
     __A       :		Dict							=	attrs or []

 def __enter__(       self    ):



     '''simple docstring'''




     *__A					,			__A       :		List[str]							=	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(__lowerCamelCase    )    ):
         try:
             __A       :		Optional[Any]							=	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       :		int							=	getattr(self.obj   ,		__lowerCamelCase    )
             # 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(__lowerCamelCase   ,		_PatchedModuleObj    ) and obj_attr._original_module is submodule)
             ):
                 __A       :		Any							=	obj_attr
                 # patch at top level
                 setattr(self.obj   ,		__lowerCamelCase   ,		_PatchedModuleObj(__lowerCamelCase   ,		attrs=self.attrs    )    )
                 __A       :		Tuple							=	getattr(self.obj   ,		__lowerCamelCase    )
                 # construct lower levels patches
                 for key in submodules[i + 1 :]:
                     setattr(__lowerCamelCase   ,		__lowerCamelCase   ,		_PatchedModuleObj(getattr(__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    )   ,		attrs=self.attrs    )    )
                     __A       :		Tuple							=	getattr(__lowerCamelCase   ,		__lowerCamelCase    )
                 # finally set the target attribute
                 setattr(__lowerCamelCase   ,		__lowerCamelCase   ,		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       :		List[str]							=	getattr(import_module('''.'''.join(__lowerCamelCase    )    )   ,		__lowerCamelCase    )
         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   ,		__lowerCamelCase    ) is attr_value:
                 __A       :		str							=	getattr(self.obj   ,		__lowerCamelCase    )
                 setattr(self.obj   ,		__lowerCamelCase   ,		self.new    )
     elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
         __A       :		Optional[int]							=	globals()['''__builtins__'''][target_attr]
         setattr(self.obj   ,		__lowerCamelCase   ,		self.new    )
     else:
         raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule."""    )

 def __exit__(       self   ,		*__lowerCamelCase    ):



     '''simple docstring'''




     for attr in list(self.original    ):
         setattr(self.obj   ,		__lowerCamelCase   ,		self.original.pop(__lowerCamelCase    )    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     self.__enter__()
     self._active_patches.append(self    )







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     try:
         self._active_patches.remove(self    )
     except ValueError:
         # If the patch hasn't been started this will fail
         return None

     return self.__exit__()











"""simple docstring"""



import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device


if is_torch_available():
       from transformers import AutoModelForSeqaSeqLM, AutoTokenizer






@require_torch
@require_sentencepiece
@require_tokenizers
class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Any							=	AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small'''   ,		return_dict=__lowerCamelCase    ).to(__lowerCamelCase    )
     __A       :		Optional[Any]							=	AutoTokenizer.from_pretrained('''google/mt5-small'''    )

     __A       :		Optional[int]							=	tokenizer('''Hello there'''   ,		return_tensors='''pt'''    ).input_ids
     __A       :		str							=	tokenizer('''Hi I am'''   ,		return_tensors='''pt'''    ).input_ids

     __A       :		Any							=	model(input_ids.to(__lowerCamelCase    )   ,		labels=labels.to(__lowerCamelCase    )    ).loss
     __A       :		Tuple							=	-(labels.shape[-1] * loss.item())

     __A       :		int							=	-8_4.9_1_2_7
     self.assertTrue(abs(mtf_score - EXPECTED_SCORE    ) < 1e-4    )




