
'''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            = 100

class     a (					nn.Module     ):




				def __init__(				self						:					int,     SCREAMING_SNAKE_CASE_						:					List[str],     SCREAMING_SNAKE_CASE_						:					List[str]="gpt2-medium",     SCREAMING_SNAKE_CASE_						:					Tuple=False,     SCREAMING_SNAKE_CASE_						:					List[Any]="cpu"   ):
										super().__init__()
										snake_case							:  Optional[Any]			=     GPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_   )
										snake_case							:  Optional[int]			=     GPTaLMHeadModel.from_pretrained(SCREAMING_SNAKE_CASE_   )
										snake_case							:  int			=     self.encoder.transformer.config.hidden_size
										snake_case							:  Union[str, Any]			=     ClassificationHead(class_size=SCREAMING_SNAKE_CASE_,     embed_size=self.embed_size   )
										snake_case							:  str			=     cached_mode
										snake_case							:  Dict			=     device




				def 						__snake_case				(				self						:					Dict   ):
										return self.classifier_head




				def 						__snake_case				(				self						:					Optional[Any]   ):
										for param in self.encoder.parameters():
																snake_case							:  Optional[Any]			=     False
										self.classifier_head.train()




				def 						__snake_case				(				self						:					Tuple,     SCREAMING_SNAKE_CASE_						:					List[Any]   ):
										snake_case							:  Dict			=     x.ne(0   ).unsqueeze(2   ).repeat(1,     1,     self.embed_size   ).float().to(self.device   ).detach()
										snake_case							:  str			=     self.encoder.transformer(SCREAMING_SNAKE_CASE_   )['''last_hidden_state''']
										snake_case							:  Any			=     hidden * mask
										snake_case							:  Union[str, Any]			=     torch.sum(SCREAMING_SNAKE_CASE_,     dim=1   ) / (torch.sum(SCREAMING_SNAKE_CASE_,     dim=1   ).detach() + EPSILON)
										return avg_hidden




				def 						__snake_case				(				self						:					Tuple,     SCREAMING_SNAKE_CASE_						:					Union[str, Any]   ):
										if self.cached_mode:
																snake_case							:  Union[str, Any]			=     x.to(self.device   )
										else:
																snake_case							:  Tuple			=     self.avg_representation(x.to(self.device   )   )

										snake_case							:  Any			=     self.classifier_head(SCREAMING_SNAKE_CASE_   )
										snake_case							:  List[Any]			=     nn.functional.log_softmax(SCREAMING_SNAKE_CASE_,     dim=-1   )

										return probs




class     a (					data.Dataset     ):




				def __init__(				self						:					Any,     SCREAMING_SNAKE_CASE_						:					int,     SCREAMING_SNAKE_CASE_						:					Any   ):
										snake_case							:  Tuple			=     X
										snake_case							:  Any			=     y




				def __len__(				self						:					Union[str, Any]   ):
										return len(self.X   )




				def __getitem__(				self						:					List[Any],     SCREAMING_SNAKE_CASE_						:					List[str]   ):
										snake_case							:  List[str]			=     {}
										snake_case							:  int			=     self.X[index]
										snake_case							:  Any			=     self.y[index]
										return data




def   A			(							A_				:       List[str]							):
						def pad_sequences(A_				:       List[str]							):
												snake_case							:  Any			=     [len(A_							) for seq in sequences]

												snake_case							:  Tuple			=     torch.zeros(len(A_							)     ,				max(A_							)							).long()  # padding value = 0

												for i, seq in enumerate(A_							):
																		snake_case							:  str			=     lengths[i]
																		snake_case							:  List[Any]			=     seq[:end]

												return padded_sequences, lengths

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

						snake_case,       snake_case							:  Any			=     pad_sequences(item_info['''X''']							)
						snake_case							:  Optional[Any]			=     torch.tensor(item_info['''y''']     ,				dtype=torch.long							)

						return x_batch, y_batch

def   A			(							A_				:       Optional[int]							):
						snake_case							:  Tuple			=     {}
						for key in data[0].keys():
												snake_case							:  List[str]			=     [d[key] for d in data]

						snake_case							:  int			=     torch.cat(item_info['''X''']     ,				0							)
						snake_case							:  int			=     torch.tensor(item_info['''y''']     ,				dtype=torch.long							)

						return x_batch, y_batch

def   A			(							A_				:       Tuple     ,				A_				:       List[Any]     ,				A_				:       List[str]     ,				A_				:       Dict=0     ,				A_				:       int=10     ,				A_				:       int="cpu"							):
						snake_case							:  Dict			=     0
						discriminator.train_custom()
						for batch_idx, (input_t, target_t) in enumerate(A_							):
												snake_case,       snake_case							:  Any			=     input_t.to(A_							), target_t.to(A_							)

												optimizer.zero_grad()

												snake_case							:  int			=     discriminator(A_							)
												snake_case							:  str			=     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			(							A_				:       Any     ,				A_				:       Tuple     ,				A_				:       Optional[Any]="cpu"							):
						discriminator.eval()
						snake_case							:  str			=     0
						snake_case							:  str			=     0
						with torch.no_grad():
												for input_t, target_t in data_loader:
																		snake_case,       snake_case							:  Optional[int]			=     input_t.to(A_							), target_t.to(A_							)
																		snake_case							:  Any			=     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
																		snake_case							:  str			=     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							)     ,				100.0 * correct / len(data_loader.dataset							)							)							)

def   A			(							A_				:       Optional[Any]     ,				A_				:       List[Any]     ,				A_				:       Tuple     ,				A_				:       Dict=False     ,				A_				:       int="cpu"							):
						snake_case							:  Dict			=     model.tokenizer.encode(A_							)
						snake_case							:  Dict			=     torch.tensor([input_t]     ,				dtype=torch.long     ,				device=A_							)
						if cached:
												snake_case							:  int			=     model.avg_representation(A_							)

						snake_case							:  Optional[Any]			=     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			(							A_				:       Dict     ,				A_				:       str     ,				A_				:       Tuple     ,				A_				:       int=False     ,				A_				:       List[Any]="cpu"							):
						snake_case							:  str			=     torch.utils.data.DataLoader(dataset=A_     ,				batch_size=A_     ,				collate_fn=A_							)

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

						snake_case							:  Any			=     torch.utils.data.DataLoader(
						    dataset=Dataset(A_     ,				A_							)     ,				batch_size=A_     ,				shuffle=A_     ,				collate_fn=A_							)

						return data_loader

def   A			(							A_				:       Any     ,				A_				:       Any=None     ,				A_				:       List[str]="gpt2-medium"     ,				A_				:       Any=10     ,				A_				:       str=64     ,				A_				:       int=10     ,				A_				:       Any=False     ,				A_				:       Optional[int]=False     ,				A_				:       Optional[Any]=False     ,				):
						snake_case							:  int			=     '''cuda''' if torch.cuda.is_available() and not no_cuda else '''cpu'''

						print('''Preprocessing {} dataset...'''.format(A_							)							)
						snake_case							:  Optional[Any]			=     time.time()

						if dataset == "SST":
												snake_case							:  List[str]			=     ['''positive''', '''negative''', '''very positive''', '''very negative''', '''neutral''']
												snake_case							:  Dict			=     {c: i for i, c in enumerate(A_							)}

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

												snake_case							:  Optional[int]			=     torchtext_data.Field()
												snake_case							:  Union[str, Any]			=     torchtext_data.Field(sequential=A_							)
												snake_case,       snake_case,       snake_case							:  Dict			=     datasets.SST.splits(
												    A_     ,				A_     ,				fine_grained=A_     ,				train_subtrees=A_     ,				)

												snake_case							:  Optional[Any]			=     []
												snake_case							:  Any			=     []
												for i in trange(len(A_							)     ,				ascii=A_							):
																		snake_case							:  Tuple			=     TreebankWordDetokenizer().detokenize(vars(train_data[i]							)['''text''']							)
																		snake_case							:  Dict			=     discriminator.tokenizer.encode(A_							)
																		snake_case							:  Optional[int]			=     torch.tensor([50256] + seq     ,				device=A_     ,				dtype=torch.long							)
																		x.append(A_							)
																		y.append(classaidx[vars(train_data[i]							)['''label''']]							)
												snake_case							:  Tuple			=     Dataset(A_     ,				A_							)

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

												snake_case							:  List[str]			=     {
												    '''class_size''': len(A_							),
												    '''embed_size''': discriminator.embed_size,
												    '''pretrained_model''': pretrained_model,
												    '''class_vocab''': classaidx,
												    '''default_class''': 2,
												}

						elif dataset == "clickbait":
												snake_case							:  List[str]			=     ['''non_clickbait''', '''clickbait''']
												snake_case							:  int			=     {c: i for i, c in enumerate(A_							)}

												snake_case							:  Union[str, 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:
																		snake_case							:  Union[str, Any]			=     []
																		for i, line in enumerate(A_							):
																								try:
																														data.append(eval(A_							)							)
																								except Exception:
																														print('''Error evaluating line {}: {}'''.format(A_     ,				A_							)							)
																														continue
												snake_case							:  str			=     []
												snake_case							:  Optional[Any]			=     []
												with open('''datasets/clickbait/clickbait_train_prefix.txt'''							) as f:
																		for i, line in enumerate(tqdm(A_     ,				ascii=A_							)							):
																								try:
																														snake_case							:  Union[str, Any]			=     eval(A_							)
																														snake_case							:  Union[str, Any]			=     discriminator.tokenizer.encode(d['''text''']							)

																														if len(A_							) < max_length_seq:
																																				snake_case							:  Dict			=     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

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

												snake_case							:  Any			=     {
												    '''class_size''': len(A_							),
												    '''embed_size''': discriminator.embed_size,
												    '''pretrained_model''': pretrained_model,
												    '''class_vocab''': classaidx,
												    '''default_class''': 1,
												}

						elif dataset == "toxic":
												snake_case							:  str			=     ['''non_toxic''', '''toxic''']
												snake_case							:  Union[str, Any]			=     {c: i for i, c in enumerate(A_							)}

												snake_case							:  int			=     Discriminator(
												    class_size=len(A_							)     ,				pretrained_model=A_     ,				cached_mode=A_     ,				device=A_							).to(A_							)

												snake_case							:  Optional[Any]			=     []
												snake_case							:  Any			=     []
												with open('''datasets/toxic/toxic_train.txt'''							) as f:
																		for i, line in enumerate(tqdm(A_     ,				ascii=A_							)							):
																								try:
																														snake_case							:  Optional[int]			=     eval(A_							)
																														snake_case							:  str			=     discriminator.tokenizer.encode(d['''text''']							)

																														if len(A_							) < max_length_seq:
																																				snake_case							:  Optional[int]			=     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

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

												snake_case							:  List[str]			=     {
												    '''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.'''							)

												snake_case							:  Optional[int]			=     set()
												with open(A_							) as f:
																		snake_case							:  List[Any]			=     csv.reader(A_     ,				delimiter='''\t'''							)
																		for row in tqdm(A_     ,				ascii=A_							):
																								if row:
																														classes.add(row[0]							)

												snake_case							:  int			=     sorted(A_							)
												snake_case							:  Any			=     {c: i for i, c in enumerate(A_							)}

												snake_case							:  str			=     Discriminator(
												    class_size=len(A_							)     ,				pretrained_model=A_     ,				cached_mode=A_     ,				device=A_							).to(A_							)

												snake_case							:  Union[str, Any]			=     []
												snake_case							:  Tuple			=     []
												with open(A_							) as f:
																		snake_case							:  Dict			=     csv.reader(A_     ,				delimiter='''\t'''							)
																		for i, row in enumerate(tqdm(A_     ,				ascii=A_							)							):
																								if row:
																														snake_case							:  Union[str, Any]			=     row[0]
																														snake_case							:  Union[str, Any]			=     row[1]

																														try:
																																				snake_case							:  int			=     discriminator.tokenizer.encode(A_							)
																																				if len(A_							) < max_length_seq:
																																										snake_case							:  Tuple			=     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

												snake_case							:  Tuple			=     Dataset(A_     ,				A_							)
												snake_case							:  Any			=     int(0.9 * len(A_							)							)
												snake_case							:  List[str]			=     len(A_							) - train_size
												snake_case,       snake_case							:  int			=     torch.utils.data.random_split(A_     ,				[train_size, test_size]							)

												snake_case							:  Any			=     {
												    '''class_size''': len(A_							),
												    '''embed_size''': discriminator.embed_size,
												    '''pretrained_model''': pretrained_model,
												    '''class_vocab''': classaidx,
												    '''default_class''': 0,
												}

						snake_case							:  Union[str, 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...'''							)

												snake_case							:  Optional[int]			=     time.time()

												snake_case							:  Optional[int]			=     get_cached_data_loader(A_     ,				A_     ,				A_     ,				shuffle=A_     ,				device=A_							)

												snake_case							:  Union[str, Any]			=     get_cached_data_loader(A_     ,				A_     ,				A_     ,				device=A_							)

												snake_case							:  Dict			=     time.time()
												print('''Building representation cache took: {:.3f}s'''.format(end - start							)							)

						else:
												snake_case							:  int			=     torch.utils.data.DataLoader(
												    dataset=A_     ,				batch_size=A_     ,				shuffle=A_     ,				collate_fn=A_							)
												snake_case							:  Tuple			=     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_							)

						snake_case							:  Dict			=     optim.Adam(discriminator.parameters()     ,				lr=0.0001							)

						for epoch in range(A_							):
												snake_case							:  Dict			=     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_							)

												snake_case							:  Optional[int]			=     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 concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class 	lowerCamelCase_				(			UpperCAmelCase_,			unittest.TestCase				):




					'''simple docstring'''






					lowercase__       =					PreTrainedTokenizerFast
					lowercase__       =					False
					lowercase__       =					True
					lowercase__       =					"""tokenizer_file"""






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			False  # because we don't have pretrained_vocab_files_map
							super().setUp()
							_snake_case      			=			True

							_snake_case      			=			["robot-test/dummy-tokenizer-fast", "robot-test/dummy-tokenizer-wordlevel"]
							_snake_case      			=			"SaulLu/dummy-tokenizer-bytelevel-bpe"

							# Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
							_snake_case      			=			[(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

							_snake_case      			=			PreTrainedTokenizerFast.from_pretrained(model_paths[0]					)
							tokenizer.save_pretrained(self.tmpdirname					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
							# model
							pass






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
							# model
							pass






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
							# model
							pass






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							# PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
							pass






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			self.tmpdirname
							# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
							for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
									with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''					):
											try:
													_snake_case      			=			tempfile.mkdtemp()
													_snake_case      			=			self.rust_tokenizer_class.from_pretrained(__UpperCamelCase,    **__UpperCamelCase					)

													tokenizer.save_pretrained(self.tmpdirname					)
													super().test_training_new_tokenizer()
											finally:
													# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
													# is restored
													shutil.rmtree(self.tmpdirname					)
													_snake_case      			=			tmpdirname_orig






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			self.tmpdirname
							# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
							for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
									with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''					):
											try:
													_snake_case      			=			tempfile.mkdtemp()
													_snake_case      			=			self.rust_tokenizer_class.from_pretrained(__UpperCamelCase,    **__UpperCamelCase					)

													tokenizer.save_pretrained(self.tmpdirname					)
													super().test_training_new_tokenizer_with_special_tokens_change()
											finally:
													# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
													# is restored
													shutil.rmtree(self.tmpdirname					)
													_snake_case      			=			tmpdirname_orig






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name					)

							_snake_case      			=			("a" for _ in range(1_000					))
							_snake_case      			=			tokenizer.train_new_from_iterator(text_iterator=__UpperCamelCase,    length=1_000,    vocab_size=50					)

							_snake_case      			=			new_tokenizer.encode("a🤗"					)
							self.assertEqual(__UpperCamelCase,    [64, 172, 253, 97, 245]					)





