






'''simple docstring'''



from __future__ import annotations

import copy
import tempfile
import unittest

from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available
from transformers.testing_utils import (
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tensorflow_probability,
    require_tf,
    slow,
)

from ..bert.test_modeling_bert import BertModelTester


if is_tf_available():
 from transformers import (
     TFAutoModel,
     TFAutoModelForCausalLM,
     TFAutoModelForMaskedLM,
     TFAutoModelForPreTraining,
     TFAutoModelForQuestionAnswering,
     TFAutoModelForSeqaSeqLM,
     TFAutoModelForSequenceClassification,
     TFAutoModelForTableQuestionAnswering,
     TFAutoModelForTokenClassification,
     TFAutoModelWithLMHead,
     TFBertForMaskedLM,
     TFBertForPreTraining,
     TFBertForQuestionAnswering,
     TFBertForSequenceClassification,
     TFBertModel,
     TFFunnelBaseModel,
     TFFunnelModel,
     TFGPTaLMHeadModel,
     TFRobertaForMaskedLM,
     TFTaForConditionalGeneration,
     TFTapasForQuestionAnswering,
 )
 from transformers.models.auto.modeling_tf_auto import (
     TF_MODEL_FOR_CAUSAL_LM_MAPPING,
     TF_MODEL_FOR_MASKED_LM_MAPPING,
     TF_MODEL_FOR_PRETRAINING_MAPPING,
     TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
     TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
     TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
     TF_MODEL_MAPPING,
 )
 from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
 from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
 from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
 from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST
class 							__SCREAMING_SNAKE_CASE       (							a__     ):
      __a  					="new-model"


if is_tf_available():
 class 							__SCREAMING_SNAKE_CASE       (							a__     ):
       __a  					=NewModelConfig
