





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






		'''simple docstring'''






		__a       :       BigBirdConfig
		__a       :       jnp.dtype       =	jnp.floataa
		__a       :       bool       =	True






		def 						snake_case__				(							self  )       -> Optional[Any]:






									"""simple docstring"""
									super().setup()
									lowercase_	:   Dict  				=     nn.Dense(5,   dtype=self.dtype  )






		def __call__(							self,   *snake_case__,   **snake_case__  )       -> Union[str, Any]:






									"""simple docstring"""
									lowercase_	:   List[Any]  				=     super().__call__(*snake_case__,   **snake_case__  )
									lowercase_	:   int  				=     self.cls(outputs[2]  )
									return outputs[:2] + (cls_out,)




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       Tuple       =	FlaxBigBirdForNaturalQuestionsModule





def  __magic_name__  (				lowercase				,       lowercase				,       lowercase				,       lowercase				,       lowercase				,       lowercase				)				-> int:

							"""simple docstring"""



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

							lowercase_	:   Dict  				=     partial(lowercase				,       reduction=jnp.mean				)
							lowercase_	:   Optional[int]  				=     cross_entropy(lowercase				,       lowercase				)
							lowercase_	:   List[Any]  				=     cross_entropy(lowercase				,       lowercase				)
							lowercase_	:   Optional[int]  				=     cross_entropy(lowercase				,       lowercase				)
							return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class     UpperCamelCase__					:






		'''simple docstring'''






		__a       :       str       =	"google/bigbird-roberta-base"
		__a       :       int       =	3_000
		__a       :       int       =	10_500

		__a       :       int       =	128
		__a       :       int       =	3

		__a       :       int       =	1
		__a       :       int       =	5

		# tx_args
		__a       :       float       =	3e-5
		__a       :       float       =	0.0
		__a       :       int       =	20_000
		__a       :       float       =	0.0_0_9_5

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






		def 						snake_case__				(							self  )       -> Optional[Any]:






									"""simple docstring"""
									os.makedirs(self.base_dir,   exist_ok=snake_case__  )
									lowercase_	:   str  				=     os.path.join(self.base_dir,   self.save_dir  )
									lowercase_	:   Optional[Any]  				=     self.batch_size_per_device * jax.device_count()




