






'''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        _UpperCAmelCase						(		nn.Module			):




    def __init__(			self  :       Any  ,     a  :       Union[str, Any]  ,     a  :       Union[str, Any]  ,     a  :       List[str]  ,     a  :       int = 0  ,     a  :       List[Any] = False  ,     a  :       str = 1  ,     ):






       '''simple docstring'''






       super().__init__()
       lowercase_	:    Any           =     nn.Convad(
           in_channels=_a  ,     out_channels=_a  ,     kernel_size=_a  ,     padding=_a  ,     bias=_a  ,     dilation=_a  ,     )
       lowercase_	:    str           =     nn.BatchNormad(_a			)
       lowercase_	:    Optional[int]           =     nn.ReLU()





    def 				lowerCAmelCase__				(			self  :       Dict  ,     a  :       Optional[Any]			):






       '''simple docstring'''






       lowercase_	:    str           =     self.conv(_a			)
       lowercase_	:    List[str]           =     self.batch_norm(_a			)
       lowercase_	:    Dict           =     self.activation(_a			)

       return output


class        _UpperCAmelCase						(		nn.Module			):




    def __init__(			self  :       str  ,     a  :       Tuple  ,     a  :       Any  ,     a  :       Union[str, Any]			):






       '''simple docstring'''






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





    def 				lowerCAmelCase__				(			self  :       Optional[Any]  ,     a  :       Dict			):






       '''simple docstring'''






       lowercase_	:    int           =     input
       for layer in self.layers:
          lowercase_	:    Any           =     layer(_a			)
       return hidden_state


class        _UpperCAmelCase						(		nn.Module			):




    def __init__(			self  :       List[str]  ,     a  :       Any  ,     a  :       Dict  ,     a  :       int  ,     a  :       List[str]			):






       '''simple docstring'''






       super().__init__()
       lowercase_	:    Optional[Any]           =     pool_scales
       lowercase_	:    int           =     align_corners
       lowercase_	:    Any           =     in_channels
       lowercase_	:    str           =     channels
       lowercase_	:    int           =     []
       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 				lowerCAmelCase__				(			self  :       Any  ,     a  :       Dict			):






       '''simple docstring'''






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


class        _UpperCAmelCase						(		nn.Module			):




    def __init__(			self  :       List[str]  ,     a  :       Union[str, Any]  ,     a  :       Dict			):






       '''simple docstring'''






       super().__init__()

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

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

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




    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       self.apply(self._init_weights			)




    def 				lowerCAmelCase__				(			self  :       Dict  ,     a  :       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 				lowerCAmelCase__				(			self  :       List[Any]  ,     a  :       Optional[Any]			):






       '''simple docstring'''






       lowercase_	:    Tuple           =     inputs[-1]
       lowercase_	:    str           =     [x]
       psp_outs.extend(self.psp_modules(_a			)			)
       lowercase_	:    Any           =     torch.cat(_a  ,     dim=1			)
       lowercase_	:    List[str]           =     self.bottleneck(_a			)

       return output





    def 				lowerCAmelCase__				(			self  :       Union[str, Any]  ,     a  :       Dict			):






       '''simple docstring'''






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

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

       return output


class        _UpperCAmelCase						(		nn.Module			):




    def __init__(			self  :       Dict  ,     a  :       Optional[Any]  ,     a  :       Optional[Any] = 2  ,     a  :       Optional[int] = 3  ,     a  :       Union[str, Any] = 1			):






       '''simple docstring'''






       super().__init__()

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

       lowercase_	:    List[str]           =     (kernel_size // 2) * dilation
       lowercase_	:    Optional[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 				lowerCAmelCase__				(			self  :       Tuple			):






       '''simple docstring'''






       self.apply(self._init_weights			)




    def 				lowerCAmelCase__				(			self  :       Any  ,     a  :       Tuple			):






       '''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 				lowerCAmelCase__				(			self  :       int  ,     a  :       int			):






       '''simple docstring'''






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


class        _UpperCAmelCase						(		__SCREAMING_SNAKE_CASE			):
    __lowerCamelCase:   str		       =    UperNetConfig
    __lowerCamelCase:   Optional[Any]		       =    'pixel_values'
    __lowerCamelCase:   List[str]		       =    True




    def 				lowerCAmelCase__				(			self  :       Optional[Any]  ,     a  :       Tuple			):






       '''simple docstring'''






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




    def 				lowerCAmelCase__				(			self  :       Dict			):






       '''simple docstring'''






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





    def 				lowerCAmelCase__				(			self  :       Any  ,     a  :       Tuple  ,     a  :       Optional[int]=False			):






       '''simple docstring'''






       if isinstance(_a  ,     _a			):
          lowercase_	:    List[str]           =     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        _UpperCAmelCase						(		__SCREAMING_SNAKE_CASE			):




    def __init__(			self  :       Any  ,     a  :       Optional[Any]			):






       '''simple docstring'''






       super().__init__(_a			)

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

       # Semantic segmentation head(s)
       lowercase_	:    Optional[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 				lowerCAmelCase__				(			self  :       Optional[Any]  ,     a  :       str = None  ,     a  :       str = None  ,     a  :       List[Any] = None  ,     a  :       Any = None  ,     a  :       Optional[Any] = None  ,     ):






       '''simple docstring'''






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

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

       lowercase_	:    Dict           =     self.decode_head(_a			)
       lowercase_	:    str           =     nn.functional.interpolate(_a  ,     size=pixel_values.shape[2:]  ,     mode="bilinear"  ,     align_corners=_a			)

       lowercase_	:    Optional[int]           =     None
       if self.auxiliary_head is not None:
          lowercase_	:    List[str]           =     self.auxiliary_head(_a			)
          lowercase_	:    List[str]           =     nn.functional.interpolate(
              _a  ,     size=pixel_values.shape[2:]  ,     mode="bilinear"  ,     align_corners=_a			)

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

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

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


UpperCamelCase__ =			{
    'configuration_encodec': [
        'ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'EncodecConfig',
    ],
    'feature_extraction_encodec': ['EncodecFeatureExtractor'],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCamelCase__ =			[
     'ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST',
     'EncodecModel',
     'EncodecPreTrainedModel',
 ]

if TYPE_CHECKING:
 from .configuration_encodec import (
     ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP,
     EncodecConfig,
 )
 from .feature_extraction_encodec import EncodecFeatureExtractor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_encodec import (
      ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST,
      EncodecModel,
      EncodecPreTrainedModel,
  )

else:
 import sys

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




