code: 
  
  
  
  
  import unittest
  
  from cer import CER
  
  
  _lowerCamelCase							:		Any										=						CER()
  
  
  
  
  
  class   lowerCamelCase_							( unittest.TestCase							):
  
  
  
  
  					'''simple docstring'''
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["White House"]
  							_snake_case			 = ["white house"]
  							# S = 2, D = 0, I = 0, N = 11, CER = 2 / 11
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.18_18_18_18_18				) < 1E-6				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["were wolf"]
  							_snake_case			 = ["werewolf"]
  							# S = 0, D = 0, I = 1, N = 9, CER = 1 / 9
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.1_11_11_11				) < 1E-6				)
  
  							_snake_case			 = ["werewolf"]
  							_snake_case			 = ["weae     wolf"]
  							# S = 1, D = 1, I = 0, N = 8, CER = 0.25
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.25				) < 1E-6				)
  
  							# consecutive whitespaces case 1
  							_snake_case			 = ["were wolf"]
  							_snake_case			 = ["were               wolf"]
  							# S = 0, D = 0, I = 0, N = 9, CER = 0
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.0				) < 1E-6				)
  
  							# consecutive whitespaces case 2
  							_snake_case			 = ["were   wolf"]
  							_snake_case			 = ["were               wolf"]
  							# S = 0, D = 0, I = 0, N = 9, CER = 0
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.0				) < 1E-6				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["werewolf"]
  							_snake_case			 = ["weaewolf"]
  							# S = 1, D = 0, I = 0, N = 8, CER = 0.125
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.1_25				) < 1E-6				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["werewolf"]
  							_snake_case			 = ["wereawolf"]
  							# S = 0, D = 1, I = 0, N = 8, CER = 0.125
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.1_25				) < 1E-6				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["werewolf"]
  							_snake_case			 = ["wereolf"]
  							# S = 0, D = 0, I = 1, N = 8, CER = 0.125
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.1_25				) < 1E-6				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["werewolf"]
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertEqual(__lowerCamelCase,						0.0				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["werewolf", "I am your father"]
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertEqual(__lowerCamelCase,						0.0				)
  
  							_snake_case			 = ["werewolf", "I am your father", "doge"]
  							_snake_case			 = ["werxwolf", "I       am your father", "doge"]
  							# S = 1, D = 0, I = 0, N = 28, CER = 1 / 28
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.03_57_14_28				) < 1E-6				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["My hovercraft", "is full of eels"]
  							_snake_case			 = ["My hovercraft is full", " of eels"]
  							# S = 0, D = 0, I = 2, N = 28, CER = 2 / 28
  							# whitespace at the front of " of eels" will be strip during preporcessing
  							# so need to insert 2 whitespaces
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase,						concatenate_texts=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.07_14_28				) < 1E-6				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = ["我能吞下玻璃而不伤身体"]
  							_snake_case			 = [" 能吞虾玻璃而 不霜身体啦"]
  							# S = 3, D = 2, I = 0, N = 11, CER = 5 / 11
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.45_45_45_45_45				) < 1E-6				)
  
  							_snake_case			 = ["我能吞下玻璃", "而不伤身体"]
  							_snake_case			 = ["我    能 吞 下 玻 璃", "而不伤身体"]
  							# S = 0, D = 5, I = 0, N = 11, CER = 5 / 11
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertTrue(abs(char_error_rate - 0.45_45_45_45_45_45				) < 1E-6				)
  
  							_snake_case			 = ["我能吞下玻璃而不伤身体"]
  							_snake_case			 = cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  							self.assertFalse(__lowerCamelCase,						0.0				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self				):
  							_snake_case			 = [""]
  							_snake_case			 = ["Hypothesis"]
  							with self.assertRaises(__lowerCamelCase				):
  									cer.compute(predictions=__lowerCamelCase,						references=__lowerCamelCase				)
  
  
  if __name__ == "__main__":
  						unittest.main()
  
  
  
  
  
  
