

import unittest

import numpy as np

from transformers.testing_utils import require_flax, require_tf, require_torch
from transformers.utils import (
    expand_dims,
    flatten_dict,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    reshape,
    squeeze,
    transpose,
)


if is_flax_available():
       import jax.numpy as jnp

if is_tf_available():
       import tensorflow as tf

if is_torch_available():
       import torch






class  UpperCAmelCase__	( unittest.TestCase ):






  """simple docstring"""


  def    lowercase_	(							self		:	Tuple      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					{
           '''task_specific_params''': {
               '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 128, '''min_length''': 12, '''num_beams''': 4},
               '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 142, '''min_length''': 56, '''num_beams''': 4},
               '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6},
           }
       }
       SCREAMING_SNAKE_CASE__					=					{
           '''task_specific_params.summarization.length_penalty''': 1.0,
           '''task_specific_params.summarization.max_length''': 128,
           '''task_specific_params.summarization.min_length''': 12,
           '''task_specific_params.summarization.num_beams''': 4,
           '''task_specific_params.summarization_cnn.length_penalty''': 2.0,
           '''task_specific_params.summarization_cnn.max_length''': 142,
           '''task_specific_params.summarization_cnn.min_length''': 56,
           '''task_specific_params.summarization_cnn.num_beams''': 4,
           '''task_specific_params.summarization_xsum.length_penalty''': 1.0,
           '''task_specific_params.summarization_xsum.max_length''': 62,
           '''task_specific_params.summarization_xsum.min_length''': 11,
           '''task_specific_params.summarization_xsum.num_beams''': 6,
       }

       self.assertEqual(flatten_dict(__lowerCamelCase      )			,     __lowerCamelCase      )






  def    lowercase_	(							self		:	Optional[int]      )	->							List[Any]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       self.assertTrue(np.allclose(transpose(__lowerCamelCase      )			,     x.transpose()      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4			,     5      )
       self.assertTrue(np.allclose(transpose(__lowerCamelCase			,     axes=(1, 2, 0)      )			,     x.transpose((1, 2, 0)      )      )      )






  @require_torch
  def    lowercase_	(							self		:	List[str]      )	->							str:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					torch.tensor(__lowerCamelCase      )
       self.assertTrue(np.allclose(transpose(__lowerCamelCase      )			,     transpose(__lowerCamelCase      ).numpy()      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4			,     5      )
       SCREAMING_SNAKE_CASE__					=					torch.tensor(__lowerCamelCase      )
       self.assertTrue(np.allclose(transpose(__lowerCamelCase			,     axes=(1, 2, 0)      )			,     transpose(__lowerCamelCase			,     axes=(1, 2, 0)      ).numpy()      )      )






  @require_tf
  def    lowercase_	(							self		:	Optional[int]      )	->							Any:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					tf.constant(__lowerCamelCase      )
       self.assertTrue(np.allclose(transpose(__lowerCamelCase      )			,     transpose(__lowerCamelCase      ).numpy()      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4			,     5      )
       SCREAMING_SNAKE_CASE__					=					tf.constant(__lowerCamelCase      )
       self.assertTrue(np.allclose(transpose(__lowerCamelCase			,     axes=(1, 2, 0)      )			,     transpose(__lowerCamelCase			,     axes=(1, 2, 0)      ).numpy()      )      )






  @require_flax
  def    lowercase_	(							self		:	Tuple      )	->							int:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					jnp.array(__lowerCamelCase      )
       self.assertTrue(np.allclose(transpose(__lowerCamelCase      )			,     np.asarray(transpose(__lowerCamelCase      )      )      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4			,     5      )
       SCREAMING_SNAKE_CASE__					=					jnp.array(__lowerCamelCase      )
       self.assertTrue(np.allclose(transpose(__lowerCamelCase			,     axes=(1, 2, 0)      )			,     np.asarray(transpose(__lowerCamelCase			,     axes=(1, 2, 0)      )      )      )      )






  def    lowercase_	(							self		:	Dict      )	->							Optional[Any]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       self.assertTrue(np.allclose(reshape(__lowerCamelCase			,     (4, 3)      )			,     np.reshape(__lowerCamelCase			,     (4, 3)      )      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4			,     5      )
       self.assertTrue(np.allclose(reshape(__lowerCamelCase			,     (12, 5)      )			,     np.reshape(__lowerCamelCase			,     (12, 5)      )      )      )






  @require_torch
  def    lowercase_	(							self		:	str      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					torch.tensor(__lowerCamelCase      )
       self.assertTrue(np.allclose(reshape(__lowerCamelCase			,     (4, 3)      )			,     reshape(__lowerCamelCase			,     (4, 3)      ).numpy()      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4			,     5      )
       SCREAMING_SNAKE_CASE__					=					torch.tensor(__lowerCamelCase      )
       self.assertTrue(np.allclose(reshape(__lowerCamelCase			,     (12, 5)      )			,     reshape(__lowerCamelCase			,     (12, 5)      ).numpy()      )      )






  @require_tf
  def    lowercase_	(							self		:	str      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					tf.constant(__lowerCamelCase      )
       self.assertTrue(np.allclose(reshape(__lowerCamelCase			,     (4, 3)      )			,     reshape(__lowerCamelCase			,     (4, 3)      ).numpy()      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4			,     5      )
       SCREAMING_SNAKE_CASE__					=					tf.constant(__lowerCamelCase      )
       self.assertTrue(np.allclose(reshape(__lowerCamelCase			,     (12, 5)      )			,     reshape(__lowerCamelCase			,     (12, 5)      ).numpy()      )      )






  @require_flax
  def    lowercase_	(							self		:	Union[str, Any]      )	->							List[str]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					jnp.array(__lowerCamelCase      )
       self.assertTrue(np.allclose(reshape(__lowerCamelCase			,     (4, 3)      )			,     np.asarray(reshape(__lowerCamelCase			,     (4, 3)      )      )      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4			,     5      )
       SCREAMING_SNAKE_CASE__					=					jnp.array(__lowerCamelCase      )
       self.assertTrue(np.allclose(reshape(__lowerCamelCase			,     (12, 5)      )			,     np.asarray(reshape(__lowerCamelCase			,     (12, 5)      )      )      )      )






  def    lowercase_	(							self		:	List[Any]      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(1			,     3			,     4      )
       self.assertTrue(np.allclose(squeeze(__lowerCamelCase      )			,     np.squeeze(__lowerCamelCase      )      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(1			,     4			,     1			,     5      )
       self.assertTrue(np.allclose(squeeze(__lowerCamelCase			,     axis=2      )			,     np.squeeze(__lowerCamelCase			,     axis=2      )      )      )






  @require_torch
  def    lowercase_	(							self		:	Optional[int]      )	->							Any:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(1			,     3			,     4      )
       SCREAMING_SNAKE_CASE__					=					torch.tensor(__lowerCamelCase      )
       self.assertTrue(np.allclose(squeeze(__lowerCamelCase      )			,     squeeze(__lowerCamelCase      ).numpy()      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(1			,     4			,     1			,     5      )
       SCREAMING_SNAKE_CASE__					=					torch.tensor(__lowerCamelCase      )
       self.assertTrue(np.allclose(squeeze(__lowerCamelCase			,     axis=2      )			,     squeeze(__lowerCamelCase			,     axis=2      ).numpy()      )      )






  @require_tf
  def    lowercase_	(							self		:	Optional[int]      )	->							List[str]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(1			,     3			,     4      )
       SCREAMING_SNAKE_CASE__					=					tf.constant(__lowerCamelCase      )
       self.assertTrue(np.allclose(squeeze(__lowerCamelCase      )			,     squeeze(__lowerCamelCase      ).numpy()      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(1			,     4			,     1			,     5      )
       SCREAMING_SNAKE_CASE__					=					tf.constant(__lowerCamelCase      )
       self.assertTrue(np.allclose(squeeze(__lowerCamelCase			,     axis=2      )			,     squeeze(__lowerCamelCase			,     axis=2      ).numpy()      )      )






  @require_flax
  def    lowercase_	(							self		:	Tuple      )	->							Tuple:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(1			,     3			,     4      )
       SCREAMING_SNAKE_CASE__					=					jnp.array(__lowerCamelCase      )
       self.assertTrue(np.allclose(squeeze(__lowerCamelCase      )			,     np.asarray(squeeze(__lowerCamelCase      )      )      )      )

       SCREAMING_SNAKE_CASE__					=					np.random.randn(1			,     4			,     1			,     5      )
       SCREAMING_SNAKE_CASE__					=					jnp.array(__lowerCamelCase      )
       self.assertTrue(np.allclose(squeeze(__lowerCamelCase			,     axis=2      )			,     np.asarray(squeeze(__lowerCamelCase			,     axis=2      )      )      )      )






  def    lowercase_	(							self		:	Dict      )	->							List[Any]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       self.assertTrue(np.allclose(expand_dims(__lowerCamelCase			,     axis=1      )			,     np.expand_dims(__lowerCamelCase			,     axis=1      )      )      )






  @require_torch
  def    lowercase_	(							self		:	Union[str, Any]      )	->							int:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					torch.tensor(__lowerCamelCase      )
       self.assertTrue(np.allclose(expand_dims(__lowerCamelCase			,     axis=1      )			,     expand_dims(__lowerCamelCase			,     axis=1      ).numpy()      )      )






  @require_tf
  def    lowercase_	(							self		:	Any      )	->							Any:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					tf.constant(__lowerCamelCase      )
       self.assertTrue(np.allclose(expand_dims(__lowerCamelCase			,     axis=1      )			,     expand_dims(__lowerCamelCase			,     axis=1      ).numpy()      )      )







  @require_flax
  def    lowercase_	(							self		:	Any      )	->							List[Any]:
       SCREAMING_SNAKE_CASE__					=					np.random.randn(3			,     4      )
       SCREAMING_SNAKE_CASE__					=					jnp.array(__lowerCamelCase      )
       self.assertTrue(np.allclose(expand_dims(__lowerCamelCase			,     axis=1      )			,     np.asarray(expand_dims(__lowerCamelCase			,     axis=1      )      )      )      )





from importlib import import_module

from .logging import get_logger


_SCREAMING_SNAKE_CASE  :						Optional[int]         =    get_logger(__name__)






class  UpperCAmelCase__	:






  """simple docstring"""


  def __init__(							self		:	Optional[int]			,     __lowerCamelCase		:	Optional[Any]			,     __lowerCamelCase		:	Any=None      )	->							int:
       SCREAMING_SNAKE_CASE__					=					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      )      )
       SCREAMING_SNAKE_CASE__					=					module._original_module if isinstance(__lowerCamelCase			,     _PatchedModuleObj      ) else module






class  UpperCAmelCase__	:






  """simple docstring"""


  a     =      []






  def __init__(							self		:	int			,     __lowerCamelCase		:	Union[str, Any]			,     __lowerCamelCase		:	str			,     __lowerCamelCase		:	Optional[int]			,     __lowerCamelCase		:	List[Any]=None      )	->							Any:
       SCREAMING_SNAKE_CASE__					=					obj
       SCREAMING_SNAKE_CASE__					=					target
       SCREAMING_SNAKE_CASE__					=					new
       SCREAMING_SNAKE_CASE__					=					target.split('''.'''      )[0]
       SCREAMING_SNAKE_CASE__					=					{}
       SCREAMING_SNAKE_CASE__					=					attrs or []






  def __enter__(							self		:	int      )	->							Tuple:
       *SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					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:
                 SCREAMING_SNAKE_CASE__					=					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__():
                 SCREAMING_SNAKE_CASE__					=					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)
                 ):
                      SCREAMING_SNAKE_CASE__					=					obj_attr
                      # patch at top level
                      setattr(self.obj			,     __lowerCamelCase			,     _PatchedModuleObj(__lowerCamelCase			,     attrs=self.attrs      )      )
                      SCREAMING_SNAKE_CASE__					=					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      )      )
                           SCREAMING_SNAKE_CASE__					=					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:
                 SCREAMING_SNAKE_CASE__					=					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:
                      SCREAMING_SNAKE_CASE__					=					getattr(self.obj			,     __lowerCamelCase      )
                      setattr(self.obj			,     __lowerCamelCase			,     self.new      )
       elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
            SCREAMING_SNAKE_CASE__					=					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		:	Optional[Any]			,     *__lowerCamelCase		:	Tuple      )	->							List[str]:
       for attr in list(self.original      ):
            setattr(self.obj			,     __lowerCamelCase			,     self.original.pop(__lowerCamelCase      )      )






  def    lowercase_	(							self		:	List[Any]      )	->							Optional[Any]:
       self.__enter__()
       self._active_patches.append(self      )







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

       return self.__exit__()


