




import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
   import jax.numpy as jnp

   from transformers.models.distilbert.modeling_flax_distilbert import (
       FlaxDistilBertForMaskedLM,
       FlaxDistilBertForMultipleChoice,
       FlaxDistilBertForQuestionAnswering,
       FlaxDistilBertForSequenceClassification,
       FlaxDistilBertForTokenClassification,
       FlaxDistilBertModel,
   )





class 			lowerCamelCase_				( unittest.TestCase   ):


 '''simple docstring'''







 def __init__(				self    :						str							,							_lowerCAmelCase    :						Optional[Any]							,							_lowerCAmelCase    :						Optional[int]=13							,							_lowerCAmelCase    :						Any=7							,							_lowerCAmelCase    :						Tuple=True							,							_lowerCAmelCase    :						List[str]=True							,							_lowerCAmelCase    :						Optional[Any]=True							,							_lowerCAmelCase    :						Any=True							,							_lowerCAmelCase    :						Optional[Any]=99							,							_lowerCAmelCase    :						Union[str, Any]=32							,							_lowerCAmelCase    :						str=5							,							_lowerCAmelCase    :						Dict=4							,							_lowerCAmelCase    :						Any=37							,							_lowerCAmelCase    :						int="gelu"							,							_lowerCAmelCase    :						Dict=0.1							,							_lowerCAmelCase    :						Optional[Any]=0.1							,							_lowerCAmelCase    :						Any=512							,							_lowerCAmelCase    :						Dict=16							,							_lowerCAmelCase    :						Union[str, Any]=2							,							_lowerCAmelCase    :						Dict=0.02							,							_lowerCAmelCase    :						List[str]=4							,							):
       SCREAMING_SNAKE_CASE_      		=     parent
       SCREAMING_SNAKE_CASE_      		=     batch_size
       SCREAMING_SNAKE_CASE_      		=     seq_length
       SCREAMING_SNAKE_CASE_      		=     is_training
       SCREAMING_SNAKE_CASE_      		=     use_attention_mask
       SCREAMING_SNAKE_CASE_      		=     use_token_type_ids
       SCREAMING_SNAKE_CASE_      		=     use_labels
       SCREAMING_SNAKE_CASE_      		=     vocab_size
       SCREAMING_SNAKE_CASE_      		=     hidden_size
       SCREAMING_SNAKE_CASE_      		=     num_hidden_layers
       SCREAMING_SNAKE_CASE_      		=     num_attention_heads
       SCREAMING_SNAKE_CASE_      		=     intermediate_size
       SCREAMING_SNAKE_CASE_      		=     hidden_act
       SCREAMING_SNAKE_CASE_      		=     hidden_dropout_prob
       SCREAMING_SNAKE_CASE_      		=     attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE_      		=     max_position_embeddings
       SCREAMING_SNAKE_CASE_      		=     type_vocab_size
       SCREAMING_SNAKE_CASE_      		=     type_sequence_label_size
       SCREAMING_SNAKE_CASE_      		=     initializer_range
       SCREAMING_SNAKE_CASE_      		=     num_choices



 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       SCREAMING_SNAKE_CASE_      		=     ids_tensor([self.batch_size, self.seq_length]							,							self.vocab_size		)

       SCREAMING_SNAKE_CASE_      		=     None
       if self.use_attention_mask:
             SCREAMING_SNAKE_CASE_      		=     random_attention_mask([self.batch_size, self.seq_length]		)

       SCREAMING_SNAKE_CASE_      		=     DistilBertConfig(
           vocab_size=self.vocab_size							,							dim=self.hidden_size							,							n_layers=self.num_hidden_layers							,							n_heads=self.num_attention_heads							,							hidden_dim=self.intermediate_size							,							hidden_act=self.hidden_act							,							dropout=self.hidden_dropout_prob							,							attention_dropout=self.attention_probs_dropout_prob							,							max_position_embeddings=self.max_position_embeddings							,							initializer_range=self.initializer_range							,							tie_weights_=_lowerCAmelCase							,							)

       return config, input_ids, attention_mask




 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       SCREAMING_SNAKE_CASE_      		=     self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     config_and_inputs
       SCREAMING_SNAKE_CASE_      		=     {'input_ids': input_ids, 'attention_mask': attention_mask}
       return config, inputs_dict