@require_tf
class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):




      @slow
      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a				     =    'bert-base-cased'
         __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
         self.assertIsNotNone(lowerCamelCase_      )
         self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

         __a				     =    TFAutoModel.from_pretrained(lowerCamelCase_      )
         self.assertIsNotNone(lowerCamelCase_      )
         self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




      @slow
      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a				     =    'bert-base-cased'
         __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
         self.assertIsNotNone(lowerCamelCase_      )
         self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

         __a				     =    TFAutoModelForPreTraining.from_pretrained(lowerCamelCase_      )
         self.assertIsNotNone(lowerCamelCase_      )
         self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




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



         '''simple docstring'''
         for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

            __a				     =    TFAutoModelForCausalLM.from_pretrained(lowerCamelCase_      )
            __a     ,			__a				     =    TFAutoModelForCausalLM.from_pretrained(lowerCamelCase_ ,   output_loading_info=lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




      @slow
      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

            __a				     =    TFAutoModelWithLMHead.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




      @slow
      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

            __a				     =    TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase_      )
            __a     ,			__a				     =    TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase_ ,   output_loading_info=lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




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



         '''simple docstring'''
         for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

            __a				     =    TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase_      )
            __a     ,			__a				     =    TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase_ ,   output_loading_info=lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




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



         '''simple docstring'''
         # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         for model_name in ["bert-base-uncased"]:
            __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

            __a				     =    TFAutoModelForSequenceClassification.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




      @slow
      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         for model_name in ["bert-base-uncased"]:
            __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

            __a				     =    TFAutoModelForQuestionAnswering.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




      @slow
      @require_tensorflow_probability
      def  __UpperCamelCase							(  self      )							->List[str]:



         '''simple docstring'''
         for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
            __a				     =    AutoConfig.from_pretrained(lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

            __a				     =    TFAutoModelForTableQuestionAnswering.from_pretrained(lowerCamelCase_      )
            __a     ,			__a				     =    TFAutoModelForTableQuestionAnswering.from_pretrained(
                lowerCamelCase_ ,   output_loading_info=lowerCamelCase_      )
            self.assertIsNotNone(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    TFAutoModelWithLMHead.from_pretrained(lowerCamelCase_      )
         self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )
         self.assertEqual(model.num_parameters() ,   1_4410      )
         self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase_      ) ,   1_4410      )




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



         '''simple docstring'''
         __a				     =    TFAutoModelWithLMHead.from_pretrained(lowerCamelCase_      )
         self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )
         self.assertEqual(model.num_parameters() ,   1_4410      )
         self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase_      ) ,   1_4410      )




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



         '''simple docstring'''
         # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel
         __a				     =    TFAutoModel.from_pretrained('sgugger/funnel-random-tiny'      )
         self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

         __a				     =    copy.deepcopy(model.config      )
         __a				     =    ['FunnelBaseModel']
         __a				     =    TFAutoModel.from_config(lowerCamelCase_      )
         self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

         with tempfile.TemporaryDirectory() as tmp_dir:
            model.save_pretrained(lowerCamelCase_      )
            __a				     =    TFAutoModel.from_pretrained(lowerCamelCase_      )
            self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )




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



         '''simple docstring'''
         try:
            AutoConfig.register('new-model' ,   lowerCamelCase_      )

            __a				     =    [
                TFAutoModel,
                TFAutoModelForCausalLM,
                TFAutoModelForMaskedLM,
                TFAutoModelForPreTraining,
                TFAutoModelForQuestionAnswering,
                TFAutoModelForSequenceClassification,
                TFAutoModelForTokenClassification,
            ]

            for auto_class in auto_classes:
               with self.subTest(auto_class.__name__      ):
                  # Wrong config class will raise an error
                  with self.assertRaises(lowerCamelCase_      ):
                     auto_class.register(lowerCamelCase_ ,   lowerCamelCase_      )
                  auto_class.register(lowerCamelCase_ ,   lowerCamelCase_      )
                  # Trying to register something existing in the Transformers library will raise an error
                  with self.assertRaises(lowerCamelCase_      ):
                     auto_class.register(lowerCamelCase_ ,   lowerCamelCase_      )

                  # Now that the config is registered, it can be used as any other config with the auto-API
                  __a				     =    BertModelTester(self      ).get_config()
                  __a				     =    NewModelConfig(**tiny_config.to_dict()      )
                  __a				     =    auto_class.from_config(lowerCamelCase_      )
                  self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

                  with tempfile.TemporaryDirectory() as tmp_dir:
                     model.save_pretrained(lowerCamelCase_      )
                     __a				     =    auto_class.from_pretrained(lowerCamelCase_      )
                     self.assertIsInstance(lowerCamelCase_ ,   lowerCamelCase_      )

         finally:
            if "new-model" in CONFIG_MAPPING._extra_content:
               del CONFIG_MAPPING._extra_content["new-model"]
            for mapping in (
                TF_MODEL_MAPPING,
                TF_MODEL_FOR_PRETRAINING_MAPPING,
                TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
                TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
                TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
                TF_MODEL_FOR_CAUSAL_LM_MAPPING,
                TF_MODEL_FOR_MASKED_LM_MAPPING,
            ):
               if NewModelConfig in mapping._extra_content:
                  del mapping._extra_content[NewModelConfig]




      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         with self.assertRaisesRegex(
             lowerCamelCase_ ,   'bert-base is not a local folder and is not a valid model identifier'      ):
            __a				     =    TFAutoModel.from_pretrained('bert-base'      )




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



         '''simple docstring'''
         with self.assertRaisesRegex(
             lowerCamelCase_ ,   r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'      ):
            __a				     =    TFAutoModel.from_pretrained(lowerCamelCase_ ,   revision='aaaaaa'      )




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



         '''simple docstring'''
         with self.assertRaisesRegex(
             lowerCamelCase_ ,   'hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin' ,   ):
            __a				     =    TFAutoModel.from_pretrained('hf-internal-testing/config-no-model'      )




      def  __UpperCamelCase							(  self      )							->List[str]:



         '''simple docstring'''
         with self.assertRaisesRegex(lowerCamelCase_ ,   'Use `from_pt=True` to load this model'      ):
            __a				     =    TFAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only'      )






      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         # Make sure we have cached the model.
         __a				     =    TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert'      )
         with RequestCounter() as counter:
            __a				     =    TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert'      )
            self.assertEqual(counter.get_request_count ,   0      )
            self.assertEqual(counter.head_request_count ,   1      )
            self.assertEqual(counter.other_request_count ,   0      )

         # With a sharded checkpoint
         __a				     =    TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded'      )
         with RequestCounter() as counter:
            __a				     =    TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded'      )
            self.assertEqual(counter.get_request_count ,   0      )
            self.assertEqual(counter.head_request_count ,   1      )
            self.assertEqual(counter.other_request_count ,   0      )














'''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'      )      )