


'''simple docstring'''







from ...configuration_utils import PretrainedConfig


a__  :					Dict        =       {
    'google/tapas-base-finetuned-sqa': (
        'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json'
    ),
    'google/tapas-base-finetuned-wtq': (
        'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json'
    ),
    'google/tapas-base-finetuned-wikisql-supervised': (
        'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json'
    ),
    'google/tapas-base-finetuned-tabfact': (
        'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json'
    ),
}
class 					lowercase_     (    a__   ):
    __UpperCAmelCase   			=	'tapas'


    def __init__(     self  ,					a=3_05_22  ,					a=7_68  ,					a=12  ,					a=12  ,					a=30_72  ,					a="gelu"  ,					a=0.1  ,					a=0.1  ,					a=10_24  ,					a=[3, 2_56, 2_56, 2, 2_56, 2_56, 10]  ,					a=0.02  ,					a=1e-12  ,					a=0  ,					a=10.0  ,					a=0  ,					a=1.0  ,					a=None  ,					a=1.0  ,					a=False  ,					a=None  ,					a=1.0  ,					a=1.0  ,					a=False  ,					a=False  ,					a="ratio"  ,					a=None  ,					a=None  ,					a=64  ,					a=32  ,					a=False  ,					a=True  ,					a=False  ,					a=False  ,					a=True  ,					a=False  ,					a=None  ,					a=None  ,					**a  ,					):
          super().__init__(pad_token_id=a  ,					**a    )

          # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes)
          UpperCamelCase__										=				vocab_size
          UpperCamelCase__										=				hidden_size
          UpperCamelCase__										=				num_hidden_layers
          UpperCamelCase__										=				num_attention_heads
          UpperCamelCase__										=				hidden_act
          UpperCamelCase__										=				intermediate_size
          UpperCamelCase__										=				hidden_dropout_prob
          UpperCamelCase__										=				attention_probs_dropout_prob
          UpperCamelCase__										=				max_position_embeddings
          UpperCamelCase__										=				type_vocab_sizes
          UpperCamelCase__										=				initializer_range
          UpperCamelCase__										=				layer_norm_eps

          # Fine-tuning task hyperparameters
          UpperCamelCase__										=				positive_label_weight
          UpperCamelCase__										=				num_aggregation_labels
          UpperCamelCase__										=				aggregation_loss_weight
          UpperCamelCase__										=				use_answer_as_supervision
          UpperCamelCase__										=				answer_loss_importance
          UpperCamelCase__										=				use_normalized_answer_loss
          UpperCamelCase__										=				huber_loss_delta
          UpperCamelCase__										=				temperature
          UpperCamelCase__										=				aggregation_temperature
          UpperCamelCase__										=				use_gumbel_for_cells
          UpperCamelCase__										=				use_gumbel_for_aggregation
          UpperCamelCase__										=				average_approximation_function
          UpperCamelCase__										=				cell_selection_preference
          UpperCamelCase__										=				answer_loss_cutoff
          UpperCamelCase__										=				max_num_rows
          UpperCamelCase__										=				max_num_columns
          UpperCamelCase__										=				average_logits_per_cell
          UpperCamelCase__										=				select_one_column
          UpperCamelCase__										=				allow_empty_column_selection
          UpperCamelCase__										=				init_cell_selection_weights_to_zero
          UpperCamelCase__										=				reset_position_index_per_cell
          UpperCamelCase__										=				disable_per_token_loss

          # Aggregation hyperparameters
          UpperCamelCase__										=				aggregation_labels
          UpperCamelCase__										=				no_aggregation_label_index

          if isinstance(self.aggregation_labels  ,					a    ):
                UpperCamelCase__										=				{int(a    ): v for k, v in aggregation_labels.items()}












