



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







       '''simple docstring'''


       UpperCamelCase		=	42
       UpperCamelCase		=	jnp.floataa
       UpperCamelCase		=	True



       def 	lowercase__							(				self     :    Any       )					->		Any:


             '''simple docstring'''




             super().setup()
             UpperCAmelCase_     					=				nn.Dense(5						,							dtype=self.dtype       )







       def __call__(				self     :    Optional[int]						,							*_UpperCAmelCase     :    List[str]						,							**_UpperCAmelCase     :    int       )					->		Any:


             '''simple docstring'''




             UpperCAmelCase_     					=				super().__call__(*_UpperCAmelCase						,							**_UpperCAmelCase       )
             UpperCAmelCase_     					=				self.cls(outputs[2]       )
             return outputs[:2] + (cls_out,)



class  lowercase__  (       SCREAMING_SNAKE_CASE ):







       '''simple docstring'''


       UpperCamelCase		=	FlaxBigBirdForNaturalQuestionsModule



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

      UpperCAmelCase_     					=				partial(lowerCAmelCase__      ,     reduction=jnp.mean )
      UpperCAmelCase_     					=				cross_entropy(lowerCAmelCase__      ,     lowerCAmelCase__ )
      UpperCAmelCase_     					=				cross_entropy(lowerCAmelCase__      ,     lowerCAmelCase__ )
      UpperCAmelCase_     					=				cross_entropy(lowerCAmelCase__      ,     lowerCAmelCase__ )
      return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class  lowercase__  :







       '''simple docstring'''


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

       UpperCamelCase		=	1_28
       UpperCamelCase		=	3

       UpperCamelCase		=	1
       UpperCamelCase		=	5

       # tx_args
       UpperCamelCase		=	3E-5
       UpperCamelCase		=	0.0
       UpperCamelCase		=	2_00_00
       UpperCamelCase		=	0.0_0_9_5

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



       def 	lowercase__							(				self     :    Dict       )					->		List[str]:


             '''simple docstring'''




             os.makedirs(self.base_dir						,							exist_ok=_UpperCAmelCase       )
             UpperCAmelCase_     					=				os.path.join(self.base_dir						,							self.save_dir       )
             UpperCAmelCase_     					=				self.batch_size_per_device * jax.device_count()