@dataclass
class     UpperCamelCase__					:






		'''simple docstring'''






		__a       :       int
		__a       :       int       =	4_096  # no dynamic padding on TPUs






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






									"""simple docstring"""
									lowercase_	:   Tuple  				=     self.collate_fn(snake_case__  )
									lowercase_	:   Union[str, Any]  				=     jax.tree_util.tree_map(snake_case__,   snake_case__  )
									return batch






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






									"""simple docstring"""
									lowercase_				,		lowercase_	:   Tuple  				=     self.fetch_inputs(features["""input_ids"""]  )
									lowercase_	:   List[Any]  				=     {
									    """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 						snake_case__				(							self,   snake_case__  )       -> List[Any]:






									"""simple docstring"""
									lowercase_	:   Optional[Any]  				=     [self._fetch_inputs(snake_case__  ) for ids in input_ids]
									return zip(*snake_case__  )






		def 						snake_case__				(							self,   snake_case__  )       -> int:






									"""simple docstring"""
									lowercase_	:   List[str]  				=     [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  __magic_name__  (				lowercase				,       lowercase				,       lowercase=None				)				-> str:

							"""simple docstring"""



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





@partial(jax.pmap				,       axis_name="""batch"""				)
def  __magic_name__  (				lowercase				,       lowercase				,       **lowercase				)				-> Optional[int]:

							"""simple docstring"""



							def loss_fn(lowercase				):
														lowercase_	:   Union[str, Any]  				=     model_inputs.pop("""start_labels"""				)
														lowercase_	:   int  				=     model_inputs.pop("""end_labels"""				)
														lowercase_	:   str  				=     model_inputs.pop("""pooled_labels"""				)

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

														return state.loss_fn(
														    lowercase				,       lowercase				,       lowercase				,       lowercase				,       lowercase				,       lowercase				,       )

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

							lowercase_	:   Union[str, Any]  				=     state.apply_gradients(grads=lowercase				)
							return state, metrics, new_drp_rng





@partial(jax.pmap				,       axis_name="""batch"""				)
def  __magic_name__  (				lowercase				,       **lowercase				)				-> Tuple:

							"""simple docstring"""



							lowercase_	:   Union[str, Any]  				=     model_inputs.pop("""start_labels"""				)
							lowercase_	:   int  				=     model_inputs.pop("""end_labels"""				)
							lowercase_	:   List[str]  				=     model_inputs.pop("""pooled_labels"""				)

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

							lowercase_	:   List[Any]  				=     state.loss_fn(lowercase				,       lowercase				,       lowercase				,       lowercase				,       lowercase				,       lowercase				)
							lowercase_	:   List[Any]  				=     jax.lax.pmean({"""loss""": loss}				,       axis_name="""batch"""				)
							return metrics
class     UpperCamelCase__					(     train_state.TrainState				):






		'''simple docstring'''






		__a       :       Callable       =	struct.field(pytree_node=lowerCamelCase__				)




@dataclass
class     UpperCamelCase__					:






		'''simple docstring'''






		__a       :       Args
		__a       :       Callable
		__a       :       Callable
		__a       :       Callable
		__a       :       Callable
		__a       :       wandb
		__a       :       Callable       =	None






		def 						snake_case__				(							self,   snake_case__,   snake_case__,   snake_case__,   snake_case__=None  )       -> List[Any]:






									"""simple docstring"""
									lowercase_	:   List[Any]  				=     model.params
									lowercase_	:   Tuple  				=     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_	:   Union[str, Any]  				=     restore_checkpoint(snake_case__,   snake_case__  )
																lowercase_	:   Optional[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,
																}
																lowercase_				,		lowercase_	:   Union[str, Any]  				=     build_tx(**snake_case__  )
																lowercase_	:   Optional[Any]  				=     train_state.TrainState(
																    step=snake_case__,   apply_fn=model.__call__,   params=snake_case__,   tx=snake_case__,   opt_state=snake_case__,   )
																lowercase_	:   str  				=     args
																lowercase_	:   Dict  				=     data_collator
																lowercase_	:   Tuple  				=     lr
																lowercase_	:   Any  				=     params
									lowercase_	:   Any  				=     jax_utils.replicate(snake_case__  )
									return state






		def 						snake_case__				(							self,   snake_case__,   snake_case__,   snake_case__  )       -> Tuple:






									"""simple docstring"""
									lowercase_	:   Optional[Any]  				=     self.args
									lowercase_	:   str  				=     len(snake_case__  ) // args.batch_size

									lowercase_	:   List[str]  				=     jax.random.PRNGKey(0  )
									lowercase_	:   List[str]  				=     jax.random.split(snake_case__,   jax.device_count()  )
									for epoch in range(args.max_epochs  ):
																lowercase_	:   List[str]  				=     jnp.array(0,   dtype=jnp.floataa  )
																lowercase_	:   List[str]  				=     get_batched_dataset(snake_case__,   args.batch_size,   seed=snake_case__  )
																lowercase_	:   str  				=     0
																for batch in tqdm(snake_case__,   total=snake_case__,   desc=f"""Running EPOCH-{epoch}"""  ):
																							lowercase_	:   str  				=     self.data_collator(snake_case__  )
																							lowercase_				,		lowercase_				,		lowercase_	:   Any  				=     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_	:   Dict  				=     jax_utils.unreplicate(state.step  )
																														lowercase_	:   List[Any]  				=     running_loss.item() / i
																														lowercase_	:   Dict  				=     self.scheduler_fn(state_step - 1  )

																														lowercase_	:   str  				=     self.evaluate(snake_case__,   snake_case__  )
																														lowercase_	:   int  				=     {
																														    """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 						snake_case__				(							self,   snake_case__,   snake_case__  )       -> Optional[int]:






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






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






									"""simple docstring"""
									lowercase_	:   Optional[int]  				=     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  __magic_name__  (				lowercase				,       lowercase				)				-> Tuple:

							"""simple docstring"""



							print(f"""RESTORING CHECKPOINT FROM {save_dir}"""				,       end=""" ... """				)
							with open(os.path.join(lowercase				,       """flax_model.msgpack"""				)				,       """rb"""				) as f:
														lowercase_	:   Optional[int]  				=     from_bytes(state.params				,       f.read()				)

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

							lowercase_	:   Union[str, Any]  				=     joblib.load(os.path.join(lowercase				,       """args.joblib"""				)				)
							lowercase_	:   int  				=     joblib.load(os.path.join(lowercase				,       """data_collator.joblib"""				)				)

							with open(os.path.join(lowercase				,       """training_state.json"""				)				,       """r"""				) as f:
														lowercase_	:   Dict  				=     json.load(lowercase				)
							lowercase_	:   Tuple  				=     training_state["""step"""]

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





def  __magic_name__  (				lowercase				,       lowercase				,       lowercase				,       lowercase				)				-> Union[str, Any]:

							"""simple docstring"""



							lowercase_	:   Optional[int]  				=     num_train_steps - warmup_steps
							lowercase_	:   Tuple  				=     optax.linear_schedule(init_value=lowercase				,       end_value=lowercase				,       transition_steps=lowercase				)
							lowercase_	:   Optional[Any]  				=     optax.linear_schedule(init_value=lowercase				,       end_value=1E-7				,       transition_steps=lowercase				)
							lowercase_	:   str  				=     optax.join_schedules(schedules=[warmup_fn, decay_fn]				,       boundaries=[warmup_steps]				)
							return lr





def  __magic_name__  (				lowercase				,       lowercase				,       lowercase				,       lowercase				,       lowercase				)				-> Optional[int]:

							"""simple docstring"""



							def weight_decay_mask(lowercase				):
														lowercase_	:   List[str]  				=     traverse_util.flatten_dict(lowercase				)
														lowercase_	:   str  				=     {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()}
														return traverse_util.unflatten_dict(lowercase				)

							lowercase_	:   int  				=     scheduler_fn(lowercase				,       lowercase				,       lowercase				,       lowercase				)

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






from typing import TYPE_CHECKING

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


UpperCAmelCase_							=				{
    """configuration_m2m_100""": ["""M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP""", """M2M100Config""", """M2M100OnnxConfig"""],
    """tokenization_m2m_100""": ["""M2M100Tokenizer"""],
}


try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							UpperCAmelCase_							=				[
							    """M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """M2M100ForConditionalGeneration""",
							    """M2M100Model""",
							    """M2M100PreTrainedModel""",
							]


if TYPE_CHECKING:
							from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig
							from .tokenization_mam_aaa import MaMaaaTokenizer

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_mam_aaa import (
														    M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST,
														    MaMaaaForConditionalGeneration,
														    MaMaaaModel,
														    MaMaaaPreTrainedModel,
														)


else:
							import sys

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