





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 			A__   (							_UpperCamelCase     ):




   """simple docstring"""



   __A       :    BigBirdConfig
   __A       :    jnp.dtype	  =  jnp.floataa
   __A       :    bool	  =  True

   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          super().setup()
          a__						:     Optional[int]			=    nn.Dense(5 ,  dtype=self.dtype)

   def __call__( self ,  *lowercase ,  **lowercase)      ->						Any:







          '''simple docstring'''

          a__						:     List[Any]			=    super().__call__(*_SCREAMING_SNAKE_CASE ,  **_SCREAMING_SNAKE_CASE)
          a__						:     str			=    self.cls(outputs[2])
          return outputs[:2] + (cls_out,)







class 			A__   (							_UpperCamelCase     ):




   """simple docstring"""



   __A       :    List[Any]	  =  FlaxBigBirdForNaturalQuestionsModule







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

       a__						:     Optional[int]			=    partial(_UpperCamelCase		,				reduction=jnp.mean    )
       a__						:     Dict			=    cross_entropy(_UpperCamelCase		,				_UpperCamelCase    )
       a__						:     int			=    cross_entropy(_UpperCamelCase		,				_UpperCamelCase    )
       a__						:     str			=    cross_entropy(_UpperCamelCase		,				_UpperCamelCase    )
       return (start_loss + end_loss + pooled_loss) / 3





@dataclass
class 			A__   :




   """simple docstring"""



   __A       :    str	  =  "google/bigbird-roberta-base"
   __A       :    int	  =  3_0_0_0
   __A       :    int	  =  1_0_5_0_0

   __A       :    int	  =  1_2_8
   __A       :    int	  =  3

   __A       :    int	  =  1
   __A       :    int	  =  5

   # tx_args
   __A       :    float	  =  3E-5
   __A       :    float	  =  0.0
   __A       :    int	  =  2_0_0_0_0
   __A       :    float	  =  0.0095

   __A       :    str	  =  "bigbird-roberta-natural-questions"
   __A       :    str	  =  "training-expt"
   __A       :    str	  =  "data/nq-training.jsonl"
   __A       :    str	  =  "data/nq-validation.jsonl"

   def 							__lowercase		( self)      ->						Optional[int]:







          '''simple docstring'''

          os.makedirs(self.base_dir ,  exist_ok=_SCREAMING_SNAKE_CASE)
          a__						:     Optional[int]			=    os.path.join(self.base_dir ,  self.save_dir)
          a__						:     List[str]			=    self.batch_size_per_device * jax.device_count()







