



import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable

import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm

from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule



class 			__lowerCAmelCase  (						lowerCAmelCase__ ):
 lowerCAmelCase__							       =	42
 lowerCAmelCase__							       =	jnp.floataa
 lowerCAmelCase__							       =	True




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    super().setup()
    __lowerCamelCase    				=     nn.Dense(5						,					dtype=self.dtype					)




 def __call__(    self						,					*__UpperCAmelCase						,					**__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     super().__call__(*__UpperCAmelCase						,					**__UpperCAmelCase					)
    __lowerCamelCase    				=     self.cls(outputs[2]					)
    return outputs[:2] + (cls_out,)



class 			__lowerCAmelCase  (						lowerCAmelCase__ ):
 lowerCAmelCase__							       =	FlaxBigBirdForNaturalQuestionsModule





def 		a__      (		_UpperCamelCase      :			List[Any]			,_UpperCamelCase      :			Any			,_UpperCamelCase      :			Union[str, Any]			,_UpperCamelCase      :			Tuple			,_UpperCamelCase      :			Optional[int]			,_UpperCamelCase      :			List[str]				):
   def cross_entropy(_UpperCamelCase      :			Optional[Any]			,_UpperCamelCase      :			str			,_UpperCamelCase      :			Optional[Any]=None				):
      __lowerCamelCase    				=     logits.shape[-1]
      __lowerCamelCase    				=     (labels[..., None] == jnp.arange(_UpperCamelCase				)[None]).astype('''f4'''				)
      __lowerCamelCase    				=     jax.nn.log_softmax(_UpperCamelCase			,axis=-1				)
      __lowerCamelCase    				=     -jnp.sum(labels * logits			,axis=-1				)
      if reduction is not None:
         __lowerCamelCase    				=     reduction(_UpperCamelCase				)
      return loss

   __lowerCamelCase    				=     partial(_UpperCamelCase			,reduction=jnp.mean				)
   __lowerCamelCase    				=     cross_entropy(_UpperCamelCase			,_UpperCamelCase				)
   __lowerCamelCase    				=     cross_entropy(_UpperCamelCase			,_UpperCamelCase				)
   __lowerCamelCase    				=     cross_entropy(_UpperCamelCase			,_UpperCamelCase				)
   return (start_loss + end_loss + pooled_loss) / 3



@dataclass
class 			__lowerCAmelCase  :
 lowerCAmelCase__							       =	"google/bigbird-roberta-base"
 lowerCAmelCase__							       =	3_0_0_0
 lowerCAmelCase__							       =	1_0_5_0_0

 lowerCAmelCase__							       =	1_2_8
 lowerCAmelCase__							       =	3

 lowerCAmelCase__							       =	1
 lowerCAmelCase__							       =	5

 # tx_args
 lowerCAmelCase__							       =	3e-5
 lowerCAmelCase__							       =	0.0
 lowerCAmelCase__							       =	2_0_0_0_0
 lowerCAmelCase__							       =	0.00_95

 lowerCAmelCase__							       =	"bigbird-roberta-natural-questions"
 lowerCAmelCase__							       =	"training-expt"
 lowerCAmelCase__							       =	"data/nq-training.jsonl"
 lowerCAmelCase__							       =	"data/nq-validation.jsonl"




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    os.makedirs(self.base_dir						,					exist_ok=__UpperCAmelCase					)
    __lowerCamelCase    				=     os.path.join(self.base_dir						,					self.save_dir					)
    __lowerCamelCase    				=     self.batch_size_per_device * jax.device_count()



@dataclass
class 			__lowerCAmelCase  :
 lowerCAmelCase__							       =	42
 lowerCAmelCase__							       =	4_0_9_6  # no dynamic padding on TPUs




 def __call__(    self						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.collate_fn(__UpperCAmelCase					)
    __lowerCamelCase    				=     jax.tree_util.tree_map(__UpperCAmelCase						,					__UpperCAmelCase					)
    return batch




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.fetch_inputs(features['''input_ids''']					)
    __lowerCamelCase    				=     {
        '''input_ids''': jnp.array(__UpperCAmelCase						,					dtype=jnp.intaa					),
        '''attention_mask''': jnp.array(__UpperCAmelCase						,					dtype=jnp.intaa					),
        '''start_labels''': jnp.array(features['''start_token''']						,					dtype=jnp.intaa					),
        '''end_labels''': jnp.array(features['''end_token''']						,					dtype=jnp.intaa					),
        '''pooled_labels''': jnp.array(features['''category''']						,					dtype=jnp.intaa					),
    }
    return batch




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     [self._fetch_inputs(__UpperCAmelCase					) for ids in input_ids]
    return zip(*__UpperCAmelCase					)




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     [1 for _ in range(len(__UpperCAmelCase					)					)]
    while len(__UpperCAmelCase					) < self.max_length:
       input_ids.append(self.pad_id					)
       attention_mask.append(0					)
    return input_ids, attention_mask





def 		a__      (		_UpperCamelCase      :			Any			,_UpperCamelCase      :			str			,_UpperCamelCase      :			Optional[int]=None				):
   if seed is not None:
      __lowerCamelCase    				=     dataset.shuffle(seed=_UpperCamelCase				)
   for i in range(len(_UpperCamelCase				) // batch_size				):
      __lowerCamelCase    				=     dataset[i * batch_size : (i + 1) * batch_size]
      yield dict(_UpperCamelCase				)





@partial(jax.pmap			,axis_name='''batch'''				)
def 		a__      (		_UpperCamelCase      :			Dict			,_UpperCamelCase      :			int			,**_UpperCamelCase      :			Dict				):
   def loss_fn(_UpperCamelCase      :			List[Any]				):
      __lowerCamelCase    				=     model_inputs.pop('''start_labels'''				)
      __lowerCamelCase    				=     model_inputs.pop('''end_labels'''				)
      __lowerCamelCase    				=     model_inputs.pop('''pooled_labels'''				)

      __lowerCamelCase    				=     state.apply_fn(**_UpperCamelCase			,params=_UpperCamelCase			,dropout_rng=_UpperCamelCase			,train=_UpperCamelCase				)
      __lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase    				=     outputs

      return state.loss_fn(
          _UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase			,)

   __lowerCamelCase				,__lowerCamelCase    				=     jax.random.split(_UpperCamelCase				)
   __lowerCamelCase    				=     jax.value_and_grad(_UpperCamelCase				)
   __lowerCamelCase				,__lowerCamelCase    				=     grad_fn(state.params				)
   __lowerCamelCase    				=     jax.lax.pmean({'''loss''': loss}			,axis_name='''batch'''				)
   __lowerCamelCase    				=     jax.lax.pmean(_UpperCamelCase			,'''batch'''				)

   __lowerCamelCase    				=     state.apply_gradients(grads=_UpperCamelCase				)
   return state, metrics, new_drp_rng





@partial(jax.pmap			,axis_name='''batch'''				)
def 		a__      (		_UpperCamelCase      :			Tuple			,**_UpperCamelCase      :			Optional[Any]				):
   __lowerCamelCase    				=     model_inputs.pop('''start_labels'''				)
   __lowerCamelCase    				=     model_inputs.pop('''end_labels'''				)
   __lowerCamelCase    				=     model_inputs.pop('''pooled_labels'''				)

   __lowerCamelCase    				=     state.apply_fn(**_UpperCamelCase			,params=state.params			,train=_UpperCamelCase				)
   __lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase    				=     outputs

   __lowerCamelCase    				=     state.loss_fn(_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase				)
   __lowerCamelCase    				=     jax.lax.pmean({'''loss''': loss}			,axis_name='''batch'''				)
   return metrics



class 			__lowerCAmelCase  (						train_state.TrainState ):
 lowerCAmelCase__							       =	struct.field(pytree_node=lowerCAmelCase__ )



@dataclass
class 			__lowerCAmelCase  :
 lowerCAmelCase__							       =	42
 lowerCAmelCase__							       =	42
 lowerCAmelCase__							       =	42
 lowerCAmelCase__							       =	42
 lowerCAmelCase__							       =	42
 lowerCAmelCase__							       =	42
 lowerCAmelCase__							       =	None




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase=None					):



    '''simple docstring'''
    __lowerCamelCase    				=     model.params
    __lowerCamelCase    				=     TrainState.create(
        apply_fn=model.__call__						,					params=__UpperCAmelCase						,					tx=__UpperCAmelCase						,					loss_fn=__UpperCAmelCase						,					)
    if ckpt_dir is not None:
       __lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase    				=     restore_checkpoint(__UpperCAmelCase						,					__UpperCAmelCase					)
       __lowerCamelCase    				=     {
           '''lr''': args.lr,
           '''init_lr''': args.init_lr,
           '''warmup_steps''': args.warmup_steps,
           '''num_train_steps''': num_train_steps,
           '''weight_decay''': args.weight_decay,
       }
       __lowerCamelCase				,__lowerCamelCase    				=     build_tx(**__UpperCAmelCase					)
       __lowerCamelCase    				=     train_state.TrainState(
           step=__UpperCAmelCase						,					apply_fn=model.__call__						,					params=__UpperCAmelCase						,					tx=__UpperCAmelCase						,					opt_state=__UpperCAmelCase						,					)
       __lowerCamelCase    				=     args
       __lowerCamelCase    				=     data_collator
       __lowerCamelCase    				=     lr
       __lowerCamelCase    				=     params
    __lowerCamelCase    				=     jax_utils.replicate(__UpperCAmelCase					)
    return state




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.args
    __lowerCamelCase    				=     len(__UpperCAmelCase					) // args.batch_size

    __lowerCamelCase    				=     jax.random.PRNGKey(0					)
    __lowerCamelCase    				=     jax.random.split(__UpperCAmelCase						,					jax.device_count()					)
    for epoch in range(args.max_epochs					):
       __lowerCamelCase    				=     jnp.array(0						,					dtype=jnp.floataa					)
       __lowerCamelCase    				=     get_batched_dataset(__UpperCAmelCase						,					args.batch_size						,					seed=__UpperCAmelCase					)
       __lowerCamelCase    				=     0
       for batch in tqdm(__UpperCAmelCase						,					total=__UpperCAmelCase						,					desc=F"""Running EPOCH-{epoch}"""					):
          __lowerCamelCase    				=     self.data_collator(__UpperCAmelCase					)
          __lowerCamelCase				,__lowerCamelCase				,__lowerCamelCase    				=     self.train_step_fn(__UpperCAmelCase						,					__UpperCAmelCase						,					**__UpperCAmelCase					)
          running_loss += jax_utils.unreplicate(metrics['''loss''']					)
          i += 1
          if i % args.logging_steps == 0:
             __lowerCamelCase    				=     jax_utils.unreplicate(state.step					)
             __lowerCamelCase    				=     running_loss.item() / i
             __lowerCamelCase    				=     self.scheduler_fn(state_step - 1					)

             __lowerCamelCase    				=     self.evaluate(__UpperCAmelCase						,					__UpperCAmelCase					)
             __lowerCamelCase    				=     {
                 '''step''': state_step.item(),
                 '''eval_loss''': eval_loss.item(),
                 '''tr_loss''': tr_loss,
                 '''lr''': lr.item(),
             }
             tqdm.write(str(__UpperCAmelCase					)					)
             self.logger.log(__UpperCAmelCase						,					commit=__UpperCAmelCase					)

          if i % args.save_steps == 0:
             self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}"""						,					state=__UpperCAmelCase					)




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     get_batched_dataset(__UpperCAmelCase						,					self.args.batch_size					)
    __lowerCamelCase    				=     len(__UpperCAmelCase					) // self.args.batch_size
    __lowerCamelCase    				=     jnp.array(0						,					dtype=jnp.floataa					)
    __lowerCamelCase    				=     0
    for batch in tqdm(__UpperCAmelCase						,					total=__UpperCAmelCase						,					desc='''Evaluating ... '''					):
       __lowerCamelCase    				=     self.data_collator(__UpperCAmelCase					)
       __lowerCamelCase    				=     self.val_step_fn(__UpperCAmelCase						,					**__UpperCAmelCase					)
       running_loss += jax_utils.unreplicate(metrics['''loss''']					)
       i += 1
    return running_loss / i




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     jax_utils.unreplicate(__UpperCAmelCase					)
    print(F"""SAVING CHECKPOINT IN {save_dir}"""						,					end=''' ... '''					)
    self.model_save_fn(__UpperCAmelCase						,					params=state.params					)
    with open(os.path.join(__UpperCAmelCase						,					'''opt_state.msgpack'''					)						,					'''wb'''					) as f:
       f.write(to_bytes(state.opt_state					)					)
    joblib.dump(self.args						,					os.path.join(__UpperCAmelCase						,					'''args.joblib'''					)					)
    joblib.dump(self.data_collator						,					os.path.join(__UpperCAmelCase						,					'''data_collator.joblib'''					)					)
    with open(os.path.join(__UpperCAmelCase						,					'''training_state.json'''					)						,					'''w'''					) as f:
       json.dump({'''step''': state.step.item()}						,					__UpperCAmelCase					)
    print('''DONE'''					)





def 		a__      (		_UpperCamelCase      :			Union[str, Any]			,_UpperCamelCase      :			int				):
   print(F"""RESTORING CHECKPOINT FROM {save_dir}"""			,end=''' ... '''				)
   with open(os.path.join(_UpperCamelCase			,'''flax_model.msgpack'''				)			,'''rb'''				) as f:
      __lowerCamelCase    				=     from_bytes(state.params			,f.read()				)

   with open(os.path.join(_UpperCamelCase			,'''opt_state.msgpack'''				)			,'''rb'''				) as f:
      __lowerCamelCase    				=     from_bytes(state.opt_state			,f.read()				)

   __lowerCamelCase    				=     joblib.load(os.path.join(_UpperCamelCase			,'''args.joblib'''				)				)
   __lowerCamelCase    				=     joblib.load(os.path.join(_UpperCamelCase			,'''data_collator.joblib'''				)				)

   with open(os.path.join(_UpperCamelCase			,'''training_state.json'''				)			,'''r'''				) as f:
      __lowerCamelCase    				=     json.load(_UpperCamelCase				)
   __lowerCamelCase    				=     training_state['''step''']

   print('''DONE'''				)
   return params, opt_state, step, args, data_collator





def 		a__      (		_UpperCamelCase      :			List[str]			,_UpperCamelCase      :			Optional[Any]			,_UpperCamelCase      :			List[Any]			,_UpperCamelCase      :			int				):
   __lowerCamelCase    				=     num_train_steps - warmup_steps
   __lowerCamelCase    				=     optax.linear_schedule(init_value=_UpperCamelCase			,end_value=_UpperCamelCase			,transition_steps=_UpperCamelCase				)
   __lowerCamelCase    				=     optax.linear_schedule(init_value=_UpperCamelCase			,end_value=1e-7			,transition_steps=_UpperCamelCase				)
   __lowerCamelCase    				=     optax.join_schedules(schedules=[warmup_fn, decay_fn]			,boundaries=[warmup_steps]				)
   return lr





def 		a__      (		_UpperCamelCase      :			Tuple			,_UpperCamelCase      :			List[Any]			,_UpperCamelCase      :			Optional[int]			,_UpperCamelCase      :			Dict			,_UpperCamelCase      :			Optional[Any]				):
   def weight_decay_mask(_UpperCamelCase      :			Optional[Any]				):
      __lowerCamelCase    				=     traverse_util.flatten_dict(_UpperCamelCase				)
      __lowerCamelCase    				=     {k: (v[-1] != '''bias''' and v[-2:] != ('''LayerNorm''', '''scale''')) for k, v in params.items()}
      return traverse_util.unflatten_dict(_UpperCamelCase				)

   __lowerCamelCase    				=     scheduler_fn(_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase			,_UpperCamelCase				)

   __lowerCamelCase    				=     optax.adamw(learning_rate=_UpperCamelCase			,weight_decay=_UpperCamelCase			,mask=_UpperCamelCase				)
   return tx, lr











import json
import os
import unittest

from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer
from transformers.testing_utils import slow

from ...test_tokenization_common import TokenizerTesterMixin



class 			__lowerCAmelCase  (						lowerCAmelCase__	,						unittest.TestCase ):
 lowerCAmelCase__							       =	XLMTokenizer
 lowerCAmelCase__							       =	False




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    super().setUp()

    # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
    __lowerCamelCase    				=     [
        '''l''',
        '''o''',
        '''w''',
        '''e''',
        '''r''',
        '''s''',
        '''t''',
        '''i''',
        '''d''',
        '''n''',
        '''w</w>''',
        '''r</w>''',
        '''t</w>''',
        '''lo''',
        '''low''',
        '''er</w>''',
        '''low</w>''',
        '''lowest</w>''',
        '''newer</w>''',
        '''wider</w>''',
        '''<unk>''',
    ]
    __lowerCamelCase    				=     dict(zip(__UpperCAmelCase						,					range(len(__UpperCAmelCase					)					)					)					)
    __lowerCamelCase    				=     ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', '''''']

    __lowerCamelCase    				=     os.path.join(self.tmpdirname						,					VOCAB_FILES_NAMES['''vocab_file''']					)
    __lowerCamelCase    				=     os.path.join(self.tmpdirname						,					VOCAB_FILES_NAMES['''merges_file''']					)
    with open(self.vocab_file						,					'''w'''					) as fp:
       fp.write(json.dumps(__UpperCAmelCase					)					)
    with open(self.merges_file						,					'''w'''					) as fp:
       fp.write('''\n'''.join(__UpperCAmelCase					)					)




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     '''lower newer'''
    __lowerCamelCase    				=     '''lower newer'''
    return input_text, output_text




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     XLMTokenizer(self.vocab_file						,					self.merges_file					)

    __lowerCamelCase    				=     '''lower'''
    __lowerCamelCase    				=     ['''low''', '''er</w>''']
    __lowerCamelCase    				=     tokenizer.tokenize(__UpperCAmelCase					)
    self.assertListEqual(__UpperCAmelCase						,					__UpperCAmelCase					)

    __lowerCamelCase    				=     tokens + ['''<unk>''']
    __lowerCamelCase    				=     [14, 15, 20]
    self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase					)						,					__UpperCAmelCase					)




 @slow
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     XLMTokenizer.from_pretrained('''xlm-mlm-en-2048'''					)

    __lowerCamelCase    				=     tokenizer.encode('''sequence builders'''						,					add_special_tokens=__UpperCAmelCase					)
    __lowerCamelCase    				=     tokenizer.encode('''multi-sequence build'''						,					add_special_tokens=__UpperCAmelCase					)

    __lowerCamelCase    				=     tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase					)
    __lowerCamelCase    				=     tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase						,					__UpperCAmelCase					)

    assert encoded_sentence == [0] + text + [1]
    assert encoded_pair == [0] + text + [1] + text_a + [1]






