






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


							def 						_UpperCamelCase       (			self      :						Union[str, Any]							):
													'''simple docstring'''





													super().setup()
													A__						:  List[Any]		  =  nn.Dense(5			,    dtype=self.dtype							)


							def __call__(			self      :						Optional[int]			,    *snake_case      :						Any			,    **snake_case      :						str							):
													'''simple docstring'''





													A__						:  int		  =  super().__call__(*snake_case			,    **snake_case							)
													A__						:  str		  =  self.cls(outputs[2]							)
													return outputs[:2] + (cls_out,)






class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase		):
							snake_case_     =							FlaxBigBirdForNaturalQuestionsModule




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

						A__						:  Tuple		  =  partial(UpperCAmelCase__,						reduction=jnp.mean      )
						A__						:  Tuple		  =  cross_entropy(UpperCAmelCase__,						UpperCAmelCase__      )
						A__						:  List[str]		  =  cross_entropy(UpperCAmelCase__,						UpperCAmelCase__      )
						A__						:  List[Any]		  =  cross_entropy(UpperCAmelCase__,						UpperCAmelCase__      )
						return (start_loss + end_loss + pooled_loss) / 3






@dataclass
class 							__SCREAMING_SNAKE_CASE						:
							snake_case_     =							"google/bigbird-roberta-base"
							snake_case_     =							3000
							snake_case_     =							10500

							snake_case_     =							128
							snake_case_     =							3

							snake_case_     =							1
							snake_case_     =							5

							# tx_args
							snake_case_     =							3E-5
							snake_case_     =							0.0
							snake_case_     =							20000
							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 						_UpperCamelCase       (			self      :						str							):
													'''simple docstring'''





													os.makedirs(self.base_dir			,    exist_ok=snake_case							)
													A__						:  str		  =  os.path.join(self.base_dir			,    self.save_dir							)
													A__						:  Optional[int]		  =  self.batch_size_per_device * jax.device_count()






