


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

# General docstring
__UpperCamelCase    :						List[str]     =							'UperNetConfig'



class 							_UpperCamelCase (						nn.Module						):

   '''simple docstring'''







   def __init__(  self  : Optional[Any]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : Union[int, Tuple[int, int]]       ,  _lowerCamelCase  : Union[int, Tuple[int, int], str] = 0       ,  _lowerCamelCase  : bool = False       ,  _lowerCamelCase  : Union[int, Tuple[int, int]] = 1       ,  ):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase     :      str       						=						nn.Convad(
             in_channels=_lowerCamelCase       ,  out_channels=_lowerCamelCase       ,  kernel_size=_lowerCamelCase       ,  padding=_lowerCamelCase       ,  bias=_lowerCamelCase       ,  dilation=_lowerCamelCase       ,  )
         __lowerCamelCase     :      List[Any]       						=						nn.BatchNormad(_lowerCamelCase							)
         __lowerCamelCase     :      Any       						=						nn.ReLU()


   def   _snake_case    (  self  : List[str]       ,  _lowerCamelCase  : torch.Tensor							):






         '''simple docstring'''



         __lowerCamelCase     :      List[Any]       						=						self.conv(_lowerCamelCase							)
         __lowerCamelCase     :      Optional[int]       						=						self.batch_norm(_lowerCamelCase							)
         __lowerCamelCase     :      Dict       						=						self.activation(_lowerCamelCase							)

         return output



class 							_UpperCamelCase (						nn.Module						):

   '''simple docstring'''







   def __init__(  self  : Tuple       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int							):






         '''simple docstring'''



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


   def   _snake_case    (  self  : List[Any]       ,  _lowerCamelCase  : torch.Tensor							):






         '''simple docstring'''



         __lowerCamelCase     :      str       						=						input
         for layer in self.layers:
               __lowerCamelCase     :      int       						=						layer(_lowerCamelCase							)
         return hidden_state



class 							_UpperCamelCase (						nn.Module						):

   '''simple docstring'''







   def __init__(  self  : Any       ,  _lowerCamelCase  : Tuple[int, ...]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : bool							):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase     :      List[Any]       						=						pool_scales
         __lowerCamelCase     :      Optional[Any]       						=						align_corners
         __lowerCamelCase     :      Any       						=						in_channels
         __lowerCamelCase     :      Union[str, Any]       						=						channels
         __lowerCamelCase     :      List[str]       						=						[]
         for i, pool_scale in enumerate(_lowerCamelCase							):
               __lowerCamelCase     :      int       						=						UperNetPyramidPoolingBlock(pool_scale=_lowerCamelCase       ,  in_channels=_lowerCamelCase       ,  channels=_lowerCamelCase							)
               self.blocks.append(_lowerCamelCase							)
               self.add_module(str(_lowerCamelCase							)       ,  _lowerCamelCase							)


   def   _snake_case    (  self  : Dict       ,  _lowerCamelCase  : torch.Tensor							):






         '''simple docstring'''



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



