




from collections import OrderedDict

from ...utils import logging
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
from .configuration_auto import CONFIG_MAPPING_NAMES


__a          =			logging.get_logger(__name__)


__a          =			OrderedDict(
    [
        # Base model mapping
        ('albert', 'FlaxAlbertModel'),
        ('bart', 'FlaxBartModel'),
        ('beit', 'FlaxBeitModel'),
        ('bert', 'FlaxBertModel'),
        ('big_bird', 'FlaxBigBirdModel'),
        ('blenderbot', 'FlaxBlenderbotModel'),
        ('blenderbot-small', 'FlaxBlenderbotSmallModel'),
        ('clip', 'FlaxCLIPModel'),
        ('distilbert', 'FlaxDistilBertModel'),
        ('electra', 'FlaxElectraModel'),
        ('gpt-sw3', 'FlaxGPT2Model'),
        ('gpt2', 'FlaxGPT2Model'),
        ('gpt_neo', 'FlaxGPTNeoModel'),
        ('gptj', 'FlaxGPTJModel'),
        ('longt5', 'FlaxLongT5Model'),
        ('marian', 'FlaxMarianModel'),
        ('mbart', 'FlaxMBartModel'),
        ('mt5', 'FlaxMT5Model'),
        ('opt', 'FlaxOPTModel'),
        ('pegasus', 'FlaxPegasusModel'),
        ('regnet', 'FlaxRegNetModel'),
        ('resnet', 'FlaxResNetModel'),
        ('roberta', 'FlaxRobertaModel'),
        ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'),
        ('roformer', 'FlaxRoFormerModel'),
        ('t5', 'FlaxT5Model'),
        ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'),
        ('vit', 'FlaxViTModel'),
        ('wav2vec2', 'FlaxWav2Vec2Model'),
        ('whisper', 'FlaxWhisperModel'),
        ('xglm', 'FlaxXGLMModel'),
        ('xlm-roberta', 'FlaxXLMRobertaModel'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for pre-training mapping
        ('albert', 'FlaxAlbertForPreTraining'),
        ('bart', 'FlaxBartForConditionalGeneration'),
        ('bert', 'FlaxBertForPreTraining'),
        ('big_bird', 'FlaxBigBirdForPreTraining'),
        ('electra', 'FlaxElectraForPreTraining'),
        ('longt5', 'FlaxLongT5ForConditionalGeneration'),
        ('mbart', 'FlaxMBartForConditionalGeneration'),
        ('mt5', 'FlaxMT5ForConditionalGeneration'),
        ('roberta', 'FlaxRobertaForMaskedLM'),
        ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'),
        ('roformer', 'FlaxRoFormerForMaskedLM'),
        ('t5', 'FlaxT5ForConditionalGeneration'),
        ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'),
        ('whisper', 'FlaxWhisperForConditionalGeneration'),
        ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for Masked LM mapping
        ('albert', 'FlaxAlbertForMaskedLM'),
        ('bart', 'FlaxBartForConditionalGeneration'),
        ('bert', 'FlaxBertForMaskedLM'),
        ('big_bird', 'FlaxBigBirdForMaskedLM'),
        ('distilbert', 'FlaxDistilBertForMaskedLM'),
        ('electra', 'FlaxElectraForMaskedLM'),
        ('mbart', 'FlaxMBartForConditionalGeneration'),
        ('roberta', 'FlaxRobertaForMaskedLM'),
        ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'),
        ('roformer', 'FlaxRoFormerForMaskedLM'),
        ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for Seq2Seq Causal LM mapping
        ('bart', 'FlaxBartForConditionalGeneration'),
        ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'),
        ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'),
        ('encoder-decoder', 'FlaxEncoderDecoderModel'),
        ('longt5', 'FlaxLongT5ForConditionalGeneration'),
        ('marian', 'FlaxMarianMTModel'),
        ('mbart', 'FlaxMBartForConditionalGeneration'),
        ('mt5', 'FlaxMT5ForConditionalGeneration'),
        ('pegasus', 'FlaxPegasusForConditionalGeneration'),
        ('t5', 'FlaxT5ForConditionalGeneration'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for Image-classsification
        ('beit', 'FlaxBeitForImageClassification'),
        ('regnet', 'FlaxRegNetForImageClassification'),
        ('resnet', 'FlaxResNetForImageClassification'),
        ('vit', 'FlaxViTForImageClassification'),
    ]
)

__a          =			OrderedDict(
    [
        ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for Causal LM mapping
        ('bart', 'FlaxBartForCausalLM'),
        ('bert', 'FlaxBertForCausalLM'),
        ('big_bird', 'FlaxBigBirdForCausalLM'),
        ('electra', 'FlaxElectraForCausalLM'),
        ('gpt-sw3', 'FlaxGPT2LMHeadModel'),
        ('gpt2', 'FlaxGPT2LMHeadModel'),
        ('gpt_neo', 'FlaxGPTNeoForCausalLM'),
        ('gptj', 'FlaxGPTJForCausalLM'),
        ('opt', 'FlaxOPTForCausalLM'),
        ('roberta', 'FlaxRobertaForCausalLM'),
        ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'),
        ('xglm', 'FlaxXGLMForCausalLM'),
        ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for Sequence Classification mapping
        ('albert', 'FlaxAlbertForSequenceClassification'),
        ('bart', 'FlaxBartForSequenceClassification'),
        ('bert', 'FlaxBertForSequenceClassification'),
        ('big_bird', 'FlaxBigBirdForSequenceClassification'),
        ('distilbert', 'FlaxDistilBertForSequenceClassification'),
        ('electra', 'FlaxElectraForSequenceClassification'),
        ('mbart', 'FlaxMBartForSequenceClassification'),
        ('roberta', 'FlaxRobertaForSequenceClassification'),
        ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'),
        ('roformer', 'FlaxRoFormerForSequenceClassification'),
        ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for Question Answering mapping
        ('albert', 'FlaxAlbertForQuestionAnswering'),
        ('bart', 'FlaxBartForQuestionAnswering'),
        ('bert', 'FlaxBertForQuestionAnswering'),
        ('big_bird', 'FlaxBigBirdForQuestionAnswering'),
        ('distilbert', 'FlaxDistilBertForQuestionAnswering'),
        ('electra', 'FlaxElectraForQuestionAnswering'),
        ('mbart', 'FlaxMBartForQuestionAnswering'),
        ('roberta', 'FlaxRobertaForQuestionAnswering'),
        ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'),
        ('roformer', 'FlaxRoFormerForQuestionAnswering'),
        ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for Token Classification mapping
        ('albert', 'FlaxAlbertForTokenClassification'),
        ('bert', 'FlaxBertForTokenClassification'),
        ('big_bird', 'FlaxBigBirdForTokenClassification'),
        ('distilbert', 'FlaxDistilBertForTokenClassification'),
        ('electra', 'FlaxElectraForTokenClassification'),
        ('roberta', 'FlaxRobertaForTokenClassification'),
        ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'),
        ('roformer', 'FlaxRoFormerForTokenClassification'),
        ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'),
    ]
)

__a          =			OrderedDict(
    [
        # Model for Multiple Choice mapping
        ('albert', 'FlaxAlbertForMultipleChoice'),
        ('bert', 'FlaxBertForMultipleChoice'),
        ('big_bird', 'FlaxBigBirdForMultipleChoice'),
        ('distilbert', 'FlaxDistilBertForMultipleChoice'),
        ('electra', 'FlaxElectraForMultipleChoice'),
        ('roberta', 'FlaxRobertaForMultipleChoice'),
        ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'),
        ('roformer', 'FlaxRoFormerForMultipleChoice'),
        ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'),
    ]
)

__a          =			OrderedDict(
    [
        ('bert', 'FlaxBertForNextSentencePrediction'),
    ]
)

__a          =			OrderedDict(
    [
        ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'),
        ('whisper', 'FlaxWhisperForConditionalGeneration'),
    ]
)

__a          =			OrderedDict(
    [
        ('whisper', 'FlaxWhisperForAudioClassification'),
    ]
)

__a          =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES)
__a          =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
__a          =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
)
__a          =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
__a          =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
)
__a          =			_LazyAutoMapping(
    CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
)

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_MAPPING


