"""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 							a					(		nn.Module ):


    def __init__(       self						:	List[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 ,					):
      super().__init__()
      _UpperCAmelCase    			=   nn.Convad(
          in_channels=__lowerCAmelCase ,					out_channels=__lowerCAmelCase ,					kernel_size=__lowerCAmelCase ,					padding=__lowerCAmelCase ,					bias=__lowerCAmelCase ,					dilation=__lowerCAmelCase ,					)
      _UpperCAmelCase    			=   nn.BatchNormad(__lowerCAmelCase       )
      _UpperCAmelCase    			=   nn.ReLU()


    def   lowerCAmelCase_	(       self						:	Optional[Any] ,					__lowerCAmelCase						:	torch.Tensor       ):
      _UpperCAmelCase    			=   self.conv(__lowerCAmelCase       )
      _UpperCAmelCase    			=   self.batch_norm(__lowerCAmelCase       )
      _UpperCAmelCase    			=   self.activation(__lowerCAmelCase       )

      return output



class 							a					(		nn.Module ):


    def __init__(       self						:	Tuple ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	int       ):
      super().__init__()
      _UpperCAmelCase    			=   [
          nn.AdaptiveAvgPoolad(__lowerCAmelCase       ),
          UperNetConvModule(__lowerCAmelCase ,					__lowerCAmelCase ,					kernel_size=1       ),
      ]
      for i, layer in enumerate(self.layers       ):
        self.add_module(str(__lowerCAmelCase       ) ,					__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	Optional[int] ,					__lowerCAmelCase						:	torch.Tensor       ):
      _UpperCAmelCase    			=   input
      for layer in self.layers:
        _UpperCAmelCase    			=   layer(__lowerCAmelCase       )
      return hidden_state



class 							a					(		nn.Module ):


    def __init__(       self						:	Optional[Any] ,					__lowerCAmelCase						:	Tuple[int, ...] ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	bool       ):
      super().__init__()
      _UpperCAmelCase    			=   pool_scales
      _UpperCAmelCase    			=   align_corners
      _UpperCAmelCase    			=   in_channels
      _UpperCAmelCase    			=   channels
      _UpperCAmelCase    			=   []
      for i, pool_scale in enumerate(__lowerCAmelCase       ):
        _UpperCAmelCase    			=   UperNetPyramidPoolingBlock(pool_scale=__lowerCAmelCase ,					in_channels=__lowerCAmelCase ,					channels=__lowerCAmelCase       )
        self.blocks.append(__lowerCAmelCase       )
        self.add_module(str(__lowerCAmelCase       ) ,					__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	Optional[int] ,					__lowerCAmelCase						:	torch.Tensor       ):
      _UpperCAmelCase    			=   []
      for ppm in self.blocks:
        _UpperCAmelCase    			=   ppm(__lowerCAmelCase       )
        _UpperCAmelCase    			=   nn.functional.interpolate(
            __lowerCAmelCase ,					size=x.size()[2:] ,					mode="""bilinear""" ,					align_corners=self.align_corners       )
        ppm_outs.append(__lowerCAmelCase       )
      return ppm_outs



class 							a					(		nn.Module ):


    def __init__(       self						:	Tuple ,					__lowerCAmelCase						:	List[str] ,					__lowerCAmelCase						:	str       ):
      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(__lowerCAmelCase ,					self.channels ,					kernel_size=1       )
        _UpperCAmelCase    			=   UperNetConvModule(self.channels ,					self.channels ,					kernel_size=3 ,					padding=1       )
        self.lateral_convs.append(__lowerCAmelCase       )
        self.fpn_convs.append(__lowerCAmelCase       )

      _UpperCAmelCase    			=   UperNetConvModule(
          len(self.in_channels       ) * self.channels ,					self.channels ,					kernel_size=3 ,					padding=1 ,					)


    def   lowerCAmelCase_	(       self						:	Any       ):
      self.apply(self._init_weights       )


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

      return output


    def   lowerCAmelCase_	(       self						:	Any ,					__lowerCAmelCase						:	torch.Tensor       ):
      # build laterals
      _UpperCAmelCase    			=   [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
      _UpperCAmelCase    			=   len(__lowerCAmelCase       )
      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=__lowerCAmelCase ,					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(__lowerCAmelCase ,					dim=1       )
      _UpperCAmelCase    			=   self.fpn_bottleneck(__lowerCAmelCase       )
      _UpperCAmelCase    			=   self.classifier(__lowerCAmelCase       )

      return output



class 							a					(		nn.Module ):


    def __init__(       self						:	Optional[Any] ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	int = 2 ,					__lowerCAmelCase						:	int = 3 ,					__lowerCAmelCase						:	Union[int, Tuple[int, int]] = 1       ):
      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=__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:
        _UpperCAmelCase    			=   nn.Identity()
      else:
        _UpperCAmelCase    			=   nn.Sequential(*__lowerCAmelCase       )
      if self.concat_input:
        _UpperCAmelCase    			=   UperNetConvModule(
            self.in_channels + self.channels ,					self.channels ,					kernel_size=__lowerCAmelCase ,					padding=kernel_size // 2       )

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


    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      self.apply(self._init_weights       )


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



class 							a					(		lowerCAmelCase_ ):
    _snake_case  :	int  				=				UperNetConfig
    _snake_case  :	Optional[int]  				=				'pixel_values'
    _snake_case  :	Optional[Any]  				=				True


    def   lowerCAmelCase_	(       self						:	Tuple ,					__lowerCAmelCase						:	List[str]       ):
      if isinstance(__lowerCAmelCase ,					__lowerCAmelCase       ):
        module.backbone.init_weights()
        module.decode_head.init_weights()
        module.auxiliary_head.init_weights()


    def   lowerCAmelCase_	(       self						:	Optional[int]       ):
      self.backbone.init_weights()
      self.decode_head.init_weights()
      self.auxiliary_head.init_weights()


    def   lowerCAmelCase_	(       self						:	int ,					__lowerCAmelCase						:	Union[str, Any] ,					__lowerCAmelCase						:	int=False       ):
      if isinstance(__lowerCAmelCase ,					__lowerCAmelCase       ):
        _UpperCAmelCase    			=   value



UpperCAmelCase__			=    r"""
    Parameters:
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.
        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

