



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   (      A						):
			UpperCamelCase        =					42
			UpperCamelCase        =					jnp.floataa
			UpperCamelCase        =					True



			def    _lowerCamelCase	(						self       :  Tuple)       ->   List[str]:



						"""simple docstring"""






						super().setup()
						_UpperCAmelCase			=       nn.Dense(5			,		dtype=self.dtype)



			def __call__(						self       :  str			,		*A       :  Tuple			,		**A       :  Dict)       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       super().__call__(*A			,		**A)
						_UpperCAmelCase			=       self.cls(outputs[2])
						return outputs[:2] + (cls_out,)







class       __lowerCAmelCase   (      A						):
			UpperCamelCase        =					FlaxBigBirdForNaturalQuestionsModule





def 							A     (					_UpperCAmelCase    :       Optional[Any]							,       _UpperCAmelCase    :       List[str]							,       _UpperCAmelCase    :       List[str]							,       _UpperCAmelCase    :       Dict							,       _UpperCAmelCase    :       Dict							,       _UpperCAmelCase    :       Union[str, Any]   )    ->			int:







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

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







@dataclass
class       __lowerCAmelCase   :
			UpperCamelCase        =					"google/bigbird-roberta-base"
			UpperCamelCase        =					3_0_0_0
			UpperCamelCase        =					1_0_5_0_0

			UpperCamelCase        =					1_2_8
			UpperCamelCase        =					3

			UpperCamelCase        =					1
			UpperCamelCase        =					5

			# tx_args
			UpperCamelCase        =					3e-5
			UpperCamelCase        =					0.0
			UpperCamelCase        =					2_0_0_0_0
			UpperCamelCase        =					0.0_095

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



			def    _lowerCamelCase	(						self       :  Tuple)       ->   str:



						"""simple docstring"""






						os.makedirs(self.base_dir			,		exist_ok=A)
						_UpperCAmelCase			=       os.path.join(self.base_dir			,		self.save_dir)
						_UpperCAmelCase			=       self.batch_size_per_device * jax.device_count()