__a          =			auto_class_update(FlaxAutoModel)

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_PRETRAINING_MAPPING


__a          =			auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining')

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_CAUSAL_LM_MAPPING


__a          =			auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling')

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_MASKED_LM_MAPPING


__a          =			auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling')

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING


__a          =			auto_class_update(
    FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base'
)

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING


__a          =			auto_class_update(
    FlaxAutoModelForSequenceClassification, head_doc='sequence classification'
)

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING


__a          =			auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering')

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING


__a          =			auto_class_update(
    FlaxAutoModelForTokenClassification, head_doc='token classification'
)

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING


__a          =			auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice')

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING


__a          =			auto_class_update(
    FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction'
)

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING


__a          =			auto_class_update(
    FlaxAutoModelForImageClassification, head_doc='image classification'
)

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING


__a          =			auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling')

class   __a(					_BaseAutoModelClass       ):






    """simple docstring"""





    lowerCAmelCase        =				FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING


__a          =			auto_class_update(
    FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling'
)





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


__a          =			logging.get_logger(__name__)







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							str       =      r'''\w+[.]\d+'''
     UpperCAmelCase_      :							int       =      re.findall(_lowercase			,						_lowercase				)
     for pat in pats:
          UpperCAmelCase_      :							List[Any]       =      key.replace(_lowercase			,						'''_'''.join(pat.split('''.'''				)				)				)
     return key







def lowerCamelCase__       (      _lowercase			,						_lowercase			,						_lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Dict       =      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)
     ):
          UpperCAmelCase_      :							List[Any]       =      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:
          UpperCAmelCase_      :							Any       =      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:
          UpperCAmelCase_      :							Tuple       =      pt_tuple_key[:-1] + ('''embedding''',)
          return renamed_pt_tuple_key, pt_tensor

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

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

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

     # old PyTorch layer norm bias
     UpperCAmelCase_      :							Tuple       =      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__       (      _lowercase			,						_lowercase			,						_lowercase=42				):

     '''simple docstring'''


     UpperCAmelCase_      :							Union[str, Any]       =      {k: v.numpy() for k, v in pt_state_dict.items()}

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

     UpperCAmelCase_      :							List[Any]       =      flatten_dict(_lowercase				)
     UpperCAmelCase_      :							int       =      {}

     # Need to change some parameters name to match Flax names
     for pt_key, pt_tensor in pt_state_dict.items():
          UpperCAmelCase_      :							Optional[int]       =      rename_key(_lowercase				)
          UpperCAmelCase_      :							List[str]       =      tuple(renamed_pt_key.split('''.'''				)				)

          # Correctly rename weight parameters
          UpperCAmelCase_,   UpperCAmelCase_      :							Any       =      rename_key_and_reshape_tensor(_lowercase			,						_lowercase			,						_lowercase				)

          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
          UpperCAmelCase_      :							int       =      jnp.asarray(_lowercase				)

     return unflatten_dict(_lowercase				)