"""simple docstring"""







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  UpperCamelCase	(    nn.Module						):
   def __init__(    self  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase = 0  ,__UpperCamelCase = False  ,__UpperCamelCase = 1  ,)			->   None:


        '''simple docstring'''


        super().__init__()
        lowercase_			:       Optional[int]									=			nn.Convad(
            in_channels=__UpperCamelCase  ,out_channels=__UpperCamelCase  ,kernel_size=__UpperCamelCase  ,padding=__UpperCamelCase  ,bias=__UpperCamelCase  ,dilation=__UpperCamelCase  ,)
        lowercase_			:       Tuple									=			nn.BatchNormad(__UpperCamelCase    )
        lowercase_			:       Dict									=			nn.ReLU()







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   torch.Tensor:


        '''simple docstring'''


        lowercase_			:       Optional[int]									=			self.conv(__UpperCamelCase    )
        lowercase_			:       List[str]									=			self.batch_norm(__UpperCamelCase    )
        lowercase_			:       Optional[int]									=			self.activation(__UpperCamelCase    )

        return output







class  UpperCamelCase	(    nn.Module						):
   def __init__(    self  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase    )			->   None:


        '''simple docstring'''


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







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   torch.Tensor:


        '''simple docstring'''


        lowercase_			:       int									=			input
        for layer in self.layers:
             lowercase_			:       Optional[int]									=			layer(__UpperCamelCase    )
        return hidden_state







class  UpperCamelCase	(    nn.Module						):
   def __init__(    self  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase    )			->   None:


        '''simple docstring'''


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







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   List[torch.Tensor]:


        '''simple docstring'''


        lowercase_			:       Union[str, Any]									=			[]
        for ppm in self.blocks:
             lowercase_			:       Tuple									=			ppm(__UpperCamelCase    )
             lowercase_			:       int									=			nn.functional.interpolate(
                 __UpperCamelCase  ,size=x.size()[2:]  ,mode='bilinear'  ,align_corners=self.align_corners    )
             ppm_outs.append(__UpperCamelCase    )
        return ppm_outs







class  UpperCamelCase	(    nn.Module						):
   def __init__(    self  ,__UpperCamelCase  ,__UpperCamelCase    )			->   Tuple:


        '''simple docstring'''


        super().__init__()

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

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

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


        '''simple docstring'''


        self.apply(self._init_weights    )
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   Optional[int]:


        '''simple docstring'''


        if isinstance(__UpperCamelCase  ,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  ,__UpperCamelCase    )			->   Tuple:


        '''simple docstring'''


        lowercase_			:       int									=			inputs[-1]
        lowercase_			:       Optional[int]									=			[x]
        psp_outs.extend(self.psp_modules(__UpperCamelCase    )    )
        lowercase_			:       Dict									=			torch.cat(__UpperCamelCase  ,dim=1    )
        lowercase_			:       Union[str, Any]									=			self.bottleneck(__UpperCamelCase    )

        return output







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   torch.Tensor:


        '''simple docstring'''


        lowercase_			:       Dict									=			[lateral_conv(encoder_hidden_states[i]    ) for i, lateral_conv in enumerate(self.lateral_convs    )]

        laterals.append(self.psp_forward(__UpperCamelCase    )    )

        # build top-down path
        lowercase_			:       Tuple									=			len(__UpperCamelCase    )
        for i in range(used_backbone_levels - 1  ,0  ,-1    ):
             lowercase_			:       Dict									=			laterals[i - 1].shape[2:]
             lowercase_			:       str									=			laterals[i - 1] + nn.functional.interpolate(
                 laterals[i]  ,size=__UpperCamelCase  ,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_			:       int									=			nn.functional.interpolate(
                 fpn_outs[i]  ,size=fpn_outs[0].shape[2:]  ,mode='bilinear'  ,align_corners=self.align_corners    )
        lowercase_			:       int									=			torch.cat(__UpperCamelCase  ,dim=1    )
        lowercase_			:       Union[str, Any]									=			self.fpn_bottleneck(__UpperCamelCase    )
        lowercase_			:       Tuple									=			self.classifier(__UpperCamelCase    )

        return output







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


        '''simple docstring'''


        super().__init__()

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

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

        lowercase_			:       Any									=			nn.Convad(self.channels  ,config.num_labels  ,kernel_size=1    )
   def     _UpperCAmelCase     (    self    )			->   Union[str, Any]:


        '''simple docstring'''


        self.apply(self._init_weights    )
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   Dict:


        '''simple docstring'''


        if isinstance(__UpperCamelCase  ,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  ,__UpperCamelCase    )			->   torch.Tensor:


        '''simple docstring'''


        lowercase_			:       Dict									=			encoder_hidden_states[self.in_index]
        lowercase_			:       Union[str, Any]									=			self.convs(__UpperCamelCase    )
        if self.concat_input:
             lowercase_			:       Tuple									=			self.conv_cat(torch.cat([hidden_states, output]  ,dim=1    )    )
        lowercase_			:       str									=			self.classifier(__UpperCamelCase    )
        return output







class  UpperCamelCase	(    lowercase_						):
   lowercase							=						UperNetConfig
   lowercase							=						'pixel_values'
   lowercase							=						True
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   int:


        '''simple docstring'''


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


        '''simple docstring'''


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







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase=False    )			->   Optional[Any]:


        '''simple docstring'''


        if isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
             lowercase_			:       Union[str, Any]									=			value






