






"""simple docstring"""
import re
import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin



class      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	_A       :				Optional[Any]    =				["""image_processor""", """tokenizer"""]
	_A       :				Optional[Any]    =				"""AutoImageProcessor"""
	_A       :				Tuple    =				"""AutoTokenizer"""





	def __init__(self     ,     lowerCAmelCase_=None     ,     lowerCAmelCase_=None     ,     **lowerCAmelCase_							):
		A_		:						List[Any]	    =   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_     ,     )
			A_		:						Any	    =   kwargs.pop("""feature_extractor"""							)

		A_		:						str	    =   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_							)
		A_		:						Optional[Any]	    =   self.image_processor
		A_		:						Union[str, Any]	    =   False





	def __call__(self     ,     *lowerCAmelCase_     ,     **lowerCAmelCase_							):
		# For backward compatibility
		if self._in_target_context_manager:
			return self.current_processor(*lowerCAmelCase_     ,     **lowerCAmelCase_							)

		A_		:						List[str]	    =   kwargs.pop("""images"""     ,     lowerCAmelCase_							)
		A_		:						Tuple	    =   kwargs.pop("""text"""     ,     lowerCAmelCase_							)
		if len(lowerCAmelCase_							) > 0:
			A_		:						str	    =   args[0]
			A_		:						Any	    =   args[1:]

		if images is None and text is None:
			raise ValueError("""You need to specify either an `images` or `text` input to process."""							)

		if images is not None:
			A_		:						Union[str, Any]	    =   self.image_processor(lowerCAmelCase_     ,     *lowerCAmelCase_     ,     **lowerCAmelCase_							)
		if text is not None:
			A_		:						Dict	    =   self.tokenizer(lowerCAmelCase_     ,     **lowerCAmelCase_							)

		if text is None:
			return inputs
		elif images is None:
			return encodings
		else:
			A_		:						List[str]	    =   encodings["""input_ids"""]
			return inputs





	def    lowerCamelCase(self     ,     *lowerCAmelCase_     ,     **lowerCAmelCase_							):
		return self.tokenizer.batch_decode(*lowerCAmelCase_     ,     **lowerCAmelCase_							)





	def    lowerCamelCase(self     ,     *lowerCAmelCase_     ,     **lowerCAmelCase_							):
		return self.tokenizer.decode(*lowerCAmelCase_     ,     **lowerCAmelCase_							)





	@contextmanager
	def    lowerCamelCase(self							):
		warnings.warn(
		    """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
		    """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
		    """your images inputs, or in a separate call."""							)
		A_		:						List[Any]	    =   True
		A_		:						List[Any]	    =   self.tokenizer
		yield
		A_		:						Any	    =   self.image_processor
		A_		:						List[str]	    =   False





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_=False     ,     lowerCAmelCase_=None							):
		if added_vocab is None:
			A_		:						str	    =   self.tokenizer.get_added_vocab()

		A_		:						str	    =   {}

		while tokens:
			A_		:						Optional[int]	    =   re.search(r"""<s_(.*?)>"""     ,     lowerCAmelCase_     ,     re.IGNORECASE							)
			if start_token is None:
				break
			A_		:						Any	    =   start_token.group(1							)
			A_		:						Optional[int]	    =   re.search(rf"""</s_{key}>"""     ,     lowerCAmelCase_     ,     re.IGNORECASE							)
			A_		:						List[str]	    =   start_token.group()
			if end_token is None:
				A_		:						str	    =   tokens.replace(lowerCAmelCase_     ,     """"""							)
			else:
				A_		:						Union[str, Any]	    =   end_token.group()
				A_		:						Optional[int]	    =   re.escape(lowerCAmelCase_							)
				A_		:						Optional[Any]	    =   re.escape(lowerCAmelCase_							)
				A_		:						Dict	    =   re.search(f"""{start_token_escaped}(.*?){end_token_escaped}"""     ,     lowerCAmelCase_     ,     re.IGNORECASE							)
				if content is not None:
					A_		:						str	    =   content.group(1							).strip()
					if r"<s_" in content and r"</s_" in content:  # non-leaf node
						A_		:						Union[str, Any]	    =   self.tokenajson(lowerCAmelCase_     ,     is_inner_value=lowerCAmelCase_     ,     added_vocab=lowerCAmelCase_							)
						if value:
							if len(lowerCAmelCase_							) == 1:
								A_		:						str	    =   value[0]
							A_		:						int	    =   value
					else:  # leaf nodes
						A_		:						int	    =   []
						for leaf in content.split(r"""<sep/>"""							):
							A_		:						List[Any]	    =   leaf.strip()
							if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
								A_		:						Dict	    =   leaf[1:-2]  # for categorical special tokens
							output[key].append(lowerCAmelCase_							)
						if len(output[key]							) == 1:
							A_		:						Optional[Any]	    =   output[key][0]

				A_		:						Dict	    =   tokens[tokens.find(lowerCAmelCase_							) + len(lowerCAmelCase_							) :].strip()
				if tokens[:6] == r"<sep/>":  # non-leaf nodes
					return [output] + self.tokenajson(tokens[6:]     ,     is_inner_value=lowerCAmelCase_     ,     added_vocab=lowerCAmelCase_							)

		if len(lowerCAmelCase_							):
			return [output] if is_inner_value else output
		else:
			return [] if is_inner_value else {"text_sequence": tokens}





	@property
	def    lowerCamelCase(self							):
		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    lowerCamelCase(self							):
		warnings.warn(
		    """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""     ,     lowerCAmelCase_     ,     )
		return self.image_processor









"""simple docstring"""
import os

import torch

from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version


if is_torch_version(">=", FSDP_PYTORCH_VERSION):
							import torch.distributed.checkpoint as dist_cp
							from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
							from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
							from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
							from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType


_lowerCAmelCase         =							get_logger(__name__)






def 			__UpperCamelCase	(		snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__=0					):
	os.makedirs(snake_case__   ,   exist_ok=snake_case__					)
	with FSDP.state_dict_type(
	    snake_case__   ,   fsdp_plugin.state_dict_type   ,   fsdp_plugin.state_dict_config   ,   fsdp_plugin.optim_state_dict_config					):
		A_		:						Optional[int]	    =   model.state_dict()
		if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
			A_		:						int	    =   F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin"""
			A_		:						Union[str, Any]	    =   os.path.join(snake_case__   ,   snake_case__					)
			if accelerator.process_index == 0:
				logger.info(F"""Saving model to {output_model_file}"""					)
				torch.save(snake_case__   ,   snake_case__					)
				logger.info(F"""Model saved to {output_model_file}"""					)
		elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
			A_		:						List[str]	    =   (
			    F"""{MODEL_NAME}_rank{accelerator.process_index}.bin"""
			    if model_index == 0
			    else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"""
			)
			A_		:						List[str]	    =   os.path.join(snake_case__   ,   snake_case__					)
			logger.info(F"""Saving model to {output_model_file}"""					)
			torch.save(snake_case__   ,   snake_case__					)
			logger.info(F"""Model saved to {output_model_file}"""					)
		elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
			A_		:						str	    =   os.path.join(snake_case__   ,   F"""{MODEL_NAME}_{model_index}"""					)
			os.makedirs(snake_case__   ,   exist_ok=snake_case__					)
			logger.info(F"""Saving model to {ckpt_dir}"""					)
			A_		:						Dict	    =   {"""model""": state_dict}

			dist_cp.save_state_dict(
			    state_dict=snake_case__   ,   storage_writer=dist_cp.FileSystemWriter(snake_case__					)   ,   planner=DefaultSavePlanner()   ,   )
			logger.info(F"""Model saved to {ckpt_dir}"""					)






def 			__UpperCamelCase	(		snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__=0					):
	accelerator.wait_for_everyone()
	with FSDP.state_dict_type(
	    snake_case__   ,   fsdp_plugin.state_dict_type   ,   fsdp_plugin.state_dict_config   ,   fsdp_plugin.optim_state_dict_config					):
		if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
			if type(snake_case__					) != FSDP and accelerator.process_index != 0:
				if not fsdp_plugin.sync_module_states:
					raise ValueError(
					    """Set the `sync_module_states` flag to `True` so that model states are synced across processes when """
					    """initializing FSDP object"""					)
				return
			A_		:						Tuple	    =   F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin"""
			A_		:						Any	    =   os.path.join(snake_case__   ,   snake_case__					)
			logger.info(F"""Loading model from {input_model_file}"""					)
			A_		:						List[Any]	    =   torch.load(snake_case__					)
			logger.info(F"""Model loaded from {input_model_file}"""					)
		elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
			A_		:						List[str]	    =   (
			    F"""{MODEL_NAME}_rank{accelerator.process_index}.bin"""
			    if model_index == 0
			    else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"""
			)
			A_		:						Any	    =   os.path.join(snake_case__   ,   snake_case__					)
			logger.info(F"""Loading model from {input_model_file}"""					)
			A_		:						List[str]	    =   torch.load(snake_case__					)
			logger.info(F"""Model loaded from {input_model_file}"""					)
		elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
			A_		:						Optional[Any]	    =   (
			    os.path.join(snake_case__   ,   F"""{MODEL_NAME}_{model_index}"""					)
			    if F"""{MODEL_NAME}""" not in input_dir
			    else input_dir
			)
			logger.info(F"""Loading model from {ckpt_dir}"""					)
			A_		:						List[str]	    =   {"""model""": model.state_dict()}
			dist_cp.load_state_dict(
			    state_dict=snake_case__   ,   storage_reader=dist_cp.FileSystemReader(snake_case__					)   ,   planner=DefaultLoadPlanner()   ,   )
			A_		:						Tuple	    =   state_dict["""model"""]
			logger.info(F"""Model loaded from {ckpt_dir}"""					)
		model.load_state_dict(snake_case__					)






def 			__UpperCamelCase	(		snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__=0					):
	os.makedirs(snake_case__   ,   exist_ok=snake_case__					)
	with FSDP.state_dict_type(
	    snake_case__   ,   fsdp_plugin.state_dict_type   ,   fsdp_plugin.state_dict_config   ,   fsdp_plugin.optim_state_dict_config					):
		A_		:						Optional[Any]	    =   FSDP.optim_state_dict(snake_case__   ,   snake_case__					)
		if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
			if accelerator.process_index == 0:
				A_		:						Any	    =   (
				    F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin"""
				)
				A_		:						Optional[int]	    =   os.path.join(snake_case__   ,   snake_case__					)
				logger.info(F"""Saving Optimizer state to {output_optimizer_file}"""					)
				torch.save(snake_case__   ,   snake_case__					)
				logger.info(F"""Optimizer state saved in {output_optimizer_file}"""					)
		else:
			A_		:						Union[str, Any]	    =   os.path.join(snake_case__   ,   F"""{OPTIMIZER_NAME}_{optimizer_index}"""					)
			os.makedirs(snake_case__   ,   exist_ok=snake_case__					)
			logger.info(F"""Saving Optimizer state to {ckpt_dir}"""					)
			dist_cp.save_state_dict(
			    state_dict={"""optimizer""": optim_state}   ,   storage_writer=dist_cp.FileSystemWriter(snake_case__					)   ,   planner=DefaultSavePlanner()   ,   )
			logger.info(F"""Optimizer state saved in {ckpt_dir}"""					)






def 			__UpperCamelCase	(		snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__=0					):
	accelerator.wait_for_everyone()
	with FSDP.state_dict_type(
	    snake_case__   ,   fsdp_plugin.state_dict_type   ,   fsdp_plugin.state_dict_config   ,   fsdp_plugin.optim_state_dict_config					):
		if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
			A_		:						List[str]	    =   None
			# below check should work but currently it isn't working (mostly opytorch issue),
			# in the meantime disabling it at the cost of excess memory usage
			# if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
			A_		:						Tuple	    =   (
			    F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin"""
			)
			A_		:						int	    =   os.path.join(snake_case__   ,   snake_case__					)
			logger.info(F"""Loading Optimizer state from {input_optimizer_file}"""					)
			A_		:						Tuple	    =   torch.load(snake_case__					)
			logger.info(F"""Optimizer state loaded from {input_optimizer_file}"""					)
		else:
			A_		:						str	    =   (
			    os.path.join(snake_case__   ,   F"""{OPTIMIZER_NAME}_{optimizer_index}"""					)
			    if F"""{OPTIMIZER_NAME}""" not in input_dir
			    else input_dir
			)
			logger.info(F"""Loading Optimizer from {ckpt_dir}"""					)
			A_		:						Union[str, Any]	    =   load_sharded_optimizer_state_dict(
			    model_state_dict=model.state_dict()   ,   optimizer_key="""optimizer"""   ,   storage_reader=dist_cp.FileSystemReader(snake_case__					)   ,   )
			A_		:						Tuple	    =   optim_state["""optimizer"""]
			logger.info(F"""Optimizer loaded from {ckpt_dir}"""					)
		A_		:						List[Any]	    =   FSDP.optim_state_dict_to_load(snake_case__   ,   snake_case__   ,   snake_case__					)
		optimizer.load_state_dict(snake_case__					)

