






"""simple docstring"""



# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# 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 json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


_snake_case       :      Union[str, Any]       =					os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
_snake_case       :      Optional[int]       =					os.path.join(hf_cache_home, "accelerate")
_snake_case       :      int       =					os.path.join(cache_dir, "default_config.yaml")
_snake_case       :      str       =					os.path.join(cache_dir, "default_config.yaml")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
						_snake_case       :      int       =					default_yaml_config_file
else:
						_snake_case       :      List[str]       =					default_json_config_file




def 						lowerCamelCase_				(  __A  :		Optional[int]			):
					if config_file is not None:
										if not os.path.isfile(__A			):
															raise FileNotFoundError(
															    f"The passed configuration file `{config_file}` does not exist. "
															    'Please pass an existing file to `accelerate launch`, or use the the default one '
															    'created through `accelerate config` and run `accelerate launch` '
															    'without the `--config_file` argument.'			)
					else:
										lowerCamelCase__				=default_config_file
					with open(__A			,	'r'			,	encoding='utf-8'			) as f:
										if config_file.endswith('.json'			):
															if (
															    json.load(__A			).get('compute_environment'			,	ComputeEnvironment.LOCAL_MACHINE			)
															    == ComputeEnvironment.LOCAL_MACHINE
															):
																				lowerCamelCase__				=ClusterConfig
															else:
																				lowerCamelCase__				=SageMakerConfig
															return config_class.from_json_file(json_file=__A			)
										else:
															if (
															    yaml.safe_load(__A			).get('compute_environment'			,	ComputeEnvironment.LOCAL_MACHINE			)
															    == ComputeEnvironment.LOCAL_MACHINE
															):
																				lowerCamelCase__				=ClusterConfig
															else:
																				lowerCamelCase__				=SageMakerConfig
															return config_class.from_yaml_file(yaml_file=__A			)




