






from sklearn.metrics import precision_score

import datasets


_UpperCAmelCase				:	Tuple       =    '\nPrecision is the fraction of correctly labeled positive examples out of all of the examples that were labeled as positive. It is computed via the equation:\nPrecision = TP / (TP + FP)\nwhere TP is the True positives (i.e. the examples correctly labeled as positive) and FP is the False positive examples (i.e. the examples incorrectly labeled as positive).\n'


_UpperCAmelCase				:	Union[str, Any]       =    '\nArgs:\n    predictions (`list` of `int`): Predicted class labels.\n    references (`list` of `int`): Actual class labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`. If `average` is `None`, it should be the label order. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n    zero_division (`int` or `string`): Sets the value to return when there is a zero division. Defaults to \'warn\'.\n\n        - 0: Returns 0 when there is a zero division.\n        - 1: Returns 1 when there is a zero division.\n        - \'warn\': Raises warnings and then returns 0 when there is a zero division.\n\nReturns:\n    precision (`float` or `array` of `float`): Precision score or list of precision scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate that fewer negative examples were incorrectly labeled as positive, which means that, generally, higher scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {\'precision\': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results[\'precision\'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(results)\n        {\'precision\': 0.23529411764705882}\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'macro\')\n        >>> print(results)\n        {\'precision\': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'micro\')\n        >>> print(results)\n        {\'precision\': 0.3333333333333333}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'weighted\')\n        >>> print(results)\n        {\'precision\': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print([round(res, 2) for res in results[\'precision\']])\n        [0.67, 0.0, 0.0]\n'


_UpperCAmelCase				:	str       =    '\n@article{scikit-learn,\n    title={Scikit-learn: Machine Learning in {P}ython},\n    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n    and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n    and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n    Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n    journal={Journal of Machine Learning Research},\n    volume={12},\n    pages={2825--2830},\n    year={2011}\n}\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,    _KWARGS_DESCRIPTION   )
class 		lowerCAmelCase_							(     datasets.Metric   ):





     def 	lowerCamelCase       (  self     )		->							Optional[Any]:
        return datasets.MetricInfo(
            description=_DESCRIPTION       ,   citation=_CITATION       ,   inputs_description=_KWARGS_DESCRIPTION       ,   features=datasets.Features(
                {
                    """predictions""": datasets.Sequence(datasets.Value("""int32"""     )     ),
                    """references""": datasets.Sequence(datasets.Value("""int32"""     )     ),
                }
                if self.config_name == """multilabel"""
                else {
                    """predictions""": datasets.Value("""int32"""     ),
                    """references""": datasets.Value("""int32"""     ),
                }     )       ,   reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html"""]       ,   )





     def 	lowerCamelCase       (  self       ,   _UpperCAmelCase       ,   _UpperCAmelCase       ,   _UpperCAmelCase=None       ,   _UpperCAmelCase=1       ,   _UpperCAmelCase="binary"       ,   _UpperCAmelCase=None       ,   _UpperCAmelCase="warn"       ,   )		->							Tuple:
        lowerCamelCase											=precision_score(
            SCREAMING_SNAKE_CASE_       ,   SCREAMING_SNAKE_CASE_       ,   labels=SCREAMING_SNAKE_CASE_       ,   pos_label=SCREAMING_SNAKE_CASE_       ,   average=SCREAMING_SNAKE_CASE_       ,   sample_weight=SCREAMING_SNAKE_CASE_       ,   zero_division=SCREAMING_SNAKE_CASE_       ,   )
        return {"precision": float(SCREAMING_SNAKE_CASE_     ) if score.size == 1 else score}







import os
from dataclasses import replace

import jax
import wandb
from bigbird_flax import Args, DataCollator, FlaxBigBirdForNaturalQuestions, Trainer, build_tx, train_step, val_step
from datasets import load_dataset
from flax import jax_utils

from transformers import BigBirdTokenizerFast


if __name__ == "__main__":
   print('#################### AVAILABLE DEVICES ####################')
   print(jax.devices())
   print('###########################################################')

   # setup for wandb sweep
   _UpperCAmelCase				:	Optional[Any]    						=    Args()
   _UpperCAmelCase				:	Tuple    						=    wandb.init(project='bigbird-natural-questions', config=args.__dict__)
   _UpperCAmelCase				:	Optional[Any]    						=    dict(logger.config)
   del wandb_args["batch_size"]
   _UpperCAmelCase				:	str    						=    replace(args, **wandb_args)
   _UpperCAmelCase				:	Dict    						=    args.base_dir + '-' + wandb.run.id
   _UpperCAmelCase				:	Tuple    						=    replace(args, base_dir=base_dir)
   print(args)

   _UpperCAmelCase				:	List[Any]    						=    load_dataset('json', data_files=args.tr_data_path)['train']
   _UpperCAmelCase				:	Dict    						=    load_dataset('json', data_files=args.val_data_path)['train']

   # drop extra batch for now
   _UpperCAmelCase				:	List[str]    						=    range(len(tr_dataset) - len(tr_dataset) % args.batch_size)
   _UpperCAmelCase				:	List[Any]    						=    tr_dataset.shuffle().select(indices)
   _UpperCAmelCase				:	Any    						=    range(len(val_dataset) - len(val_dataset) % args.batch_size)
   _UpperCAmelCase				:	Union[str, Any]    						=    val_dataset.shuffle().select(indices)

   if os.environ.get('TRAIN_ON_SMALL', 'false') == "true":
      _UpperCAmelCase				:	Optional[Any]    						=    tr_dataset.shuffle().select(range(8_0000))
      _UpperCAmelCase				:	List[Any]    						=    val_dataset.shuffle().select(range(8000))

   print(tr_dataset)
   print(val_dataset)

   _UpperCAmelCase				:	int    						=    FlaxBigBirdForNaturalQuestions.from_pretrained(
       args.model_id, block_size=args.block_size, num_random_blocks=args.num_random_blocks
   )
   _UpperCAmelCase				:	Union[str, Any]    						=    BigBirdTokenizerFast.from_pretrained(args.model_id)
   _UpperCAmelCase				:	List[str]    						=    DataCollator(pad_id=tokenizer.pad_token_id, max_length=4096)

   _UpperCAmelCase				:	Any    						=    {
       'lr': args.lr,
       'init_lr': args.init_lr,
       'warmup_steps': args.warmup_steps,
       'num_train_steps': args.max_epochs * (len(tr_dataset) // args.batch_size),
       'weight_decay': args.weight_decay,
   }
   _UpperCAmelCase						,						_UpperCAmelCase				:	Optional[int]    						=    build_tx(**tx_args)

   _UpperCAmelCase				:	List[Any]    						=    Trainer(
       args=args,
       data_collator=data_collator,
       model_save_fn=model.save_pretrained,
       train_step_fn=train_step,
       val_step_fn=val_step,
       logger=logger,
       scheduler_fn=lr,
   )

   _UpperCAmelCase				:	Union[str, Any]    						=    None
   _UpperCAmelCase				:	Optional[Any]    						=    trainer.create_state(model, tx, num_train_steps=tx_args['num_train_steps'], ckpt_dir=ckpt_dir)
   try:
      trainer.train(state, tr_dataset, val_dataset)
   except KeyboardInterrupt:
      print('Oooops; TRAINING STOPPED UNFORTUNATELY')

   print('SAVING WEIGHTS IN `final-weights`')
   _UpperCAmelCase				:	Optional[int]    						=    jax_utils.unreplicate(state.params)
   model.save_pretrained(os.path.join(args.base_dir, 'final-weights'), params=params)