



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



	def 		UpperCamelCase				(    self				:     int)->				Union[str, Any]:
						super().setup()
						__lowerCAmelCase						 =nn.Dense(5					,						dtype=self.dtype)



	def __call__(    self				:     Optional[int]					,						*snake_case_				:     List[Any]					,						**snake_case_				:     Optional[int])->				Optional[Any]:
						__lowerCAmelCase						 =super().__call__(*snake_case_					,						**snake_case_)
						__lowerCAmelCase						 =self.cls(outputs[2])
						return outputs[:2] + (cls_out,)






class     __a			(  SCREAMING_SNAKE_CASE					):
	SCREAMING_SNAKE_CASE  	=							FlaxBigBirdForNaturalQuestionsModule






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

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






@dataclass
class     __a			:
	SCREAMING_SNAKE_CASE  	=							"google/bigbird-roberta-base"
	SCREAMING_SNAKE_CASE  	=							3000
	SCREAMING_SNAKE_CASE  	=							1_0500

	SCREAMING_SNAKE_CASE  	=							128
	SCREAMING_SNAKE_CASE  	=							3

	SCREAMING_SNAKE_CASE  	=							1
	SCREAMING_SNAKE_CASE  	=							5

	# tx_args
	SCREAMING_SNAKE_CASE  	=							3E-5
	SCREAMING_SNAKE_CASE  	=							0.0
	SCREAMING_SNAKE_CASE  	=							2_0000
	SCREAMING_SNAKE_CASE  	=							0.0095

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



	def 		UpperCamelCase				(    self				:     Any)->				List[str]:
						os.makedirs(self.base_dir					,						exist_ok=snake_case_)
						__lowerCAmelCase						 =os.path.join(self.base_dir					,						self.save_dir)
						__lowerCAmelCase						 =self.batch_size_per_device * jax.device_count()






