






import copy
import logging
import random

import joblib
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm

from transformers import AdamW, GPTaLMHeadModel, get_linear_schedule_with_warmup


_UpperCAmelCase					:						List[str]         =     logging.getLogger(__name__)






def  UpperCAmelCase__						(    lowerCamelCase	:			str    ):
   random.seed(lowerCamelCase    )
   np.random.seed(lowerCamelCase    )
   torch.manual_seed(lowerCamelCase    )
   torch.cuda.manual_seed_all(lowerCamelCase    )






def  UpperCAmelCase__						(    lowerCamelCase	:			int			,lowerCamelCase	:			Any			,lowerCamelCase	:			Optional[Any]    ):
   model.eval()
   lowerCamelCase									=next(model.parameters()    ).device
   lowerCamelCase									=1
   lowerCamelCase									=torch.zeros((eval_batch_size, context_len)			,dtype=torch.long			,device=lowerCamelCase    )
   lowerCamelCase									=DataLoader(lowerCamelCase			,shuffle=lowerCamelCase			,batch_size=lowerCamelCase    )
   lowerCamelCase									=torch.zeros(1			,device=lowerCamelCase    )
   lowerCamelCase									=0
   for batch in eval_dataloader:
      batch.to(lowerCamelCase    )
      # pad
      context.zero_()
      for i in range(lowerCamelCase    ):
         lowerCamelCase									=batch[i]
      lowerCamelCase									=model(lowerCamelCase			,labels=lowerCamelCase    )
      eval_loss += outputs[0].sum().item()
      nb_eval_examples += batch.size(0    )
   lowerCamelCase									=eval_loss / nb_eval_examples
   lowerCamelCase									=torch.exp(lowerCamelCase    )
   model.train()
   return perplexity






def  UpperCAmelCase__						(    lowerCamelCase	:			List[Any]="gpt2"    ):
   lowerCamelCase									=GPTaLMHeadModel.from_pretrained(lowerCamelCase			,output_hidden_states=lowerCamelCase    )
   torch.save(model.state_dict()			,model_name + """local.pt"""    )
   return model






def  UpperCAmelCase__						(    lowerCamelCase	:			int			,lowerCamelCase	:			Dict			,lowerCamelCase	:			Union[str, Any]    ):
   lowerCamelCase									=copy.deepcopy(lowerCamelCase    )
   model.to(lowerCamelCase    )

   lowerCamelCase									=["""bias""", """LayerNorm.weight"""]
   lowerCamelCase									=[
       {
           """params""": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay    )],
           """weight_decay""": 0.0,
       },
       {"""params""": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay    )], """weight_decay""": 0.0},
   ]
   lowerCamelCase									=AdamW(lowerCamelCase			,lr=5E-5			,eps=1E-8    )
   lowerCamelCase									=get_linear_schedule_with_warmup(lowerCamelCase			,0			,lowerCamelCase    )
   torch.cuda.empty_cache()
   return model, lm_optimizer, lm_scheduler






def  UpperCAmelCase__						(    lowerCamelCase	:			int			,lowerCamelCase	:			Optional[int]			,lowerCamelCase	:			int			,lowerCamelCase	:			List[str]    ):
   lowerCamelCase									=np.array(lowerCamelCase    ).mean()
   lowerCamelCase									=np.array(lowerCamelCase    ).std()
   lowerCamelCase									=(real_perps - avg) / std
   lowerCamelCase									=list(zip(lowerCamelCase			,lowerCamelCase			,lowerCamelCase    )    )
   joblib.dump(lowerCamelCase			,lowerCamelCase    )






