





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

  """simple docstring"""


  a_      =			42
  a_      =			jnp.floataa
  a_      =			True






  def     lowercase		(    self			:		Optional[int]					)							->						Optional[int]:
     super().setup()
     __lowerCAmelCase							     =     nn.Dense(5 ,  dtype=self.dtype					)






  def __call__(    self			:		Optional[Any] ,  *lowerCAmelCase_			:		List[Any] ,  **lowerCAmelCase_			:		List[Any]					)							->						List[Any]:
     __lowerCAmelCase							     =     super().__call__(*lowerCAmelCase_ ,  **lowerCAmelCase_					)
     __lowerCAmelCase							     =     self.cls(outputs[2]					)
     return outputs[:2] + (cls_out,)





class     _UpperCAmelCase   (   _UpperCamelCase   ):

  """simple docstring"""


  a_      =			FlaxBigBirdForNaturalQuestionsModule





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

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



@dataclass
class     _UpperCAmelCase   :

  """simple docstring"""


  a_      =			"google/bigbird-roberta-base"
  a_      =			30_00
  a_      =			1_05_00

  a_      =			1_28
  a_      =			3

  a_      =			1
  a_      =			5

  # tx_args
  a_      =			3e-5
  a_      =			0.0
  a_      =			2_00_00
  a_      =			0.0_095

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






  def     lowercase		(    self			:		str					)							->						Any:
     os.makedirs(self.base_dir ,  exist_ok=lowerCAmelCase_					)
     __lowerCAmelCase							     =     os.path.join(self.base_dir ,  self.save_dir					)
     __lowerCAmelCase							     =     self.batch_size_per_device * jax.device_count()





