




"""simple docstring"""

from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


__A       						=	logging.get_logger(__name__)


# General docstring
__A       						=	"MobileNetV1Config"

# Base docstring
__A       						=	"google/mobilenet_v1_1.0_224"
__A       						=	[1, 1_024, 7, 7]

# Image classification docstring
__A       						=	"google/mobilenet_v1_1.0_224"
__A       						=	"tabby, tabby cat"


__A       						=	[
    "google/mobilenet_v1_1.0_224",
    "google/mobilenet_v1_0.75_192",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]



def      UpperCamelCase__   (						lowercase__     :   Union[str, Any]				,   lowercase__     :   Optional[Any]				,   lowercase__     :   Optional[int]=None      ):
		snake_case						:  Optional[int]    	= {}

		if isinstance(UpperCamelCase__				,   UpperCamelCase__      ):
				snake_case						:  Dict    	= model.mobilenet_va
		else:
				snake_case						:  Optional[Any]    	= model

		snake_case						:  int    	= """MobilenetV1/Conv2d_0/"""
		snake_case						:  Any    	= backbone.conv_stem.convolution.weight
		snake_case						:  str    	= backbone.conv_stem.normalization.bias
		snake_case						:  Any    	= backbone.conv_stem.normalization.weight
		snake_case						:  Any    	= backbone.conv_stem.normalization.running_mean
		snake_case						:  int    	= backbone.conv_stem.normalization.running_var

		for i in range(13      ):
				snake_case						:  int    	= i + 1
				snake_case						:  Optional[int]    	= i * 2

				snake_case						:  Optional[Any]    	= backbone.layer[pt_index]
				snake_case						:  List[str]    	= F'''MobilenetV1/Conv2d_{tf_index}_depthwise/'''
				snake_case						:  Any    	= pointer.convolution.weight
				snake_case						:  Dict    	= pointer.normalization.bias
				snake_case						:  Tuple    	= pointer.normalization.weight
				snake_case						:  Optional[Any]    	= pointer.normalization.running_mean
				snake_case						:  int    	= pointer.normalization.running_var

				snake_case						:  Optional[int]    	= backbone.layer[pt_index + 1]
				snake_case						:  Optional[Any]    	= F'''MobilenetV1/Conv2d_{tf_index}_pointwise/'''
				snake_case						:  Optional[int]    	= pointer.convolution.weight
				snake_case						:  str    	= pointer.normalization.bias
				snake_case						:  Optional[Any]    	= pointer.normalization.weight
				snake_case						:  Any    	= pointer.normalization.running_mean
				snake_case						:  Union[str, Any]    	= pointer.normalization.running_var

		if isinstance(UpperCamelCase__				,   UpperCamelCase__      ):
				snake_case						:  Optional[int]    	= """MobilenetV1/Logits/Conv2d_1c_1x1/"""
				snake_case						:  Any    	= model.classifier.weight
				snake_case						:  Union[str, Any]    	= model.classifier.bias

		return tf_to_pt_map



