


import unittest

import numpy as np

from transformers import RobertaPreLayerNormConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
       import jax.numpy as jnp

       from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import (
           FlaxRobertaPreLayerNormForCausalLM,
           FlaxRobertaPreLayerNormForMaskedLM,
           FlaxRobertaPreLayerNormForMultipleChoice,
           FlaxRobertaPreLayerNormForQuestionAnswering,
           FlaxRobertaPreLayerNormForSequenceClassification,
           FlaxRobertaPreLayerNormForTokenClassification,
           FlaxRobertaPreLayerNormModel,
       )

class       __magic_name__	(     unittest.TestCase):

     '''simple docstring'''





     def __init__(      self							:     List[str]							,	lowerCamelCase__							:     Any							,	lowerCamelCase__							:     Dict=13							,	lowerCamelCase__							:     List[Any]=7							,	lowerCamelCase__							:     str=True							,	lowerCamelCase__							:     Dict=True							,	lowerCamelCase__							:     int=True							,	lowerCamelCase__							:     Optional[Any]=True							,	lowerCamelCase__							:     Tuple=99							,	lowerCamelCase__							:     Optional[int]=32							,	lowerCamelCase__							:     str=5							,	lowerCamelCase__							:     Dict=4							,	lowerCamelCase__							:     str=37							,	lowerCamelCase__							:     Dict="gelu"							,	lowerCamelCase__							:     Optional[int]=0.1							,	lowerCamelCase__							:     Tuple=0.1							,	lowerCamelCase__							:     Dict=512							,	lowerCamelCase__							:     Tuple=16							,	lowerCamelCase__							:     str=2							,	lowerCamelCase__							:     List[Any]=0.02							,	lowerCamelCase__							:     Union[str, Any]=4							,	)  ->      Tuple:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[int]          =   parent
      UpperCamelCase__					:    Optional[int]          =   batch_size
      UpperCamelCase__					:    Union[str, Any]          =   seq_length
      UpperCamelCase__					:    int          =   is_training
      UpperCamelCase__					:    Optional[Any]          =   use_attention_mask
      UpperCamelCase__					:    str          =   use_token_type_ids
      UpperCamelCase__					:    int          =   use_labels
      UpperCamelCase__					:    List[str]          =   vocab_size
      UpperCamelCase__					:    List[Any]          =   hidden_size
      UpperCamelCase__					:    Dict          =   num_hidden_layers
      UpperCamelCase__					:    List[Any]          =   num_attention_heads
      UpperCamelCase__					:    Optional[Any]          =   intermediate_size
      UpperCamelCase__					:    Optional[int]          =   hidden_act
      UpperCamelCase__					:    int          =   hidden_dropout_prob
      UpperCamelCase__					:    Union[str, Any]          =   attention_probs_dropout_prob
      UpperCamelCase__					:    Union[str, Any]          =   max_position_embeddings
      UpperCamelCase__					:    Optional[Any]          =   type_vocab_size
      UpperCamelCase__					:    Optional[Any]          =   type_sequence_label_size
      UpperCamelCase__					:    List[Any]          =   initializer_range
      UpperCamelCase__					:    str          =   num_choices


     def      UpperCAmelCase__	(      self							:     Dict			)  ->      Tuple:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[int]          =   ids_tensor([self.batch_size, self.seq_length]							,	self.vocab_size			)

      UpperCamelCase__					:    Tuple          =   None
      if self.use_attention_mask:
       UpperCamelCase__					:    Optional[int]          =   random_attention_mask([self.batch_size, self.seq_length]			)

      UpperCamelCase__					:    List[Any]          =   None
      if self.use_token_type_ids:
       UpperCamelCase__					:    Tuple          =   ids_tensor([self.batch_size, self.seq_length]							,	self.type_vocab_size			)

      UpperCamelCase__					:    Union[str, Any]          =   RobertaPreLayerNormConfig(
          vocab_size=self.vocab_size							,	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							,	max_position_embeddings=self.max_position_embeddings							,	type_vocab_size=self.type_vocab_size							,	is_decoder=lowerCamelCase__							,	initializer_range=self.initializer_range							,	)

      return config, input_ids, token_type_ids, attention_mask


     def      UpperCAmelCase__	(      self							:     List[Any]			)  ->      Tuple:





      '''simple docstring'''






      UpperCamelCase__					:    Any          =   self.prepare_config_and_inputs()
      UpperCamelCase__					:    Tuple          =   config_and_inputs
      UpperCamelCase__					:    List[str]          =   {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
      return config, inputs_dict


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





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   self.prepare_config_and_inputs()
      UpperCamelCase__					:    Union[str, Any]          =   config_and_inputs

      UpperCamelCase__					:    int          =   True
      UpperCamelCase__					:    List[Any]          =   floats_tensor([self.batch_size, self.seq_length, self.hidden_size]			)
      UpperCamelCase__					:    Any          =   ids_tensor([self.batch_size, self.seq_length]							,	vocab_size=2			)

      return (
          config,
          input_ids,
          token_type_ids,
          encoder_hidden_states,
          encoder_attention_mask,
      )



@require_flax
# Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40
class       __magic_name__	(     __lowerCAmelCase					,				unittest.TestCase):

     '''simple docstring'''





     A:		List[Any]			=      True

     A:		Optional[Any]			=      (
         (
             FlaxRobertaPreLayerNormModel,
             FlaxRobertaPreLayerNormForCausalLM,
             FlaxRobertaPreLayerNormForMaskedLM,
             FlaxRobertaPreLayerNormForSequenceClassification,
             FlaxRobertaPreLayerNormForTokenClassification,
             FlaxRobertaPreLayerNormForMultipleChoice,
             FlaxRobertaPreLayerNormForQuestionAnswering,
         )
         if is_flax_available()
         else ()
     )


     def      UpperCAmelCase__	(      self							:     int			)  ->      Any:





      '''simple docstring'''






      UpperCamelCase__					:    Any          =   FlaxRobertaPreLayerNormModelTester(self			)


     @slow
     def      UpperCAmelCase__	(      self							:     int			)  ->      List[str]:





      '''simple docstring'''






      for model_class_name in self.all_model_classes:
       UpperCamelCase__					:    Optional[int]          =   model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''							,	from_pt=lowerCamelCase__			)
       UpperCamelCase__					:    Dict          =   model(np.ones((1, 1)			)			)
       self.assertIsNotNone(lowerCamelCase__			)



