





import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
       import bitsandbytes as bnb
       import torch
       import torch.nn as nn

       from ..pytorch_utils import ConvaD

if is_accelerate_available():
       from accelerate import init_empty_weights
       from accelerate.utils import find_tied_parameters

lowercase    : Optional[Any]    	=  logging.get_logger(__name__)


def     SCREAMING_SNAKE_CASE			(      lowerCAmelCase    ,       lowerCAmelCase    ,       lowerCAmelCase    ,       lowerCAmelCase=None    ,       lowerCAmelCase=None					):
       # Recurse if needed
       if "." in tensor_name:
              _UpperCamelCase              =						tensor_name.split('''.'''					)
              for split in splits[:-1]:
                     _UpperCamelCase              =						getattr(lowerCAmelCase    ,       lowerCAmelCase					)
                     if new_module is None:
                            raise ValueError(f'''{module} has no attribute {split}.'''					)
                     _UpperCamelCase              =						new_module
              _UpperCamelCase              =						splits[-1]

       if tensor_name not in module._parameters and tensor_name not in module._buffers:
              raise ValueError(f'''{module} does not have a parameter or a buffer named {tensor_name}.'''					)
       _UpperCamelCase              =						tensor_name in module._buffers
       _UpperCamelCase              =						getattr(lowerCAmelCase    ,       lowerCAmelCase					)

       if old_value.device == torch.device('''meta'''					) and device not in ["meta", torch.device('''meta'''					)] and value is None:
              raise ValueError(f'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.'''					)

       _UpperCamelCase              =						False
       _UpperCamelCase              =						False
       if is_buffer or not is_bitsandbytes_available():
              _UpperCamelCase              =						False
              _UpperCamelCase              =						False
       else:
              _UpperCamelCase              =						hasattr(bnb.nn    ,       '''Params4bit'''					) and isinstance(module._parameters[tensor_name]    ,       bnb.nn.Paramsabit					)
              _UpperCamelCase              =						isinstance(module._parameters[tensor_name]    ,       bnb.nn.IntaParams					)

       if is_abit or is_abit:
              _UpperCamelCase              =						module._parameters[tensor_name]
              if param.device.type != "cuda":
                     if value is None:
                            _UpperCamelCase              =						old_value.to(lowerCAmelCase					)
                     elif isinstance(lowerCAmelCase    ,       torch.Tensor					):
                            _UpperCamelCase              =						value.to('''cpu'''					)
                            if value.dtype == torch.inta:
                                   _UpperCamelCase              =						version.parse(importlib.metadata.version('''bitsandbytes'''					)					) > version.parse(
                                       '''0.37.2'''					)
                                   if not is_abit_serializable:
                                          raise ValueError(
                                              '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
                                              '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'''					)
                     else:
                            _UpperCamelCase              =						torch.tensor(lowerCAmelCase    ,       device='''cpu'''					)

                     # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
                     # Since weights are saved in the correct "orientation", we skip transposing when loading.
                     if issubclass(module.source_cls    ,       lowerCAmelCase					) and fpaa_statistics is None:
                            _UpperCamelCase              =						new_value.T

                     _UpperCamelCase              =						old_value.__dict__
                     if is_abit:
                            _UpperCamelCase              =						bnb.nn.IntaParams(lowerCAmelCase    ,       requires_grad=lowerCAmelCase    ,       **lowerCAmelCase					).to(lowerCAmelCase					)
                     elif is_abit:
                            _UpperCamelCase              =						bnb.nn.Paramsabit(lowerCAmelCase    ,       requires_grad=lowerCAmelCase    ,       **lowerCAmelCase					).to(lowerCAmelCase					)

                     _UpperCamelCase              =						new_value
                     if fpaa_statistics is not None:
                            setattr(module.weight    ,       '''SCB'''    ,       fpaa_statistics.to(lowerCAmelCase					)					)

       else:
              if value is None:
                     _UpperCamelCase              =						old_value.to(lowerCAmelCase					)
              elif isinstance(lowerCAmelCase    ,       torch.Tensor					):
                     _UpperCamelCase              =						value.to(lowerCAmelCase					)
              else:
                     _UpperCamelCase              =						torch.tensor(lowerCAmelCase    ,       device=lowerCAmelCase					)

              if is_buffer:
                     _UpperCamelCase              =						new_value
              else:
                     _UpperCamelCase              =						nn.Parameter(lowerCAmelCase    ,       requires_grad=old_value.requires_grad					)
                     _UpperCamelCase              =						new_value