class 							_UpperCamelCase (						nn.Module						):

   '''simple docstring'''







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






         '''simple docstring'''



         super().__init__()

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

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

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

   def   _snake_case    (  self  : Optional[int]							):






         '''simple docstring'''



         self.apply(self._init_weights							)

   def   _snake_case    (  self  : int       ,  _lowerCamelCase  : Tuple							):






         '''simple docstring'''



         if isinstance(_lowerCamelCase       ,  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   _snake_case    (  self  : Optional[int]       ,  _lowerCamelCase  : List[Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      str       						=						inputs[-1]
         __lowerCamelCase     :      Dict       						=						[x]
         psp_outs.extend(self.psp_modules(_lowerCamelCase							)							)
         __lowerCamelCase     :      Tuple       						=						torch.cat(_lowerCamelCase       ,  dim=1							)
         __lowerCamelCase     :      int       						=						self.bottleneck(_lowerCamelCase							)

         return output


   def   _snake_case    (  self  : str       ,  _lowerCamelCase  : torch.Tensor							):






         '''simple docstring'''



         __lowerCamelCase     :      int       						=						[lateral_conv(encoder_hidden_states[i]							) for i, lateral_conv in enumerate(self.lateral_convs							)]

         laterals.append(self.psp_forward(_lowerCamelCase							)							)

         # build top-down path
         __lowerCamelCase     :      List[Any]       						=						len(_lowerCamelCase							)
         for i in range(used_backbone_levels - 1       ,  0       ,  -1							):
               __lowerCamelCase     :      List[Any]       						=						laterals[i - 1].shape[2:]
               __lowerCamelCase     :      Any       						=						laterals[i - 1] + nn.functional.interpolate(
                   laterals[i]       ,  size=_lowerCamelCase       ,  mode="""bilinear"""       ,  align_corners=self.align_corners							)

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

         return output



class 							_UpperCamelCase (						nn.Module						):

   '''simple docstring'''







   def __init__(  self  : Union[str, Any]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int = 2       ,  _lowerCamelCase  : int = 3       ,  _lowerCamelCase  : Union[int, Tuple[int, int]] = 1							):






         '''simple docstring'''



         super().__init__()

         __lowerCamelCase     :      Optional[int]       						=						config
         __lowerCamelCase     :      Any       						=						config.auxiliary_in_channels
         __lowerCamelCase     :      str       						=						config.auxiliary_channels
         __lowerCamelCase     :      Any       						=						config.auxiliary_num_convs
         __lowerCamelCase     :      Union[str, Any]       						=						config.auxiliary_concat_input
         __lowerCamelCase     :      str       						=						in_index

         __lowerCamelCase     :      Optional[Any]       						=						(kernel_size // 2) * dilation
         __lowerCamelCase     :      List[Any]       						=						[]
         convs.append(
             UperNetConvModule(
                 self.in_channels       ,  self.channels       ,  kernel_size=_lowerCamelCase       ,  padding=_lowerCamelCase       ,  dilation=_lowerCamelCase							)							)
         for i in range(self.num_convs - 1							):
               convs.append(
                   UperNetConvModule(
                       self.channels       ,  self.channels       ,  kernel_size=_lowerCamelCase       ,  padding=_lowerCamelCase       ,  dilation=_lowerCamelCase							)							)
         if self.num_convs == 0:
               __lowerCamelCase     :      Optional[Any]       						=						nn.Identity()
         else:
               __lowerCamelCase     :      List[Any]       						=						nn.Sequential(*_lowerCamelCase							)
         if self.concat_input:
               __lowerCamelCase     :      List[str]       						=						UperNetConvModule(
                   self.in_channels + self.channels       ,  self.channels       ,  kernel_size=_lowerCamelCase       ,  padding=kernel_size // 2							)

         __lowerCamelCase     :      Optional[int]       						=						nn.Convad(self.channels       ,  config.num_labels       ,  kernel_size=1							)

   def   _snake_case    (  self  : Tuple							):






         '''simple docstring'''



         self.apply(self._init_weights							)

   def   _snake_case    (  self  : Tuple       ,  _lowerCamelCase  : Tuple							):






         '''simple docstring'''



         if isinstance(_lowerCamelCase       ,  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   _snake_case    (  self  : int       ,  _lowerCamelCase  : torch.Tensor							):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[int]       						=						encoder_hidden_states[self.in_index]
         __lowerCamelCase     :      Optional[int]       						=						self.convs(_lowerCamelCase							)
         if self.concat_input:
               __lowerCamelCase     :      str       						=						self.conv_cat(torch.cat([hidden_states, output]       ,  dim=1							)							)
         __lowerCamelCase     :      Union[str, Any]       						=						self.classifier(_lowerCamelCase							)
         return output



class 							_UpperCamelCase (						A						):

   '''simple docstring'''







   a_				:							int    = UperNetConfig
   a_				:							Optional[int]    = "pixel_values"
   a_				:							List[str]    = True

   def   _snake_case    (  self  : Union[str, Any]       ,  _lowerCamelCase  : Optional[Any]							):






         '''simple docstring'''



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

   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



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


   def   _snake_case    (  self  : Any       ,  _lowerCamelCase  : Tuple       ,  _lowerCamelCase  : int=False							):






         '''simple docstring'''



         if isinstance(_lowerCamelCase       ,  _lowerCamelCase							):
               __lowerCamelCase     :      Optional[int]       						=						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    :						Union[str, 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 							_UpperCamelCase (						A						):

   '''simple docstring'''







   def __init__(  self  : int       ,  _lowerCamelCase  : Optional[Any]							):






         '''simple docstring'''



         super().__init__(_lowerCamelCase							)

         __lowerCamelCase     :      Dict       						=						AutoBackbone.from_config(config.backbone_config							)

         # Semantic segmentation head(s)
         __lowerCamelCase     :      Any       						=						UperNetHead(_lowerCamelCase       ,  in_channels=self.backbone.channels							)
         __lowerCamelCase     :      List[Any]       						=						UperNetFCNHead(_lowerCamelCase							) 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=_lowerCamelCase       ,  config_class=_CONFIG_FOR_DOC							)
   def   _snake_case    (  self  : List[Any]       ,  _lowerCamelCase  : Optional[torch.Tensor] = None       ,  _lowerCamelCase  : Optional[bool] = None       ,  _lowerCamelCase  : Optional[bool] = None       ,  _lowerCamelCase  : Optional[torch.Tensor] = None       ,  _lowerCamelCase  : Optional[bool] = None       ,  ):






         '''simple docstring'''



         __lowerCamelCase     :      Tuple       						=						return_dict if return_dict is not None else self.config.use_return_dict
         __lowerCamelCase     :      int       						=						(
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         __lowerCamelCase     :      Dict       						=						output_attentions if output_attentions is not None else self.config.output_attentions

         __lowerCamelCase     :      str       						=						self.backbone.forward_with_filtered_kwargs(
             _lowerCamelCase       ,  output_hidden_states=_lowerCamelCase       ,  output_attentions=_lowerCamelCase							)
         __lowerCamelCase     :      Dict       						=						outputs.feature_maps

         __lowerCamelCase     :      List[str]       						=						self.decode_head(_lowerCamelCase							)
         __lowerCamelCase     :      Optional[int]       						=						nn.functional.interpolate(_lowerCamelCase       ,  size=pixel_values.shape[2:]       ,  mode="""bilinear"""       ,  align_corners=_lowerCamelCase							)

         __lowerCamelCase     :      Optional[int]       						=						None
         if self.auxiliary_head is not None:
               __lowerCamelCase     :      Any       						=						self.auxiliary_head(_lowerCamelCase							)
               __lowerCamelCase     :      Dict       						=						nn.functional.interpolate(
                   _lowerCamelCase       ,  size=pixel_values.shape[2:]       ,  mode="""bilinear"""       ,  align_corners=_lowerCamelCase							)

         __lowerCamelCase     :      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
                     __lowerCamelCase     :      Optional[Any]       						=						CrossEntropyLoss(ignore_index=self.config.loss_ignore_index							)
                     __lowerCamelCase     :      Dict       						=						loss_fct(_lowerCamelCase       ,  _lowerCamelCase							)
                     __lowerCamelCase     :      str       						=						loss_fct(_lowerCamelCase       ,  _lowerCamelCase							)
                     __lowerCamelCase     :      List[Any]       						=						main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

         if not return_dict:
               if output_hidden_states:
                     __lowerCamelCase     :      List[str]       						=						(logits,) + outputs[1:]
               else:
                     __lowerCamelCase     :      Dict       						=						(logits,) + outputs[2:]
               return ((loss,) + output) if loss is not None else output

         return SemanticSegmenterOutput(
             loss=_lowerCamelCase       ,  logits=_lowerCamelCase       ,  hidden_states=outputs.hidden_states       ,  attentions=outputs.attentions       ,  )







import argparse
import shutil
from pathlib import Path

from tqdm import tqdm

from transformers import AutoTokenizer





def   _UpperCAmelCase       (     UpperCAmelCase      :			Any						,	UpperCAmelCase      :			int						,	UpperCAmelCase      :			int						,	UpperCAmelCase      :			Any=1_024      ):
      """simple docstring"""




      __lowerCamelCase						, __lowerCamelCase     :      str       						=						[], []

      __lowerCamelCase     :      Any       						=						list(zip(UpperCAmelCase						,	UpperCAmelCase      )      )
      __lowerCamelCase						, __lowerCamelCase     :      List[str]       						=						sorted_examples[0]

      def is_too_big(UpperCAmelCase      :			Optional[Any]      ):
            return tok(UpperCAmelCase						,	return_tensors="""pt"""      ).input_ids.shape[1] > max_tokens

      for src, tgt in tqdm(sorted_examples[1:]      ):
            __lowerCamelCase     :      Union[str, Any]       						=						new_src + """ """ + src
            __lowerCamelCase     :      str       						=						new_tgt + """ """ + tgt
            if is_too_big(UpperCAmelCase      ) or is_too_big(UpperCAmelCase      ):  # cant fit, finalize example
                  finished_src.append(UpperCAmelCase      )
                  finished_tgt.append(UpperCAmelCase      )
                  __lowerCamelCase						, __lowerCamelCase     :      str       						=						src, tgt
            else:  # can fit, keep adding
                  __lowerCamelCase						, __lowerCamelCase     :      int       						=						cand_src, cand_tgt

    # cleanup
      if new_src:
            assert new_tgt
            finished_src.append(UpperCAmelCase      )
            finished_tgt.append(UpperCAmelCase      )
      return finished_src, finished_tgt





def   _UpperCAmelCase       (     UpperCAmelCase      :			Tuple						,	UpperCAmelCase      :			Path						,	UpperCAmelCase      :			Dict						,	UpperCAmelCase      :			Optional[Any]      ):
      """simple docstring"""




      __lowerCamelCase     :      List[Any]       						=						Path(UpperCAmelCase      )
      save_path.mkdir(exist_ok=UpperCAmelCase      )
      for split in ["train"]:
            __lowerCamelCase						, __lowerCamelCase     :      List[Any]       						=						data_dir / f"""{split}.source""", data_dir / f"""{split}.target"""
            __lowerCamelCase     :      Tuple       						=						[x.rstrip() for x in Path(UpperCAmelCase      ).open().readlines()]
            __lowerCamelCase     :      Tuple       						=						[x.rstrip() for x in Path(UpperCAmelCase      ).open().readlines()]
            __lowerCamelCase						, __lowerCamelCase     :      int       						=						pack_examples(UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase      )
            print(f"""packed {split} split from {len(UpperCAmelCase      )} examples -> {len(UpperCAmelCase      )}."""      )
            Path(save_path / f"""{split}.source"""      ).open("""w"""      ).write("""\n""".join(UpperCAmelCase      )      )
            Path(save_path / f"""{split}.target"""      ).open("""w"""      ).write("""\n""".join(UpperCAmelCase      )      )
      for split in ["val", "test"]:
            __lowerCamelCase						, __lowerCamelCase     :      Optional[Any]       						=						data_dir / f"""{split}.source""", data_dir / f"""{split}.target"""
            shutil.copyfile(UpperCAmelCase						,	save_path / f"""{split}.source"""      )
            shutil.copyfile(UpperCAmelCase						,	save_path / f"""{split}.target"""      )





def   _UpperCAmelCase       (     ):
      """simple docstring"""




      __lowerCamelCase     :      List[Any]       						=						argparse.ArgumentParser()
      parser.add_argument("""--tok_name"""						,	type=UpperCAmelCase						,	help="""like facebook/bart-large-cnn,t5-base, etc."""      )
      parser.add_argument("""--max_seq_len"""						,	type=UpperCAmelCase						,	default=128      )
      parser.add_argument("""--data_dir"""						,	type=UpperCAmelCase      )
      parser.add_argument("""--save_path"""						,	type=UpperCAmelCase      )
      __lowerCamelCase     :      Union[str, Any]       						=						parser.parse_args()
      __lowerCamelCase     :      Tuple       						=						AutoTokenizer.from_pretrained(args.tok_name      )
      return pack_data_dir(UpperCAmelCase						,	Path(args.data_dir      )						,	args.max_seq_len						,	args.save_path      )


if __name__ == "__main__":
    packer_cli()