@dataclass
class        __lowercase:
						lowerCAmelCase_		:							ComputeEnvironment
						lowerCAmelCase_		:							Union[DistributedType, SageMakerDistributedType]
						lowerCAmelCase_		:							str
						lowerCAmelCase_		:							bool






						def 		lowerCAmelCase   (					self)			->  List[str]:




											"""simple docstring"""





											lowerCamelCase__				=self.__dict__
											# For serialization, it's best to convert Enums to strings (or their underlying value type).
											for key, value in result.items():
																if isinstance(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE):
																					lowerCamelCase__				=value.value
																if isinstance(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE) and not bool(_SCREAMING_SNAKE_CASE):
																					lowerCamelCase__				=None
											lowerCamelCase__				={k: v for k, v in result.items() if v is not None}
											return result






						@classmethod
						def 		lowerCAmelCase   (					cls    ,						_SCREAMING_SNAKE_CASE=None)			->  Dict:




											"""simple docstring"""





											lowerCamelCase__				=default_json_config_file if json_file is None else json_file
											with open(_SCREAMING_SNAKE_CASE    ,						'r'    ,						encoding='utf-8') as f:
																lowerCamelCase__				=json.load(_SCREAMING_SNAKE_CASE)
											if "compute_environment" not in config_dict:
																lowerCamelCase__				=ComputeEnvironment.LOCAL_MACHINE
											if "mixed_precision" not in config_dict:
																lowerCamelCase__				='fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
											if "fp16" in config_dict:  # Convert the config to the new format.
																del config_dict["fp16"]
											if "dynamo_backend" in config_dict:  # Convert the config to the new format.
																lowerCamelCase__				=config_dict.pop('dynamo_backend')
																lowerCamelCase__				={} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
											if "use_cpu" not in config_dict:
																lowerCamelCase__				=False
											return cls(**_SCREAMING_SNAKE_CASE)






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




											"""simple docstring"""





											with open(_SCREAMING_SNAKE_CASE    ,						'w'    ,						encoding='utf-8') as f:
																lowerCamelCase__				=json.dumps(self.to_dict()    ,						indent=2    ,						sort_keys=_SCREAMING_SNAKE_CASE) + '\n'
																f.write(_SCREAMING_SNAKE_CASE)






						@classmethod
						def 		lowerCAmelCase   (					cls    ,						_SCREAMING_SNAKE_CASE=None)			->  List[str]:




											"""simple docstring"""





											lowerCamelCase__				=default_yaml_config_file if yaml_file is None else yaml_file
											with open(_SCREAMING_SNAKE_CASE    ,						'r'    ,						encoding='utf-8') as f:
																lowerCamelCase__				=yaml.safe_load(_SCREAMING_SNAKE_CASE)
											if "compute_environment" not in config_dict:
																lowerCamelCase__				=ComputeEnvironment.LOCAL_MACHINE

											if "mixed_precision" not in config_dict:
																lowerCamelCase__				='fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
											if isinstance(config_dict['mixed_precision']    ,						_SCREAMING_SNAKE_CASE) and not config_dict["mixed_precision"]:
																lowerCamelCase__				='no'
											if "fp16" in config_dict:  # Convert the config to the new format.
																del config_dict["fp16"]
											if "dynamo_backend" in config_dict:  # Convert the config to the new format.
																lowerCamelCase__				=config_dict.pop('dynamo_backend')
																lowerCamelCase__				={} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
											if "use_cpu" not in config_dict:
																lowerCamelCase__				=False
											return cls(**_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE)			->  Dict:




											"""simple docstring"""





											with open(_SCREAMING_SNAKE_CASE    ,						'w'    ,						encoding='utf-8') as f:
																yaml.safe_dump(self.to_dict()    ,						_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase   (					self)			->  List[str]:




											"""simple docstring"""





											if isinstance(self.compute_environment    ,						_SCREAMING_SNAKE_CASE):
																lowerCamelCase__				=ComputeEnvironment(self.compute_environment)
											if isinstance(self.distributed_type    ,						_SCREAMING_SNAKE_CASE):
																if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																					lowerCamelCase__				=SageMakerDistributedType(self.distributed_type)
																else:
																					lowerCamelCase__				=DistributedType(self.distributed_type)
											if self.dynamo_config is None:
																lowerCamelCase__				={}




@dataclass
class        __lowercase(       _UpperCamelCase  ):
						lowerCAmelCase_		:							int
						lowerCAmelCase_		:							int=       0
						lowerCAmelCase_		:							int=       1
						lowerCAmelCase_		:							Optional[str]=       None
						lowerCAmelCase_		:							Optional[str]=       None
						lowerCAmelCase_		:							Optional[int]=       None
						lowerCAmelCase_		:							Optional[str]=       "static"
						lowerCAmelCase_		:							Optional[bool]=       False
						lowerCAmelCase_		:							str=       "main"

						# args for deepspeed_plugin
						lowerCAmelCase_		:							dict=       None
						# args for fsdp
						lowerCAmelCase_		:							dict=       None
						# args for megatron_lm
						lowerCAmelCase_		:							dict=       None
						# args for ipex
						lowerCAmelCase_		:							dict=       None
						# args for TPU
						lowerCAmelCase_		:							bool=       False

						# args for TPU pods
						lowerCAmelCase_		:							str=       None
						lowerCAmelCase_		:							str=       None
						lowerCAmelCase_		:							bool=       False
						lowerCAmelCase_		:							bool=       False
						lowerCAmelCase_		:							str=       None
						lowerCAmelCase_		:							List[str]=       None
						lowerCAmelCase_		:							List[str]=       None
						lowerCAmelCase_		:							List[str]=       None

						# args for dynamo
						lowerCAmelCase_		:							dict=       None






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




											"""simple docstring"""





											if self.deepspeed_config is None:
																lowerCamelCase__				={}
											if self.fsdp_config is None:
																lowerCamelCase__				={}
											if self.megatron_lm_config is None:
																lowerCamelCase__				={}
											if self.ipex_config is None:
																lowerCamelCase__				={}
											return super().__post_init__()




@dataclass
class        __lowercase(       _UpperCamelCase  ):
						lowerCAmelCase_		:							str
						lowerCAmelCase_		:							str
						lowerCAmelCase_		:							Optional[str]=       None
						lowerCAmelCase_		:							Optional[str]=       None
						lowerCAmelCase_		:							str=       "us-east-1"
						lowerCAmelCase_		:							int=       1
						lowerCAmelCase_		:							str=       "all"
						lowerCAmelCase_		:							str=       f"""accelerate-sagemaker-{num_machines}"""
						lowerCAmelCase_		:							str=       SAGEMAKER_PYTORCH_VERSION
						lowerCAmelCase_		:							str=       SAGEMAKER_TRANSFORMERS_VERSION
						lowerCAmelCase_		:							str=       SAGEMAKER_PYTHON_VERSION
						lowerCAmelCase_		:							str=       None
						lowerCAmelCase_		:							str=       None
						lowerCAmelCase_		:							dict=       None
						lowerCAmelCase_		:							dict=       None







"""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


_snake_case       :      Union[str, Any]       =					logging.getLogger(__name__)




def 						lowerCamelCase_				(  __A  :		Any			):
					random.seed(__A			)
					np.random.seed(__A			)
					torch.manual_seed(__A			)
					torch.cuda.manual_seed_all(__A			)




def 						lowerCamelCase_				(  __A  :		str			,	__A  :		int			,	__A  :		Tuple			):
					model.eval()
					lowerCamelCase__				=next(model.parameters()			).device
					lowerCamelCase__				=1
					lowerCamelCase__				=torch.zeros((eval_batch_size, context_len)			,	dtype=torch.long			,	device=__A			)
					lowerCamelCase__				=DataLoader(__A			,	shuffle=__A			,	batch_size=__A			)
					lowerCamelCase__				=torch.zeros(1			,	device=__A			)
					lowerCamelCase__				=0
					for batch in eval_dataloader:
										batch.to(__A			)
										# pad
										context.zero_()
										for i in range(__A			):
															lowerCamelCase__				=batch[i]
										lowerCamelCase__				=model(__A			,	labels=__A			)
										eval_loss += outputs[0].sum().item()
										nb_eval_examples += batch.size(0			)
					lowerCamelCase__				=eval_loss / nb_eval_examples
					lowerCamelCase__				=torch.exp(__A			)
					model.train()
					return perplexity




def 						lowerCamelCase_				(  __A  :		List[str]="gpt2"			):
					lowerCamelCase__				=GPTaLMHeadModel.from_pretrained(__A			,	output_hidden_states=__A			)
					torch.save(model.state_dict()			,	model_name + 'local.pt'			)
					return model




def 						lowerCamelCase_				(  __A  :		Optional[Any]			,	__A  :		Tuple			,	__A  :		List[str]			):
					lowerCamelCase__				=copy.deepcopy(__A			)
					model.to(__A			)

					lowerCamelCase__				=['bias', 'LayerNorm.weight']
					lowerCamelCase__				=[
					    {
					        '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},
					]
					lowerCamelCase__				=AdamW(__A			,	lr=5E-5			,	eps=1E-8			)
					lowerCamelCase__				=get_linear_schedule_with_warmup(__A			,	0			,	__A			)
					torch.cuda.empty_cache()
					return model, lm_optimizer, lm_scheduler




def 						lowerCamelCase_				(  __A  :		Union[str, Any]			,	__A  :		Optional[int]			,	__A  :		str			,	__A  :		Tuple			):
					lowerCamelCase__				=np.array(__A			).mean()
					lowerCamelCase__				=np.array(__A			).std()
					lowerCamelCase__				=(real_perps - avg) / std
					lowerCamelCase__				=list(zip(__A			,	__A			,	__A			)			)
					joblib.dump(__A			,	__A			)




def 						lowerCamelCase_				(  __A  :		Optional[int]			,	__A  :		Union[str, Any]			,	__A  :		Any			,	__A  :		Optional[Any]			,	__A  :		Any			,	__A  :		Dict			,	__A  :		Any			,	__A  :		List[str]="dev.jbl"			,	__A  :		List[str]=recopy_gpta			,	):
					lowerCamelCase__				=[]
					lowerCamelCase__				=[]
					lowerCamelCase__				=[]

					# Initialize the transformer model
					lowerCamelCase__				=copy.deepcopy(__A			)
					orig_model.to(device='cpu'			)
					torch.cuda.empty_cache()

					# Compute perplexity of initial transformer model for comparison
					model.train()
					lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				=recopy_model(__A			,	__A			,	__A			)

					for step in tqdm(range(__A			)			):
										lowerCamelCase__				=torch.zeros((1, context_len)			,	dtype=torch.long			,	device=__A			)
										lowerCamelCase__				=random.choice(__A			)
										lowerCamelCase__				=random.randint(0			,	len(story[0]			) - context_len - 1			)
										lowerCamelCase__				=story[0][start : start + context_len]
										lm_optimizer.zero_grad()
										lowerCamelCase__				=model(__A			,	labels=__A			)
										lowerCamelCase__				=outputs[0]
										lowerCamelCase__				=compute_perplexity(__A			,	__A			,	__A			)
										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
										lowerCamelCase__				=compute_perplexity(__A			,	__A			,	__A			)

										# Periodically save the stored (X, IG(X)) pairs
										if step % 1000 == 0 and step > 1:
															intermittent_save(__A			,	__A			,	__A			,	__A			)

										# Reset the pretrained model to the original pretrained GPT-2 weights after each iteration
										lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				=recopy_model(__A			,	__A			,	__A			)

										past_perps.append(past_perp.item()			)
										real_perps.append(orig_perp - real_perp.item()			)
										contexts.append(np.array(context.cpu()			)			)

					intermittent_save(__A			,	__A			,	__A			,	__A			)




def 						lowerCamelCase_				(  __A  :		Optional[Any]			,	__A  :		Any="data/tokenized_stories_train_wikitext103.jbl"			,	__A  :		Any=100			,	__A  :		str=1026			,	__A  :		int=True			):
					lowerCamelCase__				=joblib.load(__A			)
					print('data loaded'			)
					lowerCamelCase__				=[]
					if trim:
										for i, example in enumerate(__A			):
															if len(example[0]			) > min_len:
																				lowerCamelCase__				=random.randint(0			,	len(example[0]			) - context_len - 1			)
																				objective_set.append(example[0, start : start + context_len]			)
															if len(__A			) >= number:
																				break
										lowerCamelCase__				=[]
										for j in range(i + 1			,	len(__A			)			):
															if len(data[j][0]			) > min_len:
																				train_data.append(data[j]			)
					else:
										lowerCamelCase__				=data[0:number]
										lowerCamelCase__				=data[number:]

					joblib.dump(__A			,	'objective_set.jbl'			)
					print('objective set saved'			)
					return train_data, objective_set




def 						lowerCamelCase_				(  __A  :		Optional[int]			,	__A  :		List[str]			,	__A  :		Optional[Any]			,	__A  :		str			,	__A  :		Optional[int]=50			,	__A  :		Optional[int]="secondary_learner.pt"			):
					lowerCamelCase__				=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
					lowerCamelCase__				=train_dataset[:512]
					lowerCamelCase__				=train_dataset[512:]
					lowerCamelCase__				=DataLoader(__A			,	shuffle=__A			,	batch_size=__A			)
					lowerCamelCase__				=DataLoader(__A			,	shuffle=__A			,	batch_size=__A			)

					# secondary learner model set up
					lowerCamelCase__				=nn.MSELoss()
					lowerCamelCase__				=nn.MSELoss(reduction='sum'			)
					secondary_learner.to(__A			)
					lowerCamelCase__				=torch.optim.Adam(secondary_learner.parameters()			,	lr=0.0_0_0_0_1			)
					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
					lowerCamelCase__				=float('inf'			)
					# Iterate through batches until we've used max_steps batches
					for epoch in range(int(__A			)			):
										lowerCamelCase__				=0.0
										secondary_learner.train()
										for step, batch in enumerate(__A			):
															lowerCamelCase__				=batch[0].to(__A			)
															lowerCamelCase__				=batch[1].to(__A			)
															lowerCamelCase__				=secondary_learner(__A			)
															q_optimizer.zero_grad()
															lowerCamelCase__				=loss(__A			,	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(__A			)):
																				lowerCamelCase__				=tr_q_loss / (step + 1)

																				secondary_learner.eval()
																				lowerCamelCase__				=0.0
																				lowerCamelCase__				=0.0
																				lowerCamelCase__				=[]
																				lowerCamelCase__				=[]
																				# Compute performance of the secondary learner after this batch
																				for stepa, batcha in enumerate(__A			):
																									lowerCamelCase__				=batcha[0].to(__A			)
																									lowerCamelCase__				=batcha[1].to(__A			)
																									lowerCamelCase__				=secondary_learner(__A			)
																									q_lossa += test_loss(__A			,	__A			).item()
																									sum_qa += torch.sum(__A			).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(__A			)
																				print(
																				    'Epoch: '			,	__A			,	'step: '			,	__A			,	'Avg. q:'			,	sum_qa / len(__A			)			,	'Train Loss: '			,	__A			,	'Test Loss: '			,	__A			,	)
																				if q_lossa < best_test_loss:
																									joblib.dump((predicted, actual)			,	'pred_vs_actual.jbl'			)
																									torch.save(secondary_learner.state_dict()			,	__A			)
																									lowerCamelCase__				=q_lossa

															secondary_learner.train()
					return secondary_learner




class        __lowercase(       nn.Module  ):






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




											"""simple docstring"""





											super(_SCREAMING_SNAKE_CASE    ,						self).__init__()
											lowerCamelCase__				=model.transformer.wte
											lowerCamelCase__				=copy.deepcopy(model.transformer.wte.weight)
											lowerCamelCase__				=nn.Convad(self.embeddings.weight.size(1)    ,						2_56    ,						3    ,						padding=1)
											lowerCamelCase__				=nn.Sequential(nn.Linear(2_56    ,						32)    ,						nn.Dropout(p=0.1)    ,						nn.Linear(32    ,						32)    ,						nn.Linear(32    ,						1))






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE)			->  Optional[int]:




											"""simple docstring"""





											lowerCamelCase__				=torch.max(self.conv(self.embeddings(_SCREAMING_SNAKE_CASE).squeeze(1).transpose(1    ,						2))    ,						2)[0]
											lowerCamelCase__				=self.fc(_SCREAMING_SNAKE_CASE)
											return qs.squeeze(1)






						@classmethod
						def 		lowerCAmelCase   (					cls    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  List[Any]:




											"""simple docstring"""





											lowerCamelCase__				=cls(_SCREAMING_SNAKE_CASE)  # this calls __init__
											lowerCamelCase__				=torch.load(_SCREAMING_SNAKE_CASE)
											secondary_learner.load_state_dict(_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=model.transformer.wte
											lowerCamelCase__				=copy.deepcopy(model.transformer.wte.weight)
											return secondary_learner