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_		(      __lowerCAmelCase		):
   __lowerCAmelCase           =				42
   __lowerCAmelCase           =				jnp.floataa
   __lowerCAmelCase           =				True







   def 						lowerCamelCase_	(     self						:						str				):





    """simple docstring"""


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







   def __call__(     self						:						Union[str, Any]   ,   *lowerCamelCase_						:						Any   ,   **lowerCamelCase_						:						Union[str, Any]				):





    """simple docstring"""


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





class SCREAMING_SNAKE_CASE_		(      __lowerCAmelCase		):
   __lowerCAmelCase           =				FlaxBigBirdForNaturalQuestionsModule





def 			lowercase(	UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_       )		->	List[str]:







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

 UpperCamelCase			  =      partial(UpperCamelCase_							,					reduction=jnp.mean       )
 UpperCamelCase			  =      cross_entropy(UpperCamelCase_							,					UpperCamelCase_       )
 UpperCamelCase			  =      cross_entropy(UpperCamelCase_							,					UpperCamelCase_       )
 UpperCamelCase			  =      cross_entropy(UpperCamelCase_							,					UpperCamelCase_       )
 return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class SCREAMING_SNAKE_CASE_		:
   __lowerCAmelCase           =				"google/bigbird-roberta-base"
   __lowerCAmelCase           =				3_000
   __lowerCAmelCase           =				10_500

   __lowerCAmelCase           =				128
   __lowerCAmelCase           =				3

   __lowerCAmelCase           =				1
   __lowerCAmelCase           =				5

   # tx_args
   __lowerCAmelCase           =				3e-5
   __lowerCAmelCase           =				0.0
   __lowerCAmelCase           =				20_000
   __lowerCAmelCase           =				0.0095

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







   def 						lowerCamelCase_	(     self						:						List[Any]				):





    """simple docstring"""


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





@dataclass
class SCREAMING_SNAKE_CASE_		:
   __lowerCAmelCase           =				42
   __lowerCAmelCase           =				4_096  # no dynamic padding on TPUs







   def __call__(     self						:						List[Any]   ,   lowerCamelCase_						:						Optional[int]				):





    """simple docstring"""


    UpperCamelCase			  =      self.collate_fn(lowerCamelCase_				)
    UpperCamelCase			  =      jax.tree_util.tree_map(lowerCamelCase_   ,   lowerCamelCase_				)
    return batch







   def 						lowerCamelCase_	(     self						:						str   ,   lowerCamelCase_						:						Dict				):





    """simple docstring"""


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





    """simple docstring"""


    UpperCamelCase			  =      [self._fetch_inputs(lowerCamelCase_				) for ids in input_ids]
    return zip(*lowerCamelCase_				)







   def 						lowerCamelCase_	(     self						:						Optional[int]   ,   lowerCamelCase_						:						list				):





    """simple docstring"""


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





