


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

__UpperCamelCase				:  Tuple      					=							logging.get_logger(__name__)
def      snake_case_						( __lowercase			,       __lowercase			,       __lowercase			,       __lowercase=None			,       __lowercase=None       ):
   # Recurse if needed
   if "." in tensor_name:
      UpperCAmelCase_							:      List[str]						=   tensor_name.split('''.'''       )
      for split in splits[:-1]:
         UpperCAmelCase_							:      Dict						=   getattr(__lowercase			,       __lowercase       )
         if new_module is None:
            raise ValueError(F'''{module} has no attribute {split}.'''       )
         UpperCAmelCase_							:      List[Any]						=   new_module
      UpperCAmelCase_							:      Tuple						=   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_							:      Optional[Any]						=   tensor_name in module._buffers
   UpperCAmelCase_							:      Optional[Any]						=   getattr(__lowercase			,       __lowercase       )

   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_							:      Any						=   False
   UpperCAmelCase_							:      Any						=   False
   if is_buffer or not is_bitsandbytes_available():
      UpperCAmelCase_							:      str						=   False
      UpperCAmelCase_							:      Tuple						=   False
   else:
      UpperCAmelCase_							:      List[Any]						=   hasattr(bnb.nn			,       '''Params4bit'''       ) and isinstance(module._parameters[tensor_name]			,       bnb.nn.Paramsabit       )
      UpperCAmelCase_							:      List[Any]						=   isinstance(module._parameters[tensor_name]			,       bnb.nn.IntaParams       )

   if is_abit or is_abit:
      UpperCAmelCase_							:      Optional[Any]						=   module._parameters[tensor_name]
      if param.device.type != "cuda":
         if value is None:
            UpperCAmelCase_							:      Optional[Any]						=   old_value.to(__lowercase       )
         elif isinstance(__lowercase			,       torch.Tensor       ):
            UpperCAmelCase_							:      Optional[int]						=   value.to('''cpu'''       )
            if value.dtype == torch.inta:
               UpperCAmelCase_							:      Dict						=   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_							:      Dict						=   torch.tensor(__lowercase			,       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			,       __lowercase       ) and fpaa_statistics is None:
            UpperCAmelCase_							:      Optional[Any]						=   new_value.T

         UpperCAmelCase_							:      Dict						=   old_value.__dict__
         if is_abit:
            UpperCAmelCase_							:      Dict						=   bnb.nn.IntaParams(__lowercase			,       requires_grad=__lowercase			,       **__lowercase       ).to(__lowercase       )
         elif is_abit:
            UpperCAmelCase_							:      Optional[Any]						=   bnb.nn.Paramsabit(__lowercase			,       requires_grad=__lowercase			,       **__lowercase       ).to(__lowercase       )

         UpperCAmelCase_							:      List[str]						=   new_value
         if fpaa_statistics is not None:
            setattr(module.weight			,       '''SCB'''			,       fpaa_statistics.to(__lowercase       )       )

   else:
      if value is None:
         UpperCAmelCase_							:      Any						=   old_value.to(__lowercase       )
      elif isinstance(__lowercase			,       torch.Tensor       ):
         UpperCAmelCase_							:      int						=   value.to(__lowercase       )
      else:
         UpperCAmelCase_							:      Any						=   torch.tensor(__lowercase			,       device=__lowercase       )

      if is_buffer:
         UpperCAmelCase_							:      List[str]						=   new_value
      else:
         UpperCAmelCase_							:      Union[str, Any]						=   nn.Parameter(__lowercase			,       requires_grad=old_value.requires_grad       )
         UpperCAmelCase_							:      Union[str, Any]						=   new_value
