




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







							def      __lowerCAmelCase    (						self :						Any      )    ->							Tuple:


														"""simple docstring"""


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







							def __call__(						self :						Optional[int]							,    *lowerCAmelCase_ :						Optional[int]							,    **lowerCAmelCase_ :						Union[str, Any]      )    ->							List[Any]:


														"""simple docstring"""


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



class     A					(	_a					):
							lowercase_           =       FlaxBigBirdForNaturalQuestionsModule



def 	snake_case_					(UpperCamelCase :						Optional[Any]				,		UpperCamelCase :						Dict				,		UpperCamelCase :						int				,		UpperCamelCase :						Optional[int]				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						Dict   ):





							'''simple docstring'''


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

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

@dataclass
class     A					:
							lowercase_           =       'google/bigbird-roberta-base'
							lowercase_           =       3000
							lowercase_           =       1_0500

							lowercase_           =       128
							lowercase_           =       3

							lowercase_           =       1
							lowercase_           =       5

							# tx_args
							lowercase_           =       3e-5
							lowercase_           =       0.0
							lowercase_           =       2_0000
							lowercase_           =       0.0095

							lowercase_           =       'bigbird-roberta-natural-questions'
							lowercase_           =       'training-expt'
							lowercase_           =       'data/nq-training.jsonl'
							lowercase_           =       'data/nq-validation.jsonl'







							def      __lowerCAmelCase    (						self :						Optional[int]      )    ->							List[str]:


														"""simple docstring"""


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



