






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	(	__SCREAMING_SNAKE_CASE		):




      """simple docstring"""



      A    =     42
      A    =     jnp.floataa
      A    =     True
      def       snake_case_   ( self		):



          '''simple docstring'''
          super().setup()
          lowerCAmelCase__ :Tuple   				=					nn.Dense(5     ,						dtype=self.dtype		)



      def __call__( self     ,						*_lowerCAmelCase     ,						**_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__ :Union[str, Any]   				=					super().__call__(*_SCREAMING_SNAKE_CASE     ,						**_SCREAMING_SNAKE_CASE		)
          lowerCAmelCase__ :Any   				=					self.cls(outputs[2]		)
          return outputs[:2] + (cls_out,)







class 						_UpperCAmelCase	(	__SCREAMING_SNAKE_CASE		):




      """simple docstring"""



      A    =     FlaxBigBirdForNaturalQuestionsModule





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

    lowerCAmelCase__ :List[Any]   				=					partial(__snake_case     ,      reduction=jnp.mean							)
    lowerCAmelCase__ :int   				=					cross_entropy(__snake_case     ,      __snake_case							)
    lowerCAmelCase__ :Dict   				=					cross_entropy(__snake_case     ,      __snake_case							)
    lowerCAmelCase__ :str   				=					cross_entropy(__snake_case     ,      __snake_case							)
    return (start_loss + end_loss + pooled_loss) / 3







@dataclass
class 						_UpperCAmelCase	:




      """simple docstring"""



      A    =     '''google/bigbird-roberta-base'''
      A    =     30_00
      A    =     1_05_00

      A    =     1_28
      A    =     3

      A    =     1
      A    =     5

      # tx_args
      A    =     3E-5
      A    =     0.0
      A    =     2_00_00
      A    =     0.0095

      A    =     '''bigbird-roberta-natural-questions'''
      A    =     '''training-expt'''
      A    =     '''data/nq-training.jsonl'''
      A    =     '''data/nq-validation.jsonl'''
      def       snake_case_   ( self		):



          '''simple docstring'''
          os.makedirs(self.base_dir     ,						exist_ok=_SCREAMING_SNAKE_CASE		)
          lowerCAmelCase__ :List[str]   				=					os.path.join(self.base_dir     ,						self.save_dir		)
          lowerCAmelCase__ :Dict   				=					self.batch_size_per_device * jax.device_count()







@dataclass
class 						_UpperCAmelCase	:




      """simple docstring"""



      A    =     42
      A    =     40_96  # no dynamic padding on TPUs
      def __call__( self     ,						_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__ :str   				=					self.collate_fn(_SCREAMING_SNAKE_CASE		)
          lowerCAmelCase__ :Optional[int]   				=					jax.tree_util.tree_map(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE		)
          return batch
      def       snake_case_   ( self     ,						_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__ :List[Any]   				=					self.fetch_inputs(features["input_ids"]		)
          lowerCAmelCase__ :List[Any]   				=					{
              "input_ids": jnp.array(_SCREAMING_SNAKE_CASE     ,						dtype=jnp.intaa		),
              "attention_mask": jnp.array(_SCREAMING_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     ,						_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__ :int   				=					[self._fetch_inputs(_SCREAMING_SNAKE_CASE		) for ids in input_ids]
          return zip(*_SCREAMING_SNAKE_CASE		)



      def       snake_case_   ( self     ,						_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__ :Union[str, Any]   				=					[1 for _ in range(len(_SCREAMING_SNAKE_CASE		)		)]
          while len(_SCREAMING_SNAKE_CASE		) < self.max_length:
              input_ids.append(self.pad_id		)
              attention_mask.append(0		)
          return input_ids, attention_mask





def 					snake_case__				(				UpperCAmelCase				:	List[Any]     ,      UpperCAmelCase				:	Tuple     ,      UpperCAmelCase				:	Any=None							):
    if seed is not None:
        lowerCAmelCase__ :List[Any]   				=					dataset.shuffle(seed=__snake_case							)
    for i in range(len(__snake_case							) // batch_size							):
        lowerCAmelCase__ :Optional[Any]   				=					dataset[i * batch_size : (i + 1) * batch_size]
        yield dict(__snake_case							)


@partial(jax.pmap     ,      axis_name="batch"							)
def 					snake_case__				(				UpperCAmelCase				:	Optional[int]     ,      UpperCAmelCase				:	Any     ,      **UpperCAmelCase				:	Optional[int]							):
    def loss_fn(UpperCAmelCase				:	int							):
        lowerCAmelCase__ :Union[str, Any]   				=					model_inputs.pop("start_labels"							)
        lowerCAmelCase__ :Any   				=					model_inputs.pop("end_labels"							)
        lowerCAmelCase__ :Dict   				=					model_inputs.pop("pooled_labels"							)

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

        return state.loss_fn(
            __snake_case     ,      __snake_case     ,      __snake_case     ,      __snake_case     ,      __snake_case     ,      __snake_case     ,      )

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

    lowerCAmelCase__ :Dict   				=					state.apply_gradients(grads=__snake_case							)
    return state, metrics, new_drp_rng


@partial(jax.pmap     ,      axis_name="batch"							)
def 					snake_case__				(				UpperCAmelCase				:	List[Any]     ,      **UpperCAmelCase				:	str							):
    lowerCAmelCase__ :str   				=					model_inputs.pop("start_labels"							)
    lowerCAmelCase__ :Any   				=					model_inputs.pop("end_labels"							)
    lowerCAmelCase__ :Union[str, Any]   				=					model_inputs.pop("pooled_labels"							)

    lowerCAmelCase__ :Tuple   				=					state.apply_fn(**__snake_case     ,      params=state.params     ,      train=__snake_case							)
    lowerCAmelCase__ :List[Any]   				=					outputs

    lowerCAmelCase__ :Union[str, Any]   				=					state.loss_fn(__snake_case     ,      __snake_case     ,      __snake_case     ,      __snake_case     ,      __snake_case     ,      __snake_case							)
    lowerCAmelCase__ :List[str]   				=					jax.lax.pmean({"loss": loss}     ,      axis_name="batch"							)
    return metrics







class 						_UpperCAmelCase	(	train_state.TrainState		):




      """simple docstring"""



      A    =     struct.field(pytree_node=__SCREAMING_SNAKE_CASE		)







@dataclass
class 						_UpperCAmelCase	:




      """simple docstring"""



      A    =     42
      A    =     42
      A    =     42
      A    =     42
      A    =     42
      A    =     42
      A    =     None
      def       snake_case_   ( self     ,						_lowerCAmelCase     ,						_lowerCAmelCase     ,						_lowerCAmelCase     ,						_lowerCAmelCase=None		):



          '''simple docstring'''
          lowerCAmelCase__ :Union[str, Any]   				=					model.params
          lowerCAmelCase__ :int   				=					TrainState.create(
              apply_fn=model.__call__     ,						params=_SCREAMING_SNAKE_CASE     ,						tx=_SCREAMING_SNAKE_CASE     ,						loss_fn=_SCREAMING_SNAKE_CASE     ,						)
          if ckpt_dir is not None:
              lowerCAmelCase__ :Optional[int]   				=					restore_checkpoint(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE		)
              lowerCAmelCase__ :int   				=					{
                  "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__ :Tuple   				=					build_tx(**_SCREAMING_SNAKE_CASE		)
              lowerCAmelCase__ :List[str]   				=					train_state.TrainState(
                  step=_SCREAMING_SNAKE_CASE     ,						apply_fn=model.__call__     ,						params=_SCREAMING_SNAKE_CASE     ,						tx=_SCREAMING_SNAKE_CASE     ,						opt_state=_SCREAMING_SNAKE_CASE     ,						)
              lowerCAmelCase__ :Any   				=					args
              lowerCAmelCase__ :Optional[int]   				=					data_collator
              lowerCAmelCase__ :Any   				=					lr
              lowerCAmelCase__ :List[str]   				=					params
          lowerCAmelCase__ :Any   				=					jax_utils.replicate(_SCREAMING_SNAKE_CASE		)
          return state
      def       snake_case_   ( self     ,						_lowerCAmelCase     ,						_lowerCAmelCase     ,						_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__ :Tuple   				=					self.args
          lowerCAmelCase__ :Optional[int]   				=					len(_SCREAMING_SNAKE_CASE		) // args.batch_size

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

                      lowerCAmelCase__ :Dict   				=					self.evaluate(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE		)
                      lowerCAmelCase__ :Dict   				=					{
                          "step": state_step.item(),
                          "eval_loss": eval_loss.item(),
                          "tr_loss": tr_loss,
                          "lr": lr.item(),
                      }
                      tqdm.write(str(_SCREAMING_SNAKE_CASE		)		)
                      self.logger.log(_SCREAMING_SNAKE_CASE     ,						commit=_SCREAMING_SNAKE_CASE		)

                  if i % args.save_steps == 0:
                      self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}'''     ,						state=_SCREAMING_SNAKE_CASE		)
      def       snake_case_   ( self     ,						_lowerCAmelCase     ,						_lowerCAmelCase		):



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



      def       snake_case_   ( self     ,						_lowerCAmelCase     ,						_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__ :Any   				=					jax_utils.unreplicate(_SCREAMING_SNAKE_CASE		)
          print(f'''SAVING CHECKPOINT IN {save_dir}'''     ,						end=" ... "		)
          self.model_save_fn(_SCREAMING_SNAKE_CASE     ,						params=state.params		)
          with open(os.path.join(_SCREAMING_SNAKE_CASE     ,						"opt_state.msgpack"		)     ,						"wb"		) as f:
              f.write(to_bytes(state.opt_state		)		)
          joblib.dump(self.args     ,						os.path.join(_SCREAMING_SNAKE_CASE     ,						"args.joblib"		)		)
          joblib.dump(self.data_collator     ,						os.path.join(_SCREAMING_SNAKE_CASE     ,						"data_collator.joblib"		)		)
          with open(os.path.join(_SCREAMING_SNAKE_CASE     ,						"training_state.json"		)     ,						"w"		) as f:
              json.dump({"step": state.step.item()}     ,						_SCREAMING_SNAKE_CASE		)
          print("DONE"		)





def 					snake_case__				(				UpperCAmelCase				:	Optional[Any]     ,      UpperCAmelCase				:	List[Any]							):
    print(F'''RESTORING CHECKPOINT FROM {save_dir}'''     ,      end=" ... "							)
    with open(os.path.join(__snake_case     ,      "flax_model.msgpack"							)     ,      "rb"							) as f:
        lowerCAmelCase__ :Any   				=					from_bytes(state.params     ,      f.read()							)

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

    lowerCAmelCase__ :Optional[int]   				=					joblib.load(os.path.join(__snake_case     ,      "args.joblib"							)							)
    lowerCAmelCase__ :List[Any]   				=					joblib.load(os.path.join(__snake_case     ,      "data_collator.joblib"							)							)

    with open(os.path.join(__snake_case     ,      "training_state.json"							)     ,      "r"							) as f:
        lowerCAmelCase__ :int   				=					json.load(__snake_case							)
    lowerCAmelCase__ :List[str]   				=					training_state["step"]

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


def 					snake_case__				(				UpperCAmelCase				:	List[Any]     ,      UpperCAmelCase				:	Union[str, Any]     ,      UpperCAmelCase				:	Optional[int]     ,      UpperCAmelCase				:	List[Any]							):
    lowerCAmelCase__ :Dict   				=					num_train_steps - warmup_steps
    lowerCAmelCase__ :Any   				=					optax.linear_schedule(init_value=__snake_case     ,      end_value=__snake_case     ,      transition_steps=__snake_case							)
    lowerCAmelCase__ :Any   				=					optax.linear_schedule(init_value=__snake_case     ,      end_value=1E-7     ,      transition_steps=__snake_case							)
    lowerCAmelCase__ :Tuple   				=					optax.join_schedules(schedules=[warmup_fn, decay_fn]     ,      boundaries=[warmup_steps]							)
    return lr


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

    lowerCAmelCase__ :int   				=					scheduler_fn(__snake_case     ,      __snake_case     ,      __snake_case     ,      __snake_case							)

    lowerCAmelCase__ :Tuple   				=					optax.adamw(learning_rate=__snake_case     ,      weight_decay=__snake_case     ,      mask=__snake_case							)
    return tx, lr








"""simple docstring"""






def      _lowercase							(    __snake_case   ,__snake_case      )		->  Tuple:
			# "extended trapezoidal rule"
			# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
			__lowerCAmelCase :    Optional[Any]				=			(boundary[1] - boundary[0]) / steps
			__lowerCAmelCase :    List[Any]				=			boundary[0]
			__lowerCAmelCase :    Any				=			boundary[1]
			__lowerCAmelCase :    Dict				=			make_points(__snake_case   ,__snake_case   ,__snake_case      )
			__lowerCAmelCase :    List[str]				=			0.0
			y += (h / 2.0) * f(__snake_case      )
			for i in x_i:
						# print(i)
						y += h * f(__snake_case      )
			y += (h / 2.0) * f(__snake_case      )
			return y


def      _lowercase							(    __snake_case   ,__snake_case   ,__snake_case      )		->  Union[str, Any]:
			__lowerCAmelCase :    int				=			a + h
			while x < (b - h):
						yield x
						__lowerCAmelCase :    List[str]				=			x + h


def      _lowercase							(    __snake_case      )		->  Tuple:  # enter your function here
			__lowerCAmelCase :    int				=			(x - 0) * (x - 0)
			return y


def      _lowercase							(    )		->  int:
			__lowerCAmelCase :    Tuple				=			0.0  # Lower bound of integration
			__lowerCAmelCase :    Union[str, Any]				=			1.0  # Upper bound of integration
			__lowerCAmelCase :    Dict				=			10.0  # define number of steps or resolution
			__lowerCAmelCase :    Optional[Any]				=			[a, b]  # define boundary of integration
			__lowerCAmelCase :    Optional[int]				=			method_a(__snake_case   ,__snake_case      )
			print(F"""y = {y}"""      )


if __name__ == "__main__":
	main()