






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


_A			:    Any					  =get_logger(__name__)





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase=0   )   -> int:
       os.makedirs(__SCREAMING_SNAKE_CASE       ,    exist_ok=__SCREAMING_SNAKE_CASE   )
       with FSDP.state_dict_type(
           __SCREAMING_SNAKE_CASE       ,    fsdp_plugin.state_dict_type       ,    fsdp_plugin.state_dict_config       ,    fsdp_plugin.optim_state_dict_config   ):
              lowerCamelCase__      :			Optional[int] 						= model.state_dict()
              if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
                     lowerCamelCase__      :			List[Any] 						= f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin'''
                     lowerCamelCase__      :			Optional[Any] 						= os.path.join(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                     if accelerator.process_index == 0:
                            logger.info(f'''Saving model to {output_model_file}'''   )
                            torch.save(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                            logger.info(f'''Model saved to {output_model_file}'''   )
              elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
                     lowerCamelCase__      :			Optional[int] 						= (
                         f'''{MODEL_NAME}_rank{accelerator.process_index}.bin'''
                         if model_index == 0
                         else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'''
                     )
                     lowerCamelCase__      :			Optional[int] 						= os.path.join(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Saving model to {output_model_file}'''   )
                     torch.save(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Model saved to {output_model_file}'''   )
              elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
                     lowerCamelCase__      :			List[Any] 						= os.path.join(__SCREAMING_SNAKE_CASE       ,    f'''{MODEL_NAME}_{model_index}'''   )
                     os.makedirs(__SCREAMING_SNAKE_CASE       ,    exist_ok=__SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Saving model to {ckpt_dir}'''   )
                     lowerCamelCase__      :			Tuple 						= {"""model""": state_dict}

                     dist_cp.save_state_dict(
                         state_dict=__SCREAMING_SNAKE_CASE       ,    storage_writer=dist_cp.FileSystemWriter(__SCREAMING_SNAKE_CASE   )       ,    planner=DefaultSavePlanner()       ,    )
                     logger.info(f'''Model saved to {ckpt_dir}'''   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase=0   )   -> List[Any]:
       accelerator.wait_for_everyone()
       with FSDP.state_dict_type(
           __SCREAMING_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(__SCREAMING_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
                     lowerCamelCase__      :			Any 						= f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin'''
                     lowerCamelCase__      :			Dict 						= os.path.join(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Loading model from {input_model_file}'''   )
                     lowerCamelCase__      :			Any 						= torch.load(__SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Model loaded from {input_model_file}'''   )
              elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
                     lowerCamelCase__      :			int 						= (
                         f'''{MODEL_NAME}_rank{accelerator.process_index}.bin'''
                         if model_index == 0
                         else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'''
                     )
                     lowerCamelCase__      :			int 						= os.path.join(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Loading model from {input_model_file}'''   )
                     lowerCamelCase__      :			List[str] 						= torch.load(__SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Model loaded from {input_model_file}'''   )
              elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
                     lowerCamelCase__      :			Optional[int] 						= (
                         os.path.join(__SCREAMING_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}'''   )
                     lowerCamelCase__      :			str 						= {"""model""": model.state_dict()}
                     dist_cp.load_state_dict(
                         state_dict=__SCREAMING_SNAKE_CASE       ,    storage_reader=dist_cp.FileSystemReader(__SCREAMING_SNAKE_CASE   )       ,    planner=DefaultLoadPlanner()       ,    )
                     lowerCamelCase__      :			Tuple 						= state_dict["""model"""]
                     logger.info(f'''Model loaded from {ckpt_dir}'''   )
              model.load_state_dict(__SCREAMING_SNAKE_CASE   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase=0   )   -> Optional[Any]:
       os.makedirs(__SCREAMING_SNAKE_CASE       ,    exist_ok=__SCREAMING_SNAKE_CASE   )
       with FSDP.state_dict_type(
           __SCREAMING_SNAKE_CASE       ,    fsdp_plugin.state_dict_type       ,    fsdp_plugin.state_dict_config       ,    fsdp_plugin.optim_state_dict_config   ):
              lowerCamelCase__      :			List[Any] 						= FSDP.optim_state_dict(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
              if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
                     if accelerator.process_index == 0:
                            lowerCamelCase__      :			str 						= (
                                f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
                            )
                            lowerCamelCase__      :			List[str] 						= os.path.join(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                            logger.info(f'''Saving Optimizer state to {output_optimizer_file}'''   )
                            torch.save(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                            logger.info(f'''Optimizer state saved in {output_optimizer_file}'''   )
              else:
                     lowerCamelCase__      :			int 						= os.path.join(__SCREAMING_SNAKE_CASE       ,    f'''{OPTIMIZER_NAME}_{optimizer_index}'''   )
                     os.makedirs(__SCREAMING_SNAKE_CASE       ,    exist_ok=__SCREAMING_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(__SCREAMING_SNAKE_CASE   )       ,    planner=DefaultSavePlanner()       ,    )
                     logger.info(f'''Optimizer state saved in {ckpt_dir}'''   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase=0   )   -> Optional[Any]:
       accelerator.wait_for_everyone()
       with FSDP.state_dict_type(
           __SCREAMING_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:
                     lowerCamelCase__      :			Dict 						= 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:
                     lowerCamelCase__      :			List[str] 						= (
                         f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
                     )
                     lowerCamelCase__      :			str 						= os.path.join(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Loading Optimizer state from {input_optimizer_file}'''   )
                     lowerCamelCase__      :			str 						= torch.load(__SCREAMING_SNAKE_CASE   )
                     logger.info(f'''Optimizer state loaded from {input_optimizer_file}'''   )
              else:
                     lowerCamelCase__      :			Any 						= (
                         os.path.join(__SCREAMING_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}'''   )
                     lowerCamelCase__      :			Union[str, Any] 						= load_sharded_optimizer_state_dict(
                         model_state_dict=model.state_dict()       ,    optimizer_key="""optimizer"""       ,    storage_reader=dist_cp.FileSystemReader(__SCREAMING_SNAKE_CASE   )       ,    )
                     lowerCamelCase__      :			Optional[int] 						= optim_state["""optimizer"""]
                     logger.info(f'''Optimizer loaded from {ckpt_dir}'''   )
              lowerCamelCase__      :			Dict 						= FSDP.optim_state_dict_to_load(__SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE       ,    __SCREAMING_SNAKE_CASE   )
              optimizer.load_state_dict(__SCREAMING_SNAKE_CASE   )









'''simple docstring'''







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


_A			:    Any					  ={
    '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''],
    '''processing_trocr''': ['''TrOCRProcessor'''],
}


try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			_A			:    str					  =[
			    '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''',
			    '''TrOCRForCausalLM''',
			    '''TrOCRPreTrainedModel''',
			]


if TYPE_CHECKING:
			from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
			from .processing_trocr import TrOCRProcessor

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel

else:
			import sys

			_A			:    Dict					  =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)

