




'''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


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

# General docstring
UpperCamelCase_    	=				"UperNetConfig"






class 							_a				(			nn.Module ):





       '''simple docstring'''






       def __init__(      self,							A,							A,							A,							A = 0,							A = False,							A = 1,							):







             '''simple docstring'''







             super().__init__()
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						nn.Convad(
                 in_channels=A,							out_channels=A,							kernel_size=A,							padding=A,							bias=A,							dilation=A,							)
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						nn.BatchNormad(A  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						nn.ReLU()







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.conv(A  )
             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.batch_norm(A  )
             SCREAMING_SNAKE_CASE   :      Tuple    					=						self.activation(A  )

             return output






class 							_a				(			nn.Module ):





       '''simple docstring'''






       def __init__(      self,							A,							A,							A  ):







             '''simple docstring'''







             super().__init__()
             SCREAMING_SNAKE_CASE   :      str    					=						[
                 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,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						input
             for layer in self.layers:
                   SCREAMING_SNAKE_CASE   :      Dict    					=						layer(A  )
             return hidden_state






class 							_a				(			nn.Module ):





       '''simple docstring'''






       def __init__(      self,							A,							A,							A,							A  ):







             '''simple docstring'''







             super().__init__()
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						pool_scales
             SCREAMING_SNAKE_CASE   :      List[str]    					=						align_corners
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						in_channels
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						channels
             SCREAMING_SNAKE_CASE   :      int    					=						[]
             for i, pool_scale in enumerate(A  ):
                   SCREAMING_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,							A  ):







             '''simple docstring'''







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






class 							_a				(			nn.Module ):





       '''simple docstring'''






       def __init__(      self,							A,							A  ):







             '''simple docstring'''







             super().__init__()

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

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

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             self.apply(self._init_weights  )







       def        UpperCamelCase_							(      self,							A  ):







             '''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,							A  ):







             '''simple docstring'''







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

             return output







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







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

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

             return output






class 							_a				(			nn.Module ):





       '''simple docstring'''






       def __init__(      self,							A,							A = 2,							A = 3,							A = 1  ):







             '''simple docstring'''







             super().__init__()

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

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

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             self.apply(self._init_weights  )







       def        UpperCamelCase_							(      self,							A  ):







             '''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,							A  ):







             '''simple docstring'''







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






class 							_a				(			SCREAMING_SNAKE_CASE ):





       '''simple docstring'''






       A						:				List[Any]        =						UperNetConfig
       A						:				Optional[Any]        =						'''pixel_values'''
       A						:				Optional[int]        =						True







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self,							A,							A=False  ):







             '''simple docstring'''







             if isinstance(A,							A  ):
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						value

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

UpperCamelCase_    	=				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 							_a				(			SCREAMING_SNAKE_CASE ):





       '''simple docstring'''






       def __init__(      self,							A  ):







             '''simple docstring'''







             super().__init__(A  )

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

             # Semantic segmentation head(s)
             SCREAMING_SNAKE_CASE   :      Any    					=						UperNetHead(A,							in_channels=self.backbone.channels  )
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						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,							A = None,							A = None,							A = None,							A = None,							A = None,							):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						return_dict if return_dict is not None else self.config.use_return_dict
             SCREAMING_SNAKE_CASE   :      Tuple    					=						(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             SCREAMING_SNAKE_CASE   :      int    					=						output_attentions if output_attentions is not None else self.config.output_attentions

             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.backbone.forward_with_filtered_kwargs(
                 A,							output_hidden_states=A,							output_attentions=A  )
             SCREAMING_SNAKE_CASE   :      Dict    					=						outputs.feature_maps

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

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						None
             if self.auxiliary_head is not None:
                   SCREAMING_SNAKE_CASE   :      str    					=						self.auxiliary_head(A  )
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						nn.functional.interpolate(
                       A,							size=pixel_values.shape[2:],							mode='bilinear',							align_corners=A  )

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

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



def   lowercase__(			__UpperCamelCase:					int    ):

      """simple docstring"""






      if not isinstance(__UpperCamelCase      ,__UpperCamelCase    ):
            raise TypeError('Input value must be an \'int\' type'    )

      SCREAMING_SNAKE_CASE   :      int    					=						0
      while number:
            position += 1
            number >>= 1

      return position


if __name__ == "__main__":
      import doctest

      doctest.testmod()


