

'''simple docstring'''
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__   (	A__  ):
  A__					=    42
  A__					=    jnp.floataa
  A__					=    True





  def 						A  (		self				:     str			)     ->   List[Any]:





       '''simple docstring'''






       super().setup()
       _SCREAMING_SNAKE_CASE							   =nn.Dense(5							, dtype=self.dtype			)





  def __call__(		self				:     List[str]							, *_a				:     List[Any]							, **_a				:     Dict			)     ->   int:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =super().__call__(*lowerCamelCase_							, **lowerCamelCase_			)
       _SCREAMING_SNAKE_CASE							   =self.cls(outputs[2]			)
       return outputs[:2] + (cls_out,)







class 							A__   (	A__  ):
  A__					=    FlaxBigBirdForNaturalQuestionsModule


def 	_lowerCAmelCase (						_UpperCamelCase						:					int							,			_UpperCamelCase						:					Union[str, Any]							,			_UpperCamelCase						:					Dict							,			_UpperCamelCase						:					List[str]							,			_UpperCamelCase						:					Dict							,			_UpperCamelCase						:					Tuple    )				->      str:
     """simple docstring"""




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

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







@dataclass
class 							A__   :
  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.0095

  A__					=    'bigbird-roberta-natural-questions'
  A__					=    'training-expt'
  A__					=    'data/nq-training.jsonl'
  A__					=    'data/nq-validation.jsonl'





  def 						A  (		self				:     Tuple			)     ->   int:





       '''simple docstring'''






       os.makedirs(self.base_dir							, exist_ok=lowerCamelCase_			)
       _SCREAMING_SNAKE_CASE							   =os.path.join(self.base_dir							, self.save_dir			)
       _SCREAMING_SNAKE_CASE							   =self.batch_size_per_device * jax.device_count()