@dataclass
class  lowercase__  :







       '''simple docstring'''


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



       def __call__(				self     :    str						,							_UpperCAmelCase     :    List[str]       )					->		List[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.collate_fn(_UpperCAmelCase       )
             UpperCAmelCase_     					=				jax.tree_util.tree_map(_UpperCAmelCase						,							_UpperCAmelCase       )
             return batch



       def 	lowercase__							(				self     :    str						,							_UpperCAmelCase     :    Dict       )					->		Any:


             '''simple docstring'''




             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.fetch_inputs(features["input_ids"]       )
             UpperCAmelCase_     					=				{
                 "input_ids": jnp.array(_UpperCAmelCase						,							dtype=jnp.intaa       ),
                 "attention_mask": jnp.array(_UpperCAmelCase						,							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 	lowercase__							(				self     :    str						,							_UpperCAmelCase     :    list       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				[self._fetch_inputs(_UpperCAmelCase       ) for ids in input_ids]
             return zip(*_UpperCAmelCase       )







       def 	lowercase__							(				self     :    Union[str, Any]						,							_UpperCAmelCase     :    list       )					->		Optional[int]:


             '''simple docstring'''




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



def   a__      ( lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__=None ):
      if seed is not None:
            UpperCAmelCase_     					=				dataset.shuffle(seed=lowerCAmelCase__ )
      for i in range(len(lowerCAmelCase__ ) // batch_size ):
            UpperCAmelCase_     					=				dataset[i * batch_size : (i + 1) * batch_size]
            yield dict(lowerCAmelCase__ )
@partial(jax.pmap      ,     axis_name="batch" )
def   a__      ( lowerCAmelCase__      ,     lowerCAmelCase__      ,     **lowerCAmelCase__ ):
      def loss_fn(lowerCAmelCase__ ):
            UpperCAmelCase_     					=				model_inputs.pop("start_labels" )
            UpperCAmelCase_     					=				model_inputs.pop("end_labels" )
            UpperCAmelCase_     					=				model_inputs.pop("pooled_labels" )

            UpperCAmelCase_     					=				state.apply_fn(**lowerCAmelCase__      ,     params=lowerCAmelCase__      ,     dropout_rng=lowerCAmelCase__      ,     train=lowerCAmelCase__ )
            UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_     					=				outputs

            return state.loss_fn(
                lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     )

      UpperCAmelCase_					,       UpperCAmelCase_     					=				jax.random.split(lowerCAmelCase__ )
      UpperCAmelCase_     					=				jax.value_and_grad(lowerCAmelCase__ )
      UpperCAmelCase_					,       UpperCAmelCase_     					=				grad_fn(state.params )
      UpperCAmelCase_     					=				jax.lax.pmean({"loss": loss}      ,     axis_name="batch" )
      UpperCAmelCase_     					=				jax.lax.pmean(lowerCAmelCase__      ,     "batch" )

      UpperCAmelCase_     					=				state.apply_gradients(grads=lowerCAmelCase__ )
      return state, metrics, new_drp_rng
@partial(jax.pmap      ,     axis_name="batch" )
def   a__      ( lowerCAmelCase__      ,     **lowerCAmelCase__ ):
      UpperCAmelCase_     					=				model_inputs.pop("start_labels" )
      UpperCAmelCase_     					=				model_inputs.pop("end_labels" )
      UpperCAmelCase_     					=				model_inputs.pop("pooled_labels" )

      UpperCAmelCase_     					=				state.apply_fn(**lowerCAmelCase__      ,     params=state.params      ,     train=lowerCAmelCase__ )
      UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_     					=				outputs

      UpperCAmelCase_     					=				state.loss_fn(lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__ )
      UpperCAmelCase_     					=				jax.lax.pmean({"loss": loss}      ,     axis_name="batch" )
      return metrics
class  lowercase__  (       train_state.TrainState ):







       '''simple docstring'''


       UpperCamelCase		=	struct.field(pytree_node=SCREAMING_SNAKE_CASE )



@dataclass
class  lowercase__  :







       '''simple docstring'''


       UpperCamelCase		=	42
       UpperCamelCase		=	42
       UpperCamelCase		=	42
       UpperCamelCase		=	42
       UpperCamelCase		=	42
       UpperCamelCase		=	42
       UpperCamelCase		=	None



       def 	lowercase__							(				self     :    int						,							_UpperCAmelCase     :    int						,							_UpperCAmelCase     :    Dict						,							_UpperCAmelCase     :    Tuple						,							_UpperCAmelCase     :    int=None       )					->		Union[str, Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				model.params
             UpperCAmelCase_     					=				TrainState.create(
                 apply_fn=model.__call__						,							params=_UpperCAmelCase						,							tx=_UpperCAmelCase						,							loss_fn=_UpperCAmelCase						,							)
             if ckpt_dir is not None:
                   UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_     					=				restore_checkpoint(_UpperCAmelCase						,							_UpperCAmelCase       )
                   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(**_UpperCAmelCase       )
                   UpperCAmelCase_     					=				train_state.TrainState(
                       step=_UpperCAmelCase						,							apply_fn=model.__call__						,							params=_UpperCAmelCase						,							tx=_UpperCAmelCase						,							opt_state=_UpperCAmelCase						,							)
                   UpperCAmelCase_     					=				args
                   UpperCAmelCase_     					=				data_collator
                   UpperCAmelCase_     					=				lr
                   UpperCAmelCase_     					=				params
             UpperCAmelCase_     					=				jax_utils.replicate(_UpperCAmelCase       )
             return state



       def 	lowercase__							(				self     :    Optional[int]						,							_UpperCAmelCase     :    Optional[int]						,							_UpperCAmelCase     :    Tuple						,							_UpperCAmelCase     :    List[str]       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.args
             UpperCAmelCase_     					=				len(_UpperCAmelCase       ) // args.batch_size

             UpperCAmelCase_     					=				jax.random.PRNGKey(0       )
             UpperCAmelCase_     					=				jax.random.split(_UpperCAmelCase						,							jax.device_count()       )
             for epoch in range(args.max_epochs       ):
                   UpperCAmelCase_     					=				jnp.array(0						,							dtype=jnp.floataa       )
                   UpperCAmelCase_     					=				get_batched_dataset(_UpperCAmelCase						,							args.batch_size						,							seed=_UpperCAmelCase       )
                   UpperCAmelCase_     					=				0
                   for batch in tqdm(_UpperCAmelCase						,							total=_UpperCAmelCase						,							desc=F"""Running EPOCH-{epoch}"""       ):
                         UpperCAmelCase_     					=				self.data_collator(_UpperCAmelCase       )
                         UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_     					=				self.train_step_fn(_UpperCAmelCase						,							_UpperCAmelCase						,							**_UpperCAmelCase       )
                         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(_UpperCAmelCase						,							_UpperCAmelCase       )
                               UpperCAmelCase_     					=				{
                                   "step": state_step.item(),
                                   "eval_loss": eval_loss.item(),
                                   "tr_loss": tr_loss,
                                   "lr": lr.item(),
                               }
                               tqdm.write(str(_UpperCAmelCase       )       )
                               self.logger.log(_UpperCAmelCase						,							commit=_UpperCAmelCase       )

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



       def 	lowercase__							(				self     :    Tuple						,							_UpperCAmelCase     :    str						,							_UpperCAmelCase     :    Optional[int]       )					->		Union[str, Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				get_batched_dataset(_UpperCAmelCase						,							self.args.batch_size       )
             UpperCAmelCase_     					=				len(_UpperCAmelCase       ) // self.args.batch_size
             UpperCAmelCase_     					=				jnp.array(0						,							dtype=jnp.floataa       )
             UpperCAmelCase_     					=				0
             for batch in tqdm(_UpperCAmelCase						,							total=_UpperCAmelCase						,							desc="Evaluating ... "       ):
                   UpperCAmelCase_     					=				self.data_collator(_UpperCAmelCase       )
                   UpperCAmelCase_     					=				self.val_step_fn(_UpperCAmelCase						,							**_UpperCAmelCase       )
                   running_loss += jax_utils.unreplicate(metrics["loss"]       )
                   i += 1
             return running_loss / i







       def 	lowercase__							(				self     :    Union[str, Any]						,							_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    List[Any]       )					->		str:


             '''simple docstring'''




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



def   a__      ( lowerCAmelCase__      ,     lowerCAmelCase__ ):
      print(f"""RESTORING CHECKPOINT FROM {save_dir}"""      ,     end=" ... " )
      with open(os.path.join(lowerCAmelCase__      ,     "flax_model.msgpack" )      ,     "rb" ) as f:
            UpperCAmelCase_     					=				from_bytes(state.params      ,     f.read() )

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

      UpperCAmelCase_     					=				joblib.load(os.path.join(lowerCAmelCase__      ,     "args.joblib" ) )
      UpperCAmelCase_     					=				joblib.load(os.path.join(lowerCAmelCase__      ,     "data_collator.joblib" ) )

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

      print("DONE" )
      return params, opt_state, step, args, data_collator
def   a__      ( lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__ ):
      UpperCAmelCase_     					=				num_train_steps - warmup_steps
      UpperCAmelCase_     					=				optax.linear_schedule(init_value=lowerCAmelCase__      ,     end_value=lowerCAmelCase__      ,     transition_steps=lowerCAmelCase__ )
      UpperCAmelCase_     					=				optax.linear_schedule(init_value=lowerCAmelCase__      ,     end_value=1e-7      ,     transition_steps=lowerCAmelCase__ )
      UpperCAmelCase_     					=				optax.join_schedules(schedules=[warmup_fn, decay_fn]      ,     boundaries=[warmup_steps] )
      return lr


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

      UpperCAmelCase_     					=				scheduler_fn(lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__ )

      UpperCAmelCase_     					=				optax.adamw(learning_rate=lowerCAmelCase__      ,     weight_decay=lowerCAmelCase__      ,     mask=lowerCAmelCase__ )
      return tx, lr










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


UpperCamelCase__ :   Any						=							logging.get_logger(__name__)

UpperCamelCase__ :   Any						=							{
    '''Visual-Attention-Network/van-base''': (
        '''https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json'''
    ),
}







class 				lowerCAmelCase_       (					lowerCamelCase_							):
				__a     :       List[Any]						=     "van"






				def __init__(			self      ,snake_case__=224      ,snake_case__=3      ,snake_case__=[7, 3, 3, 3]      ,snake_case__=[4, 2, 2, 2]      ,snake_case__=[64, 128, 320, 512]      ,snake_case__=[3, 3, 12, 3]      ,snake_case__=[8, 8, 4, 4]      ,snake_case__="gelu"      ,snake_case__=0.02      ,snake_case__=1E-6      ,snake_case__=1E-2      ,snake_case__=0.0      ,snake_case__=0.0      ,**snake_case__      ,):
							super().__init__(**snake_case__ )
							SCREAMING_SNAKE_CASE_   : Tuple					  =      image_size
							SCREAMING_SNAKE_CASE_   : List[str]					  =      num_channels
							SCREAMING_SNAKE_CASE_   : Dict					  =      patch_sizes
							SCREAMING_SNAKE_CASE_   : str					  =      strides
							SCREAMING_SNAKE_CASE_   : str					  =      hidden_sizes
							SCREAMING_SNAKE_CASE_   : str					  =      depths
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      mlp_ratios
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      hidden_act
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      initializer_range
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      layer_norm_eps
							SCREAMING_SNAKE_CASE_   : int					  =      layer_scale_init_value
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      drop_path_rate
							SCREAMING_SNAKE_CASE_   : List[str]					  =      dropout_rate