def  UpperCAmelCase__						(    lowerCamelCase	:			Optional[Any]			,lowerCamelCase	:			List[str]			,lowerCamelCase	:			Union[str, Any]			,lowerCamelCase	:			Optional[Any]			,lowerCamelCase	:			Optional[Any]			,lowerCamelCase	:			Any			,lowerCamelCase	:			int			,lowerCamelCase	:			Union[str, Any]="dev.jbl"			,lowerCamelCase	:			int=recopy_gpta			,):
   lowerCamelCase									=[]
   lowerCamelCase									=[]
   lowerCamelCase									=[]

   # Initialize the transformer model
   lowerCamelCase									=copy.deepcopy(lowerCamelCase    )
   orig_model.to(device="""cpu"""    )
   torch.cuda.empty_cache()

   # Compute perplexity of initial transformer model for comparison
   model.train()
   lowerCamelCase				,       lowerCamelCase				,       lowerCamelCase									=recopy_model(lowerCamelCase			,lowerCamelCase			,lowerCamelCase    )

   for step in tqdm(range(lowerCamelCase    )    ):
      lowerCamelCase									=torch.zeros((1, context_len)			,dtype=torch.long			,device=lowerCamelCase    )
      lowerCamelCase									=random.choice(lowerCamelCase    )
      lowerCamelCase									=random.randint(0			,len(story[0]    ) - context_len - 1    )
      lowerCamelCase									=story[0][start : start + context_len]
      lm_optimizer.zero_grad()
      lowerCamelCase									=model(lowerCamelCase			,labels=lowerCamelCase    )
      lowerCamelCase									=outputs[0]
      lowerCamelCase									=compute_perplexity(lowerCamelCase			,lowerCamelCase			,lowerCamelCase    )
      model.train()
      lm_loss.backward()
      # Do LM backprop
      torch.nn.utils.clip_grad_norm_(model.parameters()			,3.0    )
      lm_optimizer.step()
      lm_scheduler.step()  # Update learning rate schedule

      # Compute perplexity after back-propagating on the selected context
      lowerCamelCase									=compute_perplexity(lowerCamelCase			,lowerCamelCase			,lowerCamelCase    )

      # Periodically save the stored (X, IG(X)) pairs
      if step % 10_00 == 0 and step > 1:
         intermittent_save(lowerCamelCase			,lowerCamelCase			,lowerCamelCase			,lowerCamelCase    )

      # Reset the pretrained model to the original pretrained GPT-2 weights after each iteration
      lowerCamelCase				,       lowerCamelCase				,       lowerCamelCase									=recopy_model(lowerCamelCase			,lowerCamelCase			,lowerCamelCase    )

      past_perps.append(past_perp.item()    )
      real_perps.append(orig_perp - real_perp.item()    )
      contexts.append(np.array(context.cpu()    )    )

   intermittent_save(lowerCamelCase			,lowerCamelCase			,lowerCamelCase			,lowerCamelCase    )






def  UpperCAmelCase__						(    lowerCamelCase	:			List[str]			,lowerCamelCase	:			Dict="data/tokenized_stories_train_wikitext103.jbl"			,lowerCamelCase	:			str=1_00			,lowerCamelCase	:			Tuple=10_26			,lowerCamelCase	:			Tuple=True    ):
   lowerCamelCase									=joblib.load(lowerCamelCase    )
   print("""data loaded"""    )
   lowerCamelCase									=[]
   if trim:
      for i, example in enumerate(lowerCamelCase    ):
         if len(example[0]    ) > min_len:
            lowerCamelCase									=random.randint(0			,len(example[0]    ) - context_len - 1    )
            objective_set.append(example[0, start : start + context_len]    )
         if len(lowerCamelCase    ) >= number:
            break
      lowerCamelCase									=[]
      for j in range(i + 1			,len(lowerCamelCase    )    ):
         if len(data[j][0]    ) > min_len:
            train_data.append(data[j]    )
   else:
      lowerCamelCase									=data[0:number]
      lowerCamelCase									=data[number:]

   joblib.dump(lowerCamelCase			,"""objective_set.jbl"""    )
   print("""objective set saved"""    )
   return train_data, objective_set






