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

# General docstring
UpperCamelCase     :    str       =			"UperNetConfig"

class __lowerCAmelCase		(				nn.Module      ):





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

      '''simple docstring'''




      super().__init__()
      __UpperCamelCase      =	nn.Convad(
          in_channels=__UpperCAmelCase     ,					out_channels=__UpperCAmelCase     ,					kernel_size=__UpperCAmelCase     ,					padding=__UpperCAmelCase     ,					bias=__UpperCAmelCase     ,					dilation=__UpperCAmelCase     ,					)
      __UpperCamelCase      =	nn.BatchNormad(__UpperCAmelCase				)
      __UpperCamelCase      =	nn.ReLU()







     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	self.conv(__UpperCAmelCase				)
      __UpperCamelCase      =	self.batch_norm(__UpperCAmelCase				)
      __UpperCamelCase      =	self.activation(__UpperCAmelCase				)

      return output


class __lowerCAmelCase		(				nn.Module      ):





     def __init__(     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				):

      '''simple docstring'''




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







     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	input
      for layer in self.layers:
       __UpperCamelCase      =	layer(__UpperCAmelCase				)
      return hidden_state


class __lowerCAmelCase		(				nn.Module      ):





     def __init__(     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				):

      '''simple docstring'''




      super().__init__()
      __UpperCamelCase      =	pool_scales
      __UpperCamelCase      =	align_corners
      __UpperCamelCase      =	in_channels
      __UpperCamelCase      =	channels
      __UpperCamelCase      =	[]
      for i, pool_scale in enumerate(__UpperCAmelCase				):
       __UpperCamelCase      =	UperNetPyramidPoolingBlock(pool_scale=__UpperCAmelCase     ,					in_channels=__UpperCAmelCase     ,					channels=__UpperCAmelCase				)
       self.blocks.append(__UpperCAmelCase				)
       self.add_module(str(__UpperCAmelCase				)     ,					__UpperCAmelCase				)







     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	[]
      for ppm in self.blocks:
       __UpperCamelCase      =	ppm(__UpperCAmelCase				)
       __UpperCamelCase      =	nn.functional.interpolate(
           __UpperCAmelCase     ,					size=x.size()[2:]     ,					mode='bilinear'     ,					align_corners=self.align_corners				)
       ppm_outs.append(__UpperCAmelCase				)
      return ppm_outs


class __lowerCAmelCase		(				nn.Module      ):





     def __init__(     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase				):

      '''simple docstring'''




      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(__UpperCAmelCase     ,					self.channels     ,					kernel_size=1				)
       __UpperCamelCase      =	UperNetConvModule(self.channels     ,					self.channels     ,					kernel_size=3     ,					padding=1				)
       self.lateral_convs.append(__UpperCAmelCase				)
       self.fpn_convs.append(__UpperCAmelCase				)

      __UpperCamelCase      =	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     ,					__UpperCAmelCase				):

      '''simple docstring'''




      if isinstance(__UpperCAmelCase     ,					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     ,					__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	inputs[-1]
      __UpperCamelCase      =	[x]
      psp_outs.extend(self.psp_modules(__UpperCAmelCase				)				)
      __UpperCamelCase      =	torch.cat(__UpperCAmelCase     ,					dim=1				)
      __UpperCamelCase      =	self.bottleneck(__UpperCAmelCase				)

      return output







     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	[lateral_conv(encoder_hidden_states[i]				) for i, lateral_conv in enumerate(self.lateral_convs				)]

      laterals.append(self.psp_forward(__UpperCAmelCase				)				)

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

      return output


class __lowerCAmelCase		(				nn.Module      ):





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

      '''simple docstring'''




      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=__UpperCAmelCase     ,					padding=__UpperCAmelCase     ,					dilation=__UpperCAmelCase				)				)
      for i in range(self.num_convs - 1				):
       convs.append(
           UperNetConvModule(
               self.channels     ,					self.channels     ,					kernel_size=__UpperCAmelCase     ,					padding=__UpperCAmelCase     ,					dilation=__UpperCAmelCase				)				)
      if self.num_convs == 0:
       __UpperCamelCase      =	nn.Identity()
      else:
       __UpperCamelCase      =	nn.Sequential(*__UpperCAmelCase				)
      if self.concat_input:
       __UpperCamelCase      =	UperNetConvModule(
           self.in_channels + self.channels     ,					self.channels     ,					kernel_size=__UpperCAmelCase     ,					padding=kernel_size // 2				)

      __UpperCamelCase      =	nn.Convad(self.channels     ,					config.num_labels     ,					kernel_size=1				)





     def 						UpperCAmelCase (     self				):

      '''simple docstring'''




      self.apply(self._init_weights				)





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      if isinstance(__UpperCAmelCase     ,					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     ,					__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	encoder_hidden_states[self.in_index]
      __UpperCamelCase      =	self.convs(__UpperCAmelCase				)
      if self.concat_input:
       __UpperCamelCase      =	self.conv_cat(torch.cat([hidden_states, output]     ,					dim=1				)				)
      __UpperCamelCase      =	self.classifier(__UpperCAmelCase				)
      return output


class __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):
     lowercase						       =						UperNetConfig
     lowercase						       =						"pixel_values"
     lowercase						       =						True





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      if isinstance(__UpperCAmelCase     ,					__UpperCAmelCase				):
       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     ,					__UpperCAmelCase     ,					__UpperCAmelCase=False				):

      '''simple docstring'''




      if isinstance(__UpperCAmelCase     ,					__UpperCAmelCase				):
       __UpperCamelCase      =	value


