


'''simple docstring'''
import argparse
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.local_sgd import LocalSGD


########################################################################
# This is a fully working simple example to use Accelerate
# with LocalSGD, which is a method to synchronize model
# parameters every K batches. It is different, but complementary
# to gradient accumulation.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


UpperCAmelCase_ :     Dict								=      1_6
UpperCAmelCase_ :     Dict								=      3_2


def 			_lowercase       (				UpperCamelCase__       :					Accelerator,				UpperCamelCase__       :					int = 16			):
 __A  :		Any       =			AutoTokenizer.from_pretrained('bert-base-cased'			)
 __A  :		Optional[int]       =			load_dataset('glue',				'mrpc'			)

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

 # Apply the method we just defined to all the examples in all the splits of the dataset
 # starting with the main process first:
 with accelerator.main_process_first():
  __A  :		List[Any]       =			datasets.map(
      UpperCamelCase__,				batched=UpperCamelCase__,				remove_columns=['idx', 'sentence1', 'sentence2'],				)

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

 def collate_fn(UpperCamelCase__       :					Any			):
  # On TPU it's best to pad everything to the same length or training will be very slow.
  __A  :		Tuple       =			128 if accelerator.distributed_type == DistributedType.TPU else None
  # When using mixed precision we want round multiples of 8/16
  if accelerator.mixed_precision == "fp8":
   __A  :		List[Any]       =			16
  elif accelerator.mixed_precision != "no":
   __A  :		Dict       =			8
  else:
   __A  :		Any       =			None

  return tokenizer.pad(
      UpperCamelCase__,				padding='longest',				max_length=UpperCamelCase__,				pad_to_multiple_of=UpperCamelCase__,				return_tensors='pt',				)

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

 return train_dataloader, eval_dataloader


# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
 from accelerate.test_utils.training import mocked_dataloaders

 UpperCAmelCase_ :     Optional[Any]								=      mocked_dataloaders  # noqa: F811


def 			_lowercase       (				UpperCamelCase__       :					Any,				UpperCamelCase__       :					Optional[int]			):
 # For testing only
 if os.environ.get('TESTING_MOCKED_DATALOADERS',				UpperCamelCase__			) == "1":
  __A  :		Union[str, Any]       =			2
 # New Code #
 __A  :		Union[str, Any]       =			int(args.gradient_accumulation_steps			)
 __A  :		str       =			int(args.local_sgd_steps			)
 # Initialize accelerator
 __A  :		Tuple       =			Accelerator(
     cpu=args.cpu,				mixed_precision=args.mixed_precision,				gradient_accumulation_steps=UpperCamelCase__			)
 if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]:
  raise NotImplementedError('LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)'			)
 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
 __A  :		Dict       =			config['lr']
 __A  :		int       =			int(config['num_epochs']			)
 __A  :		List[Any]       =			int(config['seed']			)
 __A  :		str       =			int(config['batch_size']			)

 __A  :		Any       =			evaluate.load('glue',				'mrpc'			)

 set_seed(UpperCamelCase__			)
 __A     ,__A  :		Tuple       =			get_dataloaders(UpperCamelCase__,				UpperCamelCase__			)
 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
 __A  :		Optional[Any]       =			AutoModelForSequenceClassification.from_pretrained('bert-base-cased',				return_dict=UpperCamelCase__			)

 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
 __A  :		str       =			model.to(accelerator.device			)

 # Instantiate optimizer
 __A  :		Union[str, Any]       =			AdamW(params=model.parameters(),				lr=UpperCamelCase__			)

 # Instantiate scheduler
 __A  :		List[Any]       =			get_linear_schedule_with_warmup(
     optimizer=UpperCamelCase__,				num_warmup_steps=100,				num_training_steps=(len(UpperCamelCase__			) * num_epochs),				)

 # 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.
 __A     ,__A     ,__A     ,__A     ,__A  :		Optional[int]       =			accelerator.prepare(
     UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)

 # Now we train the model
 for epoch in range(UpperCamelCase__			):
  model.train()
  with LocalSGD(
      accelerator=UpperCamelCase__,				model=UpperCamelCase__,				local_sgd_steps=UpperCamelCase__,				enabled=local_sgd_steps is not None			) as local_sgd:
   for step, batch in enumerate(UpperCamelCase__			):
    # We could avoid this line since we set the accelerator with `device_placement=True`.
    batch.to(accelerator.device			)
    # New code #
    # We use the new `accumulate` context manager to perform gradient accumulation
    # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
    with accelerator.accumulate(UpperCamelCase__			):
     __A  :		List[Any]       =			model(**UpperCamelCase__			)
     __A  :		Optional[Any]       =			output.loss
     accelerator.backward(UpperCamelCase__			)
     optimizer.step()
     lr_scheduler.step()
     optimizer.zero_grad()
     # LocalSGD-specific line
     local_sgd.step()

  model.eval()
  for step, batch in enumerate(UpperCamelCase__			):
   # We could avoid this line since we set the accelerator with `device_placement=True`.
   batch.to(accelerator.device			)
   with torch.no_grad():
    __A  :		Union[str, Any]       =			model(**UpperCamelCase__			)
   __A  :		Any       =			outputs.logits.argmax(dim=-1			)
   __A     ,__A  :		List[Any]       =			accelerator.gather_for_metrics((predictions, batch['labels'])			)
   metric.add_batch(
       predictions=UpperCamelCase__,				references=UpperCamelCase__,				)

  __A  :		Optional[int]       =			metric.compute()
  # Use accelerator.print to print only on the main process.
  accelerator.print(f"""epoch {epoch}:""",				UpperCamelCase__			)


