


'''simple docstring'''
import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


__snake_case											=					'''\

'''

__snake_case											=					'''
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
'''

__snake_case											=					'''
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to \'cuda\' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        78.22
        >>> print(round(results["perplexities"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = datasets.load_dataset("wikitext",
        ...                                     "wikitext-2-raw-v1",
        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!=\'\']
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        60.35
        >>> print(round(results["perplexities"][0], 2))
        81.12
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,		_KWARGS_DESCRIPTION )
class        lowercase     (							datasets.Metric ):

		"""simple docstring"""

		def    lowerCAmelCase__    (		self							):

							'''simple docstring'''


							return datasets.MetricInfo(
							    description=_DESCRIPTION   ,       citation=_CITATION   ,       inputs_description=_KWARGS_DESCRIPTION   ,       features=datasets.Features(
							        {
							            '''input_texts''': datasets.Value('''string'''							),
							        }							)   ,       reference_urls=['''https://huggingface.co/docs/transformers/perplexity''']   ,       )




		def    lowerCAmelCase__    (		self   ,       UpperCamelCase_   ,       UpperCamelCase_   ,       UpperCamelCase_ = 16   ,       UpperCamelCase_ = True   ,       UpperCamelCase_=None							):

							'''simple docstring'''


							if device is not None:
												assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
												if device == "gpu":
																	UpperCamelCase__       :List[Any]							 =			'''cuda'''
							else:
												UpperCamelCase__       :List[str]							 =			'''cuda''' if torch.cuda.is_available() else '''cpu'''

							UpperCamelCase__       :str							 =			AutoModelForCausalLM.from_pretrained(UpperCamelCase_							)
							UpperCamelCase__       :Optional[int]							 =			model.to(UpperCamelCase_							)

							UpperCamelCase__       :Optional[Any]							 =			AutoTokenizer.from_pretrained(UpperCamelCase_							)

							# if batch_size > 1 (which generally leads to padding being required), and
							# if there is not an already assigned pad_token, assign an existing
							# special token to also be the padding token
							if tokenizer.pad_token is None and batch_size > 1:
												UpperCamelCase__       :List[str]							 =			list(tokenizer.special_tokens_map_extended.values()							)
												# check that the model already has at least one special token defined
												assert (
												    len(UpperCamelCase_							) > 0
												), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
												# assign one of the special tokens to also be the pad token
												tokenizer.add_special_tokens({'''pad_token''': existing_special_tokens[0]}							)

							if add_start_token:
												# leave room for <BOS> token to be added:
												assert (
												    tokenizer.bos_token is not None
												), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
												UpperCamelCase__       :Dict							 =			model.config.max_length - 1
							else:
												UpperCamelCase__       :Union[str, Any]							 =			model.config.max_length

							UpperCamelCase__       :List[Any]							 =			tokenizer(
							    UpperCamelCase_   ,       add_special_tokens=UpperCamelCase_   ,       padding=UpperCamelCase_   ,       truncation=UpperCamelCase_   ,       max_length=UpperCamelCase_   ,       return_tensors='''pt'''   ,       return_attention_mask=UpperCamelCase_   ,       ).to(UpperCamelCase_							)

							UpperCamelCase__       :List[str]							 =			encodings['''input_ids''']
							UpperCamelCase__       :str							 =			encodings['''attention_mask''']

							# check that each input is long enough:
							if add_start_token:
												assert torch.all(torch.ge(attn_masks.sum(1							)   ,       1							)							), "Each input text must be at least one token long."
							else:
												assert torch.all(
												    torch.ge(attn_masks.sum(1							)   ,       2							)							), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

							UpperCamelCase__       :Optional[int]							 =			[]
							UpperCamelCase__       :Optional[Any]							 =			CrossEntropyLoss(reduction='''none'''							)

							for start_index in logging.tqdm(range(0   ,       len(UpperCamelCase_							)   ,       UpperCamelCase_							)							):
												UpperCamelCase__       :Optional[int]							 =			min(start_index + batch_size   ,       len(UpperCamelCase_							)							)
												UpperCamelCase__       :str							 =			encoded_texts[start_index:end_index]
												UpperCamelCase__       :str							 =			attn_masks[start_index:end_index]

												if add_start_token:
																	UpperCamelCase__       :Optional[Any]							 =			torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0							)							).to(UpperCamelCase_							)
																	UpperCamelCase__       :List[Any]							 =			torch.cat([bos_tokens_tensor, encoded_batch]   ,       dim=1							)
																	UpperCamelCase__       :Dict							 =			torch.cat(
																	    [torch.ones(bos_tokens_tensor.size()   ,       dtype=torch.intaa							).to(UpperCamelCase_							), attn_mask]   ,       dim=1							)

												UpperCamelCase__       :Optional[Any]							 =			encoded_batch

												with torch.no_grad():
																	UpperCamelCase__       :str							 =			model(UpperCamelCase_   ,       attention_mask=UpperCamelCase_							).logits

												UpperCamelCase__       :Any							 =			out_logits[..., :-1, :].contiguous()
												UpperCamelCase__       :List[Any]							 =			labels[..., 1:].contiguous()
												UpperCamelCase__       :List[str]							 =			attn_mask[..., 1:].contiguous()

												UpperCamelCase__       :Any							 =			torch.expa(
												    (loss_fct(shift_logits.transpose(1   ,       2							)   ,       UpperCamelCase_							) * shift_attention_mask_batch).sum(1							)
												    / shift_attention_mask_batch.sum(1							)							)

												ppls += perplexity_batch.tolist()

							return {"perplexities": ppls, "mean_perplexity": np.mean(UpperCamelCase_							)}



