

'''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 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  BigBirdConfig
  SCREAMING_SNAKE_CASE    :  jnp.dtype							=			jnp.floataa
  SCREAMING_SNAKE_CASE    :  bool							=			True






  def 					SCREAMING_SNAKE_CASE      (      self   :     Tuple			):
   super().setup()
   __lowercase							  = nn.Dense(5					,dtype=self.dtype			)






  def __call__(      self   :     List[str]					,*lowercase__   :     int					,**lowercase__   :     int			):
   __lowercase							  = super().__call__(*lowercase__					,**lowercase__			)
   __lowercase							  = self.cls(outputs[2]			)
   return outputs[:2] + (cls_out,)






class 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Optional[int]							=			FlaxBigBirdForNaturalQuestionsModule


def 		_A     (    A__     ,				A__     ,				A__     ,				A__     ,				A__     ,				A__      ):






 """simple docstring"""



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

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






@dataclass
class 			lowercase_	:




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  str							=			"google/bigbird-roberta-base"
  SCREAMING_SNAKE_CASE    :  int							=			3_0_0_0
  SCREAMING_SNAKE_CASE    :  int							=			1_0_5_0_0

  SCREAMING_SNAKE_CASE    :  int							=			1_2_8
  SCREAMING_SNAKE_CASE    :  int							=			3

  SCREAMING_SNAKE_CASE    :  int							=			1
  SCREAMING_SNAKE_CASE    :  int							=			5

  # tx_args
  SCREAMING_SNAKE_CASE    :  float							=			3e-5
  SCREAMING_SNAKE_CASE    :  float							=			0.0
  SCREAMING_SNAKE_CASE    :  int							=			2_0_0_0_0
  SCREAMING_SNAKE_CASE    :  float							=			0.0095

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






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]			):
   os.makedirs(self.base_dir					,exist_ok=lowercase__			)
   __lowercase							  = os.path.join(self.base_dir					,self.save_dir			)
   __lowercase							  = self.batch_size_per_device * jax.device_count()






@dataclass
class 			lowercase_	:




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  int
  SCREAMING_SNAKE_CASE    :  int							=			4_0_9_6  # no dynamic padding on TPUs






  def __call__(      self   :     Dict					,lowercase__   :     int			):
   __lowercase							  = self.collate_fn(lowercase__			)
   __lowercase							  = jax.tree_util.tree_map(lowercase__					,lowercase__			)
   return batch






  def 					SCREAMING_SNAKE_CASE      (      self   :     int					,lowercase__   :     Tuple			):
   __lowercase  ,	__lowercase							  = self.fetch_inputs(features['''input_ids''']			)
   __lowercase							  = {
       '''input_ids''': jnp.array(lowercase__					,dtype=jnp.intaa			),
       '''attention_mask''': jnp.array(lowercase__					,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   :     Tuple					,lowercase__   :     list			):
   __lowercase							  = [self._fetch_inputs(lowercase__			) for ids in input_ids]
   return zip(*lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Any					,lowercase__   :     list			):
   __lowercase							  = [1 for _ in range(len(lowercase__			)			)]
   while len(lowercase__			) < self.max_length:
    input_ids.append(self.pad_id			)
    attention_mask.append(0			)
   return input_ids, attention_mask


def 		_A     (    A__     ,				A__     ,				A__=None      ):






 """simple docstring"""



 if seed is not None:
  __lowercase							  = dataset.shuffle(seed=A__      )
 for i in range(len(A__      ) // batch_size      ):
  __lowercase							  = dataset[i * batch_size : (i + 1) * batch_size]
  yield dict(A__      )


@partial(jax.pmap     ,				axis_name='''batch'''      )
def 		_A     (    A__     ,				A__     ,				**A__      ):






 """simple docstring"""



 def loss_fn(A__      ):
  __lowercase							  = model_inputs.pop('''start_labels'''      )
  __lowercase							  = model_inputs.pop('''end_labels'''      )
  __lowercase							  = model_inputs.pop('''pooled_labels'''      )

  __lowercase							  = state.apply_fn(**A__     ,				params=A__     ,				dropout_rng=A__     ,				train=A__      )
  __lowercase  ,	__lowercase  ,	__lowercase							  = outputs

  return state.loss_fn(
      A__     ,				A__     ,				A__     ,				A__     ,				A__     ,				A__     ,				)

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

 __lowercase							  = state.apply_gradients(grads=A__      )
 return state, metrics, new_drp_rng


@partial(jax.pmap     ,				axis_name='''batch'''      )
def 		_A     (    A__     ,				**A__      ):






 """simple docstring"""



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

 __lowercase							  = state.apply_fn(**A__     ,				params=state.params     ,				train=A__      )
 __lowercase  ,	__lowercase  ,	__lowercase							  = outputs

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






class 			lowercase_	(train_state.TrainState      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Callable							=			struct.field(pytree_node=lowerCamelCase__      )






@dataclass
class 			lowercase_	:




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Args
  SCREAMING_SNAKE_CASE    :  Callable
  SCREAMING_SNAKE_CASE    :  Callable
  SCREAMING_SNAKE_CASE    :  Callable
  SCREAMING_SNAKE_CASE    :  Callable
  SCREAMING_SNAKE_CASE    :  wandb
  SCREAMING_SNAKE_CASE    :  Callable							=			None






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






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[Any]					,lowercase__   :     List[Any]					,lowercase__   :     Tuple					,lowercase__   :     Dict			):
   __lowercase							  = self.args
   __lowercase							  = len(lowercase__			) // args.batch_size

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

      __lowercase							  = self.evaluate(lowercase__					,lowercase__			)
      __lowercase							  = {
          '''step''': state_step.item(),
          '''eval_loss''': eval_loss.item(),
          '''tr_loss''': tr_loss,
          '''lr''': lr.item(),
      }
      tqdm.write(str(lowercase__			)			)
      self.logger.log(lowercase__					,commit=lowercase__			)

     if i % args.save_steps == 0:
      self.save_checkpoint(args.save_dir + F"-e{epoch}-s{i}"					,state=lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[Any]					,lowercase__   :     Dict					,lowercase__   :     Optional[Any]			):
   __lowercase							  = get_batched_dataset(lowercase__					,self.args.batch_size			)
   __lowercase							  = len(lowercase__			) // self.args.batch_size
   __lowercase							  = jnp.array(0					,dtype=jnp.floataa			)
   __lowercase							  = 0
   for batch in tqdm(lowercase__					,total=lowercase__					,desc='''Evaluating ... '''			):
    __lowercase							  = self.data_collator(lowercase__			)
    __lowercase							  = self.val_step_fn(lowercase__					,**lowercase__			)
    running_loss += jax_utils.unreplicate(metrics['''loss''']			)
    i += 1
   return running_loss / i






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]					,lowercase__   :     int					,lowercase__   :     Any			):
   __lowercase							  = jax_utils.unreplicate(lowercase__			)
   print(F"SAVING CHECKPOINT IN {save_dir}"					,end=''' ... '''			)
   self.model_save_fn(lowercase__					,params=state.params			)
   with open(os.path.join(lowercase__					,'''opt_state.msgpack'''			)					,'''wb'''			) as f:
    f.write(to_bytes(state.opt_state			)			)
   joblib.dump(self.args					,os.path.join(lowercase__					,'''args.joblib'''			)			)
   joblib.dump(self.data_collator					,os.path.join(lowercase__					,'''data_collator.joblib'''			)			)
   with open(os.path.join(lowercase__					,'''training_state.json'''			)					,'''w'''			) as f:
    json.dump({'''step''': state.step.item()}					,lowercase__			)
   print('''DONE'''			)


def 		_A     (    A__     ,				A__      ):






 """simple docstring"""



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

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

 __lowercase							  = joblib.load(os.path.join(A__     ,				'''args.joblib'''      )      )
 __lowercase							  = joblib.load(os.path.join(A__     ,				'''data_collator.joblib'''      )      )

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

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


def 		_A     (    A__     ,				A__     ,				A__     ,				A__      ):






 """simple docstring"""



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






def 		_A     (    A__     ,				A__     ,				A__     ,				A__     ,				A__      ):






 """simple docstring"""



 def weight_decay_mask(A__      ):
  __lowercase							  = traverse_util.flatten_dict(A__      )
  __lowercase							  = {k: (v[-1] != '''bias''' and v[-2:] != ('''LayerNorm''', '''scale''')) for k, v in params.items()}
  return traverse_util.unflatten_dict(A__      )

 __lowercase							  = scheduler_fn(A__     ,				A__     ,				A__     ,				A__      )

 __lowercase							  = optax.adamw(learning_rate=A__     ,				weight_decay=A__     ,				mask=A__      )
 return tx, lr




'''simple docstring'''






def 		_A     (    A__ = 10     ,				A__ = 22      ):






 """simple docstring"""



 __lowercase							  = range(1     ,				A__      )
 __lowercase							  = range(1     ,				A__      )
 return sum(
     1 for power in powers for base in bases if len(str(base**power      )      ) == power      )


if __name__ == "__main__":
 print(f'{solution(10, 22) = }')

