


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__	( A_		):



    """simple docstring"""






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






    def _a (      self   )  ->	int:
         super().setup()
         __UpperCamelCase   							=nn.Dense(5 ,       dtype=self.dtype   )






    def __call__(      self ,       *A_ ,       **A_   )  ->	Union[str, Any]:
         __UpperCamelCase   							=super().__call__(*A_ ,       **A_   )
         __UpperCamelCase   							=self.cls(outputs[2]   )
         return outputs[:2] + (cls_out,)






class    UpperCAmelCase__	( A_		):



    """simple docstring"""






    UpperCAmelCase__						:		Tuple              =  FlaxBigBirdForNaturalQuestionsModule

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

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






@dataclass
class    UpperCAmelCase__	:



    """simple docstring"""






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

    UpperCAmelCase__						:		int              =  1_2_8
    UpperCAmelCase__						:		int              =  3

    UpperCAmelCase__						:		int              =  1
    UpperCAmelCase__						:		int              =  5

    # tx_args
    UpperCAmelCase__						:		float              =  3e-5
    UpperCAmelCase__						:		float              =  0.0
    UpperCAmelCase__						:		int              =  2_0_0_0_0
    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 _a (      self   )  ->	Any:
         os.makedirs(self.base_dir ,       exist_ok=A_   )
         __UpperCamelCase   							=os.path.join(self.base_dir ,       self.save_dir   )
         __UpperCamelCase   							=self.batch_size_per_device * jax.device_count()






@dataclass
class    UpperCAmelCase__	:



    """simple docstring"""






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






    def __call__(      self ,       A_   )  ->	List[str]:
         __UpperCamelCase   							=self.collate_fn(A_   )
         __UpperCamelCase   							=jax.tree_util.tree_map(A_ ,       A_   )
         return batch






    def _a (      self ,       A_   )  ->	Any:
         __UpperCamelCase							,				__UpperCamelCase   							=self.fetch_inputs(features['input_ids']   )
         __UpperCamelCase   							={
             'input_ids': jnp.array(A_ ,       dtype=jnp.intaa   ),
             'attention_mask': jnp.array(A_ ,       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 _a (      self ,       A_   )  ->	List[Any]:
         __UpperCamelCase   							=[self._fetch_inputs(A_   ) for ids in input_ids]
         return zip(*A_   )






    def _a (      self ,       A_   )  ->	Any:
         __UpperCamelCase   							=[1 for _ in range(len(A_   )   )]
         while len(A_   ) < self.max_length:
              input_ids.append(self.pad_id   )
              attention_mask.append(0   )
         return input_ids, attention_mask

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : List[str]      ,					SCREAMING_SNAKE_CASE__      : List[str]=None    ):
     if seed is not None:
          __UpperCamelCase   							=dataset.shuffle(seed=SCREAMING_SNAKE_CASE__    )
     for i in range(len(SCREAMING_SNAKE_CASE__    ) // batch_size    ):
          __UpperCamelCase   							=dataset[i * batch_size : (i + 1) * batch_size]
          yield dict(SCREAMING_SNAKE_CASE__    )

@partial(jax.pmap      ,					axis_name='batch'    )
def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : Union[str, Any]      ,					SCREAMING_SNAKE_CASE__      : Any      ,					**SCREAMING_SNAKE_CASE__      : List[Any]    ):
     def loss_fn(SCREAMING_SNAKE_CASE__      : List[str]    ):
          __UpperCamelCase   							=model_inputs.pop('start_labels'    )
          __UpperCamelCase   							=model_inputs.pop('end_labels'    )
          __UpperCamelCase   							=model_inputs.pop('pooled_labels'    )

          __UpperCamelCase   							=state.apply_fn(**SCREAMING_SNAKE_CASE__      ,					params=SCREAMING_SNAKE_CASE__      ,					dropout_rng=SCREAMING_SNAKE_CASE__      ,					train=SCREAMING_SNAKE_CASE__    )
          __UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase   							=outputs

          return state.loss_fn(
              SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					)

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

     __UpperCamelCase   							=state.apply_gradients(grads=SCREAMING_SNAKE_CASE__    )
     return state, metrics, new_drp_rng

@partial(jax.pmap      ,					axis_name='batch'    )
def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : str      ,					**SCREAMING_SNAKE_CASE__      : Union[str, Any]    ):
     __UpperCamelCase   							=model_inputs.pop('start_labels'    )
     __UpperCamelCase   							=model_inputs.pop('end_labels'    )
     __UpperCamelCase   							=model_inputs.pop('pooled_labels'    )

     __UpperCamelCase   							=state.apply_fn(**SCREAMING_SNAKE_CASE__      ,					params=state.params      ,					train=SCREAMING_SNAKE_CASE__    )
     __UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase   							=outputs

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






