



'''simple docstring'''

import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
__lowerCAmelCase									=   logging.getLogger(__name__)



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_  )			->      Optional[Any]:
		_a     :      Union[str, Any]        =							np.argmax(lowerCAmelCase_						,			axis=1  )
		return np.sum(outputs == labels  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      List[Any]:
		with open(lowerCAmelCase_						,			encoding='utf_8'  ) as f:
				_a     :      Optional[Any]        =							csv.reader(lowerCAmelCase_  )
				_a     :      List[Any]        =							[]
				next(lowerCAmelCase_  )  # skip the first line
				for line in tqdm(lowerCAmelCase_  ):
						output.append((' '.join(line[1:5]  ), line[5], line[6], int(line[-1]  ) - 1)  )
		return output



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_  )			->      str:
		_a     :      Union[str, Any]        =							[]
		for dataset in encoded_datasets:
				_a     :      Any        =							len(lowerCAmelCase_  )
				_a     :      str        =							np.zeros((n_batch, 2, input_len)						,			dtype=np.intaa  )
				_a     :      Dict        =							np.zeros((n_batch, 2)						,			dtype=np.intaa  )
				_a     :      List[str]        =							np.full((n_batch, 2, input_len)						,			fill_value=-100						,			dtype=np.intaa  )
				_a     :      Any        =							np.zeros((n_batch,)						,			dtype=np.intaa  )
				for (
				    i,
				    (story, conta, conta, mc_label),
				) in enumerate(lowerCAmelCase_  ):
						_a     :      int        =							[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
						_a     :      List[Any]        =							[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
						_a     :      List[Any]        =							with_conta
						_a     :      Dict        =							with_conta
						_a     :      int        =							len(lowerCAmelCase_  ) - 1
						_a     :      Optional[int]        =							len(lowerCAmelCase_  ) - 1
						_a     :      str        =							with_conta
						_a     :      Any        =							with_conta
						_a     :      Union[str, Any]        =							mc_label
				_a     :      List[str]        =							(input_ids, mc_token_ids, lm_labels, mc_labels)
				tensor_datasets.append(tuple(torch.tensor(lowerCAmelCase_  ) for t in all_inputs  )  )
		return tensor_datasets



def      __lowerCamelCase     (      )			->      Any:
		_a     :      List[str]        =							argparse.ArgumentParser()
		parser.add_argument('--model_name'						,			type=lowerCAmelCase_						,			default='openai-gpt'						,			help='pretrained model name'  )
		parser.add_argument('--do_train'						,			action='store_true'						,			help='Whether to run training.'  )
		parser.add_argument('--do_eval'						,			action='store_true'						,			help='Whether to run eval on the dev set.'  )
		parser.add_argument(
		    '--output_dir'						,			default=lowerCAmelCase_						,			type=lowerCAmelCase_						,			required=lowerCAmelCase_						,			help='The output directory where the model predictions and checkpoints will be written.'						,			)
		parser.add_argument('--train_dataset'						,			type=lowerCAmelCase_						,			default=''  )
		parser.add_argument('--eval_dataset'						,			type=lowerCAmelCase_						,			default=''  )
		parser.add_argument('--seed'						,			type=lowerCAmelCase_						,			default=42  )
		parser.add_argument('--num_train_epochs'						,			type=lowerCAmelCase_						,			default=3  )
		parser.add_argument('--train_batch_size'						,			type=lowerCAmelCase_						,			default=8  )
		parser.add_argument('--eval_batch_size'						,			type=lowerCAmelCase_						,			default=16  )
		parser.add_argument('--adam_epsilon'						,			default=1E-8						,			type=lowerCAmelCase_						,			help='Epsilon for Adam optimizer.'  )
		parser.add_argument('--max_grad_norm'						,			type=lowerCAmelCase_						,			default=1  )
		parser.add_argument(
		    '--max_steps'						,			default=-1						,			type=lowerCAmelCase_						,			help=(
		        'If > 0: set total number of training                         steps to perform. Override num_train_epochs.'
		    )						,			)
		parser.add_argument(
		    '--gradient_accumulation_steps'						,			type=lowerCAmelCase_						,			default=1						,			help='Number of updates steps to accumulate before                        performing a backward/update pass.'						,			)
		parser.add_argument('--learning_rate'						,			type=lowerCAmelCase_						,			default=6.25E-5  )
		parser.add_argument('--warmup_steps'						,			default=0						,			type=lowerCAmelCase_						,			help='Linear warmup over warmup_steps.'  )
		parser.add_argument('--lr_schedule'						,			type=lowerCAmelCase_						,			default='warmup_linear'  )
		parser.add_argument('--weight_decay'						,			type=lowerCAmelCase_						,			default=0.01  )
		parser.add_argument('--lm_coef'						,			type=lowerCAmelCase_						,			default=0.9  )
		parser.add_argument('--n_valid'						,			type=lowerCAmelCase_						,			default=374  )

		parser.add_argument('--server_ip'						,			type=lowerCAmelCase_						,			default=''						,			help='Can be used for distant debugging.'  )
		parser.add_argument('--server_port'						,			type=lowerCAmelCase_						,			default=''						,			help='Can be used for distant debugging.'  )
		_a     :      str        =							parser.parse_args()
		print(lowerCAmelCase_  )

		if args.server_ip and args.server_port:
				# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
				import ptvsd

				print('Waiting for debugger attach'  )
				ptvsd.enable_attach(address=(args.server_ip, args.server_port)						,			redirect_output=lowerCAmelCase_  )
				ptvsd.wait_for_attach()

		random.seed(args.seed  )
		np.random.seed(args.seed  )
		torch.manual_seed(args.seed  )
		torch.cuda.manual_seed_all(args.seed  )

		_a     :      List[Any]        =							torch.device('cuda' if torch.cuda.is_available() else 'cpu'  )
		_a     :      Dict        =							torch.cuda.device_count()
		logger.info('device: {}, n_gpu {}'.format(lowerCAmelCase_						,			lowerCAmelCase_  )  )

		if not args.do_train and not args.do_eval:
				raise ValueError('At least one of `do_train` or `do_eval` must be True.'  )

		if not os.path.exists(args.output_dir  ):
				os.makedirs(args.output_dir  )

		# Load tokenizer and model
		# This loading functions also add new tokens and embeddings called `special tokens`
		# These new embeddings will be fine-tuned on the RocStories dataset
		_a     :      List[Any]        =							['_start_', '_delimiter_', '_classify_']
		_a     :      Union[str, Any]        =							OpenAIGPTTokenizer.from_pretrained(args.model_name  )
		tokenizer.add_tokens(lowerCAmelCase_  )
		_a     :      Union[str, Any]        =							tokenizer.convert_tokens_to_ids(lowerCAmelCase_  )
		_a     :      Dict        =							OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name  )
		model.resize_token_embeddings(len(lowerCAmelCase_  )  )
		model.to(lowerCAmelCase_  )

		# Load and encode the datasets
		def tokenize_and_encode(lowerCAmelCase_  ):
				if isinstance(lowerCAmelCase_						,			lowerCAmelCase_  ):
						return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(lowerCAmelCase_  )  )
				elif isinstance(lowerCAmelCase_						,			lowerCAmelCase_  ):
						return obj
				return [tokenize_and_encode(lowerCAmelCase_  ) for o in obj]

		logger.info('Encoding dataset...'  )
		_a     :      str        =							load_rocstories_dataset(args.train_dataset  )
		_a     :      Dict        =							load_rocstories_dataset(args.eval_dataset  )
		_a     :      List[Any]        =							(train_dataset, eval_dataset)
		_a     :      Dict        =							tokenize_and_encode(lowerCAmelCase_  )

		# Compute the max input length for the Transformer
		_a     :      Optional[Any]        =							model.config.n_positions // 2 - 2
		_a     :      List[Any]        =							max(
		    len(story[:max_length]  ) + max(len(conta[:max_length]  )						,			len(conta[:max_length]  )  ) + 3
		    for dataset in encoded_datasets
		    for story, conta, conta, _ in dataset  )
		_a     :      str        =							min(lowerCAmelCase_						,			model.config.n_positions  )  # Max size of input for the pre-trained model

		# Prepare inputs tensors and dataloaders
		_a     :      Any        =							pre_process_datasets(lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			*lowerCAmelCase_  )
		_a       ,					_a     :      List[Any]        =							tensor_datasets[0], tensor_datasets[1]

		_a     :      str        =							TensorDataset(*lowerCAmelCase_  )
		_a     :      Tuple        =							RandomSampler(lowerCAmelCase_  )
		_a     :      Union[str, Any]        =							DataLoader(lowerCAmelCase_						,			sampler=lowerCAmelCase_						,			batch_size=args.train_batch_size  )

		_a     :      Dict        =							TensorDataset(*lowerCAmelCase_  )
		_a     :      List[str]        =							SequentialSampler(lowerCAmelCase_  )
		_a     :      Union[str, Any]        =							DataLoader(lowerCAmelCase_						,			sampler=lowerCAmelCase_						,			batch_size=args.eval_batch_size  )

		# Prepare optimizer
		if args.do_train:
				if args.max_steps > 0:
						_a     :      Dict        =							args.max_steps
						_a     :      str        =							args.max_steps // (len(lowerCAmelCase_  ) // args.gradient_accumulation_steps) + 1
				else:
						_a     :      Optional[Any]        =							len(lowerCAmelCase_  ) // args.gradient_accumulation_steps * args.num_train_epochs

				_a     :      int        =							list(model.named_parameters()  )
				_a     :      Optional[int]        =							['bias', 'LayerNorm.bias', 'LayerNorm.weight']
				_a     :      List[Any]        =							[
				    {
				        'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay  )],
				        'weight_decay': args.weight_decay,
				    },
				    {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay  )], 'weight_decay': 0.0},
				]
				_a     :      int        =							AdamW(lowerCAmelCase_						,			lr=args.learning_rate						,			eps=args.adam_epsilon  )
				_a     :      Optional[Any]        =							get_linear_schedule_with_warmup(
				    lowerCAmelCase_						,			num_warmup_steps=args.warmup_steps						,			num_training_steps=lowerCAmelCase_  )

		if args.do_train:
				_a       ,					_a       ,					_a     :      Union[str, Any]        =							0, 0, None
				model.train()
				for _ in trange(int(args.num_train_epochs  )						,			desc='Epoch'  ):
						_a     :      int        =							0
						_a     :      Union[str, Any]        =							0
						_a     :      Union[str, Any]        =							tqdm(lowerCAmelCase_						,			desc='Training'  )
						for step, batch in enumerate(lowerCAmelCase_  ):
								_a     :      Tuple        =							tuple(t.to(lowerCAmelCase_  ) for t in batch  )
								_a       ,					_a       ,					_a       ,					_a     :      Dict        =							batch
								_a     :      int        =							model(lowerCAmelCase_						,			mc_token_ids=lowerCAmelCase_						,			lm_labels=lowerCAmelCase_						,			mc_labels=lowerCAmelCase_  )
								_a     :      List[str]        =							args.lm_coef * losses[0] + losses[1]
								loss.backward()
								optimizer.step()
								scheduler.step()
								optimizer.zero_grad()
								tr_loss += loss.item()
								_a     :      Union[str, Any]        =							(
								    loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
								)
								nb_tr_steps += 1
								_a     :      str        =							'Training loss: {:.2e} lr: {:.2e}'.format(lowerCAmelCase_						,			scheduler.get_lr()[0]  )

    # Save a trained model
		if args.do_train:
				# Save a trained model, configuration and tokenizer
				_a     :      Any        =							model.module if hasattr(lowerCAmelCase_						,			'module'  ) else model  # Only save the model itself

				# If we save using the predefined names, we can load using `from_pretrained`
				_a     :      Optional[int]        =							os.path.join(args.output_dir						,			lowerCAmelCase_  )
				_a     :      Any        =							os.path.join(args.output_dir						,			lowerCAmelCase_  )

				torch.save(model_to_save.state_dict()						,			lowerCAmelCase_  )
				model_to_save.config.to_json_file(lowerCAmelCase_  )
				tokenizer.save_vocabulary(args.output_dir  )

				# Load a trained model and vocabulary that you have fine-tuned
				_a     :      int        =							OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir  )
				_a     :      List[Any]        =							OpenAIGPTTokenizer.from_pretrained(args.output_dir  )
				model.to(lowerCAmelCase_  )

		if args.do_eval:
				model.eval()
				_a       ,					_a     :      Dict        =							0, 0
				_a       ,					_a     :      Union[str, Any]        =							0, 0
				for batch in tqdm(lowerCAmelCase_						,			desc='Evaluating'  ):
						_a     :      List[Any]        =							tuple(t.to(lowerCAmelCase_  ) for t in batch  )
						_a       ,					_a       ,					_a       ,					_a     :      str        =							batch
						with torch.no_grad():
								_a       ,					_a       ,					_a       ,					_a     :      Dict        =							model(
								    lowerCAmelCase_						,			mc_token_ids=lowerCAmelCase_						,			lm_labels=lowerCAmelCase_						,			mc_labels=lowerCAmelCase_  )

						_a     :      Tuple        =							mc_logits.detach().cpu().numpy()
						_a     :      List[Any]        =							mc_labels.to('cpu'  ).numpy()
						_a     :      Optional[Any]        =							accuracy(lowerCAmelCase_						,			lowerCAmelCase_  )

						eval_loss += mc_loss.mean().item()
						eval_accuracy += tmp_eval_accuracy

						nb_eval_examples += input_ids.size(0  )
						nb_eval_steps += 1

				_a     :      Union[str, Any]        =							eval_loss / nb_eval_steps
				_a     :      Tuple        =							eval_accuracy / nb_eval_examples
				_a     :      int        =							tr_loss / nb_tr_steps if args.do_train else None
				_a     :      Dict        =							{'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

				_a     :      str        =							os.path.join(args.output_dir						,			'eval_results.txt'  )
				with open(lowerCAmelCase_						,			'w'  ) as writer:
						logger.info('***** Eval results *****'  )
						for key in sorted(result.keys()  ):
								logger.info('  %s = %s'						,			lowerCAmelCase_						,			str(result[key]  )  )
								writer.write('%s = %s\n' % (key, str(result[key]  ))  )


if __name__ == "__main__":
							main()









'''simple docstring'''

import multiprocessing
from typing import TYPE_CHECKING, Optional, Union

from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream


if TYPE_CHECKING:
							import sqlitea

							import sqlalchemy

class 	__magic_name__						(    _UpperCamelCase   ):







							def __init__(							self					:       Optional[int]	,_UpperCAmelCase					:       Union[str, "sqlalchemy.sql.Selectable"]	,_UpperCAmelCase					:       Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]	,_UpperCAmelCase					:       Optional[Features] = None	,_UpperCAmelCase					:       str = None	,_UpperCAmelCase					:       bool = False	,**_UpperCAmelCase					:       Dict	,):
									super().__init__(features=_UpperCAmelCase	,cache_dir=_UpperCAmelCase	,keep_in_memory=_UpperCAmelCase	,**_UpperCAmelCase		)
									_a     :      Tuple        =							Sql(
									    cache_dir=_UpperCAmelCase	,features=_UpperCAmelCase	,sql=_UpperCAmelCase	,con=_UpperCAmelCase	,**_UpperCAmelCase	,)







							def 							__lowercase			(							self					:       Dict		):
									_a     :      Optional[Any]        =							None
									_a     :      Dict        =							None
									_a     :      Dict        =							None
									_a     :      Optional[int]        =							None

									self.builder.download_and_prepare(
									    download_config=_UpperCAmelCase	,download_mode=_UpperCAmelCase	,verification_mode=_UpperCAmelCase	,base_path=_UpperCAmelCase	,)

									# Build dataset for splits
									_a     :      List[str]        =							self.builder.as_dataset(
									    split='train'	,verification_mode=_UpperCAmelCase	,in_memory=self.keep_in_memory		)
									return dataset

