






'''simple docstring'''



import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


__UpperCamelCase      :       Tuple      			=      logging.get_logger(__name__)

__UpperCamelCase      :       str      			=      {
    """ut/deta""": """https://huggingface.co/ut/deta/resolve/main/config.json""",
}
class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase     ):
      __a  					="deta"
      __a  					={
          "hidden_size": "d_model",
          "num_attention_heads": "encoder_attention_heads",
      }




      def __init__(  self ,   lowerCamelCase=None ,   lowerCamelCase=900 ,   lowerCamelCase=2048 ,   lowerCamelCase=6 ,   lowerCamelCase=2048 ,   lowerCamelCase=8 ,   lowerCamelCase=6 ,   lowerCamelCase=1024 ,   lowerCamelCase=8 ,   lowerCamelCase=0.0 ,   lowerCamelCase=True ,   lowerCamelCase="relu" ,   lowerCamelCase=256 ,   lowerCamelCase=0.1 ,   lowerCamelCase=0.0 ,   lowerCamelCase=0.0 ,   lowerCamelCase=0.02 ,   lowerCamelCase=1.0 ,   lowerCamelCase=True ,   lowerCamelCase=False ,   lowerCamelCase="sine" ,   lowerCamelCase=5 ,   lowerCamelCase=4 ,   lowerCamelCase=4 ,   lowerCamelCase=True ,   lowerCamelCase=300 ,   lowerCamelCase=True ,   lowerCamelCase=True ,   lowerCamelCase=1 ,   lowerCamelCase=5 ,   lowerCamelCase=2 ,   lowerCamelCase=1 ,   lowerCamelCase=1 ,   lowerCamelCase=5 ,   lowerCamelCase=2 ,   lowerCamelCase=0.1 ,   lowerCamelCase=0.25 ,   **lowerCamelCase ,   )							->str:



         '''simple docstring'''
         if backbone_config is None:
            logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'      )
            __a				     =    CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4']      )
         else:
            if isinstance(lowerCamelCase ,   lowerCamelCase      ):
               __a				     =    backbone_config.pop('model_type'      )
               __a				     =    CONFIG_MAPPING[backbone_model_type]
               __a				     =    config_class.from_dict(lowerCamelCase      )

         __a				     =    backbone_config
         __a				     =    num_queries
         __a				     =    max_position_embeddings
         __a				     =    d_model
         __a				     =    encoder_ffn_dim
         __a				     =    encoder_layers
         __a				     =    encoder_attention_heads
         __a				     =    decoder_ffn_dim
         __a				     =    decoder_layers
         __a				     =    decoder_attention_heads
         __a				     =    dropout
         __a				     =    attention_dropout
         __a				     =    activation_dropout
         __a				     =    activation_function
         __a				     =    init_std
         __a				     =    init_xavier_std
         __a				     =    encoder_layerdrop
         __a				     =    auxiliary_loss
         __a				     =    position_embedding_type
         # deformable attributes
         __a				     =    num_feature_levels
         __a				     =    encoder_n_points
         __a				     =    decoder_n_points
         __a				     =    two_stage
         __a				     =    two_stage_num_proposals
         __a				     =    with_box_refine
         __a				     =    assign_first_stage
         if two_stage is True and with_box_refine is False:
            raise ValueError('If two_stage is True, with_box_refine must be True.'      )
         # Hungarian matcher
         __a				     =    class_cost
         __a				     =    bbox_cost
         __a				     =    giou_cost
         # Loss coefficients
         __a				     =    mask_loss_coefficient
         __a				     =    dice_loss_coefficient
         __a				     =    bbox_loss_coefficient
         __a				     =    giou_loss_coefficient
         __a				     =    eos_coefficient
         __a				     =    focal_alpha
         super().__init__(is_encoder_decoder=lowerCamelCase ,   **lowerCamelCase      )




      @property
      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         return self.encoder_attention_heads




      @property
      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         return self.d_model






      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         __a				     =    copy.deepcopy(self.__dict__      )
         __a				     =    self.backbone_config.to_dict()
         __a				     =    self.__class__.model_type
         return output







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