

"""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 lowerCamelCase__   (				SCREAMING_SNAKE_CASE_    ):



    '''simple docstring'''




    _lowerCamelCase					=   42
    _lowerCamelCase					=   jnp.floataa
    _lowerCamelCase					=   True




    def UpperCamelCase__		( self    )    ->      List[str]:
          super().setup()
          A				  =		nn.Dense(5 ,dtype=self.dtype    )




    def __call__( self ,*lowerCamelCase_ ,**lowerCamelCase_    )    ->      str:
          A				  =		super().__call__(*__a ,**__a    )
          A				  =		self.cls(outputs[2]    )
          return outputs[:2] + (cls_out,)





class lowerCamelCase__   (				SCREAMING_SNAKE_CASE_    ):



    '''simple docstring'''




    _lowerCamelCase					=   FlaxBigBirdForNaturalQuestionsModule




def   _A					(	_a	:						Optional[int]     ,   _a	:						int     ,   _a	:						List[str]     ,   _a	:						Union[str, Any]     ,   _a	:						Dict     ,   _a	:						List[str]				):



      """simple docstring"""






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

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





@dataclass
class lowerCamelCase__   :



    '''simple docstring'''




    _lowerCamelCase					=   '''google/bigbird-roberta-base'''
    _lowerCamelCase					=   3000
    _lowerCamelCase					=   10500

    _lowerCamelCase					=   128
    _lowerCamelCase					=   3

    _lowerCamelCase					=   1
    _lowerCamelCase					=   5

    # tx_args
    _lowerCamelCase					=   3E-5
    _lowerCamelCase					=   0.0
    _lowerCamelCase					=   20000
    _lowerCamelCase					=   0.0_0_9_5

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




    def UpperCamelCase__		( self    )    ->      Optional[int]:
          os.makedirs(self.base_dir ,exist_ok=__a    )
          A				  =		os.path.join(self.base_dir ,self.save_dir    )
          A				  =		self.batch_size_per_device * jax.device_count()





@dataclass
class lowerCamelCase__   :



    '''simple docstring'''




    _lowerCamelCase					=   42
    _lowerCamelCase					=   4096  # no dynamic padding on TPUs




    def __call__( self ,lowerCamelCase_    )    ->      Any:
          A				  =		self.collate_fn(__a    )
          A				  =		jax.tree_util.tree_map(__a ,__a    )
          return batch




    def UpperCamelCase__		( self ,lowerCamelCase_    )    ->      Any:
          A				  =		self.fetch_inputs(features["""input_ids"""]    )
          A				  =		{
              'input_ids': jnp.array(__a ,dtype=jnp.intaa    ),
              'attention_mask': jnp.array(__a ,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 UpperCamelCase__		( self ,lowerCamelCase_    )    ->      int:
          A				  =		[self._fetch_inputs(__a    ) for ids in input_ids]
          return zip(*__a    )




    def UpperCamelCase__		( self ,lowerCamelCase_    )    ->      Optional[int]:
          A				  =		[1 for _ in range(len(__a    )    )]
          while len(__a    ) < self.max_length:
                input_ids.append(self.pad_id    )
                attention_mask.append(0    )
          return input_ids, attention_mask




def   _A					(	_a	:						Tuple     ,   _a	:						Dict     ,   _a	:						Optional[Any]=None				):



      """simple docstring"""






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



@partial(jax.pmap     ,   axis_name="""batch"""				)
def   _A					(	_a	:						Optional[int]     ,   _a	:						Optional[Any]     ,   **_a	:						List[str]				):



      """simple docstring"""






      def loss_fn(_a	:						Optional[int]				):
            A				  =		model_inputs.pop("""start_labels"""				)
            A				  =		model_inputs.pop("""end_labels"""				)
            A				  =		model_inputs.pop("""pooled_labels"""				)

            A				  =		state.apply_fn(**_UpperCAmelCase     ,   params=_UpperCAmelCase     ,   dropout_rng=_UpperCAmelCase     ,   train=_UpperCAmelCase				)
            A				  =		outputs

            return state.loss_fn(
                _UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase     ,   )

      A				  =		jax.random.split(_UpperCAmelCase				)
      A				  =		jax.value_and_grad(_UpperCAmelCase				)
      A				  =		grad_fn(state.params				)
      A				  =		jax.lax.pmean({"""loss""": loss}     ,   axis_name="""batch"""				)
      A				  =		jax.lax.pmean(_UpperCAmelCase     ,   """batch"""				)

      A				  =		state.apply_gradients(grads=_UpperCAmelCase				)
      return state, metrics, new_drp_rng



@partial(jax.pmap     ,   axis_name="""batch"""				)
def   _A					(	_a	:						List[Any]     ,   **_a	:						Optional[Any]				):



      """simple docstring"""






      A				  =		model_inputs.pop("""start_labels"""				)
      A				  =		model_inputs.pop("""end_labels"""				)
      A				  =		model_inputs.pop("""pooled_labels"""				)

      A				  =		state.apply_fn(**_UpperCAmelCase     ,   params=state.params     ,   train=_UpperCAmelCase				)
      A				  =		outputs

      A				  =		state.loss_fn(_UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase				)
      A				  =		jax.lax.pmean({"""loss""": loss}     ,   axis_name="""batch"""				)
      return metrics





class lowerCamelCase__   (				train_state.TrainState    ):



    '''simple docstring'''




    _lowerCamelCase					=   struct.field(pytree_node=SCREAMING_SNAKE_CASE_    )





@dataclass
class lowerCamelCase__   :



    '''simple docstring'''




    _lowerCamelCase					=   42
    _lowerCamelCase					=   42
    _lowerCamelCase					=   42
    _lowerCamelCase					=   42
    _lowerCamelCase					=   42
    _lowerCamelCase					=   42
    _lowerCamelCase					=   None




    def UpperCamelCase__		( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_=None    )    ->      List[str]:
          A				  =		model.params
          A				  =		TrainState.create(
              apply_fn=model.__call__ ,params=__a ,tx=__a ,loss_fn=__a ,)
          if ckpt_dir is not None:
                A				  =		restore_checkpoint(__a ,__a    )
                A				  =		{
                    '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				  =		build_tx(**__a    )
                A				  =		train_state.TrainState(
                    step=__a ,apply_fn=model.__call__ ,params=__a ,tx=__a ,opt_state=__a ,)
                A				  =		args
                A				  =		data_collator
                A				  =		lr
                A				  =		params
          A				  =		jax_utils.replicate(__a    )
          return state




    def UpperCamelCase__		( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_    )    ->      Union[str, Any]:
          A				  =		self.args
          A				  =		len(__a    ) // args.batch_size

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

                            A				  =		self.evaluate(__a ,__a    )
                            A				  =		{
                                'step': state_step.item(),
                                'eval_loss': eval_loss.item(),
                                'tr_loss': tr_loss,
                                'lr': lr.item(),
                            }
                            tqdm.write(str(__a    )    )
                            self.logger.log(__a ,commit=__a    )

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




    def UpperCamelCase__		( self ,lowerCamelCase_ ,lowerCamelCase_    )    ->      Dict:
          A				  =		get_batched_dataset(__a ,self.args.batch_size    )
          A				  =		len(__a    ) // self.args.batch_size
          A				  =		jnp.array(0 ,dtype=jnp.floataa    )
          A				  =		0
          for batch in tqdm(__a ,total=__a ,desc="""Evaluating ... """    ):
                A				  =		self.data_collator(__a    )
                A				  =		self.val_step_fn(__a ,**__a    )
                running_loss += jax_utils.unreplicate(metrics["""loss"""]    )
                i += 1
          return running_loss / i




    def UpperCamelCase__		( self ,lowerCamelCase_ ,lowerCamelCase_    )    ->      Dict:
          A				  =		jax_utils.unreplicate(__a    )
          print(f'SAVING CHECKPOINT IN {save_dir}' ,end=""" ... """    )
          self.model_save_fn(__a ,params=state.params    )
          with open(os.path.join(__a ,"""opt_state.msgpack"""    ) ,"""wb"""    ) as f:
                f.write(to_bytes(state.opt_state    )    )
          joblib.dump(self.args ,os.path.join(__a ,"""args.joblib"""    )    )
          joblib.dump(self.data_collator ,os.path.join(__a ,"""data_collator.joblib"""    )    )
          with open(os.path.join(__a ,"""training_state.json"""    ) ,"""w"""    ) as f:
                json.dump({"""step""": state.step.item()} ,__a    )
          print("""DONE"""    )




def   _A					(	_a	:						Any     ,   _a	:						List[str]				):



      """simple docstring"""






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

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

      A				  =		joblib.load(os.path.join(_UpperCAmelCase     ,   """args.joblib"""				)				)
      A				  =		joblib.load(os.path.join(_UpperCAmelCase     ,   """data_collator.joblib"""				)				)

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

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



def   _A					(	_a	:						Union[str, Any]     ,   _a	:						Optional[Any]     ,   _a	:						str     ,   _a	:						Tuple				):



      """simple docstring"""






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





def   _A					(	_a	:						Any     ,   _a	:						Optional[int]     ,   _a	:						List[Any]     ,   _a	:						Optional[Any]     ,   _a	:						Union[str, Any]				):



      """simple docstring"""






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

      A				  =		scheduler_fn(_UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase     ,   _UpperCAmelCase				)

      A				  =		optax.adamw(learning_rate=_UpperCAmelCase     ,   weight_decay=_UpperCAmelCase     ,   mask=_UpperCAmelCase				)
      return tx, lr









'''simple docstring'''





from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


A__    :   List[str]           =					{
    '''configuration_autoformer''': [
        '''AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''AutoformerConfig''',
    ],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    A__    :   Optional[Any]           =					[
        '''AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
        '''AutoformerForPrediction''',
        '''AutoformerModel''',
        '''AutoformerPreTrainedModel''',
    ]


if TYPE_CHECKING:
    from .configuration_autoformer import (
        AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
        AutoformerConfig,
    )

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_autoformer import (
            AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
            AutoformerForPrediction,
            AutoformerModel,
            AutoformerPreTrainedModel,
        )

else:
    import sys

    A__    :   Optional[int]           =					_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