def      UpperCamelCase__   (						lowercase__     :   Dict				,   lowercase__     :   Optional[Any]				,   lowercase__     :   Optional[Any]      ):
		try:
				import numpy as np
				import tensorflow as tf
		except ImportError:
				logger.error(
				    "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
				    "https://www.tensorflow.org/install/ for installation instructions."      )
				raise

		# Load weights from TF model
		snake_case						:  List[str]    	= tf.train.list_variables(UpperCamelCase__      )
		snake_case						:  List[Any]    	= {}
		for name, shape in init_vars:
				logger.info(F'''Loading TF weight {name} with shape {shape}'''      )
				snake_case						:  str    	= tf.train.load_variable(UpperCamelCase__				,   UpperCamelCase__      )
				snake_case						:  int    	= array

		# Build TF to PyTorch weights loading map
		snake_case						:  Optional[Any]    	= _build_tf_to_pytorch_map(UpperCamelCase__				,   UpperCamelCase__				,   UpperCamelCase__      )

		for name, pointer in tf_to_pt_map.items():
				logger.info(F'''Importing {name}'''      )
				if name not in tf_weights:
						logger.info(F'''{name} not in tf pre-trained weights, skipping'''      )
						continue

				snake_case						:  Optional[int]    	= tf_weights[name]

				if "depthwise_weights" in name:
						logger.info("Transposing depthwise"      )
						snake_case						:  Tuple    	= np.transpose(UpperCamelCase__				,   (2, 3, 0, 1)      )
				elif "weights" in name:
						logger.info("Transposing"      )
						if len(pointer.shape      ) == 2:  # copying into linear layer
								snake_case						:  List[Any]    	= array.squeeze().transpose()
						else:
								snake_case						:  List[str]    	= np.transpose(UpperCamelCase__				,   (3, 2, 0, 1)      )

				if pointer.shape != array.shape:
						raise ValueError(F'''Pointer shape {pointer.shape} and array shape {array.shape} mismatched'''      )

				logger.info(F'''Initialize PyTorch weight {name} {array.shape}'''      )
				snake_case						:  Optional[Any]    	= torch.from_numpy(UpperCamelCase__      )

				tf_weights.pop(UpperCamelCase__				,   UpperCamelCase__      )
				tf_weights.pop(name + "/RMSProp"				,   UpperCamelCase__      )
				tf_weights.pop(name + "/RMSProp_1"				,   UpperCamelCase__      )
				tf_weights.pop(name + "/ExponentialMovingAverage"				,   UpperCamelCase__      )

		logger.info(F'''Weights not copied to PyTorch model: {', '.join(tf_weights.keys()      )}'''      )
		return model



def      UpperCamelCase__   (						lowercase__     :   str				,   lowercase__     :   List[Any]      ):
		snake_case						:  Optional[Any]    	= features.shape[-2:]
		snake_case						:  Dict    	= conv_layer.stride
		snake_case						:  Dict    	= conv_layer.kernel_size

		if in_height % stride_height == 0:
				snake_case						:  Optional[Any]    	= max(kernel_height - stride_height				,   0      )
		else:
				snake_case						:  Optional[int]    	= max(kernel_height - (in_height % stride_height)				,   0      )

		if in_width % stride_width == 0:
				snake_case						:  Any    	= max(kernel_width - stride_width				,   0      )
		else:
				snake_case						:  int    	= max(kernel_width - (in_width % stride_width)				,   0      )

		snake_case						:  str    	= pad_along_width // 2
		snake_case						:  Union[str, Any]    	= pad_along_width - pad_left
		snake_case						:  Optional[int]    	= pad_along_height // 2
		snake_case						:  List[Any]    	= pad_along_height - pad_top

		snake_case						:  Optional[Any]    	= (pad_left, pad_right, pad_top, pad_bottom)
		return nn.functional.pad(UpperCamelCase__				,   UpperCamelCase__				,   "constant"				,   0.0      )
