
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 __snake_case		(      lowerCAmelCase     ):
    _a		:						BigBirdConfig
    _a		:						jnp.dtype=				jnp.floataa
    _a		:						bool=				True
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().setup()
           lowercase							:     List[str]       	=      nn.Dense(5		,dtype=self.dtype      )
    def __call__(  self		,*snake_case		,**snake_case      ):



           '''simple docstring'''







           lowercase							:     int       	=      super().__call__(*snake_case		,**snake_case      )
           lowercase							:     Any       	=      self.cls(outputs[2]      )
           return outputs[:2] + (cls_out,)






class __snake_case		(      lowerCAmelCase     ):
    _a		:						List[Any]=				FlaxBigBirdForNaturalQuestionsModule







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

       lowercase							:     Optional[Any]       	=      partial(SCREAMING_SNAKE_CASE__					,	reduction=jnp.mean				)
       lowercase							:     Optional[int]       	=      cross_entropy(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       lowercase							:     Dict       	=      cross_entropy(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       lowercase							:     int       	=      cross_entropy(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       return (start_loss + end_loss + pooled_loss) / 3

@dataclass
class __snake_case		:
    _a		:						str=				"google/bigbird-roberta-base"
    _a		:						int=				3000
    _a		:						int=				1_0500

    _a		:						int=				128
    _a		:						int=				3

    _a		:						int=				1
    _a		:						int=				5

    # tx_args
    _a		:						float=				3E-5
    _a		:						float=				0.0
    _a		:						int=				2_0000
    _a		:						float=				0.00_95

    _a		:						str=				"bigbird-roberta-natural-questions"
    _a		:						str=				"training-expt"
    _a		:						str=				"data/nq-training.jsonl"
    _a		:						str=				"data/nq-validation.jsonl"
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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






@dataclass
class __snake_case		:
    _a		:						int
    _a		:						int=				4096  # no dynamic padding on TPUs
    def __call__(  self		,snake_case      ):



           '''simple docstring'''







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



           '''simple docstring'''







           lowercase	,			lowercase							:     Union[str, Any]       	=      self.fetch_inputs(features["""input_ids"""]      )
           lowercase							:     Tuple       	=      {
               """input_ids""": jnp.array(snake_case		,dtype=jnp.intaa      ),
               """attention_mask""": jnp.array(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       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      [self._fetch_inputs(snake_case      ) for ids in input_ids]
           return zip(*snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      [1 for _ in range(len(snake_case      )      )]
           while len(snake_case      ) < self.max_length:
                  input_ids.append(self.pad_id      )
                  attention_mask.append(0      )
           return input_ids, attention_mask







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__=None				) ->    Any:
       if seed is not None:
              lowercase							:     Optional[int]       	=      dataset.shuffle(seed=SCREAMING_SNAKE_CASE__				)
       for i in range(len(SCREAMING_SNAKE_CASE__				) // batch_size				):
              lowercase							:     Optional[Any]       	=      dataset[i * batch_size : (i + 1) * batch_size]
              yield dict(SCREAMING_SNAKE_CASE__				)







@partial(jax.pmap					,	axis_name="""batch"""				)
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	**SCREAMING_SNAKE_CASE__				) ->    List[Any]:
       def loss_fn(SCREAMING_SNAKE_CASE__				):
              lowercase							:     List[str]       	=      model_inputs.pop("""start_labels"""				)
              lowercase							:     Optional[int]       	=      model_inputs.pop("""end_labels"""				)
              lowercase							:     str       	=      model_inputs.pop("""pooled_labels"""				)

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

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

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

       lowercase							:     str       	=      state.apply_gradients(grads=SCREAMING_SNAKE_CASE__				)
       return state, metrics, new_drp_rng







@partial(jax.pmap					,	axis_name="""batch"""				)
def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	**SCREAMING_SNAKE_CASE__				) ->    List[str]:
       lowercase							:     int       	=      model_inputs.pop("""start_labels"""				)
       lowercase							:     Dict       	=      model_inputs.pop("""end_labels"""				)
       lowercase							:     Optional[Any]       	=      model_inputs.pop("""pooled_labels"""				)

       lowercase							:     Optional[int]       	=      state.apply_fn(**SCREAMING_SNAKE_CASE__					,	params=state.params					,	train=SCREAMING_SNAKE_CASE__				)
       lowercase	,			lowercase	,			lowercase							:     List[Any]       	=      outputs

       lowercase							:     Dict       	=      state.loss_fn(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       lowercase							:     str       	=      jax.lax.pmean({"""loss""": loss}					,	axis_name="""batch"""				)
       return metrics

class __snake_case		(      train_state.TrainState     ):
    _a		:						Callable=				struct.field(pytree_node=lowerCAmelCase     )






@dataclass
class __snake_case		:
    _a		:						Args
    _a		:						Callable
    _a		:						Callable
    _a		:						Callable
    _a		:						Callable
    _a		:						wandb
    _a		:						Callable=				None
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case		,snake_case=None      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      model.params
           lowercase							:     Any       	=      TrainState.create(
               apply_fn=model.__call__		,params=snake_case		,tx=snake_case		,loss_fn=snake_case		,)
           if ckpt_dir is not None:
                  lowercase	,			lowercase	,			lowercase	,			lowercase	,			lowercase							:     Tuple       	=      restore_checkpoint(snake_case		,snake_case      )
                  lowercase							:     List[str]       	=      {
                      """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	,			lowercase							:     Tuple       	=      build_tx(**snake_case      )
                  lowercase							:     str       	=      train_state.TrainState(
                      step=snake_case		,apply_fn=model.__call__		,params=snake_case		,tx=snake_case		,opt_state=snake_case		,)
                  lowercase							:     Any       	=      args
                  lowercase							:     Optional[Any]       	=      data_collator
                  lowercase							:     List[str]       	=      lr
                  lowercase							:     str       	=      params
           lowercase							:     Tuple       	=      jax_utils.replicate(snake_case      )
           return state
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Dict       	=      self.args
           lowercase							:     Optional[Any]       	=      len(snake_case      ) // args.batch_size

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

                                lowercase							:     int       	=      self.evaluate(snake_case		,snake_case      )
                                lowercase							:     Tuple       	=      {
                                    """step""": state_step.item(),
                                    """eval_loss""": eval_loss.item(),
                                    """tr_loss""": tr_loss,
                                    """lr""": lr.item(),
                                }
                                tqdm.write(str(snake_case      )      )
                                self.logger.log(snake_case		,commit=snake_case      )

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



           '''simple docstring'''







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



           '''simple docstring'''







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







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Union[str, Any]:
       print(f"RESTORING CHECKPOINT FROM {save_dir}"					,	end=""" ... """				)
       with open(os.path.join(SCREAMING_SNAKE_CASE__					,	"""flax_model.msgpack"""				)					,	"""rb"""				) as f:
              lowercase							:     str       	=      from_bytes(state.params					,	f.read()				)

       with open(os.path.join(SCREAMING_SNAKE_CASE__					,	"""opt_state.msgpack"""				)					,	"""rb"""				) as f:
              lowercase							:     Optional[int]       	=      from_bytes(state.opt_state					,	f.read()				)

       lowercase							:     Optional[Any]       	=      joblib.load(os.path.join(SCREAMING_SNAKE_CASE__					,	"""args.joblib"""				)				)
       lowercase							:     int       	=      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							:     Tuple       	=      json.load(SCREAMING_SNAKE_CASE__				)
       lowercase							:     Tuple       	=      training_state["""step"""]

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







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    List[Any]:
       lowercase							:     List[str]       	=      num_train_steps - warmup_steps
       lowercase							:     Dict       	=      optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__					,	end_value=SCREAMING_SNAKE_CASE__					,	transition_steps=SCREAMING_SNAKE_CASE__				)
       lowercase							:     List[str]       	=      optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__					,	end_value=1e-7					,	transition_steps=SCREAMING_SNAKE_CASE__				)
       lowercase							:     Tuple       	=      optax.join_schedules(schedules=[warmup_fn, decay_fn]					,	boundaries=[warmup_steps]				)
       return lr







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Optional[Any]:
       def weight_decay_mask(SCREAMING_SNAKE_CASE__				):
              lowercase							:     List[Any]       	=      traverse_util.flatten_dict(SCREAMING_SNAKE_CASE__				)
              lowercase							:     List[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							:     List[str]       	=      scheduler_fn(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)

       lowercase							:     List[str]       	=      optax.adamw(learning_rate=SCREAMING_SNAKE_CASE__					,	weight_decay=SCREAMING_SNAKE_CASE__					,	mask=SCREAMING_SNAKE_CASE__				)
       return tx, lr




import importlib.metadata
import operator
import re
import sys
from typing import Optional

from packaging import version


__lowerCAmelCase	: Union[str, Any]  				={
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne,
    '>=': operator.ge,
    '>': operator.gt,
}


def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__      ):
						if got_ver is None or want_ver is None:
												raise ValueError(
												    F'''Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider'''
												    F''' reinstalling {pkg}.'''      )
						if not ops[op](version.parse(lowercase__      )    ,       version.parse(lowercase__      )      ):
												raise ImportError(
												    F'''{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}'''      )


def        _UpperCamelCase							(      lowercase__    ,       lowercase__ = None      ):
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		F'''\n{hint}''' if hint is not None else ''''''

						# non-versioned check
						if re.match(R'''^[\w_\-\d]+$'''    ,       lowercase__      ):
												__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     str					=		requirement, None, None
						else:
												__SCREAMING_SNAKE_CASE						:     List[Any]					=		re.findall(R'''^([^!=<>\s]+)([\s!=<>]{1,2}.+)'''    ,       lowercase__      )
												if not match:
																		raise ValueError(
																		    '''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but'''
																		    F''' got {requirement}'''      )
												__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     Tuple					=		match[0]
												__SCREAMING_SNAKE_CASE						:     Optional[int]					=		want_full.split(''','''      )  # there could be multiple requirements
												__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		{}
												for w in want_range:
																		__SCREAMING_SNAKE_CASE						:     Any					=		re.findall(R'''^([\s!=<>]{1,2})(.+)'''    ,       lowercase__      )
																		if not match:
																								raise ValueError(
																								    '''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,'''
																								    F''' but got {requirement}'''      )
																		__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     Tuple					=		match[0]
																		__SCREAMING_SNAKE_CASE						:     List[Any]					=		want_ver
																		if op not in ops:
																								raise ValueError(F'''{requirement}: need one of {list(ops.keys()      )}, but got {op}'''      )

    # special case
						if pkg == "python":
												__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		'''.'''.join([str(lowercase__      ) for x in sys.version_info[:3]]      )
												for op, want_ver in wanted.items():
																		_compare_versions(lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__      )
												return

						# check if any version is installed
						try:
												__SCREAMING_SNAKE_CASE						:     Optional[int]					=		importlib.metadata.version(lowercase__      )
						except importlib.metadata.PackageNotFoundError:
												raise importlib.metadata.PackageNotFoundError(
												    F'''The \'{requirement}\' distribution was not found and is required by this application. {hint}'''      )

						# check that the right version is installed if version number or a range was provided
						if want_ver is not None:
												for op, want_ver in wanted.items():
																		_compare_versions(lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		'''Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main'''
						return require_version(lowercase__    ,       lowercase__      )
