


from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
    from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


lowerCAmelCase__      		= logging.get_logger(__name__)

lowerCAmelCase__      		= {
    'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json',
    'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json',
    'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json',
    'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json',
    'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json',
    'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json',
}







class      lowerCAmelCase__       (				a):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE  			= "bloom"
     __SCREAMING_SNAKE_CASE  			= ["past_key_values"]
     __SCREAMING_SNAKE_CASE  			= {
         "num_hidden_layers": "n_layer",
         "num_attention_heads": "n_head",
     }


     def __init__(						self ,						__lowerCamelCase=2_5_0_8_8_0 ,						__lowerCamelCase=6_4 ,						__lowerCamelCase=2 ,						__lowerCamelCase=8 ,						__lowerCamelCase=1e-5 ,						__lowerCamelCase=0.0_2 ,						__lowerCamelCase=True ,						__lowerCamelCase=1 ,						__lowerCamelCase=2 ,						__lowerCamelCase=False ,						__lowerCamelCase=0.0 ,						__lowerCamelCase=0.0 ,						__lowerCamelCase=1 ,						__lowerCamelCase=False ,						**__lowerCamelCase ,						)			->				Tuple:
            _A      :       Optional[int]				    = vocab_size
            # Backward compatibility with n_embed kwarg
            _A      :       Any				    = kwargs.pop("n_embed" ,						__lowerCamelCase)
            _A      :       int				    = hidden_size if n_embed is None else n_embed
            _A      :       Union[str, Any]				    = n_layer
            _A      :       Optional[int]				    = n_head
            _A      :       Tuple				    = layer_norm_epsilon
            _A      :       Optional[int]				    = initializer_range
            _A      :       Optional[Any]				    = use_cache
            _A      :       Optional[int]				    = pretraining_tp
            _A      :       Optional[Any]				    = apply_residual_connection_post_layernorm
            _A      :       int				    = hidden_dropout
            _A      :       List[str]				    = attention_dropout

            _A      :       Optional[Any]				    = bos_token_id
            _A      :       int				    = eos_token_id
            _A      :       Optional[Any]				    = slow_but_exact

            super().__init__(bos_token_id=__lowerCamelCase ,						eos_token_id=__lowerCamelCase ,						**__lowerCamelCase)







class      lowerCAmelCase__       (				a):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE  			= version.parse("1.12")


     def __init__(						self ,						__lowerCamelCase ,						__lowerCamelCase = "default" ,						__lowerCamelCase = None ,						__lowerCamelCase = False ,						)			->				str:
            super().__init__(__lowerCamelCase ,						task=__lowerCamelCase ,						patching_specs=__lowerCamelCase ,						use_past=__lowerCamelCase)
            if not getattr(self._config ,						"pad_token_id" ,						__lowerCamelCase):
                   # TODO: how to do that better?
                   _A      :       Dict				    = 0


     @property
     def  _lowerCamelCase (						self)			->				List[Any]:
            _A      :       Optional[int]				    = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
            if self.use_past:
                   # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
                   self.fill_with_past_key_values_(__lowerCamelCase ,						direction="inputs" ,						inverted_values_shape=__lowerCamelCase)
                   _A      :       Any				    = {0: """batch""", 1: """past_sequence + sequence"""}
            else:
                   _A      :       Tuple				    = {0: """batch""", 1: """sequence"""}

            return common_inputs


     @property
     def  _lowerCamelCase (						self)			->				List[str]:
            return self._config.n_layer


     @property
     def  _lowerCamelCase (						self)			->				Optional[int]:
            return self._config.n_head


     @property
     def  _lowerCamelCase (						self)			->				Tuple:
            return 1e-3


     def  _lowerCamelCase (						self ,						__lowerCamelCase ,						__lowerCamelCase = -1 ,						__lowerCamelCase = -1 ,						__lowerCamelCase = False ,						__lowerCamelCase = None ,						)			->				Optional[int]:
            _A      :       Dict				    = super(__lowerCamelCase ,						self).generate_dummy_inputs(
                __lowerCamelCase ,						batch_size=__lowerCamelCase ,						seq_length=__lowerCamelCase ,						is_pair=__lowerCamelCase ,						framework=__lowerCamelCase)

            # We need to order the input in the way they appears in the forward()
            _A      :       Union[str, Any]				    = OrderedDict({"input_ids": common_inputs["input_ids"]})

            # Need to add the past_keys
            if self.use_past:
                   if not is_torch_available():
                          raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
                   else:
                          import torch

                          _A      :       Optional[Any]				    = common_inputs["""input_ids"""].shape
                          # Not using the same length for past_key_values
                          _A      :       List[str]				    = seqlen + 2
                          _A      :       Union[str, Any]				    = self._config.hidden_size // self.num_attention_heads
                          _A      :       str				    = (
                              batch * self.num_attention_heads,
                              head_dim,
                              past_key_values_length,
                          )
                          _A      :       Tuple				    = (
                              batch * self.num_attention_heads,
                              past_key_values_length,
                              head_dim,
                          )
                          _A      :       Optional[int]				    = [
                              (torch.zeros(__lowerCamelCase), torch.zeros(__lowerCamelCase)) for _ in range(self.num_layers)
                          ]

            _A      :       int				    = common_inputs["""attention_mask"""]
            if self.use_past:
                   _A      :       List[Any]				    = ordered_inputs["""attention_mask"""].dtype
                   _A      :       Any				    = torch.cat(
                       [ordered_inputs["attention_mask"], torch.ones(__lowerCamelCase ,						__lowerCamelCase ,						dtype=__lowerCamelCase)] ,						dim=1)

            return ordered_inputs


     @property
     def  _lowerCamelCase (						self)			->				Tuple:
            return 1_3




