




'''simple docstring'''






import argparse

# utilities to import the model weights and config file
import os
import pickle as pkl

# PyTorch + new model classes
import torch
from torch import nn

from transformers import AutoTokenizer, MegaConfig, MegaForMaskedLM


# import the EncoderLayer class used to pretrain
# !! NOTE !! this requires the version of fairseq that is built when you install the Mega source
try:
      from fairseq.modules.mega_layer import MegaEncoderLayer
except ImportError:
      raise ImportError("You need to install the version of fairseq from the Mega repo!")






class 					lowercase_			(	nn.Module       ):





     def __init__(    self    :				List[Any]    ,       __lowerCamelCase    :				List[str]    ,       __lowerCamelCase    :				List[str]    ,       __lowerCamelCase    :				Dict ):
           super().__init__()
           snake_case__					:      Dict  			=						mega_args
           snake_case__					:      Optional[int]  			=						nn.Embedding(__lowerCamelCase    ,       self.mega_args.encoder_embed_dim )
           snake_case__					:      Union[str, Any]  			=						nn.ModuleList([MegaEncoderLayer(self.mega_args ) for _ in range(__lowerCamelCase )] )
           snake_case__					:      Tuple  			=						depth





     def  _lowerCAmelCase			(    self    :				List[Any]    ,       __lowerCamelCase    :				Tuple    ,       __lowerCamelCase    :				Union[str, Any]    ,       __lowerCamelCase    :				str=True    ,       __lowerCamelCase    :				List[str]=0 ):

           # Mega expects embeddings to be (time, batch, embedding size), but
           # Hugging Face returns tokens as (batch, time)
           if batch_first:
                 snake_case__					:      Tuple  			=						input_ids.T

           # to make things more confusing, Mega expects the attention mask to
           # be (batch, time), but with values of 0 (normal token) and 1 (ignore token)
           # which is the opposite of what HF returns
           if ignore_mask_value == 0:
                 snake_case__					:      Tuple  			=						1 - attention_mask

           # get token embeddings from IDs
           snake_case__					:      Dict  			=						self.embedding_layer(__lowerCamelCase )

           # pass through the Mega layers
           # input is (time, batch, encoder dim) and output is the same
           for encoder in self.encoders:
                 snake_case__					:      List[str]  			=						encoder(__lowerCamelCase    ,       __lowerCamelCase )

           # return according to the shape specified
           if batch_first:
                 # (T, B, H) --> (B, T, H)
                 return torch.transpose(__lowerCamelCase    ,       0    ,       1 )
           else:
                 return embeds






class 					lowercase_			(	nn.Module       ):





     def __init__(    self    :				List[str]    ,       __lowerCamelCase    :				List[str]    ,       __lowerCamelCase    :				str    ,       __lowerCamelCase    :				Optional[Any] ):
           super().__init__()
           snake_case__					:      int  			=						MegaLM(__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase )
           snake_case__					:      List[Any]  			=						nn.Linear(mega_args.encoder_embed_dim    ,       __lowerCamelCase )
           snake_case__					:      Optional[Any]  			=						nn.Dropout(p=0.1 )





     def  _lowerCAmelCase			(    self    :				List[Any]    ,       __lowerCamelCase    :				List[str]    ,       __lowerCamelCase    :				Optional[Any]    ,       __lowerCamelCase    :				str=True    ,       __lowerCamelCase    :				str=0 ):
           snake_case__					:      Tuple  			=						self.mega(__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase )
           return self.mlm_head(self.dropout(__lowerCamelCase ) )






