






"""simple docstring"""





# Copyright (c) 2019 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import csv
import json
import math
import time

import numpy as np
import torch
import torch.optim as optim
import torch.utils.data as data
from nltk.tokenize.treebank import TreebankWordDetokenizer
from pplm_classification_head import ClassificationHead
from torch import nn
from torchtext import data as torchtext_data
from torchtext import datasets
from tqdm import tqdm, trange

from transformers import GPTaLMHeadModel, GPTaTokenizer


torch.manual_seed(0)
np.random.seed(0)
UpperCamelCase			=      1e-10
UpperCamelCase			=      """This is incredible! I love it, this is the best chicken I have ever had."""
UpperCamelCase			=      1_00







class 		_a       (						nn.Module   ):





   '''simple docstring'''






   def __init__(   self			,				UpperCAmelCase_			,				UpperCAmelCase_="gpt2-medium"			,				UpperCAmelCase_=False			,				UpperCAmelCase_="cpu")	-> int:




          '''simple docstring'''




          super().__init__()
          lowercase__:    Union[str, Any]        =      GPTaTokenizer.from_pretrained(UpperCAmelCase_)
          lowercase__:    Any        =      GPTaLMHeadModel.from_pretrained(UpperCAmelCase_)
          lowercase__:    List[str]        =      self.encoder.transformer.config.hidden_size
          lowercase__:    Optional[Any]        =      ClassificationHead(class_size=UpperCAmelCase_			,				embed_size=self.embed_size)
          lowercase__:    List[str]        =      cached_mode
          lowercase__:    int        =      device





   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          return self.classifier_head





   def __lowercase    (   self)	-> Any:




          '''simple docstring'''




          for param in self.encoder.parameters():
                 lowercase__:    int        =      False
          self.classifier_head.train()





   def __lowercase    (   self			,				UpperCAmelCase_)	-> Dict:




          '''simple docstring'''




          lowercase__:    str        =      x.ne(0).unsqueeze(2).repeat(1			,				1			,				self.embed_size).float().to(self.device).detach()
          lowercase__:    List[Any]        =      self.encoder.transformer(UpperCAmelCase_)["last_hidden_state"]
          lowercase__:    Dict        =      hidden * mask
          lowercase__:    int        =      torch.sum(UpperCAmelCase_			,				dim=1) / (torch.sum(UpperCAmelCase_			,				dim=1).detach() + EPSILON)
          return avg_hidden





   def __lowercase    (   self			,				UpperCAmelCase_)	-> Any:




          '''simple docstring'''




          if self.cached_mode:
                 lowercase__:    Optional[int]        =      x.to(self.device)
          else:
                 lowercase__:    Union[str, Any]        =      self.avg_representation(x.to(self.device))

          lowercase__:    List[str]        =      self.classifier_head(UpperCAmelCase_)
          lowercase__:    Union[str, Any]        =      nn.functional.log_softmax(UpperCAmelCase_			,				dim=-1)

          return probs







class 		_a       (						data.Dataset   ):





   '''simple docstring'''






   def __init__(   self			,				UpperCAmelCase_			,				UpperCAmelCase_)	-> Optional[int]:




          '''simple docstring'''




          lowercase__:    List[str]        =      X
          lowercase__:    Optional[Any]        =      y





   def __len__(   self)	-> Dict:




          '''simple docstring'''




          return len(self.X)





   def __getitem__(   self			,				UpperCAmelCase_)	-> Any:




          '''simple docstring'''




          lowercase__:    Union[str, Any]        =      {}
          lowercase__:    Dict        =      self.X[index]
          lowercase__:    List[Any]        =      self.y[index]
          return data







def     A(  snake_case_		):
       """simple docstring"""





       def pad_sequences(snake_case_		):
              lowercase__:    Optional[int]        =      [len(_a		) for seq in sequences]

              lowercase__:    str        =      torch.zeros(len(_a		)						,       max(_a		)		).long()  # padding value = 0

              for i, seq in enumerate(_a		):
                     lowercase__:    int        =      lengths[i]
                     lowercase__:    List[Any]        =      seq[:end]

              return padded_sequences, lengths

       lowercase__:    Optional[int]        =      {}
       for key in data[0].keys():
              lowercase__:    Tuple        =      [d[key] for d in data]

       lowercase__:    Any        =      pad_sequences(item_info["X"]		)
       lowercase__:    Union[str, Any]        =      torch.tensor(item_info["y"]						,       dtype=torch.long		)

       return x_batch, y_batch






