



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'''




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






						def 	_A     (   self		):







													'''simple docstring'''

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






						def __call__(   self				,							*_A				,							**_A		):







													'''simple docstring'''

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







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Dict      =  FlaxBigBirdForNaturalQuestionsModule







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

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

@dataclass
class        UpperCAmelCase_  :

						'''simple docstring'''




						UpperCamelCase__      :			str      =  "google/bigbird-roberta-base"
						UpperCamelCase__      :			int      =  3000
						UpperCamelCase__      :			int      =  10500

						UpperCamelCase__      :			int      =  128
						UpperCamelCase__      :			int      =  3

						UpperCamelCase__      :			int      =  1
						UpperCamelCase__      :			int      =  5

						# tx_args
						UpperCamelCase__      :			float      =  3e-5
						UpperCamelCase__      :			float      =  0.0
						UpperCamelCase__      :			int      =  20000
						UpperCamelCase__      :			float      =  0.0_0_9_5

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






						def 	_A     (   self		):







													'''simple docstring'''

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







@dataclass
class        UpperCAmelCase_  :

						'''simple docstring'''




						UpperCamelCase__      :			int
						UpperCamelCase__      :			int      =  4096  # no dynamic padding on TPUs






						def __call__(   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.collate_fn(_A		)
													__SCREAMING_SNAKE_CASE									= jax.tree_util.tree_map(_A				,							_A		)
													return batch






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

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







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= [self._fetch_inputs(_A		) for ids in input_ids]
													return zip(*_A		)






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= [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      __lowercase       (			a__							,       a__							,       a__=None       )    ->			str:
							if seed is not None:
														__SCREAMING_SNAKE_CASE									= dataset.shuffle(seed=a__       )
							for i in range(len(a__       ) // batch_size       ):
														__SCREAMING_SNAKE_CASE									= dataset[i * batch_size : (i + 1) * batch_size]
														yield dict(a__       )






@partial(jax.pmap							,       axis_name='batch'       )
def      __lowercase       (			a__							,       a__							,       **a__       )    ->			Union[str, Any]:
							def loss_fn(a__       ):
														__SCREAMING_SNAKE_CASE									= model_inputs.pop('start_labels'       )
														__SCREAMING_SNAKE_CASE									= model_inputs.pop('end_labels'       )
														__SCREAMING_SNAKE_CASE									= model_inputs.pop('pooled_labels'       )

														__SCREAMING_SNAKE_CASE									= state.apply_fn(**a__							,       params=a__							,       dropout_rng=a__							,       train=a__       )
														__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= outputs

														return state.loss_fn(
														    a__							,       a__							,       a__							,       a__							,       a__							,       a__							,       )

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

							__SCREAMING_SNAKE_CASE									= state.apply_gradients(grads=a__       )
							return state, metrics, new_drp_rng






@partial(jax.pmap							,       axis_name='batch'       )
def      __lowercase       (			a__							,       **a__       )    ->			List[Any]:
							__SCREAMING_SNAKE_CASE									= model_inputs.pop('start_labels'       )
							__SCREAMING_SNAKE_CASE									= model_inputs.pop('end_labels'       )
							__SCREAMING_SNAKE_CASE									= model_inputs.pop('pooled_labels'       )

							__SCREAMING_SNAKE_CASE									= state.apply_fn(**a__							,       params=state.params							,       train=a__       )
							__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= outputs

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

class        UpperCAmelCase_  (       train_state.TrainState	):

						'''simple docstring'''




						UpperCamelCase__      :			Callable      =  struct.field(pytree_node=UpperCamelCase_	)







@dataclass
class        UpperCAmelCase_  :

						'''simple docstring'''




						UpperCamelCase__      :			Args
						UpperCamelCase__      :			Callable
						UpperCamelCase__      :			Callable
						UpperCamelCase__      :			Callable
						UpperCamelCase__      :			Callable
						UpperCamelCase__      :			wandb
						UpperCamelCase__      :			Callable      =  None






						def 	_A     (   self				,							_A				,							_A				,							_A				,							_A=None		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= model.params
													__SCREAMING_SNAKE_CASE									= TrainState.create(
													    apply_fn=model.__call__				,							params=_A				,							tx=_A				,							loss_fn=_A				,							)
													if ckpt_dir is not None:
																				__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= restore_checkpoint(_A				,							_A		)
																				__SCREAMING_SNAKE_CASE									= {
																				    'lr': args.lr,
																				    'init_lr': args.init_lr,
																				    'warmup_steps': args.warmup_steps,
																				    'num_train_steps': num_train_steps,
																				    'weight_decay': args.weight_decay,
																				}
																				__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= build_tx(**_A		)
																				__SCREAMING_SNAKE_CASE									= train_state.TrainState(
																				    step=_A				,							apply_fn=model.__call__				,							params=_A				,							tx=_A				,							opt_state=_A				,							)
																				__SCREAMING_SNAKE_CASE									= args
																				__SCREAMING_SNAKE_CASE									= data_collator
																				__SCREAMING_SNAKE_CASE									= lr
																				__SCREAMING_SNAKE_CASE									= params
													__SCREAMING_SNAKE_CASE									= jax_utils.replicate(_A		)
													return state






						def 	_A     (   self				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.args
													__SCREAMING_SNAKE_CASE									= len(_A		) // args.batch_size

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

																																		__SCREAMING_SNAKE_CASE									= self.evaluate(_A				,							_A		)
																																		__SCREAMING_SNAKE_CASE									= {
																																		    '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		):







													'''simple docstring'''

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






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= 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      __lowercase       (			a__							,       a__       )    ->			Tuple:
							print(f"""RESTORING CHECKPOINT FROM {save_dir}"""							,       end=' ... '       )
							with open(os.path.join(a__							,       'flax_model.msgpack'       )							,       'rb'       ) as f:
														__SCREAMING_SNAKE_CASE									= from_bytes(state.params							,       f.read()       )

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

							__SCREAMING_SNAKE_CASE									= joblib.load(os.path.join(a__							,       'args.joblib'       )       )
							__SCREAMING_SNAKE_CASE									= joblib.load(os.path.join(a__							,       'data_collator.joblib'       )       )

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

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






def      __lowercase       (			a__							,       a__							,       a__							,       a__       )    ->			List[Any]:
							__SCREAMING_SNAKE_CASE									= num_train_steps - warmup_steps
							__SCREAMING_SNAKE_CASE									= optax.linear_schedule(init_value=a__							,       end_value=a__							,       transition_steps=a__       )
							__SCREAMING_SNAKE_CASE									= optax.linear_schedule(init_value=a__							,       end_value=1E-7							,       transition_steps=a__       )
							__SCREAMING_SNAKE_CASE									= optax.join_schedules(schedules=[warmup_fn, decay_fn]							,       boundaries=[warmup_steps]       )
							return lr






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

							__SCREAMING_SNAKE_CASE									= scheduler_fn(a__							,       a__							,       a__							,       a__       )

							__SCREAMING_SNAKE_CASE									= optax.adamw(learning_rate=a__							,       weight_decay=a__							,       mask=a__       )
							return tx, lr











from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowerCAmelCase__		:					List[str]							={
    '''configuration_timesformer''': ['''TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TimesformerConfig'''],
}

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCAmelCase__		:					List[str]							=[
			    '''TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
			    '''TimesformerModel''',
			    '''TimesformerForVideoClassification''',
			    '''TimesformerPreTrainedModel''',
			]

if TYPE_CHECKING:
			from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_timesformer import (
						    TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TimesformerForVideoClassification,
						    TimesformerModel,
						    TimesformerPreTrainedModel,
						)

else:
			import sys

			lowerCAmelCase__		:					Union[str, Any]							=_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)