class 	__magic_name__						:







							def __init__(							self					:       Optional[int]	,_UpperCAmelCase					:       Dataset	,_UpperCAmelCase					:       str	,_UpperCAmelCase					:       Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]	,_UpperCAmelCase					:       Optional[int] = None	,_UpperCAmelCase					:       Optional[int] = None	,**_UpperCAmelCase					:       Dict	,):
									if num_proc is not None and num_proc <= 0:
											raise ValueError(F"""num_proc {num_proc} must be an integer > 0."""		)

									_a     :      Dict        =							dataset
									_a     :      List[Any]        =							name
									_a     :      Tuple        =							con
									_a     :      Union[str, Any]        =							batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
									_a     :      List[Any]        =							num_proc
									_a     :      Tuple        =							to_sql_kwargs







							def 							__lowercase			(							self					:       List[Any]		):
									_a     :      Tuple        =							self.to_sql_kwargs.pop('sql'	,_UpperCAmelCase		)
									_a     :      str        =							self.to_sql_kwargs.pop('con'	,_UpperCAmelCase		)
									_a     :      Optional[Any]        =							self.to_sql_kwargs.pop('index'	,_UpperCAmelCase		)

									_a     :      Any        =							self._write(index=_UpperCAmelCase	,**self.to_sql_kwargs		)
									return written







							def 							__lowercase			(							self					:       Optional[int]	,_UpperCAmelCase					:       Dict		):
									_a       ,					_a       ,					_a     :      Any        =							args
									_a     :      Tuple        =							{**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs
									_a     :      Dict        =							query_table(
									    table=self.dataset.data	,key=slice(_UpperCAmelCase	,offset + self.batch_size		)	,indices=self.dataset._indices	,)
									_a     :      Tuple        =							batch.to_pandas()
									_a     :      Dict        =							df.to_sql(self.name	,self.con	,index=_UpperCAmelCase	,**_UpperCAmelCase		)
									return num_rows or len(_UpperCAmelCase		)







							def 							__lowercase			(							self					:       int	,_UpperCAmelCase					:       Optional[int]	,**_UpperCAmelCase					:       List[Any]		):
									_a     :      Union[str, Any]        =							0

									if self.num_proc is None or self.num_proc == 1:
											for offset in logging.tqdm(
											    range(0	,len(self.dataset		)	,self.batch_size		)	,unit='ba'	,disable=not logging.is_progress_bar_enabled()	,desc='Creating SQL from Arrow format'	,):
													written += self._batch_sql((offset, index, to_sql_kwargs)		)
									else:
											_a       ,					_a     :      List[Any]        =							len(self.dataset		), self.batch_size
											with multiprocessing.Pool(self.num_proc		) as pool:
													for num_rows in logging.tqdm(
													    pool.imap(
													        self._batch_sql	,[(offset, index, to_sql_kwargs) for offset in range(0	,_UpperCAmelCase	,_UpperCAmelCase		)]	,)	,total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size	,unit='ba'	,disable=not logging.is_progress_bar_enabled()	,desc='Creating SQL from Arrow format'	,):
															written += num_rows

									return written