def 		UpperCamelCase__			(		__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE		)						->      str:
      with open(os.path.join(__SCREAMING_SNAKE_CASE							,			'model_args.pkl'		)							,			'rb'		) as f:
            snake_case__					:      str  			=						pkl.load(__SCREAMING_SNAKE_CASE		)

      # load the original encoder
      snake_case__					:      Optional[int]  			=						OriginalMegaForMaskedLM(**__SCREAMING_SNAKE_CASE		).eval()

      # load its weights
      print(
          'Original Mega encoder:'							,			original_mlm.mega.load_state_dict(
              torch.load(os.path.join(__SCREAMING_SNAKE_CASE							,			'encoder_weights.pt'		)							,			map_location='cpu'		)		)							,			)
      print(
          'Original Mega MLM layer:'							,			original_mlm.mlm_head.load_state_dict(
              torch.load(os.path.join(__SCREAMING_SNAKE_CASE							,			'mlm_head_weights.pt'		)							,			map_location='cpu'		)		)							,			)

      # create a new config from the old one
      snake_case__					:      Optional[Any]  			=						MegaConfig(
          num_hidden_layers=mega_original_args['depth']							,			vocab_size=mega_original_args['vocab_size']							,			hidden_size=mega_original_args['mega_args'].encoder_embed_dim							,			shared_representation_size=mega_original_args['mega_args'].encoder_z_dim							,			intermediate_size=mega_original_args['mega_args'].encoder_hidden_dim							,			ema_projection_size=mega_original_args['mega_args'].encoder_n_dim							,			dropout_prob=mega_original_args['mega_args'].dropout							,			attention_probs_dropout_prob=mega_original_args['mega_args'].attention_dropout							,			hidden_dropout_prob=mega_original_args['mega_args'].hidden_dropout							,			activation=mega_original_args['mega_args'].activation_fn							,			attention_activation=mega_original_args['mega_args'].attention_activation_fn							,			bidirectional=mega_original_args['mega_args'].bidirectional							,			use_chunking=mega_original_args['mega_args'].encoder_chunk_size > 0							,			chunk_size=mega_original_args['mega_args'].encoder_chunk_size							,			truncation=mega_original_args['mega_args'].truncation_length							,			normalization_type=mega_original_args['mega_args'].normalization_type							,			normalize_before_mega=__SCREAMING_SNAKE_CASE							,			norm_affine=__SCREAMING_SNAKE_CASE							,			use_feature_dropout=mega_original_args['mega_args'].feature_dropout							,			relative_positional_bias=mega_original_args['mega_args'].rel_pos_bias							,			max_positions=mega_original_args['mega_args'].max_source_positions							,			nffn_hidden_size=mega_original_args['mega_args'].encoder_ffn_embed_dim							,			normalize_before_ffn=mega_original_args['mega_args'].normalize_before							,			nffn_activation_dropout_prob=0.0							,			add_token_type_embeddings=__SCREAMING_SNAKE_CASE							,			add_lm_hidden_dense_layer=__SCREAMING_SNAKE_CASE							,			)

      snake_case__					:      List[Any]  			=						MegaForMaskedLM(__SCREAMING_SNAKE_CASE		).eval()

      # the originl checkpoint just uses nn.Embedding for the word embeddings
      # we use a wrapper module for embeddings to add support for positional embeddings
      snake_case__					:      List[str]  			=						original_mlm.mega.embedding_layer.weight

      # modify the state dictionary of the original checkpoint to account for naming issues in the Hugging Face
      # ecosystem -- any names containing "beta" or "gamma" aren't safe to use and are renamed upon _load_pretrained,
      # also renaming previously confusing parameter names
      snake_case__					:      Any  			=						original_mlm.mega.encoders.state_dict()
      snake_case__					:      Dict  			=						{}
      for module_name in original_state_dict.keys():
            snake_case__					:      int  			=						None
            # have to handle gamma, beta, and alpha differently due to their use
            # in multiple modules within the original repository;
            # beta is used in EMA, MovingAverageGatedAttention, and RotaryRelativePositionalBias, and must be renamed due to flax/tf weights
            # the EMA sublayer was renamed from "move" to "ema_gate" for readability, so that is also done here
            if "beta" in module_name:
                  # EMA sub-layers were always called "move" in the original repo
                  if "move.beta" in module_name:
                        snake_case__					:      Optional[int]  			=						module_name.replace('move.beta'							,			'ema_gate.ema_expansion_matrix'		)
                  elif "mega_layer.beta" in module_name:
                        snake_case__					:      Tuple  			=						module_name.replace('beta'							,			'qk_bias'		)
                  else:
                        snake_case__					:      Any  			=						module_name.replace('beta'							,			'b_param'		)
        # beta is used in EMA and MovingAverageGatedAttention, and must be renamed due to flax/tf weights
            elif "gamma" in module_name:
                  if "move.gamma" in module_name:
                        snake_case__					:      List[str]  			=						module_name.replace('move.gamma'							,			'ema_gate.kernel_projection_matrix'		)
                  elif "mega_layer.gamma" in module_name:
                        snake_case__					:      Any  			=						module_name.replace('gamma'							,			'qk_weight'		)
                  else:
                        snake_case__					:      List[str]  			=						module_name.replace('gamma'							,			'g_param'		)
        # alpha is used in EMA and positional bias; renaming to improve readability
            elif "move.alpha" in module_name:
                  snake_case__					:      Optional[Any]  			=						module_name.replace('move.alpha'							,			'ema_gate.decay_factor'		)
            # delta is only used in EMA; renaming to improve readability
            elif "move.delta" in module_name:
                  snake_case__					:      Tuple  			=						module_name.replace('move.delta'							,			'ema_gate.damping_factor'		)
            # omega is only used in EMA; renaming to improve readability
            elif "omega" in module_name:
                  snake_case__					:      Tuple  			=						module_name.replace('move.omega'							,			'ema_gate.residual_weight'		)

            if new_module_name:
                  snake_case__					:      List[str]  			=						new_module_name

      if len(__SCREAMING_SNAKE_CASE		) != 0:
            print(f"Renaming these keys: {updated_keys.keys()}"		)
      else:
            print('No need to rename state dict entries'		)
      for old, new in updated_keys.items():
            snake_case__					:      Dict  			=						original_state_dict.pop(__SCREAMING_SNAKE_CASE		)

      # now attempt to load the state dictionary with updated names
      # note that we now call it `mega.layers` instead of `mega.encoders` due to hugging face style
      print('HF Mega encoder:'							,			hf_mlm.mega.layers.load_state_dict(__SCREAMING_SNAKE_CASE		)		)

      # load the MLM head weights directly
      print(
          'HF Mega MLM layer:'							,			hf_mlm.mlm_head.load_state_dict(
              torch.load(os.path.join(__SCREAMING_SNAKE_CASE							,			'mlm_head_weights.pt'		)							,			map_location='cpu'		)		)							,			)

      # test on a randomly generated input sequence
      snake_case__					:      Union[str, Any]  			=						torch.randint(0							,			hf_config.vocab_size							,			size=(4, 256)		)
      snake_case__					:      Optional[int]  			=						torch.ones_like(__SCREAMING_SNAKE_CASE		)
      # mask a few tokens to make sure masking is applied appropriately :)
      snake_case__					:      List[Any]  			=						0

      # run forward passes
      snake_case__					:      Optional[int]  			=						original_mlm(__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE							,			batch_first=__SCREAMING_SNAKE_CASE							,			ignore_mask_value=0		)
      snake_case__					:      Optional[Any]  			=						hf_mlm(__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE		)[0]

      # print shapes and diff
      print(f"original output {original_output.shape}"		)
      print(f"hf output {hf_output.shape}"		)
      print(f"max diff: {(original_output - hf_output).max()}"		)  # 0.0
      snake_case__					:      Optional[Any]  			=						torch.allclose(__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE							,			atol=1E-3		)

      if success:
            print('Yay!'		)
            hf_mlm.save_pretrained(__SCREAMING_SNAKE_CASE		)
      else:
            raise RuntimeError(f"Something's broken :(\nOriginal:\n{original_output}\n\nHF\n{hf_output}\n{hf_mlm}"		)

      if includes_tokenizer:
            print('Transferring tokenizer'		)
            snake_case__					:      Union[str, Any]  			=						AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE		)
            tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE		)