@dataclass
class 							__SCREAMING_SNAKE_CASE						:
							snake_case_     =							42
							snake_case_     =							4096  # no dynamic padding on TPUs


							def __call__(			self      :						str			,    snake_case      :						Dict							):
													'''simple docstring'''





													A__						:  Optional[int]		  =  self.collate_fn(snake_case							)
													A__						:  List[Any]		  =  jax.tree_util.tree_map(snake_case			,    snake_case							)
													return batch


							def 						_UpperCamelCase       (			self      :						int			,    snake_case      :						Optional[Any]							):
													'''simple docstring'''





													A__  ,  A__						:  Union[str, Any]		  =  self.fetch_inputs(features["""input_ids"""]							)
													A__						:  Union[str, 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 						_UpperCamelCase       (			self      :						Optional[Any]			,    snake_case      :						list							):
													'''simple docstring'''





													A__						:  str		  =  [self._fetch_inputs(snake_case							) for ids in input_ids]
													return zip(*snake_case							)


							def 						_UpperCamelCase       (			self      :						Union[str, Any]			,    snake_case      :						list							):
													'''simple docstring'''





													A__						:  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      _lowerCAmelCase		(							UpperCAmelCase__       :					List[Any],						UpperCAmelCase__       :					Optional[Any],						UpperCAmelCase__       :					List[str]=None      )		->Dict:
						if seed is not None:
												A__						:  Optional[int]		  =  dataset.shuffle(seed=UpperCAmelCase__      )
						for i in range(len(UpperCAmelCase__      ) // batch_size      ):
												A__						:  List[str]		  =  dataset[i * batch_size : (i + 1) * batch_size]
												yield dict(UpperCAmelCase__      )




@partial(jax.pmap,						axis_name="""batch"""      )
def      _lowerCAmelCase		(							UpperCAmelCase__       :					Dict,						UpperCAmelCase__       :					Optional[Any],						**UpperCAmelCase__       :					str      )		->Dict:
						def loss_fn(UpperCAmelCase__       :					Union[str, Any]      ):
												A__						:  Any		  =  model_inputs.pop("""start_labels"""      )
												A__						:  int		  =  model_inputs.pop("""end_labels"""      )
												A__						:  Any		  =  model_inputs.pop("""pooled_labels"""      )

												A__						:  List[Any]		  =  state.apply_fn(**UpperCAmelCase__,						params=UpperCAmelCase__,						dropout_rng=UpperCAmelCase__,						train=UpperCAmelCase__      )
												A__  ,  A__  ,  A__						:  List[str]		  =  outputs

												return state.loss_fn(
												    UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__,						)

						A__  ,  A__						:  Optional[int]		  =  jax.random.split(UpperCAmelCase__      )
						A__						:  Optional[Any]		  =  jax.value_and_grad(UpperCAmelCase__      )
						A__  ,  A__						:  Union[str, Any]		  =  grad_fn(state.params      )
						A__						:  Dict		  =  jax.lax.pmean({"""loss""": loss},						axis_name="""batch"""      )
						A__						:  int		  =  jax.lax.pmean(UpperCAmelCase__,						"""batch"""      )

						A__						:  Any		  =  state.apply_gradients(grads=UpperCAmelCase__      )
						return state, metrics, new_drp_rng




@partial(jax.pmap,						axis_name="""batch"""      )
def      _lowerCAmelCase		(							UpperCAmelCase__       :					Optional[int],						**UpperCAmelCase__       :					List[str]      )		->Optional[Any]:
						A__						:  Any		  =  model_inputs.pop("""start_labels"""      )
						A__						:  Tuple		  =  model_inputs.pop("""end_labels"""      )
						A__						:  str		  =  model_inputs.pop("""pooled_labels"""      )

						A__						:  Dict		  =  state.apply_fn(**UpperCAmelCase__,						params=state.params,						train=UpperCAmelCase__      )
						A__  ,  A__  ,  A__						:  str		  =  outputs

						A__						:  Union[str, Any]		  =  state.loss_fn(UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__      )
						A__						:  Optional[int]		  =  jax.lax.pmean({"""loss""": loss},						axis_name="""batch"""      )
						return metrics






class 							__SCREAMING_SNAKE_CASE						(				train_state.TrainState		):
							snake_case_     =							struct.field(pytree_node=UpperCamelCase		)






@dataclass
class 							__SCREAMING_SNAKE_CASE						:
							snake_case_     =							42
							snake_case_     =							42
							snake_case_     =							42
							snake_case_     =							42
							snake_case_     =							42
							snake_case_     =							42
							snake_case_     =							None


							def 						_UpperCamelCase       (			self      :						Optional[int]			,    snake_case      :						Optional[Any]			,    snake_case      :						str			,    snake_case      :						int			,    snake_case      :						int=None							):
													'''simple docstring'''





													A__						:  Tuple		  =  model.params
													A__						:  Dict		  =  TrainState.create(
													    apply_fn=model.__call__			,    params=snake_case			,    tx=snake_case			,    loss_fn=snake_case			,    )
													if ckpt_dir is not None:
																			A__  ,  A__  ,  A__  ,  A__  ,  A__						:  str		  =  restore_checkpoint(snake_case			,    snake_case							)
																			A__						:  Dict		  =  {
																			    """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__						:  int		  =  build_tx(**snake_case							)
																			A__						:  Tuple		  =  train_state.TrainState(
																			    step=snake_case			,    apply_fn=model.__call__			,    params=snake_case			,    tx=snake_case			,    opt_state=snake_case			,    )
																			A__						:  Union[str, Any]		  =  args
																			A__						:  Any		  =  data_collator
																			A__						:  Any		  =  lr
																			A__						:  Dict		  =  params
													A__						:  Union[str, Any]		  =  jax_utils.replicate(snake_case							)
													return state


							def 						_UpperCamelCase       (			self      :						Optional[Any]			,    snake_case      :						Dict			,    snake_case      :						Union[str, Any]			,    snake_case      :						int							):
													'''simple docstring'''





													A__						:  Tuple		  =  self.args
													A__						:  List[str]		  =  len(snake_case							) // args.batch_size

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

																															A__						:  str		  =  self.evaluate(snake_case			,    snake_case							)
																															A__						:  List[str]		  =  {
																															    """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 						_UpperCamelCase       (			self      :						Union[str, Any]			,    snake_case      :						List[Any]			,    snake_case      :						Optional[Any]							):
													'''simple docstring'''





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


							def 						_UpperCamelCase       (			self      :						List[Any]			,    snake_case      :						Any			,    snake_case      :						str							):
													'''simple docstring'''





													A__						:  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      _lowerCAmelCase		(							UpperCAmelCase__       :					List[str],						UpperCAmelCase__       :					Dict      )		->List[Any]:
						print(f'RESTORING CHECKPOINT FROM {save_dir}',						end=""" ... """      )
						with open(os.path.join(UpperCAmelCase__,						"""flax_model.msgpack"""      ),						"""rb"""      ) as f:
												A__						:  Optional[Any]		  =  from_bytes(state.params,						f.read()      )

						with open(os.path.join(UpperCAmelCase__,						"""opt_state.msgpack"""      ),						"""rb"""      ) as f:
												A__						:  Optional[Any]		  =  from_bytes(state.opt_state,						f.read()      )

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

						with open(os.path.join(UpperCAmelCase__,						"""training_state.json"""      ),						"""r"""      ) as f:
												A__						:  Optional[Any]		  =  json.load(UpperCAmelCase__      )
						A__						:  Union[str, Any]		  =  training_state["""step"""]

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




def      _lowerCAmelCase		(							UpperCAmelCase__       :					str,						UpperCAmelCase__       :					List[str],						UpperCAmelCase__       :					Any,						UpperCAmelCase__       :					List[str]      )		->Optional[Any]:
						A__						:  List[Any]		  =  num_train_steps - warmup_steps
						A__						:  Tuple		  =  optax.linear_schedule(init_value=UpperCAmelCase__,						end_value=UpperCAmelCase__,						transition_steps=UpperCAmelCase__      )
						A__						:  Union[str, Any]		  =  optax.linear_schedule(init_value=UpperCAmelCase__,						end_value=1e-7,						transition_steps=UpperCAmelCase__      )
						A__						:  List[str]		  =  optax.join_schedules(schedules=[warmup_fn, decay_fn],						boundaries=[warmup_steps]      )
						return lr




def      _lowerCAmelCase		(							UpperCAmelCase__       :					List[str],						UpperCAmelCase__       :					Tuple,						UpperCAmelCase__       :					List[Any],						UpperCAmelCase__       :					Union[str, Any],						UpperCAmelCase__       :					List[str]      )		->Optional[Any]:
						def weight_decay_mask(UpperCAmelCase__       :					List[str]      ):
												A__						:  Union[str, Any]		  =  traverse_util.flatten_dict(UpperCAmelCase__      )
												A__						:  Dict		  =  {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()}
												return traverse_util.unflatten_dict(UpperCAmelCase__      )

						A__						:  int		  =  scheduler_fn(UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__,						UpperCAmelCase__      )

						A__						:  str		  =  optax.adamw(learning_rate=UpperCAmelCase__,						weight_decay=UpperCAmelCase__,						mask=UpperCAmelCase__      )
						return tx, lr














"""simple docstring"""



from ...configuration_utils import PretrainedConfig
from ...utils import logging


A_    =							logging.get_logger(__name__)

A_    =							{
    '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''',
}






class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase		):
							snake_case_     =							'roc_bert'


							def __init__(			self      :						Tuple			,    snake_case      :						Union[str, Any]=3_0522			,    snake_case      :						Optional[Any]=768			,    snake_case      :						Any=12			,    snake_case      :						Tuple=12			,    snake_case      :						Any=3072			,    snake_case      :						Tuple="gelu"			,    snake_case      :						Optional[int]=0.1			,    snake_case      :						List[str]=0.1			,    snake_case      :						List[str]=512			,    snake_case      :						int=2			,    snake_case      :						Optional[Any]=0.02			,    snake_case      :						str=1e-12			,    snake_case      :						int=True			,    snake_case      :						Optional[Any]=0			,    snake_case      :						str="absolute"			,    snake_case      :						int=None			,    snake_case      :						int=True			,    snake_case      :						Optional[int]=True			,    snake_case      :						List[Any]=768			,    snake_case      :						Dict=910			,    snake_case      :						Tuple=512			,    snake_case      :						Tuple=2_4858			,    snake_case      :						Optional[Any]=True			,    **snake_case      :						Any			,    ):
													'''simple docstring'''





													A__						:  Optional[Any]		  =  vocab_size
													A__						:  Union[str, Any]		  =  max_position_embeddings
													A__						:  Any		  =  hidden_size
													A__						:  Optional[int]		  =  num_hidden_layers
													A__						:  Optional[Any]		  =  num_attention_heads
													A__						:  int		  =  intermediate_size
													A__						:  Optional[Any]		  =  hidden_act
													A__						:  Any		  =  hidden_dropout_prob
													A__						:  Tuple		  =  attention_probs_dropout_prob
													A__						:  Union[str, Any]		  =  initializer_range
													A__						:  str		  =  type_vocab_size
													A__						:  Any		  =  layer_norm_eps
													A__						:  List[str]		  =  use_cache
													A__						:  List[str]		  =  enable_pronunciation
													A__						:  int		  =  enable_shape
													A__						:  Tuple		  =  pronunciation_embed_dim
													A__						:  str		  =  pronunciation_vocab_size
													A__						:  Optional[Any]		  =  shape_embed_dim
													A__						:  str		  =  shape_vocab_size
													A__						:  List[str]		  =  concat_input
													A__						:  str		  =  position_embedding_type
													A__						:  str		  =  classifier_dropout
													super().__init__(pad_token_id=snake_case			,    **snake_case							)






