

'''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__  (							__SCREAMING_SNAKE_CASE  ):
   _SCREAMING_SNAKE_CASE   :					Optional[Any]     	=							42
   _SCREAMING_SNAKE_CASE   :					Union[str, Any]     	=							jnp.floataa
   _SCREAMING_SNAKE_CASE   :					Tuple     	=							True


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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






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





      """simple docstring"""





      _lowercase      :				Dict      					=       super().__call__(*UpperCamelCase__      ,    **UpperCamelCase__  )
      _lowercase      :				Any      					=       self.cls(outputs[2]  )
      return outputs[:2] + (cls_out,)




class        a__  (							__SCREAMING_SNAKE_CASE  ):
   _SCREAMING_SNAKE_CASE   :					Optional[Any]     	=							FlaxBigBirdForNaturalQuestionsModule







def  _A		(     snake_case		,							snake_case		,							snake_case		,							snake_case		,							snake_case		,							snake_case					)      ->     Any:


   def cross_entropy(snake_case		,							snake_case		,							snake_case=None					):
      _lowercase      :				Tuple      					=       logits.shape[-1]
      _lowercase      :				Any      					=       (labels[..., None] == jnp.arange(SCREAMING_SNAKE_CASE__					)[None]).astype("f4"					)
      _lowercase      :				str      					=       jax.nn.log_softmax(SCREAMING_SNAKE_CASE__		,							axis=-1					)
      _lowercase      :				Optional[Any]      					=       -jnp.sum(labels * logits		,							axis=-1					)
      if reduction is not None:
         _lowercase      :				Dict      					=       reduction(SCREAMING_SNAKE_CASE__					)
      return loss

   _lowercase      :				List[str]      					=       partial(SCREAMING_SNAKE_CASE__		,							reduction=jnp.mean					)
   _lowercase      :				List[str]      					=       cross_entropy(SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__					)
   _lowercase      :				Optional[Any]      					=       cross_entropy(SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__					)
   _lowercase      :				Any      					=       cross_entropy(SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__					)
   return (start_loss + end_loss + pooled_loss) / 3


@dataclass
class        a__  :
   _SCREAMING_SNAKE_CASE   :					str     	=							'google/bigbird-roberta-base'
   _SCREAMING_SNAKE_CASE   :					Optional[Any]     	=							3000
   _SCREAMING_SNAKE_CASE   :					Dict     	=							1_0500

   _SCREAMING_SNAKE_CASE   :					str     	=							128
   _SCREAMING_SNAKE_CASE   :					Union[str, Any]     	=							3

   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							1
   _SCREAMING_SNAKE_CASE   :					str     	=							5

   # tx_args
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							3E-5
   _SCREAMING_SNAKE_CASE   :					Optional[Any]     	=							0.0
   _SCREAMING_SNAKE_CASE   :					Any     	=							2_0000
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							0.0095

   _SCREAMING_SNAKE_CASE   :					str     	=							'bigbird-roberta-natural-questions'
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							'training-expt'
   _SCREAMING_SNAKE_CASE   :					Union[str, Any]     	=							'data/nq-training.jsonl'
   _SCREAMING_SNAKE_CASE   :					Dict     	=							'data/nq-validation.jsonl'


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      os.makedirs(self.base_dir      ,    exist_ok=UpperCamelCase__  )
      _lowercase      :				Optional[int]      					=       os.path.join(self.base_dir      ,    self.save_dir  )
      _lowercase      :				Optional[Any]      					=       self.batch_size_per_device * jax.device_count()




@dataclass
class        a__  :
   _SCREAMING_SNAKE_CASE   :					Tuple     	=							42
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							4096  # no dynamic padding on TPUs


   def __call__(			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Tuple      					=       self.collate_fn(UpperCamelCase__  )
      _lowercase      :				Tuple      					=       jax.tree_util.tree_map(UpperCamelCase__      ,    UpperCamelCase__  )
      return batch


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       self.fetch_inputs(features["input_ids"]  )
      _lowercase      :				str      					=       {
          '''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"""





      _lowercase      :				str      					=       [self._fetch_inputs(UpperCamelCase__  ) for ids in input_ids]
      return zip(*UpperCamelCase__  )






   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Optional[int]      					=       [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		(     snake_case		,							snake_case		,							snake_case=None					)      ->     Dict:


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







@partial(jax.pmap		,							axis_name="batch"					)
def  _A		(     snake_case		,							snake_case		,							**snake_case					)      ->     str:


   def loss_fn(snake_case					):
      _lowercase      :				Tuple      					=       model_inputs.pop("start_labels"					)
      _lowercase      :				Tuple      					=       model_inputs.pop("end_labels"					)
      _lowercase      :				Optional[int]      					=       model_inputs.pop("pooled_labels"					)

      _lowercase      :				Optional[int]      					=       state.apply_fn(**SCREAMING_SNAKE_CASE__		,							params=SCREAMING_SNAKE_CASE__		,							dropout_rng=SCREAMING_SNAKE_CASE__		,							train=SCREAMING_SNAKE_CASE__					)
      _lowercase      :				Optional[int]      					=       outputs

      return state.loss_fn(
          SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							)

   _lowercase      :				int      					=       jax.random.split(SCREAMING_SNAKE_CASE__					)
   _lowercase      :				Any      					=       jax.value_and_grad(SCREAMING_SNAKE_CASE__					)
   _lowercase      :				Any      					=       grad_fn(state.params					)
   _lowercase      :				Optional[int]      					=       jax.lax.pmean({"loss": loss}		,							axis_name="batch"					)
   _lowercase      :				List[str]      					=       jax.lax.pmean(SCREAMING_SNAKE_CASE__		,							"batch"					)

   _lowercase      :				Dict      					=       state.apply_gradients(grads=SCREAMING_SNAKE_CASE__					)
   return state, metrics, new_drp_rng







@partial(jax.pmap		,							axis_name="batch"					)
def  _A		(     snake_case		,							**snake_case					)      ->     int:
   _lowercase      :				int      					=       model_inputs.pop("start_labels"					)
   _lowercase      :				Union[str, Any]      					=       model_inputs.pop("end_labels"					)
   _lowercase      :				Any      					=       model_inputs.pop("pooled_labels"					)

   _lowercase      :				List[str]      					=       state.apply_fn(**SCREAMING_SNAKE_CASE__		,							params=state.params		,							train=SCREAMING_SNAKE_CASE__					)
   _lowercase      :				Any      					=       outputs

   _lowercase      :				Any      					=       state.loss_fn(SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__					)
   _lowercase      :				List[Any]      					=       jax.lax.pmean({"loss": loss}		,							axis_name="batch"					)
   return metrics


class        a__  (							train_state.TrainState  ):
   _SCREAMING_SNAKE_CASE   :					Dict     	=							struct.field(pytree_node=__SCREAMING_SNAKE_CASE  )




@dataclass
class        a__  :
   _SCREAMING_SNAKE_CASE   :					Union[str, Any]     	=							42
   _SCREAMING_SNAKE_CASE   :					Tuple     	=							42
   _SCREAMING_SNAKE_CASE   :					Any     	=							42
   _SCREAMING_SNAKE_CASE   :					Tuple     	=							42
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							42
   _SCREAMING_SNAKE_CASE   :					Tuple     	=							42
   _SCREAMING_SNAKE_CASE   :					str     	=							None


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase=None  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Tuple      					=       self.args
      _lowercase      :				str      					=       len(UpperCamelCase__  ) // args.batch_size

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

               _lowercase      :				int      					=       self.evaluate(UpperCamelCase__      ,    UpperCamelCase__  )
               _lowercase      :				Dict      					=       {
                   '''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"""





      _lowercase      :				Union[str, Any]      					=       get_batched_dataset(UpperCamelCase__      ,    self.args.batch_size  )
      _lowercase      :				Union[str, Any]      					=       len(UpperCamelCase__  ) // self.args.batch_size
      _lowercase      :				Dict      					=       jnp.array(0      ,    dtype=jnp.floataa  )
      _lowercase      :				Optional[Any]      					=       0
      for batch in tqdm(UpperCamelCase__      ,    total=UpperCamelCase__      ,    desc="Evaluating ... "  ):
         _lowercase      :				Union[str, Any]      					=       self.data_collator(UpperCamelCase__  )
         _lowercase      :				Union[str, Any]      					=       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"""





      _lowercase      :				Optional[int]      					=       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		(     snake_case		,							snake_case					)      ->     Dict:
   print(F'''RESTORING CHECKPOINT FROM {save_dir}'''		,							end=" ... "					)
   with open(os.path.join(SCREAMING_SNAKE_CASE__		,							"flax_model.msgpack"					)		,							"rb"					) as f:
      _lowercase      :				Union[str, Any]      					=       from_bytes(state.params		,							f.read()					)

   with open(os.path.join(SCREAMING_SNAKE_CASE__		,							"opt_state.msgpack"					)		,							"rb"					) as f:
      _lowercase      :				Any      					=       from_bytes(state.opt_state		,							f.read()					)

   _lowercase      :				Optional[int]      					=       joblib.load(os.path.join(SCREAMING_SNAKE_CASE__		,							"args.joblib"					)					)
   _lowercase      :				str      					=       joblib.load(os.path.join(SCREAMING_SNAKE_CASE__		,							"data_collator.joblib"					)					)

   with open(os.path.join(SCREAMING_SNAKE_CASE__		,							"training_state.json"					)		,							"r"					) as f:
      _lowercase      :				List[Any]      					=       json.load(SCREAMING_SNAKE_CASE__					)
   _lowercase      :				Dict      					=       training_state['''step''']

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







def  _A		(     snake_case		,							snake_case		,							snake_case		,							snake_case					)      ->     int:
   _lowercase      :				Optional[int]      					=       num_train_steps - warmup_steps
   _lowercase      :				Union[str, Any]      					=       optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__		,							end_value=SCREAMING_SNAKE_CASE__		,							transition_steps=SCREAMING_SNAKE_CASE__					)
   _lowercase      :				Optional[int]      					=       optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__		,							end_value=1E-7		,							transition_steps=SCREAMING_SNAKE_CASE__					)
   _lowercase      :				List[str]      					=       optax.join_schedules(schedules=[warmup_fn, decay_fn]		,							boundaries=[warmup_steps]					)
   return lr







def  _A		(     snake_case		,							snake_case		,							snake_case		,							snake_case		,							snake_case					)      ->     Tuple:


   def weight_decay_mask(snake_case					):
      _lowercase      :				int      					=       traverse_util.flatten_dict(SCREAMING_SNAKE_CASE__					)
      _lowercase      :				Union[str, Any]      					=       {k: (v[-1] != '''bias''' and v[-2:] != ('''LayerNorm''', '''scale''')) for k, v in params.items()}
      return traverse_util.unflatten_dict(SCREAMING_SNAKE_CASE__					)

   _lowercase      :				str      					=       scheduler_fn(SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__		,							SCREAMING_SNAKE_CASE__					)

   _lowercase      :				Dict      					=       optax.adamw(learning_rate=SCREAMING_SNAKE_CASE__		,							weight_decay=SCREAMING_SNAKE_CASE__		,							mask=SCREAMING_SNAKE_CASE__					)
   return tx, lr









'''simple docstring'''
from __future__ import annotations







def  _A		(     snake_case		,							snake_case = None		,							snake_case = None					)      ->     None:
   if start is None:
      _lowercase      :				Dict      					=       0

   if end is None:
      _lowercase      :				List[Any]      					=       len(snake_case					) - 1

   if start >= end:
      return

   _lowercase      :				int      					=       (start + end) // 2

   slowsort(snake_case		,							snake_case		,							snake_case					)
   slowsort(snake_case		,							mid + 1		,							snake_case					)

   if sequence[end] < sequence[mid]:
      _lowercase					,				_lowercase      :				Any      					=       sequence[mid], sequence[end]

   slowsort(snake_case		,							snake_case		,							end - 1					)


if __name__ == "__main__":
    from doctest import testmod

    testmod()






