




'''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 		SCREAMING_SNAKE_CASE__  (			_UpperCamelCase	):





			def 							A (      self						:    Optional[Any]							):



						"""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 		SCREAMING_SNAKE_CASE__  :





			def __init__(      self						:    List[Any]      ,		a_						:    Any      ,		a_						:    Tuple=13      ,		a_						:    Optional[Any]=64      ,		a_						:    str=3      ,		a_						:    Any=4      ,		a_						:    List[str]=[2, 2, 2, 2]      ,		a_						:    Optional[int]=[8, 4, 2, 1]      ,		a_						:    List[str]=[16, 32, 64, 128]      ,		a_						:    Union[str, Any]=[1, 4, 8, 16]      ,		a_						:    Dict=[1, 2, 4, 8]      ,		a_						:    Tuple=True      ,		a_						:    Optional[int]=True      ,		a_						:    int="gelu"      ,		a_						:    Optional[Any]=0.1      ,		a_						:    Optional[int]=0.1      ,		a_						:    int=0.02      ,		a_						:    Optional[int]=3      ,		a_						:    Any=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 							A (      self						:    int							):



						"""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 							A (      self						:    Union[str, Any]							):



						"""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 							A (      self						:    List[Any]      ,		a_						:    int      ,		a_						:    List[str]      ,		a_						:    Dict							):



						"""simple docstring"""




						__snake_case			=		SegformerModel(config=a_							)
						model.to(a_							)
						model.eval()
						__snake_case			=		model(a_							)
						__snake_case			=		__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 							A (      self						:    int      ,		a_						:    List[Any]      ,		a_						:    Dict      ,		a_						:    Optional[Any]							):



						"""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 							A (      self						:    Optional[int]      ,		a_						:    str      ,		a_						:    Dict      ,		a_						:    str							):



						"""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 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




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







@require_torch
class 		SCREAMING_SNAKE_CASE__  (			_UpperCamelCase				,     _UpperCamelCase				,     unittest.TestCase	):
			__SCREAMING_SNAKE_CASE    =			(
			    (
			        SegformerModel,
			        SegformerForSemanticSegmentation,
			        SegformerForImageClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			__SCREAMING_SNAKE_CASE    =			(
			    {
			        """feature-extraction""": SegformerModel,
			        """image-classification""": SegformerForImageClassification,
			        """image-segmentation""": SegformerForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			__SCREAMING_SNAKE_CASE    =			True
			__SCREAMING_SNAKE_CASE    =			False
			__SCREAMING_SNAKE_CASE    =			False
			__SCREAMING_SNAKE_CASE    =			False





			def 							A (      self						:    Any							):



						"""simple docstring"""




						__snake_case			=		SegformerModelTester(self							)
						__snake_case			=		SegformerConfigTester(self      ,		config_class=a_							)





			def 							A (      self						:    Any							):



						"""simple docstring"""




						self.config_tester.run_common_tests()





			def 							A (      self						:    List[Any]							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*a_							)





			def 							A (      self						:    str							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_binary_image_segmentation(*a_							)





			def 							A (      self						:    Optional[Any]							):



						"""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 							A (      self						:    Tuple							):



						"""simple docstring"""




						pass





			@unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods"							)
			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						pass





			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						__snake_case		,     __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 							A (      self						:    Tuple							):



						"""simple docstring"""




						__snake_case		,     __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 							A (      self						:    int							):



						"""simple docstring"""




						def check_hidden_states_output(a_						:    List[Any]      ,		a_						:    List[Any]      ,		a_						:    Tuple							):
									__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		,     __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 							A (      self						:    Tuple							):



						"""simple docstring"""




						if not self.model_tester.is_training:
									return

						__snake_case		,     __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 							A (      self						:    int							):



						"""simple docstring"""




						pass






			@slow
			def 							A (      self						:    List[str]							):



						"""simple docstring"""




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







def __UpperCAmelCase	(   )      ->      List[Any]:
			__snake_case			=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
			return image






@require_torch
class 		SCREAMING_SNAKE_CASE__  (			unittest.TestCase	):





			@slow
			def 							A (      self						:    Dict							):



						"""simple docstring"""




						__snake_case			=		SegformerImageProcessor(
						    image_scale=(512, 512)      ,		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, 128, 128)							)
						self.assertEqual(outputs.logits.shape      ,		a_							)

						__snake_case			=		torch.tensor(
						    [
						        [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
						        [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
						        [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
						    ]							).to(a_							)
						self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]      ,		a_      ,		atol=1e-4							)							)





			@slow
			def 							A (      self						:    Tuple							):



						"""simple docstring"""




						__snake_case			=		SegformerImageProcessor(
						    image_scale=(512, 512)      ,		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, 128, 128)							)
						self.assertEqual(outputs.logits.shape      ,		a_							)

						__snake_case			=		torch.tensor(
						    [
						        [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
						        [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
						        [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
						    ]							).to(a_							)
						self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]      ,		a_      ,		atol=1e-1							)							)






			@slow
			def 							A (      self						:    Tuple							):



						"""simple docstring"""




						__snake_case			=		SegformerImageProcessor(
						    image_scale=(512, 512)      ,		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=[(500, 300)]							)
						__snake_case			=		torch.Size((500, 300)							)
						self.assertEqual(segmentation[0].shape      ,		a_							)

						__snake_case			=		image_processor.post_process_semantic_segmentation(outputs=a_							)
						__snake_case			=		torch.Size((128, 128)							)
						self.assertEqual(segmentation[0].shape      ,		a_							)












import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_												=	logging.get_logger(__name__)

UpperCamelCase_												=	{
    'microsoft/wavlm-base': 'https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json',
    # See all WavLM models at https://huggingface.co/models?filter=wavlm
}

class     snake_case_		(   a							):






 '''simple docstring'''





 __UpperCamelCase       =      'wavlm'

 def __init__(  self,		A_=32,		A_=768,		A_=12,		A_=12,		A_=3072,		A_="gelu",		A_=0.1,		A_=0.1,		A_=0.1,		A_=0.0,		A_=0.1,		A_=0.1,		A_=0.02,		A_=1E-5,		A_="group",		A_="gelu",		A_=(512, 512, 512, 512, 512, 512, 512),		A_=(5, 2, 2, 2, 2, 2, 2),		A_=(10, 3, 3, 3, 3, 2, 2),		A_=False,		A_=128,		A_=16,		A_=320,		A_=800,		A_=False,		A_=True,		A_=0.05,		A_=10,		A_=2,		A_=0.0,		A_=10,		A_=320,		A_=2,		A_=0.1,		A_=100,		A_=256,		A_=256,		A_=0.1,		A_="mean",		A_=False,		A_=False,		A_=256,		A_=(512, 512, 512, 512, 1500),		A_=(5, 3, 3, 1, 1),		A_=(1, 2, 3, 1, 1),		A_=512,		A_=80,		A_=0,		A_=1,		A_=2,		A_=False,		A_=3,		A_=2,		A_=3,		A_=None,		**A_,		)	->       Union[str, Any]:
    super().__init__(**A_,		pad_token_id=A_,		bos_token_id=A_,		eos_token_id=A_		)
    UpperCAmelCase__						=hidden_size
    UpperCAmelCase__						=feat_extract_norm
    UpperCAmelCase__						=feat_extract_activation
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=conv_bias
    UpperCAmelCase__						=num_buckets
    UpperCAmelCase__						=max_bucket_distance
    UpperCAmelCase__						=num_conv_pos_embeddings
    UpperCAmelCase__						=num_conv_pos_embedding_groups
    UpperCAmelCase__						=len(self.conv_dim		)
    UpperCAmelCase__						=num_hidden_layers
    UpperCAmelCase__						=intermediate_size
    UpperCAmelCase__						=hidden_act
    UpperCAmelCase__						=num_attention_heads
    UpperCAmelCase__						=hidden_dropout
    UpperCAmelCase__						=attention_dropout
    UpperCAmelCase__						=activation_dropout
    UpperCAmelCase__						=feat_proj_dropout
    UpperCAmelCase__						=final_dropout
    UpperCAmelCase__						=layerdrop
    UpperCAmelCase__						=layer_norm_eps
    UpperCAmelCase__						=initializer_range
    UpperCAmelCase__						=num_ctc_classes
    UpperCAmelCase__						=vocab_size
    UpperCAmelCase__						=do_stable_layer_norm
    UpperCAmelCase__						=use_weighted_layer_sum
    UpperCAmelCase__						=classifier_proj_size

    if (
        (len(self.conv_stride		) != self.num_feat_extract_layers)
        or (len(self.conv_kernel		) != self.num_feat_extract_layers)
        or (len(self.conv_dim		) != self.num_feat_extract_layers)
    ):
       raise ValueError(
           "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
           " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
           f""" {len(self.conv_dim		)}`, `len(config.conv_stride) = {len(self.conv_stride		)}`,"""
           f""" `len(config.conv_kernel) = {len(self.conv_kernel		)}`."""		)

    # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
    UpperCAmelCase__						=apply_spec_augment
    UpperCAmelCase__						=mask_time_prob
    UpperCAmelCase__						=mask_time_length
    UpperCAmelCase__						=mask_time_min_masks
    UpperCAmelCase__						=mask_feature_prob
    UpperCAmelCase__						=mask_feature_length

    # parameters for pretraining with codevector quantized representations
    UpperCAmelCase__						=num_codevectors_per_group
    UpperCAmelCase__						=num_codevector_groups
    UpperCAmelCase__						=contrastive_logits_temperature
    UpperCAmelCase__						=num_negatives
    UpperCAmelCase__						=codevector_dim
    UpperCAmelCase__						=proj_codevector_dim
    UpperCAmelCase__						=diversity_loss_weight

    # ctc loss
    UpperCAmelCase__						=ctc_loss_reduction
    UpperCAmelCase__						=ctc_zero_infinity

    # adapter
    UpperCAmelCase__						=add_adapter
    UpperCAmelCase__						=adapter_kernel_size
    UpperCAmelCase__						=adapter_stride
    UpperCAmelCase__						=num_adapter_layers
    UpperCAmelCase__						=output_hidden_size or hidden_size

    # SequenceClassification-specific parameter. Feel free to ignore for other classes.
    UpperCAmelCase__						=classifier_proj_size

    # XVector-specific parameters. Feel free to ignore for other classes.
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=xvector_output_dim






 @property
 def  __UpperCAmelCase						(  self		)	->       List[Any]:
    return functools.reduce(operator.mul,		self.conv_stride,		1		)



