




from sklearn.metrics import recall_score

import datasets


_UpperCAmelCase	:						int			=     "\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n"


_UpperCAmelCase	:						Tuple			=     "\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while 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 y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions 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. Note that it 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** (): Sets the value to return when there is a zero division. Defaults to .\n    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {'recall': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {'recall': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {'recall': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'recall': array([1., 0., 0.])}\n"


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




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






       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, 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.recall_score.html"]       ,					)






       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]       ,					_lowerCAmelCase:					Tuple       ,					_lowerCAmelCase:					List[str]       ,					_lowerCAmelCase:					Any=None       ,					_lowerCAmelCase:					int=1       ,					_lowerCAmelCase:					List[str]="binary"       ,					_lowerCAmelCase:					Any=None       ,					_lowerCAmelCase:					Optional[Any]="warn"       ,					):
         lowercase    :Dict      	=						recall_score(
             _lowerCAmelCase       ,					_lowerCAmelCase       ,					labels=_lowerCAmelCase       ,					pos_label=_lowerCAmelCase       ,					average=_lowerCAmelCase       ,					sample_weight=_lowerCAmelCase       ,					zero_division=_lowerCAmelCase       ,					)
         return {"recall": float(_lowerCAmelCase				) if score.size == 1 else score}









import json
import os
import tempfile
from unittest.mock import patch

import torch
from torch.utils.data import DataLoader, TensorDataset

from accelerate import DistributedType, infer_auto_device_map, init_empty_weights
from accelerate.accelerator import Accelerator
from accelerate.state import GradientState, PartialState
from accelerate.test_utils import require_bnb, require_multi_gpu, slow
from accelerate.test_utils.testing import AccelerateTestCase, require_cuda
from accelerate.utils import patch_environment



def       UpperCAmelCase__  (     ):
  lowercase    :List[str]      	=						torch.nn.Linear(2,			4   )
  lowercase    :List[Any]      	=						torch.optim.AdamW(model.parameters(),			lr=1.0   )
  lowercase    :int      	=						torch.optim.lr_scheduler.OneCycleLR(lowerCamelCase,			max_lr=0.01,			steps_per_epoch=2,			epochs=1   )
  lowercase    :Optional[int]      	=						DataLoader(TensorDataset(torch.tensor([1, 2, 3]   )   )   )
  lowercase    :List[str]      	=						DataLoader(TensorDataset(torch.tensor([4, 5, 6]   )   )   )

  return model, optimizer, scheduler, train_dl, valid_dl



def       UpperCAmelCase__  (     lowerCamelCase   ):
  return (model.weight.abs().sum() + model.bias.abs().sum()).item()



def       UpperCAmelCase__  (     lowerCamelCase   ):
  lowercase    :Dict      	=						torch.nn.Linear(*tuple(model.weight.T.shape   )   ).state_dict()
  model.load_state_dict(lowerCamelCase   )







