



"""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        snake_case_  (      A_					:		Dict,				A_					:		Optional[Any],				A_					:		List[str],				A_					:		Tuple,				A_					:		List[Any]=0						):


       '''simple docstring'''





       os.makedirs(A_,				exist_ok=A_						)
       with FSDP.state_dict_type(
           A_,				fsdp_plugin.state_dict_type,				fsdp_plugin.state_dict_config,				fsdp_plugin.optim_state_dict_config						):
              _lowerCamelCase						:				Any    			= model.state_dict()
              if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
                     _lowerCamelCase						:				Union[str, Any]    			= F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin'''
                     _lowerCamelCase						:				Tuple    			= os.path.join(A_,				A_						)
                     if accelerator.process_index == 0:
                            logger.info(F'''Saving model to {output_model_file}'''						)
                            torch.save(A_,				A_						)
                            logger.info(F'''Model saved to {output_model_file}'''						)
              elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
                     _lowerCamelCase						:				Optional[Any]    			= (
                         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(A_,				A_						)
                     logger.info(F'''Saving model to {output_model_file}'''						)
                     torch.save(A_,				A_						)
                     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(A_,				F'''{MODEL_NAME}_{model_index}'''						)
                     os.makedirs(A_,				exist_ok=A_						)
                     logger.info(F'''Saving model to {ckpt_dir}'''						)
                     _lowerCamelCase						:				Tuple    			= {'''model''': state_dict}

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






def        snake_case_  (      A_					:		Optional[int],				A_					:		Union[str, Any],				A_					:		List[Any],				A_					:		Union[str, Any],				A_					:		Optional[int]=0						):


       '''simple docstring'''





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






def        snake_case_  (      A_					:		Any,				A_					:		Union[str, Any],				A_					:		int,				A_					:		Optional[Any],				A_					:		int,				A_					:		Tuple=0						):


       '''simple docstring'''





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







def        snake_case_  (      A_					:		Tuple,				A_					:		Dict,				A_					:		Any,				A_					:		Optional[int],				A_					:		List[str],				A_					:		List[Any]=0						):


       '''simple docstring'''





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










'''simple docstring'''







import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import MobileNetVaForImageClassification, MobileNetVaModel
			from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import MobileNetVaImageProcessor

class _lowercase	(				_lowercase		):




							def 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__					:	str         =       self.config_class(**self.inputs_dict     )
														self.parent.assertTrue(hasattr(UpperCamelCase__			,							"""tf_padding"""     )     )
														self.parent.assertTrue(hasattr(UpperCamelCase__			,							"""depth_multiplier"""     )     )



class _lowercase	:




							def __init__(							self:				str			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				Tuple=13			,							UpperCamelCase__:				Optional[int]=3			,							UpperCamelCase__:				List[Any]=32			,							UpperCamelCase__:				Optional[Any]=0.25			,							UpperCamelCase__:				int=8			,							UpperCamelCase__:				Any=True			,							UpperCamelCase__:				Dict=1_024			,							UpperCamelCase__:				Optional[int]=32			,							UpperCamelCase__:				Tuple="relu6"			,							UpperCamelCase__:				int=0.1			,							UpperCamelCase__:				List[Any]=0.02			,							UpperCamelCase__:				Optional[Any]=True			,							UpperCamelCase__:				Union[str, Any]=True			,							UpperCamelCase__:				Union[str, Any]=10			,							UpperCamelCase__:				str=None			,							):
														lowerCamelCase__					:	Optional[Any]         =       parent
														lowerCamelCase__					:	List[str]         =       batch_size
														lowerCamelCase__					:	Optional[int]         =       num_channels
														lowerCamelCase__					:	Optional[int]         =       image_size
														lowerCamelCase__					:	Optional[Any]         =       depth_multiplier
														lowerCamelCase__					:	Union[str, Any]         =       min_depth
														lowerCamelCase__					:	Optional[Any]         =       tf_padding
														lowerCamelCase__					:	str         =       int(last_hidden_size * depth_multiplier     )
														lowerCamelCase__					:	Any         =       output_stride
														lowerCamelCase__					:	int         =       hidden_act
														lowerCamelCase__					:	Tuple         =       classifier_dropout_prob
														lowerCamelCase__					:	Dict         =       use_labels
														lowerCamelCase__					:	Tuple         =       is_training
														lowerCamelCase__					:	Optional[Any]         =       num_labels
														lowerCamelCase__					:	Union[str, Any]         =       initializer_range
														lowerCamelCase__					:	Optional[Any]         =       scope




							def 		lowerCamelCase_				(							self:				List[str]     ):
														lowerCamelCase__					:	Optional[Any]         =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

														lowerCamelCase__					:	Optional[Any]         =       None
														lowerCamelCase__					:	Dict         =       None
														if self.use_labels:
																					lowerCamelCase__					:	Union[str, Any]         =       ids_tensor([self.batch_size]			,							self.num_labels     )
																					lowerCamelCase__					:	Dict         =       ids_tensor([self.batch_size, self.image_size, self.image_size]			,							self.num_labels     )

														lowerCamelCase__					:	Dict         =       self.get_config()

														return config, pixel_values, labels, pixel_labels




							def 		lowerCamelCase_				(							self:				str     ):
														return MobileNetVaConfig(
														    num_channels=self.num_channels			,							image_size=self.image_size			,							depth_multiplier=self.depth_multiplier			,							min_depth=self.min_depth			,							tf_padding=self.tf_padding			,							hidden_act=self.hidden_act			,							classifier_dropout_prob=self.classifier_dropout_prob			,							initializer_range=self.initializer_range			,							)




							def 		lowerCamelCase_				(							self:				Tuple			,							UpperCamelCase__:				int			,							UpperCamelCase__:				str			,							UpperCamelCase__:				Any			,							UpperCamelCase__:				Optional[int]     ):
														lowerCamelCase__					:	List[str]         =       MobileNetVaModel(config=UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()
														lowerCamelCase__					:	List[str]         =       model(UpperCamelCase__     )
														self.parent.assertEqual(
														    result.last_hidden_state.shape			,							(
														        self.batch_size,
														        self.last_hidden_size,
														        self.image_size // self.output_stride,
														        self.image_size // self.output_stride,
														    )			,							)




							def 		lowerCamelCase_				(							self:				str			,							UpperCamelCase__:				Tuple			,							UpperCamelCase__:				Optional[int]			,							UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				Union[str, Any]     ):
														lowerCamelCase__					:	List[str]         =       self.num_labels
														lowerCamelCase__					:	Optional[Any]         =       MobileNetVaForImageClassification(UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()
														lowerCamelCase__					:	List[Any]         =       model(UpperCamelCase__			,							labels=UpperCamelCase__     )
														self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)     )




							def 		lowerCamelCase_				(							self:				Optional[Any]     ):
														lowerCamelCase__					:	str         =       self.prepare_config_and_inputs()
														lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	int         =       config_and_inputs
														lowerCamelCase__					:	Optional[int]         =       {"""pixel_values""": pixel_values}
														return config, inputs_dict



@require_torch
class _lowercase	(				_lowercase				,      _lowercase				,      unittest.TestCase		):
							a				      =       (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
							a				      =       (
							    {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
							    if is_torch_available()
							    else {}
							)

							a				      =       False
							a				      =       False
							a				      =       False
							a				      =       False




							def 		lowerCamelCase_				(							self:				List[str]     ):
														lowerCamelCase__					:	Optional[int]         =       MobileNetVaModelTester(self     )
														lowerCamelCase__					:	List[str]         =       MobileNetVaConfigTester(self			,							config_class=UpperCamelCase__			,							has_text_modality=UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														self.config_tester.run_common_tests()




							@unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""     )
							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														pass




							@unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""     )
							def 		lowerCamelCase_				(							self:				Optional[Any]     ):
														pass




							@unittest.skip(reason="""MobileNetV1 does not output attentions"""     )
							def 		lowerCamelCase_				(							self:				Any     ):
														pass




							def 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	Optional[Any]         =       self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__					:	Dict         =       model_class(UpperCamelCase__     )
																					lowerCamelCase__					:	Dict         =       inspect.signature(model.forward     )
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					lowerCamelCase__					:	List[Any]         =       [*signature.parameters.keys()]

																					lowerCamelCase__					:	Dict         =       ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__					:	Tuple         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				str     ):
														def check_hidden_states_output(UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				List[Any]     ):
																					lowerCamelCase__					:	str         =       model_class(UpperCamelCase__     )
																					model.to(UpperCamelCase__     )
																					model.eval()

																					with torch.no_grad():
																												lowerCamelCase__					:	Union[str, Any]         =       model(**self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__     )     )

																					lowerCamelCase__					:	List[Any]         =       outputs.hidden_states

																					lowerCamelCase__					:	Tuple         =       26
																					self.assertEqual(len(UpperCamelCase__     )			,							UpperCamelCase__     )

														lowerCamelCase__  ,		lowerCamelCase__					:	List[str]         =       self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__					:	List[Any]         =       True
																					check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__     )

																					# check that output_hidden_states also work using config
																					del inputs_dict["output_hidden_states"]
																					lowerCamelCase__					:	Optional[Any]         =       True

																					check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	int         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__     )




							@slow
							def 		lowerCamelCase_				(							self:				List[str]     ):
														for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__					:	Dict         =       MobileNetVaModel.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )





def  SCREAMING_SNAKE_CASE_       ()      ->       Union[str, Any]:
							lowerCamelCase__					:	Optional[int]         =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
							return image



@require_torch
@require_vision
class _lowercase	(				unittest.TestCase		):




							@cached_property
							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														return (
														    MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224"""     ) if is_vision_available() else None
														)




							@slow
							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	List[Any]         =       MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""     ).to(UpperCamelCase__     )

														lowerCamelCase__					:	Dict         =       self.default_image_processor
														lowerCamelCase__					:	int         =       prepare_img()
														lowerCamelCase__					:	List[Any]         =       image_processor(images=UpperCamelCase__			,							return_tensors="""pt"""     ).to(UpperCamelCase__     )

														# forward pass
														with torch.no_grad():
																					lowerCamelCase__					:	str         =       model(**UpperCamelCase__     )

														# verify the logits
														lowerCamelCase__					:	List[str]         =       torch.Size((1, 1_001)     )
														self.assertEqual(outputs.logits.shape			,							UpperCamelCase__     )

														lowerCamelCase__					:	List[str]         =       torch.tensor([-4.1_739, -1.1_233, 3.1_205]     ).to(UpperCamelCase__     )

														self.assertTrue(torch.allclose(outputs.logits[0, :3]			,							UpperCamelCase__			,							atol=1e-4     )     )

