



'''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, MobileNetVaForSemanticSegmentation, MobileNetVaModel
						from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import MobileNetVaImageProcessor

class        SCREAMING_SNAKE_CASE(							A__    ):







	"""simple docstring"""






	def   A			(		self    :  Optional[Any]	)    ->	Any:
								UpperCAmelCase				: int											=	self.config_class(**self.inputs_dict	)
								self.parent.assertTrue(hasattr(__snake_case	,    '''tf_padding'''	)	)
								self.parent.assertTrue(hasattr(__snake_case	,    '''depth_multiplier'''	)	)

class        SCREAMING_SNAKE_CASE:







	"""simple docstring"""






	def __init__(		self    :  Optional[Any]	,    __snake_case    :  Any	,    __snake_case    :  List[str]=13	,    __snake_case    :  Optional[int]=3	,    __snake_case    :  Optional[int]=32	,    __snake_case    :  Dict=0.25	,    __snake_case    :  int=8	,    __snake_case    :  Optional[Any]=8	,    __snake_case    :  Optional[int]=6	,    __snake_case    :  Any=32	,    __snake_case    :  Dict=True	,    __snake_case    :  Optional[Any]=True	,    __snake_case    :  Optional[Any]=True	,    __snake_case    :  str="relu6"	,    __snake_case    :  Optional[int]=1280	,    __snake_case    :  str=0.1	,    __snake_case    :  Tuple=0.02	,    __snake_case    :  Dict=True	,    __snake_case    :  Any=True	,    __snake_case    :  List[Any]=10	,    __snake_case    :  str=None	,    )    ->	Tuple:
								UpperCAmelCase				: str											=	parent
								UpperCAmelCase				: Optional[int]											=	batch_size
								UpperCAmelCase				: Optional[int]											=	num_channels
								UpperCAmelCase				: Tuple											=	image_size
								UpperCAmelCase				: Optional[int]											=	depth_multiplier
								UpperCAmelCase				: Optional[Any]											=	depth_divisible_by
								UpperCAmelCase				: Optional[Any]											=	min_depth
								UpperCAmelCase				: str											=	expand_ratio
								UpperCAmelCase				: Dict											=	tf_padding
								UpperCAmelCase				: List[str]											=	output_stride
								UpperCAmelCase				: Dict											=	first_layer_is_expansion
								UpperCAmelCase				: Tuple											=	finegrained_output
								UpperCAmelCase				: Tuple											=	hidden_act
								UpperCAmelCase				: Optional[Any]											=	last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier	)
								UpperCAmelCase				: Tuple											=	classifier_dropout_prob
								UpperCAmelCase				: Optional[Any]											=	use_labels
								UpperCAmelCase				: List[Any]											=	is_training
								UpperCAmelCase				: str											=	num_labels
								UpperCAmelCase				: int											=	initializer_range
								UpperCAmelCase				: Dict											=	scope







	def   A			(		self    :  Tuple	)    ->	Dict:
								UpperCAmelCase				: List[Any]											=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

								UpperCAmelCase				: Tuple											=	self.get_config()

								return config, pixel_values, labels, pixel_labels







	def   A			(		self    :  int	)    ->	Dict:
								return MobileNetVaConfig(
								    num_channels=self.num_channels	,    image_size=self.image_size	,    depth_multiplier=self.depth_multiplier	,    depth_divisible_by=self.depth_divisible_by	,    min_depth=self.min_depth	,    expand_ratio=self.expand_ratio	,    output_stride=self.output_stride	,    first_layer_is_expansion=self.first_layer_is_expansion	,    finegrained_output=self.finegrained_output	,    hidden_act=self.hidden_act	,    tf_padding=self.tf_padding	,    classifier_dropout_prob=self.classifier_dropout_prob	,    initializer_range=self.initializer_range	,    )







	def   A			(		self    :  Optional[Any]	,    __snake_case    :  Union[str, Any]	,    __snake_case    :  Union[str, Any]	,    __snake_case    :  List[Any]	,    __snake_case    :  List[Any]	)    ->	Any:
								UpperCAmelCase				: int											=	MobileNetVaModel(config=__snake_case	)
								model.to(__snake_case	)
								model.eval()
								UpperCAmelCase				: str											=	model(__snake_case	)
								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,
								    )	,    )
								self.parent.assertEqual(
								    result.pooler_output.shape	,    (self.batch_size, self.last_hidden_size)	,    )







	def   A			(		self    :  str	,    __snake_case    :  Union[str, Any]	,    __snake_case    :  List[str]	,    __snake_case    :  str	,    __snake_case    :  Union[str, Any]	)    ->	Optional[int]:
								UpperCAmelCase				: Dict											=	self.num_labels
								UpperCAmelCase				: Tuple											=	MobileNetVaForImageClassification(__snake_case	)
								model.to(__snake_case	)
								model.eval()
								UpperCAmelCase				: str											=	model(__snake_case	,    labels=__snake_case	)
								self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels)	)







	def   A			(		self    :  str	,    __snake_case    :  Union[str, Any]	,    __snake_case    :  Dict	,    __snake_case    :  Optional[int]	,    __snake_case    :  List[str]	)    ->	int:
								UpperCAmelCase				: int											=	self.num_labels
								UpperCAmelCase				: Any											=	MobileNetVaForSemanticSegmentation(__snake_case	)
								model.to(__snake_case	)
								model.eval()
								UpperCAmelCase				: List[str]											=	model(__snake_case	)
								self.parent.assertEqual(
								    result.logits.shape	,    (
								        self.batch_size,
								        self.num_labels,
								        self.image_size // self.output_stride,
								        self.image_size // self.output_stride,
								    )	,    )
								UpperCAmelCase				: int											=	model(__snake_case	,    labels=__snake_case	)
								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   A			(		self    :  List[Any]	)    ->	List[Any]:
								UpperCAmelCase				: List[Any]											=	self.prepare_config_and_inputs()
								UpperCAmelCase							,	UpperCAmelCase							,	UpperCAmelCase							,	UpperCAmelCase				: Optional[Any]											=	config_and_inputs
								UpperCAmelCase				: Any											=	{'''pixel_values''': pixel_values}
								return config, inputs_dict

@require_torch
class        SCREAMING_SNAKE_CASE(							A__							,	A__							,	unittest.TestCase    ):







	"""simple docstring"""






	lowerCamelCase__    				= (
	    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
	    if is_torch_available()
	    else ()
	)
	lowerCamelCase__    				= (
	    {
	        """feature-extraction""": MobileNetVaModel,
	        """image-classification""": MobileNetVaForImageClassification,
	        """image-segmentation""": MobileNetVaForSemanticSegmentation,
	    }
	    if is_torch_available()
	    else {}
	)

	lowerCamelCase__    				= False
	lowerCamelCase__    				= False
	lowerCamelCase__    				= False
	lowerCamelCase__    				= False







	def   A			(		self    :  List[Any]	)    ->	Optional[Any]:
								UpperCAmelCase				: Dict											=	MobileNetVaModelTester(self	)
								UpperCAmelCase				: str											=	MobileNetVaConfigTester(self	,    config_class=__snake_case	,    has_text_modality=__snake_case	)







	def   A			(		self    :  Union[str, Any]	)    ->	Tuple:
								self.config_tester.run_common_tests()







	@unittest.skip(reason='''MobileNetV2 does not use inputs_embeds'''	)
	def   A			(		self    :  int	)    ->	Union[str, Any]:
								pass







	@unittest.skip(reason='''MobileNetV2 does not support input and output embeddings'''	)
	def   A			(		self    :  int	)    ->	Tuple:
								pass







	@unittest.skip(reason='''MobileNetV2 does not output attentions'''	)
	def   A			(		self    :  Dict	)    ->	Dict:
								pass







	def   A			(		self    :  Union[str, Any]	)    ->	Optional[int]:
								UpperCAmelCase							,	UpperCAmelCase				: int											=	self.model_tester.prepare_config_and_inputs_for_common()

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

															UpperCAmelCase				: Dict											=	['''pixel_values''']
															self.assertListEqual(arg_names[:1]	,    __snake_case	)







	def   A			(		self    :  str	)    ->	List[Any]:
								UpperCAmelCase				: Any											=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__snake_case	)







	def   A			(		self    :  Dict	)    ->	Optional[Any]:
								def check_hidden_states_output(__snake_case    :  Dict	,    __snake_case    :  List[Any]	,    __snake_case    :  Optional[int]	):
															UpperCAmelCase				: str											=	model_class(__snake_case	)
															model.to(__snake_case	)
															model.eval()

															with torch.no_grad():
																						UpperCAmelCase				: Optional[Any]											=	model(**self._prepare_for_class(__snake_case	,    __snake_case	)	)

															UpperCAmelCase				: Optional[Any]											=	outputs.hidden_states

															UpperCAmelCase				: List[str]											=	16
															self.assertEqual(len(__snake_case	)	,    __snake_case	)

								UpperCAmelCase							,	UpperCAmelCase				: Union[str, Any]											=	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase				: Dict											=	True
															check_hidden_states_output(__snake_case	,    __snake_case	,    __snake_case	)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															UpperCAmelCase				: Tuple											=	True

															check_hidden_states_output(__snake_case	,    __snake_case	,    __snake_case	)







	def   A			(		self    :  str	)    ->	int:
								UpperCAmelCase				: List[str]											=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__snake_case	)







	def   A			(		self    :  Optional[int]	)    ->	Dict:
								UpperCAmelCase				: List[Any]											=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*__snake_case	)







	@slow
	def   A			(		self    :  Tuple	)    ->	str:
								for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase				: int											=	MobileNetVaModel.from_pretrained(__snake_case	)
															self.assertIsNotNone(__snake_case	)


def 				snake_case_  (      )   ->     Optional[Any]:
							UpperCAmelCase				: Dict											=	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
							return image




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







	"""simple docstring"""






	@cached_property
	def   A			(		self    :  Any	)    ->	Any:
								return (
								    MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224'''	) if is_vision_available() else None
								)







	@slow
	def   A			(		self    :  Optional[int]	)    ->	Optional[Any]:
								UpperCAmelCase				: List[str]											=	MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224'''	).to(__snake_case	)

								UpperCAmelCase				: Any											=	self.default_image_processor
								UpperCAmelCase				: Union[str, Any]											=	prepare_img()
								UpperCAmelCase				: int											=	image_processor(images=__snake_case	,    return_tensors='''pt'''	).to(__snake_case	)

								# forward pass
								with torch.no_grad():
															UpperCAmelCase				: Optional[int]											=	model(**__snake_case	)

								# verify the logits
								UpperCAmelCase				: List[Any]											=	torch.Size((1, 1001)	)
								self.assertEqual(outputs.logits.shape	,    __snake_case	)

								UpperCAmelCase				: Optional[Any]											=	torch.tensor([0.24_45, -1.19_93, 0.19_05]	).to(__snake_case	)

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







	@slow
	def   A			(		self    :  Optional[int]	)    ->	Tuple:
								UpperCAmelCase				: Tuple											=	MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''	)
								UpperCAmelCase				: List[Any]											=	model.to(__snake_case	)

								UpperCAmelCase				: Optional[Any]											=	MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''	)

								UpperCAmelCase				: Dict											=	prepare_img()
								UpperCAmelCase				: Union[str, Any]											=	image_processor(images=__snake_case	,    return_tensors='''pt'''	).to(__snake_case	)

								# forward pass
								with torch.no_grad():
															UpperCAmelCase				: int											=	model(**__snake_case	)
								UpperCAmelCase				: Optional[int]											=	outputs.logits

								# verify the logits
								UpperCAmelCase				: Optional[int]											=	torch.Size((1, 21, 65, 65)	)
								self.assertEqual(logits.shape	,    __snake_case	)

								UpperCAmelCase				: Any											=	torch.tensor(
								    [
								        [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]],
								        [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
								        [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
								    ]	,    device=__snake_case	,    )

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










'''simple docstring'''






import contextlib
import os
import sqlitea

import pytest

from datasets import Dataset, Features, Value
from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy


def 				snake_case_  (      _lowerCAmelCase						:		int     ,   _lowerCAmelCase						:		Tuple						)   ->     str:
							assert isinstance(_lowerCAmelCase     ,   _lowerCAmelCase						)
							assert dataset.num_rows == 4
							assert dataset.num_columns == 3
							assert dataset.column_names == ["col_1", "col_2", "col_3"]
							for feature, expected_dtype in expected_features.items():
														assert dataset.features[feature].dtype == expected_dtype


@require_sqlalchemy
@pytest.mark.parametrize('''keep_in_memory'''     ,   [False, True]						)
def 				snake_case_  (      _lowerCAmelCase						:		Union[str, Any]     ,   _lowerCAmelCase						:		List[str]     ,   _lowerCAmelCase						:		Any     ,   _lowerCAmelCase						:		Optional[Any]						)   ->     List[str]:
							UpperCAmelCase				: int											=	tmp_path / '''cache'''
							UpperCAmelCase				: Dict											=	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
							with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
														UpperCAmelCase				: Any											=	SqlDatasetReader(
														    '''dataset'''     ,   '''sqlite:///''' + sqlite_path     ,   cache_dir=_lowerCAmelCase     ,   keep_in_memory=_lowerCAmelCase						).read()
							_check_sql_dataset(_lowerCAmelCase     ,   _lowerCAmelCase						)


