



'''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 __A     (    A		):



 '''simple docstring'''







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



 def    a__    (self			)       ->	Any:


      """simple docstring"""



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



 def __call__(self					,  *A					,  **A			)       ->	Any:


      """simple docstring"""



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






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			Any		=			FlaxBigBirdForNaturalQuestionsModule





def lowerCAmelCase    (__A    ,      __A    ,      __A    ,      __A    ,      __A    ,      __A):



     """simple docstring"""



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

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






@dataclass
class __A     :



 '''simple docstring'''







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

 __lowerCamelCase       :			int		=			128
 __lowerCamelCase       :			int		=			3

 __lowerCamelCase       :			int		=			1
 __lowerCamelCase       :			int		=			5

 # tx_args
 __lowerCamelCase       :			float		=			3E-5
 __lowerCamelCase       :			float		=			0.0
 __lowerCamelCase       :			int		=			20_000
 __lowerCamelCase       :			float		=			0.00_95

 __lowerCamelCase       :			str		=			"bigbird-roberta-natural-questions"
 __lowerCamelCase       :			str		=			"training-expt"
 __lowerCamelCase       :			str		=			"data/nq-training.jsonl"
 __lowerCamelCase       :			str		=			"data/nq-validation.jsonl"



 def    a__    (self			)       ->	List[Any]:


      """simple docstring"""



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






@dataclass
class __A     :



 '''simple docstring'''







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



 def __call__(self					,  A			)       ->	Tuple:


      """simple docstring"""



      _a           =    self.collate_fn(A			)
      _a           =    jax.tree_util.tree_map(A					,  A			)
      return batch



 def    a__    (self					,  A			)       ->	List[str]:


      """simple docstring"""



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


      """simple docstring"""



      _a           =    [self._fetch_inputs(A			) for ids in input_ids]
      return zip(*A			)



 def    a__    (self					,  A			)       ->	Optional[Any]:


      """simple docstring"""



      _a           =    [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 lowerCAmelCase    (__A    ,      __A    ,      __A=None):



     """simple docstring"""



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




@partial(jax.pmap    ,      axis_name='''batch''')
def lowerCAmelCase    (__A    ,      __A    ,      **__A):



     """simple docstring"""



     def loss_fn(__A):
          _a           =    model_inputs.pop('''start_labels''')
          _a           =    model_inputs.pop('''end_labels''')
          _a           =    model_inputs.pop('''pooled_labels''')

          _a           =    state.apply_fn(**__A    ,      params=__A    ,      dropout_rng=__A    ,      train=__A)
          _a    ,       _a    ,       _a           =    outputs

          return state.loss_fn(
              __A    ,      __A    ,      __A    ,      __A    ,      __A    ,      __A    ,      )

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

     _a           =    state.apply_gradients(grads=__A)
     return state, metrics, new_drp_rng




@partial(jax.pmap    ,      axis_name='''batch''')
def lowerCAmelCase    (__A    ,      **__A):



     """simple docstring"""



     _a           =    model_inputs.pop('''start_labels''')
     _a           =    model_inputs.pop('''end_labels''')
     _a           =    model_inputs.pop('''pooled_labels''')

     _a           =    state.apply_fn(**__A    ,      params=state.params    ,      train=__A)
     _a    ,       _a    ,       _a           =    outputs

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






class __A     (    train_state.TrainState		):



 '''simple docstring'''







 __lowerCamelCase       :			Callable		=			struct.field(pytree_node=A		)






@dataclass
class __A     :



 '''simple docstring'''







 __lowerCamelCase       :			Args
 __lowerCamelCase       :			Callable
 __lowerCamelCase       :			Callable
 __lowerCamelCase       :			Callable
 __lowerCamelCase       :			Callable
 __lowerCamelCase       :			wandb
 __lowerCamelCase       :			Callable		=			None



 def    a__    (self					,  A					,  A					,  A					,  A=None			)       ->	Tuple:


      """simple docstring"""



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



 def    a__    (self					,  A					,  A					,  A			)       ->	Dict:


      """simple docstring"""



      _a           =    self.args
      _a           =    len(A			) // args.batch_size

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

                     _a           =    self.evaluate(A					,  A			)
                     _a           =    {
                         '''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			)       ->	List[Any]:


      """simple docstring"""



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



 def    a__    (self					,  A					,  A			)       ->	Dict:


      """simple docstring"""



      _a           =    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 lowerCAmelCase    (__A    ,      __A):



     """simple docstring"""



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

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

     _a           =    joblib.load(os.path.join(__A    ,      '''args.joblib'''))
     _a           =    joblib.load(os.path.join(__A    ,      '''data_collator.joblib'''))

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

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




def lowerCAmelCase    (__A    ,      __A    ,      __A    ,      __A):



     """simple docstring"""



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




def lowerCAmelCase    (__A    ,      __A    ,      __A    ,      __A    ,      __A):



     """simple docstring"""



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

     _a           =    scheduler_fn(__A    ,      __A    ,      __A    ,      __A)

     _a           =    optax.adamw(learning_rate=__A    ,      weight_decay=__A    ,      mask=__A)
     return tx, lr








'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


lowercase_									=    {
    "configuration_blip": [
        "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "BlipConfig",
        "BlipTextConfig",
        "BlipVisionConfig",
    ],
    "processing_blip": ["BlipProcessor"],
}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    ["BlipImageProcessor"]


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    [
      "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
      "BlipModel",
      "BlipPreTrainedModel",
      "BlipForConditionalGeneration",
      "BlipForQuestionAnswering",
      "BlipVisionModel",
      "BlipTextModel",
      "BlipForImageTextRetrieval",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    [
      "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
      "TFBlipModel",
      "TFBlipPreTrainedModel",
      "TFBlipForConditionalGeneration",
      "TFBlipForQuestionAnswering",
      "TFBlipVisionModel",
      "TFBlipTextModel",
      "TFBlipForImageTextRetrieval",
  ]

if TYPE_CHECKING:
  from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
  from .processing_blip import BlipProcessor

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_blip import BlipImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_blip import (
        BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
        BlipForConditionalGeneration,
        BlipForImageTextRetrieval,
        BlipForQuestionAnswering,
        BlipModel,
        BlipPreTrainedModel,
        BlipTextModel,
        BlipVisionModel,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_blip import (
        TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFBlipForConditionalGeneration,
        TFBlipForImageTextRetrieval,
        TFBlipForQuestionAnswering,
        TFBlipModel,
        TFBlipPreTrainedModel,
        TFBlipTextModel,
        TFBlipVisionModel,
    )

else:
  import sys

  lowercase_									=    _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



