





"""simple docstring"""



import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from utils_rag import save_json







def 		__lowercase     (   snake_case_  :  Optional[Any]						)   ->Optional[Any]:



    '''simple docstring'''







    __A    :						Optional[Any]						 =     filter(lambda snake_case_						: p.requires_grad				,model.parameters()						)
    __A    :						int						 =     sum([np.prod(p.size()						) for p in model_parameters]						)
    return params


a_ =			logging.getLogger(__name__)







def 		__lowercase     (   snake_case_  :  Any				,snake_case_  :  int						)   ->Optional[int]:



    '''simple docstring'''







    if metric == "rouge2":
        __A    :						List[str]						 =     '''{val_avg_rouge2:.4f}-{step_count}'''
    elif metric == "bleu":
        __A    :						str						 =     '''{val_avg_bleu:.4f}-{step_count}'''
    elif metric == "em":
        __A    :						List[Any]						 =     '''{val_avg_em:.4f}-{step_count}'''
    elif metric == "loss":
        __A    :						Any						 =     '''{val_avg_loss:.4f}-{step_count}'''
    else:
        raise NotImplementedError(
            F"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this"""
            ''' function.'''						)

    __A    :						List[str]						 =     ModelCheckpoint(
        dirpath=snake_case_				,filename=snake_case_				,monitor=F"""val_{metric}"""				,mode='''max'''				,save_top_k=1				,every_n_epochs=1				,)

    return checkpoint_callback







def 		__lowercase     (   snake_case_  :  str				,snake_case_  :  Optional[Any]						)   ->Any:



    '''simple docstring'''







    return EarlyStopping(
        monitor=F"""val_{metric}"""				,mode='''min''' if '''loss''' in metric else '''max'''				,patience=snake_case_				,verbose=snake_case_				,)






class 		__snake_case					(		pl.Callback     ):





 """simple docstring"""


 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Optional[Any]						 =     {F"""lr_group_{i}""": param['''lr'''] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups  )}
     pl_module.logger.log_metrics(__lowerCamelCase  )

 @rank_zero_only
 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase=True  ):



     '''simple docstring'''




     logger.info(F"""***** {type_path} results at step {trainer.global_step:05d} *****"""  )
     __A    :						List[str]						 =     trainer.callback_metrics
     trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['''log''', '''progress_bar''', '''preds''']}  )
     # Log results
     __A    :						Optional[Any]						 =     Path(pl_module.hparams.output_dir  )
     if type_path == "test":
         __A    :						List[Any]						 =     od / '''test_results.txt'''
         __A    :						str						 =     od / '''test_generations.txt'''
     else:
         # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
         # If people want this it will be easy enough to add back.
         __A    :						int						 =     od / F"""{type_path}_results/{trainer.global_step:05d}.txt"""
         __A    :						Any						 =     od / F"""{type_path}_generations/{trainer.global_step:05d}.txt"""
         results_file.parent.mkdir(exist_ok=__lowerCamelCase  )
         generations_file.parent.mkdir(exist_ok=__lowerCamelCase  )
     with open(__lowerCamelCase					,						'''a+'''  ) as writer:
         for key in sorted(__lowerCamelCase  ):
             if key in ["log", "progress_bar", "preds"]:
                 continue
             __A    :						Optional[int]						 =     metrics[key]
             if isinstance(__lowerCamelCase					,						torch.Tensor  ):
                 __A    :						Tuple						 =     val.item()
             __A    :						List[str]						 =     F"""{key}: {val:.6f}\n"""
             writer.write(__lowerCamelCase  )

     if not save_generations:
         return

     if "preds" in metrics:
         __A    :						Optional[int]						 =     '''\n'''.join(metrics['''preds''']  )
         generations_file.open('''w+'''  ).write(__lowerCamelCase  )

 @rank_zero_only
 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     try:
         __A    :						Union[str, Any]						 =     pl_module.model.model.num_parameters()
     except AttributeError:
         __A    :						Optional[int]						 =     pl_module.model.num_parameters()

     __A    :						int						 =     count_trainable_parameters(__lowerCamelCase  )
     # mp stands for million parameters
     trainer.logger.log_metrics({'''n_params''': npars, '''mp''': npars / 1e6, '''grad_mp''': n_trainable_pars / 1e6}  )

 @rank_zero_only
 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     save_json(pl_module.metrics					,						pl_module.metrics_save_path  )
     return self._write_logs(__lowerCamelCase					,						__lowerCamelCase					,						'''test'''  )







 @rank_zero_only
 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     save_json(pl_module.metrics					,						pl_module.metrics_save_path  )
     # Uncommenting this will save val generations
     # return self._write_logs(trainer, pl_module, "valid")











