





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


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

# General docstring
_SCREAMING_SNAKE_CASE      	=		"""UperNetConfig"""
class SCREAMING_SNAKE_CASE_						(					nn.Module					):






						def __init__(      self      :      Tuple		,   _A      :      int		,   _A      :      int		,   _A      :      Union[int, Tuple[int, int]]		,   _A      :      Union[int, Tuple[int, int], str] = 0		,   _A      :      bool = False		,   _A      :      Union[int, Tuple[int, int]] = 1		,   )							->    None:







							"""simple docstring"""


							super().__init__()
							snake_case_		:			List[str]											=	nn.Convad(
							    in_channels=_A		,   out_channels=_A		,   kernel_size=_A		,   padding=_A		,   bias=_A		,   dilation=_A		,   )
							snake_case_		:			Tuple											=	nn.BatchNormad(_A	)
							snake_case_		:			Tuple											=	nn.ReLU()






						def UpperCAmelCase_				(      self      :      Optional[Any]		,   _A      :      torch.Tensor	)							->    torch.Tensor:







							"""simple docstring"""


							snake_case_		:			Optional[int]											=	self.conv(_A	)
							snake_case_		:			int											=	self.batch_norm(_A	)
							snake_case_		:			Tuple											=	self.activation(_A	)

							return output
class SCREAMING_SNAKE_CASE_						(					nn.Module					):






						def __init__(      self      :      List[str]		,   _A      :      int		,   _A      :      int		,   _A      :      int	)							->    None:







							"""simple docstring"""


							super().__init__()
							snake_case_		:			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 UpperCAmelCase_				(      self      :      int		,   _A      :      torch.Tensor	)							->    torch.Tensor:







							"""simple docstring"""


							snake_case_		:			Union[str, Any]											=	input
							for layer in self.layers:
								snake_case_		:			Any											=	layer(_A	)
							return hidden_state
class SCREAMING_SNAKE_CASE_						(					nn.Module					):






						def __init__(      self      :      str		,   _A      :      Tuple[int, ...]		,   _A      :      int		,   _A      :      int		,   _A      :      bool	)							->    None:







							"""simple docstring"""


							super().__init__()
							snake_case_		:			int											=	pool_scales
							snake_case_		:			Any											=	align_corners
							snake_case_		:			Optional[Any]											=	in_channels
							snake_case_		:			Any											=	channels
							snake_case_		:			Tuple											=	[]
							for i, pool_scale in enumerate(_A	):
								snake_case_		:			str											=	UperNetPyramidPoolingBlock(pool_scale=_A		,   in_channels=_A		,   channels=_A	)
								self.blocks.append(_A	)
								self.add_module(str(_A	)		,   _A	)






						def UpperCAmelCase_				(      self      :      Tuple		,   _A      :      torch.Tensor	)							->    List[torch.Tensor]:







							"""simple docstring"""


							snake_case_		:			Tuple											=	[]
							for ppm in self.blocks:
								snake_case_		:			Tuple											=	ppm(_A	)
								snake_case_		:			int											=	nn.functional.interpolate(
								    _A		,   size=x.size()[2:]		,   mode='bilinear'		,   align_corners=self.align_corners	)
								ppm_outs.append(_A	)
							return ppm_outs
