




from importlib import import_module

from .logging import get_logger


UpperCAmelCase_									=	get_logger(__name__)





class     lowerCamelCase__:
      def __init__(				self: int    ,       UpperCamelCase_: Tuple    ,       UpperCamelCase_: Tuple=None   ):
             __lowerCamelCase   =						attrs or []
             if module is not None:
                    for key in module.__dict__:
                           if key in attrs or not key.startswith("""__"""   ):
                                  setattr(self    ,       UpperCamelCase_    ,       getattr(UpperCamelCase_    ,       UpperCamelCase_   )   )
             __lowerCamelCase   =						module._original_module if isinstance(UpperCamelCase_    ,       _PatchedModuleObj   ) else module





class     lowerCamelCase__:
      UpperCAmelCase__      :	Any    		=   []
      def __init__(				self: Optional[Any]    ,       UpperCamelCase_: int    ,       UpperCamelCase_: str    ,       UpperCamelCase_: Dict    ,       UpperCamelCase_: Any=None   ):
             __lowerCamelCase   =						obj
             __lowerCamelCase   =						target
             __lowerCamelCase   =						new
             __lowerCamelCase   =						target.split("""."""   )[0]
             __lowerCamelCase   =						{}
             __lowerCamelCase   =						attrs or []
      def __enter__(				self: Union[str, Any]   ):
             *__lowerCamelCase,   __lowerCamelCase   =						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(UpperCamelCase_   )   ):
                    try:
                           __lowerCamelCase   =						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__():
                           __lowerCamelCase   =						getattr(self.obj    ,       UpperCamelCase_   )
                           # 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(UpperCamelCase_    ,       _PatchedModuleObj   ) and obj_attr._original_module is submodule)
                           ):
                                  __lowerCamelCase   =						obj_attr
                                  # patch at top level
                                  setattr(self.obj    ,       UpperCamelCase_    ,       _PatchedModuleObj(UpperCamelCase_    ,       attrs=self.attrs   )   )
                                  __lowerCamelCase   =						getattr(self.obj    ,       UpperCamelCase_   )
                                  # construct lower levels patches
                                  for key in submodules[i + 1 :]:
                                         setattr(UpperCamelCase_    ,       UpperCamelCase_    ,       _PatchedModuleObj(getattr(UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )    ,       attrs=self.attrs   )   )
                                         __lowerCamelCase   =						getattr(UpperCamelCase_    ,       UpperCamelCase_   )
                                  # finally set the target attribute
                                  setattr(UpperCamelCase_    ,       UpperCamelCase_    ,       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:
                           __lowerCamelCase   =						getattr(import_module(""".""".join(UpperCamelCase_   )   )    ,       UpperCamelCase_   )
                    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    ,       UpperCamelCase_   ) is attr_value:
                                  __lowerCamelCase   =						getattr(self.obj    ,       UpperCamelCase_   )
                                  setattr(self.obj    ,       UpperCamelCase_    ,       self.new   )
             elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
                    __lowerCamelCase   =						globals()["""__builtins__"""][target_attr]
                    setattr(self.obj    ,       UpperCamelCase_    ,       self.new   )
             else:
                    raise RuntimeError(F'Tried to patch attribute {target_attr} instead of a submodule.'   )
      def __exit__(				self: Any    ,       *UpperCamelCase_: Optional[Any]   ):
             for attr in list(self.original   ):
                    setattr(self.obj    ,       UpperCamelCase_    ,       self.original.pop(UpperCamelCase_   )   )
      def 			lowerCAmelCase__						(				self: Union[str, Any]   ):
             self.__enter__()
             self._active_patches.append(self   )




      def 			lowerCAmelCase__						(				self: Dict   ):
             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'''

from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow


if is_tf_available():
  import tensorflow as tf

  from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM



@require_tf
@require_sentencepiece
@require_tokenizers
class 			UpperCAmelCase  (						unittest.TestCase					):





       '''simple docstring'''



       @slow
       def _lowerCAmelCase(						self )  ->  Dict:
        lowercase__				:    List[str]  =					TFAutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' )
        lowercase__				:    Dict  =					AutoTokenizer.from_pretrained('''google/mt5-small''' )

        lowercase__				:    Any  =					tokenizer('''Hello there'''	,   return_tensors='''tf''' ).input_ids
        lowercase__				:    List[Any]  =					tokenizer('''Hi I am'''	,   return_tensors='''tf''' ).input_ids

        lowercase__				:    str  =					model(__lowerCAmelCase	,   labels=__lowerCAmelCase ).loss
        lowercase__				:    List[str]  =					-tf.math.reduce_mean(__lowerCAmelCase ).numpy()

        lowercase__				:    str  =					-2_1.2_2_8_1_6_8
        self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2E-4 )

