





import inspect
import unittest

from transformers import MobileViTConfig
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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
	from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import MobileViTImageProcessor



class    __lowerCAmelCase			(     _a	):






			def      lowerCamelCase    (self       )	->  Dict:


							'''simple docstring'''



							snake_case_		:       List[Any]           =    self.config_class(**self.inputs_dict       )
							self.parent.assertTrue(hasattr(__magic_name__   ,				'''hidden_sizes'''       )       )
							self.parent.assertTrue(hasattr(__magic_name__   ,				'''neck_hidden_sizes'''       )       )
							self.parent.assertTrue(hasattr(__magic_name__   ,				'''num_attention_heads'''       )       )




class    __lowerCAmelCase			:






			def __init__(self   ,				__magic_name__   ,				__magic_name__=13   ,				__magic_name__=32   ,				__magic_name__=2   ,				__magic_name__=3   ,				__magic_name__=640   ,				__magic_name__=4   ,				__magic_name__="silu"   ,				__magic_name__=3   ,				__magic_name__=32   ,				__magic_name__=0.1   ,				__magic_name__=0.1   ,				__magic_name__=0.1   ,				__magic_name__=0.02   ,				__magic_name__=True   ,				__magic_name__=True   ,				__magic_name__=10   ,				__magic_name__=None   ,				)	->  Tuple:


							'''simple docstring'''



							snake_case_		:       Union[str, Any]           =    parent
							snake_case_		:       str           =    batch_size
							snake_case_		:       Union[str, Any]           =    image_size
							snake_case_		:       Any           =    patch_size
							snake_case_		:       Union[str, Any]           =    num_channels
							snake_case_		:       Dict           =    last_hidden_size
							snake_case_		:       Dict           =    num_attention_heads
							snake_case_		:       str           =    hidden_act
							snake_case_		:       Optional[int]           =    conv_kernel_size
							snake_case_		:       str           =    output_stride
							snake_case_		:       int           =    hidden_dropout_prob
							snake_case_		:       Optional[Any]           =    attention_probs_dropout_prob
							snake_case_		:       Union[str, Any]           =    classifier_dropout_prob
							snake_case_		:       Any           =    use_labels
							snake_case_		:       Tuple           =    is_training
							snake_case_		:       Dict           =    num_labels
							snake_case_		:       Any           =    initializer_range
							snake_case_		:       List[Any]           =    scope






			def      lowerCamelCase    (self       )	->  Optional[int]:


							'''simple docstring'''



							snake_case_		:       Dict           =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

							snake_case_		:       Tuple           =    None
							snake_case_		:       Optional[int]           =    None
							if self.use_labels:
											snake_case_		:       Optional[int]           =    ids_tensor([self.batch_size]   ,				self.num_labels       )
											snake_case_		:       int           =    ids_tensor([self.batch_size, self.image_size, self.image_size]   ,				self.num_labels       )

							snake_case_		:       int           =    self.get_config()

							return config, pixel_values, labels, pixel_labels






			def      lowerCamelCase    (self       )	->  Union[str, Any]:


							'''simple docstring'''



							return MobileViTConfig(
							    image_size=self.image_size   ,				patch_size=self.patch_size   ,				num_channels=self.num_channels   ,				num_attention_heads=self.num_attention_heads   ,				hidden_act=self.hidden_act   ,				conv_kernel_size=self.conv_kernel_size   ,				output_stride=self.output_stride   ,				hidden_dropout_prob=self.hidden_dropout_prob   ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,				classifier_dropout_prob=self.classifier_dropout_prob   ,				initializer_range=self.initializer_range   ,				)






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  Union[str, Any]:


							'''simple docstring'''



							snake_case_		:       List[str]           =    MobileViTModel(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       Dict           =    model(__magic_name__       )
							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   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  str:


							'''simple docstring'''



							snake_case_		:       Any           =    self.num_labels
							snake_case_		:       Optional[int]           =    MobileViTForImageClassification(__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       Dict           =    model(__magic_name__   ,				labels=__magic_name__       )
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  Optional[int]:


							'''simple docstring'''



							snake_case_		:       str           =    self.num_labels
							snake_case_		:       int           =    MobileViTForSemanticSegmentation(__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       Dict           =    model(__magic_name__       )
							self.parent.assertEqual(
							    result.logits.shape   ,				(
							        self.batch_size,
							        self.num_labels,
							        self.image_size // self.output_stride,
							        self.image_size // self.output_stride,
							    )   ,				)
							snake_case_		:       List[Any]           =    model(__magic_name__   ,				labels=__magic_name__       )
							self.parent.assertEqual(
							    result.logits.shape   ,				(
							        self.batch_size,
							        self.num_labels,
							        self.image_size // self.output_stride,
							        self.image_size // self.output_stride,
							    )   ,				)






			def      lowerCamelCase    (self       )	->  Optional[int]:


							'''simple docstring'''



							snake_case_		:       Union[str, Any]           =    self.prepare_config_and_inputs()
							snake_case_     ,				snake_case_     ,				snake_case_     ,				snake_case_		:       List[str]           =    config_and_inputs
							snake_case_		:       int           =    {'''pixel_values''': pixel_values}
							return config, inputs_dict




@require_torch
class    __lowerCAmelCase			(     _a,	_a,	unittest.TestCase	):
			lowerCamelCase_	:	Tuple			     = (
			    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			lowerCamelCase_	:	Tuple			     = (
			    {
			        '''feature-extraction''': MobileViTModel,
			        '''image-classification''': MobileViTForImageClassification,
			        '''image-segmentation''': MobileViTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			lowerCamelCase_	:	Dict			     = False
			lowerCamelCase_	:	Optional[int]			     = False
			lowerCamelCase_	:	int			     = False
			lowerCamelCase_	:	int			     = False






			def      lowerCamelCase    (self       )	->  Optional[Any]:


							'''simple docstring'''



							snake_case_		:       Any           =    MobileViTModelTester(self       )
							snake_case_		:       int           =    MobileViTConfigTester(self   ,				config_class=__magic_name__   ,				has_text_modality=__magic_name__       )






			def      lowerCamelCase    (self       )	->  Tuple:


							'''simple docstring'''



							self.config_tester.run_common_tests()






			@unittest.skip(reason='''MobileViT does not use inputs_embeds'''       )
			def      lowerCamelCase    (self       )	->  Any:


							'''simple docstring'''



							pass






			@unittest.skip(reason='''MobileViT does not support input and output embeddings'''       )
			def      lowerCamelCase    (self       )	->  int:


							'''simple docstring'''



							pass






			@unittest.skip(reason='''MobileViT does not output attentions'''       )
			def      lowerCamelCase    (self       )	->  List[Any]:


							'''simple docstring'''



							pass






			def      lowerCamelCase    (self       )	->  List[Any]:


							'''simple docstring'''



							snake_case_     ,				snake_case_		:       Optional[Any]           =    self.model_tester.prepare_config_and_inputs_for_common()

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

											snake_case_		:       List[Any]           =    ['''pixel_values''']
											self.assertListEqual(arg_names[:1]   ,				__magic_name__       )






			@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''       )
			def      lowerCamelCase    (self       )	->  Tuple:


							'''simple docstring'''



							pass






			def      lowerCamelCase    (self       )	->  List[Any]:


							'''simple docstring'''



							snake_case_		:       List[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__magic_name__       )






			def      lowerCamelCase    (self       )	->  Union[str, Any]:


							'''simple docstring'''



							def check_hidden_states_output(__magic_name__   ,				__magic_name__   ,				__magic_name__       ):
											snake_case_		:       Optional[Any]           =    model_class(__magic_name__       )
											model.to(__magic_name__       )
											model.eval()

											with torch.no_grad():
															snake_case_		:       Optional[int]           =    model(**self._prepare_for_class(__magic_name__   ,				__magic_name__       )       )

											snake_case_		:       Tuple           =    outputs.hidden_states

											snake_case_		:       Tuple           =    5
											self.assertEqual(len(__magic_name__       )   ,				__magic_name__       )

											# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
											# with the width and height being successively divided by 2.
											snake_case_		:       str           =    2
											for i in range(len(__magic_name__       )       ):
															self.assertListEqual(
															    list(hidden_states[i].shape[-2:]       )   ,				[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]   ,				)
															divisor *= 2

											self.assertEqual(self.model_tester.output_stride   ,				divisor // 2       )

							snake_case_     ,				snake_case_		:       int           =    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											snake_case_		:       int           =    True
											check_hidden_states_output(__magic_name__   ,				__magic_name__   ,				__magic_name__       )

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

											check_hidden_states_output(__magic_name__   ,				__magic_name__   ,				__magic_name__       )






			def      lowerCamelCase    (self       )	->  Optional[int]:


							'''simple docstring'''



							snake_case_		:       Any           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__magic_name__       )






			def      lowerCamelCase    (self       )	->  Optional[int]:


							'''simple docstring'''



							snake_case_		:       List[str]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*__magic_name__       )






			@slow
			def      lowerCamelCase    (self       )	->  Tuple:


							'''simple docstring'''



							for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											snake_case_		:       str           =    MobileViTModel.from_pretrained(__magic_name__       )
											self.assertIsNotNone(__magic_name__       )






def 	lowerCamelCase_		(							)						->		Tuple:






				"""simple docstring"""


				snake_case_		:       Dict           =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
				return image





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






			@cached_property
			def      lowerCamelCase    (self       )	->  Union[str, Any]:


							'''simple docstring'''



							return MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''       ) if is_vision_available() else None






			@slow
			def      lowerCamelCase    (self       )	->  Any:


							'''simple docstring'''



							snake_case_		:       List[str]           =    MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''       ).to(__magic_name__       )

							snake_case_		:       List[Any]           =    self.default_image_processor
							snake_case_		:       Dict           =    prepare_img()
							snake_case_		:       Optional[int]           =    image_processor(images=__magic_name__   ,				return_tensors='''pt'''       ).to(__magic_name__       )

							# forward pass
							with torch.no_grad():
											snake_case_		:       Union[str, Any]           =    model(**__magic_name__       )

							# verify the logits
							snake_case_		:       Dict           =    torch.Size((1, 1000)       )
							self.assertEqual(outputs.logits.shape   ,				__magic_name__       )

							snake_case_		:       str           =    torch.tensor([-1.9_364, -1.2_327, -0.4_653]       ).to(__magic_name__       )

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






			@slow
			def      lowerCamelCase    (self       )	->  Union[str, Any]:


							'''simple docstring'''



							snake_case_		:       Optional[int]           =    MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''       )
							snake_case_		:       str           =    model.to(__magic_name__       )

							snake_case_		:       Optional[Any]           =    MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''       )

							snake_case_		:       Any           =    prepare_img()
							snake_case_		:       Optional[Any]           =    image_processor(images=__magic_name__   ,				return_tensors='''pt'''       ).to(__magic_name__       )

							# forward pass
							with torch.no_grad():
											snake_case_		:       Optional[int]           =    model(**__magic_name__       )
							snake_case_		:       Optional[Any]           =    outputs.logits

							# verify the logits
							snake_case_		:       List[Any]           =    torch.Size((1, 21, 32, 32)       )
							self.assertEqual(logits.shape   ,				__magic_name__       )

							snake_case_		:       List[str]           =    torch.tensor(
							    [
							        [[6.9_713, 6.9_786, 7.2_422], [7.2_893, 7.2_825, 7.4_446], [7.6_580, 7.8_797, 7.9_420]],
							        [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_868, -9.7_132], [-11.0_405, -11.0_221, -10.7_318]],
							        [[-3.3_089, -2.8_539, -2.6_740], [-3.2_706, -2.5_621, -2.5_108], [-3.2_534, -2.6_615, -2.6_651]],
							    ]   ,				device=__magic_name__   ,				)

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






			@slow
			def      lowerCamelCase    (self       )	->  List[str]:


							'''simple docstring'''



							snake_case_		:       int           =    MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''       )
							snake_case_		:       Any           =    model.to(__magic_name__       )

							snake_case_		:       int           =    MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''       )

							snake_case_		:       List[Any]           =    prepare_img()
							snake_case_		:       str           =    image_processor(images=__magic_name__   ,				return_tensors='''pt'''       ).to(__magic_name__       )

							# forward pass
							with torch.no_grad():
											snake_case_		:       str           =    model(**__magic_name__       )

							snake_case_		:       str           =    outputs.logits.detach().cpu()

							snake_case_		:       List[str]           =    image_processor.post_process_semantic_segmentation(outputs=__magic_name__   ,				target_sizes=[(50, 60)]       )
							snake_case_		:       List[Any]           =    torch.Size((50, 60)       )
							self.assertEqual(segmentation[0].shape   ,				__magic_name__       )

							snake_case_		:       List[str]           =    image_processor.post_process_semantic_segmentation(outputs=__magic_name__       )
							snake_case_		:       Tuple           =    torch.Size((32, 32)       )
							self.assertEqual(segmentation[0].shape   ,				__magic_name__       )




# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import platform

import numpy as np
import psutil
import torch

from accelerate import __version__ as version
from accelerate.commands.config import default_config_file, load_config_from_file

from ..utils import is_npu_available, is_xpu_available




def       a_ (       SCREAMING_SNAKE_CASE__   : str=None	):
       '''simple docstring'''





       if subparsers is not None:
              _lowerCamelCase			:						str            =subparsers.add_parser('env'	)
       else:
              _lowerCamelCase			:						List[Any]            =argparse.ArgumentParser('Accelerate env command'	)

       parser.add_argument(
           '--config_file'						,     default=SCREAMING_SNAKE_CASE__						,     help='The config file to use for the default values in the launching script.'	)

       if subparsers is not None:
              parser.set_defaults(func=SCREAMING_SNAKE_CASE__	)
       return parser




def       a_ (       SCREAMING_SNAKE_CASE__   : int	):
       '''simple docstring'''





       _lowerCamelCase			:						int            =torch.__version__
       _lowerCamelCase			:						Optional[Any]            =torch.cuda.is_available()
       _lowerCamelCase			:						int            =is_xpu_available()
       _lowerCamelCase			:						Union[str, Any]            =is_npu_available()

       _lowerCamelCase			:						Optional[int]            ='Not found'
       # Get the default from the config file.
       if args.config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE__	):
              _lowerCamelCase			:						Any            =load_config_from_file(args.config_file	).to_dict()

       _lowerCamelCase			:						List[str]            ={
           '`Accelerate` version': version,
           'Platform': platform.platform(),
           'Python version': platform.python_version(),
           'Numpy version': np.__version__,
           'PyTorch version (GPU?)': F'''{pt_version} ({pt_cuda_available})''',
           'PyTorch XPU available': str(SCREAMING_SNAKE_CASE__	),
           'PyTorch NPU available': str(SCREAMING_SNAKE_CASE__	),
           'System RAM': F'''{psutil.virtual_memory().total / 1_024 ** 3:.2f} GB''',
       }
       if pt_cuda_available:
              _lowerCamelCase			:						List[Any]            =torch.cuda.get_device_name()

       print('\nCopy-and-paste the text below in your GitHub issue\n'	)
       print('\n'.join([F'''- {prop}: {val}''' for prop, val in info.items()]	)	)

       print('- `Accelerate` default config:' if args.config_file is None else '- `Accelerate` config passed:'	)
       _lowerCamelCase			:						Dict            =(
           '\n'.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]	)
           if isinstance(SCREAMING_SNAKE_CASE__						,     SCREAMING_SNAKE_CASE__	)
           else F'''\t{accelerate_config}'''
       )
       print(SCREAMING_SNAKE_CASE__	)

       _lowerCamelCase			:						str            =accelerate_config

       return info




def       a_ (       ):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =env_command_parser()
       _lowerCamelCase			:						Any            =parser.parse_args()
       env_command(SCREAMING_SNAKE_CASE__	)
       return 0


if __name__ == "__main__":
 raise SystemExit(main())