def     A(  snake_case_		):
       """simple docstring"""





       lowercase__:    int        =      {}
       for key in data[0].keys():
              lowercase__:    str        =      [d[key] for d in data]

       lowercase__:    Optional[int]        =      torch.cat(item_info["X"]						,       0		)
       lowercase__:    Dict        =      torch.tensor(item_info["y"]						,       dtype=torch.long		)

       return x_batch, y_batch






def     A(  snake_case_						,       snake_case_						,       snake_case_						,       snake_case_=0						,       snake_case_=10						,       snake_case_="cpu"		):
       """simple docstring"""





       lowercase__:    Tuple        =      0
       discriminator.train_custom()
       for batch_idx, (input_t, target_t) in enumerate(_a		):
              lowercase__:    Optional[int]        =      input_t.to(_a		), target_t.to(_a		)

              optimizer.zero_grad()

              lowercase__:    List[str]        =      discriminator(_a		)
              lowercase__:    Dict        =      nn.functional.nll_loss(_a						,       _a		)
              loss.backward(retain_graph=_a		)
              optimizer.step()

              samples_so_far += len(_a		)

              if batch_idx % log_interval == 0:
                     print(
                         "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format(
                             epoch + 1						,       _a						,       len(data_loader.dataset		)						,       100 * samples_so_far / len(data_loader.dataset		)						,       loss.item()						,       )		)






def     A(  snake_case_						,       snake_case_						,       snake_case_="cpu"		):
       """simple docstring"""





       discriminator.eval()
       lowercase__:    int        =      0
       lowercase__:    Optional[int]        =      0
       with torch.no_grad():
              for input_t, target_t in data_loader:
                     lowercase__:    Any        =      input_t.to(_a		), target_t.to(_a		)
                     lowercase__:    str        =      discriminator(_a		)
                     # sum up batch loss
                     test_loss += nn.functional.nll_loss(_a						,       _a						,       reduction="sum"		).item()
                     # get the index of the max log-probability
                     lowercase__:    List[Any]        =      output_t.argmax(dim=1						,       keepdim=_a		)
                     correct += pred_t.eq(target_t.view_as(_a		)		).sum().item()

       test_loss /= len(data_loader.dataset		)

       print(
           "Performance on test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)".format(
               _a						,       _a						,       len(data_loader.dataset		)						,       1_00.0 * correct / len(data_loader.dataset		)		)		)






def     A(  snake_case_						,       snake_case_						,       snake_case_						,       snake_case_=False						,       snake_case_="cpu"		):
       """simple docstring"""





       lowercase__:    str        =      model.tokenizer.encode(_a		)
       lowercase__:    List[Any]        =      torch.tensor([input_t]						,       dtype=torch.long						,       device=_a		)
       if cached:
              lowercase__:    int        =      model.avg_representation(_a		)

       lowercase__:    Tuple        =      model(_a		).data.cpu().numpy().flatten().tolist()
       print("Input sentence:"						,       _a		)
       print(
           "Predictions:"						,       ", ".join("{}: {:.4f}".format(_a						,       math.exp(_a		)		) for c, log_prob in zip(_a						,       _a		)		)						,       )






def     A(  snake_case_						,       snake_case_						,       snake_case_						,       snake_case_=False						,       snake_case_="cpu"		):
       """simple docstring"""





       lowercase__:    Tuple        =      torch.utils.data.DataLoader(dataset=_a						,       batch_size=_a						,       collate_fn=_a		)

       lowercase__:    List[str]        =      []
       lowercase__:    Optional[Any]        =      []
       for batch_idx, (x, y) in enumerate(tqdm(_a						,       ascii=_a		)		):
              with torch.no_grad():
                     lowercase__:    str        =      x.to(_a		)
                     lowercase__:    Union[str, Any]        =      discriminator.avg_representation(_a		).cpu().detach()
                     lowercase__:    int        =      torch.unbind(avg_rep.unsqueeze(1		)		)
                     xs += avg_rep_list
                     ys += y.cpu().numpy().tolist()

       lowercase__:    str        =      torch.utils.data.DataLoader(
           dataset=Dataset(_a						,       _a		)						,       batch_size=_a						,       shuffle=_a						,       collate_fn=_a		)

       return data_loader