"""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 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     42
 _lowerCamelCase        =     jnp.floataa
 _lowerCamelCase        =     True

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     super().setup()
     __A    :						List[Any]						 =     nn.Dense(5					,						dtype=self.dtype  )







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



     '''simple docstring'''




     __A    :						Tuple						 =     super().__call__(*__lowerCamelCase					,						**__lowerCamelCase  )
     __A    :						Optional[int]						 =     self.cls(outputs[2]  )
     return outputs[:2] + (cls_out,)






class 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     FlaxBigBirdForNaturalQuestionsModule







def 		__lowercase     (   snake_case_  :  Tuple				,snake_case_  :  Optional[int]				,snake_case_  :  int				,snake_case_  :  Tuple				,snake_case_  :  Any				,snake_case_  :  Any						)   ->List[Any]:



    '''simple docstring'''







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

    __A    :						str						 =     partial(snake_case_				,reduction=jnp.mean						)
    __A    :						Dict						 =     cross_entropy(snake_case_				,snake_case_						)
    __A    :						List[str]						 =     cross_entropy(snake_case_				,snake_case_						)
    __A    :						str						 =     cross_entropy(snake_case_				,snake_case_						)
    return (start_loss + end_loss + pooled_loss) / 3






@dataclass
class 		__snake_case					:





 """simple docstring"""


 _lowerCamelCase        =     "google/bigbird-roberta-base"
 _lowerCamelCase        =     30_00
 _lowerCamelCase        =     1_05_00

 _lowerCamelCase        =     1_28
 _lowerCamelCase        =     3

 _lowerCamelCase        =     1
 _lowerCamelCase        =     5

 # tx_args
 _lowerCamelCase        =     3e-5
 _lowerCamelCase        =     0.0
 _lowerCamelCase        =     2_00_00
 _lowerCamelCase        =     0.0_0_9_5

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

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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






@dataclass
class 		__snake_case					:





 """simple docstring"""


 _lowerCamelCase        =     42
 _lowerCamelCase        =     40_96  # no dynamic padding on TPUs

 def __call__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Optional[int]						 =     self.collate_fn(__lowerCamelCase  )
     __A    :						Tuple						 =     jax.tree_util.tree_map(__lowerCamelCase					,						__lowerCamelCase  )
     return batch

 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A ,       __A    :						List[Any]						 =     self.fetch_inputs(features['''input_ids''']  )
     __A    :						Union[str, Any]						 =     {
         '''input_ids''': jnp.array(__lowerCamelCase					,						dtype=jnp.intaa  ),
         '''attention_mask''': jnp.array(__lowerCamelCase					,						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					,						__lowerCamelCase  ):



     '''simple docstring'''




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







 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Any						 =     [1 for _ in range(len(__lowerCamelCase  )  )]
     while len(__lowerCamelCase  ) < self.max_length:
         input_ids.append(self.pad_id  )
         attention_mask.append(0  )
     return input_ids, attention_mask







def 		__lowercase     (   snake_case_  :  List[Any]				,snake_case_  :  Optional[Any]				,snake_case_  :  List[str]=None						)   ->Optional[int]:



    '''simple docstring'''







    if seed is not None:
        __A    :						List[Any]						 =     dataset.shuffle(seed=snake_case_						)
    for i in range(len(snake_case_						) // batch_size						):
        __A    :						Tuple						 =     dataset[i * batch_size : (i + 1) * batch_size]
        yield dict(snake_case_						)







@partial(jax.pmap				,axis_name='''batch'''						)
def 		__lowercase     (   snake_case_  :  str				,snake_case_  :  Union[str, Any]				,**snake_case_  :  List[str]						)   ->Tuple:



    '''simple docstring'''







    def loss_fn(snake_case_  :  List[str]						):
        __A    :						str						 =     model_inputs.pop('''start_labels'''						)
        __A    :						str						 =     model_inputs.pop('''end_labels'''						)
        __A    :						int						 =     model_inputs.pop('''pooled_labels'''						)

        __A    :						Dict						 =     state.apply_fn(**snake_case_				,params=snake_case_				,dropout_rng=snake_case_				,train=snake_case_						)
        __A ,       __A ,       __A    :						Union[str, Any]						 =     outputs

        return state.loss_fn(
            snake_case_				,snake_case_				,snake_case_				,snake_case_				,snake_case_				,snake_case_				,)

    __A ,       __A    :						int						 =     jax.random.split(snake_case_						)
    __A    :						str						 =     jax.value_and_grad(snake_case_						)
    __A ,       __A    :						Optional[int]						 =     grad_fn(state.params						)
    __A    :						List[str]						 =     jax.lax.pmean({'''loss''': loss}				,axis_name='''batch'''						)
    __A    :						List[str]						 =     jax.lax.pmean(snake_case_				,'''batch'''						)

    __A    :						str						 =     state.apply_gradients(grads=snake_case_						)
    return state, metrics, new_drp_rng







@partial(jax.pmap				,axis_name='''batch'''						)
def 		__lowercase     (   snake_case_  :  int				,**snake_case_  :  Union[str, Any]						)   ->List[str]:



    '''simple docstring'''







    __A    :						Tuple						 =     model_inputs.pop('''start_labels'''						)
    __A    :						Dict						 =     model_inputs.pop('''end_labels'''						)
    __A    :						int						 =     model_inputs.pop('''pooled_labels'''						)

    __A    :						List[str]						 =     state.apply_fn(**snake_case_				,params=state.params				,train=snake_case_						)
    __A ,       __A ,       __A    :						Dict						 =     outputs

    __A    :						Optional[int]						 =     state.loss_fn(snake_case_				,snake_case_				,snake_case_				,snake_case_				,snake_case_				,snake_case_						)
    __A    :						List[str]						 =     jax.lax.pmean({'''loss''': loss}				,axis_name='''batch'''						)
    return metrics






class 		__snake_case					(		train_state.TrainState     ):





 """simple docstring"""


 _lowerCamelCase        =     struct.field(pytree_node=SCREAMING_SNAKE_CASE__     )






@dataclass
class 		__snake_case					:





 """simple docstring"""


 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     None

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase=None  ):



     '''simple docstring'''




     __A    :						Tuple						 =     model.params
     __A    :						Union[str, Any]						 =     TrainState.create(
         apply_fn=model.__call__					,						params=__lowerCamelCase					,						tx=__lowerCamelCase					,						loss_fn=__lowerCamelCase					,						)
     if ckpt_dir is not None:
         __A ,       __A ,       __A ,       __A ,       __A    :						Optional[Any]						 =     restore_checkpoint(__lowerCamelCase					,						__lowerCamelCase  )
         __A    :						List[Any]						 =     {
             '''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 ,       __A    :						List[str]						 =     build_tx(**__lowerCamelCase  )
         __A    :						int						 =     train_state.TrainState(
             step=__lowerCamelCase					,						apply_fn=model.__call__					,						params=__lowerCamelCase					,						tx=__lowerCamelCase					,						opt_state=__lowerCamelCase					,						)
         __A    :						int						 =     args
         __A    :						Optional[Any]						 =     data_collator
         __A    :						Tuple						 =     lr
         __A    :						List[Any]						 =     params
     __A    :						Dict						 =     jax_utils.replicate(__lowerCamelCase  )
     return state

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     self.args
     __A    :						Dict						 =     len(__lowerCamelCase  ) // args.batch_size

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

                 __A    :						Union[str, Any]						 =     self.evaluate(__lowerCamelCase					,						__lowerCamelCase  )
                 __A    :						Optional[Any]						 =     {
                     '''step''': state_step.item(),
                     '''eval_loss''': eval_loss.item(),
                     '''tr_loss''': tr_loss,
                     '''lr''': lr.item(),
                 }
                 tqdm.write(str(__lowerCamelCase  )  )
                 self.logger.log(__lowerCamelCase					,						commit=__lowerCamelCase  )

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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




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







 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




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







def 		__lowercase     (   snake_case_  :  int				,snake_case_  :  Dict						)   ->Optional[int]:



    '''simple docstring'''







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

    with open(os.path.join(snake_case_				,'''opt_state.msgpack'''						)				,'''rb'''						) as f:
        __A    :						Optional[int]						 =     from_bytes(state.opt_state				,f.read()						)

    __A    :						Tuple						 =     joblib.load(os.path.join(snake_case_				,'''args.joblib'''						)						)
    __A    :						List[str]						 =     joblib.load(os.path.join(snake_case_				,'''data_collator.joblib'''						)						)

    with open(os.path.join(snake_case_				,'''training_state.json'''						)				,'''r'''						) as f:
        __A    :						Dict						 =     json.load(snake_case_						)
    __A    :						int						 =     training_state['''step''']

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







def 		__lowercase     (   snake_case_  :  List[str]				,snake_case_  :  Any				,snake_case_  :  Dict				,snake_case_  :  str						)   ->List[str]:



    '''simple docstring'''







    __A    :						str						 =     num_train_steps - warmup_steps
    __A    :						Union[str, Any]						 =     optax.linear_schedule(init_value=snake_case_				,end_value=snake_case_				,transition_steps=snake_case_						)
    __A    :						Optional[Any]						 =     optax.linear_schedule(init_value=snake_case_				,end_value=1e-7				,transition_steps=snake_case_						)
    __A    :						Any						 =     optax.join_schedules(schedules=[warmup_fn, decay_fn]				,boundaries=[warmup_steps]						)
    return lr







def 		__lowercase     (   snake_case_  :  List[str]				,snake_case_  :  List[Any]				,snake_case_  :  Union[str, Any]				,snake_case_  :  List[Any]				,snake_case_  :  str						)   ->List[str]:



    '''simple docstring'''







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

    __A    :						List[Any]						 =     scheduler_fn(snake_case_				,snake_case_				,snake_case_				,snake_case_						)

    __A    :						List[str]						 =     optax.adamw(learning_rate=snake_case_				,weight_decay=snake_case_				,mask=snake_case_						)
    return tx, lr