def  UpperCAmelCase__						(    lowerCamelCase	:			List[str]			,lowerCamelCase	:			Union[str, Any]			,lowerCamelCase	:			Optional[Any]			,lowerCamelCase	:			List[Any]			,lowerCamelCase	:			List[str]=50			,lowerCamelCase	:			Tuple="secondary_learner.pt"    ):
   lowerCamelCase									=torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu"""    )
   # We will use the first 512 pairs from our dataset as a test set for
   # our secondary learner and the rest to train
   lowerCamelCase									=train_dataset[:5_12]
   lowerCamelCase									=train_dataset[5_12:]
   lowerCamelCase									=DataLoader(lowerCamelCase			,shuffle=lowerCamelCase			,batch_size=lowerCamelCase    )
   lowerCamelCase									=DataLoader(lowerCamelCase			,shuffle=lowerCamelCase			,batch_size=lowerCamelCase    )

   # secondary learner model set up
   lowerCamelCase									=nn.MSELoss()
   lowerCamelCase									=nn.MSELoss(reduction="""sum"""    )
   secondary_learner.to(lowerCamelCase    )
   lowerCamelCase									=torch.optim.Adam(secondary_learner.parameters()			,lr=0.00001    )
   secondary_learner.train()

   # TODO in original code this is written as number of actual batches seen
   # not number of items seen but other places it is number of items instead.
   # improve consistency! changed this to epochs for clarity
   lowerCamelCase									=float("""inf"""    )
   # Iterate through batches until we've used max_steps batches
   for epoch in range(int(lowerCamelCase    )    ):
      lowerCamelCase									=0.0
      secondary_learner.train()
      for step, batch in enumerate(lowerCamelCase    ):
         lowerCamelCase									=batch[0].to(lowerCamelCase    )
         lowerCamelCase									=batch[1].to(lowerCamelCase    )
         lowerCamelCase									=secondary_learner(lowerCamelCase    )
         q_optimizer.zero_grad()
         lowerCamelCase									=loss(lowerCamelCase			,real_q.float()    )
         q_loss.backward()
         q_optimizer.step()
         tr_q_loss += q_loss.item()

         # model trains fairly quickly so we won't wait for a full epoch
         # eval is triggered at eval_freq and end of epochs
         if (step % eval_freq == 0 and step > 0) or ((step + 1) == len(lowerCamelCase    )):
            lowerCamelCase									=tr_q_loss / (step + 1)

            secondary_learner.eval()
            lowerCamelCase									=0.0
            lowerCamelCase									=0.0
            lowerCamelCase									=[]
            lowerCamelCase									=[]
            # Compute performance of the secondary learner after this batch
            for stepa, batcha in enumerate(lowerCamelCase    ):
               lowerCamelCase									=batcha[0].to(lowerCamelCase    )
               lowerCamelCase									=batcha[1].to(lowerCamelCase    )
               lowerCamelCase									=secondary_learner(lowerCamelCase    )
               q_lossa += test_loss(lowerCamelCase			,lowerCamelCase    ).item()
               sum_qa += torch.sum(lowerCamelCase    ).item()
               for ei, i in enumerate(predicted_qa.cpu().detach().numpy()    ):
                  predicted.append(i.item()    )
               for ei, i in enumerate(real_qa.cpu().detach().numpy()    ):
                  actual.append(i.item()    )

            q_lossa /= len(lowerCamelCase    )
            print(
                """Epoch: """			,lowerCamelCase			,"""step: """			,lowerCamelCase			,"""Avg. q:"""			,sum_qa / len(lowerCamelCase    )			,"""Train Loss: """			,lowerCamelCase			,"""Test Loss: """			,lowerCamelCase			,)
            if q_lossa < best_test_loss:
               joblib.dump((predicted, actual)			,"""pred_vs_actual.jbl"""    )
               torch.save(secondary_learner.state_dict()			,lowerCamelCase    )
               lowerCamelCase									=q_lossa

         secondary_learner.train()
   return secondary_learner







class 		lowerCAmelCase_				(  nn.Module ):





     def __init__(	self							, _UpperCAmelCase  )		->				str:
        super(_UpperCAmelCase							, self  ).__init__()
        lowerCamelCase									=model.transformer.wte
        lowerCamelCase									=copy.deepcopy(model.transformer.wte.weight  )
        lowerCamelCase									=nn.Convad(self.embeddings.weight.size(1  )							, 256							, 3							, padding=1  )
        lowerCamelCase									=nn.Sequential(nn.Linear(256							, 32  )							, nn.Dropout(p=0.1  )							, nn.Linear(32							, 32  )							, nn.Linear(32							, 1  )  )





     def 						lowerCamelCase							(	self							, _UpperCAmelCase  )		->				Tuple:
        lowerCamelCase									=torch.max(self.conv(self.embeddings(_UpperCAmelCase  ).squeeze(1  ).transpose(1							, 2  )  )							, 2  )[0]
        lowerCamelCase									=self.fc(_UpperCAmelCase  )
        return qs.squeeze(1  )





     @classmethod
     def 						lowerCamelCase							(	cls							, _UpperCAmelCase							, _UpperCAmelCase  )		->				List[str]:
        lowerCamelCase									=cls(_UpperCAmelCase  )  # this calls __init__
        lowerCamelCase									=torch.load(_UpperCAmelCase  )
        secondary_learner.load_state_dict(_UpperCAmelCase  )
        lowerCamelCase									=model.transformer.wte
        lowerCamelCase									=copy.deepcopy(model.transformer.wte.weight  )
        return secondary_learner







import tempfile
import unittest

import transformers
from transformers import XGLMConfig, XGLMTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, require_sentencepiece, slow

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


if is_flax_available():
   import jax
   import jax.numpy as jnp
   import numpy as np

   from transformers.modeling_flax_pytorch_utils import (
       convert_pytorch_state_dict_to_flax,
       load_flax_weights_in_pytorch_model,
   )
   from transformers.models.xglm.modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel


if is_torch_available():
   import torch


@require_flax
class 		lowerCAmelCase_				:





     def __init__(	self							, _UpperCAmelCase							, _UpperCAmelCase=14							, _UpperCAmelCase=7							, _UpperCAmelCase=True							, _UpperCAmelCase=True							, _UpperCAmelCase=True							, _UpperCAmelCase=99							, _UpperCAmelCase=32							, _UpperCAmelCase=5							, _UpperCAmelCase=4							, _UpperCAmelCase=37							, _UpperCAmelCase="gelu"							, _UpperCAmelCase=0.1							, _UpperCAmelCase=0.1							, _UpperCAmelCase=512							, _UpperCAmelCase=0.02							, _UpperCAmelCase=None							, )		->				str:
        lowerCamelCase									=parent
        lowerCamelCase									=batch_size
        lowerCamelCase									=seq_length
        lowerCamelCase									=is_training
        lowerCamelCase									=use_input_mask
        lowerCamelCase									=use_labels
        lowerCamelCase									=vocab_size
        lowerCamelCase									=d_model
        lowerCamelCase									=num_hidden_layers
        lowerCamelCase									=num_attention_heads
        lowerCamelCase									=ffn_dim
        lowerCamelCase									=activation_function
        lowerCamelCase									=activation_dropout
        lowerCamelCase									=attention_dropout
        lowerCamelCase									=max_position_embeddings
        lowerCamelCase									=initializer_range
        lowerCamelCase									=None
        lowerCamelCase									=0
        lowerCamelCase									=2
        lowerCamelCase									=1





     def 						lowerCamelCase							(	self  )		->				List[str]:
        lowerCamelCase									=np.clip(ids_tensor([self.batch_size, self.seq_length]							, self.vocab_size  )							, 3							, self.vocab_size  )

        lowerCamelCase									=None
        if self.use_input_mask:
           lowerCamelCase									=random_attention_mask([self.batch_size, self.seq_length]  )

        lowerCamelCase									=XGLMConfig(
            vocab_size=self.vocab_size							, d_model=self.hidden_size							, num_layers=self.num_hidden_layers							, attention_heads=self.num_attention_heads							, ffn_dim=self.ffn_dim							, activation_function=self.activation_function							, activation_dropout=self.activation_dropout							, attention_dropout=self.attention_dropout							, max_position_embeddings=self.max_position_embeddings							, initializer_range=self.initializer_range							, use_cache=_UpperCAmelCase							, bos_token_id=self.bos_token_id							, eos_token_id=self.eos_token_id							, pad_token_id=self.pad_token_id							, )

        return (config, input_ids, input_mask)





     def 						lowerCamelCase							(	self  )		->				Tuple:
        lowerCamelCase									=self.prepare_config_and_inputs()
        lowerCamelCase				,       lowerCamelCase				,       lowerCamelCase									=config_and_inputs
        lowerCamelCase									={"""input_ids""": input_ids, """attention_mask""": attention_mask}
        return config, inputs_dict





     def 						lowerCamelCase							(	self  )		->				int:
        lowerCamelCase				,       lowerCamelCase				,       lowerCamelCase									=self.prepare_config_and_inputs()

        lowerCamelCase									=floats_tensor([self.batch_size, self.seq_length, self.hidden_size]  )
        lowerCamelCase									=ids_tensor([self.batch_size, self.seq_length]							, vocab_size=2  )

        return (
            config,
            input_ids,
            attention_mask,
            encoder_hidden_states,
            encoder_attention_mask,
        )





     def 						lowerCamelCase							(	self							, _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  )		->				Optional[Any]:
        lowerCamelCase									=20
        lowerCamelCase									=model_class_name(_UpperCAmelCase  )

        lowerCamelCase									=model.init_cache(input_ids.shape[0]							, _UpperCAmelCase  )
        lowerCamelCase									=jnp.ones((input_ids.shape[0], max_decoder_length)							, dtype="""i4"""  )

        lowerCamelCase									=jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1  )[None, :]							, (input_ids.shape[0], input_ids.shape[-1] - 1)  )
        lowerCamelCase									=model(
            input_ids[:, :-1]							, attention_mask=_UpperCAmelCase							, past_key_values=_UpperCAmelCase							, position_ids=_UpperCAmelCase							, )

        lowerCamelCase									=jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]							, dtype="""i4"""  )
        lowerCamelCase									=model(
            input_ids[:, -1:]							, attention_mask=_UpperCAmelCase							, past_key_values=outputs_cache.past_key_values							, position_ids=_UpperCAmelCase							, )

        lowerCamelCase									=model(_UpperCAmelCase  )

        lowerCamelCase									=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							, _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  )		->				List[Any]:
        lowerCamelCase									=20
        lowerCamelCase									=model_class_name(_UpperCAmelCase  )

        lowerCamelCase									=jnp.concatenate(
            [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])  )]							, axis=-1							, )

        lowerCamelCase									=model.init_cache(input_ids.shape[0]							, _UpperCAmelCase  )
        lowerCamelCase									=jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1  )[None, :]							, (input_ids.shape[0], input_ids.shape[-1] - 1)  )

        lowerCamelCase									=model(
            input_ids[:, :-1]							, attention_mask=_UpperCAmelCase							, past_key_values=_UpperCAmelCase							, position_ids=_UpperCAmelCase							, )
        lowerCamelCase									=jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]							, dtype="""i4"""  )
        lowerCamelCase									=model(
            input_ids[:, -1:]							, past_key_values=outputs_cache.past_key_values							, attention_mask=_UpperCAmelCase							, position_ids=_UpperCAmelCase							, )

        lowerCamelCase									=model(_UpperCAmelCase							, attention_mask=_UpperCAmelCase  )
        lowerCamelCase									=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_sentencepiece
@require_flax
class 		lowerCAmelCase_				(  UpperCamelCase				,     UpperCamelCase				,     unittest.TestCase ):
     __lowerCamelCase       :    Tuple 	=     (FlaxXGLMModel, FlaxXGLMForCausalLM) if is_flax_available() else ()
     __lowerCamelCase       :    Dict 	=     (FlaxXGLMForCausalLM,) if is_flax_available() else ()





     def 						lowerCamelCase							(	self  )		->				List[str]:
        lowerCamelCase									=FlaxXGLMModelTester(self  )





     def 						lowerCamelCase							(	self  )		->				List[str]:
        for model_class_name in self.all_model_classes:
           lowerCamelCase				,       lowerCamelCase				,       lowerCamelCase									=self.model_tester.prepare_config_and_inputs()
           self.model_tester.check_use_cache_forward(_UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  )





     def 						lowerCamelCase							(	self  )		->				Tuple:
        for model_class_name in self.all_model_classes:
           lowerCamelCase				,       lowerCamelCase				,       lowerCamelCase									=self.model_tester.prepare_config_and_inputs()
           self.model_tester.check_use_cache_forward_with_attn_mask(
               _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase  )





     @slow
     def 						lowerCamelCase							(	self  )		->				Tuple:
        lowerCamelCase									=XGLMTokenizer.from_pretrained("""XGLM"""							, padding_side="""left"""  )
        lowerCamelCase									=tokenizer(["""Hello this is a long string""", """Hey"""]							, return_tensors="""np"""							, padding=_UpperCAmelCase							, truncation=_UpperCAmelCase  )

        lowerCamelCase									=FlaxXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""  )
        lowerCamelCase									=1
        lowerCamelCase									=False

        lowerCamelCase									=jax.jit(model.generate  )

        lowerCamelCase									=jit_generate(inputs["""input_ids"""]							, attention_mask=inputs["""attention_mask"""]  ).sequences

        lowerCamelCase									=tokenizer.batch_decode(_UpperCAmelCase							, skip_special_tokens=_UpperCAmelCase  )

        lowerCamelCase									=[
            """Hello this is a long string of questions, but I'm not sure if I'm""",
            """Hey, I'm a newbie to the forum and I'""",
        ]

        self.assertListEqual(_UpperCAmelCase							, _UpperCAmelCase  )





     @is_pt_flax_cross_test
     def 						lowerCamelCase							(	self  )		->				Dict:
        lowerCamelCase				,       lowerCamelCase									=self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__  ):
              # prepare inputs
              lowerCamelCase									=self._prepare_for_class(_UpperCAmelCase							, _UpperCAmelCase  )
              lowerCamelCase									={k: torch.tensor(v.tolist()  ) for k, v in prepared_inputs_dict.items()}

              # load corresponding PyTorch class
              lowerCamelCase									=model_class.__name__[4:]  # Skip the "Flax" at the beginning
              lowerCamelCase									=getattr(_UpperCAmelCase							, _UpperCAmelCase  )

              lowerCamelCase				,       lowerCamelCase									=pt_inputs["""input_ids"""].shape
              lowerCamelCase									=np.random.randint(0							, seq_length - 1							, size=(batch_size,)  )
              for batch_idx, start_index in enumerate(_UpperCAmelCase  ):
                 lowerCamelCase									=0
                 lowerCamelCase									=1
                 lowerCamelCase									=0
                 lowerCamelCase									=1
              lowerCamelCase									=pt_model_class(_UpperCAmelCase  ).eval()
              # Flax models don't use the `use_cache` option and cache is not returned as a default.
              # So we disable `use_cache` here for PyTorch model.
              lowerCamelCase									=False
              lowerCamelCase									=model_class(_UpperCAmelCase							, dtype=jnp.floataa  )
              lowerCamelCase									=convert_pytorch_state_dict_to_flax(pt_model.state_dict()							, _UpperCAmelCase  )
              lowerCamelCase									=fx_state

              with torch.no_grad():
                 lowerCamelCase									=pt_model(**_UpperCAmelCase  ).to_tuple()

              lowerCamelCase									=fx_model(**_UpperCAmelCase  ).to_tuple()
              self.assertEqual(len(_UpperCAmelCase  )							, len(_UpperCAmelCase  )							, """Output lengths differ between Flax and PyTorch"""  )
              for fx_output, pt_output in zip(_UpperCAmelCase							, _UpperCAmelCase  ):
                 self.assert_almost_equals(fx_output[:, -1]							, pt_output[:, -1].numpy()							, 4E-2  )

              with tempfile.TemporaryDirectory() as tmpdirname:
                 pt_model.save_pretrained(_UpperCAmelCase  )
                 lowerCamelCase									=model_class.from_pretrained(_UpperCAmelCase							, from_pt=_UpperCAmelCase  )

              lowerCamelCase									=fx_model_loaded(**_UpperCAmelCase  ).to_tuple()
              self.assertEqual(
                  len(_UpperCAmelCase  )							, len(_UpperCAmelCase  )							, """Output lengths differ between Flax and PyTorch"""  )
              for fx_output_loaded, pt_output in zip(_UpperCAmelCase							, _UpperCAmelCase  ):
                 self.assert_almost_equals(fx_output_loaded[:, -1]							, pt_output[:, -1].numpy()							, 4E-2  )





     @is_pt_flax_cross_test
     def 						lowerCamelCase							(	self  )		->				Optional[Any]:
        lowerCamelCase				,       lowerCamelCase									=self.model_tester.prepare_config_and_inputs_for_common()
        for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__  ):
              # prepare inputs
              lowerCamelCase									=self._prepare_for_class(_UpperCAmelCase							, _UpperCAmelCase  )
              lowerCamelCase									={k: torch.tensor(v.tolist()  ) for k, v in prepared_inputs_dict.items()}

              # load corresponding PyTorch class
              lowerCamelCase									=model_class.__name__[4:]  # Skip the "Flax" at the beginning
              lowerCamelCase									=getattr(_UpperCAmelCase							, _UpperCAmelCase  )

              lowerCamelCase									=pt_model_class(_UpperCAmelCase  ).eval()
              lowerCamelCase									=False
              lowerCamelCase									=model_class(_UpperCAmelCase							, dtype=jnp.floataa  )

              lowerCamelCase									=load_flax_weights_in_pytorch_model(_UpperCAmelCase							, fx_model.params  )
              lowerCamelCase				,       lowerCamelCase									=pt_inputs["""input_ids"""].shape
              lowerCamelCase									=np.random.randint(0							, seq_length - 1							, size=(batch_size,)  )
              for batch_idx, start_index in enumerate(_UpperCAmelCase  ):
                 lowerCamelCase									=0
                 lowerCamelCase									=1
                 lowerCamelCase									=0
                 lowerCamelCase									=1

              # make sure weights are tied in PyTorch
              pt_model.tie_weights()

              with torch.no_grad():
                 lowerCamelCase									=pt_model(**_UpperCAmelCase  ).to_tuple()

              lowerCamelCase									=fx_model(**_UpperCAmelCase  ).to_tuple()
              self.assertEqual(len(_UpperCAmelCase  )							, len(_UpperCAmelCase  )							, """Output lengths differ between Flax and PyTorch"""  )
              for fx_output, pt_output in zip(_UpperCAmelCase							, _UpperCAmelCase  ):
                 self.assert_almost_equals(fx_output[:, -1]							, pt_output[:, -1].numpy()							, 4E-2  )

              with tempfile.TemporaryDirectory() as tmpdirname:
                 fx_model.save_pretrained(_UpperCAmelCase  )
                 lowerCamelCase									=pt_model_class.from_pretrained(_UpperCAmelCase							, from_flax=_UpperCAmelCase  )

              with torch.no_grad():
                 lowerCamelCase									=pt_model_loaded(**_UpperCAmelCase  ).to_tuple()

              self.assertEqual(
                  len(_UpperCAmelCase  )							, len(_UpperCAmelCase  )							, """Output lengths differ between Flax and PyTorch"""  )
              for fx_output, pt_output in zip(_UpperCAmelCase							, _UpperCAmelCase  ):
                 self.assert_almost_equals(fx_output[:, -1]							, pt_output[:, -1].numpy()							, 4E-2  )





     @slow
     def 						lowerCamelCase							(	self  )		->				int:
        for model_class_name in self.all_model_classes:
           lowerCamelCase									=model_class_name.from_pretrained("""facebook/xglm-564M"""  )
           lowerCamelCase									=model(np.ones((1, 1)  )  )
           self.assertIsNotNone(_UpperCAmelCase  )