@dataclass
class 							A__   :
  A__					=    42
  A__					=    40_96  # no dynamic padding on TPUs





  def __call__(		self				:     Any							, _a				:     Union[str, Any]			)     ->   Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =self.collate_fn(lowerCamelCase_			)
       _SCREAMING_SNAKE_CASE							   =jax.tree_util.tree_map(lowerCamelCase_							, lowerCamelCase_			)
       return batch





  def 						A  (		self				:     Any							, _a				:     Any			)     ->   Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE   ,						_SCREAMING_SNAKE_CASE							   =self.fetch_inputs(features['input_ids']			)
       _SCREAMING_SNAKE_CASE							   ={
           '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 						A  (		self				:     int							, _a				:     Optional[int]			)     ->   Union[str, Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =[self._fetch_inputs(lowerCamelCase_			) for ids in input_ids]
       return zip(*lowerCamelCase_			)





  def 						A  (		self				:     Tuple							, _a				:     Union[str, Any]			)     ->   Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =[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 	_lowerCAmelCase (						_UpperCamelCase						:					List[Any]							,			_UpperCamelCase						:					Tuple							,			_UpperCamelCase						:					Any=None    )				->      List[str]:
     """simple docstring"""




     if seed is not None:
          _SCREAMING_SNAKE_CASE							   =dataset.shuffle(seed=_a    )
     for i in range(len(_a    ) // batch_size    ):
          _SCREAMING_SNAKE_CASE							   =dataset[i * batch_size : (i + 1) * batch_size]
          yield dict(_a    )


@partial(jax.pmap							,			axis_name='batch'    )
def 	_lowerCAmelCase (						_UpperCamelCase						:					Tuple							,			_UpperCamelCase						:					Any							,			**_UpperCamelCase						:					Any    )				->      Any:
     """simple docstring"""




     def loss_fn(_UpperCamelCase						:					str    ):
          _SCREAMING_SNAKE_CASE							   =model_inputs.pop('start_labels'    )
          _SCREAMING_SNAKE_CASE							   =model_inputs.pop('end_labels'    )
          _SCREAMING_SNAKE_CASE							   =model_inputs.pop('pooled_labels'    )

          _SCREAMING_SNAKE_CASE							   =state.apply_fn(**_a							,			params=_a							,			dropout_rng=_a							,			train=_a    )
          _SCREAMING_SNAKE_CASE   ,						_SCREAMING_SNAKE_CASE   ,						_SCREAMING_SNAKE_CASE							   =outputs

          return state.loss_fn(
              _a							,			_a							,			_a							,			_a							,			_a							,			_a							,			)

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

     _SCREAMING_SNAKE_CASE							   =state.apply_gradients(grads=_a    )
     return state, metrics, new_drp_rng


@partial(jax.pmap							,			axis_name='batch'    )
def 	_lowerCAmelCase (						_UpperCamelCase						:					Dict							,			**_UpperCamelCase						:					List[Any]    )				->      Optional[Any]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							   =model_inputs.pop('start_labels'    )
     _SCREAMING_SNAKE_CASE							   =model_inputs.pop('end_labels'    )
     _SCREAMING_SNAKE_CASE							   =model_inputs.pop('pooled_labels'    )

     _SCREAMING_SNAKE_CASE							   =state.apply_fn(**_a							,			params=state.params							,			train=_a    )
     _SCREAMING_SNAKE_CASE   ,						_SCREAMING_SNAKE_CASE   ,						_SCREAMING_SNAKE_CASE							   =outputs

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







class 							A__   (	train_state.TrainState  ):
  A__					=    struct.field(pytree_node=A__  )







@dataclass
class 							A__   :
  A__					=    42
  A__					=    42
  A__					=    42
  A__					=    42
  A__					=    42
  A__					=    42
  A__					=    None





  def 						A  (		self				:     Optional[Any]							, _a				:     str							, _a				:     Optional[Any]							, _a				:     Optional[Any]							, _a				:     Optional[Any]=None			)     ->   List[str]:





       '''simple docstring'''






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





  def 						A  (		self				:     Optional[Any]							, _a				:     Dict							, _a				:     int							, _a				:     Any			)     ->   Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =self.args
       _SCREAMING_SNAKE_CASE							   =len(lowerCamelCase_			) // args.batch_size

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

                      _SCREAMING_SNAKE_CASE							   =self.evaluate(lowerCamelCase_							, lowerCamelCase_			)
                      _SCREAMING_SNAKE_CASE							   ={
                          '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 						A  (		self				:     Optional[int]							, _a				:     List[str]							, _a				:     Union[str, Any]			)     ->   int:





       '''simple docstring'''






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





  def 						A  (		self				:     Union[str, Any]							, _a				:     Dict							, _a				:     str			)     ->   List[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =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 	_lowerCAmelCase (						_UpperCamelCase						:					Union[str, Any]							,			_UpperCamelCase						:					Tuple    )				->      Optional[Any]:
     """simple docstring"""




     print(f"RESTORING CHECKPOINT FROM {save_dir}"							,			end=' ... '    )
     with open(os.path.join(_a							,			'flax_model.msgpack'    )							,			'rb'    ) as f:
          _SCREAMING_SNAKE_CASE							   =from_bytes(state.params							,			f.read()    )

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

     _SCREAMING_SNAKE_CASE							   =joblib.load(os.path.join(_a							,			'args.joblib'    )    )
     _SCREAMING_SNAKE_CASE							   =joblib.load(os.path.join(_a							,			'data_collator.joblib'    )    )

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

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


def 	_lowerCAmelCase (						_UpperCamelCase						:					Optional[Any]							,			_UpperCamelCase						:					Tuple							,			_UpperCamelCase						:					Tuple							,			_UpperCamelCase						:					Dict    )				->      Optional[int]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							   =num_train_steps - warmup_steps
     _SCREAMING_SNAKE_CASE							   =optax.linear_schedule(init_value=_a							,			end_value=_a							,			transition_steps=_a    )
     _SCREAMING_SNAKE_CASE							   =optax.linear_schedule(init_value=_a							,			end_value=1E-7							,			transition_steps=_a    )
     _SCREAMING_SNAKE_CASE							   =optax.join_schedules(schedules=[warmup_fn, decay_fn]							,			boundaries=[warmup_steps]    )
     return lr







def 	_lowerCAmelCase (						_UpperCamelCase						:					Union[str, Any]							,			_UpperCamelCase						:					Any							,			_UpperCamelCase						:					int							,			_UpperCamelCase						:					List[str]							,			_UpperCamelCase						:					Optional[int]    )				->      Any:
     """simple docstring"""




     def weight_decay_mask(_UpperCamelCase						:					Dict    ):
          _SCREAMING_SNAKE_CASE							   =traverse_util.flatten_dict(_a    )
          _SCREAMING_SNAKE_CASE							   ={k: (v[-1] != 'bias' and v[-2:] != ('LayerNorm', 'scale')) for k, v in params.items()}
          return traverse_util.unflatten_dict(_a    )

     _SCREAMING_SNAKE_CASE							   =scheduler_fn(_a							,			_a							,			_a							,			_a    )

     _SCREAMING_SNAKE_CASE							   =optax.adamw(learning_rate=_a							,			weight_decay=_a							,			mask=_a    )
     return tx, lr



'''simple docstring'''
def 	_lowerCAmelCase (						_UpperCamelCase						:					float							,			_UpperCamelCase						:					float    )				->      float:
     """simple docstring"""




     if mass < 0:
          raise ValueError('The mass of a body cannot be negative'    )
     return 0.5 * mass * abs(_UpperCamelCase    ) * abs(_UpperCamelCase    )


if __name__ == "__main__":
     import doctest

     doctest.testmod(verbose=True)