@require_flax
class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE			,  unittest.TestCase   ):


 '''simple docstring'''







 lowercase_							       =       (
     (
         FlaxDistilBertModel,
         FlaxDistilBertForMaskedLM,
         FlaxDistilBertForMultipleChoice,
         FlaxDistilBertForQuestionAnswering,
         FlaxDistilBertForSequenceClassification,
         FlaxDistilBertForTokenClassification,
         FlaxDistilBertForQuestionAnswering,
     )
     if is_flax_available()
     else ()
 )



 def  lowerCAmelCase_    (				self    :						Dict		):
       SCREAMING_SNAKE_CASE_      		=     FlaxDistilBertModelTester(self		)




 @slow
 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       for model_class_name in self.all_model_classes:
             SCREAMING_SNAKE_CASE_      		=     model_class_name.from_pretrained('distilbert-base-uncased'		)
             SCREAMING_SNAKE_CASE_      		=     model(np.ones((1, 1)		)		)
             self.assertIsNotNone(_lowerCAmelCase		)





@require_flax
class 			lowerCamelCase_				( unittest.TestCase   ):


 '''simple docstring'''







 @slow
 def  lowerCAmelCase_    (				self    :						List[Any]		):
       SCREAMING_SNAKE_CASE_      		=     FlaxDistilBertModel.from_pretrained('distilbert-base-uncased'		)
       SCREAMING_SNAKE_CASE_      		=     np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]		)
       SCREAMING_SNAKE_CASE_      		=     np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]		)
       SCREAMING_SNAKE_CASE_      		=     model(_lowerCAmelCase							,							attention_mask=_lowerCAmelCase		)[0]
       SCREAMING_SNAKE_CASE_      		=     (1, 11, 768)
       self.assertEqual(output.shape							,							_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]		)

       self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]							,							_lowerCAmelCase							,							atol=1E-4		)		)







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


lowerCamelCase      :       int    =						logging.get_logger(__name__)





def    __lowerCAmelCase   (    __snake_case							):
     __lowerCAmelCase             =       r"\w+[.]\d+"
     __lowerCAmelCase             =       re.findall(__snake_case       ,			__snake_case							)
     for pat in pats:
          __lowerCAmelCase             =       key.replace(__snake_case       ,			"_".join(pat.split("."							)							)							)
     return key





def    __lowerCAmelCase   (    __snake_case       ,			__snake_case       ,			__snake_case							):
     __lowerCAmelCase             =       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)
     ):
          __lowerCAmelCase             =       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:
          __lowerCAmelCase             =       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:
          __lowerCAmelCase             =       pt_tuple_key[:-1] + ("embedding",)
          return renamed_pt_tuple_key, pt_tensor

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

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

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

     # old PyTorch layer norm bias
     __lowerCAmelCase             =       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    __lowerCAmelCase   (    __snake_case       ,			__snake_case       ,			__snake_case=42							):
     # Step 1: Convert pytorch tensor to numpy
     __lowerCAmelCase             =       {k: v.numpy() for k, v in pt_state_dict.items()}

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

     __lowerCAmelCase             =       flatten_dict(__snake_case							)
     __lowerCAmelCase             =       {}

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

          # Correctly rename weight parameters
          __lowerCAmelCase      ,			__lowerCAmelCase             =       rename_key_and_reshape_tensor(__snake_case       ,			__snake_case       ,			__snake_case							)

          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
          __lowerCAmelCase             =       jnp.asarray(__snake_case							)

     return unflatten_dict(__snake_case							)