'''simple docstring'''
import argparse
import json
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler


__snake_case											=					16
__snake_case											=					32


def       a				(      __a			, __a = 16			, __a = "bert-base-cased"       )  ->     Any:



					'''simple docstring'''






					UpperCamelCase__       :List[str]							 =			AutoTokenizer.from_pretrained(__a       )
					UpperCamelCase__       :List[Any]							 =			load_dataset('''glue'''			, '''mrpc'''       )

					def tokenize_function(__a       ):
										# max_length=None => use the model max length (it's actually the default)
										UpperCamelCase__       :Tuple							 =			tokenizer(examples['''sentence1''']			, examples['''sentence2''']			, truncation=__a			, max_length=__a       )
										return outputs

					# Apply the method we just defined to all the examples in all the splits of the dataset
					UpperCamelCase__       :Optional[int]							 =			datasets.map(
					    __a			, batched=__a			, remove_columns=['''idx''', '''sentence1''', '''sentence2''']			, load_from_cache_file=__a       )

					# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
					# transformers library
					UpperCamelCase__       :Optional[int]							 =			tokenized_datasets.rename_column('''label'''			, '''labels'''       )

					def collate_fn(__a       ):
										# On TPU it's best to pad everything to the same length or training will be very slow.
										if accelerator.distributed_type == DistributedType.TPU:
															return tokenizer.pad(__a			, padding='''max_length'''			, max_length=128			, return_tensors='''pt'''       )
										return tokenizer.pad(__a			, padding='''longest'''			, return_tensors='''pt'''       )

					# Instantiate dataloaders.
					UpperCamelCase__       :Dict							 =			DataLoader(
					    tokenized_datasets['''train''']			, shuffle=__a			, collate_fn=__a			, batch_size=__a       )
					UpperCamelCase__       :str							 =			DataLoader(
					    tokenized_datasets['''validation''']			, shuffle=__a			, collate_fn=__a			, batch_size=__a       )

					return train_dataloader, eval_dataloader


