"""simple docstring"""
import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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 (
					    MODEL_MAPPING,
					    SegformerForImageClassification,
					    SegformerForSemanticSegmentation,
					    SegformerModel,
					)
					from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import SegformerImageProcessor



class      lowerCAmelCase_			(	lowerCAmelCase    ):



				"""simple docstring"""

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.config_class(**self.inputs_dict			)
										self.parent.assertTrue(hasattr(_a						,			'hidden_sizes'			)			)
										self.parent.assertTrue(hasattr(_a						,			'num_attention_heads'			)			)
										self.parent.assertTrue(hasattr(_a						,			'num_encoder_blocks'			)			)





class      lowerCAmelCase_			:



				"""simple docstring"""

				def __init__( self						,			lowerCAmelCase						,			lowerCAmelCase=13						,			lowerCAmelCase=64						,			lowerCAmelCase=3						,			lowerCAmelCase=4						,			lowerCAmelCase=[2, 2, 2, 2]						,			lowerCAmelCase=[8, 4, 2, 1]						,			lowerCAmelCase=[16, 32, 64, 1_28]						,			lowerCAmelCase=[1, 4, 8, 16]						,			lowerCAmelCase=[1, 2, 4, 8]						,			lowerCAmelCase=True						,			lowerCAmelCase=True						,			lowerCAmelCase="gelu"						,			lowerCAmelCase=0.1						,			lowerCAmelCase=0.1						,			lowerCAmelCase=0.02						,			lowerCAmelCase=3						,			lowerCAmelCase=None						,			):






										"""simple docstring"""

										snake_case	    =	parent
										snake_case	    =	batch_size
										snake_case	    =	image_size
										snake_case	    =	num_channels
										snake_case	    =	num_encoder_blocks
										snake_case	    =	sr_ratios
										snake_case	    =	depths
										snake_case	    =	hidden_sizes
										snake_case	    =	downsampling_rates
										snake_case	    =	num_attention_heads
										snake_case	    =	is_training
										snake_case	    =	use_labels
										snake_case	    =	hidden_act
										snake_case	    =	hidden_dropout_prob
										snake_case	    =	attention_probs_dropout_prob
										snake_case	    =	initializer_range
										snake_case	    =	num_labels
										snake_case	    =	scope

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

										snake_case	    =	None
										if self.use_labels:
																snake_case	    =	ids_tensor([self.batch_size, self.image_size, self.image_size]						,			self.num_labels			)

										snake_case	    =	self.get_config()
										return config, pixel_values, labels

				def 						snake_case       ( self			):






										"""simple docstring"""

										return SegformerConfig(
										    image_size=self.image_size						,			num_channels=self.num_channels						,			num_encoder_blocks=self.num_encoder_blocks						,			depths=self.depths						,			hidden_sizes=self.hidden_sizes						,			num_attention_heads=self.num_attention_heads						,			hidden_act=self.hidden_act						,			hidden_dropout_prob=self.hidden_dropout_prob						,			attention_probs_dropout_prob=self.attention_probs_dropout_prob						,			initializer_range=self.initializer_range						,			)

				def 						snake_case       ( self						,			lowerCAmelCase						,			lowerCAmelCase						,			lowerCAmelCase			):






										"""simple docstring"""

										snake_case	    =	SegformerModel(config=_a			)
										model.to(_a			)
										model.eval()
										snake_case	    =	model(_a			)
										snake_case	    =	self.image_size // (self.downsampling_rates[-1] * 2)
										self.parent.assertEqual(
										    result.last_hidden_state.shape						,			(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)			)

				def 						snake_case       ( self						,			lowerCAmelCase						,			lowerCAmelCase						,			lowerCAmelCase			):






										"""simple docstring"""

										snake_case	    =	self.num_labels
										snake_case	    =	SegformerForSemanticSegmentation(_a			)
										model.to(_a			)
										model.eval()
										snake_case	    =	model(_a			)
										self.parent.assertEqual(
										    result.logits.shape						,			(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)			)
										snake_case	    =	model(_a						,			labels=_a			)
										self.parent.assertEqual(
										    result.logits.shape						,			(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)			)
										self.parent.assertGreater(result.loss						,			0.0			)

				def 						snake_case       ( self						,			lowerCAmelCase						,			lowerCAmelCase						,			lowerCAmelCase			):






										"""simple docstring"""

										snake_case	    =	1
										snake_case	    =	SegformerForSemanticSegmentation(config=_a			)
										model.to(_a			)
										model.eval()
										snake_case	    =	torch.randint(0						,			1						,			(self.batch_size, self.image_size, self.image_size)			).to(_a			)
										snake_case	    =	model(_a						,			labels=_a			)
										self.parent.assertGreater(result.loss						,			0.0			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.prepare_config_and_inputs()
										snake_case	    =	config_and_inputs
										snake_case	    =	{"pixel_values": pixel_values}
										return config, inputs_dict





@require_torch
class      lowerCAmelCase_			(	lowerCAmelCase   ,			lowerCAmelCase   ,			unittest.TestCase    ):



				"""simple docstring"""
				_lowerCAmelCase   :			int	     =  (
				    (
				        SegformerModel,
				        SegformerForSemanticSegmentation,
				        SegformerForImageClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				_lowerCAmelCase   :			Dict	     =  (
				    {
				        """feature-extraction""": SegformerModel,
				        """image-classification""": SegformerForImageClassification,
				        """image-segmentation""": SegformerForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				_lowerCAmelCase   :			List[Any]	     =  True
				_lowerCAmelCase   :			Tuple	     =  False
				_lowerCAmelCase   :			str	     =  False
				_lowerCAmelCase   :			List[str]	     =  False

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	SegformerModelTester(self			)
										snake_case	    =	SegformerConfigTester(self						,			config_class=_a			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										self.config_tester.run_common_tests()

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_a			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_binary_image_segmentation(*_a			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_segmentation(*_a			)

				@unittest.skip('SegFormer does not use inputs_embeds'			)
				def 						snake_case       ( self			):






										"""simple docstring"""

										pass

				@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'			)
				def 						snake_case       ( self			):






										"""simple docstring"""

										pass

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs_for_common()

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

																snake_case	    =	["pixel_values"]
																self.assertListEqual(arg_names[:1]						,			_a			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs_for_common()
										snake_case	    =	True

										for model_class in self.all_model_classes:
																snake_case	    =	True
																snake_case	    =	False
																snake_case	    =	True
																snake_case	    =	model_class(_a			)
																model.to(_a			)
																model.eval()
																with torch.no_grad():
																						snake_case	    =	model(**self._prepare_for_class(_a						,			_a			)			)
																snake_case	    =	outputs.attentions

																snake_case	    =	sum(self.model_tester.depths			)
																self.assertEqual(len(_a			)						,			_a			)

																# check that output_attentions also work using config
																del inputs_dict["output_attentions"]
																snake_case	    =	True
																snake_case	    =	model_class(_a			)
																model.to(_a			)
																model.eval()
																with torch.no_grad():
																						snake_case	    =	model(**self._prepare_for_class(_a						,			_a			)			)
																snake_case	    =	outputs.attentions

																self.assertEqual(len(_a			)						,			_a			)

																# verify the first attentions (first block, first layer)
																snake_case	    =	(self.model_tester.image_size // 4) ** 2
																snake_case	    =	(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
																self.assertListEqual(
																    list(attentions[0].shape[-3:]			)						,			[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]						,			)

																# verify the last attentions (last block, last layer)
																snake_case	    =	(self.model_tester.image_size // 32) ** 2
																snake_case	    =	(self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
																self.assertListEqual(
																    list(attentions[-1].shape[-3:]			)						,			[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]						,			)
																snake_case	    =	len(_a			)

																# Check attention is always last and order is fine
																snake_case	    =	True
																snake_case	    =	True
																snake_case	    =	model_class(_a			)
																model.to(_a			)
																model.eval()
																with torch.no_grad():
																						snake_case	    =	model(**self._prepare_for_class(_a						,			_a			)			)

																self.assertEqual(out_len + 1						,			len(_a			)			)

																snake_case	    =	outputs.attentions

																self.assertEqual(len(_a			)						,			_a			)
																# verify the first attentions (first block, first layer)
																snake_case	    =	(self.model_tester.image_size // 4) ** 2
																snake_case	    =	(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
																self.assertListEqual(
																    list(self_attentions[0].shape[-3:]			)						,			[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]						,			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										def check_hidden_states_output(lowerCAmelCase						,			lowerCAmelCase						,			lowerCAmelCase			):
																snake_case	    =	model_class(_a			)
																model.to(_a			)
																model.eval()

																with torch.no_grad():
																						snake_case	    =	model(**self._prepare_for_class(_a						,			_a			)			)

																snake_case	    =	outputs.hidden_states

																snake_case	    =	self.model_tester.num_encoder_blocks
																self.assertEqual(len(_a			)						,			_a			)

																# verify the first hidden states (first block)
																self.assertListEqual(
																    list(hidden_states[0].shape[-3:]			)						,			[
																        self.model_tester.hidden_sizes[0],
																        self.model_tester.image_size // 4,
																        self.model_tester.image_size // 4,
																    ]						,			)

										snake_case	    =	self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																snake_case	    =	True
																check_hidden_states_output(_a						,			_a						,			_a			)

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																snake_case	    =	True

																check_hidden_states_output(_a						,			_a						,			_a			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										if not self.model_tester.is_training:
																return

										snake_case	    =	self.model_tester.prepare_config_and_inputs_for_common()
										snake_case	    =	True

										for model_class in self.all_model_classes:
																if model_class in get_values(_a			):
																						continue

																snake_case	    =	model_class(_a			)
																model.to(_a			)
																model.train()
																snake_case	    =	self._prepare_for_class(_a						,			_a						,			return_labels=_a			)
																snake_case	    =	model(**_a			).loss
																loss.backward()

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






										"""simple docstring"""

										pass

				@slow
				def 						snake_case       ( self			):






										"""simple docstring"""

										for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																snake_case	    =	SegformerModel.from_pretrained(_a			)
																self.assertIsNotNone(_a			)





def       lowerCAmelCase__			(	)    -> Tuple:





						"""simple docstring"""






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



@require_torch
class      lowerCAmelCase_			(	unittest.TestCase    ):



				"""simple docstring"""

				@slow
				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	SegformerImageProcessor(
										    image_scale=(5_12, 5_12)						,			keep_ratio=_a						,			align=_a						,			do_random_crop=_a			)
										snake_case	    =	SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'			).to(
										    _a			)

										snake_case	    =	prepare_img()
										snake_case	    =	image_processor(images=_a						,			return_tensors='pt'			)
										snake_case	    =	encoded_inputs.pixel_values.to(_a			)

										with torch.no_grad():
																snake_case	    =	model(_a			)

										snake_case	    =	torch.Size((1, model.config.num_labels, 1_28, 1_28)			)
										self.assertEqual(outputs.logits.shape						,			_a			)

										snake_case	    =	torch.tensor(
										    [
										        [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]],
										        [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]],
										        [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]],
										    ]			).to(_a			)
										self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]						,			_a						,			atol=1E-4			)			)

				@slow
				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	SegformerImageProcessor(
										    image_scale=(5_12, 5_12)						,			keep_ratio=_a						,			align=_a						,			do_random_crop=_a			)
										snake_case	    =	SegformerForSemanticSegmentation.from_pretrained(
										    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'			).to(_a			)

										snake_case	    =	prepare_img()
										snake_case	    =	image_processor(images=_a						,			return_tensors='pt'			)
										snake_case	    =	encoded_inputs.pixel_values.to(_a			)

										with torch.no_grad():
																snake_case	    =	model(_a			)

										snake_case	    =	torch.Size((1, model.config.num_labels, 1_28, 1_28)			)
										self.assertEqual(outputs.logits.shape						,			_a			)

										snake_case	    =	torch.tensor(
										    [
										        [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]],
										        [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]],
										        [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]],
										    ]			).to(_a			)
										self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]						,			_a						,			atol=1E-1			)			)

				@slow
				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	SegformerImageProcessor(
										    image_scale=(5_12, 5_12)						,			keep_ratio=_a						,			align=_a						,			do_random_crop=_a			)
										snake_case	    =	SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'			).to(
										    _a			)

										snake_case	    =	prepare_img()
										snake_case	    =	image_processor(images=_a						,			return_tensors='pt'			)
										snake_case	    =	encoded_inputs.pixel_values.to(_a			)

										with torch.no_grad():
																snake_case	    =	model(_a			)

										snake_case	    =	outputs.logits.detach().cpu()

										snake_case	    =	image_processor.post_process_semantic_segmentation(outputs=_a						,			target_sizes=[(5_00, 3_00)]			)
										snake_case	    =	torch.Size((5_00, 3_00)			)
										self.assertEqual(segmentation[0].shape						,			_a			)

										snake_case	    =	image_processor.post_process_semantic_segmentation(outputs=_a			)
										snake_case	    =	torch.Size((1_28, 1_28)			)
										self.assertEqual(segmentation[0].shape						,			_a			)




import importlib
import os

import fsspec
import pytest
from fsspec import register_implementation
from fsspec.registry import _registry as _fsspec_registry

from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem

from .utils import require_lza, require_zstandard






def   lowerCAmelCase_						(					_snake_case      :  List[Any]   )				->		List[Any]:







	'''simple docstring'''


	assert "mock" in _fsspec_registry
	assert "bz2" in _fsspec_registry






def   lowerCAmelCase_						(					)				->		Tuple:







	'''simple docstring'''


	assert "mock" not in _fsspec_registry
	assert "bz2" in _fsspec_registry






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







	'''simple docstring'''


	__magic_name__		:		Dict	   =     "mock-s3-bucket"
	__magic_name__		:		Any	   =     F'''s3://{mock_bucket}'''
	__magic_name__		:		str	   =     extract_path_from_uri(_snake_case   )
	assert dataset_path.startswith("s3://"   ) is False

	__magic_name__		:		Tuple	   =     "./local/path"
	__magic_name__		:		Optional[Any]	   =     extract_path_from_uri(_snake_case   )
	assert dataset_path == new_dataset_path






def   lowerCAmelCase_						(					_snake_case      :  List[str]   )				->		Optional[Any]:







	'''simple docstring'''


	__magic_name__		:		str	   =     is_remote_filesystem(_snake_case   )
	assert is_remote is True

	__magic_name__		:		Optional[int]	   =     fsspec.filesystem("file"   )

	__magic_name__		:		int	   =     is_remote_filesystem(_snake_case   )
	assert is_remote is False






@pytest.mark.parametrize("compression_fs_class"      ,   _snake_case   )
def   lowerCAmelCase_						(					_snake_case      :  Optional[int]      ,   _snake_case      :  Optional[Any]      ,   _snake_case      :  int      ,   _snake_case      :  Tuple      ,   _snake_case      :  Any      ,   _snake_case      :  Union[str, Any]      ,   _snake_case      :  Any   )				->		int:







	'''simple docstring'''


	__magic_name__		:		Any	   =     {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bza_file, "lz4": lza_file}
	__magic_name__		:		str	   =     input_paths[compression_fs_class.protocol]
	if input_path is None:
		__magic_name__		:		Dict	   =     F'''for \'{compression_fs_class.protocol}\' compression protocol, '''
		if compression_fs_class.protocol == "lz4":
			reason += require_lza.kwargs["reason"]
		elif compression_fs_class.protocol == "zstd":
			reason += require_zstandard.kwargs["reason"]
		pytest.skip(_snake_case   )
	__magic_name__		:		str	   =     fsspec.filesystem(compression_fs_class.protocol      ,   fo=_snake_case   )
	assert isinstance(_snake_case      ,   _snake_case   )
	__magic_name__		:		int	   =     os.path.basename(_snake_case   )
	__magic_name__		:		Optional[int]	   =     expected_filename[: expected_filename.rindex("."   )]
	assert fs.glob("*"   ) == [expected_filename]
	with fs.open(_snake_case      ,   "r"      ,   encoding="utf-8"   ) as f, open(_snake_case      ,   encoding="utf-8"   ) as expected_file:
		assert f.read() == expected_file.read()






@pytest.mark.parametrize("protocol"      ,   ["zip", "gzip"]   )
def   lowerCAmelCase_						(					_snake_case      :  List[Any]      ,   _snake_case      :  Optional[Any]      ,   _snake_case      :  Optional[Any]   )				->		str:







	'''simple docstring'''


	__magic_name__		:		int	   =     {"zip": zip_jsonl_path, "gzip": jsonl_gz_path}
	__magic_name__		:		int	   =     compressed_file_paths[protocol]
	__magic_name__		:		Tuple	   =     "dataset.jsonl"
	__magic_name__		:		List[str]	   =     F'''{protocol}://{member_file_path}::{compressed_file_path}'''
	__magic_name__   ,    *__magic_name__		:		Optional[Any]	   =     fsspec.get_fs_token_paths(_snake_case   )
	assert fs.isfile(_snake_case   )
	assert not fs.isfile("non_existing_" + member_file_path   )






@pytest.mark.integration
def   lowerCAmelCase_						(					_snake_case      :  Union[str, Any]      ,   _snake_case      :  Dict      ,   _snake_case      :  List[str]      ,   _snake_case      :  Tuple   )				->		str:







	'''simple docstring'''


	__magic_name__		:		int	   =     hf_api.dataset_info(_snake_case      ,   token=_snake_case   )
	__magic_name__		:		Optional[Any]	   =     HfFileSystem(repo_info=_snake_case      ,   token=_snake_case   )
	assert sorted(hffs.glob("*"   )   ) == [".gitattributes", "data"]
	assert hffs.isdir("data"   )
	assert hffs.isfile(".gitattributes"   ) and hffs.isfile("data/text_data.txt"   )
	with open(_snake_case   ) as f:
		assert hffs.open("data/text_data.txt"      ,   "r"   ).read() == f.read()






def   lowerCAmelCase_						(					)				->		Optional[int]:







	'''simple docstring'''


	__magic_name__		:		Optional[Any]	   =     "bz2"

	# Import module
	import datasets.filesystems

	# Overwrite protocol and reload
	register_implementation(_snake_case      ,   _snake_case      ,   clobber=_snake_case   )
	with pytest.warns(_snake_case   ) as warning_info:
		importlib.reload(datasets.filesystems   )

	assert len(_snake_case   ) == 1
	assert (
	    str(warning_info[0].message   )
	    == F'''A filesystem protocol was already set for {protocol} and will be overwritten.'''
	)
