
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__							(       __lowercase):




	'''simple docstring'''




	_A			=  4_2
	_A			=  jnp.floataa
	_A			=  True







	def      _lowerCamelCase       (      self	:int		)	->				Dict:
								super().setup()
								__UpperCamelCase			:     Optional[Any]         =      nn.Dense(5  ,     dtype=self.dtype		)







	def __call__(      self	:str  ,     *a	:Union[str, Any]  ,     **a	:Optional[Any]		)	->				Dict:
								__UpperCamelCase			:     str         =      super().__call__(*__a  ,     **__a		)
								__UpperCamelCase			:     Dict         =      self.cls(outputs[2]		)
								return outputs[:2] + (cls_out,)




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	_A			=  FlaxBigBirdForNaturalQuestionsModule




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    List[Any]		,						_lowerCamelCase				:    Any		,						_lowerCamelCase				:    List[Any]		,						_lowerCamelCase				:    int		,						_lowerCamelCase				:    Union[str, Any]		,						_lowerCamelCase				:    List[str])      ->					List[str]:






							'''simple docstring'''





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

							__UpperCamelCase			:     Dict         =      partial(__snake_case		,						reduction=jnp.mean)
							__UpperCamelCase			:     List[str]         =      cross_entropy(__snake_case		,						__snake_case)
							__UpperCamelCase			:     int         =      cross_entropy(__snake_case		,						__snake_case)
							__UpperCamelCase			:     int         =      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			=  3_0_0_0
	_A			=  1_0_5_0_0

	_A			=  1_2_8
	_A			=  3

	_A			=  1
	_A			=  5

	# tx_args
	_A			=  3E-5
	_A			=  0.0
	_A			=  2_0_0_0_0
	_A			=  0.0095

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







	def      _lowerCamelCase       (      self	:str		)	->				Optional[Any]:
								os.makedirs(self.base_dir  ,     exist_ok=__a		)
								__UpperCamelCase			:     Dict         =      os.path.join(self.base_dir  ,     self.save_dir		)
								__UpperCamelCase			:     List[Any]         =      self.batch_size_per_device * jax.device_count()




@dataclass
class 				lowerCamelCase__							:




	'''simple docstring'''




	_A			=  4_2
	_A			=  4_0_9_6  # no dynamic padding on TPUs







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







	def      _lowerCamelCase       (      self	:List[str]  ,     a	:int		)	->				Tuple:
								__UpperCamelCase     ,		__UpperCamelCase			:     str         =      self.fetch_inputs(features["input_ids"]		)
								__UpperCamelCase			:     List[str]         =      {
								    "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      _lowerCamelCase       (      self	:List[Any]  ,     a	:Union[str, Any]		)	->				List[str]:
								__UpperCamelCase			:     Tuple         =      [self._fetch_inputs(__a		) for ids in input_ids]
								return zip(*__a		)







	def      _lowerCamelCase       (      self	:List[str]  ,     a	:Any		)	->				Any:
								__UpperCamelCase			:     Any         =      [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 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    str		,						_lowerCamelCase				:    Union[str, Any]		,						_lowerCamelCase				:    Any=None)      ->					Optional[Any]:






							'''simple docstring'''





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




@partial(jax.pmap		,						axis_name="batch")
def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    int		,						_lowerCamelCase				:    str		,						**_lowerCamelCase				:    Optional[int])      ->					Union[str, Any]:






							'''simple docstring'''





							def loss_fn(_lowerCamelCase				:    Any):
														__UpperCamelCase			:     int         =      model_inputs.pop("start_labels")
														__UpperCamelCase			:     List[str]         =      model_inputs.pop("end_labels")
														__UpperCamelCase			:     Union[str, Any]         =      model_inputs.pop("pooled_labels")

														__UpperCamelCase			:     Tuple         =      state.apply_fn(**__snake_case		,						params=__snake_case		,						dropout_rng=__snake_case		,						train=__snake_case)
														__UpperCamelCase     ,		__UpperCamelCase     ,		__UpperCamelCase			:     Any         =      outputs

														return state.loss_fn(
														    __snake_case		,						__snake_case		,						__snake_case		,						__snake_case		,						__snake_case		,						__snake_case		,						)

							__UpperCamelCase     ,		__UpperCamelCase			:     Any         =      jax.random.split(__snake_case)
							__UpperCamelCase			:     Optional[Any]         =      jax.value_and_grad(__snake_case)
							__UpperCamelCase     ,		__UpperCamelCase			:     List[str]         =      grad_fn(state.params)
							__UpperCamelCase			:     List[str]         =      jax.lax.pmean({"loss": loss}		,						axis_name="batch")
							__UpperCamelCase			:     List[str]         =      jax.lax.pmean(__snake_case		,						"batch")

							__UpperCamelCase			:     Optional[int]         =      state.apply_gradients(grads=__snake_case)
							return state, metrics, new_drp_rng




@partial(jax.pmap		,						axis_name="batch")
def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    Dict		,						**_lowerCamelCase				:    int)      ->					Union[str, Any]:






							'''simple docstring'''





							__UpperCamelCase			:     Any         =      model_inputs.pop("start_labels")
							__UpperCamelCase			:     Optional[Any]         =      model_inputs.pop("end_labels")
							__UpperCamelCase			:     Optional[Any]         =      model_inputs.pop("pooled_labels")

							__UpperCamelCase			:     Any         =      state.apply_fn(**__snake_case		,						params=state.params		,						train=__snake_case)
							__UpperCamelCase     ,		__UpperCamelCase     ,		__UpperCamelCase			:     Union[str, Any]         =      outputs

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