def       a				(      __a			, __a			, __a			, __a       )  ->     str:



					'''simple docstring'''






					model.eval()
					UpperCamelCase__       :List[str]							 =			0
					for step, batch in enumerate(__a       ):
										# We could avoid this line since we set the accelerator with `device_placement=True`.
										batch.to(accelerator.device       )
										with torch.no_grad():
															UpperCamelCase__       :int							 =			model(**__a       )
										UpperCamelCase__       :Tuple							 =			outputs.logits.argmax(dim=-1       )
										# It is slightly faster to call this once, than multiple times
										UpperCamelCase__ ,    UpperCamelCase__       :int							 =			accelerator.gather(
										    (predictions, batch['''labels'''])       )  # If we are in a multiprocess environment, the last batch has duplicates
										if accelerator.use_distributed:
															if step == len(__a       ) - 1:
																				UpperCamelCase__       :Union[str, Any]							 =			predictions[: len(eval_dataloader.dataset       ) - samples_seen]
																				UpperCamelCase__       :List[str]							 =			references[: len(eval_dataloader.dataset       ) - samples_seen]
															else:
																				samples_seen += references.shape[0]
										metric.add_batch(
										    predictions=__a			, references=__a			, )

					UpperCamelCase__       :Union[str, Any]							 =			metric.compute()
					return eval_metric["accuracy"]