def     A(  snake_case_						,       snake_case_=None						,       snake_case_="gpt2-medium"						,       snake_case_=10						,       snake_case_=64						,       snake_case_=10						,       snake_case_=False						,       snake_case_=False						,       snake_case_=False						,       ):
       """simple docstring"""





       lowercase__:    Any        =      "cuda" if torch.cuda.is_available() and not no_cuda else "cpu"

       print("Preprocessing {} dataset...".format(_a		)		)
       lowercase__:    Optional[int]        =      time.time()

       if dataset == "SST":
              lowercase__:    Optional[int]        =      ["positive", "negative", "very positive", "very negative", "neutral"]
              lowercase__:    List[Any]        =      {c: i for i, c in enumerate(_a		)}

              lowercase__:    Optional[int]        =      Discriminator(
                  class_size=len(_a		)						,       pretrained_model=_a						,       cached_mode=_a						,       device=_a		).to(_a		)

              lowercase__:    str        =      torchtext_data.Field()
              lowercase__:    List[Any]        =      torchtext_data.Field(sequential=_a		)
              lowercase__:    Dict        =      datasets.SST.splits(
                  _a						,       _a						,       fine_grained=_a						,       train_subtrees=_a						,       )

              lowercase__:    Union[str, Any]        =      []
              lowercase__:    int        =      []
              for i in trange(len(_a		)						,       ascii=_a		):
                     lowercase__:    int        =      TreebankWordDetokenizer().detokenize(vars(train_data[i]		)["text"]		)
                     lowercase__:    List[Any]        =      discriminator.tokenizer.encode(_a		)
                     lowercase__:    str        =      torch.tensor([50256] + seq						,       device=_a						,       dtype=torch.long		)
                     x.append(_a		)
                     y.append(classaidx[vars(train_data[i]		)["label"]]		)
              lowercase__:    Tuple        =      Dataset(_a						,       _a		)

              lowercase__:    Union[str, Any]        =      []
              lowercase__:    Dict        =      []
              for i in trange(len(_a		)						,       ascii=_a		):
                     lowercase__:    Union[str, Any]        =      TreebankWordDetokenizer().detokenize(vars(test_data[i]		)["text"]		)
                     lowercase__:    Optional[Any]        =      discriminator.tokenizer.encode(_a		)
                     lowercase__:    Optional[Any]        =      torch.tensor([50256] + seq						,       device=_a						,       dtype=torch.long		)
                     test_x.append(_a		)
                     test_y.append(classaidx[vars(test_data[i]		)["label"]]		)
              lowercase__:    Optional[int]        =      Dataset(_a						,       _a		)

              lowercase__:    Optional[Any]        =      {
                  "class_size": len(_a		),
                  "embed_size": discriminator.embed_size,
                  "pretrained_model": pretrained_model,
                  "class_vocab": classaidx,
                  "default_class": 2,
              }

       elif dataset == "clickbait":
              lowercase__:    Optional[Any]        =      ["non_clickbait", "clickbait"]
              lowercase__:    Tuple        =      {c: i for i, c in enumerate(_a		)}

              lowercase__:    List[Any]        =      Discriminator(
                  class_size=len(_a		)						,       pretrained_model=_a						,       cached_mode=_a						,       device=_a		).to(_a		)

              with open("datasets/clickbait/clickbait_train_prefix.txt"		) as f:
                     lowercase__:    Tuple        =      []
                     for i, line in enumerate(_a		):
                            try:
                                   data.append(eval(_a		)		)
                            except Exception:
                                   print("Error evaluating line {}: {}".format(_a						,       _a		)		)
                                   continue
              lowercase__:    Optional[Any]        =      []
              lowercase__:    Optional[Any]        =      []
              with open("datasets/clickbait/clickbait_train_prefix.txt"		) as f:
                     for i, line in enumerate(tqdm(_a						,       ascii=_a		)		):
                            try:
                                   lowercase__:    Dict        =      eval(_a		)
                                   lowercase__:    Optional[Any]        =      discriminator.tokenizer.encode(d["text"]		)

                                   if len(_a		) < max_length_seq:
                                          lowercase__:    Union[str, Any]        =      torch.tensor([50256] + seq						,       device=_a						,       dtype=torch.long		)
                                   else:
                                          print("Line {} is longer than maximum length {}".format(_a						,       _a		)		)
                                          continue
                                   x.append(_a		)
                                   y.append(d["label"]		)
                            except Exception:
                                   print("Error evaluating / tokenizing line {}, skipping it".format(_a		)		)
                                   pass

              lowercase__:    Optional[Any]        =      Dataset(_a						,       _a		)
              lowercase__:    Optional[int]        =      int(0.9 * len(_a		)		)
              lowercase__:    Optional[Any]        =      len(_a		) - train_size
              lowercase__:    Optional[Any]        =      torch.utils.data.random_split(_a						,       [train_size, test_size]		)

              lowercase__:    Any        =      {
                  "class_size": len(_a		),
                  "embed_size": discriminator.embed_size,
                  "pretrained_model": pretrained_model,
                  "class_vocab": classaidx,
                  "default_class": 1,
              }

       elif dataset == "toxic":
              lowercase__:    Optional[Any]        =      ["non_toxic", "toxic"]
              lowercase__:    int        =      {c: i for i, c in enumerate(_a		)}

              lowercase__:    int        =      Discriminator(
                  class_size=len(_a		)						,       pretrained_model=_a						,       cached_mode=_a						,       device=_a		).to(_a		)

              lowercase__:    Any        =      []
              lowercase__:    Dict        =      []
              with open("datasets/toxic/toxic_train.txt"		) as f:
                     for i, line in enumerate(tqdm(_a						,       ascii=_a		)		):
                            try:
                                   lowercase__:    Dict        =      eval(_a		)
                                   lowercase__:    Tuple        =      discriminator.tokenizer.encode(d["text"]		)

                                   if len(_a		) < max_length_seq:
                                          lowercase__:    str        =      torch.tensor([50256] + seq						,       device=_a						,       dtype=torch.long		)
                                   else:
                                          print("Line {} is longer than maximum length {}".format(_a						,       _a		)		)
                                          continue
                                   x.append(_a		)
                                   y.append(int(np.sum(d["label"]		) > 0		)		)
                            except Exception:
                                   print("Error evaluating / tokenizing line {}, skipping it".format(_a		)		)
                                   pass

              lowercase__:    Any        =      Dataset(_a						,       _a		)
              lowercase__:    Union[str, Any]        =      int(0.9 * len(_a		)		)
              lowercase__:    Dict        =      len(_a		) - train_size
              lowercase__:    Any        =      torch.utils.data.random_split(_a						,       [train_size, test_size]		)

              lowercase__:    List[Any]        =      {
                  "class_size": len(_a		),
                  "embed_size": discriminator.embed_size,
                  "pretrained_model": pretrained_model,
                  "class_vocab": classaidx,
                  "default_class": 0,
              }

       else:  # if dataset == "generic":
              # This assumes the input dataset is a TSV with the following structure:
              # class \t text

              if dataset_fp is None:
                     raise ValueError("When generic dataset is selected, dataset_fp needs to be specified aswell."		)

              lowercase__:    str        =      set()
              with open(_a		) as f:
                     lowercase__:    Any        =      csv.reader(_a						,       delimiter="\t"		)
                     for row in tqdm(_a						,       ascii=_a		):
                            if row:
                                   classes.add(row[0]		)

              lowercase__:    Optional[Any]        =      sorted(_a		)
              lowercase__:    List[Any]        =      {c: i for i, c in enumerate(_a		)}

              lowercase__:    Tuple        =      Discriminator(
                  class_size=len(_a		)						,       pretrained_model=_a						,       cached_mode=_a						,       device=_a		).to(_a		)

              lowercase__:    Optional[int]        =      []
              lowercase__:    List[str]        =      []
              with open(_a		) as f:
                     lowercase__:    Any        =      csv.reader(_a						,       delimiter="\t"		)
                     for i, row in enumerate(tqdm(_a						,       ascii=_a		)		):
                            if row:
                                   lowercase__:    Dict        =      row[0]
                                   lowercase__:    List[Any]        =      row[1]

                                   try:
                                          lowercase__:    int        =      discriminator.tokenizer.encode(_a		)
                                          if len(_a		) < max_length_seq:
                                                 lowercase__:    List[str]        =      torch.tensor([50256] + seq						,       device=_a						,       dtype=torch.long		)

                                          else:
                                                 print("Line {} is longer than maximum length {}".format(_a						,       _a		)		)
                                                 continue

                                          x.append(_a		)
                                          y.append(classaidx[label]		)

                                   except Exception:
                                          print("Error tokenizing line {}, skipping it".format(_a		)		)
                                          pass

              lowercase__:    str        =      Dataset(_a						,       _a		)
              lowercase__:    Optional[int]        =      int(0.9 * len(_a		)		)
              lowercase__:    Optional[int]        =      len(_a		) - train_size
              lowercase__:    Optional[Any]        =      torch.utils.data.random_split(_a						,       [train_size, test_size]		)

              lowercase__:    Union[str, Any]        =      {
                  "class_size": len(_a		),
                  "embed_size": discriminator.embed_size,
                  "pretrained_model": pretrained_model,
                  "class_vocab": classaidx,
                  "default_class": 0,
              }

       lowercase__:    Optional[Any]        =      time.time()
       print("Preprocessed {} data points".format(len(_a		) + len(_a		)		)		)
       print("Data preprocessing took: {:.3f}s".format(end - start		)		)

       if cached:
              print("Building representation cache..."		)

              lowercase__:    List[Any]        =      time.time()

              lowercase__:    int        =      get_cached_data_loader(_a						,       _a						,       _a						,       shuffle=_a						,       device=_a		)

              lowercase__:    Tuple        =      get_cached_data_loader(_a						,       _a						,       _a						,       device=_a		)

              lowercase__:    Any        =      time.time()
              print("Building representation cache took: {:.3f}s".format(end - start		)		)

       else:
              lowercase__:    Tuple        =      torch.utils.data.DataLoader(
                  dataset=_a						,       batch_size=_a						,       shuffle=_a						,       collate_fn=_a		)
              lowercase__:    Any        =      torch.utils.data.DataLoader(dataset=_a						,       batch_size=_a						,       collate_fn=_a		)

       if save_model:
              with open("{}_classifier_head_meta.json".format(_a		)						,       "w"		) as meta_file:
                     json.dump(_a						,       _a		)

       lowercase__:    Dict        =      optim.Adam(discriminator.parameters()						,       lr=0.00_01		)

       for epoch in range(_a		):
              lowercase__:    Union[str, Any]        =      time.time()
              print("\nEpoch"						,       epoch + 1		)

              train_epoch(
                  discriminator=_a						,       data_loader=_a						,       optimizer=_a						,       epoch=_a						,       log_interval=_a						,       device=_a						,       )
              evaluate_performance(data_loader=_a						,       discriminator=_a						,       device=_a		)

              lowercase__:    List[str]        =      time.time()
              print("Epoch took: {:.3f}s".format(end - start		)		)

              print("\nExample prediction"		)
              predict(_a						,       _a						,       _a						,       cached=_a						,       device=_a		)

              if save_model:
                     # torch.save(discriminator.state_dict(),
                     #           "{}_discriminator_{}.pt".format(
                     #               args.dataset, epoch + 1
                     #               ))
                     torch.save(
                         discriminator.get_classifier().state_dict()						,       "{}_classifier_head_epoch_{}.pt".format(_a						,       epoch + 1		)						,       )