def     SCREAMING_SNAKE_CASE			(      lowerCAmelCase    ,       lowerCAmelCase=None    ,       lowerCAmelCase=None    ,       lowerCAmelCase=None    ,       lowerCAmelCase=False					):
       for name, module in model.named_children():
              if current_key_name is None:
                     _UpperCamelCase              =						[]
              current_key_name.append(lowerCAmelCase					)

              if (isinstance(lowerCAmelCase    ,       nn.Linear					) or isinstance(lowerCAmelCase    ,       lowerCAmelCase					)) and name not in modules_to_not_convert:
                     # Check if the current key is not in the `modules_to_not_convert`
                     if not any(key in '''.'''.join(lowerCAmelCase					) for key in modules_to_not_convert					):
                            with init_empty_weights():
                                   if isinstance(lowerCAmelCase    ,       lowerCAmelCase					):
                                          _UpperCamelCase       ,		_UpperCamelCase              =						module.weight.shape
                                   else:
                                          _UpperCamelCase              =						module.in_features
                                          _UpperCamelCase              =						module.out_features

                                   if quantization_config.quantization_method() == "llm_int8":
                                          _UpperCamelCase              =						bnb.nn.LinearabitLt(
                                              lowerCAmelCase    ,       lowerCAmelCase    ,       module.bias is not None    ,       has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight    ,       threshold=quantization_config.llm_inta_threshold    ,       )
                                          _UpperCamelCase              =						True
                                   else:
                                          if (
                                              quantization_config.llm_inta_skip_modules is not None
                                              and name in quantization_config.llm_inta_skip_modules
                                          ):
                                                 pass
                                          else:
                                                 _UpperCamelCase              =						bnb.nn.Linearabit(
                                                     lowerCAmelCase    ,       lowerCAmelCase    ,       module.bias is not None    ,       quantization_config.bnb_abit_compute_dtype    ,       compress_statistics=quantization_config.bnb_abit_use_double_quant    ,       quant_type=quantization_config.bnb_abit_quant_type    ,       )
                                                 _UpperCamelCase              =						True
                    # Store the module class in case we need to transpose the weight later
                                   _UpperCamelCase              =						type(lowerCAmelCase					)
                                   # Force requires grad to False to avoid unexpected errors
                                   model._modules[name].requires_grad_(lowerCAmelCase					)
              if len(list(module.children()					)					) > 0:
                     _UpperCamelCase       ,		_UpperCamelCase              =						_replace_with_bnb_linear(
                         lowerCAmelCase    ,       lowerCAmelCase    ,       lowerCAmelCase    ,       lowerCAmelCase    ,       has_been_replaced=lowerCAmelCase    ,       )
              # Remove the last key for recursion
              current_key_name.pop(-1					)
       return model, has_been_replaced