@dataclass
class 			A__   :




   """simple docstring"""



   __A       :    int
   __A       :    int	  =  4_0_9_6  # no dynamic padding on TPUs

   def __call__( self ,  lowercase)      ->						Dict:







          '''simple docstring'''

          a__						:     int			=    self.collate_fn(_SCREAMING_SNAKE_CASE)
          a__						:     Union[str, Any]			=    jax.tree_util.tree_map(_SCREAMING_SNAKE_CASE ,  _SCREAMING_SNAKE_CASE)
          return batch

   def 							__lowercase		( self ,  lowercase)      ->						Any:







          '''simple docstring'''

          a__			,							a__						:     Optional[int]			=    self.fetch_inputs(features['input_ids'])
          a__						:     Optional[Any]			=    {
              'input_ids': jnp.array(_SCREAMING_SNAKE_CASE ,  dtype=jnp.intaa),
              'attention_mask': jnp.array(_SCREAMING_SNAKE_CASE ,  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 							__lowercase		( self ,  lowercase)      ->						Dict:







          '''simple docstring'''

          a__						:     Union[str, Any]			=    [self._fetch_inputs(_SCREAMING_SNAKE_CASE) for ids in input_ids]
          return zip(*_SCREAMING_SNAKE_CASE)

   def 							__lowercase		( self ,  lowercase)      ->						str:







          '''simple docstring'''

          a__						:     List[str]			=    [1 for _ in range(len(_SCREAMING_SNAKE_CASE))]
          while len(_SCREAMING_SNAKE_CASE) < self.max_length:
                 input_ids.append(self.pad_id)
                 attention_mask.append(0)
          return input_ids, attention_mask







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



@partial(jax.pmap		,				axis_name='batch'    )
def A_     (		A__		,				A__		,				**A__    )  ->		Optional[int]:
       def loss_fn(A__    ):
              a__						:     int			=    model_inputs.pop('start_labels'    )
              a__						:     int			=    model_inputs.pop('end_labels'    )
              a__						:     Tuple			=    model_inputs.pop('pooled_labels'    )

              a__						:     Dict			=    state.apply_fn(**_UpperCamelCase		,				params=_UpperCamelCase		,				dropout_rng=_UpperCamelCase		,				train=_UpperCamelCase    )
              a__			,							a__			,							a__						:     int			=    outputs

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

       a__			,							a__						:     Optional[int]			=    jax.random.split(_UpperCamelCase    )
       a__						:     List[str]			=    jax.value_and_grad(_UpperCamelCase    )
       a__			,							a__						:     int			=    grad_fn(state.params    )
       a__						:     str			=    jax.lax.pmean({'loss': loss}		,				axis_name='batch'    )
       a__						:     str			=    jax.lax.pmean(_UpperCamelCase		,				'batch'    )

       a__						:     Tuple			=    state.apply_gradients(grads=_UpperCamelCase    )
       return state, metrics, new_drp_rng



@partial(jax.pmap		,				axis_name='batch'    )
def A_     (		A__		,				**A__    )  ->		Union[str, Any]:
       a__						:     List[Any]			=    model_inputs.pop('start_labels'    )
       a__						:     Optional[Any]			=    model_inputs.pop('end_labels'    )
       a__						:     Union[str, Any]			=    model_inputs.pop('pooled_labels'    )

       a__						:     List[str]			=    state.apply_fn(**_UpperCamelCase		,				params=state.params		,				train=_UpperCamelCase    )
       a__			,							a__			,							a__						:     Dict			=    outputs

       a__						:     Optional[int]			=    state.loss_fn(_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase    )
       a__						:     Optional[Any]			=    jax.lax.pmean({'loss': loss}		,				axis_name='batch'    )
       return metrics





class 			A__   (							train_state.TrainState     ):




   """simple docstring"""



   __A       :    Callable	  =  struct.field(pytree_node=_UpperCamelCase     )







@dataclass
class 			A__   :




   """simple docstring"""



   __A       :    Args
   __A       :    Callable
   __A       :    Callable
   __A       :    Callable
   __A       :    Callable
   __A       :    wandb
   __A       :    Callable	  =  None

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     int			=    model.params
          a__						:     Tuple			=    TrainState.create(
              apply_fn=model.__call__ ,  params=_SCREAMING_SNAKE_CASE ,  tx=_SCREAMING_SNAKE_CASE ,  loss_fn=_SCREAMING_SNAKE_CASE ,  )
          if ckpt_dir is not None:
                 a__			,							a__			,							a__			,							a__			,							a__						:     List[str]			=    restore_checkpoint(_SCREAMING_SNAKE_CASE ,  _SCREAMING_SNAKE_CASE)
                 a__						:     Tuple			=    {
                     'lr': args.lr,
                     'init_lr': args.init_lr,
                     'warmup_steps': args.warmup_steps,
                     'num_train_steps': num_train_steps,
                     'weight_decay': args.weight_decay,
                 }
                 a__			,							a__						:     int			=    build_tx(**_SCREAMING_SNAKE_CASE)
                 a__						:     Any			=    train_state.TrainState(
                     step=_SCREAMING_SNAKE_CASE ,  apply_fn=model.__call__ ,  params=_SCREAMING_SNAKE_CASE ,  tx=_SCREAMING_SNAKE_CASE ,  opt_state=_SCREAMING_SNAKE_CASE ,  )
                 a__						:     List[Any]			=    args
                 a__						:     Optional[int]			=    data_collator
                 a__						:     List[Any]			=    lr
                 a__						:     Any			=    params
          a__						:     Union[str, Any]			=    jax_utils.replicate(_SCREAMING_SNAKE_CASE)
          return state

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						Dict:







          '''simple docstring'''

          a__						:     Tuple			=    self.args
          a__						:     str			=    len(_SCREAMING_SNAKE_CASE) // args.batch_size

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

                               a__						:     List[Any]			=    self.evaluate(_SCREAMING_SNAKE_CASE ,  _SCREAMING_SNAKE_CASE)
                               a__						:     Union[str, Any]			=    {
                                   'step': state_step.item(),
                                   'eval_loss': eval_loss.item(),
                                   'tr_loss': tr_loss,
                                   'lr': lr.item(),
                               }
                               tqdm.write(str(_SCREAMING_SNAKE_CASE))
                               self.logger.log(_SCREAMING_SNAKE_CASE ,  commit=_SCREAMING_SNAKE_CASE)

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

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     List[str]			=    get_batched_dataset(_SCREAMING_SNAKE_CASE ,  self.args.batch_size)
          a__						:     Optional[int]			=    len(_SCREAMING_SNAKE_CASE) // self.args.batch_size
          a__						:     str			=    jnp.array(0 ,  dtype=jnp.floataa)
          a__						:     Tuple			=    0
          for batch in tqdm(_SCREAMING_SNAKE_CASE ,  total=_SCREAMING_SNAKE_CASE ,  desc='Evaluating ... '):
                 a__						:     str			=    self.data_collator(_SCREAMING_SNAKE_CASE)
                 a__						:     int			=    self.val_step_fn(_SCREAMING_SNAKE_CASE ,  **_SCREAMING_SNAKE_CASE)
                 running_loss += jax_utils.unreplicate(metrics['loss'])
                 i += 1
          return running_loss / i

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						List[Any]:







          '''simple docstring'''

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







def A_     (		A__		,				A__    )  ->		List[str]:
       print(F'RESTORING CHECKPOINT FROM {save_dir}'		,				end=' ... '    )
       with open(os.path.join(_UpperCamelCase		,				'flax_model.msgpack'    )		,				'rb'    ) as f:
              a__						:     Tuple			=    from_bytes(state.params		,				f.read()    )

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

       a__						:     Dict			=    joblib.load(os.path.join(_UpperCamelCase		,				'args.joblib'    )    )
       a__						:     Any			=    joblib.load(os.path.join(_UpperCamelCase		,				'data_collator.joblib'    )    )

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

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



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



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

       a__						:     int			=    scheduler_fn(_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase		,				_UpperCamelCase    )

       a__						:     Any			=    optax.adamw(learning_rate=_UpperCamelCase		,				weight_decay=_UpperCamelCase		,				mask=_UpperCamelCase    )
       return tx, lr









import re

from filelock import FileLock


try:
    import nltk

    lowercase				:	List[str]      						=  True
except (ImportError, ModuleNotFoundError):
    lowercase				:	Tuple      						=  False

if NLTK_AVAILABLE:
    with FileLock(""".lock""") as lock:
        nltk.download("""punkt""", quiet=True)



def A_     (		A__    )  ->		str:
       re.sub('<n>'		,				''		,				A__    )  # remove pegasus newline char
       assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)"
       return "\n".join(nltk.sent_tokenize(A__    )    )


