






import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


UpperCAmelCase__				   =		logging.get_logger(__name__)
def 						_a    (      a :Union[str, Any] )							->			Optional[int]:
 a		  =      r'''\w+[.]\d+'''
 a		  =      re.findall(a	,							a )
 for pat in pats:
  a		  =      key.replace(a	,							'''_'''.join(pat.split('''.''' ) ) )
 return key
def 						_a    (      a :List[str]	,							a :List[Any]	,							a :Union[str, Any] )							->			Optional[int]:
 a		  =      pt_tuple_key[:-1] + ('''scale''',)
 if (
     any('''norm''' in str_ for str_ in pt_tuple_key )
     and (pt_tuple_key[-1] == "bias")
     and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
     and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
 ):
  a		  =      pt_tuple_key[:-1] + ('''scale''',)
  return renamed_pt_tuple_key, pt_tensor
 elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
  a		  =      pt_tuple_key[:-1] + ('''scale''',)
  return renamed_pt_tuple_key, pt_tensor

 # embedding
 if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
  a		  =      pt_tuple_key[:-1] + ('''embedding''',)
  return renamed_pt_tuple_key, pt_tensor

 # conv layer
 a		  =      pt_tuple_key[:-1] + ('''kernel''',)
 if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
  a		  =      pt_tensor.transpose(2	,							3	,							1	,							0 )
  return renamed_pt_tuple_key, pt_tensor

 # linear layer
 a		  =      pt_tuple_key[:-1] + ('''kernel''',)
 if pt_tuple_key[-1] == "weight":
  a		  =      pt_tensor.T
  return renamed_pt_tuple_key, pt_tensor

 # old PyTorch layer norm weight
 a		  =      pt_tuple_key[:-1] + ('''weight''',)
 if pt_tuple_key[-1] == "gamma":
  return renamed_pt_tuple_key, pt_tensor

 # old PyTorch layer norm bias
 a		  =      pt_tuple_key[:-1] + ('''bias''',)
 if pt_tuple_key[-1] == "beta":
  return renamed_pt_tuple_key, pt_tensor

 return pt_tuple_key, pt_tensor

def 						_a    (      a :List[str]	,							a :List[Any]	,							a :Dict=42 )							->			Optional[Any]:
 # Step 1: Convert pytorch tensor to numpy
 a		  =      {k: v.numpy() for k, v in pt_state_dict.items()}

 # Step 2: Since the model is stateless, get random Flax params
 a		  =      flax_model.init_weights(PRNGKey(a ) )

 a		  =      flatten_dict(a )
 a		  =      {}

 # Need to change some parameters name to match Flax names
 for pt_key, pt_tensor in pt_state_dict.items():
  a		  =      rename_key(a )
  a		  =      tuple(renamed_pt_key.split('''.''' ) )

  # Correctly rename weight parameters
  a  ,     a		  =      rename_key_and_reshape_tensor(a	,							a	,							a )

  if flax_key in random_flax_state_dict:
   if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
    raise ValueError(
        F"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """
        F"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.""" )

        # also add unexpected weight so that warning is thrown
  a		  =      jnp.asarray(a )

 return unflatten_dict(a )










from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import MagicMock, patch

from transformers import AutoModel, TFAutoModel
from transformers.onnx import FeaturesManager
from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch






@require_torch
@require_tf
class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      def       __lowerCAmelCase					(      self      :						str  )    ->int:




       """simple docstring"""


       a		  =      SMALL_MODEL_IDENTIFIER
       a		  =      '''pt'''
       a		  =      '''tf'''







      def       __lowerCAmelCase					(      self      :						Optional[Any] ,					__UpperCAmelCase      :						str  )    ->Union[str, Any]:




       """simple docstring"""


       a		  =      AutoModel.from_pretrained(self.test_model  )
       model_pt.save_pretrained(__UpperCAmelCase  )







      def       __lowerCAmelCase					(      self      :						Any ,					__UpperCAmelCase      :						Union[str, Any]  )    ->List[str]:




       """simple docstring"""


       a		  =      TFAutoModel.from_pretrained(self.test_model ,					from_pt=__UpperCAmelCase  )
       model_tf.save_pretrained(__UpperCAmelCase  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->int:




       """simple docstring"""


       a		  =      '''mock_framework'''

       # Framework provided - return whatever the user provides
       a		  =      FeaturesManager.determine_framework(self.test_model ,					__UpperCAmelCase  )
       self.assertEqual(__UpperCAmelCase ,					__UpperCAmelCase  )

       # Local checkpoint and framework provided - return provided framework
       # PyTorch checkpoint
       with TemporaryDirectory() as local_pt_ckpt:
        self._setup_pt_ckpt(__UpperCAmelCase  )
        a		  =      FeaturesManager.determine_framework(__UpperCAmelCase ,					__UpperCAmelCase  )
        self.assertEqual(__UpperCAmelCase ,					__UpperCAmelCase  )

       # TensorFlow checkpoint
       with TemporaryDirectory() as local_tf_ckpt:
        self._setup_tf_ckpt(__UpperCAmelCase  )
        a		  =      FeaturesManager.determine_framework(__UpperCAmelCase ,					__UpperCAmelCase  )
        self.assertEqual(__UpperCAmelCase ,					__UpperCAmelCase  )







      def       __lowerCAmelCase					(      self      :						str  )    ->int:




       """simple docstring"""


       with TemporaryDirectory() as local_pt_ckpt:
        self._setup_pt_ckpt(__UpperCAmelCase  )
        a		  =      FeaturesManager.determine_framework(__UpperCAmelCase  )
        self.assertEqual(__UpperCAmelCase ,					self.framework_pt  )

       # TensorFlow checkpoint
       with TemporaryDirectory() as local_tf_ckpt:
        self._setup_tf_ckpt(__UpperCAmelCase  )
        a		  =      FeaturesManager.determine_framework(__UpperCAmelCase  )
        self.assertEqual(__UpperCAmelCase ,					self.framework_tf  )

       # Invalid local checkpoint
       with TemporaryDirectory() as local_invalid_ckpt:
        with self.assertRaises(__UpperCAmelCase  ):
         a		  =      FeaturesManager.determine_framework(__UpperCAmelCase  )







      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->List[str]:




       """simple docstring"""


       a		  =      MagicMock(return_value=__UpperCAmelCase  )
       with patch('''transformers.onnx.features.is_tf_available''' ,					__UpperCAmelCase  ):
        a		  =      FeaturesManager.determine_framework(self.test_model  )
        self.assertEqual(__UpperCAmelCase ,					self.framework_pt  )

       # PyTorch not in environment -> use TensorFlow
       a		  =      MagicMock(return_value=__UpperCAmelCase  )
       with patch('''transformers.onnx.features.is_torch_available''' ,					__UpperCAmelCase  ):
        a		  =      FeaturesManager.determine_framework(self.test_model  )
        self.assertEqual(__UpperCAmelCase ,					self.framework_tf  )

       # Both in environment -> use PyTorch
       a		  =      MagicMock(return_value=__UpperCAmelCase  )
       a		  =      MagicMock(return_value=__UpperCAmelCase  )
       with patch('''transformers.onnx.features.is_tf_available''' ,					__UpperCAmelCase  ), patch(
           '''transformers.onnx.features.is_torch_available''' ,					__UpperCAmelCase  ):
        a		  =      FeaturesManager.determine_framework(self.test_model  )
        self.assertEqual(__UpperCAmelCase ,					self.framework_pt  )

       # Both not in environment -> raise error
       a		  =      MagicMock(return_value=__UpperCAmelCase  )
       a		  =      MagicMock(return_value=__UpperCAmelCase  )
       with patch('''transformers.onnx.features.is_tf_available''' ,					__UpperCAmelCase  ), patch(
           '''transformers.onnx.features.is_torch_available''' ,					__UpperCAmelCase  ):
        with self.assertRaises(__UpperCAmelCase  ):
         a		  =      FeaturesManager.determine_framework(self.test_model  )


