
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__   :					List[Any]							=   [
    'openmmlab/upernet-convnext-tiny',
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
A__   :					List[Any]							=   'UperNetConfig'


class 			__magic_name__       (       nn.Module ):
       def __init__(     self ,				A_ ,				A_ ,				A_ ,				A_ = 0 ,				A_ = False ,				A_ = 1 ,				)     ->	None:





         """simple docstring"""




         super().__init__()
         _lowercase:			Union[str, Any]       =     nn.Convad(
             in_channels=A_ ,				out_channels=A_ ,				kernel_size=A_ ,				padding=A_ ,				bias=A_ ,				dilation=A_ ,				)
         _lowercase:			Any       =     nn.BatchNormad(A_       )
         _lowercase:			List[Any]       =     nn.ReLU()



       def 							lowercase_							(     self ,				A_       )     ->	torch.Tensor:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     self.conv(A_       )
         _lowercase:			Union[str, Any]       =     self.batch_norm(A_       )
         _lowercase:			Any       =     self.activation(A_       )

         return output


class 			__magic_name__       (       nn.Module ):
       def __init__(     self ,				A_ ,				A_ ,				A_       )     ->	None:





         """simple docstring"""




         super().__init__()
         _lowercase:			List[str]       =     [
             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:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     input
         for layer in self.layers:
           _lowercase:			Union[str, Any]       =     layer(A_       )
         return hidden_state


class 			__magic_name__       (       nn.Module ):
       def __init__(     self ,				A_ ,				A_ ,				A_ ,				A_       )     ->	None:





         """simple docstring"""




         super().__init__()
         _lowercase:			Optional[int]       =     pool_scales
         _lowercase:			Any       =     align_corners
         _lowercase:			Union[str, Any]       =     in_channels
         _lowercase:			str       =     channels
         _lowercase:			Dict       =     []
         for i, pool_scale in enumerate(A_       ):
           _lowercase:			Any       =     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]:





         """simple docstring"""




         _lowercase:			Any       =     []
         for ppm in self.blocks:
           _lowercase:			Dict       =     ppm(A_       )
           _lowercase:			Any       =     nn.functional.interpolate(
               A_ ,				size=x.size()[2:] ,				mode='''bilinear''' ,				align_corners=self.align_corners       )
           ppm_outs.append(A_       )
         return ppm_outs


class 			__magic_name__       (       nn.Module ):
       def __init__(     self ,				A_ ,				A_       )     ->	Tuple:





         """simple docstring"""




         super().__init__()

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

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

         _lowercase:			Tuple       =     UperNetConvModule(
             len(self.in_channels       ) * self.channels ,				self.channels ,				kernel_size=3 ,				padding=1 ,				)
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         self.apply(self._init_weights       )
       def 							lowercase_							(     self ,				A_       )     ->	Union[str, 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 							lowercase_							(     self ,				A_       )     ->	Tuple:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     inputs[-1]
         _lowercase:			Dict       =     [x]
         psp_outs.extend(self.psp_modules(A_       )       )
         _lowercase:			int       =     torch.cat(A_ ,				dim=1       )
         _lowercase:			Tuple       =     self.bottleneck(A_       )

         return output



       def 							lowercase_							(     self ,				A_       )     ->	torch.Tensor:





         """simple docstring"""




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

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

         return output


class 			__magic_name__       (       nn.Module ):
       def __init__(     self ,				A_ ,				A_ = 2 ,				A_ = 3 ,				A_ = 1       )     ->	None:





         """simple docstring"""




         super().__init__()

         _lowercase:			List[Any]       =     config
         _lowercase:			List[str]       =     config.auxiliary_in_channels
         _lowercase:			int       =     config.auxiliary_channels
         _lowercase:			Optional[int]       =     config.auxiliary_num_convs
         _lowercase:			List[str]       =     config.auxiliary_concat_input
         _lowercase:			Optional[int]       =     in_index

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

         _lowercase:			int       =     nn.Convad(self.channels ,				config.num_labels ,				kernel_size=1       )
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         self.apply(self._init_weights       )
       def 							lowercase_							(     self ,				A_       )     ->	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 							lowercase_							(     self ,				A_       )     ->	torch.Tensor:





         """simple docstring"""




         _lowercase:			Dict       =     encoder_hidden_states[self.in_index]
         _lowercase:			Optional[Any]       =     self.convs(A_       )
         if self.concat_input:
           _lowercase:			Optional[int]       =     self.conv_cat(torch.cat([hidden_states, output] ,				dim=1       )       )
         _lowercase:			List[Any]       =     self.classifier(A_       )
         return output


class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       UpperCamelCase_   =		UperNetConfig
       UpperCamelCase_   =		'''pixel_values'''
       UpperCamelCase_   =		True
       def 							lowercase_							(     self ,				A_       )     ->	Dict:





         """simple docstring"""




         if isinstance(A_ ,				A_       ):
           module.backbone.init_weights()
           module.decode_head.init_weights()
           module.auxiliary_head.init_weights()
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




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



       def 							lowercase_							(     self ,				A_ ,				A_=False       )     ->	Tuple:





         """simple docstring"""




         if isinstance(A_ ,				A_       ):
           _lowercase:			Any       =     value

A__   :					Dict							=   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__   :					Any							=   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.'''   ,					SCREAMING_SNAKE_CASE__   ,					)
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       def __init__(     self ,				A_       )     ->	str:





         """simple docstring"""




         super().__init__(A_       )

         _lowercase:			Optional[int]       =     AutoBackbone.from_config(config.backbone_config       )

         # Semantic segmentation head(s)
         _lowercase:			Any       =     UperNetHead(A_ ,				in_channels=self.backbone.channels       )
         _lowercase:			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]:





         """simple docstring"""




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

         _lowercase:			List[str]       =     self.backbone.forward_with_filtered_kwargs(
             A_ ,				output_hidden_states=A_ ,				output_attentions=A_       )
         _lowercase:			Optional[int]       =     outputs.feature_maps

         _lowercase:			Any       =     self.decode_head(A_       )
         _lowercase:			Optional[int]       =     nn.functional.interpolate(A_ ,				size=pixel_values.shape[2:] ,				mode='''bilinear''' ,				align_corners=A_       )

         _lowercase:			Tuple       =     None
         if self.auxiliary_head is not None:
           _lowercase:			str       =     self.auxiliary_head(A_       )
           _lowercase:			Union[str, Any]       =     nn.functional.interpolate(
               A_ ,				size=pixel_values.shape[2:] ,				mode='''bilinear''' ,				align_corners=A_       )

         _lowercase:			Union[str, Any]       =     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
             _lowercase:			List[str]       =     CrossEntropyLoss(ignore_index=self.config.loss_ignore_index       )
             _lowercase:			List[Any]       =     loss_fct(A_ ,				A_       )
             _lowercase:			Tuple       =     loss_fct(A_ ,				A_       )
             _lowercase:			Dict       =     main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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


"""simple docstring"""




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


A__   :					Dict							=   logging.get_logger(__name__)


class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       UpperCamelCase_   =		['''pixel_values''']
       def __init__(     self ,				A_ = True ,				A_ = None ,				A_ = PILImageResampling.BICUBIC ,				A_ = True ,				A_ = True ,				A_ = 1 / 255 ,				A_ = None ,				A_ = True ,				A_ = None ,				A_ = None ,				**A_ ,				)     ->	None:





         """simple docstring"""




         super().__init__(**A_       )
         _lowercase:			List[str]       =     size if size is not None else {'''height''': 224, '''width''': 224}
         _lowercase:			Dict       =     get_size_dict(A_       )
         _lowercase:			Any       =     crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
         _lowercase:			List[str]       =     get_size_dict(A_ ,				default_to_square=A_ ,				param_name='''crop_size'''       )

         _lowercase:			List[Any]       =     do_resize
         _lowercase:			Tuple       =     do_rescale
         _lowercase:			Union[str, Any]       =     do_normalize
         _lowercase:			Optional[int]       =     do_center_crop
         _lowercase:			List[str]       =     crop_size
         _lowercase:			int       =     size
         _lowercase:			List[Any]       =     resample
         _lowercase:			Optional[Any]       =     rescale_factor
         _lowercase:			str       =     image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
         _lowercase:			Dict       =     image_std if image_std is not None else IMAGENET_DEFAULT_STD
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ = PILImageResampling.BILINEAR ,				A_ = None ,				**A_ ,				)     ->	np.ndarray:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     get_size_dict(A_       )

         if "shortest_edge" in size:
           _lowercase:			Optional[int]       =     get_resize_output_image_size(A_ ,				size=size['''shortest_edge'''] ,				default_to_square=A_       )
           # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
         elif "height" in size and "width" in size:
           _lowercase:			Dict       =     (size['''height'''], size['''width'''])
         else:
           raise ValueError(f'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}'''       )
         return resize(A_ ,				size=A_ ,				resample=A_ ,				data_format=A_ ,				**A_       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ = None ,				**A_ ,				)     ->	np.ndarray:





         """simple docstring"""




         _lowercase:			Dict       =     get_size_dict(A_       )
         if "height" not in size or "width" not in size:
           raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''       )
         return center_crop(A_ ,				size=(size['''height'''], size['''width''']) ,				data_format=A_ ,				**A_       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ = None ,				**A_       )     ->	np.ndarray:





         """simple docstring"""




         return rescale(A_ ,				scale=A_ ,				data_format=A_ ,				**A_       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ = None ,				**A_ ,				)     ->	np.ndarray:





         """simple docstring"""




         return normalize(A_ ,				mean=A_ ,				std=A_ ,				data_format=A_ ,				**A_       )



       def 							lowercase_							(     self ,				A_ ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = ChannelDimension.FIRST ,				**A_ ,				)     ->	BatchFeature:





         """simple docstring"""




         _lowercase:			List[Any]       =     do_resize if do_resize is not None else self.do_resize
         _lowercase:			Tuple       =     do_rescale if do_rescale is not None else self.do_rescale
         _lowercase:			Optional[Any]       =     do_normalize if do_normalize is not None else self.do_normalize
         _lowercase:			Optional[int]       =     do_center_crop if do_center_crop is not None else self.do_center_crop
         _lowercase:			Optional[int]       =     crop_size if crop_size is not None else self.crop_size
         _lowercase:			List[Any]       =     get_size_dict(A_ ,				param_name='''crop_size''' ,				default_to_square=A_       )
         _lowercase:			List[str]       =     resample if resample is not None else self.resample
         _lowercase:			List[str]       =     rescale_factor if rescale_factor is not None else self.rescale_factor
         _lowercase:			List[Any]       =     image_mean if image_mean is not None else self.image_mean
         _lowercase:			List[str]       =     image_std if image_std is not None else self.image_std

         _lowercase:			List[Any]       =     size if size is not None else self.size
         _lowercase:			List[str]       =     get_size_dict(A_       )

         if not is_batched(A_       ):
           _lowercase:			Optional[Any]       =     [images]

         if not valid_images(A_       ):
           raise ValueError(
               '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
               '''torch.Tensor, tf.Tensor or jax.ndarray.'''       )

         if do_resize and size is None:
           raise ValueError('''Size must be specified if do_resize is True.'''       )

         if do_center_crop and crop_size is None:
           raise ValueError('''Crop size must be specified if do_center_crop is True.'''       )

         if do_rescale and rescale_factor is None:
           raise ValueError('''Rescale factor must be specified if do_rescale is True.'''       )

         # All transformations expect numpy arrays.
         _lowercase:			Dict       =     [to_numpy_array(A_       ) for image in images]

         if do_resize:
           _lowercase:			int       =     [self.resize(image=A_ ,				size=A_ ,				resample=A_       ) for image in images]

         if do_center_crop:
           _lowercase:			str       =     [self.center_crop(image=A_ ,				size=A_       ) for image in images]

         if do_rescale:
           _lowercase:			Optional[Any]       =     [self.rescale(image=A_ ,				scale=A_       ) for image in images]

         if do_normalize:
           _lowercase:			List[Any]       =     [self.normalize(image=A_ ,				mean=A_ ,				std=A_       ) for image in images]

         _lowercase:			Optional[Any]       =     [to_channel_dimension_format(A_ ,				A_       ) for image in images]

         _lowercase:			Any       =     {'''pixel_values''': images}
         return BatchFeature(data=A_ ,				tensor_type=A_       )