class 	lowerCamelCase__			(     nn.Module	):


			def __init__(   self ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE = 1 ,       SCREAMING_SNAKE_CASE = 1 ,       SCREAMING_SNAKE_CASE = False ,       SCREAMING_SNAKE_CASE = True ,       SCREAMING_SNAKE_CASE = True ,       ):



					"""simple docstring"""







					super().__init__()
					snake_case						:  Any    	= config

					if in_channels % groups != 0:
							raise ValueError(F'''Input channels ({in_channels}) are not divisible by {groups} groups.'''							)
					if out_channels % groups != 0:
							raise ValueError(F'''Output channels ({out_channels}) are not divisible by {groups} groups.'''							)

					snake_case						:  Dict    	= 0 if config.tf_padding else int((kernel_size - 1) / 2							)

					snake_case						:  List[Any]    	= nn.Convad(
					    in_channels=UpperCAmelCase__ ,       out_channels=UpperCAmelCase__ ,       kernel_size=UpperCAmelCase__ ,       stride=UpperCAmelCase__ ,       padding=UpperCAmelCase__ ,       groups=UpperCAmelCase__ ,       bias=UpperCAmelCase__ ,       padding_mode="zeros" ,       )

					if use_normalization:
							snake_case						:  int    	= nn.BatchNormad(
							    num_features=UpperCAmelCase__ ,       eps=config.layer_norm_eps ,       momentum=0.99_97 ,       affine=UpperCAmelCase__ ,       track_running_stats=UpperCAmelCase__ ,       )
					else:
							snake_case						:  int    	= None

					if use_activation:
							if isinstance(UpperCAmelCase__ ,       UpperCAmelCase__							):
									snake_case						:  Optional[int]    	= ACTaFN[use_activation]
							elif isinstance(config.hidden_act ,       UpperCAmelCase__							):
									snake_case						:  int    	= ACTaFN[config.hidden_act]
							else:
									snake_case						:  str    	= config.hidden_act
					else:
							snake_case						:  Union[str, Any]    	= None



			def 							lowerCamelCase_ (   self ,       SCREAMING_SNAKE_CASE							):



					"""simple docstring"""







					if self.config.tf_padding:
							snake_case						:  List[str]    	= apply_tf_padding(UpperCAmelCase__ ,       self.convolution							)
					snake_case						:  List[str]    	= self.convolution(UpperCAmelCase__							)
					if self.normalization is not None:
							snake_case						:  Optional[int]    	= self.normalization(UpperCAmelCase__							)
					if self.activation is not None:
							snake_case						:  Dict    	= self.activation(UpperCAmelCase__							)
					return features







class 	lowerCamelCase__			(     snake_case_	):
			a__       :					Dict	    =   MobileNetVaConfig
			a__       :					Optional[Any]	    =   load_tf_weights_in_mobilenet_va
			a__       :					Dict	    =   '''mobilenet_v1'''
			a__       :					Any	    =   '''pixel_values'''
			a__       :					str	    =   False


			def 							lowerCamelCase_ (   self ,       SCREAMING_SNAKE_CASE							):



					"""simple docstring"""







					if isinstance(UpperCAmelCase__ ,       (nn.Linear, nn.Convad)							):
							module.weight.data.normal_(mean=0.0 ,       std=self.config.initializer_range							)
							if module.bias is not None:
									module.bias.data.zero_()
					elif isinstance(UpperCAmelCase__ ,       nn.BatchNormad							):
							module.bias.data.zero_()
							module.weight.data.fill_(1.0							)







__A       						=	R"\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

__A       						=	R"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`MobileNetV1ImageProcessor.__call__`] for details.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"
@add_start_docstrings(
    """The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.""" ,     snake_case_ ,     )
