




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


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

# General docstring
_lowerCamelCase      			=						'UperNetConfig'



class       a					(       nn.Module      ):

					'''simple docstring'''





					def __init__(     self       :      Union[str, Any] ,   __snake_case       :      int ,   __snake_case       :      int ,   __snake_case       :      Union[int, Tuple[int, int]] ,   __snake_case       :      Union[int, Tuple[int, int], str] = 0 ,   __snake_case       :      bool = False ,   __snake_case       :      Union[int, Tuple[int, int]] = 1 ,   ):
									super().__init__()
									UpperCAmelCase_										=					nn.Convad(
									    in_channels=__snake_case ,   out_channels=__snake_case ,   kernel_size=__snake_case ,   padding=__snake_case ,   bias=__snake_case ,   dilation=__snake_case ,   )
									UpperCAmelCase_										=					nn.BatchNormad(__snake_case    )
									UpperCAmelCase_										=					nn.ReLU()




					def   lowerCamelCase_       (     self       :      int ,   __snake_case       :      torch.Tensor    ):
									UpperCAmelCase_										=					self.conv(__snake_case    )
									UpperCAmelCase_										=					self.batch_norm(__snake_case    )
									UpperCAmelCase_										=					self.activation(__snake_case    )

									return output



class       a					(       nn.Module      ):

					'''simple docstring'''





					def __init__(     self       :      Union[str, Any] ,   __snake_case       :      int ,   __snake_case       :      int ,   __snake_case       :      int    ):
									super().__init__()
									UpperCAmelCase_										=					[
									    nn.AdaptiveAvgPoolad(__snake_case    ),
									    UperNetConvModule(__snake_case ,   __snake_case ,   kernel_size=1    ),
									]
									for i, layer in enumerate(self.layers    ):
													self.add_module(str(__snake_case    ) ,   __snake_case    )




					def   lowerCamelCase_       (     self       :      List[Any] ,   __snake_case       :      torch.Tensor    ):
									UpperCAmelCase_										=					input
									for layer in self.layers:
													UpperCAmelCase_										=					layer(__snake_case    )
									return hidden_state



class       a					(       nn.Module      ):

					'''simple docstring'''





					def __init__(     self       :      Optional[Any] ,   __snake_case       :      Tuple[int, ...] ,   __snake_case       :      int ,   __snake_case       :      int ,   __snake_case       :      bool    ):
									super().__init__()
									UpperCAmelCase_										=					pool_scales
									UpperCAmelCase_										=					align_corners
									UpperCAmelCase_										=					in_channels
									UpperCAmelCase_										=					channels
									UpperCAmelCase_										=					[]
									for i, pool_scale in enumerate(__snake_case    ):
													UpperCAmelCase_										=					UperNetPyramidPoolingBlock(pool_scale=__snake_case ,   in_channels=__snake_case ,   channels=__snake_case    )
													self.blocks.append(__snake_case    )
													self.add_module(str(__snake_case    ) ,   __snake_case    )




					def   lowerCamelCase_       (     self       :      List[str] ,   __snake_case       :      torch.Tensor    ):
									UpperCAmelCase_										=					[]
									for ppm in self.blocks:
													UpperCAmelCase_										=					ppm(__snake_case    )
													UpperCAmelCase_										=					nn.functional.interpolate(
													    __snake_case ,   size=x.size()[2:] ,   mode='''bilinear''' ,   align_corners=self.align_corners    )
													ppm_outs.append(__snake_case    )
									return ppm_outs