def      snake_case_						( __lowercase			,       __lowercase=None			,       __lowercase=None			,       __lowercase=None			,       __lowercase=False       ):
   for name, module in model.named_children():
      if current_key_name is None:
         UpperCAmelCase_							:      int						=   []
      current_key_name.append(__lowercase       )

      if (isinstance(__lowercase			,       nn.Linear       ) or isinstance(__lowercase			,       __lowercase       )) 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(__lowercase       ) for key in modules_to_not_convert       ):
            with init_empty_weights():
               if isinstance(__lowercase			,       __lowercase       ):
                  UpperCAmelCase_		,      UpperCAmelCase_							:      Any						=   module.weight.shape
               else:
                  UpperCAmelCase_							:      Any						=   module.in_features
                  UpperCAmelCase_							:      Any						=   module.out_features

               if quantization_config.quantization_method() == "llm_int8":
                  UpperCAmelCase_							:      Tuple						=   bnb.nn.LinearabitLt(
                      __lowercase			,       __lowercase			,       module.bias is not None			,       has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight			,       threshold=quantization_config.llm_inta_threshold			,       )
                  UpperCAmelCase_							:      Optional[int]						=   True
               else:
                  if (
                      quantization_config.llm_inta_skip_modules is not None
                      and name in quantization_config.llm_inta_skip_modules
                  ):
                     pass
                  else:
                     UpperCAmelCase_							:      Any						=   bnb.nn.Linearabit(
                         __lowercase			,       __lowercase			,       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_							:      List[Any]						=   True
                    # Store the module class in case we need to transpose the weight later
               UpperCAmelCase_							:      List[str]						=   type(__lowercase       )
               # Force requires grad to False to avoid unexpected errors
               model._modules[name].requires_grad_(__lowercase       )
      if len(list(module.children()       )       ) > 0:
         UpperCAmelCase_		,      UpperCAmelCase_							:      Optional[Any]						=   _replace_with_bnb_linear(
             __lowercase			,       __lowercase			,       __lowercase			,       __lowercase			,       has_been_replaced=__lowercase			,       )
      # Remove the last key for recursion
      current_key_name.pop(-1       )
   return model, has_been_replaced
def      snake_case_						( __lowercase			,       __lowercase=None			,       __lowercase=None			,       __lowercase=None       ):
   UpperCAmelCase_							:      Any						=   ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
   UpperCAmelCase_		,      UpperCAmelCase_							:      List[Any]						=   _replace_with_bnb_linear(
       __lowercase			,       __lowercase			,       __lowercase			,       __lowercase       )

   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      snake_case_						( *__lowercase			,       **__lowercase       ):
   warnings.warn(
       '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead'''			,       __lowercase			,       )
   return replace_with_bnb_linear(*__lowercase			,       **__lowercase       )
def      snake_case_						( *__lowercase			,       **__lowercase       ):
   warnings.warn(
       '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead'''			,       __lowercase			,       )
   return set_module_quantized_tensor_to_device(*__lowercase			,       **__lowercase       )


def      snake_case_						( __lowercase       ):
   UpperCAmelCase_							:      Tuple						=   deepcopy(__lowercase       )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
   tied_model.tie_weights()

   UpperCAmelCase_							:      List[Any]						=   find_tied_parameters(__lowercase       )
   # For compatibility with Accelerate < 0.18
   if isinstance(__lowercase			,       __lowercase       ):
      UpperCAmelCase_							:      Optional[int]						=   sum(list(tied_params.values()       )			,       []       ) + list(tied_params.keys()       )
   else:
      UpperCAmelCase_							:      str						=   sum(__lowercase			,       []       )
   UpperCAmelCase_							:      List[Any]						=   len(__lowercase       ) > 0

   # Check if it is a base model
   UpperCAmelCase_							:      str						=   not hasattr(__lowercase			,       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_							:      Optional[int]						=   list(model.named_children()       )
   UpperCAmelCase_							:      Optional[Any]						=   [list_modules[-1][0]]

   # add last module together with tied weights
   UpperCAmelCase_							:      List[Any]						=   set(__lowercase       ) - set(__lowercase       )
   UpperCAmelCase_							:      List[str]						=   list(set(__lowercase       )       ) + list(__lowercase       )

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

   return filtered_module_names



import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType





class  lowerCAmelCase__(    snake_case__						):






    '''simple docstring'''





    A_  :     str			= ['image_processor', 'tokenizer']
    A_  :     int			= 'LayoutLMv2ImageProcessor'
    A_  :     str			= ('LayoutXLMTokenizer', 'LayoutXLMTokenizerFast')





    def __init__(	self				:   Union[str, Any]       ,   __snake_case				:   List[Any]=None       ,   __snake_case				:   List[str]=None       ,   **__snake_case				:   Optional[int]	):





       '''simple docstring'''
       if "feature_extractor" in kwargs:
          warnings.warn(
              '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
              ''' instead.'''       ,   __snake_case       ,   )
          UpperCAmelCase_							:      List[Any]						=   kwargs.pop('''feature_extractor'''	)

       UpperCAmelCase_							:      Optional[int]						=   image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
          raise ValueError('''You need to specify an `image_processor`.'''	)
       if tokenizer is None:
          raise ValueError('''You need to specify a `tokenizer`.'''	)

       super().__init__(__snake_case       ,   __snake_case	)





    def __call__(	self				:   List[str]       ,   __snake_case				:   Dict       ,   __snake_case				:   Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None       ,   __snake_case				:   Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None       ,   __snake_case				:   Union[List[List[int]], List[List[List[int]]]] = None       ,   __snake_case				:   Optional[Union[List[int], List[List[int]]]] = None       ,   __snake_case				:   bool = True       ,   __snake_case				:   Union[bool, str, PaddingStrategy] = False       ,   __snake_case				:   Union[bool, str, TruncationStrategy] = None       ,   __snake_case				:   Optional[int] = None       ,   __snake_case				:   int = 0       ,   __snake_case				:   Optional[int] = None       ,   __snake_case				:   Optional[bool] = None       ,   __snake_case				:   Optional[bool] = None       ,   __snake_case				:   bool = False       ,   __snake_case				:   bool = False       ,   __snake_case				:   bool = False       ,   __snake_case				:   bool = False       ,   __snake_case				:   bool = True       ,   __snake_case				:   Optional[Union[str, TensorType]] = None       ,   **__snake_case				:   Optional[int]       ,   ):





       '''simple docstring'''
       # verify input
       if self.image_processor.apply_ocr and (boxes is not None):
          raise ValueError(
              '''You cannot provide bounding boxes '''
              '''if you initialized the image processor with apply_ocr set to True.'''	)

       if self.image_processor.apply_ocr and (word_labels is not None):
          raise ValueError(
              '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.'''	)

       if return_overflowing_tokens is True and return_offsets_mapping is False:
          raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.'''	)

       # first, apply the image processor
       UpperCAmelCase_							:      Tuple						=   self.image_processor(images=__snake_case       ,   return_tensors=__snake_case	)

       # second, apply the tokenizer
       if text is not None and self.image_processor.apply_ocr and text_pair is None:
          if isinstance(__snake_case       ,   __snake_case	):
             UpperCAmelCase_							:      Optional[Any]						=   [text]  # add batch dimension (as the image processor always adds a batch dimension)
          UpperCAmelCase_							:      Any						=   features['''words''']

       UpperCAmelCase_							:      str						=   self.tokenizer(
           text=text if text is not None else features['''words''']       ,   text_pair=text_pair if text_pair is not None else None       ,   boxes=boxes if boxes is not None else features['''boxes''']       ,   word_labels=__snake_case       ,   add_special_tokens=__snake_case       ,   padding=__snake_case       ,   truncation=__snake_case       ,   max_length=__snake_case       ,   stride=__snake_case       ,   pad_to_multiple_of=__snake_case       ,   return_token_type_ids=__snake_case       ,   return_attention_mask=__snake_case       ,   return_overflowing_tokens=__snake_case       ,   return_special_tokens_mask=__snake_case       ,   return_offsets_mapping=__snake_case       ,   return_length=__snake_case       ,   verbose=__snake_case       ,   return_tensors=__snake_case       ,   **__snake_case       ,   )

       # add pixel values
       UpperCAmelCase_							:      List[str]						=   features.pop('''pixel_values'''	)
       if return_overflowing_tokens is True:
          UpperCAmelCase_							:      Optional[int]						=   self.get_overflowing_images(__snake_case       ,   encoded_inputs['''overflow_to_sample_mapping''']	)
       UpperCAmelCase_							:      List[Any]						=   images

       return encoded_inputs





    def 					_lowerCamelCase (	self				:   Union[str, Any]       ,   __snake_case				:   str       ,   __snake_case				:   List[Any]	):





       '''simple docstring'''
       # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
       UpperCAmelCase_							:      List[str]						=   []
       for sample_idx in overflow_to_sample_mapping:
          images_with_overflow.append(images[sample_idx]	)

       if len(__snake_case	) != len(__snake_case	):
          raise ValueError(
              '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'''
              f''' {len(__snake_case	)} and {len(__snake_case	)}'''	)

       return images_with_overflow





    def 					_lowerCamelCase (	self				:   List[Any]       ,   *__snake_case				:   Optional[int]       ,   **__snake_case				:   List[Any]	):





       '''simple docstring'''
       return self.tokenizer.batch_decode(*__snake_case       ,   **__snake_case	)





    def 					_lowerCamelCase (	self				:   str       ,   *__snake_case				:   Optional[Any]       ,   **__snake_case				:   Union[str, Any]	):





       '''simple docstring'''
       return self.tokenizer.decode(*__snake_case       ,   **__snake_case	)





    @property
    def 					_lowerCamelCase (	self				:   Optional[Any]	):





       '''simple docstring'''
       return ["input_ids", "bbox", "attention_mask", "image"]





    @property
    def 					_lowerCamelCase (	self				:   List[str]	):





       '''simple docstring'''
       warnings.warn(
           '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''       ,   __snake_case       ,   )
       return self.image_processor_class





    @property
    def 					_lowerCamelCase (	self				:   Dict	):





       '''simple docstring'''
       warnings.warn(
           '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''       ,   __snake_case       ,   )
       return self.image_processor