@require_flax
class       __magic_name__	(     unittest.TestCase):

     '''simple docstring'''





     @slow
     def      UpperCAmelCase__	(      self							:     str			)  ->      str:





      '''simple docstring'''






      UpperCamelCase__					:    Union[str, Any]          =   FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''							,	from_pt=lowerCamelCase__			)

      UpperCamelCase__					:    Optional[Any]          =   np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]							,	dtype=jnp.intaa			)
      UpperCamelCase__					:    List[str]          =   model(lowerCamelCase__			)[0]
      UpperCamelCase__					:    int          =   [1, 11, 50265]
      self.assertEqual(list(output.shape			)							,	lowerCamelCase__			)
      # compare the actual values for a slice.
      UpperCamelCase__					:    Union[str, Any]          =   np.array(
          [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]]							,	dtype=np.floataa			)
      self.assertTrue(np.allclose(output[:, :3, :3]							,	lowerCamelCase__							,	atol=1E-4			)			)


     @slow
     def      UpperCAmelCase__	(      self							:     Optional[Any]			)  ->      List[str]:





      '''simple docstring'''






      UpperCamelCase__					:    Union[str, Any]          =   FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''							,	from_pt=lowerCamelCase__			)

      UpperCamelCase__					:    Dict          =   np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]							,	dtype=jnp.intaa			)
      UpperCamelCase__					:    str          =   model(lowerCamelCase__			)[0]
      # compare the actual values for a slice.
      UpperCamelCase__					:    Dict          =   np.array(
          [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]]							,	dtype=np.floataa			)
      self.assertTrue(np.allclose(output[:, :3, :3]							,	lowerCamelCase__							,	atol=1E-4			)			)






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


     def __init__(      self							:     Dict			)  ->      str:





      '''simple docstring'''






      super().__init__()
      UpperCamelCase__					:    int          =   nn.Linear(3							,	4			)
      UpperCamelCase__					:    str          =   nn.BatchNormad(4			)
      UpperCamelCase__					:    List[str]          =   nn.Linear(4							,	5			)


     def      UpperCAmelCase__	(      self							:     int							,	lowerCamelCase__							:     Dict			)  ->      Tuple:





      '''simple docstring'''






      return self.lineara(self.batchnorm(self.lineara(lowerCamelCase__			)			)			)



class       __magic_name__	(     __lowerCAmelCase):


     def      UpperCAmelCase__	(      self							:     Union[str, Any]							,	lowerCamelCase__							:     Any							,	*lowerCamelCase__							:     int							,	**lowerCamelCase__							:     List[str]			)  ->      Any:





      '''simple docstring'''






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



class       __magic_name__	(     __lowerCAmelCase):


     def      UpperCAmelCase__	(      self							:     Any							,	lowerCamelCase__							:     Any							,	lowerCamelCase__							:     Any			)  ->      Any:





      '''simple docstring'''






      return output + 1