class 				lowerCamelCase__							(       train_state.TrainState):




	'''simple docstring'''




	_A			=  struct.field(pytree_node=__lowercase)




@dataclass
class 				lowerCamelCase__							:




	'''simple docstring'''




	_A			=  4_2
	_A			=  4_2
	_A			=  4_2
	_A			=  4_2
	_A			=  4_2
	_A			=  4_2
	_A			=  None







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







	def      _lowerCamelCase       (      self	:Union[str, Any]  ,     a	:List[Any]  ,     a	:Dict  ,     a	:Optional[Any]		)	->				List[Any]:
								__UpperCamelCase			:     Optional[int]         =      self.args
								__UpperCamelCase			:     Optional[int]         =      len(__a		) // args.batch_size

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

																													__UpperCamelCase			:     Tuple         =      self.evaluate(__a  ,     __a		)
																													__UpperCamelCase			:     Optional[Any]         =      {
																													    "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      _lowerCamelCase       (      self	:Dict  ,     a	:Optional[Any]  ,     a	:str		)	->				Any:
								__UpperCamelCase			:     Dict         =      get_batched_dataset(__a  ,     self.args.batch_size		)
								__UpperCamelCase			:     str         =      len(__a		) // self.args.batch_size
								__UpperCamelCase			:     str         =      jnp.array(0  ,     dtype=jnp.floataa		)
								__UpperCamelCase			:     Dict         =      0
								for batch in tqdm(__a  ,     total=__a  ,     desc="Evaluating ... "		):
															__UpperCamelCase			:     Dict         =      self.data_collator(__a		)
															__UpperCamelCase			:     Tuple         =      self.val_step_fn(__a  ,     **__a		)
															running_loss += jax_utils.unreplicate(metrics["loss"]		)
															i += 1
								return running_loss / i







	def      _lowerCamelCase       (      self	:Optional[Any]  ,     a	:Tuple  ,     a	:Dict		)	->				int:
								__UpperCamelCase			:     Any         =      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 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    Optional[int]		,						_lowerCamelCase				:    str)      ->					int:






							'''simple docstring'''





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

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

							__UpperCamelCase			:     Any         =      joblib.load(os.path.join(__snake_case		,						"args.joblib"))
							__UpperCamelCase			:     Tuple         =      joblib.load(os.path.join(__snake_case		,						"data_collator.joblib"))

							with open(os.path.join(__snake_case		,						"training_state.json")		,						"r") as f:
														__UpperCamelCase			:     int         =      json.load(__snake_case)
							__UpperCamelCase			:     List[Any]         =      training_state["step"]

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




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    List[str]		,						_lowerCamelCase				:    List[Any]		,						_lowerCamelCase				:    Union[str, Any]		,						_lowerCamelCase				:    Optional[Any])      ->					List[str]:






							'''simple docstring'''





							__UpperCamelCase			:     List[Any]         =      num_train_steps - warmup_steps
							__UpperCamelCase			:     Optional[Any]         =      optax.linear_schedule(init_value=__snake_case		,						end_value=__snake_case		,						transition_steps=__snake_case)
							__UpperCamelCase			:     str         =      optax.linear_schedule(init_value=__snake_case		,						end_value=1e-7		,						transition_steps=__snake_case)
							__UpperCamelCase			:     Union[str, Any]         =      optax.join_schedules(schedules=[warmup_fn, decay_fn]		,						boundaries=[warmup_steps])
							return lr




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    List[Any]		,						_lowerCamelCase				:    Optional[int]		,						_lowerCamelCase				:    Optional[Any]		,						_lowerCamelCase				:    Any		,						_lowerCamelCase				:    Union[str, Any])      ->					Tuple:






							'''simple docstring'''





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

							__UpperCamelCase			:     int         =      scheduler_fn(__snake_case		,						__snake_case		,						__snake_case		,						__snake_case)

							__UpperCamelCase			:     str         =      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_tf_available, is_torch_available


lowercase						:      List[Any]									= {'configuration_swin': ['SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwinConfig', 'SwinOnnxConfig']}


try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase						:      Dict									= [
		    'SWIN_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'SwinForImageClassification',
		    'SwinForMaskedImageModeling',
		    'SwinModel',
		    'SwinPreTrainedModel',
		    'SwinBackbone',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase						:      Optional[int]									= [
		    'TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'TFSwinForImageClassification',
		    'TFSwinForMaskedImageModeling',
		    'TFSwinModel',
		    'TFSwinPreTrainedModel',
		]

if TYPE_CHECKING:
		from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_swin import (
				    SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
				    SwinBackbone,
				    SwinForImageClassification,
				    SwinForMaskedImageModeling,
				    SwinModel,
				    SwinPreTrainedModel,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_swin import (
				    TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFSwinForImageClassification,
				    TFSwinForMaskedImageModeling,
				    TFSwinModel,
				    TFSwinPreTrainedModel,
				)

else:
		import sys

		lowercase						:      Optional[Any]									= _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)