



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   lowercase_   (  __lowercase					):
      UpperCamelCase_      :		BigBirdConfig
      UpperCamelCase_      :		jnp.dtype										=    jnp.floataa
      UpperCamelCase_      :		bool										=    True



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







      def __call__(      self				:    List[Any]      , *A__				:    str      , **A__				:    List[Any]		)   ->					Union[str, Any]:
        _snake_case						=							super().__call__(*A__      , **A__		)
        _snake_case						=							self.cls(outputs[2]		)
        return outputs[:2] + (cls_out,)



class   lowercase_   (  __lowercase					):
      UpperCamelCase_      :		Tuple										=    FlaxBigBirdForNaturalQuestionsModule



def 				snake_case_(_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase					)							->     Tuple:



  """simple docstring"""






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

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



@dataclass
class   lowercase_   :
      UpperCamelCase_      :		str										=    "google/bigbird-roberta-base"
      UpperCamelCase_      :		int										=    3_0_0_0
      UpperCamelCase_      :		int										=    1_0_5_0_0

      UpperCamelCase_      :		int										=    1_2_8
      UpperCamelCase_      :		int										=    3

      UpperCamelCase_      :		int										=    1
      UpperCamelCase_      :		int										=    5

      # tx_args
      UpperCamelCase_      :		float										=    3E-5
      UpperCamelCase_      :		float										=    0.0
      UpperCamelCase_      :		int										=    2_0_0_0_0
      UpperCamelCase_      :		float										=    0.0_095

      UpperCamelCase_      :		str										=    "bigbird-roberta-natural-questions"
      UpperCamelCase_      :		str										=    "training-expt"
      UpperCamelCase_      :		str										=    "data/nq-training.jsonl"
      UpperCamelCase_      :		str										=    "data/nq-validation.jsonl"



      def 						UpperCamelCase_		(      self				:    List[Any]		)   ->					Tuple:
        os.makedirs(self.base_dir      , exist_ok=A__		)
        _snake_case						=							os.path.join(self.base_dir      , self.save_dir		)
        _snake_case						=							self.batch_size_per_device * jax.device_count()



@dataclass
class   lowercase_   :
      UpperCamelCase_      :		int
      UpperCamelCase_      :		int										=    4_0_9_6  # no dynamic padding on TPUs



      def __call__(      self				:    Dict      , A__				:    Optional[Any]		)   ->					Optional[Any]:
        _snake_case						=							self.collate_fn(A__		)
        _snake_case						=							jax.tree_util.tree_map(A__      , A__		)
        return batch



      def 						UpperCamelCase_		(      self				:    Dict      , A__				:    str		)   ->					List[str]:
        _snake_case,					_snake_case						=							self.fetch_inputs(features['''input_ids''']		)
        _snake_case						=							{
            '''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				:    str      , A__				:    list		)   ->					Tuple:
        _snake_case						=							[self._fetch_inputs(A__		) for ids in input_ids]
        return zip(*A__		)







      def 						UpperCamelCase_		(      self				:    Optional[Any]      , A__				:    list		)   ->					Dict:
        _snake_case						=							[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 				snake_case_(_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase=None					)							->     Optional[Any]:



  """simple docstring"""






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



@partial(jax.pmap			,	axis_name='''batch'''					)
def 				snake_case_(_UpperCamelCase			,	_UpperCamelCase			,	**_UpperCamelCase					)							->     Any:



  """simple docstring"""






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

    _snake_case						=							state.apply_fn(**_UpperCamelCase			,	params=_UpperCamelCase			,	dropout_rng=_UpperCamelCase			,	train=_UpperCamelCase					)
    _snake_case,					_snake_case,					_snake_case						=							outputs

    return state.loss_fn(
        _UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	)

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

  _snake_case						=							state.apply_gradients(grads=_UpperCamelCase					)
  return state, metrics, new_drp_rng



@partial(jax.pmap			,	axis_name='''batch'''					)
def 				snake_case_(_UpperCamelCase			,	**_UpperCamelCase					)							->     Any:



  """simple docstring"""






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

  _snake_case						=							state.apply_fn(**_UpperCamelCase			,	params=state.params			,	train=_UpperCamelCase					)
  _snake_case,					_snake_case,					_snake_case						=							outputs

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



class   lowercase_   (  train_state.TrainState					):
      UpperCamelCase_      :		Callable										=    struct.field(pytree_node=__lowercase					)



@dataclass
class   lowercase_   :
      UpperCamelCase_      :		Args
      UpperCamelCase_      :		Callable
      UpperCamelCase_      :		Callable
      UpperCamelCase_      :		Callable
      UpperCamelCase_      :		Callable
      UpperCamelCase_      :		wandb
      UpperCamelCase_      :		Callable										=    None



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



      def 						UpperCamelCase_		(      self				:    Union[str, Any]      , A__				:    List[str]      , A__				:    str      , A__				:    int		)   ->					Tuple:
        _snake_case						=							self.args
        _snake_case						=							len(A__		) // args.batch_size

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

              _snake_case						=							self.evaluate(A__      , A__		)
              _snake_case						=							{
                  '''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				:    int      , A__				:    List[str]      , A__				:    List[Any]		)   ->					Tuple:
        _snake_case						=							get_batched_dataset(A__      , self.args.batch_size		)
        _snake_case						=							len(A__		) // self.args.batch_size
        _snake_case						=							jnp.array(0      , dtype=jnp.floataa		)
        _snake_case						=							0
        for batch in tqdm(A__      , total=A__      , desc='''Evaluating ... '''		):
          _snake_case						=							self.data_collator(A__		)
          _snake_case						=							self.val_step_fn(A__      , **A__		)
          running_loss += jax_utils.unreplicate(metrics['''loss''']		)
          i += 1
        return running_loss / i







      def 						UpperCamelCase_		(      self				:    int      , A__				:    Dict      , A__				:    Tuple		)   ->					List[Any]:
        _snake_case						=							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 				snake_case_(_UpperCamelCase			,	_UpperCamelCase					)							->     List[str]:



  """simple docstring"""






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

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

  _snake_case						=							joblib.load(os.path.join(_UpperCamelCase			,	'''args.joblib'''					)					)
  _snake_case						=							joblib.load(os.path.join(_UpperCamelCase			,	'''data_collator.joblib'''					)					)

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

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



def 				snake_case_(_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase					)							->     List[Any]:



  """simple docstring"""






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



def 				snake_case_(_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase					)							->     Union[str, Any]:



  """simple docstring"""






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

  _snake_case						=							scheduler_fn(_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase			,	_UpperCamelCase					)

  _snake_case						=							optax.adamw(learning_rate=_UpperCamelCase			,	weight_decay=_UpperCamelCase			,	mask=_UpperCamelCase					)
  return tx, lr




# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

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


__A      		=     {'''configuration_mra''': ['''MRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MraConfig''']}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __A      		=     [
     '''MRA_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''MraForMaskedLM''',
     '''MraForMultipleChoice''',
     '''MraForQuestionAnswering''',
     '''MraForSequenceClassification''',
     '''MraForTokenClassification''',
     '''MraLayer''',
     '''MraModel''',
     '''MraPreTrainedModel''',
 ]


if TYPE_CHECKING:
 from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_mra import (
      MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
      MraForMaskedLM,
      MraForMultipleChoice,
      MraForQuestionAnswering,
      MraForSequenceClassification,
      MraForTokenClassification,
      MraLayer,
      MraModel,
      MraPreTrainedModel,
  )
else:
 import sys

 __A      		=     _LazyModule(__name__, globals()['''__file__'''], _import_structure)

