




"""simple docstring"""




import inspect
import unittest

import torch
import torch.nn as nn

from accelerate.hooks import (
    AlignDevicesHook,
    ModelHook,
    SequentialHook,
    add_hook_to_module,
    attach_align_device_hook,
    remove_hook_from_module,
    remove_hook_from_submodules,
)
from accelerate.test_utils import require_multi_gpu






class     __magic_name__							(       nn.Module				):






				'''simple docstring'''





				def __init__(       self ):





							"""simple docstring"""
							super().__init__()
							lowerCamelCase			      =					nn.Linear(3		, 4 )
							lowerCamelCase			      =					nn.BatchNormad(4 )
							lowerCamelCase			      =					nn.Linear(4		, 5 )





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							return self.lineara(self.batchnorm(self.lineara(_a ) ) )






class     __magic_name__							(       UpperCAmelCase__				):






				'''simple docstring'''





				def    _lowerCAmelCase				(       self		, _a		, *_a		, **_a ):





							"""simple docstring"""
							return (args[0] + 1,) + args[1:], kwargs






class     __magic_name__							(       UpperCAmelCase__				):






				'''simple docstring'''





				def    _lowerCAmelCase				(       self		, _a		, _a ):





							"""simple docstring"""
							return output + 1






class     __magic_name__							(       unittest.TestCase				):






				'''simple docstring'''





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()
							lowerCamelCase			      =					ModelHook()

							add_hook_to_module(_a		, _a )
							self.assertEqual(test_model._hf_hook		, _a )
							self.assertTrue(hasattr(_a		, """_old_forward""" ) )

							# Check adding the hook did not change the name or the signature
							self.assertEqual(test_model.forward.__name__		, """forward""" )
							self.assertListEqual(list(inspect.signature(test_model.forward ).parameters )		, ["""x"""] )

							remove_hook_from_module(_a )
							self.assertFalse(hasattr(_a		, """_hf_hook""" ) )
							self.assertFalse(hasattr(_a		, """_old_forward""" ) )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()
							lowerCamelCase			      =					ModelHook()

							add_hook_to_module(_a		, _a )
							add_hook_to_module(_a		, _a		, append=_a )

							self.assertEqual(isinstance(test_model._hf_hook		, _a )		, _a )
							self.assertEqual(len(test_model._hf_hook.hooks )		, 2 )
							self.assertTrue(hasattr(_a		, """_old_forward""" ) )

							# Check adding the hook did not change the name or the signature
							self.assertEqual(test_model.forward.__name__		, """forward""" )
							self.assertListEqual(list(inspect.signature(test_model.forward ).parameters )		, ["""x"""] )

							remove_hook_from_module(_a )
							self.assertFalse(hasattr(_a		, """_hf_hook""" ) )
							self.assertFalse(hasattr(_a		, """_old_forward""" ) )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()
							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					test_model(x + 1 )
							lowerCamelCase			      =					test_model(x + 2 )

							lowerCamelCase			      =					PreForwardHook()
							add_hook_to_module(_a		, _a )
							lowerCamelCase			      =					test_model(_a )
							self.assertTrue(torch.allclose(_a		, _a		, atol=1e-5 ) )

							# Attaching a hook to a model when it already has one replaces, does not chain
							lowerCamelCase			      =					PreForwardHook()
							add_hook_to_module(_a		, _a )
							lowerCamelCase			      =					test_model(_a )
							self.assertTrue(torch.allclose(_a		, _a		, atol=1e-5 ) )

							# You need to use the sequential hook to chain two or more hooks
							lowerCamelCase			      =					SequentialHook(PreForwardHook()		, PreForwardHook() )
							add_hook_to_module(_a		, _a )

							lowerCamelCase			      =					test_model(_a )
							assert torch.allclose(_a		, _a		, atol=1e-5 )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()
							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					test_model(_a )

							lowerCamelCase			      =					PostForwardHook()
							add_hook_to_module(_a		, _a )
							lowerCamelCase			      =					test_model(_a )
							self.assertTrue(torch.allclose(_a		, output + 1		, atol=1e-5 ) )

							# Attaching a hook to a model when it already has one replaces, does not chain
							lowerCamelCase			      =					PostForwardHook()
							add_hook_to_module(_a		, _a )
							lowerCamelCase			      =					test_model(_a )
							self.assertTrue(torch.allclose(_a		, output + 1		, atol=1e-5 ) )

							# You need to use the sequential hook to chain two or more hooks
							lowerCamelCase			      =					SequentialHook(PostForwardHook()		, PostForwardHook() )
							add_hook_to_module(_a		, _a )

							lowerCamelCase			      =					test_model(_a )
							assert torch.allclose(_a		, output + 2		, atol=1e-5 )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()
							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					test_model(_a )

							lowerCamelCase			      =					PostForwardHook()
							add_hook_to_module(_a		, _a )
							lowerCamelCase			      =					test_model(_a )
							self.assertTrue(torch.allclose(_a		, output + 1 ) )
							self.assertTrue(outputa.requires_grad )

							lowerCamelCase			      =					True
							lowerCamelCase			      =					test_model(_a )
							self.assertFalse(outputa.requires_grad )





				@require_multi_gpu
				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()
							# Everything is on CPU
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )

							# This will move each submodule on different devices
							add_hook_to_module(model.lineara		, AlignDevicesHook(execution_device=0 ) )
							add_hook_to_module(model.batchnorm		, AlignDevicesHook(execution_device=0 ) )
							add_hook_to_module(model.lineara		, AlignDevicesHook(execution_device=1 ) )

							self.assertEqual(model.lineara.weight.device		, torch.device(0 ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device(0 ) )
							self.assertEqual(model.batchnorm.running_mean.device		, torch.device(0 ) )
							self.assertEqual(model.lineara.weight.device		, torch.device(1 ) )

							# We can still make a forward pass. The input does not need to be on any particular device
							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					model(_a )
							self.assertEqual(output.device		, torch.device(1 ) )

							# We can add a general hook to put back output on same device as input.
							add_hook_to_module(_a		, AlignDevicesHook(io_same_device=_a ) )
							lowerCamelCase			      =					torch.randn(2		, 3 ).to(0 )
							lowerCamelCase			      =					model(_a )
							self.assertEqual(output.device		, torch.device(0 ) )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()

							# Everything is on CPU
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )

							# This will move each submodule on different devices
							lowerCamelCase			      =					{"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True}

							add_hook_to_module(model.lineara		, AlignDevicesHook(**_a ) )
							add_hook_to_module(model.batchnorm		, AlignDevicesHook(**_a ) )
							add_hook_to_module(model.lineara		, AlignDevicesHook(**_a ) )

							# Parameters have been offloaded, so on the meta device
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							# Buffers are not included in the offload by default, so are on the execution device
							lowerCamelCase			      =					torch.device(hook_kwargs["""execution_device"""] )
							self.assertEqual(model.batchnorm.running_mean.device		, _a )

							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					model(_a )
							self.assertEqual(output.device		, _a )

							# Removing hooks loads back the weights in the model.
							remove_hook_from_module(model.lineara )
							remove_hook_from_module(model.batchnorm )
							remove_hook_from_module(model.lineara )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )

							# Now test with buffers included in the offload
							lowerCamelCase			      =					{
							    """execution_device""": 0 if torch.cuda.is_available() else """cpu""",
							    """offload""": True,
							    """offload_buffers""": True,
							}

							add_hook_to_module(model.lineara		, AlignDevicesHook(**_a ) )
							add_hook_to_module(model.batchnorm		, AlignDevicesHook(**_a ) )
							add_hook_to_module(model.lineara		, AlignDevicesHook(**_a ) )

							# Parameters have been offloaded, so on the meta device, buffers included
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.running_mean.device		, torch.device("""meta""" ) )

							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					model(_a )
							self.assertEqual(output.device		, _a )

							# Removing hooks loads back the weights in the model.
							remove_hook_from_module(model.lineara )
							remove_hook_from_module(model.batchnorm )
							remove_hook_from_module(model.lineara )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()

							# Everything is on CPU
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )

							# This will move each submodule on different devices
							lowerCamelCase			      =					0 if torch.cuda.is_available() else """cpu"""
							attach_align_device_hook(_a		, execution_device=_a		, offload=_a )

							# Parameters have been offloaded, so on the meta device
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							# Buffers are not included in the offload by default, so are on the execution device
							lowerCamelCase			      =					torch.device(_a )
							self.assertEqual(model.batchnorm.running_mean.device		, _a )

							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					model(_a )
							self.assertEqual(output.device		, _a )

							# Removing hooks loads back the weights in the model.
							remove_hook_from_submodules(_a )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )

							# Now test with buffers included in the offload
							attach_align_device_hook(_a		, execution_device=_a		, offload=_a		, offload_buffers=_a )

							# Parameters have been offloaded, so on the meta device, buffers included
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.running_mean.device		, torch.device("""meta""" ) )

							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					model(_a )
							self.assertEqual(output.device		, _a )

							# Removing hooks loads back the weights in the model.
							remove_hook_from_submodules(_a )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					ModelForTest()

							# Everything is on CPU
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )

							# This will move each submodule on different devices
							lowerCamelCase			      =					0 if torch.cuda.is_available() else """cpu"""
							attach_align_device_hook(
							    _a		, execution_device=_a		, offload=_a		, weights_map=model.state_dict() )

							# Parameters have been offloaded, so on the meta device
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							# Buffers are not included in the offload by default, so are on the execution device
							lowerCamelCase			      =					torch.device(_a )
							self.assertEqual(model.batchnorm.running_mean.device		, _a )

							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					model(_a )
							self.assertEqual(output.device		, _a )

							# Removing hooks loads back the weights in the model.
							remove_hook_from_submodules(_a )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )

							# Now test with buffers included in the offload
							attach_align_device_hook(
							    _a		, execution_device=_a		, offload=_a		, weights_map=model.state_dict()		, offload_buffers=_a		, )

							# Parameters have been offloaded, so on the meta device, buffers included
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""meta""" ) )
							self.assertEqual(model.batchnorm.running_mean.device		, torch.device("""meta""" ) )

							lowerCamelCase			      =					torch.randn(2		, 3 )
							lowerCamelCase			      =					model(_a )
							self.assertEqual(output.device		, _a )

							# Removing hooks loads back the weights in the model.
							remove_hook_from_submodules(_a )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.batchnorm.weight.device		, torch.device("""cpu""" ) )
							self.assertEqual(model.lineara.weight.device		, torch.device("""cpu""" ) )









"""simple docstring"""




from sklearn.metrics import recall_score

import datasets


lowerCAmelCase							:			Any     							=							"""
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


lowerCAmelCase							:			Any     							=							"""
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **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.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **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'`.
    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
    - `'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.
    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **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.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


lowerCAmelCase							:			Any     							=							"""
@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}
"""






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






				'''simple docstring'''





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							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    _lowerCAmelCase				(       self		, _a		, _a		, _a=None		, _a=1		, _a="binary"		, _a=None		, _a="warn"		, ):





							"""simple docstring"""
							lowerCamelCase			      =					recall_score(
							    _a		, _a		, labels=_a		, pos_label=_a		, average=_a		, sample_weight=_a		, zero_division=_a		, )
							return {"recall": float(_a ) if score.size == 1 else score}