if __name__ == "__main__":
      A_ 			=		argparse.ArgumentParser()

      parser.add_argument(
          "--pretrained_checkpoint_path",
          default=None,
          type=str,
          required=True,
          help="Point to the directory containing your model weights using the official Mega repo",
      )

      parser.add_argument(
          "--output_path", default=None, type=str, required=True, help="Location to save the Hugging Face version"
      )

      parser.add_argument(
          "--includes_tokenizer",
          action="store_true",
          help="Use this flag if there is a Hugging Face tokenizer in the original checkpoint repo",
      )

      A_ 			=		parser.parse_args()

      convert_checkpoint_to_huggingface(args.pretrained_checkpoint_path, args.output_path, args.includes_tokenizer)






'''simple docstring'''






import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
      import os

      # The slow tests are often failing with OOM error on GPU
      # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
      # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
      A_ 			=		"platform"

      import jax
      import jax.numpy as jnp

      from transformers import MarianTokenizer
      from transformers.models.marian.modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, shift_tokens_right






def 		UpperCamelCase__			(		__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			)						->      Union[str, Any]:
      if attention_mask is None:
            snake_case__					:      Union[str, Any]  			=						np.where(input_ids != config.pad_token_id							,			1							,			0		)
      if decoder_attention_mask is None:
            snake_case__					:      int  			=						np.where(decoder_input_ids != config.pad_token_id							,			1							,			0		)
      if head_mask is None:
            snake_case__					:      Optional[int]  			=						np.ones((config.encoder_layers, config.encoder_attention_heads)		)
      if decoder_head_mask is None:
            snake_case__					:      str  			=						np.ones((config.decoder_layers, config.decoder_attention_heads)		)
      if cross_attn_head_mask is None:
            snake_case__					:      int  			=						np.ones((config.decoder_layers, config.decoder_attention_heads)		)
      return {
          "input_ids": input_ids,
          "decoder_input_ids": decoder_input_ids,
          "attention_mask": attention_mask,
          "decoder_attention_mask": attention_mask,
      }