if __name__ == "__main__":
       UpperCamelCase			=      argparse.ArgumentParser(description="""Train a discriminator on top of GPT-2 representations""")
       parser.add_argument(
           """--dataset""",
           type=str,
           default="""SST""",
           choices=("""SST""", """clickbait""", """toxic""", """generic"""),
           help=(
               """dataset to train the discriminator on."""
               """In case of generic, the dataset is expected"""
               """to be a TSBV file with structure: class \\t text"""
           ),
       )
       parser.add_argument(
           """--dataset_fp""",
           type=str,
           default="""""",
           help="""File path of the dataset to use. Needed only in case of generic datadset""",
       )
       parser.add_argument(
           """--pretrained_model""", type=str, default="""gpt2-medium""", help="""Pretrained model to use as encoder"""
       )
       parser.add_argument("""--epochs""", type=int, default=10, metavar="""N""", help="""Number of training epochs""")
       parser.add_argument(
           """--batch_size""", type=int, default=64, metavar="""N""", help="""input batch size for training (default: 64)"""
       )
       parser.add_argument(
           """--log_interval""",
           type=int,
           default=10,
           metavar="""N""",
           help="""how many batches to wait before logging training status""",
       )
       parser.add_argument("""--save_model""", action="""store_true""", help="""whether to save the model""")
       parser.add_argument("""--cached""", action="""store_true""", help="""whether to cache the input representations""")
       parser.add_argument("""--no_cuda""", action="""store_true""", help="""use to turn off cuda""")
       UpperCamelCase			=      parser.parse_args()

       train_discriminator(**(vars(args)))