def     SCREAMING_SNAKE_CASE			(      lowerCAmelCase    ,       lowerCAmelCase=None    ,       lowerCAmelCase=None    ,       lowerCAmelCase=None					):
       _UpperCamelCase              =						['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
       _UpperCamelCase       ,		_UpperCamelCase              =						_replace_with_bnb_linear(
           lowerCAmelCase    ,       lowerCAmelCase    ,       lowerCAmelCase    ,       lowerCAmelCase					)

       if not has_been_replaced:
              logger.warning(
                  '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
                  ''' Please double check your model architecture, or submit an issue on github if you think this is'''
                  ''' a bug.'''					)

       return model


def     SCREAMING_SNAKE_CASE			(      *lowerCAmelCase    ,       **lowerCAmelCase					):
       warnings.warn(
           '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead'''    ,       lowerCAmelCase    ,       )
       return replace_with_bnb_linear(*lowerCAmelCase    ,       **lowerCAmelCase					)


def     SCREAMING_SNAKE_CASE			(      *lowerCAmelCase    ,       **lowerCAmelCase					):
       warnings.warn(
           '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead'''    ,       lowerCAmelCase    ,       )
       return set_module_quantized_tensor_to_device(*lowerCAmelCase    ,       **lowerCAmelCase					)


def     SCREAMING_SNAKE_CASE			(      lowerCAmelCase					):
       _UpperCamelCase              =						deepcopy(lowerCAmelCase					)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
       tied_model.tie_weights()

       _UpperCamelCase              =						find_tied_parameters(lowerCAmelCase					)
       # For compatibility with Accelerate < 0.18
       if isinstance(lowerCAmelCase    ,       lowerCAmelCase					):
              _UpperCamelCase              =						sum(list(tied_params.values()					)    ,       []					) + list(tied_params.keys()					)
       else:
              _UpperCamelCase              =						sum(lowerCAmelCase    ,       []					)
       _UpperCamelCase              =						len(lowerCAmelCase					) > 0

       # Check if it is a base model
       _UpperCamelCase              =						not hasattr(lowerCAmelCase    ,       model.base_model_prefix					)

       # Ignore this for base models (BertModel, GPT2Model, etc.)
       if (not has_tied_params) and is_base_model:
              return []

       # otherwise they have an attached head
       _UpperCamelCase              =						list(model.named_children()					)
       _UpperCamelCase              =						[list_modules[-1][0]]

       # add last module together with tied weights
       _UpperCamelCase              =						set(lowerCAmelCase					) - set(lowerCAmelCase					)
       _UpperCamelCase              =						list(set(lowerCAmelCase					)					) + list(lowerCAmelCase					)

       # remove ".weight" from the keys
       _UpperCamelCase              =						['''.weight''', '''.bias''']
       _UpperCamelCase              =						[]
       for name in list_untouched:
              for name_to_remove in names_to_remove:
                     if name_to_remove in name:
                            _UpperCamelCase              =						name.replace(lowerCAmelCase    ,       ''''''					)
              filtered_module_names.append(lowerCAmelCase					)

       return filtered_module_names













import copy
from collections import OrderedDict
from typing import Dict, Mapping

from packaging import version

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


lowercase    : Optional[int]    	=  logging.get_logger(__name__)

lowercase    : List[Any]    	=  {
    """facebook/detr-resnet-50""": """https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json""",
    # See all DETR models at https://huggingface.co/models?filter=detr
}

class  __A(						__UpperCAmelCase ):
     __A	  =       "detr"
     __A	  =       ["past_key_values"]
     __A	  =       {
         "hidden_size": "d_model",
         "num_attention_heads": "encoder_attention_heads",
     }

     def __init__(      self,       A=True,       A=None,       A=3,       A=100,       A=6,       A=2048,       A=8,       A=6,       A=2048,       A=8,       A=0.0,       A=0.0,       A=True,       A="relu",       A=256,       A=0.1,       A=0.0,       A=0.0,       A=0.02,       A=1.0,       A=False,       A="sine",       A="resnet50",       A=True,       A=False,       A=1,       A=5,       A=2,       A=1,       A=1,       A=5,       A=2,       A=0.1,       **A,       ):





            """simple docstring"""

            if backbone_config is not None and use_timm_backbone:
                   raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.'''      )

            if not use_timm_backbone:
                   if backbone_config is None:
                          logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''      )
                          _UpperCamelCase              =						CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']      )
                   elif isinstance(A,       A      ):
                          _UpperCamelCase              =						backbone_config.get('''model_type'''      )
                          _UpperCamelCase              =						CONFIG_MAPPING[backbone_model_type]
                          _UpperCamelCase              =						config_class.from_dict(A      )
                   # set timm attributes to None
                   _UpperCamelCase       ,		_UpperCamelCase       ,		_UpperCamelCase              =						None, None, None

            _UpperCamelCase              =						use_timm_backbone
            _UpperCamelCase              =						backbone_config
            _UpperCamelCase              =						num_channels
            _UpperCamelCase              =						num_queries
            _UpperCamelCase              =						d_model
            _UpperCamelCase              =						encoder_ffn_dim
            _UpperCamelCase              =						encoder_layers
            _UpperCamelCase              =						encoder_attention_heads
            _UpperCamelCase              =						decoder_ffn_dim
            _UpperCamelCase              =						decoder_layers
            _UpperCamelCase              =						decoder_attention_heads
            _UpperCamelCase              =						dropout
            _UpperCamelCase              =						attention_dropout
            _UpperCamelCase              =						activation_dropout
            _UpperCamelCase              =						activation_function
            _UpperCamelCase              =						init_std
            _UpperCamelCase              =						init_xavier_std
            _UpperCamelCase              =						encoder_layerdrop
            _UpperCamelCase              =						decoder_layerdrop
            _UpperCamelCase              =						encoder_layers
            _UpperCamelCase              =						auxiliary_loss
            _UpperCamelCase              =						position_embedding_type
            _UpperCamelCase              =						backbone
            _UpperCamelCase              =						use_pretrained_backbone
            _UpperCamelCase              =						dilation
            # Hungarian matcher
            _UpperCamelCase              =						class_cost
            _UpperCamelCase              =						bbox_cost
            _UpperCamelCase              =						giou_cost
            # Loss coefficients
            _UpperCamelCase              =						mask_loss_coefficient
            _UpperCamelCase              =						dice_loss_coefficient
            _UpperCamelCase              =						bbox_loss_coefficient
            _UpperCamelCase              =						giou_loss_coefficient
            _UpperCamelCase              =						eos_coefficient
            super().__init__(is_encoder_decoder=A,       **A      )

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return self.encoder_attention_heads

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return self.d_model

     @classmethod
     def 	_UpperCamelCase     (      cls,       A,       **A      ):





            """simple docstring"""

            return cls(backbone_config=A,       **A      )



     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						copy.deepcopy(self.__dict__      )
            if output["backbone_config"] is not None:
                   _UpperCamelCase              =						self.backbone_config.to_dict()
            _UpperCamelCase              =						self.__class__.model_type
            return output






class  __A(						__UpperCAmelCase ):
     __A	  =       version.parse("1.11" )

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return OrderedDict(
                [
                    ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                    ('''pixel_mask''', {0: '''batch'''}),
                ]      )

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return 1E-5



     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return 12






