


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 (					UpperCamelCase			):




       """simple docstring"""
       snake_case      =    42
       snake_case      =    jnp.floataa
       snake_case      =    True



       def        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





         super().setup()
         A_      :				Tuple		     =					nn.Dense(5				,       dtype=self.dtype		)







       def __call__(      self				,       *_SCREAMING_SNAKE_CASE				,       **_SCREAMING_SNAKE_CASE		)->List[Any]:




         '''simple docstring'''





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






class   _lowerCamelCase (					UpperCamelCase			):




       """simple docstring"""
       snake_case      =    FlaxBigBirdForNaturalQuestionsModule




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

  A_      :				int		     =					partial(SCREAMING_SNAKE_CASE ,			reduction=jnp.mean       )
  A_      :				Dict		     =					cross_entropy(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       )
  A_      :				List[str]		     =					cross_entropy(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       )
  A_      :				Union[str, Any]		     =					cross_entropy(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       )
  return (start_loss + end_loss + pooled_loss) / 3






@dataclass
class   _lowerCamelCase :




       """simple docstring"""
       snake_case      =    "google/bigbird-roberta-base"
       snake_case      =    3_000
       snake_case      =    10_500

       snake_case      =    128
       snake_case      =    3

       snake_case      =    1
       snake_case      =    5

       # tx_args
       snake_case      =    3e-5
       snake_case      =    0.0
       snake_case      =    20_000
       snake_case      =    0.0_0_9_5

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



       def        _snake_case       (      self		)->Any:




         '''simple docstring'''





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






@dataclass
class   _lowerCamelCase :




       """simple docstring"""
       snake_case      =    42
       snake_case      =    4_096  # no dynamic padding on TPUs



       def __call__(      self				,       _SCREAMING_SNAKE_CASE		)->List[str]:




         '''simple docstring'''





         A_      :				Dict		     =					self.collate_fn(_SCREAMING_SNAKE_CASE		)
         A_      :				Union[str, Any]		     =					jax.tree_util.tree_map(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)
         return batch



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE		)->List[Any]:




         '''simple docstring'''





         A_     ,       A_      :				List[str]		     =					self.fetch_inputs(features['''input_ids''']		)
         A_      :				Dict		     =					{
             '''input_ids''': jnp.array(_SCREAMING_SNAKE_CASE				,       dtype=jnp.intaa		),
             '''attention_mask''': jnp.array(_SCREAMING_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        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE		)->Optional[Any]:




         '''simple docstring'''





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







       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE		)->Union[str, Any]:




         '''simple docstring'''





         A_      :				Dict		     =					[1 for _ in range(len(_SCREAMING_SNAKE_CASE		)		)]
         while len(_SCREAMING_SNAKE_CASE		) < self.max_length:
           input_ids.append(self.pad_id		)
           attention_mask.append(0		)
         return input_ids, attention_mask




def   _SCREAMING_SNAKE_CASE	( SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE=None       ):
  if seed is not None:
    A_      :				str		     =					dataset.shuffle(seed=SCREAMING_SNAKE_CASE       )
  for i in range(len(SCREAMING_SNAKE_CASE       ) // batch_size       ):
    A_      :				Optional[Any]		     =					dataset[i * batch_size : (i + 1) * batch_size]
    yield dict(SCREAMING_SNAKE_CASE       )


@partial(jax.pmap ,			axis_name='''batch'''       )
def   _SCREAMING_SNAKE_CASE	( SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			**SCREAMING_SNAKE_CASE       ):
  def loss_fn(SCREAMING_SNAKE_CASE       ):
    A_      :				Tuple		     =					model_inputs.pop('''start_labels'''       )
    A_      :				List[Any]		     =					model_inputs.pop('''end_labels'''       )
    A_      :				List[str]		     =					model_inputs.pop('''pooled_labels'''       )

    A_      :				Union[str, Any]		     =					state.apply_fn(**SCREAMING_SNAKE_CASE ,			params=SCREAMING_SNAKE_CASE ,			dropout_rng=SCREAMING_SNAKE_CASE ,			train=SCREAMING_SNAKE_CASE       )
    A_     ,       A_     ,       A_      :				Any		     =					outputs

    return state.loss_fn(
        SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			)

  A_     ,       A_      :				int		     =					jax.random.split(SCREAMING_SNAKE_CASE       )
  A_      :				str		     =					jax.value_and_grad(SCREAMING_SNAKE_CASE       )
  A_     ,       A_      :				Union[str, Any]		     =					grad_fn(state.params       )
  A_      :				Tuple		     =					jax.lax.pmean({'''loss''': loss} ,			axis_name='''batch'''       )
  A_      :				Dict		     =					jax.lax.pmean(SCREAMING_SNAKE_CASE ,			'''batch'''       )

  A_      :				Dict		     =					state.apply_gradients(grads=SCREAMING_SNAKE_CASE       )
  return state, metrics, new_drp_rng


@partial(jax.pmap ,			axis_name='''batch'''       )
def   _SCREAMING_SNAKE_CASE	( SCREAMING_SNAKE_CASE ,			**SCREAMING_SNAKE_CASE       ):
  A_      :				List[str]		     =					model_inputs.pop('''start_labels'''       )
  A_      :				int		     =					model_inputs.pop('''end_labels'''       )
  A_      :				Any		     =					model_inputs.pop('''pooled_labels'''       )

  A_      :				Dict		     =					state.apply_fn(**SCREAMING_SNAKE_CASE ,			params=state.params ,			train=SCREAMING_SNAKE_CASE       )
  A_     ,       A_     ,       A_      :				Optional[int]		     =					outputs

  A_      :				Union[str, Any]		     =					state.loss_fn(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       )
  A_      :				int		     =					jax.lax.pmean({'''loss''': loss} ,			axis_name='''batch'''       )
  return metrics






class   _lowerCamelCase (					train_state.TrainState			):




       """simple docstring"""
       snake_case      =    struct.field(pytree_node=UpperCamelCase			)






@dataclass
class   _lowerCamelCase :




       """simple docstring"""
       snake_case      =    42
       snake_case      =    42
       snake_case      =    42
       snake_case      =    42
       snake_case      =    42
       snake_case      =    42
       snake_case      =    None



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE=None		)->int:




         '''simple docstring'''





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



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)->Optional[Any]:




         '''simple docstring'''





         A_      :				str		     =					self.args
         A_      :				Optional[int]		     =					len(_SCREAMING_SNAKE_CASE		) // args.batch_size

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

               A_      :				Optional[int]		     =					self.evaluate(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)
               A_      :				Optional[Any]		     =					{
                   '''step''': state_step.item(),
                   '''eval_loss''': eval_loss.item(),
                   '''tr_loss''': tr_loss,
                   '''lr''': lr.item(),
               }
               tqdm.write(str(_SCREAMING_SNAKE_CASE		)		)
               self.logger.log(_SCREAMING_SNAKE_CASE				,       commit=_SCREAMING_SNAKE_CASE		)

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



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)->List[Any]:




         '''simple docstring'''





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







       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		)->Optional[int]:




         '''simple docstring'''





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