UpperCAmelCase__			=    r"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See
            `attentions` under returned tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under
            returned tensors for more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""


@add_start_docstrings(
    'UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.'						,				lowerCAmelCase_						,				)
class 							a					(		lowerCAmelCase_ ):


    def __init__(       self						:	List[Any] ,					__lowerCAmelCase						:	List[str]       ):
      super().__init__(__lowerCAmelCase       )

      _UpperCAmelCase    			=   AutoBackbone.from_config(config.backbone_config       )

      # Semantic segmentation head(s)
      _UpperCAmelCase    			=   UperNetHead(__lowerCAmelCase ,					in_channels=self.backbone.channels       )
      _UpperCAmelCase    			=   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   lowerCAmelCase_	(       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 ,					):
      _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(
          __lowerCAmelCase ,					output_hidden_states=__lowerCAmelCase ,					output_attentions=__lowerCAmelCase       )
      _UpperCAmelCase    			=   outputs.feature_maps

      _UpperCAmelCase    			=   self.decode_head(__lowerCAmelCase       )
      _UpperCAmelCase    			=   nn.functional.interpolate(__lowerCAmelCase ,					size=pixel_values.shape[2:] ,					mode="""bilinear""" ,					align_corners=__lowerCAmelCase       )

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

      _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(__lowerCAmelCase ,					__lowerCAmelCase       )
          _UpperCAmelCase    			=   loss_fct(__lowerCAmelCase ,					__lowerCAmelCase       )
          _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=__lowerCAmelCase ,					logits=__lowerCAmelCase ,					hidden_states=outputs.hidden_states ,					attentions=outputs.attentions ,					)

"""simple docstring"""


import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path

import pytest

import transformers
from transformers import (
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AutoTokenizer,
    BertConfig,
    BertTokenizer,
    BertTokenizerFast,
    CTRLTokenizer,
    GPTaTokenizer,
    GPTaTokenizerFast,
    PreTrainedTokenizerFast,
    RobertaTokenizer,
    RobertaTokenizerFast,
    is_tokenizers_available,
)
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.auto.tokenization_auto import (
    TOKENIZER_MAPPING,
    get_tokenizer_config,
    tokenizer_class_from_name,
)
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import (
    DUMMY_DIFF_TOKENIZER_IDENTIFIER,
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tokenizers,
    slow,
)


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
    from test_module.custom_tokenization_fast import CustomTokenizerFast