__SCREAMING_SNAKE_CASE								=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"

__SCREAMING_SNAKE_CASE								=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  UpperCamelCase	(    lowercase_						):
   def __init__(    self  ,__UpperCamelCase    )			->   Tuple:


        '''simple docstring'''


        super().__init__(__UpperCamelCase    )

        lowercase_			:       List[str]									=			AutoBackbone.from_config(config.backbone_config    )

        # Semantic segmentation head(s)
        lowercase_			:       Optional[int]									=			UperNetHead(__UpperCamelCase  ,in_channels=self.backbone.channels    )
        lowercase_			:       Optional[Any]									=			UperNetFCNHead(__UpperCamelCase    ) 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=__UpperCamelCase  ,config_class=_CONFIG_FOR_DOC    )
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,)			->   Union[tuple, SemanticSegmenterOutput]:


        '''simple docstring'''


        lowercase_			:       Dict									=			return_dict if return_dict is not None else self.config.use_return_dict
        lowercase_			:       Optional[Any]									=			(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        lowercase_			:       Tuple									=			output_attentions if output_attentions is not None else self.config.output_attentions

        lowercase_			:       Any									=			self.backbone.forward_with_filtered_kwargs(
            __UpperCamelCase  ,output_hidden_states=__UpperCamelCase  ,output_attentions=__UpperCamelCase    )
        lowercase_			:       Optional[int]									=			outputs.feature_maps

        lowercase_			:       Union[str, Any]									=			self.decode_head(__UpperCamelCase    )
        lowercase_			:       Dict									=			nn.functional.interpolate(__UpperCamelCase  ,size=pixel_values.shape[2:]  ,mode='bilinear'  ,align_corners=__UpperCamelCase    )

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

        lowercase_			:       Dict									=			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[Any]									=			CrossEntropyLoss(ignore_index=self.config.loss_ignore_index    )
                  lowercase_			:       Optional[Any]									=			loss_fct(__UpperCamelCase  ,__UpperCamelCase    )
                  lowercase_			:       Union[str, Any]									=			loss_fct(__UpperCamelCase  ,__UpperCamelCase    )
                  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_			:       Tuple									=			(logits,) + outputs[2:]
             return ((loss,) + output) if loss is not None else output

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


"""simple docstring"""







from diffusers.utils.testing_utils import require_onnxruntime







@require_onnxruntime
class  UpperCamelCase	:
   pass