class 	lowerCamelCase__			(     snake_case_	):


			def __init__(   self ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE = True							):



					"""simple docstring"""







					super().__init__(UpperCAmelCase__							)
					snake_case						:  List[Any]    	= config

					snake_case						:  Any    	= 32
					snake_case						:  Optional[Any]    	= max(int(depth * config.depth_multiplier							) ,       config.min_depth							)

					snake_case						:  Optional[Any]    	= MobileNetVaConvLayer(
					    UpperCAmelCase__ ,       in_channels=config.num_channels ,       out_channels=UpperCAmelCase__ ,       kernel_size=3 ,       stride=2 ,       )

					snake_case						:  int    	= [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

					snake_case						:  List[Any]    	= nn.ModuleList()
					for i in range(13							):
							snake_case						:  List[Any]    	= out_channels

							if strides[i] == 2 or i == 0:
									depth *= 2
									snake_case						:  Union[str, Any]    	= max(int(depth * config.depth_multiplier							) ,       config.min_depth							)

							self.layer.append(
							    MobileNetVaConvLayer(
							        UpperCAmelCase__ ,       in_channels=UpperCAmelCase__ ,       out_channels=UpperCAmelCase__ ,       kernel_size=3 ,       stride=strides[i] ,       groups=UpperCAmelCase__ ,       )							)

							self.layer.append(
							    MobileNetVaConvLayer(
							        UpperCAmelCase__ ,       in_channels=UpperCAmelCase__ ,       out_channels=UpperCAmelCase__ ,       kernel_size=1 ,       )							)

					snake_case						:  Dict    	= nn.AdaptiveAvgPoolad((1, 1)							) if add_pooling_layer else None

					# Initialize weights and apply final processing
					self.post_init()


			def 							lowerCamelCase_ (   self ,       SCREAMING_SNAKE_CASE							):



					"""simple docstring"""







					raise NotImplementedError



			@add_start_docstrings_to_model_forward(UpperCAmelCase__							)
			@add_code_sample_docstrings(
			    checkpoint=_CHECKPOINT_FOR_DOC ,       output_type=UpperCAmelCase__ ,       config_class=_CONFIG_FOR_DOC ,       modality="vision" ,       expected_output=_EXPECTED_OUTPUT_SHAPE ,       )
			def 							lowerCamelCase_ (   self ,       SCREAMING_SNAKE_CASE = None ,       SCREAMING_SNAKE_CASE = None ,       SCREAMING_SNAKE_CASE = None ,       ):



					"""simple docstring"""







					snake_case						:  Union[str, Any]    	= (
					    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
					)
					snake_case						:  Union[str, Any]    	= return_dict if return_dict is not None else self.config.use_return_dict

					if pixel_values is None:
							raise ValueError("You have to specify pixel_values"							)

					snake_case						:  Tuple    	= self.conv_stem(UpperCAmelCase__							)

					snake_case						:  Tuple    	= () if output_hidden_states else None

					for i, layer_module in enumerate(self.layer							):
							snake_case						:  Optional[int]    	= layer_module(UpperCAmelCase__							)

							if output_hidden_states:
									snake_case						:  int    	= all_hidden_states + (hidden_states,)

					snake_case						:  int    	= hidden_states

					if self.pooler is not None:
							snake_case						:  Tuple    	= torch.flatten(self.pooler(UpperCAmelCase__							) ,       start_dim=1							)
					else:
							snake_case						:  str    	= None

					if not return_dict:
							return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None							)

					return BaseModelOutputWithPoolingAndNoAttention(
					    last_hidden_state=UpperCAmelCase__ ,       pooler_output=UpperCAmelCase__ ,       hidden_states=UpperCAmelCase__ ,       )







