





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 							_UpperCAmelCase       (       UpperCAmelCase__       ):

  """simple docstring"""


  a_              =					42
  a_              =					jnp.floataa
  a_              =					True






  def 							lowercase						(							self					:						Union[str, Any]	)				->		Any:
     super().setup()
     __lowerCAmelCase				      =      nn.Dense(5   ,    dtype=self.dtype	)






  def __call__(							self					:						List[Any]   ,    *lowerCAmelCase_					:						List[Any]   ,    **lowerCAmelCase_					:						Union[str, Any]	)				->		Union[str, Any]:
     __lowerCAmelCase				      =      super().__call__(*__lowercase   ,    **__lowercase	)
     __lowerCAmelCase				      =      self.cls(outputs[2]	)
     return outputs[:2] + (cls_out,)





class 							_UpperCAmelCase       (       UpperCAmelCase__       ):

  """simple docstring"""


  a_              =					FlaxBigBirdForNaturalQuestionsModule





def     a_       (					lowerCAmelCase_ :     str,      lowerCAmelCase_ :     int,      lowerCAmelCase_ :     Dict,      lowerCAmelCase_ :     List[Any],      lowerCAmelCase_ :     List[Any],      lowerCAmelCase_ :     Optional[Any]      ):





   def cross_entropy(lowerCAmelCase_ :     Union[str, Any],      lowerCAmelCase_ :     Any,      lowerCAmelCase_ :     Tuple=None      ):
      __lowerCAmelCase				      =      logits.shape[-1]
      __lowerCAmelCase				      =      (labels[..., None] == jnp.arange(_A      )[None]).astype('f4'      )
      __lowerCAmelCase				      =      jax.nn.log_softmax(_A,      axis=-1      )
      __lowerCAmelCase				      =      -jnp.sum(labels * logits,      axis=-1      )
      if reduction is not None:
         __lowerCAmelCase				      =      reduction(_A      )
      return loss

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