"""simple docstring"""





import os
import unittest

from transformers import ElectraTokenizerFast
from transformers.models.electra.tokenization_electra import (
    VOCAB_FILES_NAMES,
    BasicTokenizer,
    ElectraTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english







@require_tokenizers
class 		_a       (						lowercase_    ,					unittest.TestCase   ):





   '''simple docstring'''






   UpperCamelCase__      					=    ElectraTokenizer
   UpperCamelCase__      					=    ElectraTokenizerFast
   UpperCamelCase__      					=    True
   UpperCamelCase__      					=    True
   UpperCamelCase__      					=    filter_non_english





   def __lowercase    (   self)	-> str:




          '''simple docstring'''




          super().setUp()

          lowercase__:    List[str]        =      [
              "[UNK]",
              "[CLS]",
              "[SEP]",
              "[PAD]",
              "[MASK]",
              "want",
              "##want",
              "##ed",
              "wa",
              "un",
              "runn",
              "##ing",
              ",",
              "low",
              "lowest",
          ]
          lowercase__:    int        =      os.path.join(self.tmpdirname			,				VOCAB_FILES_NAMES["vocab_file"])
          with open(self.vocab_file			,				"w"			,				encoding="utf-8") as vocab_writer:
                 vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))





   def __lowercase    (   self			,				UpperCAmelCase_)	-> Dict:




          '''simple docstring'''




          lowercase__:    str        =      "UNwant\u00E9d,running"
          lowercase__:    List[Any]        =      "unwanted, running"
          return input_text, output_text





   def __lowercase    (   self)	-> Union[str, Any]:




          '''simple docstring'''




          lowercase__:    str        =      self.tokenizer_class(self.vocab_file)

          lowercase__:    Tuple        =      tokenizer.tokenize("UNwant\u00E9d,running")
          self.assertListEqual(UpperCAmelCase_			,				["un", "##want", "##ed", ",", "runn", "##ing"])
          self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_)			,				[9, 6, 7, 12, 10, 11])





   def __lowercase    (   self)	-> Optional[int]:




          '''simple docstring'''




          if not self.test_rust_tokenizer:
                 return

          lowercase__:    Dict        =      self.get_tokenizer()
          lowercase__:    List[Any]        =      self.get_rust_tokenizer()

          lowercase__:    Optional[Any]        =      "UNwant\u00E9d,running"

          lowercase__:    Tuple        =      tokenizer.tokenize(UpperCAmelCase_)
          lowercase__:    Tuple        =      rust_tokenizer.tokenize(UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          lowercase__:    List[str]        =      tokenizer.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
          lowercase__:    Optional[Any]        =      rust_tokenizer.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          lowercase__:    List[Any]        =      self.get_rust_tokenizer()
          lowercase__:    int        =      tokenizer.encode(UpperCAmelCase_)
          lowercase__:    str        =      rust_tokenizer.encode(UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          # With lower casing
          lowercase__:    Optional[Any]        =      self.get_tokenizer(do_lower_case=UpperCAmelCase_)
          lowercase__:    List[Any]        =      self.get_rust_tokenizer(do_lower_case=UpperCAmelCase_)

          lowercase__:    str        =      "UNwant\u00E9d,running"

          lowercase__:    str        =      tokenizer.tokenize(UpperCAmelCase_)
          lowercase__:    Tuple        =      rust_tokenizer.tokenize(UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          lowercase__:    List[Any]        =      tokenizer.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
          lowercase__:    List[str]        =      rust_tokenizer.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

          lowercase__:    Any        =      self.get_rust_tokenizer()
          lowercase__:    Dict        =      tokenizer.encode(UpperCAmelCase_)
          lowercase__:    List[Any]        =      rust_tokenizer.encode(UpperCAmelCase_)
          self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)





   def __lowercase    (   self)	-> Dict:




          '''simple docstring'''




          lowercase__:    Optional[int]        =      BasicTokenizer()

          self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz")			,				["ah", "\u535A", "\u63A8", "zz"])





   def __lowercase    (   self)	-> Optional[int]:




          '''simple docstring'''




          lowercase__:    str        =      BasicTokenizer(do_lower_case=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  ")			,				["hello", "!", "how", "are", "you", "?"])
          self.assertListEqual(tokenizer.tokenize("H\u00E9llo")			,				["hello"])





   def __lowercase    (   self)	-> Union[str, Any]:




          '''simple docstring'''




          lowercase__:    Any        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				strip_accents=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["hällo", "!", "how", "are", "you", "?"])
          self.assertListEqual(tokenizer.tokenize("H\u00E9llo")			,				["h\u00E9llo"])





   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    Tuple        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				strip_accents=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["hallo", "!", "how", "are", "you", "?"])
          self.assertListEqual(tokenizer.tokenize("H\u00E9llo")			,				["hello"])





   def __lowercase    (   self)	-> Union[str, Any]:




          '''simple docstring'''




          lowercase__:    int        =      BasicTokenizer(do_lower_case=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["hallo", "!", "how", "are", "you", "?"])
          self.assertListEqual(tokenizer.tokenize("H\u00E9llo")			,				["hello"])





   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          lowercase__:    Optional[int]        =      BasicTokenizer(do_lower_case=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  ")			,				["HeLLo", "!", "how", "Are", "yoU", "?"])





   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          lowercase__:    Optional[Any]        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				strip_accents=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["HäLLo", "!", "how", "Are", "yoU", "?"])





   def __lowercase    (   self)	-> Union[str, Any]:




          '''simple docstring'''




          lowercase__:    Any        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				strip_accents=UpperCAmelCase_)

          self.assertListEqual(
              tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  ")			,				["HaLLo", "!", "how", "Are", "yoU", "?"])





   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    List[Any]        =      BasicTokenizer(do_lower_case=UpperCAmelCase_			,				never_split=["[UNK]"])

          self.assertListEqual(
              tokenizer.tokenize(" \tHeLLo!how  \n Are yoU? [UNK]")			,				["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"])





   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    List[str]        =      ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]

          lowercase__:    Dict        =      {}
          for i, token in enumerate(UpperCAmelCase_):
                 lowercase__:    Optional[int]        =      i
          lowercase__:    str        =      WordpieceTokenizer(vocab=UpperCAmelCase_			,				unk_token="[UNK]")

          self.assertListEqual(tokenizer.tokenize("")			,				[])

          self.assertListEqual(tokenizer.tokenize("unwanted running")			,				["un", "##want", "##ed", "runn", "##ing"])

          self.assertListEqual(tokenizer.tokenize("unwantedX running")			,				["[UNK]", "runn", "##ing"])





   def __lowercase    (   self)	-> Dict:




          '''simple docstring'''




          self.assertTrue(_is_whitespace(" "))
          self.assertTrue(_is_whitespace("\t"))
          self.assertTrue(_is_whitespace("\r"))
          self.assertTrue(_is_whitespace("\n"))
          self.assertTrue(_is_whitespace("\u00A0"))

          self.assertFalse(_is_whitespace("A"))
          self.assertFalse(_is_whitespace("-"))





   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          self.assertTrue(_is_control("\u0005"))

          self.assertFalse(_is_control("A"))
          self.assertFalse(_is_control(" "))
          self.assertFalse(_is_control("\t"))
          self.assertFalse(_is_control("\r"))





   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          self.assertTrue(_is_punctuation("-"))
          self.assertTrue(_is_punctuation("$"))
          self.assertTrue(_is_punctuation("`"))
          self.assertTrue(_is_punctuation("."))

          self.assertFalse(_is_punctuation("A"))
          self.assertFalse(_is_punctuation(" "))





   def __lowercase    (   self)	-> Tuple:




          '''simple docstring'''




          lowercase__:    Optional[Any]        =      self.get_tokenizer()
          lowercase__:    str        =      self.get_rust_tokenizer()

          # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
          self.assertListEqual([tokenizer.tokenize(UpperCAmelCase_) for t in ["Test", "\xad", "test"]]			,				[["[UNK]"], [], ["[UNK]"]])

          self.assertListEqual(
              [rust_tokenizer.tokenize(UpperCAmelCase_) for t in ["Test", "\xad", "test"]]			,				[["[UNK]"], [], ["[UNK]"]])





   @slow
   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    Dict        =      self.tokenizer_class.from_pretrained("google/electra-base-discriminator")

          lowercase__:    Optional[int]        =      tokenizer.encode("sequence builders"			,				add_special_tokens=UpperCAmelCase_)
          lowercase__:    List[str]        =      tokenizer.encode("multi-sequence build"			,				add_special_tokens=UpperCAmelCase_)

          lowercase__:    Dict        =      tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_)
          lowercase__:    Union[str, Any]        =      tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_			,				UpperCAmelCase_)

          assert encoded_sentence == [101] + text + [102]
          assert encoded_pair == [101] + text + [102] + text_a + [102]





   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                 with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
                        lowercase__:    Any        =      self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)

                        lowercase__:    int        =      F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
                        lowercase__:    Tuple        =      tokenizer_r.encode_plus(
                            UpperCAmelCase_			,				return_attention_mask=UpperCAmelCase_			,				return_token_type_ids=UpperCAmelCase_			,				return_offsets_mapping=UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_			,				)

                        lowercase__:    str        =      tokenizer_r.do_lower_case if hasattr(UpperCAmelCase_			,				"do_lower_case") else False
                        lowercase__:    List[Any]        =      (
                            [
                                ((0, 0), tokenizer_r.cls_token),
                                ((0, 1), "A"),
                                ((1, 2), ","),
                                ((3, 5), "na"),
                                ((5, 6), "##ï"),
                                ((6, 8), "##ve"),
                                ((9, 15), tokenizer_r.mask_token),
                                ((16, 21), "Allen"),
                                ((21, 23), "##NL"),
                                ((23, 24), "##P"),
                                ((25, 33), "sentence"),
                                ((33, 34), "."),
                                ((0, 0), tokenizer_r.sep_token),
                            ]
                            if not do_lower_case
                            else [
                                ((0, 0), tokenizer_r.cls_token),
                                ((0, 1), "a"),
                                ((1, 2), ","),
                                ((3, 8), "naive"),
                                ((9, 15), tokenizer_r.mask_token),
                                ((16, 21), "allen"),
                                ((21, 23), "##nl"),
                                ((23, 24), "##p"),
                                ((25, 33), "sentence"),
                                ((33, 34), "."),
                                ((0, 0), tokenizer_r.sep_token),
                            ]
                        )

                        self.assertEqual(
                            [e[1] for e in expected_results]			,				tokenizer_r.convert_ids_to_tokens(tokens["input_ids"]))
                        self.assertEqual([e[0] for e in expected_results]			,				tokens["offset_mapping"])





   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          lowercase__:    Union[str, Any]        =      ["的", "人", "有"]
          lowercase__:    Any        =      "".join(UpperCAmelCase_)
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                 with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
                        lowercase__:    Optional[Any]        =      True
                        lowercase__:    List[str]        =      self.tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)
                        lowercase__:    Dict        =      self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)

                        lowercase__:    str        =      tokenizer_p.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
                        lowercase__:    Optional[int]        =      tokenizer_r.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)

                        lowercase__:    Union[str, Any]        =      tokenizer_r.convert_ids_to_tokens(UpperCAmelCase_)
                        lowercase__:    List[str]        =      tokenizer_p.convert_ids_to_tokens(UpperCAmelCase_)

                        # it is expected that each Chinese character is not preceded by "##"
                        self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)
                        self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)

                        lowercase__:    Dict        =      False
                        lowercase__:    Optional[int]        =      self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)
                        lowercase__:    int        =      self.tokenizer_class.from_pretrained(UpperCAmelCase_			,				**UpperCAmelCase_)

                        lowercase__:    str        =      tokenizer_r.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)
                        lowercase__:    Tuple        =      tokenizer_p.encode(UpperCAmelCase_			,				add_special_tokens=UpperCAmelCase_)

                        lowercase__:    Union[str, Any]        =      tokenizer_r.convert_ids_to_tokens(UpperCAmelCase_)
                        lowercase__:    List[str]        =      tokenizer_p.convert_ids_to_tokens(UpperCAmelCase_)

                        # it is expected that only the first Chinese character is not preceded by "##".
                        lowercase__:    List[str]        =      [
                            F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase_)
                        ]
                        self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)
                        self.assertListEqual(UpperCAmelCase_			,				UpperCAmelCase_)






