




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



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



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







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







								"""simple docstring"""



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







class  A		(  __UpperCAmelCase     ):
		__snake_case									=   FlaxBigBirdForNaturalQuestionsModule







def __UpperCamelCase			(       _A ,  _A ,  _A ,  _A ,  _A ,  _A  ):
						def cross_entropy(_A ,  _A ,  _A=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  A		:
		__snake_case									=   "google/bigbird-roberta-base"
		__snake_case									=   3000
		__snake_case									=   1_0500

		__snake_case									=   128
		__snake_case									=   3

		__snake_case									=   1
		__snake_case									=   5

		# tx_args
		__snake_case									=   3E-5
		__snake_case									=   0.0
		__snake_case									=   2_0000
		__snake_case									=   0.0095

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



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



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







@dataclass
class  A		:
		__snake_case									=   42
		__snake_case									=   4096  # no dynamic padding on TPUs



		def __call__(     self,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  self.collate_fn(UpperCamelCase__   )
								lowerCAmelCase_      			=  jax.tree_util.tree_map(UpperCamelCase__,	UpperCamelCase__   )
								return batch



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_			,					lowerCAmelCase_      			=  self.fetch_inputs(features['''input_ids''']   )
								lowerCAmelCase_      			=  {
								    '''input_ids''': jnp.array(UpperCamelCase__,	dtype=jnp.intaa   ),
								    '''attention_mask''': jnp.array(UpperCamelCase__,	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        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  [self._fetch_inputs(UpperCamelCase__   ) for ids in input_ids]
								return zip(*UpperCamelCase__   )







		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__   ):







								"""simple docstring"""



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







def __UpperCamelCase			(       _A ,  _A ,  _A=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 __UpperCamelCase			(       _A ,  _A ,  **_A  ):
						def loss_fn(_A  ):
												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 __UpperCamelCase			(       _A ,  **_A  ):
						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  A		(  train_state.TrainState     ):
		__snake_case									=   struct.field(pytree_node=__UpperCAmelCase     )







@dataclass
class  A		:
		__snake_case									=   42
		__snake_case									=   42
		__snake_case									=   42
		__snake_case									=   42
		__snake_case									=   42
		__snake_case									=   42
		__snake_case									=   None



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__=None   ):







								"""simple docstring"""



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



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  self.args
								lowerCAmelCase_      			=  len(UpperCamelCase__   ) // args.batch_size

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

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



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



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







		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



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







def __UpperCamelCase			(       _A ,  _A  ):
						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 __UpperCamelCase			(       _A ,  _A ,  _A ,  _A  ):
						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 __UpperCamelCase			(       _A ,  _A ,  _A ,  _A ,  _A  ):
						def weight_decay_mask(_A  ):
												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










from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
						if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline
else:
						from .pipeline_unclip import UnCLIPPipeline
						from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline
						from .text_proj import UnCLIPTextProjModel




