





"""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   __SCREAMING_SNAKE_CASE     (    UpperCAmelCase_ ):







  '''simple docstring'''


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

  def  __SCREAMING_SNAKE_CASE					(		self :							int						)		->					Union[str, Any]:
        super().setup()
        _UpperCamelCase   :						Dict    =							nn.Dense(5       , dtype=self.dtype						)


  def __call__(		self :							Union[str, Any]       , *__a :							Tuple       , **__a :							Tuple						)		->					Optional[int]:
        _UpperCamelCase   :						List[str]    =							super().__call__(*SCREAMING_SNAKE_CASE_       , **SCREAMING_SNAKE_CASE_						)
        _UpperCamelCase   :						List[str]    =							self.cls(outputs[2]						)
        return outputs[:2] + (cls_out,)





class   __SCREAMING_SNAKE_CASE     (    UpperCAmelCase_ ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:Optional[int]						  =       FlaxBigBirdForNaturalQuestionsModule





def        lowercase__     (       lowercase_		,lowercase_		,lowercase_		,lowercase_		,lowercase_		,lowercase_      )       ->		int:




      """simple docstring"""

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

      _UpperCamelCase   :						int    =							partial(lowercase_		,reduction=jnp.mean      )
      _UpperCamelCase   :						Tuple    =							cross_entropy(lowercase_		,lowercase_      )
      _UpperCamelCase   :						List[Any]    =							cross_entropy(lowercase_		,lowercase_      )
      _UpperCamelCase   :						Union[str, Any]    =							cross_entropy(lowercase_		,lowercase_      )
      return (start_loss + end_loss + pooled_loss) / 3



@dataclass
class   __SCREAMING_SNAKE_CASE     :







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:str						  =       "google/bigbird-roberta-base"
  SCREAMING_SNAKE_CASE__				:int						  =       3_000
  SCREAMING_SNAKE_CASE__				:int						  =       10_500

  SCREAMING_SNAKE_CASE__				:int						  =       128
  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						  =       20_000
  SCREAMING_SNAKE_CASE__				:float						  =       0.0_095

  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 :							Union[str, Any]						)		->					Any:
        os.makedirs(self.base_dir       , exist_ok=SCREAMING_SNAKE_CASE_						)
        _UpperCamelCase   :						Any    =							os.path.join(self.base_dir       , self.save_dir						)
        _UpperCamelCase   :						str    =							self.batch_size_per_device * jax.device_count()





@dataclass
class   __SCREAMING_SNAKE_CASE     :







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:int
  SCREAMING_SNAKE_CASE__				:int						  =       4_096  # no dynamic padding on TPUs

  def __call__(		self :							Any       , __a :							Union[str, Any]						)		->					Optional[Any]:
        _UpperCamelCase   :						Dict    =							self.collate_fn(SCREAMING_SNAKE_CASE_						)
        _UpperCamelCase   :						List[Any]    =							jax.tree_util.tree_map(SCREAMING_SNAKE_CASE_       , SCREAMING_SNAKE_CASE_						)
        return batch

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]       , __a :							List[Any]						)		->					Optional[Any]:
        _UpperCamelCase   :						str    =							self.fetch_inputs(features["input_ids"]						)
        _UpperCamelCase   :						str    =							{
            """input_ids""": jnp.array(SCREAMING_SNAKE_CASE_       , dtype=jnp.intaa						),
            """attention_mask""": jnp.array(SCREAMING_SNAKE_CASE_       , 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 :							Dict       , __a :							str						)		->					Union[str, Any]:
        _UpperCamelCase   :						List[Any]    =							[self._fetch_inputs(SCREAMING_SNAKE_CASE_						) for ids in input_ids]
        return zip(*SCREAMING_SNAKE_CASE_						)


  def  __SCREAMING_SNAKE_CASE					(		self :							Dict       , __a :							Optional[int]						)		->					List[str]:
        _UpperCamelCase   :						Tuple    =							[1 for _ in range(len(SCREAMING_SNAKE_CASE_						)						)]
        while len(SCREAMING_SNAKE_CASE_						) < self.max_length:
              input_ids.append(self.pad_id						)
              attention_mask.append(0						)
        return input_ids, attention_mask





def        lowercase__     (       lowercase_		,lowercase_		,lowercase_=None      )       ->		Optional[Any]:




      """simple docstring"""

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




@partial(jax.pmap		,axis_name="batch"      )
def        lowercase__     (       lowercase_		,lowercase_		,**lowercase_      )       ->		int:




      """simple docstring"""

      def loss_fn(lowercase_      ):
            _UpperCamelCase   :						Dict    =							model_inputs.pop("start_labels"      )
            _UpperCamelCase   :						List[Any]    =							model_inputs.pop("end_labels"      )
            _UpperCamelCase   :						List[Any]    =							model_inputs.pop("pooled_labels"      )

            _UpperCamelCase   :						List[Any]    =							state.apply_fn(**lowercase_		,params=lowercase_		,dropout_rng=lowercase_		,train=lowercase_      )
            _UpperCamelCase   :						Any    =							outputs

            return state.loss_fn(
                lowercase_		,lowercase_		,lowercase_		,lowercase_		,lowercase_		,lowercase_		,)

      _UpperCamelCase   :						Optional[int]    =							jax.random.split(lowercase_      )
      _UpperCamelCase   :						Tuple    =							jax.value_and_grad(lowercase_      )
      _UpperCamelCase   :						Optional[int]    =							grad_fn(state.params      )
      _UpperCamelCase   :						Tuple    =							jax.lax.pmean({"loss": loss}		,axis_name="batch"      )
      _UpperCamelCase   :						Any    =							jax.lax.pmean(lowercase_		,"batch"      )

      _UpperCamelCase   :						str    =							state.apply_gradients(grads=lowercase_      )
      return state, metrics, new_drp_rng




@partial(jax.pmap		,axis_name="batch"      )
def        lowercase__     (       lowercase_		,**lowercase_      )       ->		str:




      """simple docstring"""

      _UpperCamelCase   :						Tuple    =							model_inputs.pop("start_labels"      )
      _UpperCamelCase   :						List[str]    =							model_inputs.pop("end_labels"      )
      _UpperCamelCase   :						int    =							model_inputs.pop("pooled_labels"      )

      _UpperCamelCase   :						List[Any]    =							state.apply_fn(**lowercase_		,params=state.params		,train=lowercase_      )
      _UpperCamelCase   :						Optional[int]    =							outputs

      _UpperCamelCase   :						Optional[Any]    =							state.loss_fn(lowercase_		,lowercase_		,lowercase_		,lowercase_		,lowercase_		,lowercase_      )
      _UpperCamelCase   :						List[str]    =							jax.lax.pmean({"loss": loss}		,axis_name="batch"      )
      return metrics



class   __SCREAMING_SNAKE_CASE     (    train_state.TrainState ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:Callable						  =       struct.field(pytree_node=UpperCAmelCase_ )





@dataclass
class   __SCREAMING_SNAKE_CASE     :







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

  def  __SCREAMING_SNAKE_CASE					(		self :							int       , __a :							int       , __a :							str       , __a :							Optional[Any]						)		->					Union[str, Any]:
        _UpperCamelCase   :						Tuple    =							self.args
        _UpperCamelCase   :						List[str]    =							len(SCREAMING_SNAKE_CASE_						) // args.batch_size

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

                          _UpperCamelCase   :						Tuple    =							self.evaluate(SCREAMING_SNAKE_CASE_       , SCREAMING_SNAKE_CASE_						)
                          _UpperCamelCase   :						List[Any]    =							{
                              """step""": state_step.item(),
                              """eval_loss""": eval_loss.item(),
                              """tr_loss""": tr_loss,
                              """lr""": lr.item(),
                          }
                          tqdm.write(str(SCREAMING_SNAKE_CASE_						)						)
                          self.logger.log(SCREAMING_SNAKE_CASE_       , commit=SCREAMING_SNAKE_CASE_						)

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

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]       , __a :							Dict       , __a :							Optional[int]						)		->					Union[str, Any]:
        _UpperCamelCase   :						Dict    =							get_batched_dataset(SCREAMING_SNAKE_CASE_       , self.args.batch_size						)
        _UpperCamelCase   :						Tuple    =							len(SCREAMING_SNAKE_CASE_						) // self.args.batch_size
        _UpperCamelCase   :						Union[str, Any]    =							jnp.array(0       , dtype=jnp.floataa						)
        _UpperCamelCase   :						Optional[Any]    =							0
        for batch in tqdm(SCREAMING_SNAKE_CASE_       , total=SCREAMING_SNAKE_CASE_       , desc="Evaluating ... "						):
              _UpperCamelCase   :						Tuple    =							self.data_collator(SCREAMING_SNAKE_CASE_						)
              _UpperCamelCase   :						List[Any]    =							self.val_step_fn(SCREAMING_SNAKE_CASE_       , **SCREAMING_SNAKE_CASE_						)
              running_loss += jax_utils.unreplicate(metrics["loss"]						)
              i += 1
        return running_loss / i


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





def        lowercase__     (       lowercase_		,lowercase_      )       ->		Optional[Any]:




      """simple docstring"""

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

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

      _UpperCamelCase   :						Any    =							joblib.load(os.path.join(lowercase_		,"args.joblib"      )      )
      _UpperCamelCase   :						Optional[int]    =							joblib.load(os.path.join(lowercase_		,"data_collator.joblib"      )      )

      with open(os.path.join(lowercase_		,"training_state.json"      )		,"r"      ) as f:
            _UpperCamelCase   :						int    =							json.load(lowercase_      )
      _UpperCamelCase   :						Optional[Any]    =							training_state["""step"""]

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




def        lowercase__     (       lowercase_		,lowercase_		,lowercase_		,lowercase_      )       ->		Tuple:




      """simple docstring"""

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




def        lowercase__     (       lowercase_		,lowercase_		,lowercase_		,lowercase_		,lowercase_      )       ->		Optional[int]:




      """simple docstring"""

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

      _UpperCamelCase   :						Optional[int]    =							scheduler_fn(lowercase_		,lowercase_		,lowercase_		,lowercase_      )

      _UpperCamelCase   :						int    =							optax.adamw(learning_rate=lowercase_		,weight_decay=lowercase_		,mask=lowercase_      )
      return tx, lr


lowerCamelCase__     :		List[str]        = """
# Installazione di Transformers
! pip install transformers datasets
# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e
# rimuovi la modalità commento al comando seguente.
# ! pip install git+https://github.com/huggingface/transformers.git
"""

lowerCamelCase__     :		List[Any]        = [{"""type""": """code""", """content""": INSTALL_CONTENT}]
lowerCamelCase__     :		int        = {
    """{processor_class}""": """FakeProcessorClass""",
    """{model_class}""": """FakeModelClass""",
    """{object_class}""": """FakeObjectClass""",
}






