





'''simple docstring'''






import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
	import bitsandbytes as bnb
	import torch
	import torch.nn as nn

	from ..pytorch_utils import ConvaD

if is_accelerate_available():
	from accelerate import init_empty_weights
	from accelerate.utils import find_tied_parameters

__UpperCamelCase					    =	logging.get_logger(__name__)







def 					_a						(       _lowerCamelCase    ,	_lowerCamelCase    ,	_lowerCamelCase    ,	_lowerCamelCase=None    ,	_lowerCamelCase=None ) ->				List[Any]:



			"""simple docstring"""


			if "." in tensor_name:
						__snake_case					:      List[str]							      =     tensor_name.split(""".""" )
						for split in splits[:-1]:
									__snake_case					:      Optional[int]							      =     getattr(_lowerCamelCase    ,	_lowerCamelCase )
									if new_module is None:
												raise ValueError(F'''{module} has no attribute {split}.''' )
									__snake_case					:      str							      =     new_module
						__snake_case					:      str							      =     splits[-1]

			if tensor_name not in module._parameters and tensor_name not in module._buffers:
						raise ValueError(F'''{module} does not have a parameter or a buffer named {tensor_name}.''' )
			__snake_case					:      Union[str, Any]							      =     tensor_name in module._buffers
			__snake_case					:      Union[str, Any]							      =     getattr(_lowerCamelCase    ,	_lowerCamelCase )

			if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None:
						raise ValueError(F'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.''' )

			__snake_case					:      Union[str, Any]							      =     False
			__snake_case					:      int							      =     False
			if is_buffer or not is_bitsandbytes_available():
						__snake_case					:      int							      =     False
						__snake_case					:      Dict							      =     False
			else:
						__snake_case					:      int							      =     hasattr(bnb.nn    ,	"""Params4bit""" ) and isinstance(module._parameters[tensor_name]    ,	bnb.nn.Paramsabit )
						__snake_case					:      Any							      =     isinstance(module._parameters[tensor_name]    ,	bnb.nn.IntaParams )

			if is_abit or is_abit:
						__snake_case					:      Union[str, Any]							      =     module._parameters[tensor_name]
						if param.device.type != "cuda":
									if value is None:
												__snake_case					:      Dict							      =     old_value.to(_lowerCamelCase )
									elif isinstance(_lowerCamelCase    ,	torch.Tensor ):
												__snake_case					:      Tuple							      =     value.to("""cpu""" )
												if value.dtype == torch.inta:
															__snake_case					:      Tuple							      =     version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse(
															    """0.37.2""" )
															if not is_abit_serializable:
																		raise ValueError(
																		    """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """
																		    """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" )
									else:
												__snake_case					:      Union[str, Any]							      =     torch.tensor(_lowerCamelCase    ,	device="""cpu""" )

									# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
									# Since weights are saved in the correct "orientation", we skip transposing when loading.
									if issubclass(module.source_cls    ,	_lowerCamelCase ) and fpaa_statistics is None:
												__snake_case					:      Optional[int]							      =     new_value.T

									__snake_case					:      str							      =     old_value.__dict__
									if is_abit:
												__snake_case					:      Tuple							      =     bnb.nn.IntaParams(_lowerCamelCase    ,	requires_grad=_lowerCamelCase    ,	**_lowerCamelCase ).to(_lowerCamelCase )
									elif is_abit:
												__snake_case					:      int							      =     bnb.nn.Paramsabit(_lowerCamelCase    ,	requires_grad=_lowerCamelCase    ,	**_lowerCamelCase ).to(_lowerCamelCase )

									__snake_case					:      Tuple							      =     new_value
									if fpaa_statistics is not None:
												setattr(module.weight    ,	"""SCB"""    ,	fpaa_statistics.to(_lowerCamelCase ) )

			else:
						if value is None:
									__snake_case					:      List[Any]							      =     old_value.to(_lowerCamelCase )
						elif isinstance(_lowerCamelCase    ,	torch.Tensor ):
									__snake_case					:      Dict							      =     value.to(_lowerCamelCase )
						else:
									__snake_case					:      List[Any]							      =     torch.tensor(_lowerCamelCase    ,	device=_lowerCamelCase )

						if is_buffer:
									__snake_case					:      Optional[int]							      =     new_value
						else:
									__snake_case					:      Tuple							      =     nn.Parameter(_lowerCamelCase    ,	requires_grad=old_value.requires_grad )
									__snake_case					:      str							      =     new_value







def 					_a						(       _lowerCamelCase    ,	_lowerCamelCase=None    ,	_lowerCamelCase=None    ,	_lowerCamelCase=None    ,	_lowerCamelCase=False ) ->				Optional[Any]:



			"""simple docstring"""


			for name, module in model.named_children():
						if current_key_name is None:
									__snake_case					:      Tuple							      =     []
						current_key_name.append(_lowerCamelCase )

						if (isinstance(_lowerCamelCase    ,	nn.Linear ) or isinstance(_lowerCamelCase    ,	_lowerCamelCase )) and name not in modules_to_not_convert:
									# Check if the current key is not in the `modules_to_not_convert`
									if not any(key in """.""".join(_lowerCamelCase ) for key in modules_to_not_convert ):
												with init_empty_weights():
															if isinstance(_lowerCamelCase    ,	_lowerCamelCase ):
																		__snake_case      ,     __snake_case					:      Union[str, Any]							      =     module.weight.shape
															else:
																		__snake_case					:      Dict							      =     module.in_features
																		__snake_case					:      Any							      =     module.out_features

															if quantization_config.quantization_method() == "llm_int8":
																		__snake_case					:      Union[str, Any]							      =     bnb.nn.LinearabitLt(
																		    _lowerCamelCase    ,	_lowerCamelCase    ,	module.bias is not None    ,	has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight    ,	threshold=quantization_config.llm_inta_threshold    ,	)
																		__snake_case					:      Any							      =     True
															else:
																		if (
																		    quantization_config.llm_inta_skip_modules is not None
																		    and name in quantization_config.llm_inta_skip_modules
																		):
																					pass
																		else:
																					__snake_case					:      Any							      =     bnb.nn.Linearabit(
																					    _lowerCamelCase    ,	_lowerCamelCase    ,	module.bias is not None    ,	quantization_config.bnb_abit_compute_dtype    ,	compress_statistics=quantization_config.bnb_abit_use_double_quant    ,	quant_type=quantization_config.bnb_abit_quant_type    ,	)
																					__snake_case					:      Optional[int]							      =     True
                    # Store the module class in case we need to transpose the weight later
															__snake_case					:      List[Any]							      =     type(_lowerCamelCase )
															# Force requires grad to False to avoid unexpected errors
															model._modules[name].requires_grad_(_lowerCamelCase )
						if len(list(module.children() ) ) > 0:
									__snake_case      ,     __snake_case					:      Optional[Any]							      =     _replace_with_bnb_linear(
									    _lowerCamelCase    ,	_lowerCamelCase    ,	_lowerCamelCase    ,	_lowerCamelCase    ,	has_been_replaced=_lowerCamelCase    ,	)
						# Remove the last key for recursion
						current_key_name.pop(-1 )
			return model, has_been_replaced







def 					_a						(       _lowerCamelCase    ,	_lowerCamelCase=None    ,	_lowerCamelCase=None    ,	_lowerCamelCase=None ) ->				str:



			"""simple docstring"""


			__snake_case					:      Dict							      =     ["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert
			__snake_case      ,     __snake_case					:      int							      =     _replace_with_bnb_linear(
			    _lowerCamelCase    ,	_lowerCamelCase    ,	_lowerCamelCase    ,	_lowerCamelCase )

			if not has_been_replaced:
						logger.warning(
						    """You are loading your model in 8bit or 4bit but no linear modules were found in your model."""
						    """ Please double check your model architecture, or submit an issue on github if you think this is"""
						    """ a bug.""" )

			return model







def 					_a						(       *_lowerCamelCase    ,	**_lowerCamelCase ) ->				List[str]:



			"""simple docstring"""


			warnings.warn(
			    """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead"""    ,	_lowerCamelCase    ,	)
			return replace_with_bnb_linear(*_lowerCamelCase    ,	**_lowerCamelCase )







def 					_a						(       *_lowerCamelCase    ,	**_lowerCamelCase ) ->				str:



			"""simple docstring"""


			warnings.warn(
			    """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead"""    ,	_lowerCamelCase    ,	)
			return set_module_quantized_tensor_to_device(*_lowerCamelCase    ,	**_lowerCamelCase )







def 					_a						(       _lowerCamelCase ) ->				Any:



			"""simple docstring"""


			__snake_case					:      Tuple							      =     deepcopy(_lowerCamelCase )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
			tied_model.tie_weights()

			__snake_case					:      int							      =     find_tied_parameters(_lowerCamelCase )
			# For compatibility with Accelerate < 0.18
			if isinstance(_lowerCamelCase    ,	_lowerCamelCase ):
						__snake_case					:      Union[str, Any]							      =     sum(list(tied_params.values() )    ,	[] ) + list(tied_params.keys() )
			else:
						__snake_case					:      Dict							      =     sum(_lowerCamelCase    ,	[] )
			__snake_case					:      int							      =     len(_lowerCamelCase ) > 0

			# Check if it is a base model
			__snake_case					:      Tuple							      =     not hasattr(_lowerCamelCase    ,	model.base_model_prefix )

			# Ignore this for base models (BertModel, GPT2Model, etc.)
			if (not has_tied_params) and is_base_model:
						return []

			# otherwise they have an attached head
			__snake_case					:      Union[str, Any]							      =     list(model.named_children() )
			__snake_case					:      List[Any]							      =     [list_modules[-1][0]]

			# add last module together with tied weights
			__snake_case					:      Tuple							      =     set(_lowerCamelCase ) - set(_lowerCamelCase )
			__snake_case					:      str							      =     list(set(_lowerCamelCase ) ) + list(_lowerCamelCase )

			# remove ".weight" from the keys
			__snake_case					:      List[Any]							      =     [""".weight""", """.bias"""]
			__snake_case					:      Union[str, Any]							      =     []
			for name in list_untouched:
						for name_to_remove in names_to_remove:
									if name_to_remove in name:
												__snake_case					:      Optional[int]							      =     name.replace(_lowerCamelCase    ,	"""""" )
						filtered_module_names.append(_lowerCamelCase )

			return filtered_module_names









'''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  _A (					nn.Module		):

		def __init__(   self					:   List[str]			)					->    Optional[Any]:


					"""simple docstring"""

					super().__init__()
					__snake_case					:      List[Any]							      =     nn.Linear(3  ,      4			)
					__snake_case					:      str							      =     nn.BatchNormad(4			)
					__snake_case					:      Optional[Any]							      =     nn.Linear(4  ,      5			)

		def 	lowercase__     (   self					:   str  ,      __magic_name__					:   Dict			)					->    List[str]:


					"""simple docstring"""

					return self.lineara(self.batchnorm(self.lineara(__magic_name__			)			)			)





class  _A (					__lowercase		):

		def 	lowercase__     (   self					:   List[str]  ,      __magic_name__					:   Tuple  ,      *__magic_name__					:   Dict  ,      **__magic_name__					:   Optional[Any]			)					->    Tuple:


					"""simple docstring"""

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





class  _A (					__lowercase		):

		def 	lowercase__     (   self					:   str  ,      __magic_name__					:   Union[str, Any]  ,      __magic_name__					:   Tuple			)					->    Union[str, Any]:


					"""simple docstring"""

					return output + 1





class  _A (					unittest.TestCase		):

		def 	lowercase__     (   self					:   Dict			)					->    Any:


					"""simple docstring"""

					__snake_case					:      int							      =     ModelForTest()
					__snake_case					:      Tuple							      =     ModelHook()

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

		def 	lowercase__     (   self					:   Tuple			)					->    List[str]:


					"""simple docstring"""

					__snake_case					:      List[Any]							      =     ModelForTest()
					__snake_case					:      Optional[int]							      =     ModelHook()

					add_hook_to_module(__magic_name__  ,      __magic_name__			)
					add_hook_to_module(__magic_name__  ,      __magic_name__  ,      append=__magic_name__			)

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

		def 	lowercase__     (   self					:   str			)					->    Union[str, Any]:


					"""simple docstring"""

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

					__snake_case					:      Union[str, Any]							      =     PreForwardHook()
					add_hook_to_module(__magic_name__  ,      __magic_name__			)
					__snake_case					:      int							      =     test_model(__magic_name__			)
					self.assertTrue(torch.allclose(__magic_name__  ,      __magic_name__  ,      atol=1E-5			)			)

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

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

					__snake_case					:      List[str]							      =     test_model(__magic_name__			)
					assert torch.allclose(__magic_name__  ,      __magic_name__  ,      atol=1E-5			)

		def 	lowercase__     (   self					:   Union[str, Any]			)					->    List[str]:


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     ModelForTest()
					__snake_case					:      str							      =     torch.randn(2  ,      3			)
					__snake_case					:      Any							      =     test_model(__magic_name__			)

					__snake_case					:      Any							      =     PostForwardHook()
					add_hook_to_module(__magic_name__  ,      __magic_name__			)
					__snake_case					:      Any							      =     test_model(__magic_name__			)
					self.assertTrue(torch.allclose(__magic_name__  ,      output + 1  ,      atol=1E-5			)			)

					# Attaching a hook to a model when it already has one replaces, does not chain
					__snake_case					:      Any							      =     PostForwardHook()
					add_hook_to_module(__magic_name__  ,      __magic_name__			)
					__snake_case					:      Dict							      =     test_model(__magic_name__			)
					self.assertTrue(torch.allclose(__magic_name__  ,      output + 1  ,      atol=1E-5			)			)

					# You need to use the sequential hook to chain two or more hooks
					__snake_case					:      str							      =     SequentialHook(PostForwardHook()  ,      PostForwardHook()			)
					add_hook_to_module(__magic_name__  ,      __magic_name__			)

					__snake_case					:      int							      =     test_model(__magic_name__			)
					assert torch.allclose(__magic_name__  ,      output + 2  ,      atol=1E-5			)

		def 	lowercase__     (   self					:   str			)					->    int:


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     ModelForTest()
					__snake_case					:      int							      =     torch.randn(2  ,      3			)
					__snake_case					:      Any							      =     test_model(__magic_name__			)

					__snake_case					:      Dict							      =     PostForwardHook()
					add_hook_to_module(__magic_name__  ,      __magic_name__			)
					__snake_case					:      List[Any]							      =     test_model(__magic_name__			)
					self.assertTrue(torch.allclose(__magic_name__  ,      output + 1			)			)
					self.assertTrue(outputa.requires_grad			)

					__snake_case					:      Dict							      =     True
					__snake_case					:      int							      =     test_model(__magic_name__			)
					self.assertFalse(outputa.requires_grad			)

		@require_multi_gpu
		def 	lowercase__     (   self					:   Tuple			)					->    List[Any]:


					"""simple docstring"""

					__snake_case					:      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
					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
					__snake_case					:      Tuple							      =     torch.randn(2  ,      3			)
					__snake_case					:      Union[str, Any]							      =     model(__magic_name__			)
					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(__magic_name__  ,      AlignDevicesHook(io_same_device=__magic_name__			)			)
					__snake_case					:      Tuple							      =     torch.randn(2  ,      3			).to(0			)
					__snake_case					:      Any							      =     model(__magic_name__			)
					self.assertEqual(output.device  ,      torch.device(0			)			)

		def 	lowercase__     (   self					:   Union[str, Any]			)					->    str:


					"""simple docstring"""

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

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

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

					__snake_case					:      Dict							      =     torch.randn(2  ,      3			)
					__snake_case					:      Any							      =     model(__magic_name__			)
					self.assertEqual(output.device  ,      __magic_name__			)

					# 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
					__snake_case					:      int							      =     {
					    """execution_device""": 0 if torch.cuda.is_available() else """cpu""",
					    """offload""": True,
					    """offload_buffers""": True,
					}

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

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

					__snake_case					:      str							      =     torch.randn(2  ,      3			)
					__snake_case					:      str							      =     model(__magic_name__			)
					self.assertEqual(output.device  ,      __magic_name__			)

					# 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 	lowercase__     (   self					:   Dict			)					->    str:


					"""simple docstring"""

					__snake_case					:      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
					__snake_case					:      Union[str, Any]							      =     0 if torch.cuda.is_available() else """cpu"""
					attach_align_device_hook(__magic_name__  ,      execution_device=__magic_name__  ,      offload=__magic_name__			)

					# 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
					__snake_case					:      Union[str, Any]							      =     torch.device(__magic_name__			)
					self.assertEqual(model.batchnorm.running_mean.device  ,      __magic_name__			)

					__snake_case					:      Optional[int]							      =     torch.randn(2  ,      3			)
					__snake_case					:      Dict							      =     model(__magic_name__			)
					self.assertEqual(output.device  ,      __magic_name__			)

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

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

					__snake_case					:      Dict							      =     torch.randn(2  ,      3			)
					__snake_case					:      Optional[int]							      =     model(__magic_name__			)
					self.assertEqual(output.device  ,      __magic_name__			)

					# Removing hooks loads back the weights in the model.
					remove_hook_from_submodules(__magic_name__			)
					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 	lowercase__     (   self					:   Any			)					->    Union[str, Any]:


					"""simple docstring"""

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

					__snake_case					:      Tuple							      =     torch.randn(2  ,      3			)
					__snake_case					:      Optional[Any]							      =     model(__magic_name__			)
					self.assertEqual(output.device  ,      __magic_name__			)

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

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

					__snake_case					:      List[str]							      =     torch.randn(2  ,      3			)
					__snake_case					:      Dict							      =     model(__magic_name__			)
					self.assertEqual(output.device  ,      __magic_name__			)

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