style_context: 
  
  
  
  
  '''simple docstring'''
  
  
  
  
  
  
  
  import copy
  import logging
  import random
  
  import joblib
  import numpy as np
  import torch
  import torch.nn as nn
  from torch.utils.data import DataLoader
  from tqdm import tqdm
  
  from transformers import AdamW, GPTaLMHeadModel, get_linear_schedule_with_warmup
  
  
  _lowerCamelCase							:		str										=						logging.getLogger(__name__)
  
  
  
  
  
  
  def 	_lowercase	(			lowercase_						):
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  
  		random.seed(lowercase_						)
  		np.random.seed(lowercase_						)
  		torch.manual_seed(lowercase_						)
  		torch.cuda.manual_seed_all(lowercase_						)
  
  
  
  
  
  
  def 	_lowercase	(			lowercase_		,							lowercase_		,							lowercase_						):
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  
  		model.eval()
  		_snake_case			 = next(model.parameters()						).device
  		_snake_case			 = 1
  		_snake_case			 = torch.zeros((eval_batch_size, context_len)		,							dtype=torch.long		,							device=lowercase_						)
  		_snake_case			 = DataLoader(lowercase_		,							shuffle=lowercase_		,							batch_size=lowercase_						)
  		_snake_case			 = torch.zeros(1		,							device=lowercase_						)
  		_snake_case			 = 0
  		for batch in eval_dataloader:
  				batch.to(lowercase_						)
  				# pad
  				context.zero_()
  				for i in range(lowercase_						):
  						_snake_case			 = batch[i]
  				_snake_case			 = model(lowercase_		,							labels=lowercase_						)
  				eval_loss += outputs[0].sum().item()
  				nb_eval_examples += batch.size(0						)
  		_snake_case			 = eval_loss / nb_eval_examples
  		_snake_case			 = torch.exp(lowercase_						)
  		model.train()
  		return perplexity
  
  
  
  
  
  
  def 	_lowercase	(			lowercase_="gpt2"						):
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  
  		_snake_case			 = GPTaLMHeadModel.from_pretrained(lowercase_		,							output_hidden_states=lowercase_						)
  		torch.save(model.state_dict()		,							model_name + "local.pt"						)
  		return model
  
  
  
  
  
  
  def 	_lowercase	(			lowercase_		,							lowercase_		,							lowercase_						):
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  
  		_snake_case			 = copy.deepcopy(lowercase_						)
  		model.to(lowercase_						)
  
  		_snake_case			 = ["bias", "LayerNorm.weight"]
  		_snake_case			 = [
  		    {
  		        "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay						)],
  		        "weight_decay": 0.0,
  		    },
  		    {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay						)], "weight_decay": 0.0},
  		]
  		_snake_case			 = AdamW(lowercase_		,							lr=5e-5		,							eps=1e-8						)
  		_snake_case			 = get_linear_schedule_with_warmup(lowercase_		,							0		,							lowercase_						)
  		torch.cuda.empty_cache()
  		return model, lm_optimizer, lm_scheduler
  
  
  
  
  
  
  def 	_lowercase	(			lowercase_		,							lowercase_		,							lowercase_		,							lowercase_						):
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  
  		_snake_case			 = np.array(lowercase_						).mean()
  		_snake_case			 = np.array(lowercase_						).std()
  		_snake_case			 = (real_perps - avg) / std
  		_snake_case			 = list(zip(lowercase_		,							lowercase_		,							lowercase_						)						)
  		joblib.dump(lowercase_		,							lowercase_						)
  
  
  
  
  
  
  def 	_lowercase	(			lowercase_		,							lowercase_		,							lowercase_		,							lowercase_		,							lowercase_		,							lowercase_		,							lowercase_		,							lowercase_="dev.jbl"		,							lowercase_=recopy_gpta		,							):
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  
  		_snake_case			 = []
  		_snake_case			 = []
  		_snake_case			 = []
  
  		# Initialize the transformer model
  		_snake_case			 = copy.deepcopy(lowercase_						)
  		orig_model.to(device="cpu"						)
  		torch.cuda.empty_cache()
  
  		# Compute perplexity of initial transformer model for comparison
  		model.train()
  		_snake_case ,					_snake_case ,					_snake_case			 = recopy_model(lowercase_		,							lowercase_		,							lowercase_						)
  
  		for step in tqdm(range(lowercase_						)						):
  				_snake_case			 = torch.zeros((1, context_len)		,							dtype=torch.long		,							device=lowercase_						)
  				_snake_case			 = random.choice(lowercase_						)
  				_snake_case			 = random.randint(0		,							len(story[0]						) - context_len - 1						)
  				_snake_case			 = story[0][start : start + context_len]
  				lm_optimizer.zero_grad()
  				_snake_case			 = model(lowercase_		,							labels=lowercase_						)
  				_snake_case			 = outputs[0]
  				_snake_case			 = compute_perplexity(lowercase_		,							lowercase_		,							lowercase_						)
  				model.train()
  				lm_loss.backward()
  				# Do LM backprop
  				torch.nn.utils.clip_grad_norm_(model.parameters()		,							3.0						)
  				lm_optimizer.step()
  				lm_scheduler.step()  # Update learning rate schedule
  
  				# Compute perplexity after back-propagating on the selected context
  				_snake_case			 = compute_perplexity(lowercase_		,							lowercase_		,							lowercase_						)
  
  				# Periodically save the stored (X, IG(X)) pairs
  				if step % 1000 == 0 and step > 1:
  						intermittent_save(lowercase_		,							lowercase_		,							lowercase_		,							lowercase_						)
  
  				# Reset the pretrained model to the original pretrained GPT-2 weights after each iteration
  				_snake_case ,					_snake_case ,					_snake_case			 = recopy_model(lowercase_		,							lowercase_		,							lowercase_						)
  
  				past_perps.append(past_perp.item()						)
  				real_perps.append(orig_perp - real_perp.item()						)
  				contexts.append(np.array(context.cpu()						)						)
  
  		intermittent_save(lowercase_		,							lowercase_		,							lowercase_		,							lowercase_						)
  
  
  
  
  
  
  def 	_lowercase	(			lowercase_		,							lowercase_="data/tokenized_stories_train_wikitext103.jbl"		,							lowercase_=100		,							lowercase_=1026		,							lowercase_=True						):
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  
  		_snake_case			 = joblib.load(lowercase_						)
  		print("data loaded"						)
  		_snake_case			 = []
  		if trim:
  				for i, example in enumerate(lowercase_						):
  						if len(example[0]						) > min_len:
  								_snake_case			 = random.randint(0		,							len(example[0]						) - context_len - 1						)
  								objective_set.append(example[0, start : start + context_len]						)
  						if len(lowercase_						) >= number:
  								break
  				_snake_case			 = []
  				for j in range(i + 1		,							len(lowercase_						)						):
  						if len(data[j][0]						) > min_len:
  								train_data.append(data[j]						)
  		else:
  				_snake_case			 = data[0:number]
  				_snake_case			 = data[number:]
  
  		joblib.dump(lowercase_		,							"objective_set.jbl"						)
  		print("objective set saved"						)
  		return train_data, objective_set
  
  
  
  
  
  
  def 	_lowercase	(			lowercase_		,							lowercase_		,							lowercase_		,							lowercase_		,							lowercase_=50		,							lowercase_="secondary_learner.pt"						):
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  
  		_snake_case			 = torch.device("cuda:0" if torch.cuda.is_available() else "cpu"						)
  		# We will use the first 512 pairs from our dataset as a test set for
  		# our secondary learner and the rest to train
  		_snake_case			 = train_dataset[:512]
  		_snake_case			 = train_dataset[512:]
  		_snake_case			 = DataLoader(lowercase_		,							shuffle=lowercase_		,							batch_size=lowercase_						)
  		_snake_case			 = DataLoader(lowercase_		,							shuffle=lowercase_		,							batch_size=lowercase_						)
  
  		# secondary learner model set up
  		_snake_case			 = nn.MSELoss()
  		_snake_case			 = nn.MSELoss(reduction="sum"						)
  		secondary_learner.to(lowercase_						)
  		_snake_case			 = torch.optim.Adam(secondary_learner.parameters()		,							lr=0.00001						)
  		secondary_learner.train()
  
  		# TODO in original code this is written as number of actual batches seen
  		# not number of items seen but other places it is number of items instead.
  		# improve consistency! changed this to epochs for clarity
  		_snake_case			 = float("inf"						)
  		# Iterate through batches until we've used max_steps batches
  		for epoch in range(int(lowercase_						)						):
  				_snake_case			 = 0.0
  				secondary_learner.train()
  				for step, batch in enumerate(lowercase_						):
  						_snake_case			 = batch[0].to(lowercase_						)
  						_snake_case			 = batch[1].to(lowercase_						)
  						_snake_case			 = secondary_learner(lowercase_						)
  						q_optimizer.zero_grad()
  						_snake_case			 = loss(lowercase_		,							real_q.float()						)
  						q_loss.backward()
  						q_optimizer.step()
  						tr_q_loss += q_loss.item()
  
  						# model trains fairly quickly so we won't wait for a full epoch
  						# eval is triggered at eval_freq and end of epochs
  						if (step % eval_freq == 0 and step > 0) or ((step + 1) == len(lowercase_						)):
  								_snake_case			 = tr_q_loss / (step + 1)
  
  								secondary_learner.eval()
  								_snake_case			 = 0.0
  								_snake_case			 = 0.0
  								_snake_case			 = []
  								_snake_case			 = []
  								# Compute performance of the secondary learner after this batch
  								for stepa, batcha in enumerate(lowercase_						):
  										_snake_case			 = batcha[0].to(lowercase_						)
  										_snake_case			 = batcha[1].to(lowercase_						)
  										_snake_case			 = secondary_learner(lowercase_						)
  										q_lossa += test_loss(lowercase_		,							lowercase_						).item()
  										sum_qa += torch.sum(lowercase_						).item()
  										for ei, i in enumerate(predicted_qa.cpu().detach().numpy()						):
  												predicted.append(i.item()						)
  										for ei, i in enumerate(real_qa.cpu().detach().numpy()						):
  												actual.append(i.item()						)
  
  								q_lossa /= len(lowercase_						)
  								print(
  								    "Epoch: "		,							lowercase_		,							"step: "		,							lowercase_		,							"Avg. q:"		,							sum_qa / len(lowercase_						)		,							"Train Loss: "		,							lowercase_		,							"Test Loss: "		,							lowercase_		,							)
  								if q_lossa < best_test_loss:
  										joblib.dump((predicted, actual)		,							"pred_vs_actual.jbl"						)
  										torch.save(secondary_learner.state_dict()		,							lowercase_						)
  										_snake_case			 = q_lossa
  
  						secondary_learner.train()
  		return secondary_learner
  
  
  
  
  
  class   lowerCamelCase_							( nn.Module							):
  
  
  
  
  					'''simple docstring'''
  
  
  
  
  
  
  					def __init__(					self,						__UpperCamelCase				):
  							super(__UpperCamelCase,						self				).__init__()
  							_snake_case			 = model.transformer.wte
  							_snake_case			 = copy.deepcopy(model.transformer.wte.weight				)
  							_snake_case			 = nn.Convad(self.embeddings.weight.size(1				),						256,						3,						padding=1				)
  							_snake_case			 = nn.Sequential(nn.Linear(256,						32				),						nn.Dropout(p=0.1				),						nn.Linear(32,						32				),						nn.Linear(32,						1				)				)
  
  
  
  
  
  
  					def        __SCREAMING_SNAKE_CASE			(					self,						__UpperCamelCase				):
  							_snake_case			 = torch.max(self.conv(self.embeddings(__UpperCamelCase				).squeeze(1				).transpose(1,						2				)				),						2				)[0]
  							_snake_case			 = self.fc(__UpperCamelCase				)
  							return qs.squeeze(1				)
  
  
  
  
  
  
  					@classmethod
  					def        __SCREAMING_SNAKE_CASE			(					cls,						__UpperCamelCase,						__UpperCamelCase				):
  							_snake_case			 = cls(__UpperCamelCase				)  # this calls __init__
  							_snake_case			 = torch.load(__UpperCamelCase				)
  							secondary_learner.load_state_dict(__UpperCamelCase				)
  							_snake_case			 = model.transformer.wte
  							_snake_case			 = copy.deepcopy(model.transformer.wte.weight				)
  							return secondary_learner
  
  
  
  
  
  