def       a				(      __a			, __a       )  ->     List[Any]:



					'''simple docstring'''






					UpperCamelCase__       :Any							 =			Accelerator()

					# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
					UpperCamelCase__       :Any							 =			config['''lr''']
					UpperCamelCase__       :Optional[int]							 =			int(config['''num_epochs''']       )
					UpperCamelCase__       :List[Any]							 =			int(config['''seed''']       )
					UpperCamelCase__       :List[Any]							 =			int(config['''batch_size''']       )
					UpperCamelCase__       :List[Any]							 =			args.model_name_or_path

					set_seed(__a       )
					UpperCamelCase__ ,    UpperCamelCase__       :Any							 =			get_dataloaders(__a			, __a			, __a       )

					# Instantiate the model (we build the model here so that the seed also control new weights initialization)
					UpperCamelCase__       :Union[str, Any]							 =			AutoModelForSequenceClassification.from_pretrained(__a			, return_dict=__a       )

					# Instantiate optimizer
					UpperCamelCase__       :Any							 =			(
					    AdamW
					    if accelerator.state.deepspeed_plugin is None
					    or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config
					    else DummyOptim
					)
					UpperCamelCase__       :Optional[Any]							 =			optimizer_cls(params=model.parameters()			, lr=__a       )

					if accelerator.state.deepspeed_plugin is not None:
										UpperCamelCase__       :Tuple							 =			accelerator.state.deepspeed_plugin.deepspeed_config[
										    '''gradient_accumulation_steps'''
										]
					else:
										UpperCamelCase__       :Dict							 =			1
					UpperCamelCase__       :Tuple							 =			(len(__a       ) * num_epochs) // gradient_accumulation_steps

					# Instantiate scheduler
					if (
					    accelerator.state.deepspeed_plugin is None
					    or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
					):
										UpperCamelCase__       :Any							 =			get_linear_schedule_with_warmup(
										    optimizer=__a			, num_warmup_steps=0			, num_training_steps=__a			, )
					else:
										UpperCamelCase__       :Any							 =			DummyScheduler(__a			, total_num_steps=__a			, warmup_num_steps=0       )

					# Prepare everything
					# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
					# prepare method.
					UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       :Dict							 =			accelerator.prepare(
					    __a			, __a			, __a			, __a			, __a       )

					# We need to keep track of how many total steps we have iterated over
					UpperCamelCase__       :Tuple							 =			0
					# We also need to keep track of the stating epoch so files are named properly
					UpperCamelCase__       :Optional[Any]							 =			0
					UpperCamelCase__       :Optional[int]							 =			evaluate.load('''glue'''			, '''mrpc'''       )
					UpperCamelCase__       :List[Any]							 =			num_epochs

					if args.partial_train_epoch is not None:
										UpperCamelCase__       :Optional[Any]							 =			args.partial_train_epoch

					if args.resume_from_checkpoint:
										accelerator.load_state(args.resume_from_checkpoint       )
										UpperCamelCase__       :Dict							 =			args.resume_from_checkpoint.split('''epoch_'''       )[1]
										UpperCamelCase__       :Tuple							 =			''''''
										for char in epoch_string:
															if char.isdigit():
																				state_epoch_num += char
															else:
																				break
										UpperCamelCase__       :Any							 =			int(__a       ) + 1
										UpperCamelCase__       :Dict							 =			evaluation_loop(__a			, __a			, __a			, __a       )
										accelerator.print('''resumed checkpoint performance:'''			, __a       )
										accelerator.print('''resumed checkpoint\'s scheduler\'s lr:'''			, lr_scheduler.get_lr()[0]       )
										accelerator.print('''resumed optimizers\'s lr:'''			, optimizer.param_groups[0]['''lr''']       )
										with open(os.path.join(args.output_dir			, f'''state_{starting_epoch-1}.json'''       )			, '''r'''       ) as f:
															UpperCamelCase__       :Optional[int]							 =			json.load(__a       )
															assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed"
															assert (
															    resumed_state["lr"] == lr_scheduler.get_lr()[0]
															), "Scheduler learning rate mismatch, loading from checkpoint failed"
															assert (
															    resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"]
															), "Optimizer learning rate mismatch, loading from checkpoint failed"
															assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed"
															return

    # Now we train the model
					UpperCamelCase__       :Optional[Any]							 =			{}
					for epoch in range(__a			, __a       ):
										model.train()
										for step, batch in enumerate(__a       ):
															UpperCamelCase__       :Optional[int]							 =			model(**__a       )
															UpperCamelCase__       :Optional[int]							 =			outputs.loss
															UpperCamelCase__       :str							 =			loss / gradient_accumulation_steps
															accelerator.backward(__a       )
															if step % gradient_accumulation_steps == 0:
																				optimizer.step()
																				lr_scheduler.step()
																				optimizer.zero_grad()

															overall_step += 1
										UpperCamelCase__       :Union[str, Any]							 =			f'''epoch_{epoch}'''
										UpperCamelCase__       :List[Any]							 =			os.path.join(args.output_dir			, __a       )
										accelerator.save_state(__a       )
										UpperCamelCase__       :List[Any]							 =			evaluation_loop(__a			, __a			, __a			, __a       )
										UpperCamelCase__       :int							 =			accuracy
										UpperCamelCase__       :List[Any]							 =			lr_scheduler.get_lr()[0]
										UpperCamelCase__       :Any							 =			optimizer.param_groups[0]['''lr''']
										UpperCamelCase__       :int							 =			epoch
										UpperCamelCase__       :Tuple							 =			overall_step
										accelerator.print(f'''epoch {epoch}:'''			, __a       )

										accelerator.wait_for_everyone()
										if accelerator.is_main_process:
															with open(os.path.join(args.output_dir			, f'''state_{epoch}.json'''       )			, '''w'''       ) as f:
																				json.dump(__a			, __a       )


def       a				(      )  ->     Tuple:



					'''simple docstring'''






					UpperCamelCase__       :List[Any]							 =			argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.'''       )
					parser.add_argument(
					    '''--model_name_or_path'''			, type=__a			, default='''bert-base-cased'''			, help='''Path to pretrained model or model identifier from huggingface.co/models.'''			, required=__a			, )
					parser.add_argument(
					    '''--output_dir'''			, type=__a			, default='''.'''			, help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.'''			, )
					parser.add_argument(
					    '''--resume_from_checkpoint'''			, type=__a			, default=__a			, help='''If the training should continue from a checkpoint folder.'''			, )
					parser.add_argument(
					    '''--partial_train_epoch'''			, type=__a			, default=__a			, help='''If passed, the training will stop after this number of epochs.'''			, )
					parser.add_argument(
					    '''--num_epochs'''			, type=__a			, default=2			, help='''Number of train epochs.'''			, )
					UpperCamelCase__       :Optional[int]							 =			parser.parse_args()
					UpperCamelCase__       :List[str]							 =			{'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16}

					training_function(__a			, __a       )


if __name__ == "__main__":
		main()