@add_start_docstrings(
    """
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """ ,     snake_case_ ,     )
class 	lowerCamelCase__			(     snake_case_	):


			def __init__(   self ,       SCREAMING_SNAKE_CASE							):



					"""simple docstring"""







					super().__init__(UpperCAmelCase__							)

					snake_case						:  int    	= config.num_labels
					snake_case						:  List[Any]    	= MobileNetVaModel(UpperCAmelCase__							)

					snake_case						:  Union[str, Any]    	= self.mobilenet_va.layer[-1].convolution.out_channels

					# Classifier head
					snake_case						:  Optional[int]    	= nn.Dropout(config.classifier_dropout_prob ,       inplace=UpperCAmelCase__							)
					snake_case						:  Tuple    	= nn.Linear(UpperCAmelCase__ ,       config.num_labels							) if config.num_labels > 0 else nn.Identity()

					# Initialize weights and apply final processing
					self.post_init()



			@add_start_docstrings_to_model_forward(UpperCAmelCase__							)
			@add_code_sample_docstrings(
			    checkpoint=_IMAGE_CLASS_CHECKPOINT ,       output_type=UpperCAmelCase__ ,       config_class=_CONFIG_FOR_DOC ,       expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,       )
			def 							lowerCamelCase_ (   self ,       SCREAMING_SNAKE_CASE = None ,       SCREAMING_SNAKE_CASE = None ,       SCREAMING_SNAKE_CASE = None ,       SCREAMING_SNAKE_CASE = None ,       ):



					"""simple docstring"""







					snake_case						:  Union[str, Any]    	= return_dict if return_dict is not None else self.config.use_return_dict

					snake_case						:  Any    	= self.mobilenet_va(UpperCAmelCase__ ,       output_hidden_states=UpperCAmelCase__ ,       return_dict=UpperCAmelCase__							)

					snake_case						:  Optional[int]    	= outputs.pooler_output if return_dict else outputs[1]

					snake_case						:  List[Any]    	= self.classifier(self.dropout(UpperCAmelCase__							)							)

					snake_case						:  List[Any]    	= None
					if labels is not None:
							if self.config.problem_type is None:
									if self.num_labels == 1:
											snake_case						:  str    	= """regression"""
									elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
											snake_case						:  str    	= """single_label_classification"""
									else:
											snake_case						:  Union[str, Any]    	= """multi_label_classification"""

							if self.config.problem_type == "regression":
									snake_case						:  Optional[Any]    	= MSELoss()
									if self.num_labels == 1:
											snake_case						:  Optional[int]    	= loss_fct(logits.squeeze() ,       labels.squeeze()							)
									else:
											snake_case						:  Optional[int]    	= loss_fct(UpperCAmelCase__ ,       UpperCAmelCase__							)
							elif self.config.problem_type == "single_label_classification":
									snake_case						:  Optional[Any]    	= CrossEntropyLoss()
									snake_case						:  List[Any]    	= loss_fct(logits.view(-1 ,       self.num_labels							) ,       labels.view(-1							)							)
							elif self.config.problem_type == "multi_label_classification":
									snake_case						:  Any    	= BCEWithLogitsLoss()
									snake_case						:  Union[str, Any]    	= loss_fct(UpperCAmelCase__ ,       UpperCAmelCase__							)

					if not return_dict:
							snake_case						:  str    	= (logits,) + outputs[2:]
							return ((loss,) + output) if loss is not None else output

					return ImageClassifierOutputWithNoAttention(
					    loss=UpperCAmelCase__ ,       logits=UpperCAmelCase__ ,       hidden_states=outputs.hidden_states ,       )









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


 def __init__(     self		:						Union[str, Any]							)					->       int:
   super().__init__()
   _a  :       Optional[Any]             =	nn.Linear(3							,						4							)
   _a  :       Tuple             =	nn.BatchNormad(4							)
   _a  :       Dict             =	nn.Linear(4							,						5							)







 def _lowercase	(     self		:						Optional[int]							,						UpperCAmelCase__		:						List[str]							)					->       int:
   return self.lineara(self.batchnorm(self.lineara(UpperCAmelCase__							)							)							)







class        UpperCamelCase			(	snake_case_      ):


 def _lowercase	(     self		:						Any							,						UpperCAmelCase__		:						Any							,						*UpperCAmelCase__		:						List[str]							,						**UpperCAmelCase__		:						Optional[int]							)					->       Optional[int]:
   return (args[0] + 1,) + args[1:], kwargs







class        UpperCamelCase			(	snake_case_      ):


 def _lowercase	(     self		:						Optional[Any]							,						UpperCAmelCase__		:						Tuple							,						UpperCAmelCase__		:						Optional[Any]							)					->       List[str]:
   return output + 1