class    UpperCAmelCase__	( train_state.TrainState		):



    """simple docstring"""






    UpperCAmelCase__						:		Callable              =  struct.field(pytree_node=A_		)






@dataclass
class    UpperCAmelCase__	:



    """simple docstring"""






    UpperCAmelCase__						:		Args
    UpperCAmelCase__						:		Callable
    UpperCAmelCase__						:		Callable
    UpperCAmelCase__						:		Callable
    UpperCAmelCase__						:		Callable
    UpperCAmelCase__						:		wandb
    UpperCAmelCase__						:		Callable              =  None






    def _a (      self ,       A_ ,       A_ ,       A_ ,       A_=None   )  ->	Dict:
         __UpperCamelCase   							=model.params
         __UpperCamelCase   							=TrainState.create(
             apply_fn=model.__call__ ,       params=A_ ,       tx=A_ ,       loss_fn=A_ ,       )
         if ckpt_dir is not None:
              __UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase   							=restore_checkpoint(A_ ,       A_   )
              __UpperCamelCase   							={
                  'lr': args.lr,
                  'init_lr': args.init_lr,
                  'warmup_steps': args.warmup_steps,
                  'num_train_steps': num_train_steps,
                  'weight_decay': args.weight_decay,
              }
              __UpperCamelCase							,				__UpperCamelCase   							=build_tx(**A_   )
              __UpperCamelCase   							=train_state.TrainState(
                  step=A_ ,       apply_fn=model.__call__ ,       params=A_ ,       tx=A_ ,       opt_state=A_ ,       )
              __UpperCamelCase   							=args
              __UpperCamelCase   							=data_collator
              __UpperCamelCase   							=lr
              __UpperCamelCase   							=params
         __UpperCamelCase   							=jax_utils.replicate(A_   )
         return state






    def _a (      self ,       A_ ,       A_ ,       A_   )  ->	Any:
         __UpperCamelCase   							=self.args
         __UpperCamelCase   							=len(A_   ) // args.batch_size

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

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

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






    def _a (      self ,       A_ ,       A_   )  ->	Dict:
         __UpperCamelCase   							=get_batched_dataset(A_ ,       self.args.batch_size   )
         __UpperCamelCase   							=len(A_   ) // self.args.batch_size
         __UpperCamelCase   							=jnp.array(0 ,       dtype=jnp.floataa   )
         __UpperCamelCase   							=0
         for batch in tqdm(A_ ,       total=A_ ,       desc='Evaluating ... '   ):
              __UpperCamelCase   							=self.data_collator(A_   )
              __UpperCamelCase   							=self.val_step_fn(A_ ,       **A_   )
              running_loss += jax_utils.unreplicate(metrics['loss']   )
              i += 1
         return running_loss / i






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

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : Tuple      ,					SCREAMING_SNAKE_CASE__      : Union[str, Any]    ):
     print(F'RESTORING CHECKPOINT FROM {save_dir}'      ,					end=' ... '    )
     with open(os.path.join(SCREAMING_SNAKE_CASE__      ,					'flax_model.msgpack'    )      ,					'rb'    ) as f:
          __UpperCamelCase   							=from_bytes(state.params      ,					f.read()    )

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

     __UpperCamelCase   							=joblib.load(os.path.join(SCREAMING_SNAKE_CASE__      ,					'args.joblib'    )    )
     __UpperCamelCase   							=joblib.load(os.path.join(SCREAMING_SNAKE_CASE__      ,					'data_collator.joblib'    )    )

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

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

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : Tuple      ,					SCREAMING_SNAKE_CASE__      : Any      ,					SCREAMING_SNAKE_CASE__      : Any      ,					SCREAMING_SNAKE_CASE__      : int    ):
     __UpperCamelCase   							=num_train_steps - warmup_steps
     __UpperCamelCase   							=optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__      ,					end_value=SCREAMING_SNAKE_CASE__      ,					transition_steps=SCREAMING_SNAKE_CASE__    )
     __UpperCamelCase   							=optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__      ,					end_value=1E-7      ,					transition_steps=SCREAMING_SNAKE_CASE__    )
     __UpperCamelCase   							=optax.join_schedules(schedules=[warmup_fn, decay_fn]      ,					boundaries=[warmup_steps]    )
     return lr





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

     __UpperCamelCase   							=scheduler_fn(SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__    )

     __UpperCamelCase   							=optax.adamw(learning_rate=SCREAMING_SNAKE_CASE__      ,					weight_decay=SCREAMING_SNAKE_CASE__      ,					mask=SCREAMING_SNAKE_CASE__    )
     return tx, lr