class       a					(       nn.Module      ):

					'''simple docstring'''





					def __init__(     self       :      Union[str, Any] ,   __snake_case       :      Dict ,   __snake_case       :      List[str]    ):
									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(__snake_case ,   self.channels ,   kernel_size=1    )
													UpperCAmelCase_										=					UperNetConvModule(self.channels ,   self.channels ,   kernel_size=3 ,   padding=1    )
													self.lateral_convs.append(__snake_case    )
													self.fpn_convs.append(__snake_case    )

									UpperCAmelCase_										=					UperNetConvModule(
									    len(self.in_channels    ) * self.channels ,   self.channels ,   kernel_size=3 ,   padding=1 ,   )
					def   lowerCamelCase_       (     self       :      Tuple    ):
									self.apply(self._init_weights    )
					def   lowerCamelCase_       (     self       :      List[Any] ,   __snake_case       :      List[Any]    ):
									if isinstance(__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   lowerCamelCase_       (     self       :      List[Any] ,   __snake_case       :      int    ):
									UpperCAmelCase_										=					inputs[-1]
									UpperCAmelCase_										=					[x]
									psp_outs.extend(self.psp_modules(__snake_case    )    )
									UpperCAmelCase_										=					torch.cat(__snake_case ,   dim=1    )
									UpperCAmelCase_										=					self.bottleneck(__snake_case    )

									return output




					def   lowerCamelCase_       (     self       :      str ,   __snake_case       :      torch.Tensor    ):
									# build laterals
									UpperCAmelCase_										=					[lateral_conv(encoder_hidden_states[i]    ) for i, lateral_conv in enumerate(self.lateral_convs    )]

									laterals.append(self.psp_forward(__snake_case    )    )

									# build top-down path
									UpperCAmelCase_										=					len(__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=__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(__snake_case ,   dim=1    )
									UpperCAmelCase_										=					self.fpn_bottleneck(__snake_case    )
									UpperCAmelCase_										=					self.classifier(__snake_case    )

									return output



class       a					(       nn.Module      ):

					'''simple docstring'''





					def __init__(     self       :      Any ,   __snake_case       :      int ,   __snake_case       :      int = 2 ,   __snake_case       :      int = 3 ,   __snake_case       :      Union[int, Tuple[int, int]] = 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=__snake_case ,   padding=__snake_case ,   dilation=__snake_case    )    )
									for i in range(self.num_convs - 1    ):
													convs.append(
													    UperNetConvModule(
													        self.channels ,   self.channels ,   kernel_size=__snake_case ,   padding=__snake_case ,   dilation=__snake_case    )    )
									if self.num_convs == 0:
													UpperCAmelCase_										=					nn.Identity()
									else:
													UpperCAmelCase_										=					nn.Sequential(*__snake_case    )
									if self.concat_input:
													UpperCAmelCase_										=					UperNetConvModule(
													    self.in_channels + self.channels ,   self.channels ,   kernel_size=__snake_case ,   padding=kernel_size // 2    )

									UpperCAmelCase_										=					nn.Convad(self.channels ,   config.num_labels ,   kernel_size=1    )
					def   lowerCamelCase_       (     self       :      Tuple    ):
									self.apply(self._init_weights    )
					def   lowerCamelCase_       (     self       :      Union[str, Any] ,   __snake_case       :      Tuple    ):
									if isinstance(__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   lowerCamelCase_       (     self       :      List[str] ,   __snake_case       :      torch.Tensor    ):
									# just take the relevant feature maps
									UpperCAmelCase_										=					encoder_hidden_states[self.in_index]
									UpperCAmelCase_										=					self.convs(__snake_case    )
									if self.concat_input:
													UpperCAmelCase_										=					self.conv_cat(torch.cat([hidden_states, output] ,   dim=1    )    )
									UpperCAmelCase_										=					self.classifier(__snake_case    )
									return output



class       a					(       _A      ):

					'''simple docstring'''





					lowerCAmelCase    :	Tuple       		=  UperNetConfig
					lowerCAmelCase    :	Tuple       		=  'pixel_values'
					lowerCAmelCase    :	Tuple       		=  True
					def   lowerCamelCase_       (     self       :      List[str] ,   __snake_case       :      int    ):
									if isinstance(__snake_case ,   __snake_case    ):
													module.backbone.init_weights()
													module.decode_head.init_weights()
													module.auxiliary_head.init_weights()
					def   lowerCamelCase_       (     self       :      List[str]    ):
									self.backbone.init_weights()
									self.decode_head.init_weights()
									self.auxiliary_head.init_weights()




					def   lowerCamelCase_       (     self       :      Union[str, Any] ,   __snake_case       :      Dict ,   __snake_case       :      int=False    ):
									if isinstance(__snake_case ,   __snake_case    ):
													UpperCAmelCase_										=					value


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

_lowerCamelCase      			=						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       a					(       _A      ):

					'''simple docstring'''





					def __init__(     self       :      Dict ,   __snake_case       :      Any    ):
									super().__init__(__snake_case    )

									UpperCAmelCase_										=					AutoBackbone.from_config(config.backbone_config    )

									# Semantic segmentation head(s)
									UpperCAmelCase_										=					UperNetHead(__snake_case ,   in_channels=self.backbone.channels    )
									UpperCAmelCase_										=					UperNetFCNHead(__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=__snake_case ,   config_class=_CONFIG_FOR_DOC    )
					def   lowerCamelCase_       (     self       :      Union[str, Any] ,   __snake_case       :      Optional[torch.Tensor] = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[torch.Tensor] = None ,   __snake_case       :      Optional[bool] = 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(
									    __snake_case ,   output_hidden_states=__snake_case ,   output_attentions=__snake_case    )
									UpperCAmelCase_										=					outputs.feature_maps

									UpperCAmelCase_										=					self.decode_head(__snake_case    )
									UpperCAmelCase_										=					nn.functional.interpolate(__snake_case ,   size=pixel_values.shape[2:] ,   mode='''bilinear''' ,   align_corners=__snake_case    )

									UpperCAmelCase_										=					None
									if self.auxiliary_head is not None:
													UpperCAmelCase_										=					self.auxiliary_head(__snake_case    )
													UpperCAmelCase_										=					nn.functional.interpolate(
													    __snake_case ,   size=pixel_values.shape[2:] ,   mode='''bilinear''' ,   align_corners=__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(__snake_case ,   __snake_case    )
																	UpperCAmelCase_										=					loss_fct(__snake_case ,   __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=__snake_case ,   logits=__snake_case ,   hidden_states=outputs.hidden_states ,   attentions=outputs.attentions ,   )











from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_lowerCamelCase      			=						{
    'configuration_conditional_detr': [
        'CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'ConditionalDetrConfig',
        'ConditionalDetrOnnxConfig',
    ]
}

try:
 if not is_vision_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCamelCase      			=						['ConditionalDetrFeatureExtractor']
 _lowerCamelCase      			=						['ConditionalDetrImageProcessor']

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCamelCase      			=						[
     'CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST',
     'ConditionalDetrForObjectDetection',
     'ConditionalDetrForSegmentation',
     'ConditionalDetrModel',
     'ConditionalDetrPreTrainedModel',
 ]


if TYPE_CHECKING:
 from .configuration_conditional_detr import (
     CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP,
     ConditionalDetrConfig,
     ConditionalDetrOnnxConfig,
 )

 try:
  if not is_vision_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor
  from .image_processing_conditional_detr import ConditionalDetrImageProcessor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_conditional_detr import (
      CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
      ConditionalDetrForObjectDetection,
      ConditionalDetrForSegmentation,
      ConditionalDetrModel,
      ConditionalDetrPreTrainedModel,
  )

else:
 import sys

 _lowerCamelCase      			=						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)