class 							a					(		unittest.TestCase ):


    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      _UpperCAmelCase    			=   0


    @slow
    def   lowerCAmelCase_	(       self						:	List[str]       ):
      for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x):
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )
        self.assertIsNotNone(__lowerCAmelCase       )
        self.assertIsInstance(__lowerCAmelCase ,					(BertTokenizer, BertTokenizerFast)       )
        self.assertGreater(len(__lowerCAmelCase       ) ,					0       )

      for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys():
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )
        self.assertIsNotNone(__lowerCAmelCase       )
        self.assertIsInstance(__lowerCAmelCase ,					(GPTaTokenizer, GPTaTokenizerFast)       )
        self.assertGreater(len(__lowerCAmelCase       ) ,					0       )


    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )
      self.assertIsInstance(__lowerCAmelCase ,					(BertTokenizer, BertTokenizerFast)       )
      self.assertEqual(tokenizer.vocab_size ,					12       )


    def   lowerCAmelCase_	(       self						:	List[str]       ):
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )
      self.assertIsInstance(__lowerCAmelCase ,					(RobertaTokenizer, RobertaTokenizerFast)       )
      self.assertEqual(tokenizer.vocab_size ,					20       )


    def   lowerCAmelCase_	(       self						:	Any       ):
      _UpperCAmelCase    			=   AutoConfig.from_pretrained(__lowerCAmelCase       )
      self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )
      # Check that tokenizer_type ≠ model_type
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					config=__lowerCAmelCase       )
      self.assertIsInstance(__lowerCAmelCase ,					(BertTokenizer, BertTokenizerFast)       )
      self.assertEqual(tokenizer.vocab_size ,					12       )


    def   lowerCAmelCase_	(       self						:	List[str]       ):
      with tempfile.TemporaryDirectory() as tmp_dir:
        shutil.copy("""./tests/fixtures/vocab.txt""" ,					os.path.join(__lowerCAmelCase ,					"""vocab.txt"""       )       )

        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					tokenizer_type="""bert""" ,					use_fast=__lowerCAmelCase       )
        self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )

      with tempfile.TemporaryDirectory() as tmp_dir:
        shutil.copy("""./tests/fixtures/vocab.json""" ,					os.path.join(__lowerCAmelCase ,					"""vocab.json"""       )       )
        shutil.copy("""./tests/fixtures/merges.txt""" ,					os.path.join(__lowerCAmelCase ,					"""merges.txt"""       )       )

        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					tokenizer_type="""gpt2""" ,					use_fast=__lowerCAmelCase       )
        self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )


    @require_tokenizers
    def   lowerCAmelCase_	(       self						:	Tuple       ):
      with tempfile.TemporaryDirectory() as tmp_dir:
        shutil.copy("""./tests/fixtures/vocab.txt""" ,					os.path.join(__lowerCAmelCase ,					"""vocab.txt"""       )       )

        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					tokenizer_type="""bert"""       )
        self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )

      with tempfile.TemporaryDirectory() as tmp_dir:
        shutil.copy("""./tests/fixtures/vocab.json""" ,					os.path.join(__lowerCAmelCase ,					"""vocab.json"""       )       )
        shutil.copy("""./tests/fixtures/merges.txt""" ,					os.path.join(__lowerCAmelCase ,					"""merges.txt"""       )       )

        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					tokenizer_type="""gpt2"""       )
        self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      with pytest.raises(__lowerCAmelCase       ):
        AutoTokenizer.from_pretrained("""./""" ,					tokenizer_type="""xxx"""       )


    @require_tokenizers
    def   lowerCAmelCase_	(       self						:	Optional[int]       ):
      for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
        _UpperCAmelCase    			=   tokenizer_class.from_pretrained("""wietsedv/bert-base-dutch-cased"""       )
        self.assertIsInstance(__lowerCAmelCase ,					(BertTokenizer, BertTokenizerFast)       )

        if isinstance(__lowerCAmelCase ,					__lowerCAmelCase       ):
          self.assertEqual(tokenizer.basic_tokenizer.do_lower_case ,					__lowerCAmelCase       )
        else:
          self.assertEqual(tokenizer.do_lower_case ,					__lowerCAmelCase       )

        self.assertEqual(tokenizer.model_max_length ,					512       )


    @require_tokenizers
    def   lowerCAmelCase_	(       self						:	List[str]       ):
      for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
        with self.assertRaisesRegex(
            __lowerCAmelCase ,					"""julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier""" ,					):
          _UpperCAmelCase    			=   tokenizer_class.from_pretrained("""julien-c/herlolip-not-exists"""       )


    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      # tests: https://github.com/huggingface/transformers/pull/13251
      # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta
      # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai
      _UpperCAmelCase    			=   TOKENIZER_MAPPING.values()
      _UpperCAmelCase    			=   []

      for slow_tok, fast_tok in tokenizers:
        if slow_tok is not None:
          tokenizer_names.append(slow_tok.__name__       )

        if fast_tok is not None:
          tokenizer_names.append(fast_tok.__name__       )

      for tokenizer_name in tokenizer_names:
        # must find the right class
        tokenizer_class_from_name(__lowerCAmelCase       )


    @require_tokenizers
    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" ,					use_fast=__lowerCAmelCase       ) ,					__lowerCAmelCase       )
      self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased"""       ) ,					__lowerCAmelCase       )


    @require_tokenizers
    def   lowerCAmelCase_	(       self						:	int       ):
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""distilbert-base-uncased""" ,					do_lower_case=__lowerCAmelCase       )
      _UpperCAmelCase    			=   """Hello, world. How are you?"""
      _UpperCAmelCase    			=   tokenizer.tokenize(__lowerCAmelCase       )
      self.assertEqual("""[UNK]""" ,					tokens[0]       )

      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""microsoft/mpnet-base""" ,					do_lower_case=__lowerCAmelCase       )
      _UpperCAmelCase    			=   tokenizer.tokenize(__lowerCAmelCase       )
      self.assertEqual("""[UNK]""" ,					tokens[0]       )


    @require_tokenizers
    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""robot-test/dummy-tokenizer-fast-with-model-config"""       )
      self.assertEqual(type(__lowerCAmelCase       ) ,					__lowerCAmelCase       )
      self.assertEqual(tokenizer.model_max_length ,					512       )
      self.assertEqual(tokenizer.vocab_size ,					3_0000       )
      self.assertEqual(tokenizer.unk_token ,					"""[UNK]"""       )
      self.assertEqual(tokenizer.padding_side ,					"""right"""       )
      self.assertEqual(tokenizer.truncation_side ,					"""right"""       )


    def   lowerCAmelCase_	(       self						:	Optional[int]       ):
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )
      self.assertIsInstance(__lowerCAmelCase ,					(BertTokenizer, BertTokenizerFast)       )
      with tempfile.TemporaryDirectory() as tmp_dir:
        tokenizer.save_pretrained(__lowerCAmelCase       )
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )

      self.assertIsInstance(__lowerCAmelCase ,					tokenizer.__class__       )
      self.assertEqual(tokenizera.vocab_size ,					12       )


    def   lowerCAmelCase_	(       self						:	Optional[int]       ):
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""ctrl"""       )
      # There is no fast CTRL so this always gives us a slow tokenizer.
      self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )


    def   lowerCAmelCase_	(       self						:	str       ):
      # Check we can load the tokenizer config of an online model.
      _UpperCAmelCase    			=   get_tokenizer_config("""bert-base-cased"""       )
      _UpperCAmelCase    			=   config.pop("""_commit_hash""" ,					__lowerCAmelCase       )
      # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated.
      self.assertEqual(__lowerCAmelCase ,					{"""do_lower_case""": False}       )

      # This model does not have a tokenizer_config so we get back an empty dict.
      _UpperCAmelCase    			=   get_tokenizer_config(__lowerCAmelCase       )
      self.assertDictEqual(__lowerCAmelCase ,					{}       )

      # A tokenizer saved with `save_pretrained` always creates a tokenizer config.
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )
      with tempfile.TemporaryDirectory() as tmp_dir:
        tokenizer.save_pretrained(__lowerCAmelCase       )
        _UpperCAmelCase    			=   get_tokenizer_config(__lowerCAmelCase       )

      # Check the class of the tokenizer was properly saved (note that it always saves the slow class).
      self.assertEqual(config["""tokenizer_class"""] ,					"""BertTokenizer"""       )


    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      try:
        AutoConfig.register("""custom""" ,					__lowerCAmelCase       )

        AutoTokenizer.register(__lowerCAmelCase ,					slow_tokenizer_class=__lowerCAmelCase       )
        # Trying to register something existing in the Transformers library will raise an error
        with self.assertRaises(__lowerCAmelCase       ):
          AutoTokenizer.register(__lowerCAmelCase ,					slow_tokenizer_class=__lowerCAmelCase       )

        _UpperCAmelCase    			=   CustomTokenizer.from_pretrained(__lowerCAmelCase       )
        with tempfile.TemporaryDirectory() as tmp_dir:
          tokenizer.save_pretrained(__lowerCAmelCase       )

          _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )
          self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )

      finally:
        if "custom" in CONFIG_MAPPING._extra_content:
          del CONFIG_MAPPING._extra_content["custom"]
        if CustomConfig in TOKENIZER_MAPPING._extra_content:
          del TOKENIZER_MAPPING._extra_content[CustomConfig]


    @require_tokenizers
    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      try:
        AutoConfig.register("""custom""" ,					__lowerCAmelCase       )

        # Can register in two steps
        AutoTokenizer.register(__lowerCAmelCase ,					slow_tokenizer_class=__lowerCAmelCase       )
        self.assertEqual(TOKENIZER_MAPPING[CustomConfig] ,					(CustomTokenizer, None)       )
        AutoTokenizer.register(__lowerCAmelCase ,					fast_tokenizer_class=__lowerCAmelCase       )
        self.assertEqual(TOKENIZER_MAPPING[CustomConfig] ,					(CustomTokenizer, CustomTokenizerFast)       )

        del TOKENIZER_MAPPING._extra_content[CustomConfig]
        # Can register in one step
        AutoTokenizer.register(
            __lowerCAmelCase ,					slow_tokenizer_class=__lowerCAmelCase ,					fast_tokenizer_class=__lowerCAmelCase       )
        self.assertEqual(TOKENIZER_MAPPING[CustomConfig] ,					(CustomTokenizer, CustomTokenizerFast)       )

        # Trying to register something existing in the Transformers library will raise an error
        with self.assertRaises(__lowerCAmelCase       ):
          AutoTokenizer.register(__lowerCAmelCase ,					fast_tokenizer_class=__lowerCAmelCase       )

        # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer
        # and that model does not have a tokenizer.json
        with tempfile.TemporaryDirectory() as tmp_dir:
          _UpperCAmelCase    			=   BertTokenizerFast.from_pretrained(__lowerCAmelCase       )
          bert_tokenizer.save_pretrained(__lowerCAmelCase       )
          _UpperCAmelCase    			=   CustomTokenizerFast.from_pretrained(__lowerCAmelCase       )

        with tempfile.TemporaryDirectory() as tmp_dir:
          tokenizer.save_pretrained(__lowerCAmelCase       )

          _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase       )
          self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )

          _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					use_fast=__lowerCAmelCase       )
          self.assertIsInstance(__lowerCAmelCase ,					__lowerCAmelCase       )

      finally:
        if "custom" in CONFIG_MAPPING._extra_content:
          del CONFIG_MAPPING._extra_content["custom"]
        if CustomConfig in TOKENIZER_MAPPING._extra_content:
          del TOKENIZER_MAPPING._extra_content[CustomConfig]


    def   lowerCAmelCase_	(       self						:	List[str]       ):
      # If remote code is not set, we will time out when asking whether to load the model.
      with self.assertRaises(__lowerCAmelCase       ):
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer"""       )
      # If remote code is disabled, we can't load this config.
      with self.assertRaises(__lowerCAmelCase       ):
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(
            """hf-internal-testing/test_dynamic_tokenizer""" ,					trust_remote_code=__lowerCAmelCase       )

      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ,					trust_remote_code=__lowerCAmelCase       )
      self.assertTrue(tokenizer.special_attribute_present       )
      # Test tokenizer can be reloaded.
      with tempfile.TemporaryDirectory() as tmp_dir:
        tokenizer.save_pretrained(__lowerCAmelCase       )
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					trust_remote_code=__lowerCAmelCase       )
      self.assertTrue(reloaded_tokenizer.special_attribute_present       )

      if is_tokenizers_available():
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizerFast"""       )
        self.assertEqual(reloaded_tokenizer.__class__.__name__ ,					"""NewTokenizerFast"""       )

        # Test we can also load the slow version
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(
            """hf-internal-testing/test_dynamic_tokenizer""" ,					trust_remote_code=__lowerCAmelCase ,					use_fast=__lowerCAmelCase       )
        self.assertTrue(tokenizer.special_attribute_present       )
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )
        # Test tokenizer can be reloaded.
        with tempfile.TemporaryDirectory() as tmp_dir:
          tokenizer.save_pretrained(__lowerCAmelCase       )
          _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					trust_remote_code=__lowerCAmelCase ,					use_fast=__lowerCAmelCase       )
        self.assertEqual(reloaded_tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )
        self.assertTrue(reloaded_tokenizer.special_attribute_present       )
      else:
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )
        self.assertEqual(reloaded_tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )


    @require_tokenizers
    def   lowerCAmelCase_	(       self						:	List[str]       ):


      class 							a					(		lowerCAmelCase_ ):
          _snake_case  :	Tuple  				=				False



      class 							a					(		lowerCAmelCase_ ):
          _snake_case  :	Optional[int]  				=				NewTokenizer
          _snake_case  :	Any  				=				False

      try:
        AutoConfig.register("""custom""" ,					__lowerCAmelCase       )
        AutoTokenizer.register(__lowerCAmelCase ,					slow_tokenizer_class=__lowerCAmelCase       )
        AutoTokenizer.register(__lowerCAmelCase ,					fast_tokenizer_class=__lowerCAmelCase       )
        # If remote code is not set, the default is to use local
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer"""       )
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizerFast"""       )
        self.assertFalse(tokenizer.special_attribute_present       )
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ,					use_fast=__lowerCAmelCase       )
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )
        self.assertFalse(tokenizer.special_attribute_present       )

        # If remote code is disabled, we load the local one.
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(
            """hf-internal-testing/test_dynamic_tokenizer""" ,					trust_remote_code=__lowerCAmelCase       )
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizerFast"""       )
        self.assertFalse(tokenizer.special_attribute_present       )
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(
            """hf-internal-testing/test_dynamic_tokenizer""" ,					trust_remote_code=__lowerCAmelCase ,					use_fast=__lowerCAmelCase       )
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )
        self.assertFalse(tokenizer.special_attribute_present       )

        # If remote is enabled, we load from the Hub
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(
            """hf-internal-testing/test_dynamic_tokenizer""" ,					trust_remote_code=__lowerCAmelCase       )
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizerFast"""       )
        self.assertTrue(tokenizer.special_attribute_present       )
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(
            """hf-internal-testing/test_dynamic_tokenizer""" ,					trust_remote_code=__lowerCAmelCase ,					use_fast=__lowerCAmelCase       )
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )
        self.assertTrue(tokenizer.special_attribute_present       )

      finally:
        if "custom" in CONFIG_MAPPING._extra_content:
          del CONFIG_MAPPING._extra_content["custom"]
        if CustomConfig in TOKENIZER_MAPPING._extra_content:
          del TOKENIZER_MAPPING._extra_content[CustomConfig]


    def   lowerCAmelCase_	(       self						:	Dict       ):
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(
          """hf-internal-testing/test_dynamic_tokenizer_legacy""" ,					trust_remote_code=__lowerCAmelCase       )
      self.assertTrue(tokenizer.special_attribute_present       )
      if is_tokenizers_available():
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizerFast"""       )

        # Test we can also load the slow version
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(
            """hf-internal-testing/test_dynamic_tokenizer_legacy""" ,					trust_remote_code=__lowerCAmelCase ,					use_fast=__lowerCAmelCase       )
        self.assertTrue(tokenizer.special_attribute_present       )
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )
      else:
        self.assertEqual(tokenizer.__class__.__name__ ,					"""NewTokenizer"""       )


    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      with self.assertRaisesRegex(
          __lowerCAmelCase ,					"""bert-base is not a local folder and is not a valid model identifier"""       ):
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""bert-base"""       )


    def   lowerCAmelCase_	(       self						:	int       ):
      with self.assertRaisesRegex(
          __lowerCAmelCase ,					R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""       ):
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained(__lowerCAmelCase ,					revision="""aaaaaa"""       )


    def   lowerCAmelCase_	(       self						:	List[str]       ):
      # Make sure we have cached the tokenizer.
      _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert"""       )
      with RequestCounter() as counter:
        _UpperCAmelCase    			=   AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert"""       )
        self.assertEqual(counter.get_request_count ,					0       )
        self.assertEqual(counter.head_request_count ,					1       )
        self.assertEqual(counter.other_request_count ,					0       )