class       __magic_name__	(     unittest.TestCase):


     def      UpperCAmelCase__	(      self							:     Tuple			)  ->      Tuple:





      '''simple docstring'''






      UpperCamelCase__					:    Tuple          =   ModelForTest()
      UpperCamelCase__					:    Union[str, Any]          =   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							:     Dict			)  ->      str:





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   ModelForTest()
      UpperCamelCase__					:    List[str]          =   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							:     List[str]			)  ->      int:





      '''simple docstring'''






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

      UpperCamelCase__					:    Optional[int]          =   PreForwardHook()
      add_hook_to_module(lowerCamelCase__							,	lowerCamelCase__			)
      UpperCamelCase__					:    List[Any]          =   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
      UpperCamelCase__					:    Optional[Any]          =   PreForwardHook()
      add_hook_to_module(lowerCamelCase__							,	lowerCamelCase__			)
      UpperCamelCase__					:    List[str]          =   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
      UpperCamelCase__					:    Tuple          =   SequentialHook(PreForwardHook()							,	PreForwardHook()			)
      add_hook_to_module(lowerCamelCase__							,	lowerCamelCase__			)

      UpperCamelCase__					:    Any          =   test_model(lowerCamelCase__			)
      assert torch.allclose(lowerCamelCase__							,	lowerCamelCase__							,	atol=1E-5			)


     def      UpperCAmelCase__	(      self							:     List[Any]			)  ->      Optional[int]:





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   ModelForTest()
      UpperCamelCase__					:    str          =   torch.randn(2							,	3			)
      UpperCamelCase__					:    Any          =   test_model(lowerCamelCase__			)

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

      UpperCamelCase__					:    Tuple          =   test_model(lowerCamelCase__			)
      assert torch.allclose(lowerCamelCase__							,	output + 2							,	atol=1E-5			)


     def      UpperCAmelCase__	(      self							:     List[Any]			)  ->      Dict:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   ModelForTest()
      UpperCamelCase__					:    Tuple          =   torch.randn(2							,	3			)
      UpperCamelCase__					:    Tuple          =   test_model(lowerCamelCase__			)

      UpperCamelCase__					:    Union[str, Any]          =   PostForwardHook()
      add_hook_to_module(lowerCamelCase__							,	lowerCamelCase__			)
      UpperCamelCase__					:    Any          =   test_model(lowerCamelCase__			)
      self.assertTrue(torch.allclose(lowerCamelCase__							,	output + 1			)			)
      self.assertTrue(outputa.requires_grad			)

      UpperCamelCase__					:    Optional[int]          =   True
      UpperCamelCase__					:    Optional[int]          =   test_model(lowerCamelCase__			)
      self.assertFalse(outputa.requires_grad			)


     @require_multi_gpu
     def      UpperCAmelCase__	(      self							:     Any			)  ->      Dict:





      '''simple docstring'''






      UpperCamelCase__					:    int          =   ModelForTest()
      # Everything is on CPU
      self.assertEqual(model.lineara.weight.device							,	torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device							,	torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device							,	torch.device('''cpu'''			)			)

      # This will move each submodule on different devices
      add_hook_to_module(model.lineara							,	AlignDevicesHook(execution_device=0			)			)
      add_hook_to_module(model.batchnorm							,	AlignDevicesHook(execution_device=0			)			)
      add_hook_to_module(model.lineara							,	AlignDevicesHook(execution_device=1			)			)

      self.assertEqual(model.lineara.weight.device							,	torch.device(0			)			)
      self.assertEqual(model.batchnorm.weight.device							,	torch.device(0			)			)
      self.assertEqual(model.batchnorm.running_mean.device							,	torch.device(0			)			)
      self.assertEqual(model.lineara.weight.device							,	torch.device(1			)			)

      # We can still make a forward pass. The input does not need to be on any particular device
      UpperCamelCase__					:    Tuple          =   torch.randn(2							,	3			)
      UpperCamelCase__					:    str          =   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__			)			)
      UpperCamelCase__					:    Tuple          =   torch.randn(2							,	3			).to(0			)
      UpperCamelCase__					:    Optional[int]          =   model(lowerCamelCase__			)
      self.assertEqual(output.device							,	torch.device(0			)			)


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





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   ModelForTest()

      # Everything is on CPU
      self.assertEqual(model.lineara.weight.device							,	torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device							,	torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device							,	torch.device('''cpu'''			)			)

      # This will move each submodule on different devices
      UpperCamelCase__					:    int          =   {'''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
      UpperCamelCase__					:    int          =   torch.device(hook_kwargs['''execution_device''']			)
      self.assertEqual(model.batchnorm.running_mean.device							,	lowerCamelCase__			)

      UpperCamelCase__					:    Dict          =   torch.randn(2							,	3			)
      UpperCamelCase__					:    List[str]          =   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
      UpperCamelCase__					:    Optional[Any]          =   {
          '''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'''			)			)

      UpperCamelCase__					:    List[Any]          =   torch.randn(2							,	3			)
      UpperCamelCase__					:    str          =   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							:     str			)  ->      Optional[int]:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[int]          =   ModelForTest()

      # Everything is on CPU
      self.assertEqual(model.lineara.weight.device							,	torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device							,	torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device							,	torch.device('''cpu'''			)			)

      # This will move each submodule on different devices
      UpperCamelCase__					:    Any          =   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
      UpperCamelCase__					:    str          =   torch.device(lowerCamelCase__			)
      self.assertEqual(model.batchnorm.running_mean.device							,	lowerCamelCase__			)

      UpperCamelCase__					:    int          =   torch.randn(2							,	3			)
      UpperCamelCase__					:    Tuple          =   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'''			)			)

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





      '''simple docstring'''






      UpperCamelCase__					:    List[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
      UpperCamelCase__					:    List[str]          =   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
      UpperCamelCase__					:    List[str]          =   torch.device(lowerCamelCase__			)
      self.assertEqual(model.batchnorm.running_mean.device							,	lowerCamelCase__			)

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

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