@dataclass
class     A					:
							lowercase_           =       42
							lowercase_           =       4096  # no dynamic padding on TPUs







							def __call__(						self :						Union[str, Any]							,    lowerCAmelCase_ :						List[str]      )    ->							str:


														"""simple docstring"""


														_a			  =       self.collate_fn(__A      )
														_a			  =       jax.tree_util.tree_map(__A							,    __A      )
														return batch







							def      __lowerCAmelCase    (						self :						List[Any]							,    lowerCAmelCase_ :						Optional[Any]      )    ->							str:


														"""simple docstring"""


														_a			  =       self.fetch_inputs(features['''input_ids''']      )
														_a			  =       {
														    "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 :						Union[str, Any]							,    lowerCAmelCase_ :						list      )    ->							List[Any]:


														"""simple docstring"""


														_a			  =       [self._fetch_inputs(__A      ) for ids in input_ids]
														return zip(*__A      )







							def      __lowerCAmelCase    (						self :						Tuple							,    lowerCAmelCase_ :						list      )    ->							str:


														"""simple docstring"""


														_a			  =       [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 :						Any				,		UpperCamelCase :						List[str]				,		UpperCamelCase :						Dict=None   ):





							'''simple docstring'''


							if seed is not None:
														_a			  =       dataset.shuffle(seed=_lowerCAmelCase   )
							for i in range(len(_lowerCAmelCase   ) // batch_size   ):
														_a			  =       dataset[i * batch_size : (i + 1) * batch_size]
														yield dict(_lowerCAmelCase   )
@partial(jax.pmap				,		axis_name='''batch'''   )
def 	snake_case_					(UpperCamelCase :						Union[str, Any]				,		UpperCamelCase :						List[str]				,		**UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							def loss_fn(UpperCamelCase :						str   ):
														_a			  =       model_inputs.pop('''start_labels'''   )
														_a			  =       model_inputs.pop('''end_labels'''   )
														_a			  =       model_inputs.pop('''pooled_labels'''   )

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

														return state.loss_fn(
														    _lowerCAmelCase				,		_lowerCAmelCase				,		_lowerCAmelCase				,		_lowerCAmelCase				,		_lowerCAmelCase				,		_lowerCAmelCase				,		)

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

							_a			  =       state.apply_gradients(grads=_lowerCAmelCase   )
							return state, metrics, new_drp_rng
@partial(jax.pmap				,		axis_name='''batch'''   )
def 	snake_case_					(UpperCamelCase :						int				,		**UpperCamelCase :						Tuple   ):





							'''simple docstring'''


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

							_a			  =       state.apply_fn(**_lowerCAmelCase				,		params=state.params				,		train=_lowerCAmelCase   )
							_a			  =       outputs

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

class     A					(	train_state.TrainState					):
							lowercase_           =       struct.field(pytree_node=_a					)



@dataclass
class     A					:
							lowercase_           =       42
							lowercase_           =       42
							lowercase_           =       42
							lowercase_           =       42
							lowercase_           =       42
							lowercase_           =       42
							lowercase_           =       None







							def      __lowerCAmelCase    (						self :						Tuple							,    lowerCAmelCase_ :						List[Any]							,    lowerCAmelCase_ :						int							,    lowerCAmelCase_ :						List[str]							,    lowerCAmelCase_ :						Tuple=None      )    ->							Any:


														"""simple docstring"""


														_a			  =       model.params
														_a			  =       TrainState.create(
														    apply_fn=model.__call__							,    params=__A							,    tx=__A							,    loss_fn=__A							,    )
														if ckpt_dir is not None:
																					_a			  =       restore_checkpoint(__A							,    __A      )
																					_a			  =       {
																					    "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			  =       build_tx(**__A      )
																					_a			  =       train_state.TrainState(
																					    step=__A							,    apply_fn=model.__call__							,    params=__A							,    tx=__A							,    opt_state=__A							,    )
																					_a			  =       args
																					_a			  =       data_collator
																					_a			  =       lr
																					_a			  =       params
														_a			  =       jax_utils.replicate(__A      )
														return state







							def      __lowerCAmelCase    (						self :						List[Any]							,    lowerCAmelCase_ :						int							,    lowerCAmelCase_ :						Dict							,    lowerCAmelCase_ :						Optional[Any]      )    ->							str:


														"""simple docstring"""


														_a			  =       self.args
														_a			  =       len(__A      ) // args.batch_size

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

																																			_a			  =       self.evaluate(__A							,    __A      )
																																			_a			  =       {
																																			    "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]							,    lowerCAmelCase_ :						int							,    lowerCAmelCase_ :						Tuple      )    ->							Optional[int]:


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						List[str]							,    lowerCAmelCase_ :						Optional[Any]							,    lowerCAmelCase_ :						Union[str, Any]      )    ->							str:


														"""simple docstring"""


														_a			  =       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 :						Optional[Any]				,		UpperCamelCase :						List[str]   ):





							'''simple docstring'''


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

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

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

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

							print('''DONE'''   )
							return params, opt_state, step, args, data_collator
def 	snake_case_					(UpperCamelCase :						Optional[int]				,		UpperCamelCase :						int				,		UpperCamelCase :						List[str]				,		UpperCamelCase :						str   ):





							'''simple docstring'''


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

def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						int				,		UpperCamelCase :						Optional[int]				,		UpperCamelCase :						Dict				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


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

							_a			  =       scheduler_fn(_lowerCAmelCase				,		_lowerCAmelCase				,		_lowerCAmelCase				,		_lowerCAmelCase   )

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







'''simple docstring'''


_snake_case   :   Any     							=	tuple[float, float, float]
_snake_case   :   Optional[int]     							=	tuple[float, float, float]
def 	snake_case_					(UpperCamelCase :						Pointad				,		UpperCamelCase :						Pointad   ):





							'''simple docstring'''


							_a			  =       end_pointa[0] - end_pointa[0]
							_a			  =       end_pointa[1] - end_pointa[1]
							_a			  =       end_pointa[2] - end_pointa[2]
							return (x, y, z)
def 	snake_case_					(UpperCamelCase :						Vectorad				,		UpperCamelCase :						Vectorad   ):





							'''simple docstring'''


							_a			  =       ab[1] * ac[2] - ab[2] * ac[1]  # *i
							_a			  =       (ab[0] * ac[2] - ab[2] * ac[0]) * -1  # *j
							_a			  =       ab[0] * ac[1] - ab[1] * ac[0]  # *k
							return (x, y, z)
def 	snake_case_					(UpperCamelCase :						Vectorad				,		UpperCamelCase :						int   ):





							'''simple docstring'''


							return tuple(round(UpperCamelCase				,		UpperCamelCase   ) for x in vector   ) == (0, 0, 0)

def 	snake_case_					(UpperCamelCase :						Pointad				,		UpperCamelCase :						Pointad				,		UpperCamelCase :						Pointad				,		UpperCamelCase :						int = 10   ):





							'''simple docstring'''


							_a			  =       create_vector(UpperCamelCase				,		UpperCamelCase   )
							_a			  =       create_vector(UpperCamelCase				,		UpperCamelCase   )
							return is_zero_vector(get_ad_vectors_cross(UpperCamelCase				,		UpperCamelCase   )				,		UpperCamelCase   )