class        UpperCamelCase			(	unittest.TestCase      ):


 def _lowercase	(     self		:						Dict							)					->       str:
   _a  :       List[Any]             =	ModelForTest()
   _a  :       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 _lowercase	(     self		:						Optional[int]							)					->       Optional[int]:
   _a  :       Dict             =	ModelForTest()
   _a  :       Dict             =	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 _lowercase	(     self		:						Dict							)					->       int:
   _a  :       str             =	ModelForTest()
   _a  :       List[Any]             =	torch.randn(2							,						3							)
   _a  :       Optional[Any]             =	test_model(x + 1							)
   _a  :       str             =	test_model(x + 2							)

   _a  :       Union[str, Any]             =	PreForwardHook()
   add_hook_to_module(UpperCAmelCase__							,						UpperCAmelCase__							)
   _a  :       Tuple             =	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
   _a  :       int             =	PreForwardHook()
   add_hook_to_module(UpperCAmelCase__							,						UpperCAmelCase__							)
   _a  :       str             =	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
   _a  :       int             =	SequentialHook(PreForwardHook()							,						PreForwardHook()							)
   add_hook_to_module(UpperCAmelCase__							,						UpperCAmelCase__							)

   _a  :       Tuple             =	test_model(UpperCAmelCase__							)
   assert torch.allclose(UpperCAmelCase__							,						UpperCAmelCase__							,						atol=1E-5							)


 def _lowercase	(     self		:						Tuple							)					->       int:
   _a  :       Tuple             =	ModelForTest()
   _a  :       Union[str, Any]             =	torch.randn(2							,						3							)
   _a  :       Optional[int]             =	test_model(UpperCAmelCase__							)

   _a  :       int             =	PostForwardHook()
   add_hook_to_module(UpperCAmelCase__							,						UpperCAmelCase__							)
   _a  :       List[str]             =	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
   _a  :       List[Any]             =	PostForwardHook()
   add_hook_to_module(UpperCAmelCase__							,						UpperCAmelCase__							)
   _a  :       Dict             =	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
   _a  :       Any             =	SequentialHook(PostForwardHook()							,						PostForwardHook()							)
   add_hook_to_module(UpperCAmelCase__							,						UpperCAmelCase__							)

   _a  :       Optional[int]             =	test_model(UpperCAmelCase__							)
   assert torch.allclose(UpperCAmelCase__							,						output + 2							,						atol=1E-5							)


 def _lowercase	(     self		:						Dict							)					->       Optional[Any]:
   _a  :       Any             =	ModelForTest()
   _a  :       List[Any]             =	torch.randn(2							,						3							)
   _a  :       Dict             =	test_model(UpperCAmelCase__							)

   _a  :       Any             =	PostForwardHook()
   add_hook_to_module(UpperCAmelCase__							,						UpperCAmelCase__							)
   _a  :       List[str]             =	test_model(UpperCAmelCase__							)
   self.assertTrue(torch.allclose(UpperCAmelCase__							,						output + 1							)							)
   self.assertTrue(outputa.requires_grad							)

   _a  :       Any             =	True
   _a  :       Union[str, Any]             =	test_model(UpperCAmelCase__							)
   self.assertFalse(outputa.requires_grad							)


 @require_multi_gpu
 def _lowercase	(     self		:						Optional[Any]							)					->       str:
   _a  :       List[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
   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
   _a  :       Optional[int]             =	torch.randn(2							,						3							)
   _a  :       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__							)							)
   _a  :       str             =	torch.randn(2							,						3							).to(0							)
   _a  :       Union[str, Any]             =	model(UpperCAmelCase__							)
   self.assertEqual(output.device							,						torch.device(0							)							)


 def _lowercase	(     self		:						str							)					->       Union[str, Any]:
   _a  :       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
   _a  :       List[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
   _a  :       Dict             =	torch.device(hook_kwargs["""execution_device"""]							)
   self.assertEqual(model.batchnorm.running_mean.device							,						UpperCAmelCase__							)

   _a  :       int             =	torch.randn(2							,						3							)
   _a  :       str             =	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
   _a  :       List[str]             =	{
       """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"""							)							)

   _a  :       Tuple             =	torch.randn(2							,						3							)
   _a  :       Union[str, Any]             =	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 _lowercase	(     self		:						Tuple							)					->       List[str]:
   _a  :       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
   _a  :       Union[str, Any]             =	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
   _a  :       Dict             =	torch.device(UpperCAmelCase__							)
   self.assertEqual(model.batchnorm.running_mean.device							,						UpperCAmelCase__							)

   _a  :       Union[str, Any]             =	torch.randn(2							,						3							)
   _a  :       List[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"""							)							)

   _a  :       List[str]             =	torch.randn(2							,						3							)
   _a  :       Union[str, 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 _lowercase	(     self		:						Dict							)					->       str:
   _a  :       Optional[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
   _a  :       str             =	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
   _a  :       Union[str, Any]             =	torch.device(UpperCAmelCase__							)
   self.assertEqual(model.batchnorm.running_mean.device							,						UpperCAmelCase__							)

   _a  :       Union[str, Any]             =	torch.randn(2							,						3							)
   _a  :       int             =	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"""							)							)

   _a  :       Any             =	torch.randn(2							,						3							)
   _a  :       int             =	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"""							)							)