"""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 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     42
 _lowerCamelCase        =     jnp.floataa
 _lowerCamelCase        =     True

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     super().setup()
     __A    :						List[Any]						 =     nn.Dense(5					,						dtype=self.dtype  )







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



     '''simple docstring'''




     __A    :						Tuple						 =     super().__call__(*__lowerCamelCase					,						**__lowerCamelCase  )
     __A    :						Optional[int]						 =     self.cls(outputs[2]  )
     return outputs[:2] + (cls_out,)






class 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     FlaxBigBirdForNaturalQuestionsModule







def 		__lowercase     (   snake_case_  :  Tuple				,snake_case_  :  Optional[int]				,snake_case_  :  int				,snake_case_  :  Tuple				,snake_case_  :  Any				,snake_case_  :  Any						)   ->List[Any]:



    '''simple docstring'''







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

    __A    :						str						 =     partial(snake_case_				,reduction=jnp.mean						)
    __A    :						Dict						 =     cross_entropy(snake_case_				,snake_case_						)
    __A    :						List[str]						 =     cross_entropy(snake_case_				,snake_case_						)
    __A    :						str						 =     cross_entropy(snake_case_				,snake_case_						)
    return (start_loss + end_loss + pooled_loss) / 3






@dataclass
class 		__snake_case					:





 """simple docstring"""


 _lowerCamelCase        =     "google/bigbird-roberta-base"
 _lowerCamelCase        =     30_00
 _lowerCamelCase        =     1_05_00

 _lowerCamelCase        =     1_28
 _lowerCamelCase        =     3

 _lowerCamelCase        =     1
 _lowerCamelCase        =     5

 # tx_args
 _lowerCamelCase        =     3e-5
 _lowerCamelCase        =     0.0
 _lowerCamelCase        =     2_00_00
 _lowerCamelCase        =     0.0_0_9_5

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

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     os.makedirs(self.base_dir					,						exist_ok=__lowerCamelCase  )
     __A    :						Dict						 =     os.path.join(self.base_dir					,						self.save_dir  )
     __A    :						Dict						 =     self.batch_size_per_device * jax.device_count()






@dataclass
class 		__snake_case					:





 """simple docstring"""


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

 def __call__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Optional[int]						 =     self.collate_fn(__lowerCamelCase  )
     __A    :						Tuple						 =     jax.tree_util.tree_map(__lowerCamelCase					,						__lowerCamelCase  )
     return batch

 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A ,       __A    :						List[Any]						 =     self.fetch_inputs(features['''input_ids''']  )
     __A    :						Union[str, Any]						 =     {
         '''input_ids''': jnp.array(__lowerCamelCase					,						dtype=jnp.intaa  ),
         '''attention_mask''': jnp.array(__lowerCamelCase					,						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					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Any						 =     [self._fetch_inputs(__lowerCamelCase  ) for ids in input_ids]
     return zip(*__lowerCamelCase  )







 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




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







def 		__lowercase     (   snake_case_  :  List[Any]				,snake_case_  :  Optional[Any]				,snake_case_  :  List[str]=None						)   ->Optional[int]:



    '''simple docstring'''







    if seed is not None:
        __A    :						List[Any]						 =     dataset.shuffle(seed=snake_case_						)
    for i in range(len(snake_case_						) // batch_size						):
        __A    :						Tuple						 =     dataset[i * batch_size : (i + 1) * batch_size]
        yield dict(snake_case_						)







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



    '''simple docstring'''







    def loss_fn(snake_case_  :  List[str]						):
        __A    :						str						 =     model_inputs.pop('''start_labels'''						)
        __A    :						str						 =     model_inputs.pop('''end_labels'''						)
        __A    :						int						 =     model_inputs.pop('''pooled_labels'''						)

        __A    :						Dict						 =     state.apply_fn(**snake_case_				,params=snake_case_				,dropout_rng=snake_case_				,train=snake_case_						)
        __A ,       __A ,       __A    :						Union[str, Any]						 =     outputs

        return state.loss_fn(
            snake_case_				,snake_case_				,snake_case_				,snake_case_				,snake_case_				,snake_case_				,)

    __A ,       __A    :						int						 =     jax.random.split(snake_case_						)
    __A    :						str						 =     jax.value_and_grad(snake_case_						)
    __A ,       __A    :						Optional[int]						 =     grad_fn(state.params						)
    __A    :						List[str]						 =     jax.lax.pmean({'''loss''': loss}				,axis_name='''batch'''						)
    __A    :						List[str]						 =     jax.lax.pmean(snake_case_				,'''batch'''						)

    __A    :						str						 =     state.apply_gradients(grads=snake_case_						)
    return state, metrics, new_drp_rng







@partial(jax.pmap				,axis_name='''batch'''						)
def 		__lowercase     (   snake_case_  :  int				,**snake_case_  :  Union[str, Any]						)   ->List[str]:



    '''simple docstring'''







    __A    :						Tuple						 =     model_inputs.pop('''start_labels'''						)
    __A    :						Dict						 =     model_inputs.pop('''end_labels'''						)
    __A    :						int						 =     model_inputs.pop('''pooled_labels'''						)

    __A    :						List[str]						 =     state.apply_fn(**snake_case_				,params=state.params				,train=snake_case_						)
    __A ,       __A ,       __A    :						Dict						 =     outputs

    __A    :						Optional[int]						 =     state.loss_fn(snake_case_				,snake_case_				,snake_case_				,snake_case_				,snake_case_				,snake_case_						)
    __A    :						List[str]						 =     jax.lax.pmean({'''loss''': loss}				,axis_name='''batch'''						)
    return metrics






class 		__snake_case					(		train_state.TrainState     ):





 """simple docstring"""


 _lowerCamelCase        =     struct.field(pytree_node=SCREAMING_SNAKE_CASE__     )






@dataclass
class 		__snake_case					:





 """simple docstring"""


 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     42
 _lowerCamelCase        =     None

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



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     self.args
     __A    :						Dict						 =     len(__lowerCamelCase  ) // args.batch_size

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

                 __A    :						Union[str, Any]						 =     self.evaluate(__lowerCamelCase					,						__lowerCamelCase  )
                 __A    :						Optional[Any]						 =     {
                     '''step''': state_step.item(),
                     '''eval_loss''': eval_loss.item(),
                     '''tr_loss''': tr_loss,
                     '''lr''': lr.item(),
                 }
                 tqdm.write(str(__lowerCamelCase  )  )
                 self.logger.log(__lowerCamelCase					,						commit=__lowerCamelCase  )

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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




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







 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




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







def 		__lowercase     (   snake_case_  :  int				,snake_case_  :  Dict						)   ->Optional[int]:



    '''simple docstring'''







    print(F"""RESTORING CHECKPOINT FROM {save_dir}"""				,end=''' ... '''						)
    with open(os.path.join(snake_case_				,'''flax_model.msgpack'''						)				,'''rb'''						) as f:
        __A    :						List[Any]						 =     from_bytes(state.params				,f.read()						)

    with open(os.path.join(snake_case_				,'''opt_state.msgpack'''						)				,'''rb'''						) as f:
        __A    :						Optional[int]						 =     from_bytes(state.opt_state				,f.read()						)

    __A    :						Tuple						 =     joblib.load(os.path.join(snake_case_				,'''args.joblib'''						)						)
    __A    :						List[str]						 =     joblib.load(os.path.join(snake_case_				,'''data_collator.joblib'''						)						)

    with open(os.path.join(snake_case_				,'''training_state.json'''						)				,'''r'''						) as f:
        __A    :						Dict						 =     json.load(snake_case_						)
    __A    :						int						 =     training_state['''step''']

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







def 		__lowercase     (   snake_case_  :  List[str]				,snake_case_  :  Any				,snake_case_  :  Dict				,snake_case_  :  str						)   ->List[str]:



    '''simple docstring'''







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







def 		__lowercase     (   snake_case_  :  List[str]				,snake_case_  :  List[Any]				,snake_case_  :  Union[str, Any]				,snake_case_  :  List[Any]				,snake_case_  :  str						)   ->List[str]:



    '''simple docstring'''







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

    __A    :						List[Any]						 =     scheduler_fn(snake_case_				,snake_case_				,snake_case_				,snake_case_						)

    __A    :						List[str]						 =     optax.adamw(learning_rate=snake_case_				,weight_decay=snake_case_				,mask=snake_case_						)
    return tx, lr




