"""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     :		List[str]											=					[
    "openmmlab/upernet-convnext-tiny",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

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


class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a	,    a	,    a = 0	,    a = False	,    a = 1	,    ) ->      None:
             super().__init__()
             lowercase__    :	List[str]     					=			nn.Convad(
                 in_channels=a	,    out_channels=a	,    kernel_size=a	,    padding=a	,    bias=a	,    dilation=a	,    )
             lowercase__    :	int     					=			nn.BatchNormad(a							)
             lowercase__    :	Union[str, Any]     					=			nn.ReLU()


      def 	_UpperCAmelCase (     self	,    a							) ->      torch.Tensor:
             lowercase__    :	Union[str, Any]     					=			self.conv(a							)
             lowercase__    :	Tuple     					=			self.batch_norm(a							)
             lowercase__    :	str     					=			self.activation(a							)

             return output





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a	,    a							) ->      None:
             super().__init__()
             lowercase__    :	Optional[int]     					=			[
                 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							) ->      torch.Tensor:
             lowercase__    :	Optional[Any]     					=			input
             for layer in self.layers:
                    lowercase__    :	Union[str, Any]     					=			layer(a							)
             return hidden_state





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a	,    a	,    a							) ->      None:
             super().__init__()
             lowercase__    :	int     					=			pool_scales
             lowercase__    :	Optional[int]     					=			align_corners
             lowercase__    :	List[str]     					=			in_channels
             lowercase__    :	Optional[int]     					=			channels
             lowercase__    :	Dict     					=			[]
             for i, pool_scale in enumerate(a							):
                    lowercase__    :	Optional[Any]     					=			UperNetPyramidPoolingBlock(pool_scale=a	,    in_channels=a	,    channels=a							)
                    self.blocks.append(a							)
                    self.add_module(str(a							)	,    a							)


      def 	_UpperCAmelCase (     self	,    a							) ->      List[torch.Tensor]:
             lowercase__    :	Union[str, Any]     					=			[]
             for ppm in self.blocks:
                    lowercase__    :	str     					=			ppm(a							)
                    lowercase__    :	List[Any]     					=			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	,    a	,    a							) ->      Dict:
             super().__init__()

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

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

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


      def 	_UpperCAmelCase (     self							) ->      List[Any]:
             self.apply(self._init_weights							)


      def 	_UpperCAmelCase (     self	,    a							) ->      str:
             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							) ->      Dict:
             lowercase__    :	Optional[int]     					=			inputs[-1]
             lowercase__    :	int     					=			[x]
             psp_outs.extend(self.psp_modules(a							)							)
             lowercase__    :	Tuple     					=			torch.cat(a	,    dim=1							)
             lowercase__    :	Tuple     					=			self.bottleneck(a							)

             return output


      def 	_UpperCAmelCase (     self	,    a							) ->      torch.Tensor:
             # build laterals
             lowercase__    :	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
             lowercase__    :	str     					=			len(a							)
             for i in range(used_backbone_levels - 1	,    0	,    -1							):
                    lowercase__    :	str     					=			laterals[i - 1].shape[2:]
                    lowercase__    :	Union[str, Any]     					=			laterals[i - 1] + nn.functional.interpolate(
                        laterals[i]	,    size=a	,    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__    :	Union[str, 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__    :	Dict     					=			self.fpn_bottleneck(a							)
             lowercase__    :	int     					=			self.classifier(a							)

             return output





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a = 2	,    a = 3	,    a = 1							) ->      None:
             super().__init__()

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

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

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


      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             self.apply(self._init_weights							)


      def 	_UpperCAmelCase (     self	,    a							) ->      str:
             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							) ->      torch.Tensor:
             # just take the relevant feature maps
             lowercase__    :	List[Any]     					=			encoder_hidden_states[self.in_index]
             lowercase__    :	Tuple     					=			self.convs(a							)
             if self.concat_input:
                    lowercase__    :	Optional[int]     					=			self.conv_cat(torch.cat([hidden_states, output]	,    dim=1							)							)
             lowercase__    :	int     					=			self.classifier(a							)
             return output





class   UpperCAmelCase_			(					_a):
      lowerCamelCase__	:					int										=						UperNetConfig
      lowerCamelCase__	:					Optional[Any]										=						"pixel_values"
      lowerCamelCase__	:					List[Any]										=						True


      def 	_UpperCAmelCase (     self	,    a							) ->      Optional[Any]:
             if isinstance(a	,    a							):
                    module.backbone.init_weights()
                    module.decode_head.init_weights()
                    module.auxiliary_head.init_weights()


      def 	_UpperCAmelCase (     self							) ->      Optional[int]:
             self.backbone.init_weights()
             self.decode_head.init_weights()
             self.auxiliary_head.init_weights()


      def 	_UpperCAmelCase (     self	,    a	,    a=False							) ->      List[str]:
             if isinstance(a	,    a							):
                    lowercase__    :	Tuple     					=			value





_UpperCamelCase     :		int											=					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     :		str											=					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   UpperCAmelCase_			(					_a):


      def __init__(     self	,    a							) ->      Tuple:
             super().__init__(a							)

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

             # Semantic segmentation head(s)
             lowercase__    :	Optional[int]     					=			UperNetHead(a	,    in_channels=self.backbone.channels							)
             lowercase__    :	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	,    ) ->      Union[tuple, SemanticSegmenterOutput]:
             lowercase__    :	Tuple     					=			return_dict if return_dict is not None else self.config.use_return_dict
             lowercase__    :	Union[str, Any]     					=			(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             lowercase__    :	List[Any]     					=			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__    :	List[str]     					=			outputs.feature_maps

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

             lowercase__    :	List[str]     					=			None
             if self.auxiliary_head is not None:
                    lowercase__    :	Dict     					=			self.auxiliary_head(a							)
                    lowercase__    :	int     					=			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__    :	List[Any]     					=			CrossEntropyLoss(ignore_index=self.config.loss_ignore_index							)
                           lowercase__    :	Union[str, Any]     					=			loss_fct(a	,    a							)
                           lowercase__    :	Dict     					=			loss_fct(a	,    a							)
                           lowercase__    :	Dict     					=			main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

             if not return_dict:
                    if output_hidden_states:
                           lowercase__    :	Optional[int]     					=			(logits,) + outputs[1:]
                    else:
                           lowercase__    :	Optional[Any]     					=			(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 .glue import GlueDataset, GlueDataTrainingArguments
from .language_modeling import (
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    LineByLineWithSOPTextDataset,
    TextDataset,
    TextDatasetForNextSentencePrediction,
)
from .squad import SquadDataset, SquadDataTrainingArguments