class    __lowerCAmelCase       (							lowerCAmelCase):






       @require_cuda
       def 					SCREAMING_SNAKE_CASE    (   self:					str				):
         lowercase    :List[str]      	=						Accelerator()
         assert PartialState._shared_state["_cpu"] is False
         assert PartialState._shared_state["device"].type == "cuda"
         with self.assertRaises(_lowerCAmelCase				):
           lowercase    :Any      	=						Accelerator(cpu=_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         lowercase    :Any      	=						Accelerator()
         lowercase    :Dict      	=						GradientState()
         assert state.num_steps == 1
         lowercase    :Tuple      	=						4
         assert state.num_steps == 4

         assert state.sync_gradients is True
         lowercase    :List[Any]      	=						False
         assert state.sync_gradients is False
         GradientState._reset_state()






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         lowercase    :str      	=						Accelerator()
         lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase    :Any      	=						create_components()

         (
             (
             lowercase
         )	,    (
             lowercase
         )	,    (
             lowercase
         )	,    (
             lowercase
         )	,    (
             lowercase
         )	,    
         )    :Tuple      	=						accelerator.prepare(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)

         self.assertTrue(prepared_model in accelerator._models				)
         self.assertTrue(prepared_optimizer in accelerator._optimizers				)
         self.assertTrue(prepared_scheduler in accelerator._schedulers				)
         self.assertTrue(prepared_train_dl in accelerator._dataloaders				)
         self.assertTrue(prepared_valid_dl in accelerator._dataloaders				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         lowercase    :Dict      	=						Accelerator()
         lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase    :List[str]      	=						create_components()
         accelerator.prepare(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)
         accelerator.free_memory()

         self.assertTrue(len(accelerator._models				) == 0				)
         self.assertTrue(len(accelerator._optimizers				) == 0				)
         self.assertTrue(len(accelerator._schedulers				) == 0				)
         self.assertTrue(len(accelerator._dataloaders				) == 0				)






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         PartialState._reset_state()

         # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist
         def noop(*_lowerCAmelCase:					List[str]       ,					**_lowerCAmelCase:					Optional[int]				):
           pass

         with patch("torch.cuda.set_device"       ,					_lowerCAmelCase				), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64"				):
           lowercase    :List[Any]      	=						Accelerator()
           self.assertEqual(str(accelerator.state.device				)       ,					"cuda:64"				)






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         lowercase    :Tuple      	=						Accelerator()
         lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase    :Optional[Any]      	=						create_components()
         accelerator.prepare(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)

         lowercase    :Tuple      	=						get_signature(_lowerCAmelCase				)

         with tempfile.TemporaryDirectory() as tmpdirname:
           accelerator.save_state(_lowerCAmelCase				)

           # make sure random weights don't match
           load_random_weights(_lowerCAmelCase				)
           self.assertTrue(abs(model_signature - get_signature(_lowerCAmelCase				)				) > 1e-3				)

           # make sure loaded weights match
           accelerator.load_state(_lowerCAmelCase				)
           self.assertTrue(abs(model_signature - get_signature(_lowerCAmelCase				)				) < 1e-3				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]				):
         lowercase    :Dict      	=						Accelerator()
         lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase    :int      	=						create_components()
         accelerator.prepare(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)

         lowercase    :int      	=						get_signature(_lowerCAmelCase				)

         # saving hook
         def save_config(_lowerCAmelCase:					Union[str, Any]       ,					_lowerCAmelCase:					str       ,					_lowerCAmelCase:					List[Any]				):
           lowercase    :Dict      	=						{"class_name": models[0].__class__.__name__}

           with open(os.path.join(_lowerCAmelCase       ,					"data.json"				)       ,					"w"				) as f:
             json.dump(_lowerCAmelCase       ,					_lowerCAmelCase				)

        # loading hook
         def load_config(_lowerCAmelCase:					Union[str, Any]       ,					_lowerCAmelCase:					Union[str, Any]				):
           with open(os.path.join(_lowerCAmelCase       ,					"data.json"				)       ,					"r"				) as f:
             lowercase    :int      	=						json.load(_lowerCAmelCase				)

           lowercase    :Optional[int]      	=						config["class_name"]

         lowercase    :Optional[Any]      	=						accelerator.register_save_state_pre_hook(_lowerCAmelCase				)
         lowercase    :Tuple      	=						accelerator.register_load_state_pre_hook(_lowerCAmelCase				)

         with tempfile.TemporaryDirectory() as tmpdirname:
           accelerator.save_state(_lowerCAmelCase				)

           # make sure random weights don't match with hooks
           load_random_weights(_lowerCAmelCase				)
           self.assertTrue(abs(model_signature - get_signature(_lowerCAmelCase				)				) > 1e-3				)

           # random class name to verify correct one is loaded
           lowercase    :Optional[int]      	=						"random"

           # make sure loaded weights match with hooks
           accelerator.load_state(_lowerCAmelCase				)
           self.assertTrue(abs(model_signature - get_signature(_lowerCAmelCase				)				) < 1e-3				)

           # mode.class_name is loaded from config
           self.assertTrue(model.class_name == model.__class__.__name__				)

         # remove hooks
         save_hook.remove()
         load_hook.remove()

         with tempfile.TemporaryDirectory() as tmpdirname:
           accelerator.save_state(_lowerCAmelCase				)

           # make sure random weights don't match with hooks removed
           load_random_weights(_lowerCAmelCase				)
           self.assertTrue(abs(model_signature - get_signature(_lowerCAmelCase				)				) > 1e-3				)

           # random class name to verify correct one is loaded
           lowercase    :str      	=						"random"

           # make sure loaded weights match with hooks removed
           accelerator.load_state(_lowerCAmelCase				)
           self.assertTrue(abs(model_signature - get_signature(_lowerCAmelCase				)				) < 1e-3				)

           # mode.class_name is NOT loaded from config
           self.assertTrue(model.class_name != model.__class__.__name__				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]				):
         lowercase    :List[str]      	=						Accelerator()
         lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase    :List[Any]      	=						create_components()
         lowercase    :List[str]      	=						None

         # This should work
         lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase    :str      	=						accelerator.prepare(
             _lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)
         self.assertTrue(dummy_obj is None				)






       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):
         lowercase    :Union[str, Any]      	=						Accelerator()
         lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase    :Union[str, Any]      	=						create_components()
         lowercase    :Union[str, Any]      	=						[1, 2, 3]

         # This should work
         lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase	,    lowercase    :List[str]      	=						accelerator.prepare(
             _lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)
         self.assertEqual(
             getattr(_lowerCAmelCase       ,					"_is_accelerate_prepared"       ,					_lowerCAmelCase				)       ,					_lowerCAmelCase       ,					"Dummy object should have `_is_accelerate_prepared` set to `True`"       ,					)
         self.assertEqual(
             getattr(_lowerCAmelCase       ,					"_is_accelerate_prepared"       ,					_lowerCAmelCase				)       ,					_lowerCAmelCase       ,					"Model is missing `_is_accelerator_prepared` or is set to `False`"       ,					)
         self.assertEqual(
             getattr(_lowerCAmelCase       ,					"_is_accelerate_prepared"       ,					_lowerCAmelCase				)       ,					_lowerCAmelCase       ,					"Optimizer is missing `_is_accelerator_prepared` or is set to `False`"       ,					)
         self.assertEqual(
             getattr(_lowerCAmelCase       ,					"_is_accelerate_prepared"       ,					_lowerCAmelCase				)       ,					_lowerCAmelCase       ,					"Scheduler is missing `_is_accelerator_prepared` or is set to `False`"       ,					)
         self.assertEqual(
             getattr(_lowerCAmelCase       ,					"_is_accelerate_prepared"       ,					_lowerCAmelCase				)       ,					_lowerCAmelCase       ,					"Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`"       ,					)
         self.assertEqual(
             getattr(_lowerCAmelCase       ,					"_is_accelerate_prepared"       ,					_lowerCAmelCase				)       ,					_lowerCAmelCase       ,					"Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`"       ,					)






       @slow
       @require_bnb
       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, Any]				):
         from transformers import AutoModelForCausalLM

         lowercase    :Any      	=						AutoModelForCausalLM.from_pretrained(
             "EleutherAI/gpt-neo-125m"       ,					load_in_abit=_lowerCAmelCase       ,					device_map={"": 0}       ,					)
         lowercase    :int      	=						Accelerator()

         # This should work
         lowercase    :Optional[int]      	=						accelerator.prepare(_lowerCAmelCase				)






       @slow
       @require_bnb
       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):
         from transformers import AutoModelForCausalLM

         lowercase    :Optional[Any]      	=						Accelerator()

         with init_empty_weights():
           lowercase    :Any      	=						AutoModelForCausalLM.from_pretrained(
               "EleutherAI/gpt-neo-125m"       ,					)
           model.tie_weights()
           lowercase    :Dict      	=						infer_auto_device_map(_lowerCAmelCase				)
           lowercase    :int      	=						"cpu"

         lowercase    :str      	=						AutoModelForCausalLM.from_pretrained(
             "EleutherAI/gpt-neo-125m"       ,					device_map=_lowerCAmelCase       ,					load_in_abit=_lowerCAmelCase       ,					llm_inta_enable_fpaa_cpu_offload=_lowerCAmelCase				)

         # This should not work and get value error
         with self.assertRaises(_lowerCAmelCase				):
           lowercase    :Dict      	=						accelerator.prepare(_lowerCAmelCase				)






       @slow
       @require_bnb
       @require_multi_gpu
       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         from transformers import AutoModelForCausalLM

         lowercase    :List[str]      	=						{"distributed_type": DistributedType.MULTI_GPU}

         with init_empty_weights():
           lowercase    :str      	=						AutoModelForCausalLM.from_pretrained(
               "EleutherAI/gpt-neo-125m"       ,					)
           model.tie_weights()
           lowercase    :Optional[Any]      	=						infer_auto_device_map(_lowerCAmelCase				)
           lowercase    :Any      	=						1

         lowercase    :str      	=						AutoModelForCausalLM.from_pretrained(
             "EleutherAI/gpt-neo-125m"       ,					load_in_abit=_lowerCAmelCase       ,					device_map=_lowerCAmelCase       ,					)
         lowercase    :List[str]      	=						Accelerator()

         # This should not work and get value error
         with self.assertRaises(_lowerCAmelCase				):
           lowercase    :Optional[Any]      	=						accelerator.prepare(_lowerCAmelCase				)

         PartialState._reset_state()






       @slow
       @require_bnb
       @require_multi_gpu
       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]				):
         from transformers import AutoModelForCausalLM

         with init_empty_weights():
           lowercase    :List[str]      	=						AutoModelForCausalLM.from_pretrained(
               "EleutherAI/gpt-neo-125m"       ,					)
           lowercase    :List[Any]      	=						infer_auto_device_map(_lowerCAmelCase				)
           lowercase    :Optional[int]      	=						1

         lowercase    :Union[str, Any]      	=						AutoModelForCausalLM.from_pretrained(
             "EleutherAI/gpt-neo-125m"       ,					load_in_abit=_lowerCAmelCase       ,					device_map=_lowerCAmelCase       ,					)
         lowercase    :Union[str, Any]      	=						Accelerator()

         # This should work
         lowercase    :List[Any]      	=						accelerator.prepare(_lowerCAmelCase				)






       @require_cuda
       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         lowercase    :Optional[int]      	=						torch.nn.Linear(10       ,					10				)
         lowercase    :Optional[int]      	=						torch.optim.SGD(model.parameters()       ,					lr=0.01				)
         lowercase    :List[Any]      	=						Accelerator(cpu=_lowerCAmelCase				)
         lowercase    :List[str]      	=						accelerator.prepare(_lowerCAmelCase				)