@require_sqlalchemy
@pytest.mark.parametrize(
    '''features'''     ,   [
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ]     ,   )
def 				snake_case_  (      _lowerCAmelCase						:		int     ,   _lowerCAmelCase						:		Any     ,   _lowerCAmelCase						:		Optional[int]     ,   _lowerCAmelCase						:		str						)   ->     Optional[int]:
							UpperCAmelCase				: Union[str, Any]											=	tmp_path / '''cache'''
							UpperCAmelCase				: Union[str, Any]											=	{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
							UpperCAmelCase				: str											=	features.copy() if features else default_expected_features
							UpperCAmelCase				: Optional[Any]											=	(
							    Features({feature: Value(_lowerCAmelCase						) for feature, dtype in features.items()}						) if features is not None else None
							)
							UpperCAmelCase				: Tuple											=	SqlDatasetReader('''dataset'''     ,   '''sqlite:///''' + sqlite_path     ,   features=_lowerCAmelCase     ,   cache_dir=_lowerCAmelCase						).read()
							_check_sql_dataset(_lowerCAmelCase     ,   _lowerCAmelCase						)


def 				snake_case_  (      _lowerCAmelCase						:		List[Any]						)   ->     Dict:
							with contextlib.closing(sqlitea.connect(_lowerCAmelCase						)						) as con:
														UpperCAmelCase				: Any											=	con.cursor()
														cur.execute('''SELECT * FROM dataset'''						)
														for row in cur:
																					yield row


@require_sqlalchemy
def 				snake_case_  (      _lowerCAmelCase						:		Union[str, Any]     ,   _lowerCAmelCase						:		str     ,   _lowerCAmelCase						:		Any						)   ->     Optional[int]:
							UpperCAmelCase				: Optional[int]											=	tmp_path / '''cache'''
							UpperCAmelCase				: int											=	os.path.join(_lowerCAmelCase     ,   '''tmp.sql'''						)
							UpperCAmelCase				: Any											=	SqlDatasetReader('''dataset'''     ,   '''sqlite:///''' + sqlite_path     ,   cache_dir=_lowerCAmelCase						).read()
							SqlDatasetWriter(_lowerCAmelCase     ,   '''dataset'''     ,   '''sqlite:///''' + output_sqlite_path     ,   num_proc=1						).write()

							UpperCAmelCase				: List[Any]											=	iter_sql_file(_lowerCAmelCase						)
							UpperCAmelCase				: List[Any]											=	iter_sql_file(_lowerCAmelCase						)

							for rowa, rowa in zip(_lowerCAmelCase     ,   _lowerCAmelCase						):
														assert rowa == rowa


@require_sqlalchemy
def 				snake_case_  (      _lowerCAmelCase						:		int     ,   _lowerCAmelCase						:		Optional[Any]     ,   _lowerCAmelCase						:		Union[str, Any]						)   ->     int:
							UpperCAmelCase				: Optional[Any]											=	tmp_path / '''cache'''
							UpperCAmelCase				: Any											=	os.path.join(_lowerCAmelCase     ,   '''tmp.sql'''						)
							UpperCAmelCase				: List[str]											=	SqlDatasetReader('''dataset'''     ,   '''sqlite:///''' + sqlite_path     ,   cache_dir=_lowerCAmelCase						).read()
							SqlDatasetWriter(_lowerCAmelCase     ,   '''dataset'''     ,   '''sqlite:///''' + output_sqlite_path     ,   num_proc=2						).write()

							UpperCAmelCase				: List[str]											=	iter_sql_file(_lowerCAmelCase						)
							UpperCAmelCase				: Any											=	iter_sql_file(_lowerCAmelCase						)

							for rowa, rowa in zip(_lowerCAmelCase     ,   _lowerCAmelCase						):
														assert rowa == rowa




@require_sqlalchemy
def 				snake_case_  (      _lowerCAmelCase						:		Union[str, Any]     ,   _lowerCAmelCase						:		Any     ,   _lowerCAmelCase						:		Optional[Any]						)   ->     List[Any]:
							UpperCAmelCase				: Union[str, Any]											=	tmp_path / '''cache'''
							UpperCAmelCase				: Tuple											=	os.path.join(_lowerCAmelCase     ,   '''tmp.sql'''						)
							UpperCAmelCase				: Optional[int]											=	SqlDatasetReader('''dataset'''     ,   '''sqlite:///''' + sqlite_path     ,   cache_dir=_lowerCAmelCase						).read()
							with pytest.raises(_lowerCAmelCase						):
														SqlDatasetWriter(_lowerCAmelCase     ,   '''dataset'''     ,   '''sqlite:///''' + output_sqlite_path     ,   num_proc=0						).write()