UpperCamelCase     :    List[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"

UpperCamelCase     :    int       =			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 __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):





     def __init__(     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      super().__init__(__UpperCAmelCase				)

      __UpperCamelCase      =	AutoBackbone.from_config(config.backbone_config				)

      # Semantic segmentation head(s)
      __UpperCamelCase      =	UperNetHead(__UpperCAmelCase     ,					in_channels=self.backbone.channels				)
      __UpperCamelCase      =	UperNetFCNHead(__UpperCAmelCase				) 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=__UpperCAmelCase     ,					config_class=_CONFIG_FOR_DOC				)
     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase = None     ,					__UpperCAmelCase = None     ,					__UpperCAmelCase = None     ,					__UpperCAmelCase = None     ,					__UpperCAmelCase = None     ,					):

      '''simple docstring'''




      __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(
          __UpperCAmelCase     ,					output_hidden_states=__UpperCAmelCase     ,					output_attentions=__UpperCAmelCase				)
      __UpperCamelCase      =	outputs.feature_maps

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

      __UpperCamelCase      =	None
      if self.auxiliary_head is not None:
       __UpperCamelCase      =	self.auxiliary_head(__UpperCAmelCase				)
       __UpperCamelCase      =	nn.functional.interpolate(
           __UpperCAmelCase     ,					size=pixel_values.shape[2:]     ,					mode='bilinear'     ,					align_corners=__UpperCAmelCase				)

      __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(__UpperCAmelCase     ,					__UpperCAmelCase				)
        __UpperCamelCase      =	loss_fct(__UpperCAmelCase     ,					__UpperCAmelCase				)
        __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=__UpperCAmelCase     ,					logits=__UpperCAmelCase     ,					hidden_states=outputs.hidden_states     ,					attentions=outputs.attentions     ,					)





"""simple docstring"""

import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
      if is_torch_available():
            import torch
      if is_tf_available():
            import tensorflow as tf

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer


UpperCamelCase     :    List[Any]       =			logging.get_logger(__name__)