@dataclass
class     __a			:
	SCREAMING_SNAKE_CASE  	=							42
	SCREAMING_SNAKE_CASE  	=							4096  # no dynamic padding on TPUs



	def __call__(    self				:     List[Any]					,						snake_case_				:     Any)->				List[Any]:
						__lowerCAmelCase						 =self.collate_fn(snake_case_)
						__lowerCAmelCase						 =jax.tree_util.tree_map(snake_case_					,						snake_case_)
						return batch



	def 		UpperCamelCase				(    self				:     Tuple					,						snake_case_				:     List[str])->				List[Any]:
						__lowerCAmelCase ,						__lowerCAmelCase						 =self.fetch_inputs(features["""input_ids"""])
						__lowerCAmelCase						 ={
						    """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				:     Any					,						snake_case_				:     list)->				str:
						__lowerCAmelCase						 =[self._fetch_inputs(snake_case_) for ids in input_ids]
						return zip(*snake_case_)



	def 		UpperCamelCase				(    self				:     Any					,						snake_case_				:     list)->				List[str]:
						__lowerCAmelCase						 =[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		(	__lowerCamelCase						:     List[Any]					, __lowerCamelCase						:     Any					, __lowerCamelCase						:     int=None						)	->    Optional[Any]:
					if seed is not None:
										__lowerCAmelCase						 =dataset.shuffle(seed=__lowerCamelCase						)
					for i in range(len(__lowerCamelCase						) // batch_size						):
										__lowerCAmelCase						 =dataset[i * batch_size : (i + 1) * batch_size]
										yield dict(__lowerCamelCase						)






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

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

										return state.loss_fn(
										    __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, )

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

					__lowerCAmelCase						 =state.apply_gradients(grads=__lowerCamelCase						)
					return state, metrics, new_drp_rng






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

					__lowerCAmelCase						 =state.apply_fn(**__lowerCamelCase					, params=state.params					, train=__lowerCamelCase						)
					__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase						 =outputs

					__lowerCAmelCase						 =state.loss_fn(__lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase						)
					__lowerCAmelCase						 =jax.lax.pmean({"""loss""": loss}					, axis_name="""batch"""						)
					return metrics






class     __a			(  train_state.TrainState					):
	SCREAMING_SNAKE_CASE  	=							struct.field(pytree_node=SCREAMING_SNAKE_CASE					)






@dataclass
class     __a			:
	SCREAMING_SNAKE_CASE  	=							42
	SCREAMING_SNAKE_CASE  	=							42
	SCREAMING_SNAKE_CASE  	=							42
	SCREAMING_SNAKE_CASE  	=							42
	SCREAMING_SNAKE_CASE  	=							42
	SCREAMING_SNAKE_CASE  	=							42
	SCREAMING_SNAKE_CASE  	=							None



	def 		UpperCamelCase				(    self				:     List[Any]					,						snake_case_				:     List[str]					,						snake_case_				:     Tuple					,						snake_case_				:     Dict					,						snake_case_				:     int=None)->				Optional[Any]:
						__lowerCAmelCase						 =model.params
						__lowerCAmelCase						 =TrainState.create(
						    apply_fn=model.__call__					,						params=snake_case_					,						tx=snake_case_					,						loss_fn=snake_case_					,						)
						if ckpt_dir is not None:
											__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase						 =restore_checkpoint(snake_case_					,						snake_case_)
											__lowerCAmelCase						 ={
											    """lr""": args.lr,
											    """init_lr""": args.init_lr,
											    """warmup_steps""": args.warmup_steps,
											    """num_train_steps""": num_train_steps,
											    """weight_decay""": args.weight_decay,
											}
											__lowerCAmelCase ,						__lowerCAmelCase						 =build_tx(**snake_case_)
											__lowerCAmelCase						 =train_state.TrainState(
											    step=snake_case_					,						apply_fn=model.__call__					,						params=snake_case_					,						tx=snake_case_					,						opt_state=snake_case_					,						)
											__lowerCAmelCase						 =args
											__lowerCAmelCase						 =data_collator
											__lowerCAmelCase						 =lr
											__lowerCAmelCase						 =params
						__lowerCAmelCase						 =jax_utils.replicate(snake_case_)
						return state



	def 		UpperCamelCase				(    self				:     List[Any]					,						snake_case_				:     int					,						snake_case_				:     Dict					,						snake_case_				:     List[Any])->				List[str]:
						__lowerCAmelCase						 =self.args
						__lowerCAmelCase						 =len(snake_case_) // args.batch_size

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

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



	def 		UpperCamelCase				(    self				:     Union[str, Any]					,						snake_case_				:     List[str]					,						snake_case_				:     List[str])->				str:
						__lowerCAmelCase						 =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		(	__lowerCamelCase						:     Optional[int]					, __lowerCamelCase						:     Union[str, Any]						)	->    Tuple:
					print(f"""RESTORING CHECKPOINT FROM {save_dir}"""					, end=""" ... """						)
					with open(os.path.join(__lowerCamelCase					, """flax_model.msgpack"""						)					, """rb"""						) as f:
										__lowerCAmelCase						 =from_bytes(state.params					, f.read()						)

					with open(os.path.join(__lowerCamelCase					, """opt_state.msgpack"""						)					, """rb"""						) as f:
										__lowerCAmelCase						 =from_bytes(state.opt_state					, f.read()						)

					__lowerCAmelCase						 =joblib.load(os.path.join(__lowerCamelCase					, """args.joblib"""						)						)
					__lowerCAmelCase						 =joblib.load(os.path.join(__lowerCamelCase					, """data_collator.joblib"""						)						)

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

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






def        __lowerCAmelCase		(	__lowerCamelCase						:     str					, __lowerCamelCase						:     List[Any]					, __lowerCamelCase						:     Union[str, Any]					, __lowerCamelCase						:     Dict						)	->    Optional[Any]:
					__lowerCAmelCase						 =num_train_steps - warmup_steps
					__lowerCAmelCase						 =optax.linear_schedule(init_value=__lowerCamelCase					, end_value=__lowerCamelCase					, transition_steps=__lowerCamelCase						)
					__lowerCAmelCase						 =optax.linear_schedule(init_value=__lowerCamelCase					, end_value=1E-7					, transition_steps=__lowerCamelCase						)
					__lowerCAmelCase						 =optax.join_schedules(schedules=[warmup_fn, decay_fn]					, boundaries=[warmup_steps]						)
					return lr






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

					__lowerCAmelCase						 =scheduler_fn(__lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase						)

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









from collections.abc import Sequence
from queue import Queue






class     __a			:



	def __init__(    self				:     str					,						snake_case_				:     List[str]					,						snake_case_				:     Tuple					,						snake_case_				:     Tuple					,						snake_case_				:     Optional[Any]=None					,						snake_case_				:     Dict=None)->				Optional[int]:
						__lowerCAmelCase						 =start
						__lowerCAmelCase						 =end
						__lowerCAmelCase						 =val
						__lowerCAmelCase						 =(start + end) // 2
						__lowerCAmelCase						 =left
						__lowerCAmelCase						 =right



	def __repr__(    self				:     List[Any])->				Dict:
						return F"""SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})"""






class     __a			:



	def __init__(    self				:     List[str]					,						snake_case_				:     Sequence					,						snake_case_				:     int)->				str:
						__lowerCAmelCase						 =collection
						__lowerCAmelCase						 =function
						if self.collection:
											__lowerCAmelCase						 =self._build_tree(0					,						len(snake_case_) - 1)



	def 		UpperCamelCase				(    self				:     Dict					,						snake_case_				:     Tuple					,						snake_case_				:     Optional[int])->				Optional[int]:
						self._update_tree(self.root					,						snake_case_					,						snake_case_)



	def 		UpperCamelCase				(    self				:     Optional[Any]					,						snake_case_				:     Any					,						snake_case_				:     Union[str, Any])->				Union[str, Any]:
						return self._query_range(self.root					,						snake_case_					,						snake_case_)



	def 		UpperCamelCase				(    self				:     List[str]					,						snake_case_				:     List[str]					,						snake_case_				:     List[str])->				List[Any]:
						if start == end:
											return SegmentTreeNode(snake_case_					,						snake_case_					,						self.collection[start])
						__lowerCAmelCase						 =(start + end) // 2
						__lowerCAmelCase						 =self._build_tree(snake_case_					,						snake_case_)
						__lowerCAmelCase						 =self._build_tree(mid + 1					,						snake_case_)
						return SegmentTreeNode(snake_case_					,						snake_case_					,						self.fn(left.val					,						right.val)					,						snake_case_					,						snake_case_)



	def 		UpperCamelCase				(    self				:     Dict					,						snake_case_				:     Tuple					,						snake_case_				:     int					,						snake_case_				:     int)->				List[Any]:
						if node.start == i and node.end == i:
											__lowerCAmelCase						 =val
											return
						if i <= node.mid:
											self._update_tree(node.left					,						snake_case_					,						snake_case_)
						else:
											self._update_tree(node.right					,						snake_case_					,						snake_case_)
						__lowerCAmelCase						 =self.fn(node.left.val					,						node.right.val)



	def 		UpperCamelCase				(    self				:     Tuple					,						snake_case_				:     str					,						snake_case_				:     str					,						snake_case_				:     List[Any])->				Optional[int]:
						if node.start == i and node.end == j:
											return node.val

						if i <= node.mid:
											if j <= node.mid:
																# range in left child tree
																return self._query_range(node.left					,						snake_case_					,						snake_case_)
											else:
																# range in left child tree and right child tree
																return self.fn(
																    self._query_range(node.left					,						snake_case_					,						node.mid)					,						self._query_range(node.right					,						node.mid + 1					,						snake_case_)					,						)
						else:
											# range in right child tree
											return self._query_range(node.right					,						snake_case_					,						snake_case_)



	def 		UpperCamelCase				(    self				:     List[str])->				Tuple:
						if self.root is not None:
											__lowerCAmelCase						 =Queue()
											queue.put(self.root)
											while not queue.empty():
																__lowerCAmelCase						 =queue.get()
																yield node

																if node.left is not None:
																					queue.put(node.left)

																if node.right is not None:
																					queue.put(node.right)


if __name__ == "__main__":
				import operator

				for fn in [operator.add, max, min]:
								print('''*''' * 50)
								lowercase_													=      SegmentTree([2, 1, 5, 3, 4], fn)
								for node in arr.traverse():
												print(node)
								print()

								arr.update(1, 5)
								for node in arr.traverse():
												print(node)
								print()

								print(arr.query_range(3, 4))  # 7
								print(arr.query_range(2, 2))  # 5
								print(arr.query_range(1, 3))  # 13
								print()




