

import inspect
import warnings

import torch

from .state import AcceleratorState, GradientState
from .utils import DistributedType, honor_type, is_tpu_available


if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm
def   _lowerCAmelCase(						__A ,							__A      ):
  if isinstance(__A ,							(list, tuple)      ):
    return honor_type(__A ,							(move_to_device(__A ,							__A      ) for t in state)      )
  elif isinstance(__A ,							__A      ):
    return type(__A      )({k: move_to_device(__A ,							__A      ) for k, v in state.items()}      )
  elif isinstance(__A ,							torch.Tensor      ):
    return state.to(__A      )
  return state






class     __magic_name__     (							torch.optim.Optimizer     ):


 def __init__(    self		:			Union[str, Any]      ,    lowerCAmelCase__		:			Tuple      ,    lowerCAmelCase__		:			Union[str, Any]=True      ,    lowerCAmelCase__		:			str=None     )     ->   int:
   UpperCAmelCase          =	optimizer
   UpperCAmelCase          =	scaler
   UpperCAmelCase          =	AcceleratorState()
   UpperCAmelCase          =	GradientState()
   UpperCAmelCase          =	device_placement
   UpperCAmelCase          =	False
   UpperCAmelCase          =	None

   # Handle device placement
   if device_placement:
     UpperCAmelCase          =	self.optimizer.state_dict()
     if self.accelerator_state.distributed_type == DistributedType.TPU:
       xm.send_cpu_data_to_device(lowerCAmelCase__      ,    self.accelerator_state.device     )
     else:
       UpperCAmelCase          =	move_to_device(lowerCAmelCase__      ,    self.accelerator_state.device     )
     self.optimizer.load_state_dict(lowerCAmelCase__     )


 @property
 def _UpperCamelCase						(    self		:			List[str]     )     ->   Tuple:
   return self.optimizer.state


 @state.setter
 def _UpperCamelCase						(    self		:			int      ,    lowerCAmelCase__		:			Tuple     )     ->   Tuple:
   UpperCAmelCase          =	state


 @property
 def _UpperCamelCase						(    self		:			Dict     )     ->   Optional[Any]:
   return self.optimizer.param_groups


 @param_groups.setter
 def _UpperCamelCase						(    self		:			Tuple      ,    lowerCAmelCase__		:			List[Any]     )     ->   Dict:
   UpperCAmelCase          =	param_groups


 @property
 def _UpperCamelCase						(    self		:			List[Any]     )     ->   Optional[int]:
   return self.optimizer.defaults


 @defaults.setter
 def _UpperCamelCase						(    self		:			Optional[Any]      ,    lowerCAmelCase__		:			Union[str, Any]     )     ->   List[Any]:
   UpperCAmelCase          =	defaults


 def _UpperCamelCase						(    self		:			Union[str, Any]      ,    lowerCAmelCase__		:			Optional[int]     )     ->   Tuple:
   self.optimizer.add_param_group(lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			int      ,    lowerCAmelCase__		:			Dict     )     ->   List[Any]:
   if self.accelerator_state.distributed_type == DistributedType.TPU and self.device_placement:
     xm.send_cpu_data_to_device(lowerCAmelCase__      ,    self.accelerator_state.device     )
   self.optimizer.load_state_dict(lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Tuple     )     ->   Any:
   return self.optimizer.state_dict()


 def _UpperCamelCase						(    self		:			Dict      ,    lowerCAmelCase__		:			Union[str, Any]=None     )     ->   List[str]:
   if self.gradient_state.sync_gradients:
     UpperCAmelCase          =	"set_to_none" in inspect.signature(self.optimizer.zero_grad     ).parameters
     if accept_arg:
       if set_to_none is None:
         UpperCAmelCase          =	False
       self.optimizer.zero_grad(set_to_none=lowerCAmelCase__     )
     else:
       if set_to_none is not None:
         raise ValueError("`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer."     )
       self.optimizer.zero_grad()


 def _UpperCamelCase						(    self		:			Dict      ,    lowerCAmelCase__		:			str=None     )     ->   Dict:
   if self.gradient_state.sync_gradients:
     if self.accelerator_state.distributed_type == DistributedType.TPU:
       UpperCAmelCase          =	{"closure": closure} if closure is not None else {}
       xm.optimizer_step(self.optimizer      ,    optimizer_args=lowerCAmelCase__     )
     elif self.scaler is not None:
       UpperCAmelCase          =	False
       if self._last_scale is None:
         # `get_scale` is an async operation requiring full synchronization
         # on CPU and GPUs before finishing. As a result, we store away
         # the prior one to reduce the call overhead
         UpperCAmelCase          =	self.scaler.get_scale()
         UpperCAmelCase          =	True
       self.scaler.step(self.optimizer      ,    lowerCAmelCase__     )
       self.scaler.update()
       UpperCAmelCase          =	self.scaler.get_scale()
       if not new_scale:
         # If we reduced the loss scale, it means the optimizer step was skipped because of gradient overflow.
         UpperCAmelCase          =	scale_after < self._last_scale
       UpperCAmelCase          =	scale_after

     else:
       self.optimizer.step(lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			List[str]      ,    lowerCAmelCase__		:			List[Any]     )     ->   Dict:
   for param_group in self.optimizer.param_groups:
     UpperCAmelCase          =	[parameters_map.get(lowerCAmelCase__      ,    lowerCAmelCase__     ) for p in param_group["params"]]


 @property
 def _UpperCamelCase						(    self		:			Tuple     )     ->   List[Any]:
   warnings.warn(
       "The `is_overflow` property is deprecated and will be removed in version 1.0 of Accelerate use "
       "`optimizer.step_was_skipped` instead."      ,    lowerCAmelCase__      ,    )
   return self._is_overflow


 @property
 def _UpperCamelCase						(    self		:			List[Any]     )     ->   Optional[Any]:
   return self._is_overflow


 def __getstate__(    self		:			Tuple     )     ->   Dict:
   return self.__dict__.copy()


 def __setstate__(    self		:			int      ,    lowerCAmelCase__		:			Dict     )     ->   Union[str, Any]:
   self.__dict__.update(lowerCAmelCase__     )






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     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    ["""image_processor""", """tokenizer"""]
 UpperCAmelCase				     =    """LayoutLMv2ImageProcessor"""
 UpperCAmelCase				     =    ("""LayoutLMv2Tokenizer""", """LayoutLMv2TokenizerFast""")


 def __init__(    self		:			Any      ,    lowerCAmelCase__		:			Any=None      ,    lowerCAmelCase__		:			Optional[Any]=None      ,    **lowerCAmelCase__		:			int     )     ->   Union[str, Any]:
   UpperCAmelCase          =	None
   if "feature_extractor" in kwargs:
     warnings.warn(
         "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
         " instead."      ,    lowerCAmelCase__      ,    )
     UpperCAmelCase          =	kwargs.pop("feature_extractor"     )

   UpperCAmelCase          =	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__(lowerCAmelCase__      ,    lowerCAmelCase__     )


 def __call__(    self		:			int      ,    lowerCAmelCase__		:			Tuple      ,    lowerCAmelCase__		:			Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None      ,    lowerCAmelCase__		:			Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None      ,    lowerCAmelCase__		:			Union[List[List[int]], List[List[List[int]]]] = None      ,    lowerCAmelCase__		:			Optional[Union[List[int], List[List[int]]]] = None      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Union[bool, str, PaddingStrategy] = False      ,    lowerCAmelCase__		:			Union[bool, str, TruncationStrategy] = False      ,    lowerCAmelCase__		:			Optional[int] = None      ,    lowerCAmelCase__		:			int = 0      ,    lowerCAmelCase__		:			Optional[int] = None      ,    lowerCAmelCase__		:			Optional[bool] = None      ,    lowerCAmelCase__		:			Optional[bool] = None      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Optional[Union[str, TensorType]] = None      ,    **lowerCAmelCase__		:			Any      ,    )     ->   BatchEncoding:
   # 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          =	self.image_processor(images=lowerCAmelCase__      ,    return_tensors=lowerCAmelCase__     )

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

   UpperCAmelCase          =	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=lowerCAmelCase__      ,    add_special_tokens=lowerCAmelCase__      ,    padding=lowerCAmelCase__      ,    truncation=lowerCAmelCase__      ,    max_length=lowerCAmelCase__      ,    stride=lowerCAmelCase__      ,    pad_to_multiple_of=lowerCAmelCase__      ,    return_token_type_ids=lowerCAmelCase__      ,    return_attention_mask=lowerCAmelCase__      ,    return_overflowing_tokens=lowerCAmelCase__      ,    return_special_tokens_mask=lowerCAmelCase__      ,    return_offsets_mapping=lowerCAmelCase__      ,    return_length=lowerCAmelCase__      ,    verbose=lowerCAmelCase__      ,    return_tensors=lowerCAmelCase__      ,    **lowerCAmelCase__      ,    )

   # add pixel values
   UpperCAmelCase          =	features.pop("pixel_values"     )
   if return_overflowing_tokens is True:
     UpperCAmelCase          =	self.get_overflowing_images(lowerCAmelCase__      ,    encoded_inputs["overflow_to_sample_mapping"]     )
   UpperCAmelCase          =	images

   return encoded_inputs


 def _UpperCamelCase						(    self		:			str      ,    lowerCAmelCase__		:			Union[str, Any]      ,    lowerCAmelCase__		:			Union[str, Any]     )     ->   int:
   # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
   UpperCAmelCase          =	[]
   for sample_idx in overflow_to_sample_mapping:
     images_with_overflow.append(images[sample_idx]     )

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

   return images_with_overflow


 def _UpperCamelCase						(    self		:			Optional[Any]      ,    *lowerCAmelCase__		:			int      ,    **lowerCAmelCase__		:			Union[str, Any]     )     ->   List[str]:
   return self.tokenizer.batch_decode(*lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Union[str, Any]      ,    *lowerCAmelCase__		:			Tuple      ,    **lowerCAmelCase__		:			Union[str, Any]     )     ->   List[Any]:
   return self.tokenizer.decode(*lowerCAmelCase__      ,    **lowerCAmelCase__     )


 @property
 def _UpperCamelCase						(    self		:			int     )     ->   List[str]:
   return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]


 @property
 def _UpperCamelCase						(    self		:			Dict     )     ->   List[str]:
   warnings.warn(
       "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."      ,    lowerCAmelCase__      ,    )
   return self.image_processor_class


 @property
 def _UpperCamelCase						(    self		:			List[Any]     )     ->   int:
   warnings.warn(
       "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."      ,    lowerCAmelCase__      ,    )
   return self.image_processor



