

from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


a__				=		[
    '''openmmlab/upernet-convnext-tiny''',
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
a__				=		'''UperNetConfig'''

class 				UpperCAmelCase_		(			nn.Module   ):
							"""simple docstring"""







							def __init__(			self       ,							_a       ,							_a       ,							_a       ,							_a = 0       ,							_a = False       ,							_a = 1       ,							)    ->    None:
												super().__init__()
												_a	:    str         =		nn.Convad(
												    in_channels=_a       ,							out_channels=_a       ,							kernel_size=_a       ,							padding=_a       ,							bias=_a       ,							dilation=_a       ,							)
												_a	:    Union[str, Any]         =		nn.BatchNormad(_a       )
												_a	:    Union[str, Any]         =		nn.ReLU()




							def 				__lowercase				(			self       ,							_a       )    ->    torch.Tensor:
												_a	:    int         =		self.conv(_a       )
												_a	:    int         =		self.batch_norm(_a       )
												_a	:    List[Any]         =		self.activation(_a       )

												return output



class 				UpperCAmelCase_		(			nn.Module   ):
							"""simple docstring"""







							def __init__(			self       ,							_a       ,							_a       ,							_a       )    ->    None:
												super().__init__()
												_a	:    Union[str, Any]         =		[
												    nn.AdaptiveAvgPoolad(_a       ),
												    UperNetConvModule(_a       ,							_a       ,							kernel_size=1       ),
												]
												for i, layer in enumerate(self.layers       ):
																	self.add_module(str(_a       )       ,							_a       )




							def 				__lowercase				(			self       ,							_a       )    ->    torch.Tensor:
												_a	:    Any         =		input
												for layer in self.layers:
																	_a	:    List[Any]         =		layer(_a       )
												return hidden_state



class 				UpperCAmelCase_		(			nn.Module   ):
							"""simple docstring"""







							def __init__(			self       ,							_a       ,							_a       ,							_a       ,							_a       )    ->    None:
												super().__init__()
												_a	:    Union[str, Any]         =		pool_scales
												_a	:    Dict         =		align_corners
												_a	:    Dict         =		in_channels
												_a	:    List[Any]         =		channels
												_a	:    Dict         =		[]
												for i, pool_scale in enumerate(_a       ):
																	_a	:    str         =		UperNetPyramidPoolingBlock(pool_scale=_a       ,							in_channels=_a       ,							channels=_a       )
																	self.blocks.append(_a       )
																	self.add_module(str(_a       )       ,							_a       )




							def 				__lowercase				(			self       ,							_a       )    ->    List[torch.Tensor]:
												_a	:    Optional[Any]         =		[]
												for ppm in self.blocks:
																	_a	:    Tuple         =		ppm(_a       )
																	_a	:    Optional[int]         =		nn.functional.interpolate(
																	    _a       ,							size=x.size()[2:]       ,							mode='''bilinear'''       ,							align_corners=self.align_corners       )
																	ppm_outs.append(_a       )
												return ppm_outs



class 				UpperCAmelCase_		(			nn.Module   ):
							"""simple docstring"""







							def __init__(			self       ,							_a       ,							_a       )    ->    Dict:
												super().__init__()

												_a	:    int         =		config
												_a	:    int         =		config.pool_scales  # e.g. (1, 2, 3, 6)
												_a	:    Union[str, Any]         =		in_channels
												_a	:    Optional[int]         =		config.hidden_size
												_a	:    Dict         =		False
												_a	:    Tuple         =		nn.Convad(self.channels       ,							config.num_labels       ,							kernel_size=1       )

												# PSP Module
												_a	:    Optional[Any]         =		UperNetPyramidPoolingModule(
												    self.pool_scales       ,							self.in_channels[-1]       ,							self.channels       ,							align_corners=self.align_corners       ,							)
												_a	:    List[Any]         =		UperNetConvModule(
												    self.in_channels[-1] + len(self.pool_scales       ) * self.channels       ,							self.channels       ,							kernel_size=3       ,							padding=1       ,							)
												# FPN Module
												_a	:    Optional[Any]         =		nn.ModuleList()
												_a	:    Tuple         =		nn.ModuleList()
												for in_channels in self.in_channels[:-1]:  # skip the top layer
																	_a	:    Any         =		UperNetConvModule(_a       ,							self.channels       ,							kernel_size=1       )
																	_a	:    Any         =		UperNetConvModule(self.channels       ,							self.channels       ,							kernel_size=3       ,							padding=1       )
																	self.lateral_convs.append(_a       )
																	self.fpn_convs.append(_a       )

												_a	:    List[Any]         =		UperNetConvModule(
												    len(self.in_channels       ) * self.channels       ,							self.channels       ,							kernel_size=3       ,							padding=1       ,							)


							def 				__lowercase				(			self       )    ->    Dict:
												self.apply(self._init_weights       )


							def 				__lowercase				(			self       ,							_a       )    ->    Tuple:
												if isinstance(_a       ,							nn.Convad       ):
																	module.weight.data.normal_(mean=0.0       ,							std=self.config.initializer_range       )
																	if module.bias is not None:
																						module.bias.data.zero_()


							def 				__lowercase				(			self       ,							_a       )    ->    List[Any]:
												_a	:    Union[str, Any]         =		inputs[-1]
												_a	:    List[Any]         =		[x]
												psp_outs.extend(self.psp_modules(_a       )       )
												_a	:    List[Any]         =		torch.cat(_a       ,							dim=1       )
												_a	:    Tuple         =		self.bottleneck(_a       )

												return output




							def 				__lowercase				(			self       ,							_a       )    ->    torch.Tensor:
												# build laterals
												_a	:    Any         =		[lateral_conv(encoder_hidden_states[i]       ) for i, lateral_conv in enumerate(self.lateral_convs       )]

												laterals.append(self.psp_forward(_a       )       )

												# build top-down path
												_a	:    Optional[int]         =		len(_a       )
												for i in range(used_backbone_levels - 1       ,							0       ,							-1       ):
																	_a	:    Union[str, Any]         =		laterals[i - 1].shape[2:]
																	_a	:    List[Any]         =		laterals[i - 1] + nn.functional.interpolate(
																	    laterals[i]       ,							size=_a       ,							mode='''bilinear'''       ,							align_corners=self.align_corners       )

												# build outputs
												_a	:    int         =		[self.fpn_convs[i](laterals[i]       ) for i in range(used_backbone_levels - 1       )]
												# append psp feature
												fpn_outs.append(laterals[-1]       )

												for i in range(used_backbone_levels - 1       ,							0       ,							-1       ):
																	_a	:    int         =		nn.functional.interpolate(
																	    fpn_outs[i]       ,							size=fpn_outs[0].shape[2:]       ,							mode='''bilinear'''       ,							align_corners=self.align_corners       )
												_a	:    Optional[int]         =		torch.cat(_a       ,							dim=1       )
												_a	:    Tuple         =		self.fpn_bottleneck(_a       )
												_a	:    Dict         =		self.classifier(_a       )

												return output



class 				UpperCAmelCase_		(			nn.Module   ):
							"""simple docstring"""







							def __init__(			self       ,							_a       ,							_a = 2       ,							_a = 3       ,							_a = 1       )    ->    None:
												super().__init__()

												_a	:    Dict         =		config
												_a	:    Dict         =		config.auxiliary_in_channels
												_a	:    List[Any]         =		config.auxiliary_channels
												_a	:    int         =		config.auxiliary_num_convs
												_a	:    Tuple         =		config.auxiliary_concat_input
												_a	:    Union[str, Any]         =		in_index

												_a	:    Dict         =		(kernel_size // 2) * dilation
												_a	:    Dict         =		[]
												convs.append(
												    UperNetConvModule(
												        self.in_channels       ,							self.channels       ,							kernel_size=_a       ,							padding=_a       ,							dilation=_a       )       )
												for i in range(self.num_convs - 1       ):
																	convs.append(
																	    UperNetConvModule(
																	        self.channels       ,							self.channels       ,							kernel_size=_a       ,							padding=_a       ,							dilation=_a       )       )
												if self.num_convs == 0:
																	_a	:    int         =		nn.Identity()
												else:
																	_a	:    Optional[Any]         =		nn.Sequential(*_a       )
												if self.concat_input:
																	_a	:    int         =		UperNetConvModule(
																	    self.in_channels + self.channels       ,							self.channels       ,							kernel_size=_a       ,							padding=kernel_size // 2       )

												_a	:    Dict         =		nn.Convad(self.channels       ,							config.num_labels       ,							kernel_size=1       )


							def 				__lowercase				(			self       )    ->    Union[str, Any]:
												self.apply(self._init_weights       )


							def 				__lowercase				(			self       ,							_a       )    ->    Optional[Any]:
												if isinstance(_a       ,							nn.Convad       ):
																	module.weight.data.normal_(mean=0.0       ,							std=self.config.initializer_range       )
																	if module.bias is not None:
																						module.bias.data.zero_()




							def 				__lowercase				(			self       ,							_a       )    ->    torch.Tensor:
												# just take the relevant feature maps
												_a	:    Optional[int]         =		encoder_hidden_states[self.in_index]
												_a	:    Optional[Any]         =		self.convs(_a       )
												if self.concat_input:
																	_a	:    str         =		self.conv_cat(torch.cat([hidden_states, output]       ,							dim=1       )       )
												_a	:    Tuple         =		self.classifier(_a       )
												return output



class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						List[Any]	    =    UperNetConfig
							UpperCAmelCase__       :						str	    =    "pixel_values"
							UpperCAmelCase__       :						Dict	    =    True


							def 				__lowercase				(			self       ,							_a       )    ->    str:
												if isinstance(_a       ,							_a       ):
																	module.backbone.init_weights()
																	module.decode_head.init_weights()
																	module.auxiliary_head.init_weights()


							def 				__lowercase				(			self       )    ->    Union[str, Any]:
												self.backbone.init_weights()
												self.decode_head.init_weights()
												self.auxiliary_head.init_weights()




							def 				__lowercase				(			self       ,							_a       ,							_a=False       )    ->    int:
												if isinstance(_a       ,							_a       ):
																	_a	:    Any         =		value



a__				=		R'''
    Parameters:
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.
        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

a__				=		R'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See
            `attentions` under returned tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under
            returned tensors for more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''

@add_start_docstrings(
    "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes."				,       __lowercase				,       )
class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							def __init__(			self       ,							_a       )    ->    int:
												super().__init__(_a       )

												_a	:    Union[str, Any]         =		AutoBackbone.from_config(config.backbone_config       )

												# Semantic segmentation head(s)
												_a	:    int         =		UperNetHead(_a       ,							in_channels=self.backbone.channels       )
												_a	:    List[str]         =		UperNetFCNHead(_a       ) if config.use_auxiliary_head else None

												# Initialize weights and apply final processing
												self.post_init()




							@add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('''batch_size, sequence_length'''       )       )
							@replace_return_docstrings(output_type=_a       ,							config_class=_CONFIG_FOR_DOC       )
							def 				__lowercase				(			self       ,							_a = None       ,							_a = None       ,							_a = None       ,							_a = None       ,							_a = None       ,							)    ->    Union[tuple, SemanticSegmenterOutput]:
												_a	:    str         =		return_dict if return_dict is not None else self.config.use_return_dict
												_a	:    Dict         =		(
												    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
												)
												_a	:    Tuple         =		output_attentions if output_attentions is not None else self.config.output_attentions

												_a	:    str         =		self.backbone.forward_with_filtered_kwargs(
												    _a       ,							output_hidden_states=_a       ,							output_attentions=_a       )
												_a	:    Tuple         =		outputs.feature_maps

												_a	:    List[Any]         =		self.decode_head(_a       )
												_a	:    Tuple         =		nn.functional.interpolate(_a       ,							size=pixel_values.shape[2:]       ,							mode='''bilinear'''       ,							align_corners=_a       )

												_a	:    List[str]         =		None
												if self.auxiliary_head is not None:
																	_a	:    List[str]         =		self.auxiliary_head(_a       )
																	_a	:    List[str]         =		nn.functional.interpolate(
																	    _a       ,							size=pixel_values.shape[2:]       ,							mode='''bilinear'''       ,							align_corners=_a       )

												_a	:    Tuple         =		None
												if labels is not None:
																	if self.config.num_labels == 1:
																						raise ValueError('''The number of labels should be greater than one'''       )
																	else:
																						# compute weighted loss
																						_a	:    Dict         =		CrossEntropyLoss(ignore_index=self.config.loss_ignore_index       )
																						_a	:    Union[str, Any]         =		loss_fct(_a       ,							_a       )
																						_a	:    Any         =		loss_fct(_a       ,							_a       )
																						_a	:    str         =		main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

												if not return_dict:
																	if output_hidden_states:
																						_a	:    Tuple         =		(logits,) + outputs[1:]
																	else:
																						_a	:    List[str]         =		(logits,) + outputs[2:]
																	return ((loss,) + output) if loss is not None else output

												return SemanticSegmenterOutput(
												    loss=_a       ,							logits=_a       ,							hidden_states=outputs.hidden_states       ,							attentions=outputs.attentions       ,							)






import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding

class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						str	    =    ["image_processor", "tokenizer"]
							UpperCAmelCase__       :						Optional[int]	    =    "CLIPImageProcessor"
							UpperCAmelCase__       :						Tuple	    =    ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")


							def __init__(			self       ,							_a=None       ,							_a=None       ,							**_a       )    ->    Any:
												_a	:    int         =		None
												if "feature_extractor" in kwargs:
																	warnings.warn(
																	    '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
																	    ''' instead.'''       ,							_a       ,							)
																	_a	:    int         =		kwargs.pop('''feature_extractor'''       )

												_a	:    int         =		image_processor if image_processor is not None else feature_extractor
												if image_processor is None:
																	raise ValueError('''You need to specify an `image_processor`.'''       )
												if tokenizer is None:
																	raise ValueError('''You need to specify a `tokenizer`.'''       )

												super().__init__(_a       ,							_a       )


							def __call__(			self       ,							_a=None       ,							_a=None       ,							_a=None       ,							**_a       )    ->    List[Any]:

												if text is None and images is None:
																	raise ValueError('''You have to specify either text or images. Both cannot be none.'''       )

												if text is not None:
																	_a	:    str         =		self.tokenizer(_a       ,							return_tensors=_a       ,							**_a       )

												if images is not None:
																	_a	:    Optional[Any]         =		self.image_processor(_a       ,							return_tensors=_a       ,							**_a       )

												if text is not None and images is not None:
																	_a	:    List[Any]         =		image_features.pixel_values
																	return encoding
												elif text is not None:
																	return encoding
												else:
																	return BatchEncoding(data=dict(**_a       )       ,							tensor_type=_a       )


							def 				__lowercase				(			self       ,							*_a       ,							**_a       )    ->    Optional[Any]:
												return self.tokenizer.batch_decode(*_a       ,							**_a       )


							def 				__lowercase				(			self       ,							*_a       ,							**_a       )    ->    Optional[int]:
												return self.tokenizer.decode(*_a       ,							**_a       )




							@property
							def 				__lowercase				(			self       )    ->    Optional[int]:
												_a	:    Dict         =		self.tokenizer.model_input_names
												_a	:    Dict         =		self.image_processor.model_input_names
												return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names       )       )