@dataclass
class       __lowerCAmelCase   :
			UpperCamelCase        =					42
			UpperCamelCase        =					4_0_9_6  # no dynamic padding on TPUs



			def __call__(						self       :  Optional[int]			,		A       :  int)       ->   int:



						"""simple docstring"""






						_UpperCAmelCase			=       self.collate_fn(A)
						_UpperCAmelCase			=       jax.tree_util.tree_map(A			,		A)
						return batch



			def    _lowerCamelCase	(						self       :  Any			,		A       :  List[str])       ->   List[str]:



						"""simple docstring"""






						_UpperCAmelCase	,					_UpperCAmelCase			=       self.fetch_inputs(features['input_ids'])
						_UpperCAmelCase			=       {
						    '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    _lowerCamelCase	(						self       :  Any			,		A       :  list)       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       [self._fetch_inputs(A) for ids in input_ids]
						return zip(*A)



			def    _lowerCamelCase	(						self       :  str			,		A       :  list)       ->   List[str]:



						"""simple docstring"""






						_UpperCAmelCase			=       [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     (					_UpperCAmelCase    :       Union[str, Any]							,       _UpperCAmelCase    :       List[Any]							,       _UpperCAmelCase    :       List[Any]=None   )    ->			Dict:







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





@partial(jax.pmap							,       axis_name='batch'   )
def 							A     (					_UpperCAmelCase    :       str							,       _UpperCAmelCase    :       int							,       **_UpperCAmelCase    :       Dict   )    ->			int:







			'''simple docstring'''
			def loss_fn(_UpperCAmelCase    :       str   ):
						_UpperCAmelCase			=       model_inputs.pop('start_labels'   )
						_UpperCAmelCase			=       model_inputs.pop('end_labels'   )
						_UpperCAmelCase			=       model_inputs.pop('pooled_labels'   )

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

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

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

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





@partial(jax.pmap							,       axis_name='batch'   )
def 							A     (					_UpperCAmelCase    :       Union[str, Any]							,       **_UpperCAmelCase    :       List[Any]   )    ->			str:







			'''simple docstring'''
			_UpperCAmelCase			=       model_inputs.pop('start_labels'   )
			_UpperCAmelCase			=       model_inputs.pop('end_labels'   )
			_UpperCAmelCase			=       model_inputs.pop('pooled_labels'   )

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

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







class       __lowerCAmelCase   (      train_state.TrainState						):
			UpperCamelCase        =					struct.field(pytree_node=A						)







@dataclass
class       __lowerCAmelCase   :
			UpperCamelCase        =					42
			UpperCamelCase        =					42
			UpperCamelCase        =					42
			UpperCamelCase        =					42
			UpperCamelCase        =					42
			UpperCamelCase        =					42
			UpperCamelCase        =					None



			def    _lowerCamelCase	(						self       :  str			,		A       :  int			,		A       :  Optional[Any]			,		A       :  List[str]			,		A       :  int=None)       ->   Dict:



						"""simple docstring"""






						_UpperCAmelCase			=       model.params
						_UpperCAmelCase			=       TrainState.create(
						    apply_fn=model.__call__			,		params=A			,		tx=A			,		loss_fn=A			,		)
						if ckpt_dir is not None:
									_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase			=       restore_checkpoint(A			,		A)
									_UpperCAmelCase			=       {
									    'lr': args.lr,
									    'init_lr': args.init_lr,
									    'warmup_steps': args.warmup_steps,
									    'num_train_steps': num_train_steps,
									    'weight_decay': args.weight_decay,
									}
									_UpperCAmelCase	,					_UpperCAmelCase			=       build_tx(**A)
									_UpperCAmelCase			=       train_state.TrainState(
									    step=A			,		apply_fn=model.__call__			,		params=A			,		tx=A			,		opt_state=A			,		)
									_UpperCAmelCase			=       args
									_UpperCAmelCase			=       data_collator
									_UpperCAmelCase			=       lr
									_UpperCAmelCase			=       params
						_UpperCAmelCase			=       jax_utils.replicate(A)
						return state



			def    _lowerCamelCase	(						self       :  Union[str, Any]			,		A       :  int			,		A       :  Any			,		A       :  Dict)       ->   List[str]:



						"""simple docstring"""






						_UpperCAmelCase			=       self.args
						_UpperCAmelCase			=       len(A) // args.batch_size

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

															_UpperCAmelCase			=       self.evaluate(A			,		A)
															_UpperCAmelCase			=       {
															    '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    _lowerCamelCase	(						self       :  Union[str, Any]			,		A       :  Tuple			,		A       :  Union[str, Any])       ->   Any:



						"""simple docstring"""






						_UpperCAmelCase			=       get_batched_dataset(A			,		self.args.batch_size)
						_UpperCAmelCase			=       len(A) // self.args.batch_size
						_UpperCAmelCase			=       jnp.array(0			,		dtype=jnp.floataa)
						_UpperCAmelCase			=       0
						for batch in tqdm(A			,		total=A			,		desc='Evaluating ... '):
									_UpperCAmelCase			=       self.data_collator(A)
									_UpperCAmelCase			=       self.val_step_fn(A			,		**A)
									running_loss += jax_utils.unreplicate(metrics['loss'])
									i += 1
						return running_loss / i



			def    _lowerCamelCase	(						self       :  List[Any]			,		A       :  Union[str, Any]			,		A       :  Tuple)       ->   Optional[int]:



						"""simple docstring"""






						_UpperCAmelCase			=       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     (					_UpperCAmelCase    :       Tuple							,       _UpperCAmelCase    :       List[Any]   )    ->			Dict:







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

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

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

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

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





def 							A     (					_UpperCAmelCase    :       List[str]							,       _UpperCAmelCase    :       Tuple							,       _UpperCAmelCase    :       List[Any]							,       _UpperCAmelCase    :       int   )    ->			Optional[Any]:







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





def 							A     (					_UpperCAmelCase    :       Union[str, Any]							,       _UpperCAmelCase    :       int							,       _UpperCAmelCase    :       int							,       _UpperCAmelCase    :       Any							,       _UpperCAmelCase    :       List[Any]   )    ->			Tuple:







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

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

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





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCAmelCase__       =	{
    "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"],
    "tokenization_deberta": ["DebertaTokenizer"],
}

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							UpperCAmelCase__       =	["DebertaTokenizerFast"]

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							UpperCAmelCase__       =	[
							    "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST",
							    "DebertaForMaskedLM",
							    "DebertaForQuestionAnswering",
							    "DebertaForSequenceClassification",
							    "DebertaForTokenClassification",
							    "DebertaModel",
							    "DebertaPreTrainedModel",
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							UpperCAmelCase__       =	[
							    "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST",
							    "TFDebertaForMaskedLM",
							    "TFDebertaForQuestionAnswering",
							    "TFDebertaForSequenceClassification",
							    "TFDebertaForTokenClassification",
							    "TFDebertaModel",
							    "TFDebertaPreTrainedModel",
							]


if TYPE_CHECKING:
							from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig
							from .tokenization_deberta import DebertaTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_deberta_fast import DebertaTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_deberta import (
														    DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
														    DebertaForMaskedLM,
														    DebertaForQuestionAnswering,
														    DebertaForSequenceClassification,
														    DebertaForTokenClassification,
														    DebertaModel,
														    DebertaPreTrainedModel,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_tf_deberta import (
														    TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
														    TFDebertaForMaskedLM,
														    TFDebertaForQuestionAnswering,
														    TFDebertaForSequenceClassification,
														    TFDebertaForTokenClassification,
														    TFDebertaModel,
														    TFDebertaPreTrainedModel,
														)


else:
							import sys

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