






'''simple docstring'''



import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import (
     MODEL_MAPPING,
     BeitForImageClassification,
     BeitForMaskedImageModeling,
     BeitForSemanticSegmentation,
     BeitModel,
 )
 from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 import PIL
 from PIL import Image

 from transformers import BeitImageProcessor
class 							__SCREAMING_SNAKE_CASE       :




      def __init__(  self ,   lowerCamelCase ,   lowerCamelCase=100 ,   lowerCamelCase=13 ,   lowerCamelCase=30 ,   lowerCamelCase=2 ,   lowerCamelCase=3 ,   lowerCamelCase=True ,   lowerCamelCase=True ,   lowerCamelCase=32 ,   lowerCamelCase=4 ,   lowerCamelCase=4 ,   lowerCamelCase=37 ,   lowerCamelCase="gelu" ,   lowerCamelCase=0.1 ,   lowerCamelCase=0.1 ,   lowerCamelCase=10 ,   lowerCamelCase=0.02 ,   lowerCamelCase=3 ,   lowerCamelCase=None ,   lowerCamelCase=[0, 1, 2, 3] ,   )							->Optional[Any]:



         '''simple docstring'''
         __a				     =    parent
         __a				     =    100
         __a				     =    batch_size
         __a				     =    image_size
         __a				     =    patch_size
         __a				     =    num_channels
         __a				     =    is_training
         __a				     =    use_labels
         __a				     =    hidden_size
         __a				     =    num_hidden_layers
         __a				     =    num_attention_heads
         __a				     =    intermediate_size
         __a				     =    hidden_act
         __a				     =    hidden_dropout_prob
         __a				     =    attention_probs_dropout_prob
         __a				     =    type_sequence_label_size
         __a				     =    initializer_range
         __a				     =    scope
         __a				     =    out_indices
         __a				     =    num_labels

         # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         __a				     =    (image_size // patch_size) ** 2
         __a				     =    num_patches + 1




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



         '''simple docstring'''
         __a				     =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

         __a				     =    None
         __a				     =    None
         if self.use_labels:
            __a				     =    ids_tensor([self.batch_size] ,   self.type_sequence_label_size      )
            __a				     =    ids_tensor([self.batch_size, self.image_size, self.image_size] ,   self.num_labels      )

         __a				     =    self.get_config()

         return config, pixel_values, labels, pixel_labels




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         return BeitConfig(
             vocab_size=self.vocab_size ,   image_size=self.image_size ,   patch_size=self.patch_size ,   num_channels=self.num_channels ,   hidden_size=self.hidden_size ,   num_hidden_layers=self.num_hidden_layers ,   num_attention_heads=self.num_attention_heads ,   intermediate_size=self.intermediate_size ,   hidden_act=self.hidden_act ,   hidden_dropout_prob=self.hidden_dropout_prob ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob ,   is_decoder=lowerCamelCase ,   initializer_range=self.initializer_range ,   out_indices=self.out_indices ,   )




      def  __UpperCamelCase							(  self ,   lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase      )							->int:



         '''simple docstring'''
         __a				     =    BeitModel(config=lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()
         __a				     =    model(lowerCamelCase      )
         self.parent.assertEqual(result.last_hidden_state.shape ,   (self.batch_size, self.seq_length, self.hidden_size)      )




      def  __UpperCamelCase							(  self ,   lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase      )							->int:



         '''simple docstring'''
         __a				     =    BeitForMaskedImageModeling(config=lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()
         __a				     =    model(lowerCamelCase      )
         self.parent.assertEqual(result.logits.shape ,   (self.batch_size, self.seq_length - 1, self.vocab_size)      )




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



         '''simple docstring'''
         __a				     =    self.type_sequence_label_size
         __a				     =    BeitForImageClassification(lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()
         __a				     =    model(lowerCamelCase ,   labels=lowerCamelCase      )
         self.parent.assertEqual(result.logits.shape ,   (self.batch_size, self.type_sequence_label_size)      )

         # test greyscale images
         __a				     =    1
         __a				     =    BeitForImageClassification(lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()

         __a				     =    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
         __a				     =    model(lowerCamelCase ,   labels=lowerCamelCase      )
         self.parent.assertEqual(result.logits.shape ,   (self.batch_size, self.type_sequence_label_size)      )




      def  __UpperCamelCase							(  self ,   lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase ,   lowerCamelCase      )							->Optional[int]:



         '''simple docstring'''
         __a				     =    self.num_labels
         __a				     =    BeitForSemanticSegmentation(lowerCamelCase      )
         model.to(lowerCamelCase      )
         model.eval()
         __a				     =    model(lowerCamelCase      )
         self.parent.assertEqual(
             result.logits.shape ,   (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )
         __a				     =    model(lowerCamelCase ,   labels=lowerCamelCase      )
         self.parent.assertEqual(
             result.logits.shape ,   (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )






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



         '''simple docstring'''
         __a				     =    self.prepare_config_and_inputs()
         __a     ,			__a     ,			__a     ,			__a				     =    config_and_inputs
         __a				     =    {'pixel_values': pixel_values}
         return config, inputs_dict







@require_torch
class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase      ,      _lowerCAmelCase      ,      unittest.TestCase     ):
      __a  					=(
          (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
          if is_torch_available()
          else ()
      )
      __a  					=(
          {
              "feature-extraction": BeitModel,
              "image-classification": BeitForImageClassification,
              "image-segmentation": BeitForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      __a  					=False
      __a  					=False
      __a  					=False




      def  __UpperCamelCase							(  self      )							->Optional[Any]:



         '''simple docstring'''
         __a				     =    BeitModelTester(self      )
         __a				     =    ConfigTester(self ,   config_class=lowerCamelCase ,   has_text_modality=lowerCamelCase ,   hidden_size=37      )




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         self.config_tester.run_common_tests()




      @unittest.skip(reason='BEiT does not use inputs_embeds'      )
      def  __UpperCamelCase							(  self      )							->Dict:



         '''simple docstring'''
         pass




      @require_torch_multi_gpu
      @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'      )
      def  __UpperCamelCase							(  self      )							->List[Any]:



         '''simple docstring'''
         pass




      def  __UpperCamelCase							(  self      )							->Optional[int]:



         '''simple docstring'''
         __a     ,			__a				     =    self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            __a				     =    model_class(lowerCamelCase      )
            self.assertIsInstance(model.get_input_embeddings() ,   (nn.Module)      )
            __a				     =    model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(lowerCamelCase ,   nn.Linear      )      )




      def  __UpperCamelCase							(  self      )							->Any:



         '''simple docstring'''
         __a     ,			__a				     =    self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            __a				     =    model_class(lowerCamelCase      )
            __a				     =    inspect.signature(model.forward      )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            __a				     =    [*signature.parameters.keys()]

            __a				     =    ['pixel_values']
            self.assertListEqual(arg_names[:1] ,   lowerCamelCase      )




      def  __UpperCamelCase							(  self      )							->Dict:



         '''simple docstring'''
         __a				     =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCamelCase      )




      def  __UpperCamelCase							(  self      )							->Dict:



         '''simple docstring'''
         __a				     =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase      )




      def  __UpperCamelCase							(  self      )							->Optional[Any]:



         '''simple docstring'''
         __a				     =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*lowerCamelCase      )




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



         '''simple docstring'''
         __a				     =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase      )




      def  __UpperCamelCase							(  self      )							->Optional[int]:



         '''simple docstring'''
         if not self.model_tester.is_training:
            return

         __a     ,			__a				     =    self.model_tester.prepare_config_and_inputs_for_common()
         __a				     =    True

         for model_class in self.all_model_classes:
            # we don't test BeitForMaskedImageModeling
            if model_class in [*get_values(lowerCamelCase      ), BeitForMaskedImageModeling]:
               continue

            __a				     =    model_class(lowerCamelCase      )
            model.to(lowerCamelCase      )
            model.train()
            __a				     =    self._prepare_for_class(lowerCamelCase ,   lowerCamelCase ,   return_labels=lowerCamelCase      )
            __a				     =    model(**lowerCamelCase      ).loss
            loss.backward()




      def  __UpperCamelCase							(  self      )							->Any:



         '''simple docstring'''
         __a     ,			__a				     =    self.model_tester.prepare_config_and_inputs_for_common()
         if not self.model_tester.is_training:
            return

         __a				     =    False
         __a				     =    True

         for model_class in self.all_model_classes:
            # we don't test BeitForMaskedImageModeling
            if (
                model_class in [*get_values(lowerCamelCase      ), BeitForMaskedImageModeling]
                or not model_class.supports_gradient_checkpointing
            ):
               continue

            __a				     =    model_class(lowerCamelCase      )
            model.gradient_checkpointing_enable()
            model.to(lowerCamelCase      )
            model.train()
            __a				     =    self._prepare_for_class(lowerCamelCase ,   lowerCamelCase ,   return_labels=lowerCamelCase      )
            __a				     =    model(**lowerCamelCase      ).loss
            loss.backward()




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



         '''simple docstring'''
         __a     ,			__a				     =    self.model_tester.prepare_config_and_inputs_for_common()

         __a				     =    _config_zero_init(lowerCamelCase      )
         for model_class in self.all_model_classes:
            __a				     =    model_class(config=lowerCamelCase      )
            for name, param in model.named_parameters():
               # we skip lambda parameters as these require special initial values
               # determined by config.layer_scale_init_value
               if "lambda" in name:
                  continue
               if param.requires_grad:
                  self.assertIn(
                      ((param.data.mean() * 1e9).round() / 1e9).item() ,   [0.0, 1.0] ,   msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" ,   )






      @slow
      def  __UpperCamelCase							(  self      )							->Optional[Any]:



         '''simple docstring'''
         for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a				     =    BeitModel.from_pretrained(lowerCamelCase      )
            self.assertIsNotNone(lowerCamelCase      )







def    __UpperCAmelCase	(				)  ->			List[str]:

   """simple docstring"""
   __a				     =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
   return image



@require_torch
@require_vision
class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):




      @cached_property
      def  __UpperCamelCase							(  self      )							->List[Any]:



         '''simple docstring'''
         return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224'      ) if is_vision_available() else None




      @slow
      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         __a				     =    BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k'      ).to(lowerCamelCase      )

         __a				     =    self.default_image_processor
         __a				     =    prepare_img()
         __a				     =    image_processor(images=lowerCamelCase ,   return_tensors='pt'      ).pixel_values.to(lowerCamelCase      )

         # prepare bool_masked_pos
         __a				     =    torch.ones((1, 196) ,   dtype=torch.bool      ).to(lowerCamelCase      )

         # forward pass
         with torch.no_grad():
            __a				     =    model(pixel_values=lowerCamelCase ,   bool_masked_pos=lowerCamelCase      )
         __a				     =    outputs.logits

         # verify the logits
         __a				     =    torch.Size((1, 196, 8192)      )
         self.assertEqual(logits.shape ,   lowerCamelCase      )

         __a				     =    torch.tensor(
             [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]      ).to(lowerCamelCase      )

         self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,   lowerCamelCase ,   atol=1e-2      )      )




      @slow
      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a				     =    BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224'      ).to(lowerCamelCase      )

         __a				     =    self.default_image_processor
         __a				     =    prepare_img()
         __a				     =    image_processor(images=lowerCamelCase ,   return_tensors='pt'      ).to(lowerCamelCase      )

         # forward pass
         with torch.no_grad():
            __a				     =    model(**lowerCamelCase      )
         __a				     =    outputs.logits

         # verify the logits
         __a				     =    torch.Size((1, 1000)      )
         self.assertEqual(logits.shape ,   lowerCamelCase      )

         __a				     =    torch.tensor([-1.2385, -1.0987, -1.0108]      ).to(lowerCamelCase      )

         self.assertTrue(torch.allclose(logits[0, :3] ,   lowerCamelCase ,   atol=1e-4      )      )

         __a				     =    281
         self.assertEqual(logits.argmax(-1      ).item() ,   lowerCamelCase      )




      @slow
      def  __UpperCamelCase							(  self      )							->Union[str, Any]:



         '''simple docstring'''
         __a				     =    BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k'      ).to(
             lowerCamelCase      )

         __a				     =    self.default_image_processor
         __a				     =    prepare_img()
         __a				     =    image_processor(images=lowerCamelCase ,   return_tensors='pt'      ).to(lowerCamelCase      )

         # forward pass
         with torch.no_grad():
            __a				     =    model(**lowerCamelCase      )
         __a				     =    outputs.logits

         # verify the logits
         __a				     =    torch.Size((1, 2_1841)      )
         self.assertEqual(logits.shape ,   lowerCamelCase      )

         __a				     =    torch.tensor([1.6881, -0.2787, 0.5901]      ).to(lowerCamelCase      )

         self.assertTrue(torch.allclose(logits[0, :3] ,   lowerCamelCase ,   atol=1e-4      )      )

         __a				     =    2396
         self.assertEqual(logits.argmax(-1      ).item() ,   lowerCamelCase      )




      @slow
      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a				     =    BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640'      )
         __a				     =    model.to(lowerCamelCase      )

         __a				     =    BeitImageProcessor(do_resize=lowerCamelCase ,   size=640 ,   do_center_crop=lowerCamelCase      )

         __a				     =    load_dataset('hf-internal-testing/fixtures_ade20k' ,   split='test'      )
         __a				     =    Image.open(ds[0]['file']      )
         __a				     =    image_processor(images=lowerCamelCase ,   return_tensors='pt'      ).to(lowerCamelCase      )

         # forward pass
         with torch.no_grad():
            __a				     =    model(**lowerCamelCase      )
         __a				     =    outputs.logits

         # verify the logits
         __a				     =    torch.Size((1, 150, 160, 160)      )
         self.assertEqual(logits.shape ,   lowerCamelCase      )

         __a				     =    version.parse(PIL.__version__      ) < version.parse('9.0.0'      )

         if is_pillow_less_than_a:
            __a				     =    torch.tensor(
                [
                    [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]],
                    [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]],
                    [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]],
                ] ,   device=lowerCamelCase ,   )
         else:
            __a				     =    torch.tensor(
                [
                    [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]],
                    [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]],
                    [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]],
                ] ,   device=lowerCamelCase ,   )

         self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,   lowerCamelCase ,   atol=1e-4      )      )






      @slow
      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a				     =    BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640'      )
         __a				     =    model.to(lowerCamelCase      )

         __a				     =    BeitImageProcessor(do_resize=lowerCamelCase ,   size=640 ,   do_center_crop=lowerCamelCase      )

         __a				     =    load_dataset('hf-internal-testing/fixtures_ade20k' ,   split='test'      )
         __a				     =    Image.open(ds[0]['file']      )
         __a				     =    image_processor(images=lowerCamelCase ,   return_tensors='pt'      ).to(lowerCamelCase      )

         # forward pass
         with torch.no_grad():
            __a				     =    model(**lowerCamelCase      )

         __a				     =    outputs.logits.detach().cpu()

         __a				     =    image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase ,   target_sizes=[(500, 300)]      )
         __a				     =    torch.Size((500, 300)      )
         self.assertEqual(segmentation[0].shape ,   lowerCamelCase      )

         __a				     =    image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase      )
         __a				     =    torch.Size((160, 160)      )
         self.assertEqual(segmentation[0].shape ,   lowerCamelCase      )







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




      def __init__(  self      )							->Dict:



         '''simple docstring'''
         super().__init__()
         __a				     =    nn.Linear(3 ,   4      )
         __a				     =    nn.BatchNormad(4      )
         __a				     =    nn.Linear(4 ,   5      )






      def  __UpperCamelCase							(  self ,   lowerCamelCase      )							->str:



         '''simple docstring'''
         return self.lineara(self.batchnorm(self.lineara(lowerCamelCase      )      )      )







