



"""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      :      Tuple   					=					1E-10
__UpperCAmelCase      :      List[Any]   					=					'This is incredible! I love it, this is the best chicken I have ever had.'
__UpperCAmelCase      :      Any   					=					1_00

class 	__lowerCAmelCase							(nn.Module  ):


					'''simple docstring'''


					def __init__(      self    ,       a    ,       a="gpt2-medium"    ,       a=False    ,       a="cpu"   ):




										"""simple docstring"""





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







					def 		_a (      self   ):




										"""simple docstring"""





										return self.classifier_head







					def 		_a (      self   ):




										"""simple docstring"""





										for param in self.encoder.parameters():
															snake_case_						:Union[str, Any]								=						False
										self.classifier_head.train()







					def 		_a (      self    ,       a   ):




										"""simple docstring"""





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







					def 		_a (      self    ,       a   ):




										"""simple docstring"""





										if self.cached_mode:
															snake_case_						:Optional[Any]								=						x.to(self.device   )
										else:
															snake_case_						:Optional[int]								=						self.avg_representation(x.to(self.device   )   )

										snake_case_						:Any								=						self.classifier_head(a   )
										snake_case_						:Tuple								=						nn.functional.log_softmax(a    ,       dim=-1   )

										return probs



class 	__lowerCAmelCase							(data.Dataset  ):


					'''simple docstring'''


					def __init__(      self    ,       a    ,       a   ):




										"""simple docstring"""





										snake_case_						:Union[str, Any]								=						X
										snake_case_						:int								=						y







					def __len__(      self   ):




										"""simple docstring"""





										return len(self.X   )







					def __getitem__(      self    ,       a   ):




										"""simple docstring"""





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



def      A      (			_A							):




					"""simple docstring"""
					def pad_sequences(_A							):
										snake_case_						:Optional[int]								=						[len(_A							) for seq in sequences]

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

										for i, seq in enumerate(_A							):
															snake_case_						:str								=						lengths[i]
															snake_case_						:str								=						seq[:end]

										return padded_sequences, lengths

					snake_case_						:Dict								=						{}
					for key in data[0].keys():
										snake_case_						:List[Any]								=						[d[key] for d in data]

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

					return x_batch, y_batch
def      A      (			_A							):




					"""simple docstring"""
					snake_case_						:Tuple								=						{}
					for key in data[0].keys():
										snake_case_						:Dict								=						[d[key] for d in data]

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

					return x_batch, y_batch
def      A      (			_A,     _A,     _A,     _A=0,     _A=10,     _A="cpu"							):




					"""simple docstring"""
					snake_case_						:Optional[int]								=						0
					discriminator.train_custom()
					for batch_idx, (input_t, target_t) in enumerate(_A							):
										snake_case_	,  snake_case_						:List[str]								=						input_t.to(_A							), target_t.to(_A							)

										optimizer.zero_grad()

										snake_case_						:Optional[int]								=						discriminator(_A							)
										snake_case_						: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      (			_A,     _A,     _A="cpu"							):




					"""simple docstring"""
					discriminator.eval()
					snake_case_						:Tuple								=						0
					snake_case_						:Optional[int]								=						0
					with torch.no_grad():
										for input_t, target_t in data_loader:
															snake_case_	,  snake_case_						:List[Any]								=						input_t.to(_A							), target_t.to(_A							)
															snake_case_						:List[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_						: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							),     100.0 * correct / len(data_loader.dataset							)							)							)
def      A      (			_A,     _A,     _A,     _A=False,     _A="cpu"							):




					"""simple docstring"""
					snake_case_						:Any								=						model.tokenizer.encode(_A							)
					snake_case_						:List[str]								=						torch.tensor([input_t],     dtype=torch.long,     device=_A							)
					if cached:
										snake_case_						:List[str]								=						model.avg_representation(_A							)

					snake_case_						:Optional[int]								=						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,     _A,     _A,     _A=False,     _A="cpu"							):




					"""simple docstring"""
					snake_case_						:Any								=						torch.utils.data.DataLoader(dataset=_A,     batch_size=_A,     collate_fn=_A							)

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

					snake_case_						:Optional[int]								=						torch.utils.data.DataLoader(
					    dataset=Dataset(_A,     _A							),     batch_size=_A,     shuffle=_A,     collate_fn=_A							)

					return data_loader
def      A      (			_A,     _A=None,     _A="gpt2-medium",     _A=10,     _A=64,     _A=10,     _A=False,     _A=False,     _A=False,     ):




					"""simple docstring"""
					snake_case_						:List[Any]								=						"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_						:Any								=						{c: i for i, c in enumerate(_A							)}

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

										snake_case_						:List[str]								=						torchtext_data.Field()
										snake_case_						:List[Any]								=						torchtext_data.Field(sequential=_A							)
										snake_case_	,  snake_case_	,  snake_case_						:str								=						datasets.SST.splits(
										    _A,     _A,     fine_grained=_A,     train_subtrees=_A,     )

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

										snake_case_						:List[str]								=						[]
										snake_case_						:Tuple								=						[]
										for i in trange(len(_A							),     ascii=_A							):
															snake_case_						:List[Any]								=						TreebankWordDetokenizer().detokenize(vars(test_data[i]							)["text"]							)
															snake_case_						:int								=						discriminator.tokenizer.encode(_A							)
															snake_case_						:int								=						torch.tensor([50_256] + seq,     device=_A,     dtype=torch.long							)
															test_x.append(_A							)
															test_y.append(classaidx[vars(test_data[i]							)["label"]]							)
										snake_case_						:List[str]								=						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[Any]								=						["non_clickbait", "clickbait"]
										snake_case_						:Dict								=						{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							)

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

																									if len(_A							) < max_length_seq:
																														snake_case_						:Any								=						torch.tensor([50_256] + 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_						:Dict								=						Dataset(_A,     _A							)
										snake_case_						:str								=						int(0.9 * len(_A							)							)
										snake_case_						:List[Any]								=						len(_A							) - train_size
										snake_case_	,  snake_case_						:Any								=						torch.utils.data.random_split(_A,     [train_size, test_size]							)

										snake_case_						:Tuple								=						{
										    "class_size": len(_A							),
										    "embed_size": discriminator.embed_size,
										    "pretrained_model": pretrained_model,
										    "class_vocab": classaidx,
										    "default_class": 1,
										}

					elif dataset == "toxic":
										snake_case_						:Optional[int]								=						["non_toxic", "toxic"]
										snake_case_						:str								=						{c: i for i, c in enumerate(_A							)}

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

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

																									if len(_A							) < max_length_seq:
																														snake_case_						:List[Any]								=						torch.tensor([50_256] + 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_						:Any								=						Dataset(_A,     _A							)
										snake_case_						:Tuple								=						int(0.9 * len(_A							)							)
										snake_case_						:Any								=						len(_A							) - train_size
										snake_case_	,  snake_case_						:List[Any]								=						torch.utils.data.random_split(_A,     [train_size, test_size]							)

										snake_case_						: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."							)

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

										snake_case_						:str								=						sorted(_A							)
										snake_case_						:str								=						{c: i for i, c in enumerate(_A							)}

										snake_case_						:List[str]								=						Discriminator(
										    class_size=len(_A							),     pretrained_model=_A,     cached_mode=_A,     device=_A							).to(_A							)

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

																									try:
																														snake_case_						:str								=						discriminator.tokenizer.encode(_A							)
																														if len(_A							) < max_length_seq:
																																			snake_case_						:Optional[Any]								=						torch.tensor([50_256] + 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_						:List[Any]								=						Dataset(_A,     _A							)
										snake_case_						:Optional[Any]								=						int(0.9 * len(_A							)							)
										snake_case_						:List[Any]								=						len(_A							) - train_size
										snake_case_	,  snake_case_						:Tuple								=						torch.utils.data.random_split(_A,     [train_size, test_size]							)

										snake_case_						:Optional[Any]								=						{
										    "class_size": len(_A							),
										    "embed_size": discriminator.embed_size,
										    "pretrained_model": pretrained_model,
										    "class_vocab": classaidx,
										    "default_class": 0,
										}

					snake_case_						:int								=						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_						:Any								=						time.time()

										snake_case_						:Tuple								=						get_cached_data_loader(_A,     _A,     _A,     shuffle=_A,     device=_A							)

										snake_case_						:Optional[Any]								=						get_cached_data_loader(_A,     _A,     _A,     device=_A							)

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

					else:
										snake_case_						:str								=						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_						:Optional[int]								=						optim.Adam(discriminator.parameters(),     lr=0.0_001							)

					for epoch in range(_A							):
										snake_case_						:str								=						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_						:Union[str, Any]								=						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      :      Any   					=					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      :      Dict   					=					parser.parse_args()

				train_discriminator(**(vars(args)))






"""simple docstring"""






def      A      (			_A,     _A							):




					"""simple docstring"""
					if not isinstance(_A,     _A							):
										raise TypeError("plaintext must be a string"							)
					if not isinstance(_A,     _A							):
										raise TypeError("key must be a string"							)

					if not plaintext:
										raise ValueError("plaintext is empty"							)
					if not key:
										raise ValueError("key is empty"							)

					key += plaintext
					snake_case_						:Optional[int]								=						plaintext.lower()
					snake_case_						:Union[str, Any]								=						key.lower()
					snake_case_						:Any								=						0
					snake_case_						:str								=						0
					snake_case_						:Union[str, Any]								=						""
					while plaintext_iterator < len(_A							):
										if (
										    ord(plaintext[plaintext_iterator]							) < 97
										    or ord(plaintext[plaintext_iterator]							) > 122
										):
															ciphertext += plaintext[plaintext_iterator]
															plaintext_iterator += 1
										elif ord(key[key_iterator]							) < 97 or ord(key[key_iterator]							) > 122:
															key_iterator += 1
										else:
															ciphertext += chr(
															    (
															        (ord(plaintext[plaintext_iterator]							) - 97 + ord(key[key_iterator]							))
															        - 97
															    )
															    % 26
															    + 97							)
															key_iterator += 1
															plaintext_iterator += 1
					return ciphertext
def      A      (			_A,     _A							):




					"""simple docstring"""
					if not isinstance(_A,     _A							):
										raise TypeError("ciphertext must be a string"							)
					if not isinstance(_A,     _A							):
										raise TypeError("key must be a string"							)

					if not ciphertext:
										raise ValueError("ciphertext is empty"							)
					if not key:
										raise ValueError("key is empty"							)

					snake_case_						:Tuple								=						key.lower()
					snake_case_						:Tuple								=						0
					snake_case_						:int								=						0
					snake_case_						:int								=						""
					while ciphertext_iterator < len(_A							):
										if (
										    ord(ciphertext[ciphertext_iterator]							) < 97
										    or ord(ciphertext[ciphertext_iterator]							) > 122
										):
															plaintext += ciphertext[ciphertext_iterator]
										else:
															plaintext += chr(
															    (ord(ciphertext[ciphertext_iterator]							) - ord(key[key_iterator]							)) % 26
															    + 97							)
															key += chr(
															    (ord(ciphertext[ciphertext_iterator]							) - ord(key[key_iterator]							)) % 26
															    + 97							)
															key_iterator += 1
										ciphertext_iterator += 1
					return plaintext


if __name__ == "__main__":
				import doctest

				doctest.testmod()
				__UpperCAmelCase      :      Dict   					=					int(input('Type 1 to encrypt or 2 to decrypt:'))
				if operation == 1:
								__UpperCAmelCase      :      List[str]   					=					input('Typeplaintext to be encrypted:\n')
								__UpperCAmelCase      :      Optional[int]   					=					input('Type the key:\n')
								print(encrypt(plaintext, key))
				elif operation == 2:
								__UpperCAmelCase      :      List[Any]   					=					input('Type the ciphertext to be decrypted:\n')
								__UpperCAmelCase      :      Dict   					=					input('Type the key:\n')
								print(decrypt(ciphertext, key))
				decrypt('jsqqs avvwo', 'coffee')

