


'''simple docstring'''






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       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		jnp.floataa
 _lowerCAmelCase	   =		True
 def 							__UpperCAmelCase						(	self  )   ->							Optional[Any]:
      super().setup()
      _a      =							nn.Dense(5 ,			dtype=self.dtype  )




 def __call__(	self ,			*__magic_name__ ,			**__magic_name__  )   ->							Optional[Any]:
      _a      =							super().__call__(*__magic_name__ ,			**__magic_name__  )
      _a      =							self.cls(outputs[2]  )
      return outputs[:2] + (cls_out,)





class 	a       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		FlaxBigBirdForNaturalQuestionsModule






def 		_A			(lowerCAmelCase__					:Any			,  lowerCAmelCase__					:int			,  lowerCAmelCase__					:Union[str, Any]			,  lowerCAmelCase__					:int			,  lowerCAmelCase__					:Optional[int]			,  lowerCAmelCase__					:str						)				->					str:




     '''simple docstring'''



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

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




@dataclass
class 	a       :
 _lowerCAmelCase	   =		"google/bigbird-roberta-base"
 _lowerCAmelCase	   =		3_0_0_0
 _lowerCAmelCase	   =		1_0_5_0_0

 _lowerCAmelCase	   =		1_2_8
 _lowerCAmelCase	   =		3

 _lowerCAmelCase	   =		1
 _lowerCAmelCase	   =		5

 # tx_args
 _lowerCAmelCase	   =		3E-5
 _lowerCAmelCase	   =		0.0
 _lowerCAmelCase	   =		2_0_0_0_0
 _lowerCAmelCase	   =		0.0_095

 _lowerCAmelCase	   =		"bigbird-roberta-natural-questions"
 _lowerCAmelCase	   =		"training-expt"
 _lowerCAmelCase	   =		"data/nq-training.jsonl"
 _lowerCAmelCase	   =		"data/nq-validation.jsonl"
 def 							__UpperCAmelCase						(	self  )   ->							Optional[int]:
      os.makedirs(self.base_dir ,			exist_ok=__magic_name__  )
      _a      =							os.path.join(self.base_dir ,			self.save_dir  )
      _a      =							self.batch_size_per_device * jax.device_count()