class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase     ):




      def  __UpperCamelCase							(  self ,   lowerCamelCase ,   *lowerCamelCase ,   **lowerCamelCase      )							->str:



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







class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase     ):




      def  __UpperCamelCase							(  self ,   lowerCamelCase ,   lowerCamelCase      )							->int:



         '''simple docstring'''
         return output + 1







class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):




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



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    ModelHook()

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




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    ModelHook()

         add_hook_to_module(lowerCamelCase ,   lowerCamelCase      )
         add_hook_to_module(lowerCamelCase ,   lowerCamelCase ,   append=lowerCamelCase      )

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




      def  __UpperCamelCase							(  self      )							->Tuple:



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

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

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

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

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




      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    torch.randn(2 ,   3      )
         __a				     =    test_model(lowerCamelCase      )

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

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

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

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




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    torch.randn(2 ,   3      )
         __a				     =    test_model(lowerCamelCase      )

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

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




      @require_multi_gpu
      def  __UpperCamelCase							(  self      )							->Any:



         '''simple docstring'''
         __a				     =    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				     =    torch.randn(2 ,   3      )
         __a				     =    model(lowerCamelCase      )
         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(lowerCamelCase ,   AlignDevicesHook(io_same_device=lowerCamelCase      )      )
         __a				     =    torch.randn(2 ,   3      ).to(0      )
         __a				     =    model(lowerCamelCase      )
         self.assertEqual(output.device ,   torch.device(0      )      )




      def  __UpperCamelCase							(  self      )							->Any:



         '''simple docstring'''
         __a				     =    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				     =    {'execution_device': 0 if torch.cuda.is_available() else 'cpu', 'offload': True}

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

         # 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				     =    torch.device(hook_kwargs['execution_device']      )
         self.assertEqual(model.batchnorm.running_mean.device ,   lowerCamelCase      )

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

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

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

         # 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				     =    torch.randn(2 ,   3      )
         __a				     =    model(lowerCamelCase      )
         self.assertEqual(output.device ,   lowerCamelCase      )

         # 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  __UpperCamelCase							(  self      )							->List[Any]:



         '''simple docstring'''
         __a				     =    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				     =    0 if torch.cuda.is_available() else 'cpu'
         attach_align_device_hook(lowerCamelCase ,   execution_device=lowerCamelCase ,   offload=lowerCamelCase      )

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

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

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

         # 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				     =    torch.randn(2 ,   3      )
         __a				     =    model(lowerCamelCase      )
         self.assertEqual(output.device ,   lowerCamelCase      )

         # Removing hooks loads back the weights in the model.
         remove_hook_from_submodules(lowerCamelCase      )
         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  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         __a				     =    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				     =    0 if torch.cuda.is_available() else 'cpu'
         attach_align_device_hook(
             lowerCamelCase ,   execution_device=lowerCamelCase ,   offload=lowerCamelCase ,   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				     =    torch.device(lowerCamelCase      )
         self.assertEqual(model.batchnorm.running_mean.device ,   lowerCamelCase      )

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

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

         # 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				     =    torch.randn(2 ,   3      )
         __a				     =    model(lowerCamelCase      )
         self.assertEqual(output.device ,   lowerCamelCase      )

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