@require_tokenizers
class 	lowerCamelCase_				(			unittest.TestCase				):




					'''simple docstring'''






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			AutoTokenizer.from_pretrained("bert-base-cased"					)
							_snake_case      			=			json.loads(tokenizer._tokenizer.to_str()					)
							_snake_case      			=			len(__UpperCamelCase					)

							with tempfile.TemporaryDirectory() as tmp_dir:
									# Hack to save this in the tokenizer_config.json
									_snake_case      			=			["tokenizer.4.0.0.json"]
									tokenizer.save_pretrained(__UpperCamelCase					)
									json.dump(__UpperCamelCase,    open(os.path.join(__UpperCamelCase,    "tokenizer.4.0.0.json"					),    "w"					)					)

									# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
									_snake_case      			=			AutoTokenizer.from_pretrained(__UpperCamelCase					)
									self.assertEqual(len(__UpperCamelCase					),    len(__UpperCamelCase					) + 1					)
									_snake_case      			=			json.loads(new_tokenizer._tokenizer.to_str()					)
									self.assertIn("huggingface",    json_tokenizer["model"]["vocab"]					)

									# Will need to be adjusted if we reach v42 and this test is still here.
									# Should pick the old tokenizer file as the version of Transformers is < 4.0.0
									shutil.move(os.path.join(__UpperCamelCase,    "tokenizer.4.0.0.json"					),    os.path.join(__UpperCamelCase,    "tokenizer.42.0.0.json"					)					)
									_snake_case      			=			["tokenizer.42.0.0.json"]
									tokenizer.save_pretrained(__UpperCamelCase					)
									_snake_case      			=			AutoTokenizer.from_pretrained(__UpperCamelCase					)
									self.assertEqual(len(__UpperCamelCase					),    len(__UpperCamelCase					)					)
									_snake_case      			=			json.loads(new_tokenizer._tokenizer.to_str()					)
									self.assertNotIn("huggingface",    json_tokenizer["model"]["vocab"]					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							# This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
							_snake_case      			=			"hf-internal-testing/test-two-tokenizers"

							# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
							_snake_case      			=			AutoTokenizer.from_pretrained(__UpperCamelCase					)
							self.assertEqual(len(__UpperCamelCase					),    28_997					)
							_snake_case      			=			json.loads(tokenizer._tokenizer.to_str()					)
							self.assertIn("huggingface",    json_tokenizer["model"]["vocab"]					)

							# Testing an older version by monkey-patching the version in the module it's used.
							import transformers as old_transformers

							_snake_case      			=			"3.0.0"
							_snake_case      			=			old_transformers.models.auto.AutoTokenizer.from_pretrained(__UpperCamelCase					)
							self.assertEqual(len(__UpperCamelCase					),    28_996					)
							_snake_case      			=			json.loads(old_tokenizer._tokenizer.to_str()					)
							self.assertNotIn("huggingface",    json_tokenizer["model"]["vocab"]					)





@require_tokenizers
class 	lowerCamelCase_				(			unittest.TestCase				):




					'''simple docstring'''






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							# See https://github.com/huggingface/transformers/pull/12550
							# and https://github.com/huggingface/tokenizers/issues/537
							_snake_case      			=			PreTrainedTokenizerFast.from_pretrained("robot-test/dummy-tokenizer-wordlevel"					)
							_snake_case      			=			"The Matrix is a 1999 science fiction action film."

							with concurrent.futures.ThreadPoolExecutor() as executor:
									_snake_case      			=			[executor.submit(self.fetch,    __UpperCamelCase,    __UpperCamelCase					) for i in range(10					)]
									_snake_case      			=			[future.result() for future in futures]
									self.assertEqual(__UpperCamelCase,    [[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10					)]					)






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase					):
							return tokenizer.encode(__UpperCamelCase,    truncation="longest_first",    padding="longest"					)