def 			_lowercase       (				):
 __A  :		Dict       =			argparse.ArgumentParser(description='Simple example of training script.'			)
 parser.add_argument(
     '--mixed_precision',				type=UpperCamelCase__,				default=UpperCamelCase__,				choices=['no', 'fp16', 'bf16', 'fp8'],				help='Whether to use mixed precision. Choose'
     'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'
     'and an Nvidia Ampere GPU.',				)
 # New Code #
 parser.add_argument(
     '--gradient_accumulation_steps',				type=UpperCamelCase__,				default=1,				help='The number of minibatches to be ran before gradients are accumulated.',				)
 parser.add_argument(
     '--local_sgd_steps',				type=UpperCamelCase__,				default=8,				help='Number of local SGD steps or None to disable local SGD'			)
 parser.add_argument('--cpu',				action='store_true',				help='If passed, will train on the CPU.'			)
 __A  :		List[Any]       =			parser.parse_args()
 __A  :		Optional[Any]       =			{'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
 training_function(UpperCamelCase__,				UpperCamelCase__			)


if __name__ == "__main__":
 main()










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

import datasets
from datasets import logging


UpperCAmelCase_ :     Optional[int]								=      '\\n\n'

UpperCAmelCase_ :     Tuple								=      '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n'

UpperCAmelCase_ :     str								=      '\nArgs:\n    model_id (str): model used for calculating Perplexity\n            NOTE: Perplexity can only be calculated for causal language models.\n                    This includes models such as gpt2, causal variations of bert,\n                    causal versions of t5, and more (the full list can be found\n                    in the AutoModelForCausalLM documentation here:\n                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n    input_texts (list of str): input text, each separate text snippet\n        is one list entry.\n    batch_size (int): the batch size to run texts through the model. Defaults to 16.\n    add_start_token (bool): whether to add the start token to the texts,\n        so the perplexity can include the probability of the first word. Defaults to True.\n    device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n    perplexity: dictionary containing the perplexity scores for the texts\n        in the input list, as well as the mean perplexity. If one of the input texts is\n        longer than the max input length of the model, then it is truncated to the\n        max length for the perplexity computation.\nExamples:\n    Example 1:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              add_start_token=False,\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        78.22\n        >>> print(round(results["perplexities"][0], 2))\n        11.11\n\n    Example 2:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = datasets.load_dataset("wikitext",\n        ...                                     "wikitext-2-raw-v1",\n        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS\n        [...]\n        >>> input_texts = [s for s in input_texts if s!=\'\']\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        60.35\n        >>> print(round(results["perplexities"][0], 2))\n        81.12\n'

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,		_KWARGS_DESCRIPTION				)
class 						_lowerCamelCase					(    datasets.Metric				):




 '''simple docstring'''


 def  snake_case__   (      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  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase = 16      ,      __lowercase = True      ,      __lowercase=None						):

  """simple docstring"""







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

  __A  :		List[Any]       =			AutoModelForCausalLM.from_pretrained(__lowercase						)
  __A  :		Any       =			model.to(__lowercase						)

  __A  :		List[Any]       =			AutoTokenizer.from_pretrained(__lowercase						)

  # 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:
   __A  :		Union[str, Any]       =			list(tokenizer.special_tokens_map_extended.values()						)
   # check that the model already has at least one special token defined
   assert (
       len(__lowercase						) > 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"
   __A  :		Tuple       =			model.config.max_length - 1
  else:
   __A  :		str       =			model.config.max_length

  __A  :		int       =			tokenizer(
      __lowercase      ,      add_special_tokens=__lowercase      ,      padding=__lowercase      ,      truncation=__lowercase      ,      max_length=__lowercase      ,      return_tensors='pt'      ,      return_attention_mask=__lowercase      ,      ).to(__lowercase						)

  __A  :		Union[str, Any]       =			encodings['input_ids']
  __A  :		Optional[int]       =			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."

  __A  :		Union[str, Any]       =			[]
  __A  :		str       =			CrossEntropyLoss(reduction='none'						)

  for start_index in logging.tqdm(range(0      ,      len(__lowercase						)      ,      __lowercase						)						):
   __A  :		str       =			min(start_index + batch_size      ,      len(__lowercase						)						)
   __A  :		Tuple       =			encoded_texts[start_index:end_index]
   __A  :		List[str]       =			attn_masks[start_index:end_index]

   if add_start_token:
    __A  :		str       =			torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0						)						).to(__lowercase						)
    __A  :		str       =			torch.cat([bos_tokens_tensor, encoded_batch]      ,      dim=1						)
    __A  :		Union[str, Any]       =			torch.cat(
        [torch.ones(bos_tokens_tensor.size()      ,      dtype=torch.intaa						).to(__lowercase						), attn_mask]      ,      dim=1						)

   __A  :		Tuple       =			encoded_batch

   with torch.no_grad():
    __A  :		List[str]       =			model(__lowercase      ,      attention_mask=__lowercase						).logits

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

   __A  :		Tuple       =			torch.expa(
       (loss_fct(shift_logits.transpose(1      ,      2						)      ,      __lowercase						) * shift_attention_mask_batch).sum(1						)
       / shift_attention_mask_batch.sum(1						)						)

   ppls += perplexity_batch.tolist()

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






