




"""simple docstring"""


import torch
from torch import nn






class  lowercase(					nn.Module			):







 '''simple docstring'''





 def __init__(    self:		Any,				a_:		List[str],				a_:		Union[str, Any],				a_:		int,				a_:		int,				a_:		List[Any]=1,				a_:		Union[str, Any]=False		):




   '''simple docstring'''



   super().__init__()

   _snake_case							:		int								=  n_token
   _snake_case							:		Tuple								=  d_embed
   _snake_case							:		List[str]								=  d_proj

   _snake_case							:		Optional[int]								=  cutoffs + [n_token]
   _snake_case							:		Any								=  [0] + self.cutoffs
   _snake_case							:		Tuple								=  div_val

   _snake_case							:		Optional[int]								=  self.cutoffs[0]
   _snake_case							:		Union[str, Any]								=  len(self.cutoffs		) - 1
   _snake_case							:		Union[str, Any]								=  self.shortlist_size + self.n_clusters

   if self.n_clusters > 0:
     _snake_case							:		List[Any]								=  nn.Parameter(torch.zeros(self.n_clusters,				self.d_embed		)		)
     _snake_case							:		Tuple								=  nn.Parameter(torch.zeros(self.n_clusters		)		)

   _snake_case							:		Any								=  nn.ModuleList()
   _snake_case							:		Optional[Any]								=  nn.ParameterList()

   if div_val == 1:
     for i in range(len(self.cutoffs		)		):
       if d_proj != d_embed:
         self.out_projs.append(nn.Parameter(torch.FloatTensor(a_,				a_		)		)		)
       else:
         self.out_projs.append(a_		)

     self.out_layers.append(nn.Linear(a_,				a_		)		)
   else:
     for i in range(len(self.cutoffs		)		):
       _snake_case							:		List[Any]								=  self.cutoff_ends[i], self.cutoff_ends[i + 1]
       _snake_case							:		Union[str, Any]								=  d_embed // (div_val**i)

       self.out_projs.append(nn.Parameter(torch.FloatTensor(a_,				a_		)		)		)

       self.out_layers.append(nn.Linear(a_,				r_idx - l_idx		)		)

   _snake_case							:		Optional[int]								=  keep_order


 def 			UpperCamelCase_       (    self:		str,				a_:		Union[str, Any],				a_:		Dict,				a_:		int,				a_:		Tuple		):




   '''simple docstring'''



   if proj is None:
     _snake_case							:		List[Any]								=  nn.functional.linear(a_,				a_,				bias=a_		)
   else:
     # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
     _snake_case							:		List[Any]								=  nn.functional.linear(a_,				proj.t().contiguous()		)
     _snake_case							:		Tuple								=  nn.functional.linear(a_,				a_,				bias=a_		)
     # else:
     #     logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
     #     if bias is not None:
     #         logit = logit + bias

   return logit


 def 			UpperCamelCase_       (    self:		Dict,				a_:		Dict,				a_:		str=None,				a_:		Union[str, Any]=False		):




   '''simple docstring'''



   if labels is not None:
     # Shift so that tokens < n predict n
     _snake_case							:		int								=  hidden[..., :-1, :].contiguous()
     _snake_case							:		List[Any]								=  labels[..., 1:].contiguous()
     _snake_case							:		str								=  hidden.view(-1,				hidden.size(-1		)		)
     _snake_case							:		Dict								=  labels.view(-1		)
     if hidden.size(0		) != labels.size(0		):
       raise RuntimeError("""Input and labels should have the same size in the batch dimension."""		)
   else:
     _snake_case							:		int								=  hidden.view(-1,				hidden.size(-1		)		)

   if self.n_clusters == 0:
     _snake_case							:		Tuple								=  self._compute_logit(a_,				self.out_layers[0].weight,				self.out_layers[0].bias,				self.out_projs[0]		)
     if labels is not None:
       _snake_case							:		Dict								=  labels != -100
       _snake_case							:		str								=  torch.zeros_like(a_,				dtype=hidden.dtype,				device=hidden.device		)
       _snake_case							:		str								=  (
           -nn.functional.log_softmax(a_,				dim=-1		)[mask].gather(1,				labels[mask].unsqueeze(1		)		).squeeze(1		)
       )
     else:
       _snake_case							:		Optional[int]								=  nn.functional.log_softmax(a_,				dim=-1		)
   else:
     # construct weights and biases
     _snake_case							:		Optional[int]								=  [], []
     for i in range(len(self.cutoffs		)		):
       if self.div_val == 1:
         _snake_case							:		Optional[int]								=  self.cutoff_ends[i], self.cutoff_ends[i + 1]
         _snake_case							:		List[Any]								=  self.out_layers[0].weight[l_idx:r_idx]
         _snake_case							:		Tuple								=  self.out_layers[0].bias[l_idx:r_idx]
       else:
         _snake_case							:		Optional[int]								=  self.out_layers[i].weight
         _snake_case							:		int								=  self.out_layers[i].bias

       if i == 0:
         _snake_case							:		List[str]								=  torch.cat([weight_i, self.cluster_weight],				dim=0		)
         _snake_case							:		int								=  torch.cat([bias_i, self.cluster_bias],				dim=0		)

       weights.append(a_		)
       biases.append(a_		)

     _snake_case							:		Any								=  weights[0], biases[0], self.out_projs[0]

     _snake_case							:		List[str]								=  self._compute_logit(a_,				a_,				a_,				a_		)
     _snake_case							:		Union[str, Any]								=  nn.functional.log_softmax(a_,				dim=1		)

     if labels is None:
       _snake_case							:		Tuple								=  hidden.new_empty((head_logit.size(0		), self.n_token)		)
     else:
       _snake_case							:		Dict								=  torch.zeros_like(a_,				dtype=hidden.dtype,				device=hidden.device		)

     _snake_case							:		Union[str, Any]								=  0
     _snake_case							:		Optional[Any]								=  [0] + self.cutoffs
     for i in range(len(a_		) - 1		):
       _snake_case							:		Dict								=  cutoff_values[i], cutoff_values[i + 1]

       if labels is not None:
         _snake_case							:		Dict								=  (labels >= l_idx) & (labels < r_idx)
         _snake_case							:		int								=  mask_i.nonzero().squeeze()

         if indices_i.numel() == 0:
           continue

         _snake_case							:		List[str]								=  labels.index_select(0,				a_		) - l_idx
         _snake_case							:		List[str]								=  head_logprob.index_select(0,				a_		)
         _snake_case							:		List[str]								=  hidden.index_select(0,				a_		)
       else:
         _snake_case							:		List[str]								=  hidden

       if i == 0:
         if labels is not None:
           _snake_case							:		Dict								=  head_logprob_i.gather(1,				target_i[:, None]		).squeeze(1		)
         else:
           _snake_case							:		Optional[Any]								=  head_logprob[:, : self.cutoffs[0]]
       else:
         _snake_case							:		Dict								=  weights[i], biases[i], self.out_projs[i]

         _snake_case							:		int								=  self._compute_logit(a_,				a_,				a_,				a_		)
         _snake_case							:		int								=  nn.functional.log_softmax(a_,				dim=1		)
         _snake_case							:		Dict								=  self.cutoffs[0] + i - 1  # No probability for the head cluster
         if labels is not None:
           _snake_case							:		Dict								=  head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
               1,				target_i[:, None]		).squeeze(1		)
         else:
           _snake_case							:		Optional[Any]								=  head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
           _snake_case							:		Any								=  logprob_i

       if labels is not None:
         if (hasattr(self,				"""keep_order"""		) and self.keep_order) or keep_order:
           out.index_copy_(0,				a_,				-logprob_i		)
         else:
           out[offset : offset + logprob_i.size(0		)].copy_(-logprob_i		)
         offset += logprob_i.size(0		)

   return out


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		Optional[int]		):




   '''simple docstring'''



   if self.n_clusters == 0:
     _snake_case							:		Optional[int]								=  self._compute_logit(a_,				self.out_layers[0].weight,				self.out_layers[0].bias,				self.out_projs[0]		)
     return nn.functional.log_softmax(a_,				dim=-1		)
   else:
     # construct weights and biases
     _snake_case							:		List[Any]								=  [], []
     for i in range(len(self.cutoffs		)		):
       if self.div_val == 1:
         _snake_case							:		Optional[Any]								=  self.cutoff_ends[i], self.cutoff_ends[i + 1]
         _snake_case							:		Optional[int]								=  self.out_layers[0].weight[l_idx:r_idx]
         _snake_case							:		str								=  self.out_layers[0].bias[l_idx:r_idx]
       else:
         _snake_case							:		List[Any]								=  self.out_layers[i].weight
         _snake_case							:		Union[str, Any]								=  self.out_layers[i].bias

       if i == 0:
         _snake_case							:		int								=  torch.cat([weight_i, self.cluster_weight],				dim=0		)
         _snake_case							:		Dict								=  torch.cat([bias_i, self.cluster_bias],				dim=0		)

       weights.append(a_		)
       biases.append(a_		)

     _snake_case							:		int								=  weights[0], biases[0], self.out_projs[0]
     _snake_case							:		List[Any]								=  self._compute_logit(a_,				a_,				a_,				a_		)

     _snake_case							:		List[Any]								=  hidden.new_empty((head_logit.size(0		), self.n_token)		)
     _snake_case							:		int								=  nn.functional.log_softmax(a_,				dim=1		)

     _snake_case							:		List[Any]								=  [0] + self.cutoffs
     for i in range(len(a_		) - 1		):
       _snake_case							:		List[str]								=  cutoff_values[i], cutoff_values[i + 1]

       if i == 0:
         _snake_case							:		List[str]								=  head_logprob[:, : self.cutoffs[0]]
       else:
         _snake_case							:		List[Any]								=  weights[i], biases[i], self.out_projs[i]

         _snake_case							:		Optional[int]								=  self._compute_logit(a_,				a_,				a_,				a_		)
         _snake_case							:		Any								=  nn.functional.log_softmax(a_,				dim=1		)

         _snake_case							:		Dict								=  head_logprob[:, -i] + tail_logprob_i
         _snake_case							:		Any								=  logprob_i

     return out








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







 '''simple docstring'''





 def __init__(    self:		Optional[int]		):




   '''simple docstring'''



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


 def 			UpperCamelCase_       (    self:		Any,				a_:		Union[str, Any]		):




   '''simple docstring'''



   return self.lineara(self.batchnorm(self.lineara(a_		)		)		)