def 			lowercase(	UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_=None       )		->	str:







 '''simple docstring'''
 if seed is not None:
  UpperCamelCase			  =      dataset.shuffle(seed=UpperCamelCase_       )
 for i in range(len(UpperCamelCase_       ) // batch_size       ):
  UpperCamelCase			  =      dataset[i * batch_size : (i + 1) * batch_size]
  yield dict(UpperCamelCase_       )





@partial(jax.pmap							,					axis_name="""batch"""       )
def 			lowercase(	UpperCamelCase_							,					UpperCamelCase_							,					**UpperCamelCase_       )		->	Union[str, Any]:







 '''simple docstring'''
 def loss_fn(UpperCamelCase_       ):
  UpperCamelCase			  =      model_inputs.pop("""start_labels"""       )
  UpperCamelCase			  =      model_inputs.pop("""end_labels"""       )
  UpperCamelCase			  =      model_inputs.pop("""pooled_labels"""       )

  UpperCamelCase			  =      state.apply_fn(**UpperCamelCase_							,					params=UpperCamelCase_							,					dropout_rng=UpperCamelCase_							,					train=UpperCamelCase_       )
  UpperCamelCase  ,     UpperCamelCase  ,     UpperCamelCase			  =      outputs

  return state.loss_fn(
      UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					)

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

 UpperCamelCase			  =      state.apply_gradients(grads=UpperCamelCase_       )
 return state, metrics, new_drp_rng





@partial(jax.pmap							,					axis_name="""batch"""       )
def 			lowercase(	UpperCamelCase_							,					**UpperCamelCase_       )		->	List[Any]:







 '''simple docstring'''
 UpperCamelCase			  =      model_inputs.pop("""start_labels"""       )
 UpperCamelCase			  =      model_inputs.pop("""end_labels"""       )
 UpperCamelCase			  =      model_inputs.pop("""pooled_labels"""       )

 UpperCamelCase			  =      state.apply_fn(**UpperCamelCase_							,					params=state.params							,					train=UpperCamelCase_       )
 UpperCamelCase  ,     UpperCamelCase  ,     UpperCamelCase			  =      outputs

 UpperCamelCase			  =      state.loss_fn(UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_       )
 UpperCamelCase			  =      jax.lax.pmean({"""loss""": loss}							,					axis_name="""batch"""       )
 return metrics
class SCREAMING_SNAKE_CASE_		(      train_state.TrainState		):
   __lowerCAmelCase           =				struct.field(pytree_node=__lowerCAmelCase		)





@dataclass
class SCREAMING_SNAKE_CASE_		:
   __lowerCAmelCase           =				42
   __lowerCAmelCase           =				42
   __lowerCAmelCase           =				42
   __lowerCAmelCase           =				42
   __lowerCAmelCase           =				42
   __lowerCAmelCase           =				42
   __lowerCAmelCase           =				None







   def 						lowerCamelCase_	(     self						:						Dict   ,   lowerCamelCase_						:						Any   ,   lowerCamelCase_						:						Optional[Any]   ,   lowerCamelCase_						:						Optional[Any]   ,   lowerCamelCase_						:						Any=None				):





    """simple docstring"""


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







   def 						lowerCamelCase_	(     self						:						Optional[Any]   ,   lowerCamelCase_						:						Tuple   ,   lowerCamelCase_						:						List[Any]   ,   lowerCamelCase_						:						Optional[int]				):





    """simple docstring"""


    UpperCamelCase			  =      self.args
    UpperCamelCase			  =      len(lowerCamelCase_				) // args.batch_size

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

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







   def 						lowerCamelCase_	(     self						:						Optional[Any]   ,   lowerCamelCase_						:						int   ,   lowerCamelCase_						:						int				):





    """simple docstring"""


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







   def 						lowerCamelCase_	(     self						:						Optional[int]   ,   lowerCamelCase_						:						Any   ,   lowerCamelCase_						:						str				):





    """simple docstring"""


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





def 			lowercase(	UpperCamelCase_							,					UpperCamelCase_       )		->	Union[str, Any]:







 '''simple docstring'''
 print(f"""RESTORING CHECKPOINT FROM {save_dir}"""							,					end=""" ... """       )
 with open(os.path.join(UpperCamelCase_							,					"""flax_model.msgpack"""       )							,					"""rb"""       ) as f:
  UpperCamelCase			  =      from_bytes(state.params							,					f.read()       )

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

 UpperCamelCase			  =      joblib.load(os.path.join(UpperCamelCase_							,					"""args.joblib"""       )       )
 UpperCamelCase			  =      joblib.load(os.path.join(UpperCamelCase_							,					"""data_collator.joblib"""       )       )

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

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





def 			lowercase(	UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_       )		->	List[str]:







 '''simple docstring'''
 UpperCamelCase			  =      num_train_steps - warmup_steps
 UpperCamelCase			  =      optax.linear_schedule(init_value=UpperCamelCase_							,					end_value=UpperCamelCase_							,					transition_steps=UpperCamelCase_       )
 UpperCamelCase			  =      optax.linear_schedule(init_value=UpperCamelCase_							,					end_value=1E-7							,					transition_steps=UpperCamelCase_       )
 UpperCamelCase			  =      optax.join_schedules(schedules=[warmup_fn, decay_fn]							,					boundaries=[warmup_steps]       )
 return lr





def 			lowercase(	UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_       )		->	Dict:







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

 UpperCamelCase			  =      scheduler_fn(UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_       )

 UpperCamelCase			  =      optax.adamw(learning_rate=UpperCamelCase_							,					weight_decay=UpperCamelCase_							,					mask=UpperCamelCase_       )
 return tx, lr

import json
import logging
import os
import sys
from pathlib import Path

import finetune_rag

from transformers.file_utils import is_apex_available
from transformers.testing_utils import (
    TestCasePlus,
    execute_subprocess_async,
    require_ray,
    require_torch_gpu,
    require_torch_multi_gpu,
)


logging.basicConfig(level=logging.DEBUG)
_SCREAMING_SNAKE_CASE 		=      logging.getLogger()

_SCREAMING_SNAKE_CASE 		=      logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class SCREAMING_SNAKE_CASE_		(      __lowerCAmelCase		):







   def 						lowerCamelCase_	(     self						:						Union[str, Any]   ,   lowerCamelCase_						:						List[str]				):





    """simple docstring"""


    os.makedirs(lowerCamelCase_   ,   exist_ok=lowerCamelCase_				)
    UpperCamelCase			  =      {"""source""": """What is love ?""", """target""": """life"""}
    UpperCamelCase			  =      {"""train""": 12, """val""": 2, """test""": 2}
    for split in ["train", "test", "val"]:
     for field in ["source", "target"]:
      UpperCamelCase			  =      """\n""".join([contents[field]] * n_lines[split]				)
      with open(os.path.join(lowerCamelCase_   ,   f"""{split}.{field}"""				)   ,   """w"""				) as f:
       f.write(lowerCamelCase_				)







   def 						lowerCamelCase_	(     self						:						Tuple   ,   lowerCamelCase_						:						int   ,   lowerCamelCase_						:						str = "pytorch"				):





    """simple docstring"""


    UpperCamelCase			  =      self.get_auto_remove_tmp_dir()
    UpperCamelCase			  =      os.path.join(lowerCamelCase_   ,   """output"""				)
    UpperCamelCase			  =      os.path.join(lowerCamelCase_   ,   """data"""				)
    self._create_dummy_data(data_dir=lowerCamelCase_				)

    UpperCamelCase			  =      f"""
                --data_dir {data_dir} \
                --output_dir {output_dir} \
                --model_name_or_path facebook/rag-sequence-base \
                --model_type rag_sequence \
                --do_train \
                --do_predict \
                --n_val -1 \
                --val_check_interval 1.0 \
                --train_batch_size 2 \
                --eval_batch_size 1 \
                --max_source_length 25 \
                --max_target_length 25 \
                --val_max_target_length 25 \
                --test_max_target_length 25 \
                --label_smoothing 0.1 \
                --dropout 0.1 \
                --attention_dropout 0.1 \
                --weight_decay 0.001 \
                --adam_epsilon 1e-08 \
                --max_grad_norm 0.1 \
                --lr_scheduler polynomial \
                --learning_rate 3e-04 \
                --num_train_epochs 1 \
                --warmup_steps 4 \
                --gradient_accumulation_steps 1 \
                --distributed-port 8787 \
                --use_dummy_dataset 1 \
                --distributed_retriever {distributed_retriever} \
            """.split()

    if gpus > 0:
     testargs.append(f"""--gpus={gpus}"""				)
     if is_apex_available():
      testargs.append("""--fp16"""				)
    else:
     testargs.append("""--gpus=0"""				)
     testargs.append("""--distributed_backend=ddp_cpu"""				)
     testargs.append("""--num_processes=2"""				)

    UpperCamelCase			  =      [sys.executable, str(Path(finetune_rag.__file__				).resolve()				)] + testargs
    execute_subprocess_async(lowerCamelCase_   ,   env=self.get_env()				)

    UpperCamelCase			  =      os.path.join(lowerCamelCase_   ,   """metrics.json"""				)
    with open(lowerCamelCase_				) as f:
     UpperCamelCase			  =      json.load(lowerCamelCase_				)
    return result







   @require_torch_gpu
   def 						lowerCamelCase_	(     self						:						Tuple				):





    """simple docstring"""


    UpperCamelCase			  =      self._run_finetune(gpus=1				)
    self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]   ,   0.2				)







   @require_torch_multi_gpu
   def 						lowerCamelCase_	(     self						:						List[Any]				):





    """simple docstring"""


    UpperCamelCase			  =      self._run_finetune(gpus=2				)
    self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]   ,   0.2				)







   @require_torch_gpu
   @require_ray
   def 						lowerCamelCase_	(     self						:						Union[str, Any]				):





    """simple docstring"""


    UpperCamelCase			  =      self._run_finetune(gpus=1   ,   distributed_retriever="""ray"""				)
    self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]   ,   0.2				)







   @require_torch_multi_gpu
   @require_ray
   def 						lowerCamelCase_	(     self						:						int				):





    """simple docstring"""


    UpperCamelCase			  =      self._run_finetune(gpus=1   ,   distributed_retriever="""ray"""				)
    self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]   ,   0.2				)