class 					lowercase_			:





     def __init__(    self    :				Any    ,       __lowerCamelCase    :				Optional[Any]    ,       __lowerCamelCase    :				Optional[Any]=13    ,       __lowerCamelCase    :				str=7    ,       __lowerCamelCase    :				Optional[int]=True    ,       __lowerCamelCase    :				List[str]=False    ,       __lowerCamelCase    :				str=99    ,       __lowerCamelCase    :				List[str]=16    ,       __lowerCamelCase    :				Optional[Any]=2    ,       __lowerCamelCase    :				Tuple=4    ,       __lowerCamelCase    :				Any=4    ,       __lowerCamelCase    :				Optional[int]="gelu"    ,       __lowerCamelCase    :				Optional[Any]=0.1    ,       __lowerCamelCase    :				List[Any]=0.1    ,       __lowerCamelCase    :				Optional[int]=32    ,       __lowerCamelCase    :				Optional[Any]=2    ,       __lowerCamelCase    :				Union[str, Any]=1    ,       __lowerCamelCase    :				Dict=0    ,       __lowerCamelCase    :				Tuple=0.0_2    ,       ):
           snake_case__					:      Tuple  			=						parent
           snake_case__					:      Any  			=						batch_size
           snake_case__					:      Union[str, Any]  			=						seq_length
           snake_case__					:      Optional[Any]  			=						is_training
           snake_case__					:      Union[str, Any]  			=						use_labels
           snake_case__					:      Union[str, Any]  			=						vocab_size
           snake_case__					:      Any  			=						hidden_size
           snake_case__					:      Tuple  			=						num_hidden_layers
           snake_case__					:      Tuple  			=						num_attention_heads
           snake_case__					:      str  			=						intermediate_size
           snake_case__					:      Union[str, Any]  			=						hidden_act
           snake_case__					:      Optional[Any]  			=						hidden_dropout_prob
           snake_case__					:      str  			=						attention_probs_dropout_prob
           snake_case__					:      Optional[int]  			=						max_position_embeddings
           snake_case__					:      Union[str, Any]  			=						eos_token_id
           snake_case__					:      str  			=						pad_token_id
           snake_case__					:      Tuple  			=						bos_token_id
           snake_case__					:      str  			=						initializer_range





     def  _lowerCAmelCase			(    self    :				Optional[int] ):
           snake_case__					:      List[Any]  			=						np.clip(ids_tensor([self.batch_size, self.seq_length - 1]    ,       self.vocab_size )    ,       3    ,       self.vocab_size )
           snake_case__					:      Tuple  			=						np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)    ,       dtype=np.intaa ))    ,       -1 )

           snake_case__					:      Optional[int]  			=						shift_tokens_right(__lowerCamelCase    ,       1    ,       2 )

           snake_case__					:      Union[str, Any]  			=						MarianConfig(
               vocab_size=self.vocab_size    ,       d_model=self.hidden_size    ,       encoder_layers=self.num_hidden_layers    ,       decoder_layers=self.num_hidden_layers    ,       encoder_attention_heads=self.num_attention_heads    ,       decoder_attention_heads=self.num_attention_heads    ,       encoder_ffn_dim=self.intermediate_size    ,       decoder_ffn_dim=self.intermediate_size    ,       dropout=self.hidden_dropout_prob    ,       attention_dropout=self.attention_probs_dropout_prob    ,       max_position_embeddings=self.max_position_embeddings    ,       eos_token_id=self.eos_token_id    ,       bos_token_id=self.bos_token_id    ,       pad_token_id=self.pad_token_id    ,       initializer_range=self.initializer_range    ,       use_cache=__lowerCamelCase    ,       )
           snake_case__					:      Union[str, Any]  			=						prepare_marian_inputs_dict(__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase )
           return config, inputs_dict





     def  _lowerCAmelCase			(    self    :				Optional[int] ):
           snake_case__			,       snake_case__					:      Optional[int]  			=						self.prepare_config_and_inputs()
           return config, inputs_dict





     def  _lowerCAmelCase			(    self    :				Tuple    ,       __lowerCamelCase    :				Union[str, Any]    ,       __lowerCamelCase    :				Dict    ,       __lowerCamelCase    :				Dict ):
           snake_case__					:      Optional[int]  			=						20
           snake_case__					:      str  			=						model_class_name(__lowerCamelCase )

           snake_case__					:      Dict  			=						model.encode(inputs_dict['input_ids'] )

           snake_case__			,       snake_case__					:      int  			=						(
               inputs_dict['decoder_input_ids'],
               inputs_dict['decoder_attention_mask'],
           )

           snake_case__					:      Dict  			=						model.init_cache(decoder_input_ids.shape[0]    ,       __lowerCamelCase    ,       __lowerCamelCase )
           snake_case__					:      Optional[int]  			=						jnp.ones((decoder_input_ids.shape[0], max_decoder_length)    ,       dtype='i4' )

           snake_case__					:      List[str]  			=						jnp.broadcast_to(
               jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :]    ,       (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)    ,       )
           snake_case__					:      Dict  			=						model.decode(
               decoder_input_ids[:, :-1]    ,       __lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase    ,       past_key_values=__lowerCamelCase    ,       decoder_position_ids=__lowerCamelCase    ,       )

           snake_case__					:      List[str]  			=						jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]    ,       dtype='i4' )
           snake_case__					:      Tuple  			=						model.decode(
               decoder_input_ids[:, -1:]    ,       __lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase    ,       past_key_values=outputs_cache.past_key_values    ,       decoder_position_ids=__lowerCamelCase    ,       )

           snake_case__					:      Union[str, Any]  			=						model.decode(__lowerCamelCase    ,       __lowerCamelCase )

           snake_case__					:      Tuple  			=						np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
           self.parent.assertTrue(diff < 1E-3    ,       msg=F"Max diff is {diff}" )





     def  _lowerCAmelCase			(    self    :				Tuple    ,       __lowerCamelCase    :				Any    ,       __lowerCamelCase    :				Dict    ,       __lowerCamelCase    :				Optional[int] ):
           snake_case__					:      int  			=						20
           snake_case__					:      Tuple  			=						model_class_name(__lowerCamelCase )

           snake_case__					:      Optional[int]  			=						model.encode(inputs_dict['input_ids'] )

           snake_case__			,       snake_case__					:      Dict  			=						(
               inputs_dict['decoder_input_ids'],
               inputs_dict['decoder_attention_mask'],
           )

           snake_case__					:      List[str]  			=						jnp.concatenate(
               [
                   decoder_attention_mask,
                   jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ),
               ]    ,       axis=-1    ,       )

           snake_case__					:      Union[str, Any]  			=						model.init_cache(decoder_input_ids.shape[0]    ,       __lowerCamelCase    ,       __lowerCamelCase )
           snake_case__					:      List[str]  			=						jnp.broadcast_to(
               jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :]    ,       (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)    ,       )

           snake_case__					:      List[Any]  			=						model.decode(
               decoder_input_ids[:, :-1]    ,       __lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase    ,       past_key_values=__lowerCamelCase    ,       decoder_position_ids=__lowerCamelCase    ,       )
           snake_case__					:      Tuple  			=						jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]    ,       dtype='i4' )
           snake_case__					:      int  			=						model.decode(
               decoder_input_ids[:, -1:]    ,       __lowerCamelCase    ,       past_key_values=outputs_cache.past_key_values    ,       decoder_attention_mask=__lowerCamelCase    ,       decoder_position_ids=__lowerCamelCase    ,       )

           snake_case__					:      Dict  			=						model.decode(__lowerCamelCase    ,       __lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase )

           snake_case__					:      Optional[int]  			=						np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
           self.parent.assertTrue(diff < 1E-3    ,       msg=F"Max diff is {diff}" )






