




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       _A				(		nn.Module     ):






		def __init__(    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE = 0						,		_SCREAMING_SNAKE_CASE = False						,		_SCREAMING_SNAKE_CASE = 1						,		):
								super().__init__()
								_UpperCAmelCase      =			nn.Convad(
								    in_channels=_SCREAMING_SNAKE_CASE						,		out_channels=_SCREAMING_SNAKE_CASE						,		kernel_size=_SCREAMING_SNAKE_CASE						,		padding=_SCREAMING_SNAKE_CASE						,		bias=_SCREAMING_SNAKE_CASE						,		dilation=_SCREAMING_SNAKE_CASE						,		)
								_UpperCAmelCase      =			nn.BatchNormad(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			nn.ReLU()






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			self.conv(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			self.batch_norm(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			self.activation(_SCREAMING_SNAKE_CASE			)

								return output




class       _A				(		nn.Module     ):






		def __init__(    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								super().__init__()
								_UpperCAmelCase      =			[
								    nn.AdaptiveAvgPoolad(_SCREAMING_SNAKE_CASE			),
								    UperNetConvModule(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		kernel_size=1			),
								]
								for i, layer in enumerate(self.layers			):
														self.add_module(str(_SCREAMING_SNAKE_CASE			)						,		_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			input
								for layer in self.layers:
														_UpperCAmelCase      =			layer(_SCREAMING_SNAKE_CASE			)
								return hidden_state




class       _A				(		nn.Module     ):






		def __init__(    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								super().__init__()
								_UpperCAmelCase      =			pool_scales
								_UpperCAmelCase      =			align_corners
								_UpperCAmelCase      =			in_channels
								_UpperCAmelCase      =			channels
								_UpperCAmelCase      =			[]
								for i, pool_scale in enumerate(_SCREAMING_SNAKE_CASE			):
														_UpperCAmelCase      =			UperNetPyramidPoolingBlock(pool_scale=_SCREAMING_SNAKE_CASE						,		in_channels=_SCREAMING_SNAKE_CASE						,		channels=_SCREAMING_SNAKE_CASE			)
														self.blocks.append(_SCREAMING_SNAKE_CASE			)
														self.add_module(str(_SCREAMING_SNAKE_CASE			)						,		_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			[]
								for ppm in self.blocks:
														_UpperCAmelCase      =			ppm(_SCREAMING_SNAKE_CASE			)
														_UpperCAmelCase      =			nn.functional.interpolate(
														    _SCREAMING_SNAKE_CASE						,		size=x.size()[2:]						,		mode="""bilinear"""						,		align_corners=self.align_corners			)
														ppm_outs.append(_SCREAMING_SNAKE_CASE			)
								return ppm_outs




class       _A				(		nn.Module     ):






		def __init__(    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								super().__init__()

								_UpperCAmelCase      =			config
								_UpperCAmelCase      =			config.pool_scales  # e.g. (1, 2, 3, 6)
								_UpperCAmelCase      =			in_channels
								_UpperCAmelCase      =			config.hidden_size
								_UpperCAmelCase      =			False
								_UpperCAmelCase      =			nn.Convad(self.channels						,		config.num_labels						,		kernel_size=1			)

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

								_UpperCAmelCase      =			UperNetConvModule(
								    len(self.in_channels			) * self.channels						,		self.channels						,		kernel_size=3						,		padding=1						,		)






		def 				UpperCAmelCase (    self			):
								self.apply(self._init_weights			)






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								if isinstance(_SCREAMING_SNAKE_CASE						,		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						,		_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			inputs[-1]
								_UpperCAmelCase      =			[x]
								psp_outs.extend(self.psp_modules(_SCREAMING_SNAKE_CASE			)			)
								_UpperCAmelCase      =			torch.cat(_SCREAMING_SNAKE_CASE						,		dim=1			)
								_UpperCAmelCase      =			self.bottleneck(_SCREAMING_SNAKE_CASE			)

								return output






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								# build laterals
								_UpperCAmelCase      =			[lateral_conv(encoder_hidden_states[i]			) for i, lateral_conv in enumerate(self.lateral_convs			)]

								laterals.append(self.psp_forward(_SCREAMING_SNAKE_CASE			)			)

								# build top-down path
								_UpperCAmelCase      =			len(_SCREAMING_SNAKE_CASE			)
								for i in range(used_backbone_levels - 1						,		0						,		-1			):
														_UpperCAmelCase      =			laterals[i - 1].shape[2:]
														_UpperCAmelCase      =			laterals[i - 1] + nn.functional.interpolate(
														    laterals[i]						,		size=_SCREAMING_SNAKE_CASE						,		mode="""bilinear"""						,		align_corners=self.align_corners			)

								# build outputs
								_UpperCAmelCase      =			[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			):
														_UpperCAmelCase      =			nn.functional.interpolate(
														    fpn_outs[i]						,		size=fpn_outs[0].shape[2:]						,		mode="""bilinear"""						,		align_corners=self.align_corners			)
								_UpperCAmelCase      =			torch.cat(_SCREAMING_SNAKE_CASE						,		dim=1			)
								_UpperCAmelCase      =			self.fpn_bottleneck(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			self.classifier(_SCREAMING_SNAKE_CASE			)

								return output




class       _A				(		nn.Module     ):






		def __init__(    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE = 2						,		_SCREAMING_SNAKE_CASE = 3						,		_SCREAMING_SNAKE_CASE = 1			):
								super().__init__()

								_UpperCAmelCase      =			config
								_UpperCAmelCase      =			config.auxiliary_in_channels
								_UpperCAmelCase      =			config.auxiliary_channels
								_UpperCAmelCase      =			config.auxiliary_num_convs
								_UpperCAmelCase      =			config.auxiliary_concat_input
								_UpperCAmelCase      =			in_index

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

								_UpperCAmelCase      =			nn.Convad(self.channels						,		config.num_labels						,		kernel_size=1			)






		def 				UpperCAmelCase (    self			):
								self.apply(self._init_weights			)






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								if isinstance(_SCREAMING_SNAKE_CASE						,		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						,		_SCREAMING_SNAKE_CASE			):
								# just take the relevant feature maps
								_UpperCAmelCase      =			encoder_hidden_states[self.in_index]
								_UpperCAmelCase      =			self.convs(_SCREAMING_SNAKE_CASE			)
								if self.concat_input:
														_UpperCAmelCase      =			self.conv_cat(torch.cat([hidden_states, output]						,		dim=1			)			)
								_UpperCAmelCase      =			self.classifier(_SCREAMING_SNAKE_CASE			)
								return output




class       _A				(		__lowercase     ):
		__a					    =       UperNetConfig
		__a					    =       """pixel_values"""
		__a					    =       True






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								if isinstance(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
														module.backbone.init_weights()
														module.decode_head.init_weights()
														module.auxiliary_head.init_weights()






		def 				UpperCAmelCase (    self			):
								self.backbone.init_weights()
								self.decode_head.init_weights()
								self.auxiliary_head.init_weights()






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE=False			):
								if isinstance(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
														_UpperCAmelCase      =			value



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

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




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






		def __init__(    self						,		_SCREAMING_SNAKE_CASE			):
								super().__init__(_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			AutoBackbone.from_config(config.backbone_config			)

								# Semantic segmentation head(s)
								_UpperCAmelCase      =			UperNetHead(_SCREAMING_SNAKE_CASE						,		in_channels=self.backbone.channels			)
								_UpperCAmelCase      =			UperNetFCNHead(_SCREAMING_SNAKE_CASE			) 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=_SCREAMING_SNAKE_CASE						,		config_class=_CONFIG_FOR_DOC			)
		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE = None						,		_SCREAMING_SNAKE_CASE = None						,		_SCREAMING_SNAKE_CASE = None						,		_SCREAMING_SNAKE_CASE = None						,		_SCREAMING_SNAKE_CASE = None						,		):
								_UpperCAmelCase      =			return_dict if return_dict is not None else self.config.use_return_dict
								_UpperCAmelCase      =			(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								_UpperCAmelCase      =			output_attentions if output_attentions is not None else self.config.output_attentions

								_UpperCAmelCase      =			self.backbone.forward_with_filtered_kwargs(
								    _SCREAMING_SNAKE_CASE						,		output_hidden_states=_SCREAMING_SNAKE_CASE						,		output_attentions=_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			outputs.feature_maps

								_UpperCAmelCase      =			self.decode_head(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			nn.functional.interpolate(_SCREAMING_SNAKE_CASE						,		size=pixel_values.shape[2:]						,		mode="""bilinear"""						,		align_corners=_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			None
								if self.auxiliary_head is not None:
														_UpperCAmelCase      =			self.auxiliary_head(_SCREAMING_SNAKE_CASE			)
														_UpperCAmelCase      =			nn.functional.interpolate(
														    _SCREAMING_SNAKE_CASE						,		size=pixel_values.shape[2:]						,		mode="""bilinear"""						,		align_corners=_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			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
																				_UpperCAmelCase      =			CrossEntropyLoss(ignore_index=self.config.loss_ignore_index			)
																				_UpperCAmelCase      =			loss_fct(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)
																				_UpperCAmelCase      =			loss_fct(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)
																				_UpperCAmelCase      =			main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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

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





from typing import Dict

from .base import GenericTensor, Pipeline




class       _A				(		__lowercase     ):






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE=None						,		_SCREAMING_SNAKE_CASE=None						,		_SCREAMING_SNAKE_CASE=None						,		**_SCREAMING_SNAKE_CASE			):
								if tokenize_kwargs is None:
														_UpperCAmelCase      =			{}

								if truncation is not None:
														if "truncation" in tokenize_kwargs:
																				raise ValueError(
																				    """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)"""			)
														_UpperCAmelCase      =			truncation

								_UpperCAmelCase      =			tokenize_kwargs

								_UpperCAmelCase      =			{}
								if return_tensors is not None:
														_UpperCAmelCase      =			return_tensors

								return preprocess_params, {}, postprocess_params






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			self.framework
								_UpperCAmelCase      =			self.tokenizer(_SCREAMING_SNAKE_CASE						,		return_tensors=_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			)
								return model_inputs






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			self.model(**_SCREAMING_SNAKE_CASE			)
								return model_outputs






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE=False			):
								# [0] is the first available tensor, logits or last_hidden_state.
								if return_tensors:
														return model_outputs[0]
								if self.framework == "pt":
														return model_outputs[0].tolist()
								elif self.framework == "tf":
														return model_outputs[0].numpy().tolist()






		def __call__(    self						,		*_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			):
								return super().__call__(*_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			)