





import argparse

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


########################################################################
# This is a fully working simple example to use Accelerate
#
# 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     :     Any							=	16
UpperCAmelCase     :     Optional[int]							=	32
def 					_A	(		SCREAMING_SNAKE_CASE					:       Accelerator	,	SCREAMING_SNAKE_CASE					:       int = 16						):





  """simple docstring"""



  a__     : Dict  =AutoTokenizer.from_pretrained("bert-base-cased"						)
  a__     : Union[str, Any]  =load_dataset("glue"	,	"mrpc"						)

  def tokenize_function(SCREAMING_SNAKE_CASE					:       int						):
    # max_length=None => use the model max length (it's actually the default)
    a__     : int  =tokenizer(examples["sentence1"]	,	examples["sentence2"]	,	truncation=SCREAMING_SNAKE_CASE	,	max_length=SCREAMING_SNAKE_CASE						)
    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__     : Any  =datasets.map(
        SCREAMING_SNAKE_CASE	,	batched=SCREAMING_SNAKE_CASE	,	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__     : Any  =tokenized_datasets.rename_column("label"	,	"labels"						)

  def collate_fn(SCREAMING_SNAKE_CASE					:       Optional[int]						):
    # On TPU it's best to pad everything to the same length or training will be very slow.
    a__     : List[str]  =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[str]  =16
    elif accelerator.mixed_precision != "no":
      a__     : Dict  =8
    else:
      a__     : Optional[int]  =None

    return tokenizer.pad(
        SCREAMING_SNAKE_CASE	,	padding="longest"	,	max_length=SCREAMING_SNAKE_CASE	,	pad_to_multiple_of=SCREAMING_SNAKE_CASE	,	return_tensors="pt"	,	)

  # Instantiate dataloaders.
  a__     : Union[str, Any]  =DataLoader(
      tokenized_datasets["train"]	,	shuffle=SCREAMING_SNAKE_CASE	,	collate_fn=SCREAMING_SNAKE_CASE	,	batch_size=SCREAMING_SNAKE_CASE	,	drop_last=SCREAMING_SNAKE_CASE						)
  a__     : Optional[int]  =DataLoader(
      tokenized_datasets["validation"]	,	shuffle=SCREAMING_SNAKE_CASE	,	collate_fn=SCREAMING_SNAKE_CASE	,	batch_size=SCREAMING_SNAKE_CASE	,	drop_last=(accelerator.mixed_precision == "fp8")	,	)

  return train_dataloader, eval_dataloader
def 					_A	(		SCREAMING_SNAKE_CASE					:       Optional[Any]	,	SCREAMING_SNAKE_CASE					:       str						):





  """simple docstring"""



  a__     : Optional[Any]  =Accelerator(cpu=args.cpu	,	mixed_precision=args.mixed_precision						)
  # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
  a__     : Union[str, Any]  =config["lr"]
  a__     : List[Any]  =int(config["num_epochs"]						)
  a__     : Any  =int(config["seed"]						)
  a__     : Optional[Any]  =int(config["batch_size"]						)

  a__     : Dict  =evaluate.load("glue"	,	"mrpc"						)

  # If the batch size is too big we use gradient accumulation
  a__     : str  =1
  if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
    a__     : Optional[int]  =batch_size // MAX_GPU_BATCH_SIZE
    a__     : List[Any]  =MAX_GPU_BATCH_SIZE

  set_seed(SCREAMING_SNAKE_CASE						)
  a__ ,							a__     : List[str]  =get_dataloaders(SCREAMING_SNAKE_CASE	,	SCREAMING_SNAKE_CASE						)
  # Instantiate the model (we build the model here so that the seed also control new weights initialization)
  a__     : Union[str, Any]  =AutoModelForSequenceClassification.from_pretrained("bert-base-cased"	,	return_dict=SCREAMING_SNAKE_CASE						)

  # 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__     : Any  =model.to(accelerator.device						)
  # Instantiate optimizer
  a__     : str  =AdamW(params=model.parameters()	,	lr=SCREAMING_SNAKE_CASE						)

  # Instantiate scheduler
  a__     : Optional[int]  =get_linear_schedule_with_warmup(
      optimizer=SCREAMING_SNAKE_CASE	,	num_warmup_steps=100	,	num_training_steps=(len(SCREAMING_SNAKE_CASE						) * num_epochs) // gradient_accumulation_steps	,	)

  # 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__     : str  =accelerator.prepare(
      SCREAMING_SNAKE_CASE	,	SCREAMING_SNAKE_CASE	,	SCREAMING_SNAKE_CASE	,	SCREAMING_SNAKE_CASE	,	SCREAMING_SNAKE_CASE						)

  # Now we train the model
  for epoch in range(SCREAMING_SNAKE_CASE						):
    model.train()
    for step, batch in enumerate(SCREAMING_SNAKE_CASE						):
      # We could avoid this line since we set the accelerator with `device_placement=True`.
      batch.to(accelerator.device						)
      a__     : int  =model(**SCREAMING_SNAKE_CASE						)
      a__     : Union[str, Any]  =outputs.loss
      a__     : Optional[int]  =loss / gradient_accumulation_steps
      accelerator.backward(SCREAMING_SNAKE_CASE						)
      if step % gradient_accumulation_steps == 0:
        optimizer.step()
        lr_scheduler.step()
        optimizer.zero_grad()

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

    a__     : Dict  =metric.compute()
    # Use accelerator.print to print only on the main process.
    accelerator.print(f'''epoch {epoch}:'''	,	SCREAMING_SNAKE_CASE						)
def 					_A	(		):





  """simple docstring"""



  a__     : List[Any]  =argparse.ArgumentParser(description="Simple example of training script."						)
  parser.add_argument(
      "--mixed_precision"	,	type=SCREAMING_SNAKE_CASE	,	default=SCREAMING_SNAKE_CASE	,	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."	,	)
  parser.add_argument("--cpu"	,	action="store_true"	,	help="If passed, will train on the CPU."						)
  a__     : Any  =parser.parse_args()
  a__     : List[Any]  ={"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
  training_function(SCREAMING_SNAKE_CASE	,	SCREAMING_SNAKE_CASE						)


if __name__ == "__main__":
     main()













import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


UpperCAmelCase     :     Tuple							=	logging.get_logger(__name__)

UpperCAmelCase     :     List[Any]							=	list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCAmelCase     :     Dict							=	tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class     __lowerCAmelCase	:
      _lowercase    : str            =      field(
          default=UpperCamelCase__						,    metadata={"""help""": """Model type selected in the list: """ + """, """.join(UpperCamelCase__)})
      _lowercase    : str            =      field(
          default=UpperCamelCase__						,    metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""})
      _lowercase    : int            =      field(
          default=128						,    metadata={
              """help""": (
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )
          }						,    )
      _lowercase    : int            =      field(
          default=128						,    metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}						,    )
      _lowercase    : int            =      field(
          default=64						,    metadata={
              """help""": (
                  """The maximum number of tokens for the question. Questions longer than this will """
                  """be truncated to this length."""
              )
          }						,    )
      _lowercase    : int            =      field(
          default=30						,    metadata={
              """help""": (
                  """The maximum length of an answer that can be generated. This is needed because the start """
                  """and end predictions are not conditioned on one another."""
              )
          }						,    )
      _lowercase    : bool            =      field(
          default=UpperCamelCase__						,    metadata={"""help""": """Overwrite the cached training and evaluation sets"""})
      _lowercase    : bool            =      field(
          default=UpperCamelCase__						,    metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""})
      _lowercase    : float            =      field(
          default=0.0						,    metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""})
      _lowercase    : int            =      field(
          default=20						,    metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""})
      _lowercase    : int            =      field(
          default=0						,    metadata={
              """help""": (
                  """language id of input for language-specific xlm models (see"""
                  """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
              )
          }						,    )
      _lowercase    : int            =      field(default=1						,    metadata={"""help""": """multiple threads for converting example to features"""})







class     __lowerCAmelCase	(   UpperCamelCase__):
      _lowercase    : List[Any]            =      """train"""
      _lowercase    : Any            =      """dev"""







class     __lowerCAmelCase	(   UpperCamelCase__):
      _lowercase    : SquadDataTrainingArguments
      _lowercase    : List[SquadFeatures]
      _lowercase    : Split
      _lowercase    : bool







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = Split.train		,				lowerCAmelCase__ = False		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = "pt"		,				)       ->						str:



        '''simple docstring'''




        a__     : List[Any]  =args
        a__     : int  =is_language_sensitive
        a__     : List[str]  =SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
        if isinstance(lowerCAmelCase__		,				lowerCAmelCase__							):
          try:
            a__     : str  =Split[mode]
          except KeyError:
            raise KeyError("mode is not a valid split name"							)
        a__     : Any  =mode
        # Load data features from cache or dataset file
        a__     : str  ="v2" if args.version_2_with_negative else "v1"
        a__     : str  =os.path.join(
            cache_dir if cache_dir is not None else args.data_dir		,				F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'''		,				)

        # Make sure only the first process in distributed training processes the dataset,
        # and the others will use the cache.
        a__     : Dict  =cached_features_file + ".lock"
        with FileLock(lowerCAmelCase__							):
          if os.path.exists(lowerCAmelCase__							) and not args.overwrite_cache:
            a__     : Any  =time.time()
            a__     : List[Any]  =torch.load(lowerCAmelCase__							)

            # Legacy cache files have only features, while new cache files
            # will have dataset and examples also.
            a__     : str  =self.old_features["features"]
            a__     : str  =self.old_features.get("dataset"		,				lowerCAmelCase__							)
            a__     : Optional[int]  =self.old_features.get("examples"		,				lowerCAmelCase__							)
            logger.info(
                F'''Loading features from cached file {cached_features_file} [took %.3f s]'''		,				time.time() - start							)

            if self.dataset is None or self.examples is None:
              logger.warning(
                  F'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
                  " future run"							)
          else:
            if mode == Split.dev:
              a__     : Dict  =self.processor.get_dev_examples(args.data_dir							)
            else:
              a__     : str  =self.processor.get_train_examples(args.data_dir							)

            a__ ,							a__     : Union[str, Any]  =squad_convert_examples_to_features(
                examples=self.examples		,				tokenizer=lowerCAmelCase__		,				max_seq_length=args.max_seq_length		,				doc_stride=args.doc_stride		,				max_query_length=args.max_query_length		,				is_training=mode == Split.train		,				threads=args.threads		,				return_dataset=lowerCAmelCase__		,				)

            a__     : Any  =time.time()
            torch.save(
                {"features": self.features, "dataset": self.dataset, "examples": self.examples}		,				lowerCAmelCase__		,				)
            # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
            logger.info(
                F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''							)







      def __len__(   self							)       ->						Tuple:



        '''simple docstring'''




        return len(self.features							)







      def __getitem__(   self		,				lowerCAmelCase__							)       ->						Dict[str, torch.Tensor]:



        '''simple docstring'''




        a__     : str  =self.features[i]

        a__     : Optional[Any]  =torch.tensor(feature.input_ids		,				dtype=torch.long							)
        a__     : List[Any]  =torch.tensor(feature.attention_mask		,				dtype=torch.long							)
        a__     : int  =torch.tensor(feature.token_type_ids		,				dtype=torch.long							)
        a__     : List[str]  =torch.tensor(feature.cls_index		,				dtype=torch.long							)
        a__     : int  =torch.tensor(feature.p_mask		,				dtype=torch.float							)
        a__     : Tuple  =torch.tensor(feature.is_impossible		,				dtype=torch.float							)

        a__     : Tuple  ={
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "token_type_ids": token_type_ids,
        }

        if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
          del inputs["token_type_ids"]

        if self.args.model_type in ["xlnet", "xlm"]:
          inputs.update({"cls_index": cls_index, "p_mask": p_mask}							)
          if self.args.version_2_with_negative:
            inputs.update({"is_impossible": is_impossible}							)
          if self.is_language_sensitive:
            inputs.update({"langs": (torch.ones(input_ids.shape		,				dtype=torch.intaa							) * self.args.lang_id)}							)

        if self.mode == Split.train:
          a__     : int  =torch.tensor(feature.start_position		,				dtype=torch.long							)
          a__     : Any  =torch.tensor(feature.end_position		,				dtype=torch.long							)
          inputs.update({"start_positions": start_positions, "end_positions": end_positions}							)

        return inputs






