



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 ,       )









import numpy as np
import torch
from torch.utils.data import Dataset

from utils import logger

class        snake_case__    (A__		):







						"""simple docstring"""




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




									a__       :						Tuple							=  params

									a__       :						str							=  np.array(__lowercase  )
									a__       :						List[Any]							=  np.array([len(__lowercase  ) for t in data]  )

									self.check()
									self.remove_long_sequences()
									self.remove_empty_sequences()
									self.remove_unknown_sequences()
									self.check()
									self.print_statistics()

						def __getitem__(       self ,       __lowercase  ) ->				Any:
									"""simple docstring"""




									return (self.token_ids[index], self.lengths[index])

						def __len__(       self  ) ->				Dict:
									"""simple docstring"""




									return len(self.lengths  )

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




									assert len(self.token_ids  ) == len(self.lengths  )
									assert all(self.lengths[i] == len(self.token_ids[i]  ) for i in range(len(self.lengths  )  )  )

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Tuple:
									"""simple docstring"""




									a__       :						int							=  self.params.max_model_input_size
									a__       :						int							=  self.lengths > max_len
									logger.info(F'''Splitting {sum(__lowercase  )} too long sequences.'''  )

									def divide_chunks(__lowercase ,       __lowercase  ):
												return [l[i : i + n] for i in range(0 ,       len(__lowercase  ) ,       __lowercase  )]

									a__       :						Any							=  []
									a__       :						Optional[int]							=  []
									if self.params.mlm:
												a__	,						a__       :						Any							=  self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""]
									else:
												a__	,						a__       :						Dict							=  self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""]

									for seq_, len_ in zip(self.token_ids ,       self.lengths  ):
												assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
												if len_ <= max_len:
															new_tok_ids.append(seq_  )
															new_lengths.append(len_  )
												else:
															a__       :						int							=  []
															for sub_s in divide_chunks(seq_ ,       max_len - 2  ):
																		if sub_s[0] != cls_id:
																					a__       :						str							=  np.insert(__lowercase ,       0 ,       __lowercase  )
																		if sub_s[-1] != sep_id:
																					a__       :						List[str]							=  np.insert(__lowercase ,       len(__lowercase  ) ,       __lowercase  )
																		assert len(__lowercase  ) <= max_len
																		assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
																		sub_seqs.append(__lowercase  )

															new_tok_ids.extend(__lowercase  )
															new_lengths.extend([len(__lowercase  ) for l in sub_seqs]  )

									a__       :						Optional[int]							=  np.array(__lowercase  )
									a__       :						Any							=  np.array(__lowercase  )

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




									a__       :						Union[str, Any]							=  len(self  )
									a__       :						List[str]							=  self.lengths > 1_1
									a__       :						Dict							=  self.token_ids[indices]
									a__       :						List[str]							=  self.lengths[indices]
									a__       :						int							=  len(self  )
									logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.'''  )

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




									if "unk_token" not in self.params.special_tok_ids:
												return
									else:
												a__       :						Union[str, Any]							=  self.params.special_tok_ids["""unk_token"""]
									a__       :						List[Any]							=  len(self  )
									a__       :						Optional[int]							=  np.array([np.count_nonzero(a == unk_token_id  ) for a in self.token_ids]  )
									a__       :						Optional[Any]							=  (unk_occs / self.lengths) < 0.5
									a__       :						Tuple							=  self.token_ids[indices]
									a__       :						Union[str, Any]							=  self.lengths[indices]
									a__       :						Tuple							=  len(self  )
									logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).'''  )

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




									if not self.params.is_master:
												return
									logger.info(F'''{len(self  )} sequences'''  )
									# data_len = sum(self.lengths)
									# nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
									# logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')

									# unk_idx = self.params.special_tok_ids['unk_token']
									# nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
									# logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')

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




									a__       :						Optional[int]							=  [t[0] for t in batch]
									a__       :						Any							=  [t[1] for t in batch]
									assert len(__lowercase  ) == len(__lowercase  )

									# Max for paddings
									a__       :						List[Any]							=  max(__lowercase  )

									# Pad token ids
									if self.params.mlm:
												a__       :						int							=  self.params.special_tok_ids["""pad_token"""]
									else:
												a__       :						List[str]							=  self.params.special_tok_ids["""unk_token"""]
									a__       :						int							=  [list(t.astype(__lowercase  )  ) + [pad_idx] * (max_seq_len_ - len(__lowercase  )) for t in token_ids]
									assert len(tk_  ) == len(__lowercase  )
									assert all(len(__lowercase  ) == max_seq_len_ for t in tk_  )

									a__       :						List[Any]							=  torch.tensor(tk_  )  # (bs, max_seq_len_)
									a__       :						Optional[int]							=  torch.tensor(__lowercase  )  # (bs)
									return tk_t, lg_t