from ...configuration_utils import PretrainedConfig
from ...utils import logging


_A			=						logging.get_logger(__name__)

_A			=						{
    'google/realm-cc-news-pretrained-embedder': (
        'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json'
    ),
    'google/realm-cc-news-pretrained-encoder': (
        'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json'
    ),
    'google/realm-cc-news-pretrained-scorer': (
        'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json'
    ),
    'google/realm-cc-news-pretrained-openqa': (
        'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json'
    ),
    'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json',
    'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json',
    'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json',
    'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json',
    # See all REALM models at https://huggingface.co/models?filter=realm
}






class    UpperCAmelCase__	( A_		):



    """simple docstring"""






    UpperCAmelCase__						:		str              =  "realm"






    def __init__(      self ,       A_=30522 ,       A_=768 ,       A_=128 ,       A_=12 ,       A_=12 ,       A_=8 ,       A_=3072 ,       A_="gelu_new" ,       A_=0.1 ,       A_=0.1 ,       A_=512 ,       A_=2 ,       A_=0.02 ,       A_=1E-12 ,       A_=256 ,       A_=10 ,       A_=1E-3 ,       A_=5 ,       A_=320 ,       A_=13353718 ,       A_=5000 ,       A_=1 ,       A_=0 ,       A_=2 ,       **A_ ,       )  ->	Dict:
         super().__init__(pad_token_id=A_ ,       bos_token_id=A_ ,       eos_token_id=A_ ,       **A_   )

         # Common config
         __UpperCamelCase   							=vocab_size
         __UpperCamelCase   							=max_position_embeddings
         __UpperCamelCase   							=hidden_size
         __UpperCamelCase   							=retriever_proj_size
         __UpperCamelCase   							=num_hidden_layers
         __UpperCamelCase   							=num_attention_heads
         __UpperCamelCase   							=num_candidates
         __UpperCamelCase   							=intermediate_size
         __UpperCamelCase   							=hidden_act
         __UpperCamelCase   							=hidden_dropout_prob
         __UpperCamelCase   							=attention_probs_dropout_prob
         __UpperCamelCase   							=initializer_range
         __UpperCamelCase   							=type_vocab_size
         __UpperCamelCase   							=layer_norm_eps

         # Reader config
         __UpperCamelCase   							=span_hidden_size
         __UpperCamelCase   							=max_span_width
         __UpperCamelCase   							=reader_layer_norm_eps
         __UpperCamelCase   							=reader_beam_size
         __UpperCamelCase   							=reader_seq_len

         # Retrieval config
         __UpperCamelCase   							=num_block_records
         __UpperCamelCase   							=searcher_beam_size