@dataclass
class 							_UpperCAmelCase       :

  """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.0_095

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






  def 							lowercase						(							self					:						List[Any]	)				->		Optional[int]:
     os.makedirs(self.base_dir   ,    exist_ok=__lowercase	)
     __lowerCAmelCase				      =      os.path.join(self.base_dir   ,    self.save_dir	)
     __lowerCAmelCase				      =      self.batch_size_per_device * jax.device_count()





@dataclass
class 							_UpperCAmelCase       :

  """simple docstring"""


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






  def __call__(							self					:						Union[str, Any]   ,    lowerCAmelCase_					:						Tuple	)				->		Dict:
     __lowerCAmelCase				      =      self.collate_fn(__lowercase	)
     __lowerCAmelCase				      =      jax.tree_util.tree_map(__lowercase   ,    __lowercase	)
     return batch






  def 							lowercase						(							self					:						List[Any]   ,    lowerCAmelCase_					:						int	)				->		int:
     __lowerCAmelCase      ,      __lowerCAmelCase				      =      self.fetch_inputs(features['input_ids']	)
     __lowerCAmelCase				      =      {
         'input_ids': jnp.array(__lowercase   ,    dtype=jnp.intaa	),
         'attention_mask': jnp.array(__lowercase   ,    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					:						Optional[Any]   ,    lowerCAmelCase_					:						list	)				->		List[str]:
     __lowerCAmelCase				      =      [self._fetch_inputs(__lowercase	) for ids in input_ids]
     return zip(*__lowercase	)






  def 							lowercase						(							self					:						Any   ,    lowerCAmelCase_					:						list	)				->		Optional[int]:
     __lowerCAmelCase				      =      [1 for _ in range(len(__lowercase	)	)]
     while len(__lowercase	) < self.max_length:
        input_ids.append(self.pad_id	)
        attention_mask.append(0	)
     return input_ids, attention_mask





def     a_       (					lowerCAmelCase_ :     int,      lowerCAmelCase_ :     List[Any],      lowerCAmelCase_ :     List[Any]=None      ):





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

@partial(jax.pmap,      axis_name='batch'      )
def     a_       (					lowerCAmelCase_ :     Optional[Any],      lowerCAmelCase_ :     str,      **lowerCAmelCase_ :     Union[str, Any]      ):





   def loss_fn(lowerCAmelCase_ :     Union[str, Any]      ):
      __lowerCAmelCase				      =      model_inputs.pop('start_labels'      )
      __lowerCAmelCase				      =      model_inputs.pop('end_labels'      )
      __lowerCAmelCase				      =      model_inputs.pop('pooled_labels'      )

      __lowerCAmelCase				      =      state.apply_fn(**_A,      params=_A,      dropout_rng=_A,      train=_A      )
      __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase				      =      outputs

      return state.loss_fn(
          _A,      _A,      _A,      _A,      _A,      _A,      )

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

   __lowerCAmelCase				      =      state.apply_gradients(grads=_A      )
   return state, metrics, new_drp_rng

@partial(jax.pmap,      axis_name='batch'      )
def     a_       (					lowerCAmelCase_ :     Dict,      **lowerCAmelCase_ :     Optional[int]      ):
   __lowerCAmelCase				      =      model_inputs.pop('start_labels'      )
   __lowerCAmelCase				      =      model_inputs.pop('end_labels'      )
   __lowerCAmelCase				      =      model_inputs.pop('pooled_labels'      )

   __lowerCAmelCase				      =      state.apply_fn(**_A,      params=state.params,      train=_A      )
   __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase				      =      outputs

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



class 							_UpperCAmelCase       (       train_state.TrainState       ):

  """simple docstring"""


  a_              =					struct.field(pytree_node=UpperCAmelCase__       )





@dataclass
class 							_UpperCAmelCase       :

  """simple docstring"""


  a_              =					42
  a_              =					42
  a_              =					42
  a_              =					42
  a_              =					42
  a_              =					42
  a_              =					None






  def 							lowercase						(							self					:						int   ,    lowerCAmelCase_					:						Any   ,    lowerCAmelCase_					:						Union[str, Any]   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						Optional[int]=None	)				->		Optional[Any]:
     __lowerCAmelCase				      =      model.params
     __lowerCAmelCase				      =      TrainState.create(
         apply_fn=model.__call__   ,    params=__lowercase   ,    tx=__lowercase   ,    loss_fn=__lowercase   ,    )
     if ckpt_dir is not None:
        __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase				      =      restore_checkpoint(__lowercase   ,    __lowercase	)
        __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(**__lowercase	)
        __lowerCAmelCase				      =      train_state.TrainState(
            step=__lowercase   ,    apply_fn=model.__call__   ,    params=__lowercase   ,    tx=__lowercase   ,    opt_state=__lowercase   ,    )
        __lowerCAmelCase				      =      args
        __lowerCAmelCase				      =      data_collator
        __lowerCAmelCase				      =      lr
        __lowerCAmelCase				      =      params
     __lowerCAmelCase				      =      jax_utils.replicate(__lowercase	)
     return state






  def 							lowercase						(							self					:						Optional[Any]   ,    lowerCAmelCase_					:						str   ,    lowerCAmelCase_					:						Tuple   ,    lowerCAmelCase_					:						str	)				->		List[str]:
     __lowerCAmelCase				      =      self.args
     __lowerCAmelCase				      =      len(__lowercase	) // args.batch_size

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

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






  def 							lowercase						(							self					:						str   ,    lowerCAmelCase_					:						List[Any]   ,    lowerCAmelCase_					:						str	)				->		Optional[int]:
     __lowerCAmelCase				      =      get_batched_dataset(__lowercase   ,    self.args.batch_size	)
     __lowerCAmelCase				      =      len(__lowercase	) // self.args.batch_size
     __lowerCAmelCase				      =      jnp.array(0   ,    dtype=jnp.floataa	)
     __lowerCAmelCase				      =      0
     for batch in tqdm(__lowercase   ,    total=__lowercase   ,    desc='Evaluating ... '	):
        __lowerCAmelCase				      =      self.data_collator(__lowercase	)
        __lowerCAmelCase				      =      self.val_step_fn(__lowercase   ,    **__lowercase	)
        running_loss += jax_utils.unreplicate(metrics['loss']	)
        i += 1
     return running_loss / i






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





def     a_       (					lowerCAmelCase_ :     int,      lowerCAmelCase_ :     Union[str, Any]      ):
   print(F"""RESTORING CHECKPOINT FROM {save_dir}""",      end=' ... '      )
   with open(os.path.join(_A,      'flax_model.msgpack'      ),      'rb'      ) as f:
      __lowerCAmelCase				      =      from_bytes(state.params,      f.read()      )

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

   __lowerCAmelCase				      =      joblib.load(os.path.join(_A,      'args.joblib'      )      )
   __lowerCAmelCase				      =      joblib.load(os.path.join(_A,      'data_collator.joblib'      )      )

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

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

def     a_       (					lowerCAmelCase_ :     List[str],      lowerCAmelCase_ :     Any,      lowerCAmelCase_ :     str,      lowerCAmelCase_ :     Dict      ):
   __lowerCAmelCase				      =      num_train_steps - warmup_steps
   __lowerCAmelCase				      =      optax.linear_schedule(init_value=_A,      end_value=_A,      transition_steps=_A      )
   __lowerCAmelCase				      =      optax.linear_schedule(init_value=_A,      end_value=1E-7,      transition_steps=_A      )
   __lowerCAmelCase				      =      optax.join_schedules(schedules=[warmup_fn, decay_fn],      boundaries=[warmup_steps]      )
   return lr




def     a_       (					lowerCAmelCase_ :     Optional[Any],      lowerCAmelCase_ :     List[Any],      lowerCAmelCase_ :     Union[str, Any],      lowerCAmelCase_ :     List[str],      lowerCAmelCase_ :     int      ):





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

   __lowerCAmelCase				      =      scheduler_fn(_A,      _A,      _A,      _A      )

   __lowerCAmelCase				      =      optax.adamw(learning_rate=_A,      weight_decay=_A,      mask=_A      )
   return tx, lr







import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized, parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
		from sagemaker import Session, TrainingJobAnalytics
		from sagemaker.huggingface import HuggingFace
@pytest.mark.skipif(
    literal_eval(os.getenv('''TEST_SAGEMAKER'''			,  '''False'''     )     ) is not True			,  reason='''Skipping test because should only be run when releasing minor transformers version'''			,  )
@pytest.mark.usefixtures('''sm_env'''     )
@parameterized_class(
    [
        {
            '''framework''': '''pytorch''',
            '''script''': '''run_glue_model_parallelism.py''',
            '''model_name_or_path''': '''roberta-large''',
            '''instance_type''': '''ml.p3dn.24xlarge''',
            '''results''': {'''train_runtime''': 1600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2},
        },
        {
            '''framework''': '''pytorch''',
            '''script''': '''run_glue.py''',
            '''model_name_or_path''': '''roberta-large''',
            '''instance_type''': '''ml.p3dn.24xlarge''',
            '''results''': {'''train_runtime''': 1600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2},
        },
    ]     )
class 						UpperCAmelCase  (							unittest.TestCase     ):







						'''simple docstring'''





						def 			snake_case__		(		self				:	int		):






							"""simple docstring"""






							if self.framework == "pytorch":
								subprocess.run(
								    f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split()			,      encoding="utf-8"			,      check=__lowercase			,      )
							assert hasattr(self			,      "env"		)






						def 			snake_case__		(		self				:	Any			,      __lowercase				:	Dict		):






							"""simple docstring"""






							snake_case_						       =	{
							    "enabled": True,
							    "processes_per_host": 8,
							}
							snake_case_						       =	{
							    "enabled": True,
							    "parameters": {
							        "microbatches": 4,
							        "placement_strategy": "spread",
							        "pipeline": "interleaved",
							        "optimize": "speed",
							        "partitions": 4,
							        "ddp": True,
							    },
							}

							snake_case_						       =	{"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options}

							snake_case_						       =	"trainer" if self.script == "run_glue.py" else "smtrainer"
							# creates estimator
							return HuggingFace(
							    entry_point=self.script			,      source_dir=self.env.test_path			,      role=self.env.role			,      image_uri=self.env.image_uri			,      base_job_name=f"{self.env.base_job_name}-{instance_count}-smp-{name_extension}"			,      instance_count=__lowercase			,      instance_type=self.instance_type			,      debugger_hook_config=__lowercase			,      hyperparameters={
							        **self.env.hyperparameters,
							        "model_name_or_path": self.model_name_or_path,
							        "max_steps": 5_00,
							    }			,      metric_definitions=self.env.metric_definitions			,      distribution=__lowercase			,      py_version="py36"			,      )






						def 			snake_case__		(		self				:	Tuple			,      __lowercase				:	Dict		):






							"""simple docstring"""






							TrainingJobAnalytics(__lowercase		).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv"		)






						@parameterized.expand([(1,)]		)
						def 			snake_case__		(		self				:	Any			,      __lowercase				:	int		):






							"""simple docstring"""






							snake_case_						       =	self.create_estimator(__lowercase		)

							# run training
							estimator.fit()

							# result dataframe
							snake_case_						       =	TrainingJobAnalytics(estimator.latest_training_job.name		).dataframe()

							# extract kpis
							snake_case_						       =	list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]		)
							snake_case_						       =	list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]		)
							# get train time from SageMaker job, this includes starting, preprocessing, stopping
							snake_case_						       =	(
							    Session().describe_training_job(estimator.latest_training_job.name		).get("TrainingTimeInSeconds"			,      99_99_99		)
							)

							# assert kpis
							assert train_runtime <= self.results["train_runtime"]
							assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy		)
							assert all(t <= self.results["eval_loss"] for t in eval_loss		)

							# dump tests result into json file to share in PR
							with open(f"{estimator.latest_training_job.name}.json"			,      "w"		) as outfile:
								json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}			,      __lowercase		)