class SCREAMING_SNAKE_CASE_						(					nn.Module					):






						def __init__(      self      :      List[str]		,   _A      :      Tuple		,   _A      :      Optional[Any]	)							->    Optional[int]:







							"""simple docstring"""


							super().__init__()

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

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

							snake_case_		:			Any											=	UperNetConvModule(
							    len(self.in_channels	) * self.channels		,   self.channels		,   kernel_size=3		,   padding=1		,   )






						def UpperCAmelCase_				(      self      :      List[str]	)							->    Optional[Any]:







							"""simple docstring"""


							self.apply(self._init_weights	)






						def UpperCAmelCase_				(      self      :      Optional[Any]		,   _A      :      Any	)							->    Optional[int]:







							"""simple docstring"""


							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 UpperCAmelCase_				(      self      :      Any		,   _A      :      Optional[Any]	)							->    int:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	inputs[-1]
							snake_case_		:			int											=	[x]
							psp_outs.extend(self.psp_modules(_A	)	)
							snake_case_		:			List[str]											=	torch.cat(_A		,   dim=1	)
							snake_case_		:			List[Any]											=	self.bottleneck(_A	)

							return output






						def UpperCAmelCase_				(      self      :      Optional[int]		,   _A      :      torch.Tensor	)							->    torch.Tensor:







							"""simple docstring"""


							snake_case_		:			Optional[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
							snake_case_		:			Dict											=	len(_A	)
							for i in range(used_backbone_levels - 1		,   0		,   -1	):
								snake_case_		:			Optional[Any]											=	laterals[i - 1].shape[2:]
								snake_case_		:			Optional[int]											=	laterals[i - 1] + nn.functional.interpolate(
								    laterals[i]		,   size=_A		,   mode='bilinear'		,   align_corners=self.align_corners	)

							# build outputs
							snake_case_		:			Union[str, Any]											=	[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	):
								snake_case_		:			Dict											=	nn.functional.interpolate(
								    fpn_outs[i]		,   size=fpn_outs[0].shape[2:]		,   mode='bilinear'		,   align_corners=self.align_corners	)
							snake_case_		:			int											=	torch.cat(_A		,   dim=1	)
							snake_case_		:			Optional[int]											=	self.fpn_bottleneck(_A	)
							snake_case_		:			str											=	self.classifier(_A	)

							return output
class SCREAMING_SNAKE_CASE_						(					nn.Module					):






						def __init__(      self      :      Optional[Any]		,   _A      :      Union[str, Any]		,   _A      :      int = 2		,   _A      :      int = 3		,   _A      :      Union[int, Tuple[int, int]] = 1	)							->    None:







							"""simple docstring"""


							super().__init__()

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

							snake_case_		:			Dict											=	(kernel_size // 2) * dilation
							snake_case_		:			int											=	[]
							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:
								snake_case_		:			Dict											=	nn.Identity()
							else:
								snake_case_		:			Union[str, Any]											=	nn.Sequential(*_A	)
							if self.concat_input:
								snake_case_		:			List[str]											=	UperNetConvModule(
								    self.in_channels + self.channels		,   self.channels		,   kernel_size=_A		,   padding=kernel_size // 2	)

							snake_case_		:			List[Any]											=	nn.Convad(self.channels		,   config.num_labels		,   kernel_size=1	)






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







							"""simple docstring"""


							self.apply(self._init_weights	)






						def UpperCAmelCase_				(      self      :      Optional[Any]		,   _A      :      Union[str, Any]	)							->    List[Any]:







							"""simple docstring"""


							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 UpperCAmelCase_				(      self      :      Optional[int]		,   _A      :      torch.Tensor	)							->    torch.Tensor:







							"""simple docstring"""


							snake_case_		:			List[Any]											=	encoder_hidden_states[self.in_index]
							snake_case_		:			str											=	self.convs(_A	)
							if self.concat_input:
								snake_case_		:			List[str]											=	self.conv_cat(torch.cat([hidden_states, output]		,   dim=1	)	)
							snake_case_		:			str											=	self.classifier(_A	)
							return output
class SCREAMING_SNAKE_CASE_						(					snake_case_					):
						__magic_name__:			int       =       UperNetConfig
						__magic_name__:			List[str]       =       "pixel_values"
						__magic_name__:			Any       =       True






						def UpperCAmelCase_				(      self      :      List[Any]		,   _A      :      int	)							->    int:







							"""simple docstring"""


							if isinstance(_A		,   _A	):
								module.backbone.init_weights()
								module.decode_head.init_weights()
								module.auxiliary_head.init_weights()






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







							"""simple docstring"""


							self.backbone.init_weights()
							self.decode_head.init_weights()
							self.auxiliary_head.init_weights()






						def UpperCAmelCase_				(      self      :      List[Any]		,   _A      :      Optional[int]		,   _A      :      List[Any]=False	)							->    Optional[Any]:







							"""simple docstring"""


							if isinstance(_A		,   _A	):
								snake_case_		:			Any											=	value
_SCREAMING_SNAKE_CASE      	=		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.
"""

_SCREAMING_SNAKE_CASE      	=		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."       ,				snake_case_       ,				)
class SCREAMING_SNAKE_CASE_						(					snake_case_					):






						def __init__(      self      :      List[str]		,   _A      :      Union[str, Any]	)							->    List[Any]:







							"""simple docstring"""


							super().__init__(_A	)

							snake_case_		:			int											=	AutoBackbone.from_config(config.backbone_config	)

							# Semantic segmentation head(s)
							snake_case_		:			List[str]											=	UperNetHead(_A		,   in_channels=self.backbone.channels	)
							snake_case_		:			Union[str, Any]											=	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 UpperCAmelCase_				(      self      :      List[Any]		,   _A      :      Optional[torch.Tensor] = None		,   _A      :      Optional[bool] = None		,   _A      :      Optional[bool] = None		,   _A      :      Optional[torch.Tensor] = None		,   _A      :      Optional[bool] = None		,   )							->    Union[tuple, SemanticSegmenterOutput]:







							"""simple docstring"""


							snake_case_		:			Union[str, Any]											=	return_dict if return_dict is not None else self.config.use_return_dict
							snake_case_		:			Any											=	(
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							snake_case_		:			List[str]											=	output_attentions if output_attentions is not None else self.config.output_attentions

							snake_case_		:			List[Any]											=	self.backbone.forward_with_filtered_kwargs(
							    _A		,   output_hidden_states=_A		,   output_attentions=_A	)
							snake_case_		:			str											=	outputs.feature_maps

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

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

							snake_case_		:			int											=	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
									snake_case_		:			Optional[int]											=	CrossEntropyLoss(ignore_index=self.config.loss_ignore_index	)
									snake_case_		:			str											=	loss_fct(_A		,   _A	)
									snake_case_		:			Optional[int]											=	loss_fct(_A		,   _A	)
									snake_case_		:			List[str]											=	main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

							if not return_dict:
								if output_hidden_states:
									snake_case_		:			Tuple											=	(logits,) + outputs[1:]
								else:
									snake_case_		:			Optional[Any]											=	(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		,   )








from ....utils import logging


_SCREAMING_SNAKE_CASE      	=		logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE_						(					snake_case_					):






						def __init__(      self      :      str		,   _A      :      List[Any]		,   _A      :      List[Any]=None		,   _A      :      str=2048	)							->    Optional[int]:







							"""simple docstring"""


							snake_case_		:			Tuple											=	config.__dict__
							snake_case_		:			List[str]											=	modal_hidden_size
							if num_labels:
								snake_case_		:			int											=	num_labels