class  lowercase(					__a			):







 '''simple docstring'''





 def 			UpperCamelCase_       (    self:		Any,				a_:		int,				*a_:		Dict,				**a_:		Dict		):




   '''simple docstring'''



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







class  lowercase(					__a			):







 '''simple docstring'''





 def 			UpperCamelCase_       (    self:		str,				a_:		Tuple,				a_:		Union[str, Any]		):




   '''simple docstring'''



   return output + 1







class  lowercase(					unittest.TestCase			):







 '''simple docstring'''





 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''simple docstring'''



   _snake_case							:		Tuple								=  ModelForTest()
   _snake_case							:		List[str]								=  ModelHook()

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


 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		Dict								=  ModelForTest()
   _snake_case							:		List[Any]								=  ModelHook()

   add_hook_to_module(a_,				a_		)
   add_hook_to_module(a_,				a_,				append=a_		)

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


 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



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

   _snake_case							:		Any								=  PreForwardHook()
   add_hook_to_module(a_,				a_		)
   _snake_case							:		List[Any]								=  test_model(a_		)
   self.assertTrue(torch.allclose(a_,				a_,				atol=1E-5		)		)

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

   # You need to use the sequential hook to chain two or more hooks
   _snake_case							:		str								=  SequentialHook(PreForwardHook(),				PreForwardHook()		)
   add_hook_to_module(a_,				a_		)

   _snake_case							:		str								=  test_model(a_		)
   assert torch.allclose(a_,				a_,				atol=1E-5		)


 def 			UpperCamelCase_       (    self:		Optional[int]		):




   '''simple docstring'''



   _snake_case							:		Optional[int]								=  ModelForTest()
   _snake_case							:		List[Any]								=  torch.randn(2,				3		)
   _snake_case							:		List[str]								=  test_model(a_		)

   _snake_case							:		List[Any]								=  PostForwardHook()
   add_hook_to_module(a_,				a_		)
   _snake_case							:		Union[str, Any]								=  test_model(a_		)
   self.assertTrue(torch.allclose(a_,				output + 1,				atol=1E-5		)		)

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

   # You need to use the sequential hook to chain two or more hooks
   _snake_case							:		Dict								=  SequentialHook(PostForwardHook(),				PostForwardHook()		)
   add_hook_to_module(a_,				a_		)

   _snake_case							:		List[str]								=  test_model(a_		)
   assert torch.allclose(a_,				output + 2,				atol=1E-5		)


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		str								=  ModelForTest()
   _snake_case							:		Any								=  torch.randn(2,				3		)
   _snake_case							:		List[str]								=  test_model(a_		)

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

   _snake_case							:		Union[str, Any]								=  True
   _snake_case							:		Dict								=  test_model(a_		)
   self.assertFalse(outputa.requires_grad		)


 @require_multi_gpu
 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		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
   add_hook_to_module(model.lineara,				AlignDevicesHook(execution_device=0		)		)
   add_hook_to_module(model.batchnorm,				AlignDevicesHook(execution_device=0		)		)
   add_hook_to_module(model.lineara,				AlignDevicesHook(execution_device=1		)		)

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

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


 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''simple docstring'''



   _snake_case							:		int								=  ModelForTest()

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

   # This will move each submodule on different devices
   _snake_case							:		Optional[int]								=  {"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True}

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

   # Parameters have been offloaded, so on the meta device
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   # Buffers are not included in the offload by default, so are on the execution device
   _snake_case							:		Union[str, Any]								=  torch.device(hook_kwargs["""execution_device"""]		)
   self.assertEqual(model.batchnorm.running_mean.device,				a_		)

   _snake_case							:		str								=  torch.randn(2,				3		)
   _snake_case							:		Optional[int]								=  model(a_		)
   self.assertEqual(output.device,				a_		)

   # Removing hooks loads back the weights in the model.
   remove_hook_from_module(model.lineara		)
   remove_hook_from_module(model.batchnorm		)
   remove_hook_from_module(model.lineara		)
   self.assertEqual(model.lineara.weight.device,				torch.device("""cpu"""		)		)
   self.assertEqual(model.batchnorm.weight.device,				torch.device("""cpu"""		)		)
   self.assertEqual(model.lineara.weight.device,				torch.device("""cpu"""		)		)

   # Now test with buffers included in the offload
   _snake_case							:		Any								=  {
       """execution_device""": 0 if torch.cuda.is_available() else """cpu""",
       """offload""": True,
       """offload_buffers""": True,
   }

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

   # Parameters have been offloaded, so on the meta device, buffers included
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.running_mean.device,				torch.device("""meta"""		)		)

   _snake_case							:		List[Any]								=  torch.randn(2,				3		)
   _snake_case							:		Any								=  model(a_		)
   self.assertEqual(output.device,				a_		)

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




   '''simple docstring'''



   _snake_case							:		Any								=  ModelForTest()

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

   # This will move each submodule on different devices
   _snake_case							:		Tuple								=  0 if torch.cuda.is_available() else """cpu"""
   attach_align_device_hook(a_,				execution_device=a_,				offload=a_		)

   # Parameters have been offloaded, so on the meta device
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   # Buffers are not included in the offload by default, so are on the execution device
   _snake_case							:		Optional[int]								=  torch.device(a_		)
   self.assertEqual(model.batchnorm.running_mean.device,				a_		)

   _snake_case							:		List[Any]								=  torch.randn(2,				3		)
   _snake_case							:		List[Any]								=  model(a_		)
   self.assertEqual(output.device,				a_		)

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

   # Parameters have been offloaded, so on the meta device, buffers included
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.running_mean.device,				torch.device("""meta"""		)		)

   _snake_case							:		str								=  torch.randn(2,				3		)
   _snake_case							:		List[Any]								=  model(a_		)
   self.assertEqual(output.device,				a_		)

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




   '''simple docstring'''



   _snake_case							:		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
   _snake_case							:		Any								=  0 if torch.cuda.is_available() else """cpu"""
   attach_align_device_hook(
       a_,				execution_device=a_,				offload=a_,				weights_map=model.state_dict()		)

   # Parameters have been offloaded, so on the meta device
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   # Buffers are not included in the offload by default, so are on the execution device
   _snake_case							:		Optional[Any]								=  torch.device(a_		)
   self.assertEqual(model.batchnorm.running_mean.device,				a_		)

   _snake_case							:		int								=  torch.randn(2,				3		)
   _snake_case							:		str								=  model(a_		)
   self.assertEqual(output.device,				a_		)

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

   # Parameters have been offloaded, so on the meta device, buffers included
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.lineara.weight.device,				torch.device("""meta"""		)		)
   self.assertEqual(model.batchnorm.running_mean.device,				torch.device("""meta"""		)		)

   _snake_case							:		Optional[int]								=  torch.randn(2,				3		)
   _snake_case							:		Any								=  model(a_		)
   self.assertEqual(output.device,				a_		)

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