@dataclass
class 	a       :
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		4_0_9_6  # no dynamic padding on TPUs
 def __call__(	self ,			__magic_name__  )   ->							List[str]:
      _a      =							self.collate_fn(__magic_name__  )
      _a      =							jax.tree_util.tree_map(__magic_name__ ,			__magic_name__  )
      return batch
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							List[Any]:
      _a ,				_a      =							self.fetch_inputs(features['input_ids']  )
      _a      =							{
          'input_ids': jnp.array(__magic_name__ ,			dtype=jnp.intaa  ),
          'attention_mask': jnp.array(__magic_name__ ,			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 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							List[Any]:
      _a      =							[self._fetch_inputs(__magic_name__  ) for ids in input_ids]
      return zip(*__magic_name__  )




 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							List[str]:
      _a      =							[1 for _ in range(len(__magic_name__  )  )]
      while len(__magic_name__  ) < self.max_length:
           input_ids.append(self.pad_id  )
           attention_mask.append(0  )
      return input_ids, attention_mask






def 		_A			(lowerCAmelCase__					:Any			,  lowerCAmelCase__					:Dict			,  lowerCAmelCase__					:List[Any]=None						)				->					Dict:




     '''simple docstring'''



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






@partial(jax.pmap			,  axis_name='batch'						)
def 		_A			(lowerCAmelCase__					:Tuple			,  lowerCAmelCase__					:Any			,  **lowerCAmelCase__					:Dict						)				->					Dict:




     '''simple docstring'''



     def loss_fn(lowerCAmelCase__					:Tuple						):
          _a      =							model_inputs.pop('start_labels'						)
          _a      =							model_inputs.pop('end_labels'						)
          _a      =							model_inputs.pop('pooled_labels'						)

          _a      =							state.apply_fn(**lowerCAmelCase__			,  params=lowerCAmelCase__			,  dropout_rng=lowerCAmelCase__			,  train=lowerCAmelCase__						)
          _a ,				_a ,				_a      =							outputs

          return state.loss_fn(
              lowerCAmelCase__			,  lowerCAmelCase__			,  lowerCAmelCase__			,  lowerCAmelCase__			,  lowerCAmelCase__			,  lowerCAmelCase__			,  )

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

     _a      =							state.apply_gradients(grads=lowerCAmelCase__						)
     return state, metrics, new_drp_rng






@partial(jax.pmap			,  axis_name='batch'						)
def 		_A			(lowerCAmelCase__					:Tuple			,  **lowerCAmelCase__					:List[Any]						)				->					Union[str, Any]:




     '''simple docstring'''



     _a      =							model_inputs.pop('start_labels'						)
     _a      =							model_inputs.pop('end_labels'						)
     _a      =							model_inputs.pop('pooled_labels'						)

     _a      =							state.apply_fn(**lowerCAmelCase__			,  params=state.params			,  train=lowerCAmelCase__						)
     _a ,				_a ,				_a      =							outputs

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




class 	a       (       train_state.TrainState    ):
 _lowerCAmelCase	   =		struct.field(pytree_node=_SCREAMING_SNAKE_CASE    )





@dataclass
class 	a       :
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		None
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__ ,			__magic_name__=None  )   ->							Dict:
      _a      =							model.params
      _a      =							TrainState.create(
          apply_fn=model.__call__ ,			params=__magic_name__ ,			tx=__magic_name__ ,			loss_fn=__magic_name__ ,			)
      if ckpt_dir is not None:
           _a ,				_a ,				_a ,				_a ,				_a      =							restore_checkpoint(__magic_name__ ,			__magic_name__  )
           _a      =							{
               'lr': args.lr,
               'init_lr': args.init_lr,
               'warmup_steps': args.warmup_steps,
               'num_train_steps': num_train_steps,
               'weight_decay': args.weight_decay,
           }
           _a ,				_a      =							build_tx(**__magic_name__  )
           _a      =							train_state.TrainState(
               step=__magic_name__ ,			apply_fn=model.__call__ ,			params=__magic_name__ ,			tx=__magic_name__ ,			opt_state=__magic_name__ ,			)
           _a      =							args
           _a      =							data_collator
           _a      =							lr
           _a      =							params
      _a      =							jax_utils.replicate(__magic_name__  )
      return state
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__  )   ->							Union[str, Any]:
      _a      =							self.args
      _a      =							len(__magic_name__  ) // args.batch_size

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

                     _a      =							self.evaluate(__magic_name__ ,			__magic_name__  )
                     _a      =							{
                         'step': state_step.item(),
                         'eval_loss': eval_loss.item(),
                         'tr_loss': tr_loss,
                         'lr': lr.item(),
                     }
                     tqdm.write(str(__magic_name__  )  )
                     self.logger.log(__magic_name__ ,			commit=__magic_name__  )

                if i % args.save_steps == 0:
                     self.save_checkpoint(args.save_dir + f'-e{epoch}-s{i}' ,			state=__magic_name__  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							Union[str, Any]:
      _a      =							get_batched_dataset(__magic_name__ ,			self.args.batch_size  )
      _a      =							len(__magic_name__  ) // self.args.batch_size
      _a      =							jnp.array(0 ,			dtype=jnp.floataa  )
      _a      =							0
      for batch in tqdm(__magic_name__ ,			total=__magic_name__ ,			desc='Evaluating ... '  ):
           _a      =							self.data_collator(__magic_name__  )
           _a      =							self.val_step_fn(__magic_name__ ,			**__magic_name__  )
           running_loss += jax_utils.unreplicate(metrics['loss']  )
           i += 1
      return running_loss / i




 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							Optional[int]:
      _a      =							jax_utils.unreplicate(__magic_name__  )
      print(f'SAVING CHECKPOINT IN {save_dir}' ,			end=' ... '  )
      self.model_save_fn(__magic_name__ ,			params=state.params  )
      with open(os.path.join(__magic_name__ ,			'opt_state.msgpack'  ) ,			'wb'  ) as f:
           f.write(to_bytes(state.opt_state  )  )
      joblib.dump(self.args ,			os.path.join(__magic_name__ ,			'args.joblib'  )  )
      joblib.dump(self.data_collator ,			os.path.join(__magic_name__ ,			'data_collator.joblib'  )  )
      with open(os.path.join(__magic_name__ ,			'training_state.json'  ) ,			'w'  ) as f:
           json.dump({'step': state.step.item()} ,			__magic_name__  )
      print('DONE'  )






def 		_A			(lowerCAmelCase__					:Optional[Any]			,  lowerCAmelCase__					:Optional[Any]						)				->					List[Any]:




     '''simple docstring'''



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

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

     _a      =							joblib.load(os.path.join(lowerCAmelCase__			,  'args.joblib'						)						)
     _a      =							joblib.load(os.path.join(lowerCAmelCase__			,  'data_collator.joblib'						)						)

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

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






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




     '''simple docstring'''



     _a      =							num_train_steps - warmup_steps
     _a      =							optax.linear_schedule(init_value=lowerCAmelCase__			,  end_value=lowerCAmelCase__			,  transition_steps=lowerCAmelCase__						)
     _a      =							optax.linear_schedule(init_value=lowerCAmelCase__			,  end_value=1E-7			,  transition_steps=lowerCAmelCase__						)
     _a      =							optax.join_schedules(schedules=[warmup_fn, decay_fn]			,  boundaries=[warmup_steps]						)
     return lr






def 		_A			(lowerCAmelCase__					:List[Any]			,  lowerCAmelCase__					:List[str]			,  lowerCAmelCase__					:str			,  lowerCAmelCase__					:List[str]			,  lowerCAmelCase__					:int						)				->					List[str]:




     '''simple docstring'''



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

     _a      =							scheduler_fn(lowerCAmelCase__			,  lowerCAmelCase__			,  lowerCAmelCase__			,  lowerCAmelCase__						)

     _a      =							optax.adamw(learning_rate=lowerCAmelCase__			,  weight_decay=lowerCAmelCase__			,  mask=lowerCAmelCase__						)
     return tx, lr





'''simple docstring'''






import unittest

from diffusers.pipelines.pipeline_utils import is_safetensors_compatible




class 	a       (       unittest.TestCase    ):
 def 							__UpperCAmelCase						(	self  )   ->							int:
      _a      =							[
          'safety_checker/pytorch_model.bin',
          'safety_checker/model.safetensors',
          'vae/diffusion_pytorch_model.bin',
          'vae/diffusion_pytorch_model.safetensors',
          'text_encoder/pytorch_model.bin',
          'text_encoder/model.safetensors',
          'unet/diffusion_pytorch_model.bin',
          'unet/diffusion_pytorch_model.safetensors',
      ]
      self.assertTrue(is_safetensors_compatible(__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							Dict:
      _a      =							[
          'unet/diffusion_pytorch_model.bin',
          'unet/diffusion_pytorch_model.safetensors',
      ]
      self.assertTrue(is_safetensors_compatible(__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							Optional[int]:
      _a      =							[
          'safety_checker/pytorch_model.bin',
          'safety_checker/model.safetensors',
          'vae/diffusion_pytorch_model.bin',
          'vae/diffusion_pytorch_model.safetensors',
          'text_encoder/pytorch_model.bin',
          'text_encoder/model.safetensors',
          'unet/diffusion_pytorch_model.bin',
          # Removed: 'unet/diffusion_pytorch_model.safetensors',
      ]
      self.assertFalse(is_safetensors_compatible(__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							Optional[Any]:
      _a      =							[
          'text_encoder/pytorch_model.bin',
          'text_encoder/model.safetensors',
      ]
      self.assertTrue(is_safetensors_compatible(__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							str:
      _a      =							[
          'safety_checker/pytorch_model.bin',
          'safety_checker/model.safetensors',
          'vae/diffusion_pytorch_model.bin',
          'vae/diffusion_pytorch_model.safetensors',
          'text_encoder/pytorch_model.bin',
          # Removed: 'text_encoder/model.safetensors',
          'unet/diffusion_pytorch_model.bin',
          'unet/diffusion_pytorch_model.safetensors',
      ]
      self.assertFalse(is_safetensors_compatible(__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							List[Any]:
      _a      =							[
          'safety_checker/pytorch_model.fp16.bin',
          'safety_checker/model.fp16.safetensors',
          'vae/diffusion_pytorch_model.fp16.bin',
          'vae/diffusion_pytorch_model.fp16.safetensors',
          'text_encoder/pytorch_model.fp16.bin',
          'text_encoder/model.fp16.safetensors',
          'unet/diffusion_pytorch_model.fp16.bin',
          'unet/diffusion_pytorch_model.fp16.safetensors',
      ]
      _a      =							'fp16'
      self.assertTrue(is_safetensors_compatible(__magic_name__ ,			variant=__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							Any:
      _a      =							[
          'unet/diffusion_pytorch_model.fp16.bin',
          'unet/diffusion_pytorch_model.fp16.safetensors',
      ]
      _a      =							'fp16'
      self.assertTrue(is_safetensors_compatible(__magic_name__ ,			variant=__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							int:
      # pass variant but use the non-variant filenames
      _a      =							[
          'unet/diffusion_pytorch_model.bin',
          'unet/diffusion_pytorch_model.safetensors',
      ]
      _a      =							'fp16'
      self.assertTrue(is_safetensors_compatible(__magic_name__ ,			variant=__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							List[str]:
      _a      =							[
          'safety_checker/pytorch_model.fp16.bin',
          'safety_checker/model.fp16.safetensors',
          'vae/diffusion_pytorch_model.fp16.bin',
          'vae/diffusion_pytorch_model.fp16.safetensors',
          'text_encoder/pytorch_model.fp16.bin',
          'text_encoder/model.fp16.safetensors',
          'unet/diffusion_pytorch_model.fp16.bin',
          # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
      ]
      _a      =							'fp16'
      self.assertFalse(is_safetensors_compatible(__magic_name__ ,			variant=__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							Union[str, Any]:
      _a      =							[
          'text_encoder/pytorch_model.fp16.bin',
          'text_encoder/model.fp16.safetensors',
      ]
      _a      =							'fp16'
      self.assertTrue(is_safetensors_compatible(__magic_name__ ,			variant=__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							List[Any]:
      # pass variant but use the non-variant filenames
      _a      =							[
          'text_encoder/pytorch_model.bin',
          'text_encoder/model.safetensors',
      ]
      _a      =							'fp16'
      self.assertTrue(is_safetensors_compatible(__magic_name__ ,			variant=__magic_name__  )  )




 def 							__UpperCAmelCase						(	self  )   ->							List[Any]:
      _a      =							[
          'safety_checker/pytorch_model.fp16.bin',
          'safety_checker/model.fp16.safetensors',
          'vae/diffusion_pytorch_model.fp16.bin',
          'vae/diffusion_pytorch_model.fp16.safetensors',
          'text_encoder/pytorch_model.fp16.bin',
          # 'text_encoder/model.fp16.safetensors',
          'unet/diffusion_pytorch_model.fp16.bin',
          'unet/diffusion_pytorch_model.fp16.safetensors',
      ]
      _a      =							'fp16'
      self.assertFalse(is_safetensors_compatible(__magic_name__ ,			variant=__magic_name__  )  )