def   _SCREAMING_SNAKE_CASE	( SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       ):
  print(f'''RESTORING CHECKPOINT FROM {save_dir}''' ,			end=''' ... '''       )
  with open(os.path.join(SCREAMING_SNAKE_CASE ,			'''flax_model.msgpack'''       ) ,			'''rb'''       ) as f:
    A_      :				Optional[Any]		     =					from_bytes(state.params ,			f.read()       )

  with open(os.path.join(SCREAMING_SNAKE_CASE ,			'''opt_state.msgpack'''       ) ,			'''rb'''       ) as f:
    A_      :				List[str]		     =					from_bytes(state.opt_state ,			f.read()       )

  A_      :				Optional[int]		     =					joblib.load(os.path.join(SCREAMING_SNAKE_CASE ,			'''args.joblib'''       )       )
  A_      :				Dict		     =					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:
    A_      :				str		     =					json.load(SCREAMING_SNAKE_CASE       )
  A_      :				Optional[Any]		     =					training_state['''step''']

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


def   _SCREAMING_SNAKE_CASE	( SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       ):
  A_      :				Union[str, Any]		     =					num_train_steps - warmup_steps
  A_      :				Union[str, Any]		     =					optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE ,			end_value=SCREAMING_SNAKE_CASE ,			transition_steps=SCREAMING_SNAKE_CASE       )
  A_      :				Optional[int]		     =					optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE ,			end_value=1e-7 ,			transition_steps=SCREAMING_SNAKE_CASE       )
  A_      :				List[str]		     =					optax.join_schedules(schedules=[warmup_fn, decay_fn] ,			boundaries=[warmup_steps]       )
  return lr







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

  A_      :				Any		     =					scheduler_fn(SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE ,			SCREAMING_SNAKE_CASE       )

  A_      :				Optional[int]		     =					optax.adamw(learning_rate=SCREAMING_SNAKE_CASE ,			weight_decay=SCREAMING_SNAKE_CASE ,			mask=SCREAMING_SNAKE_CASE       )
  return tx, lr








from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


UpperCamelCase								=	{
    """configuration_nezha""": ["""NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NezhaConfig"""],
}

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase								=	[
         """NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """NezhaForNextSentencePrediction""",
         """NezhaForMaskedLM""",
         """NezhaForPreTraining""",
         """NezhaForMultipleChoice""",
         """NezhaForQuestionAnswering""",
         """NezhaForSequenceClassification""",
         """NezhaForTokenClassification""",
         """NezhaModel""",
         """NezhaPreTrainedModel""",
     ]


if TYPE_CHECKING:
     from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_nezha import (
              NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST,
              NezhaForMaskedLM,
              NezhaForMultipleChoice,
              NezhaForNextSentencePrediction,
              NezhaForPreTraining,
              NezhaForQuestionAnswering,
              NezhaForSequenceClassification,
              NezhaForTokenClassification,
              NezhaModel,
              NezhaPreTrainedModel,
          )


else:
     import sys

     UpperCamelCase								=	_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