"""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      lowerCamelCase__   (     nn.Module				):







					"""simple docstring"""


					def __init__(       self    : List[Any]  ):
												'''simple docstring'''






												super().__init__()
												__UpperCAmelCase   :						Optional[Any]      							=					nn.Linear(3 ,       4  )
												__UpperCAmelCase   :						Optional[int]      							=					nn.BatchNormad(4  )
												__UpperCAmelCase   :						int      							=					nn.Linear(4 ,       5  )






					def lowerCamelCase__							(       self    : List[str] ,       UpperCamelCase    : Dict  ):
												'''simple docstring'''






												return self.lineara(self.batchnorm(self.lineara(UpperCamelCase  )  )  )






class      lowerCamelCase__   (     A				):







					"""simple docstring"""


					def lowerCamelCase__							(       self    : str ,       UpperCamelCase    : Any ,       *UpperCamelCase    : List[Any] ,       **UpperCamelCase    : Dict  ):
												'''simple docstring'''






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






class      lowerCamelCase__   (     A				):







					"""simple docstring"""


					def lowerCamelCase__							(       self    : Any ,       UpperCamelCase    : Dict ,       UpperCamelCase    : List[Any]  ):
												'''simple docstring'''






												return output + 1






class      lowerCamelCase__   (     unittest.TestCase				):







					"""simple docstring"""


					def lowerCamelCase__							(       self    : str  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Dict      							=					ModelForTest()
												__UpperCAmelCase   :						List[str]      							=					ModelHook()

												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )
												self.assertEqual(test_model._hf_hook ,       UpperCamelCase  )
												self.assertTrue(hasattr(UpperCamelCase ,       """_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(UpperCamelCase  )
												self.assertFalse(hasattr(UpperCamelCase ,       """_hf_hook"""  )  )
												self.assertFalse(hasattr(UpperCamelCase ,       """_old_forward"""  )  )






					def lowerCamelCase__							(       self    : str  ):
												'''simple docstring'''






												__UpperCAmelCase   :						int      							=					ModelForTest()
												__UpperCAmelCase   :						Optional[Any]      							=					ModelHook()

												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )
												add_hook_to_module(UpperCamelCase ,       UpperCamelCase ,       append=UpperCamelCase  )

												self.assertEqual(isinstance(test_model._hf_hook ,       UpperCamelCase  ) ,       UpperCamelCase  )
												self.assertEqual(len(test_model._hf_hook.hooks  ) ,       2  )
												self.assertTrue(hasattr(UpperCamelCase ,       """_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(UpperCamelCase  )
												self.assertFalse(hasattr(UpperCamelCase ,       """_hf_hook"""  )  )
												self.assertFalse(hasattr(UpperCamelCase ,       """_old_forward"""  )  )






					def lowerCamelCase__							(       self    : Any  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Union[str, Any]      							=					ModelForTest()
												__UpperCAmelCase   :						str      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						List[str]      							=					test_model(x + 1  )
												__UpperCAmelCase   :						Optional[int]      							=					test_model(x + 2  )

												__UpperCAmelCase   :						Optional[Any]      							=					PreForwardHook()
												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )
												__UpperCAmelCase   :						Optional[Any]      							=					test_model(UpperCamelCase  )
												self.assertTrue(torch.allclose(UpperCamelCase ,       UpperCamelCase ,       atol=1e-5  )  )

												# Attaching a hook to a model when it already has one replaces, does not chain
												__UpperCAmelCase   :						Optional[Any]      							=					PreForwardHook()
												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )
												__UpperCAmelCase   :						Optional[int]      							=					test_model(UpperCamelCase  )
												self.assertTrue(torch.allclose(UpperCamelCase ,       UpperCamelCase ,       atol=1e-5  )  )

												# You need to use the sequential hook to chain two or more hooks
												__UpperCAmelCase   :						Optional[Any]      							=					SequentialHook(PreForwardHook() ,       PreForwardHook()  )
												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )

												__UpperCAmelCase   :						List[str]      							=					test_model(UpperCamelCase  )
												assert torch.allclose(UpperCamelCase ,       UpperCamelCase ,       atol=1e-5  )






					def lowerCamelCase__							(       self    : Dict  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[int]      							=					ModelForTest()
												__UpperCAmelCase   :						str      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						int      							=					test_model(UpperCamelCase  )

												__UpperCAmelCase   :						Dict      							=					PostForwardHook()
												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )
												__UpperCAmelCase   :						Any      							=					test_model(UpperCamelCase  )
												self.assertTrue(torch.allclose(UpperCamelCase ,       output + 1 ,       atol=1e-5  )  )

												# Attaching a hook to a model when it already has one replaces, does not chain
												__UpperCAmelCase   :						List[str]      							=					PostForwardHook()
												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )
												__UpperCAmelCase   :						Optional[Any]      							=					test_model(UpperCamelCase  )
												self.assertTrue(torch.allclose(UpperCamelCase ,       output + 1 ,       atol=1e-5  )  )

												# You need to use the sequential hook to chain two or more hooks
												__UpperCAmelCase   :						Optional[int]      							=					SequentialHook(PostForwardHook() ,       PostForwardHook()  )
												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )

												__UpperCAmelCase   :						int      							=					test_model(UpperCamelCase  )
												assert torch.allclose(UpperCamelCase ,       output + 2 ,       atol=1e-5  )






					def lowerCamelCase__							(       self    : Optional[int]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						int      							=					ModelForTest()
												__UpperCAmelCase   :						str      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						Optional[Any]      							=					test_model(UpperCamelCase  )

												__UpperCAmelCase   :						Union[str, Any]      							=					PostForwardHook()
												add_hook_to_module(UpperCamelCase ,       UpperCamelCase  )
												__UpperCAmelCase   :						Optional[int]      							=					test_model(UpperCamelCase  )
												self.assertTrue(torch.allclose(UpperCamelCase ,       output + 1  )  )
												self.assertTrue(outputa.requires_grad  )

												__UpperCAmelCase   :						List[str]      							=					True
												__UpperCAmelCase   :						Optional[int]      							=					test_model(UpperCamelCase  )
												self.assertFalse(outputa.requires_grad  )






					@require_multi_gpu
					def lowerCamelCase__							(       self    : Optional[Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						str      							=					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
												__UpperCAmelCase   :						List[str]      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						Any      							=					model(UpperCamelCase  )
												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(UpperCamelCase ,       AlignDevicesHook(io_same_device=UpperCamelCase  )  )
												__UpperCAmelCase   :						int      							=					torch.randn(2 ,       3  ).to(0  )
												__UpperCAmelCase   :						Any      							=					model(UpperCamelCase  )
												self.assertEqual(output.device ,       torch.device(0  )  )






					def lowerCamelCase__							(       self    : Optional[int]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Tuple      							=					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
												__UpperCAmelCase   :						Union[str, Any]      							=					{"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True}

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

												# 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
												__UpperCAmelCase   :						Any      							=					torch.device(hook_kwargs["""execution_device"""]  )
												self.assertEqual(model.batchnorm.running_mean.device ,       UpperCamelCase  )

												__UpperCAmelCase   :						Union[str, Any]      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						Optional[int]      							=					model(UpperCamelCase  )
												self.assertEqual(output.device ,       UpperCamelCase  )

												# 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
												__UpperCAmelCase   :						Union[str, Any]      							=					{
												    """execution_device""": 0 if torch.cuda.is_available() else """cpu""",
												    """offload""": True,
												    """offload_buffers""": True,
												}

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

												# 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"""  )  )

												__UpperCAmelCase   :						str      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						Dict      							=					model(UpperCamelCase  )
												self.assertEqual(output.device ,       UpperCamelCase  )

												# 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    : Union[str, Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						int      							=					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
												__UpperCAmelCase   :						Optional[int]      							=					0 if torch.cuda.is_available() else """cpu"""
												attach_align_device_hook(UpperCamelCase ,       execution_device=UpperCamelCase ,       offload=UpperCamelCase  )

												# 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
												__UpperCAmelCase   :						Any      							=					torch.device(UpperCamelCase  )
												self.assertEqual(model.batchnorm.running_mean.device ,       UpperCamelCase  )

												__UpperCAmelCase   :						str      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						Any      							=					model(UpperCamelCase  )
												self.assertEqual(output.device ,       UpperCamelCase  )

												# Removing hooks loads back the weights in the model.
												remove_hook_from_submodules(UpperCamelCase  )
												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(UpperCamelCase ,       execution_device=UpperCamelCase ,       offload=UpperCamelCase ,       offload_buffers=UpperCamelCase  )

												# 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"""  )  )

												__UpperCAmelCase   :						List[str]      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						Any      							=					model(UpperCamelCase  )
												self.assertEqual(output.device ,       UpperCamelCase  )

												# Removing hooks loads back the weights in the model.
												remove_hook_from_submodules(UpperCamelCase  )
												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    : Any  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Dict      							=					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
												__UpperCAmelCase   :						Any      							=					0 if torch.cuda.is_available() else """cpu"""
												attach_align_device_hook(
												    UpperCamelCase ,       execution_device=UpperCamelCase ,       offload=UpperCamelCase ,       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
												__UpperCAmelCase   :						str      							=					torch.device(UpperCamelCase  )
												self.assertEqual(model.batchnorm.running_mean.device ,       UpperCamelCase  )

												__UpperCAmelCase   :						Dict      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						Optional[Any]      							=					model(UpperCamelCase  )
												self.assertEqual(output.device ,       UpperCamelCase  )

												# Removing hooks loads back the weights in the model.
												remove_hook_from_submodules(UpperCamelCase  )
												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(
												    UpperCamelCase ,       execution_device=UpperCamelCase ,       offload=UpperCamelCase ,       weights_map=model.state_dict() ,       offload_buffers=UpperCamelCase ,       )

												# 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"""  )  )

												__UpperCAmelCase   :						int      							=					torch.randn(2 ,       3  )
												__UpperCAmelCase   :						List[str]      							=					model(UpperCamelCase  )
												self.assertEqual(output.device ,       UpperCamelCase  )

												# Removing hooks loads back the weights in the model.
												remove_hook_from_submodules(UpperCamelCase  )
												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"""  )  )
