



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    lowerCamelCase__  (						UpperCAmelCase_):
     """simple docstring"""



     _A       =			42
     _A       =			jnp.floataa
     _A       =			True







     def 						_a      (self    ):






           '''simple docstring'''



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







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






           '''simple docstring'''



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





class    lowerCamelCase__  (						UpperCAmelCase_):
     """simple docstring"""



     _A       =			FlaxBigBirdForNaturalQuestionsModule



def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__ ):


      """simple docstring"""



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

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





@dataclass
class    lowerCamelCase__  :
     """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.00_95

     _A       =			'bigbird-roberta-natural-questions'
     _A       =			'training-expt'
     _A       =			'data/nq-training.jsonl'
     _A       =			'data/nq-validation.jsonl'







     def 						_a      (self    ):






           '''simple docstring'''



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





@dataclass
class    lowerCamelCase__  :
     """simple docstring"""



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







     def __call__(self				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		self.collate_fn(__a    )
           lowerCamelCase								=		jax.tree_util.tree_map(__a				,			__a    )
           return batch







     def 						_a      (self				,			__a    ):






           '''simple docstring'''



           lowerCamelCase			,							lowerCamelCase								=		self.fetch_inputs(features["input_ids"]    )
           lowerCamelCase								=		{
               "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    ):






           '''simple docstring'''



           lowerCamelCase								=		[self._fetch_inputs(__a    ) for ids in input_ids]
           return zip(*__a    )







     def 						_a      (self				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		[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     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__=None ):


      """simple docstring"""



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

@partial(jax.pmap   ,   axis_name="batch" )
def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__   ,   **UpperCAmelCase__ ):


      """simple docstring"""



      def loss_fn(UpperCAmelCase__ ):
            lowerCamelCase								=		model_inputs.pop("start_labels" )
            lowerCamelCase								=		model_inputs.pop("end_labels" )
            lowerCamelCase								=		model_inputs.pop("pooled_labels" )

            lowerCamelCase								=		state.apply_fn(**_snake_case   ,   params=_snake_case   ,   dropout_rng=_snake_case   ,   train=_snake_case )
            lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase								=		outputs

            return state.loss_fn(
                _snake_case   ,   _snake_case   ,   _snake_case   ,   _snake_case   ,   _snake_case   ,   _snake_case   ,   )

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

      lowerCamelCase								=		state.apply_gradients(grads=_snake_case )
      return state, metrics, new_drp_rng

@partial(jax.pmap   ,   axis_name="batch" )
def     __lowercase(	UpperCAmelCase__   ,   **UpperCAmelCase__ ):


      """simple docstring"""



      lowerCamelCase								=		model_inputs.pop("start_labels" )
      lowerCamelCase								=		model_inputs.pop("end_labels" )
      lowerCamelCase								=		model_inputs.pop("pooled_labels" )

      lowerCamelCase								=		state.apply_fn(**_snake_case   ,   params=state.params   ,   train=_snake_case )
      lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase								=		outputs

      lowerCamelCase								=		state.loss_fn(_snake_case   ,   _snake_case   ,   _snake_case   ,   _snake_case   ,   _snake_case   ,   _snake_case )
      lowerCamelCase								=		jax.lax.pmean({"loss": loss}   ,   axis_name="batch" )
      return metrics





class    lowerCamelCase__  (						train_state.TrainState):
     """simple docstring"""



     _A       =			struct.field(pytree_node=UpperCAmelCase_)





@dataclass
class    lowerCamelCase__  :
     """simple docstring"""



     _A       =			42
     _A       =			42
     _A       =			42
     _A       =			42
     _A       =			42
     _A       =			42
     _A       =			None







     def 						_a      (self				,			__a				,			__a				,			__a				,			__a=None    ):






           '''simple docstring'''



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







     def 						_a      (self				,			__a				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		self.args
           lowerCamelCase								=		len(__a    ) // args.batch_size

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

                             lowerCamelCase								=		self.evaluate(__a				,			__a    )
                             lowerCamelCase								=		{
                                 "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    ):






           '''simple docstring'''



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







     def 						_a      (self				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		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     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__ ):


      """simple docstring"""



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

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

      lowerCamelCase								=		joblib.load(os.path.join(_snake_case   ,   "args.joblib" ) )
      lowerCamelCase								=		joblib.load(os.path.join(_snake_case   ,   "data_collator.joblib" ) )

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

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

def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__ ):


      """simple docstring"""



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






def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__ ):


      """simple docstring"""



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

      lowerCamelCase								=		scheduler_fn(_snake_case   ,   _snake_case   ,   _snake_case   ,   _snake_case )

      lowerCamelCase								=		optax.adamw(learning_rate=_snake_case   ,   weight_decay=_snake_case   ,   mask=_snake_case )
      return tx, lr




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


a_						:     List[str]	     =		{
    'configuration_clipseg': [
        'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'CLIPSegConfig',
        'CLIPSegTextConfig',
        'CLIPSegVisionConfig',
    ],
    'processing_clipseg': ['CLIPSegProcessor'],
}

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     a_						:     Any	     =		[
         'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST',
         'CLIPSegModel',
         'CLIPSegPreTrainedModel',
         'CLIPSegTextModel',
         'CLIPSegVisionModel',
         'CLIPSegForImageSegmentation',
     ]

if TYPE_CHECKING:
     from .configuration_clipseg import (
         CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP,
         CLIPSegConfig,
         CLIPSegTextConfig,
         CLIPSegVisionConfig,
     )
     from .processing_clipseg import CLIPSegProcessor

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_clipseg import (
              CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST,
              CLIPSegForImageSegmentation,
              CLIPSegModel,
              CLIPSegPreTrainedModel,
              CLIPSegTextModel,
              CLIPSegVisionModel,
          )

else:
     import sys

     a_						:     Dict	     =		_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)