@dataclass
class     _UpperCAmelCase   :

  """simple docstring"""


  a_      =			42
  a_      =			40_96  # no dynamic padding on TPUs






  def __call__(    self			:		Optional[int] ,  lowerCAmelCase_			:		Optional[Any]					)							->						List[str]:
     __lowerCAmelCase							     =     self.collate_fn(lowerCAmelCase_					)
     __lowerCAmelCase							     =     jax.tree_util.tree_map(lowerCAmelCase_ ,  lowerCAmelCase_					)
     return batch






  def     lowercase		(    self			:		Union[str, Any] ,  lowerCAmelCase_			:		str					)							->						Dict:
     __lowerCAmelCase     ,     __lowerCAmelCase							     =     self.fetch_inputs(features['input_ids']					)
     __lowerCAmelCase							     =     {
         'input_ids': jnp.array(lowerCAmelCase_ ,  dtype=jnp.intaa					),
         'attention_mask': jnp.array(lowerCAmelCase_ ,  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			:		Optional[Any] ,  lowerCAmelCase_			:		list					)							->						Union[str, Any]:
     __lowerCAmelCase							     =     [self._fetch_inputs(lowerCAmelCase_					) for ids in input_ids]
     return zip(*lowerCAmelCase_					)






  def     lowercase		(    self			:		Tuple ,  lowerCAmelCase_			:		list					)							->						List[Any]:
     __lowerCAmelCase							     =     [1 for _ in range(len(lowerCAmelCase_					)					)]
     while len(lowerCAmelCase_					) < self.max_length:
        input_ids.append(self.pad_id					)
        attention_mask.append(0					)
     return input_ids, attention_mask





def   a_   (			lowerCAmelCase_				:      Dict,     lowerCAmelCase_				:      List[str],     lowerCAmelCase_				:      str=None     ):
   if seed is not None:
      __lowerCAmelCase							     =     dataset.shuffle(seed=lowerCAmelCase_     )
   for i in range(len(lowerCAmelCase_     ) // batch_size     ):
      __lowerCAmelCase							     =     dataset[i * batch_size : (i + 1) * batch_size]
      yield dict(lowerCAmelCase_     )

@partial(jax.pmap,     axis_name='batch'     )
def   a_   (			lowerCAmelCase_				:      Union[str, Any],     lowerCAmelCase_				:      Optional[int],     **lowerCAmelCase_				:      Dict     ):
   def loss_fn(lowerCAmelCase_				:      List[str]     ):
      __lowerCAmelCase							     =     model_inputs.pop('start_labels'     )
      __lowerCAmelCase							     =     model_inputs.pop('end_labels'     )
      __lowerCAmelCase							     =     model_inputs.pop('pooled_labels'     )

      __lowerCAmelCase							     =     state.apply_fn(**lowerCAmelCase_,     params=lowerCAmelCase_,     dropout_rng=lowerCAmelCase_,     train=lowerCAmelCase_     )
      __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase							     =     outputs

      return state.loss_fn(
          lowerCAmelCase_,     lowerCAmelCase_,     lowerCAmelCase_,     lowerCAmelCase_,     lowerCAmelCase_,     lowerCAmelCase_,     )

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

   __lowerCAmelCase							     =     state.apply_gradients(grads=lowerCAmelCase_     )
   return state, metrics, new_drp_rng

@partial(jax.pmap,     axis_name='batch'     )
def   a_   (			lowerCAmelCase_				:      Dict,     **lowerCAmelCase_				:      int     ):
   __lowerCAmelCase							     =     model_inputs.pop('start_labels'     )
   __lowerCAmelCase							     =     model_inputs.pop('end_labels'     )
   __lowerCAmelCase							     =     model_inputs.pop('pooled_labels'     )

   __lowerCAmelCase							     =     state.apply_fn(**lowerCAmelCase_,     params=state.params,     train=lowerCAmelCase_     )
   __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase							     =     outputs

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



class     _UpperCAmelCase   (   train_state.TrainState   ):

  """simple docstring"""


  a_      =			struct.field(pytree_node=_UpperCamelCase   )





@dataclass
class     _UpperCAmelCase   :

  """simple docstring"""


  a_      =			42
  a_      =			42
  a_      =			42
  a_      =			42
  a_      =			42
  a_      =			42
  a_      =			None






  def     lowercase		(    self			:		Optional[int] ,  lowerCAmelCase_			:		Dict ,  lowerCAmelCase_			:		List[str] ,  lowerCAmelCase_			:		Optional[int] ,  lowerCAmelCase_			:		int=None					)							->						int:
     __lowerCAmelCase							     =     model.params
     __lowerCAmelCase							     =     TrainState.create(
         apply_fn=model.__call__ ,  params=lowerCAmelCase_ ,  tx=lowerCAmelCase_ ,  loss_fn=lowerCAmelCase_ ,  )
     if ckpt_dir is not None:
        __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase							     =     restore_checkpoint(lowerCAmelCase_ ,  lowerCAmelCase_					)
        __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(**lowerCAmelCase_					)
        __lowerCAmelCase							     =     train_state.TrainState(
            step=lowerCAmelCase_ ,  apply_fn=model.__call__ ,  params=lowerCAmelCase_ ,  tx=lowerCAmelCase_ ,  opt_state=lowerCAmelCase_ ,  )
        __lowerCAmelCase							     =     args
        __lowerCAmelCase							     =     data_collator
        __lowerCAmelCase							     =     lr
        __lowerCAmelCase							     =     params
     __lowerCAmelCase							     =     jax_utils.replicate(lowerCAmelCase_					)
     return state






  def     lowercase		(    self			:		List[Any] ,  lowerCAmelCase_			:		Dict ,  lowerCAmelCase_			:		Optional[Any] ,  lowerCAmelCase_			:		Union[str, Any]					)							->						Optional[Any]:
     __lowerCAmelCase							     =     self.args
     __lowerCAmelCase							     =     len(lowerCAmelCase_					) // args.batch_size

     __lowerCAmelCase							     =     jax.random.PRNGKey(0					)
     __lowerCAmelCase							     =     jax.random.split(lowerCAmelCase_ ,  jax.device_count()					)
     for epoch in range(args.max_epochs					):
        __lowerCAmelCase							     =     jnp.array(0 ,  dtype=jnp.floataa					)
        __lowerCAmelCase							     =     get_batched_dataset(lowerCAmelCase_ ,  args.batch_size ,  seed=lowerCAmelCase_					)
        __lowerCAmelCase							     =     0
        for batch in tqdm(lowerCAmelCase_ ,  total=lowerCAmelCase_ ,  desc=f"""Running EPOCH-{epoch}"""					):
           __lowerCAmelCase							     =     self.data_collator(lowerCAmelCase_					)
           __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase							     =     self.train_step_fn(lowerCAmelCase_ ,  lowerCAmelCase_ ,  **lowerCAmelCase_					)
           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(lowerCAmelCase_ ,  lowerCAmelCase_					)
              __lowerCAmelCase							     =     {
                  'step': state_step.item(),
                  'eval_loss': eval_loss.item(),
                  'tr_loss': tr_loss,
                  'lr': lr.item(),
              }
              tqdm.write(str(lowerCAmelCase_					)					)
              self.logger.log(lowerCAmelCase_ ,  commit=lowerCAmelCase_					)

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






  def     lowercase		(    self			:		Tuple ,  lowerCAmelCase_			:		Dict ,  lowerCAmelCase_			:		List[str]					)							->						Optional[Any]:
     __lowerCAmelCase							     =     get_batched_dataset(lowerCAmelCase_ ,  self.args.batch_size					)
     __lowerCAmelCase							     =     len(lowerCAmelCase_					) // self.args.batch_size
     __lowerCAmelCase							     =     jnp.array(0 ,  dtype=jnp.floataa					)
     __lowerCAmelCase							     =     0
     for batch in tqdm(lowerCAmelCase_ ,  total=lowerCAmelCase_ ,  desc='Evaluating ... '					):
        __lowerCAmelCase							     =     self.data_collator(lowerCAmelCase_					)
        __lowerCAmelCase							     =     self.val_step_fn(lowerCAmelCase_ ,  **lowerCAmelCase_					)
        running_loss += jax_utils.unreplicate(metrics['loss']					)
        i += 1
     return running_loss / i






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





def   a_   (			lowerCAmelCase_				:      int,     lowerCAmelCase_				:      int     ):
   print(F"""RESTORING CHECKPOINT FROM {save_dir}""",     end=' ... '     )
   with open(os.path.join(lowerCAmelCase_,     'flax_model.msgpack'     ),     'rb'     ) as f:
      __lowerCAmelCase							     =     from_bytes(state.params,     f.read()     )

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

   __lowerCAmelCase							     =     joblib.load(os.path.join(lowerCAmelCase_,     'args.joblib'     )     )
   __lowerCAmelCase							     =     joblib.load(os.path.join(lowerCAmelCase_,     'data_collator.joblib'     )     )

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

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

def   a_   (			lowerCAmelCase_				:      Dict,     lowerCAmelCase_				:      Optional[Any],     lowerCAmelCase_				:      Optional[Any],     lowerCAmelCase_				:      Optional[Any]     ):
   __lowerCAmelCase							     =     num_train_steps - warmup_steps
   __lowerCAmelCase							     =     optax.linear_schedule(init_value=lowerCAmelCase_,     end_value=lowerCAmelCase_,     transition_steps=lowerCAmelCase_     )
   __lowerCAmelCase							     =     optax.linear_schedule(init_value=lowerCAmelCase_,     end_value=1E-7,     transition_steps=lowerCAmelCase_     )
   __lowerCAmelCase							     =     optax.join_schedules(schedules=[warmup_fn, decay_fn],     boundaries=[warmup_steps]     )
   return lr




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

   __lowerCAmelCase							     =     scheduler_fn(lowerCAmelCase_,     lowerCAmelCase_,     lowerCAmelCase_,     lowerCAmelCase_     )

   __lowerCAmelCase							     =     optax.adamw(learning_rate=lowerCAmelCase_,     weight_decay=lowerCAmelCase_,     mask=lowerCAmelCase_     )
   return tx, lr








from functools import lru_cache

@lru_cache
def   a_   (			lowerCAmelCase_				:      int     ):
   if num < 0:
      raise ValueError('Number should not be negative.'     )

   return 1 if num in (0, 1) else num * factorial(num - 1     )


if __name__ == "__main__":
     import doctest

     doctest.testmod()