UpperCamelCase     :    List[str]       =			{"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

UpperCamelCase     :    List[Any]       =			{
    "vocab_file": {
        "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json",
    },
    "merges_file": {
        "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt",
    },
    "tokenizer_file": {
        "Salesforce/codegen-350M-mono": (
            "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json"
        ),
    },
}

UpperCamelCase     :    List[Any]       =			{
    "Salesforce/codegen-350M-mono": 2_0_4_8,
}

class __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):
     lowercase						       =						VOCAB_FILES_NAMES
     lowercase						       =						PRETRAINED_VOCAB_FILES_MAP
     lowercase						       =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowercase						       =						["input_ids", "attention_mask"]
     lowercase						       =						CodeGenTokenizer





     def __init__(     self     ,					__UpperCAmelCase=None     ,					__UpperCAmelCase=None     ,					__UpperCAmelCase=None     ,					__UpperCAmelCase="<|endoftext|>"     ,					__UpperCAmelCase="<|endoftext|>"     ,					__UpperCAmelCase="<|endoftext|>"     ,					__UpperCAmelCase=False     ,					**__UpperCAmelCase     ,					):

      '''simple docstring'''




      super().__init__(
          __UpperCAmelCase     ,					__UpperCAmelCase     ,					tokenizer_file=__UpperCAmelCase     ,					unk_token=__UpperCAmelCase     ,					bos_token=__UpperCAmelCase     ,					eos_token=__UpperCAmelCase     ,					add_prefix_space=__UpperCAmelCase     ,					**__UpperCAmelCase     ,					)

      if kwargs.pop('add_bos_token'     ,					__UpperCAmelCase				):
       __UpperCamelCase      =	kwargs.pop('name_or_path'     ,					''				)
       raise ValueError(
           'Currenty GPT2\'s fast tokenizer does NOT support adding a BOS token.'
           'Instead you should use GPT2\'s slow tokenizer class `CodeGenTokenizer` as follows: \n'
           F'`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n'
           F'`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n'
           'This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.'
           ' so that the fast tokenizer works correctly.'				)

      __UpperCamelCase      =	json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()				)
      if pre_tok_state.get('add_prefix_space'     ,					__UpperCAmelCase				) != add_prefix_space:
       __UpperCamelCase      =	getattr(__UpperCAmelCase     ,					pre_tok_state.pop('type'				)				)
       __UpperCamelCase      =	add_prefix_space
       __UpperCamelCase      =	pre_tok_class(**__UpperCAmelCase				)

      __UpperCamelCase      =	add_prefix_space





     def 						UpperCAmelCase (     self     ,					*__UpperCAmelCase     ,					**__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	kwargs.get('is_split_into_words'     ,					__UpperCAmelCase				)
      assert self.add_prefix_space or not is_split_into_words, (
          F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
          "to use it with pretokenized inputs."
      )

      return super()._batch_encode_plus(*__UpperCAmelCase     ,					**__UpperCAmelCase				)





     def 						UpperCAmelCase (     self     ,					*__UpperCAmelCase     ,					**__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	kwargs.get('is_split_into_words'     ,					__UpperCAmelCase				)

      assert self.add_prefix_space or not is_split_into_words, (
          F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
          "to use it with pretokenized inputs."
      )

      return super()._encode_plus(*__UpperCAmelCase     ,					**__UpperCAmelCase				)





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase = None				):

      '''simple docstring'''




      __UpperCamelCase      =	self._tokenizer.model.save(__UpperCAmelCase     ,					name=__UpperCAmelCase				)
      return tuple(__UpperCAmelCase				)





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase = False     ,					__UpperCAmelCase = None     ,					__UpperCAmelCase = None     ,					**__UpperCAmelCase     ,					):

      '''simple docstring'''




      __UpperCamelCase      =	super().decode(
          token_ids=__UpperCAmelCase     ,					skip_special_tokens=__UpperCAmelCase     ,					clean_up_tokenization_spaces=__UpperCAmelCase     ,					**__UpperCAmelCase     ,					)

      if truncate_before_pattern is not None and len(__UpperCAmelCase				) > 0:
       __UpperCamelCase      =	self.truncate(__UpperCAmelCase     ,					__UpperCAmelCase				)

      return decoded_text







     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase				):

      '''simple docstring'''




      def find_re(__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				):
       __UpperCamelCase      =	pattern.search(__UpperCAmelCase     ,					__UpperCAmelCase				)
       return m.start() if m else -1

      __UpperCamelCase      =	[re.compile(__UpperCAmelCase     ,					re.MULTILINE				) for pattern in truncate_before_pattern]

      __UpperCamelCase      =	list(re.finditer('^print'     ,					__UpperCAmelCase     ,					re.MULTILINE				)				)

      if len(__UpperCAmelCase				) > 1:
       __UpperCamelCase      =	completion[: prints[1].start()]

      __UpperCamelCase      =	list(re.finditer('^def'     ,					__UpperCAmelCase     ,					re.MULTILINE				)				)

      if len(__UpperCAmelCase				) > 1:
       __UpperCamelCase      =	completion[: defs[1].start()]

      __UpperCamelCase      =	0

      __UpperCamelCase      =	[
          pos for pos in [find_re(__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				) for terminal in terminals] if pos != -1
      ]

      if len(__UpperCAmelCase				) > 0:
       return completion[: min(__UpperCAmelCase				)]
      else:
       return completion