@require_flax
class 					lowercase_			(	lowerCAmelCase_	,					unittest.TestCase	,					lowerCAmelCase_       ):
     A_       							= True
     A_       							= (FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
     A_       							= (FlaxMarianMTModel,) if is_flax_available() else ()





     def  _lowerCAmelCase			(    self    :				int ):
           snake_case__					:      Any  			=						FlaxMarianModelTester(self )





     def  _lowerCAmelCase			(    self    :				Optional[Any] ):
           snake_case__			,       snake_case__					:      Optional[Any]  			=						self.model_tester.prepare_config_and_inputs()
           for model_class in self.all_model_classes:
                 self.model_tester.check_use_cache_forward(__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase )





     def  _lowerCAmelCase			(    self    :				str ):
           snake_case__			,       snake_case__					:      str  			=						self.model_tester.prepare_config_and_inputs()
           for model_class in self.all_model_classes:
                 self.model_tester.check_use_cache_forward_with_attn_mask(__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase )





     def  _lowerCAmelCase			(    self    :				List[Any] ):
           snake_case__			,       snake_case__					:      Optional[Any]  			=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 with self.subTest(model_class.__name__ ):
                       snake_case__					:      Union[str, Any]  			=						self._prepare_for_class(__lowerCamelCase    ,       __lowerCamelCase )
                       snake_case__					:      List[str]  			=						model_class(__lowerCamelCase )

                       @jax.jit
                       def encode_jitted(__lowerCamelCase    :				Dict    ,       __lowerCamelCase    :				Optional[Any]=None    ,       **__lowerCamelCase    :				List[str] ):
                             return model.encode(input_ids=__lowerCamelCase    ,       attention_mask=__lowerCamelCase )

                       with self.subTest('JIT Enabled' ):
                             snake_case__					:      List[Any]  			=						encode_jitted(**__lowerCamelCase ).to_tuple()

                       with self.subTest('JIT Disabled' ):
                             with jax.disable_jit():
                                   snake_case__					:      Dict  			=						encode_jitted(**__lowerCamelCase ).to_tuple()

                       self.assertEqual(len(__lowerCamelCase )    ,       len(__lowerCamelCase ) )
                       for jitted_output, output in zip(__lowerCamelCase    ,       __lowerCamelCase ):
                             self.assertEqual(jitted_output.shape    ,       output.shape )





     def  _lowerCAmelCase			(    self    :				int ):
           snake_case__			,       snake_case__					:      Dict  			=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 with self.subTest(model_class.__name__ ):
                       snake_case__					:      List[str]  			=						model_class(__lowerCamelCase )
                       snake_case__					:      Union[str, Any]  			=						model.encode(inputs_dict['input_ids']    ,       inputs_dict['attention_mask'] )

                       snake_case__					:      str  			=						{
                           'decoder_input_ids': inputs_dict['decoder_input_ids'],
                           'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
                           'encoder_outputs': encoder_outputs,
                       }

                       @jax.jit
                       def decode_jitted(__lowerCamelCase    :				Tuple    ,       __lowerCamelCase    :				Any    ,       __lowerCamelCase    :				Optional[Any] ):
                             return model.decode(
                                 decoder_input_ids=__lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase    ,       encoder_outputs=__lowerCamelCase    ,       )

                       with self.subTest('JIT Enabled' ):
                             snake_case__					:      List[str]  			=						decode_jitted(**__lowerCamelCase ).to_tuple()

                       with self.subTest('JIT Disabled' ):
                             with jax.disable_jit():
                                   snake_case__					:      str  			=						decode_jitted(**__lowerCamelCase ).to_tuple()

                       self.assertEqual(len(__lowerCamelCase )    ,       len(__lowerCamelCase ) )
                       for jitted_output, output in zip(__lowerCamelCase    ,       __lowerCamelCase ):
                             self.assertEqual(jitted_output.shape    ,       output.shape )





     @slow
     def  _lowerCAmelCase			(    self    :				List[str] ):
           for model_class_name in self.all_model_classes:
                 snake_case__					:      Any  			=						model_class_name.from_pretrained('Helsinki-NLP/opus-mt-en-de' )
                 # FlaxMarianForSequenceClassification expects eos token in input_ids
                 snake_case__					:      List[Any]  			=						np.ones((1, 1) ) * model.config.eos_token_id
                 snake_case__					:      Union[str, Any]  			=						model(__lowerCamelCase )
                 self.assertIsNotNone(__lowerCamelCase )






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	unittest.TestCase       ):
     A_       							= None
     A_       							= None





     @classmethod
     def  _lowerCAmelCase			(    cls    :				Union[str, Any] ):
           snake_case__					:      List[Any]  			=						F"Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"
           return cls





     @cached_property
     def  _lowerCAmelCase			(    self    :				Optional[int] ):
           return MarianTokenizer.from_pretrained(self.model_name )





     @property
     def  _lowerCAmelCase			(    self    :				int ):
           return self.tokenizer.eos_token_id





     @cached_property
     def  _lowerCAmelCase			(    self    :				Dict ):
           snake_case__					:      FlaxMarianMTModel  			=						FlaxMarianMTModel.from_pretrained(self.model_name )
           self.assertEqual(model.config.decoder_start_token_id    ,       model.config.pad_token_id )
           return model





     def  _lowerCAmelCase			(    self    :				Tuple    ,       **__lowerCamelCase    :				List[Any] ):
           snake_case__					:      Dict  			=						self.translate_src_text(**__lowerCamelCase )
           self.assertListEqual(self.expected_text    ,       __lowerCamelCase )





     def  _lowerCAmelCase			(    self    :				List[str]    ,       **__lowerCamelCase    :				Dict ):
           snake_case__					:      str  			=						self.tokenizer(self.src_text    ,       padding=__lowerCamelCase    ,       return_tensors='np'    ,       **__lowerCamelCase )
           snake_case__					:      Any  			=						self.model.generate(
               model_inputs.input_ids    ,       attention_mask=model_inputs.attention_mask    ,       num_beams=2    ,       max_length=128    ,       ).sequences
           snake_case__					:      List[str]  			=						self.tokenizer.batch_decode(__lowerCamelCase    ,       skip_special_tokens=__lowerCamelCase )
           return generated_words






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "en"
     A_       							= "fr"
     A_       							= [
         "I am a small frog.",
         "Now I can forget the 100 words of german that I know.",
     ]
     A_       							= [
         "Je suis une petite grenouille.",
         "Maintenant, je peux oublier les 100 mots d'allemand que je connais.",
     ]





     @slow
     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "fr"
     A_       							= "en"
     A_       							= [
         "Donnez moi le micro.",
         "Tom et Mary étaient assis à une table.",  # Accents
     ]
     A_       							= [
         "Give me the microphone.",
         "Tom and Mary were sitting at a table.",
     ]





     @slow
     def  _lowerCAmelCase			(    self    :				List[Any] ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "mt"
     A_       							= "en"
     A_       							= ["Billi messu b'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem."]
     A_       							= ["Touching gently, Jesus healed a man who was affected by the sad disease of leprosy."]





     @slow
     def  _lowerCAmelCase			(    self    :				Dict ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "en"
     A_       							= "de"
     A_       							= [
         "I am a small frog.",
         "Now I can forget the 100 words of german that I know.",
         "Tom asked his teacher for advice.",
         "That's how I would do it.",
         "Tom really admired Mary's courage.",
         "Turn around and close your eyes.",
     ]
     A_       							= [
         "Ich bin ein kleiner Frosch.",
         "Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.",
         "Tom bat seinen Lehrer um Rat.",
         "So würde ich das machen.",
         "Tom bewunderte Marias Mut wirklich.",
         "Drehen Sie sich um und schließen Sie die Augen.",
     ]





     @slow
     def  _lowerCAmelCase			(    self    :				Dict ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "en"
     A_       							= "zh"
     A_       							= ["My name is Wolfgang and I live in Berlin"]
     A_       							= ["我叫沃尔夫冈 我住在柏林"]





     @slow
     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "ru"
     A_       							= "fr"
     A_       							= ["Он показал мне рукопись своей новой пьесы."]
     A_       							= ["Il m'a montré le manuscrit de sa nouvelle pièce."]





     @slow
     def  _lowerCAmelCase			(    self    :				Optional[Any] ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "en"
     A_       							= "ROMANCE"
     A_       							= [
         ">>fr<< Don't spend so much time watching TV.",
         ">>pt<< Your message has been sent.",
         ">>es<< He's two years older than me.",
     ]
     A_       							= [
         "Ne passez pas autant de temps à regarder la télé.",
         "A sua mensagem foi enviada.",
         "Es dos años más viejo que yo.",
     ]





     @slow
     def  _lowerCAmelCase			(    self    :				int ):
           self._assert_generated_batch_equal_expected()
