



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


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

# General docstring
_lowercase		:				List[Any]      		="UperNetConfig"

class        snake_case__    (nn.Module		):







      """simple docstring"""




      def __init__(       self ,       __lowercase ,       __lowercase ,       __lowercase ,       __lowercase = 0 ,       __lowercase = False ,       __lowercase = 1 ,       ) ->				None:
         """simple docstring"""




         super().__init__()
         a__       :						List[Any]							=  nn.Convad(
             in_channels=__lowercase ,       out_channels=__lowercase ,       kernel_size=__lowercase ,       padding=__lowercase ,       bias=__lowercase ,       dilation=__lowercase ,       )
         a__       :						Optional[int]							=  nn.BatchNormad(__lowercase  )
         a__       :						Any							=  nn.ReLU()

      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				torch.Tensor:
         """simple docstring"""




         a__       :						Dict							=  self.conv(__lowercase  )
         a__       :						str							=  self.batch_norm(__lowercase  )
         a__       :						Optional[int]							=  self.activation(__lowercase  )

         return output




class        snake_case__    (nn.Module		):







      """simple docstring"""




      def __init__(       self ,       __lowercase ,       __lowercase ,       __lowercase  ) ->				None:
         """simple docstring"""




         super().__init__()
         a__       :						Optional[Any]							=  [
             nn.AdaptiveAvgPoolad(__lowercase  ),
             UperNetConvModule(__lowercase ,       __lowercase ,       kernel_size=1  ),
         ]
         for i, layer in enumerate(self.layers  ):
            self.add_module(str(__lowercase  ) ,       __lowercase  )

      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				torch.Tensor:
         """simple docstring"""




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




class        snake_case__    (nn.Module		):







      """simple docstring"""




      def __init__(       self ,       __lowercase ,       __lowercase ,       __lowercase ,       __lowercase  ) ->				None:
         """simple docstring"""




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

      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				List[torch.Tensor]:
         """simple docstring"""




         a__       :						Optional[Any]							=  []
         for ppm in self.blocks:
            a__       :						List[str]							=  ppm(__lowercase  )
            a__       :						Any							=  nn.functional.interpolate(
                __lowercase ,       size=x.size()[2:] ,       mode="""bilinear""" ,       align_corners=self.align_corners  )
            ppm_outs.append(__lowercase  )
         return ppm_outs




class        snake_case__    (nn.Module		):







      """simple docstring"""




      def __init__(       self ,       __lowercase ,       __lowercase  ) ->				Optional[int]:
         """simple docstring"""




         super().__init__()

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

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

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

      def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Union[str, Any]:
         """simple docstring"""




         self.apply(self._init_weights  )

      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Union[str, Any]:
         """simple docstring"""




         if isinstance(__lowercase ,       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 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Any:
         """simple docstring"""




         a__       :						Optional[Any]							=  inputs[-1]
         a__       :						Any							=  [x]
         psp_outs.extend(self.psp_modules(__lowercase  )  )
         a__       :						str							=  torch.cat(__lowercase ,       dim=1  )
         a__       :						Optional[Any]							=  self.bottleneck(__lowercase  )

         return output

      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				torch.Tensor:
         """simple docstring"""




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

         laterals.append(self.psp_forward(__lowercase  )  )

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

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

         return output




class        snake_case__    (nn.Module		):







      """simple docstring"""




      def __init__(       self ,       __lowercase ,       __lowercase = 2 ,       __lowercase = 3 ,       __lowercase = 1  ) ->				None:
         """simple docstring"""




         super().__init__()

         a__       :						Union[str, Any]							=  config
         a__       :						Union[str, Any]							=  config.auxiliary_in_channels
         a__       :						Tuple							=  config.auxiliary_channels
         a__       :						str							=  config.auxiliary_num_convs
         a__       :						Tuple							=  config.auxiliary_concat_input
         a__       :						str							=  in_index

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

         a__       :						Union[str, Any]							=  nn.Convad(self.channels ,       config.num_labels ,       kernel_size=1  )

      def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[Any]:
         """simple docstring"""




         self.apply(self._init_weights  )

      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Optional[int]:
         """simple docstring"""




         if isinstance(__lowercase ,       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 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				torch.Tensor:
         """simple docstring"""




         a__       :						str							=  encoder_hidden_states[self.in_index]
         a__       :						List[Any]							=  self.convs(__lowercase  )
         if self.concat_input:
            a__       :						Tuple							=  self.conv_cat(torch.cat([hidden_states, output] ,       dim=1  )  )
         a__       :						List[Any]							=  self.classifier(__lowercase  )
         return output




class        snake_case__    (A__		):







      """simple docstring"""




      __lowerCAmelCase					:Union[str, Any]      =					UperNetConfig
      __lowerCAmelCase					:str      =					"pixel_values"
      __lowerCAmelCase					:int      =					True

      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Dict:
         """simple docstring"""




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

      def 							SCREAMING_SNAKE_CASE__(       self  ) ->				List[str]:
         """simple docstring"""




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

      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase=False  ) ->				List[str]:
         """simple docstring"""




         if isinstance(__lowercase ,       __lowercase  ):
            a__       :						Dict							=  value




_lowercase		:				Union[str, Any]      		=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"

_lowercase		:				List[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." ,     A__ ,     )
class        snake_case__    (A__		):







      """simple docstring"""




      def __init__(       self ,       __lowercase  ) ->				List[Any]:
         """simple docstring"""




         super().__init__(__lowercase  )

         a__       :						Optional[Any]							=  AutoBackbone.from_config(config.backbone_config  )

         # Semantic segmentation head(s)
         a__       :						Tuple							=  UperNetHead(__lowercase ,       in_channels=self.backbone.channels  )
         a__       :						Union[str, Any]							=  UperNetFCNHead(__lowercase  ) 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=__lowercase ,       config_class=_CONFIG_FOR_DOC  )
      def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase = None ,       __lowercase = None ,       __lowercase = None ,       __lowercase = None ,       __lowercase = None ,       ) ->				Union[tuple, SemanticSegmenterOutput]:
         """simple docstring"""




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

         a__       :						int							=  self.backbone.forward_with_filtered_kwargs(
             __lowercase ,       output_hidden_states=__lowercase ,       output_attentions=__lowercase  )
         a__       :						Any							=  outputs.feature_maps

         a__       :						Tuple							=  self.decode_head(__lowercase  )
         a__       :						Any							=  nn.functional.interpolate(__lowercase ,       size=pixel_values.shape[2:] ,       mode="""bilinear""" ,       align_corners=__lowercase  )

         a__       :						Tuple							=  None
         if self.auxiliary_head is not None:
            a__       :						Dict							=  self.auxiliary_head(__lowercase  )
            a__       :						int							=  nn.functional.interpolate(
                __lowercase ,       size=pixel_values.shape[2:] ,       mode="""bilinear""" ,       align_corners=__lowercase  )

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

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

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









def      lowerCAmelCase_					(  _lowercase    :       int)							->	int:







			"""simple docstring"""

			if not isinstance(_lowercase						,       _lowercase):
						raise TypeError("""only integers accepted as input""")
			else:
						a__       :						Any							=  str(abs(_lowercase))
						a__       :						str							=  [list(_lowercase) for char in range(len(_lowercase))]
						for index in range(len(_lowercase)):
									num_transpositions[index].pop(_lowercase)
						return max(
						    int("""""".join(list(_lowercase))) for transposition in num_transpositions)


if __name__ == "__main__":
		__import__("doctest").testmod()




