"""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_      (     __UpperCamelCase			):
					UpperCamelCase_ :	BigBirdConfig
					UpperCamelCase_ :	jnp.dtype			=    jnp.floataa
					UpperCamelCase_ :	bool			=    True




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Any     ):
							super().setup()
							lowerCAmelCase__        =   nn.Dense(5  ,						dtype=self.dtype     )




					def __call__(	self						:     str  ,						*snake_case__						:     int  ,						**snake_case__						:     Optional[int]     ):
							lowerCAmelCase__        =   super().__call__(*snake_case__  ,						**snake_case__     )
							lowerCAmelCase__        =   self.cls(outputs[2]     )
							return outputs[:2] + (cls_out,)

class       a_      (     __UpperCamelCase			):
					UpperCamelCase_ :	Any			=    FlaxBigBirdForNaturalQuestionsModule







def 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__     ):





		"""simple docstring"""




		def cross_entropy(lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__=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_      :
					UpperCamelCase_ :	str			=    "google/bigbird-roberta-base"
					UpperCamelCase_ :	int			=    3000
					UpperCamelCase_ :	int			=    1_0500

					UpperCamelCase_ :	int			=    128
					UpperCamelCase_ :	int			=    3

					UpperCamelCase_ :	int			=    1
					UpperCamelCase_ :	int			=    5

					# tx_args
					UpperCamelCase_ :	float			=    3e-5
					UpperCamelCase_ :	float			=    0.0
					UpperCamelCase_ :	int			=    2_0000
					UpperCamelCase_ :	float			=    0.00_95

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




					def 						_SCREAMING_SNAKE_CASE						(	self						:     int     ):
							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_      :
					UpperCamelCase_ :	int
					UpperCamelCase_ :	int			=    4096  # no dynamic padding on TPUs




					def __call__(	self						:     int  ,						snake_case__						:     Any     ):
							lowerCAmelCase__        =   self.collate_fn(snake_case__     )
							lowerCAmelCase__        =   jax.tree_util.tree_map(snake_case__  ,						snake_case__     )
							return batch




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Tuple  ,						snake_case__						:     Dict     ):
							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 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]  ,						snake_case__						:     list     ):
							lowerCAmelCase__        =   [self._fetch_inputs(snake_case__     ) for ids in input_ids]
							return zip(*snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]  ,						snake_case__						:     list     ):
							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 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__=None     ):





		"""simple docstring"""




		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 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__			,  **lowerCamelCase__     ):





		"""simple docstring"""




		def loss_fn(lowerCamelCase__     ):
				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 							_UpperCAmelCase		(       lowerCamelCase__			,  **lowerCamelCase__     ):





		"""simple docstring"""




		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			):
					UpperCamelCase_ :	Callable			=    struct.field(pytree_node=__UpperCamelCase			)

@dataclass
class       a_      :
					UpperCamelCase_ :	Args
					UpperCamelCase_ :	Callable
					UpperCamelCase_ :	Callable
					UpperCamelCase_ :	Callable
					UpperCamelCase_ :	Callable
					UpperCamelCase_ :	wandb
					UpperCamelCase_ :	Callable			=    None




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]  ,						snake_case__						:     List[Any]  ,						snake_case__						:     Dict  ,						snake_case__						:     Optional[Any]  ,						snake_case__						:     int=None     ):
							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 						_SCREAMING_SNAKE_CASE						(	self						:     Any  ,						snake_case__						:     Dict  ,						snake_case__						:     Optional[int]  ,						snake_case__						:     Any     ):
							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 						_SCREAMING_SNAKE_CASE						(	self						:     int  ,						snake_case__						:     Optional[Any]  ,						snake_case__						:     int     ):
							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 						_SCREAMING_SNAKE_CASE						(	self						:     Tuple  ,						snake_case__						:     Any  ,						snake_case__						:     Any     ):
							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 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__     ):





		"""simple docstring"""




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





		"""simple docstring"""




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





		"""simple docstring"""




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





"""simple docstring"""




import os







def 							_UpperCAmelCase		(       ):





		"""simple docstring"""




		lowerCAmelCase__        =   os.path.dirname(os.path.realpath(lowerCamelCase__     )     )
		lowerCAmelCase__        =   os.path.join(lowerCamelCase__			,  """triangle.txt"""     )

		with open(lowerCamelCase__     ) as f:
				lowerCAmelCase__        =   f.readlines()

		lowerCAmelCase__        =   []
		for line in triangle:
				lowerCAmelCase__        =   []
				for number in line.strip().split(""" """     ):
						numbers_from_line.append(int(lowerCamelCase__     )     )
				a.append(lowerCamelCase__     )

		for i in range(1			,  len(lowerCamelCase__     )     ):
				for j in range(len(a[i]     )     ):
						lowerCAmelCase__        =   a[i - 1][j] if j != len(a[i - 1]     ) else 0
						lowerCAmelCase__        =   a[i - 1][j - 1] if j > 0 else 0
						a[i][j] += max(lowerCamelCase__			,  lowerCamelCase__     )
		return max(a[-1]     )


if __name__ == "__main__":
			print(solution())




