




"""simple docstring"""

import argparse
from typing import List

import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset

# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
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,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# 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 help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# 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
#
########################################################################


a         =      16
a         =      32






def 						_snake_case					( _snake_case							: Accelerator    ,  _snake_case							: DatasetDict    ,  _snake_case							: List[int]    ,  _snake_case							: List[int]    ,  _snake_case							: int = 16							)   -> Union[str, Any]:






      '''simple docstring'''


      _A        =       AutoTokenizer.from_pretrained('bert-base-cased'							)
      _A        =       DatasetDict(
          {
              'train': dataset['train'].select(_snake_case							),
              'validation': dataset['train'].select(_snake_case							),
              'test': dataset['validation'],
          }							)

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

      def collate_fn(_snake_case							: Any							):
            # On TPU it's best to pad everything to the same length or training will be very slow.
            _A        =       1_28 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        =       16
            elif accelerator.mixed_precision != "no":
                  _A        =       8
            else:
                  _A        =       None

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

      # Instantiate dataloaders.
      _A        =       DataLoader(
          tokenized_datasets['train']    ,  shuffle=_snake_case    ,  collate_fn=_snake_case    ,  batch_size=_snake_case							)
      _A        =       DataLoader(
          tokenized_datasets['validation']    ,  shuffle=_snake_case    ,  collate_fn=_snake_case    ,  batch_size=_snake_case							)

      _A        =       DataLoader(
          tokenized_datasets['test']    ,  shuffle=_snake_case    ,  collate_fn=_snake_case    ,  batch_size=_snake_case							)

      return train_dataloader, eval_dataloader, test_dataloader






def 						_snake_case					( _snake_case							: List[Any]    ,  _snake_case							: str							)   -> Optional[Any]:






      '''simple docstring'''


      _A        =       []
      # Download the dataset
      _A        =       load_dataset('glue'    ,  'mrpc'							)
      # Create our splits
      _A        =       StratifiedKFold(n_splits=int(args.num_folds							)							)
      # Initialize accelerator
      _A        =       Accelerator(cpu=args.cpu    ,  mixed_precision=args.mixed_precision							)
      # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
      _A        =       config['lr']
      _A        =       int(config['num_epochs']							)
      _A        =       int(config['seed']							)
      _A        =       int(config['batch_size']							)

      _A        =       evaluate.load('glue'    ,  'mrpc'							)

      # If the batch size is too big we use gradient accumulation
      _A        =       1
      if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
            _A        =       batch_size // MAX_GPU_BATCH_SIZE
            _A        =       MAX_GPU_BATCH_SIZE

      set_seed(_snake_case							)

      # New Code #
      # Create our folds:
      _A        =       kfold.split(np.zeros(datasets['train'].num_rows							)    ,  datasets['train']['label']							)
      _A        =       []
      # Iterate over them
      for i, (train_idxs, valid_idxs) in enumerate(_snake_case							):
            _A       ,   _A       ,   _A        =       get_fold_dataloaders(
                _snake_case    ,  _snake_case    ,  _snake_case    ,  _snake_case    ,  )
            # Instantiate the model (we build the model here so that the seed also control new weights initialization)
            _A        =       AutoModelForSequenceClassification.from_pretrained('bert-base-cased'    ,  return_dict=_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        =       model.to(accelerator.device							)

            # Instantiate optimizer
            _A        =       AdamW(params=model.parameters()    ,  lr=_snake_case							)

            # Instantiate scheduler
            _A        =       get_linear_schedule_with_warmup(
                optimizer=_snake_case    ,  num_warmup_steps=1_00    ,  num_training_steps=(len(_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        =       accelerator.prepare(
                _snake_case    ,  _snake_case    ,  _snake_case    ,  _snake_case    ,  _snake_case							)

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

                  model.eval()
                  for step, batch in enumerate(_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        =       model(**_snake_case							)
                        _A        =       outputs.logits.argmax(dim=-1							)
                        _A       ,   _A        =       accelerator.gather_for_metrics((predictions, batch['labels'])							)
                        metric.add_batch(
                            predictions=_snake_case    ,  references=_snake_case    ,  )

                  _A        =       metric.compute()
                  # Use accelerator.print to print only on the main process.
                  accelerator.print(F'''epoch {epoch}:'''    ,  _snake_case							)

            # New Code #
            # We also run predictions on the test set at the very end
            _A        =       []
            for step, batch in enumerate(_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        =       model(**_snake_case							)
                  _A        =       outputs.logits
                  _A       ,   _A        =       accelerator.gather_for_metrics((predictions, batch['labels'])							)
                  fold_predictions.append(predictions.cpu()							)
                  if i == 0:
                        # We need all of the test predictions
                        test_references.append(references.cpu()							)
        # Use accelerator.print to print only on the main process.
            test_predictions.append(torch.cat(_snake_case    ,  dim=0							)							)
            # We now need to release all our memory and get rid of the current model, optimizer, etc
            accelerator.free_memory()
      # New Code #
      # Finally we check the accuracy of our folded results:
      _A        =       torch.cat(_snake_case    ,  dim=0							)
      _A        =       torch.stack(_snake_case    ,  dim=0							).sum(dim=0							).div(int(args.num_folds							)							).argmax(dim=-1							)
      _A        =       metric.compute(predictions=_snake_case    ,  references=_snake_case							)
      accelerator.print('Average test metrics from all folds:'    ,  _snake_case							)






def 						_snake_case					( )   -> int:






      '''simple docstring'''


      _A        =       argparse.ArgumentParser(description='Simple example of training script.'							)
      parser.add_argument(
          '--mixed_precision'    ,  type=_snake_case    ,  default=_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.'							)
      # New Code #
      parser.add_argument('--num_folds'    ,  type=_snake_case    ,  default=3    ,  help='The number of splits to perform across the dataset'							)
      _A        =       parser.parse_args()
      _A        =       {'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
      training_function(_snake_case    ,  _snake_case							)


if __name__ == "__main__":
       main()












"""simple docstring"""

from typing import Any, Dict, List, Optional, Tuple, Union

import torch
from torch import nn
from torch.utils.data import DistributedSampler, RandomSampler

from transformers import PreTrainedModel, Trainer, logging
from transformers.integrations import is_fairscale_available
from transformers.models.fsmt.configuration_fsmt import FSMTConfig
from transformers.optimization import (
    Adafactor,
    AdamW,
    get_constant_schedule,
    get_constant_schedule_with_warmup,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.trainer_pt_utils import get_tpu_sampler
from transformers.training_args import ParallelMode
from transformers.utils import is_torch_tpu_available


if is_fairscale_available():
       from fairscale.optim import OSS


a         =      logging.get_logger(__name__)

a         =      {
    '''linear''': get_linear_schedule_with_warmup,
    '''cosine''': get_cosine_schedule_with_warmup,
    '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup,
    '''polynomial''': get_polynomial_decay_schedule_with_warmup,
    '''constant''': get_constant_schedule,
    '''constant_w_warmup''': get_constant_schedule_with_warmup,
}





class     lowercase_	(					__lowerCAmelCase							):



 '''simple docstring'''

 def __init__(			self	:	Any   ,							_UpperCAmelCase	:	Optional[int]=None   ,							_UpperCAmelCase	:	Tuple=None   ,							*_UpperCAmelCase	:	int   ,							**_UpperCAmelCase	:	Tuple		):
       super().__init__(*_UpperCAmelCase   ,							**_UpperCAmelCase		)

       if config is None:
             assert isinstance(self.model   ,							_UpperCAmelCase		), (
                 "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is"
                 F''' {self.model.__class__}'''
             )
             _A        =       self.model.config
       else:
             _A        =       config

       _A        =       data_args
       _A        =       self.config.tgt_vocab_size if isinstance(self.config   ,							_UpperCAmelCase		) else self.config.vocab_size

       if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss):
             assert self.config.pad_token_id is not None, (
                 "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss"
                 " calculation or doing label smoothing."
             )

       if self.config.pad_token_id is None and self.config.eos_token_id is not None:
             logger.warning(
                 F'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for'''
                 ' padding..'		)

       if self.args.label_smoothing == 0:
             _A        =       torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id		)
       else:
             # dynamically import label_smoothed_nll_loss
             from utils import label_smoothed_nll_loss

             _A        =       label_smoothed_nll_loss

 def       lowerCAmelCase_							(			self	:	List[str]   ,							_UpperCAmelCase	:	int		):
       if self.optimizer is None:
             _A        =       ['bias', 'LayerNorm.weight']
             _A        =       [
                 {
                     'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay		)],
                     'weight_decay': self.args.weight_decay,
                 },
                 {
                     'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay		)],
                     'weight_decay': 0.0,
                 },
             ]
             _A        =       Adafactor if self.args.adafactor else AdamW
             if self.args.adafactor:
                   _A        =       Adafactor
                   _A        =       {'scale_parameter': False, 'relative_step': False}
             else:
                   _A        =       AdamW
                   _A        =       {
                       'betas': (self.args.adam_betaa, self.args.adam_betaa),
                       'eps': self.args.adam_epsilon,
                   }
             _A        =       self.args.learning_rate
             if self.sharded_ddp:
                   _A        =       OSS(
                       params=_UpperCAmelCase   ,							optim=_UpperCAmelCase   ,							**_UpperCAmelCase   ,							)
             else:
                   _A        =       optimizer_cls(_UpperCAmelCase   ,							**_UpperCAmelCase		)

       if self.lr_scheduler is None:
             _A        =       self._get_lr_scheduler(_UpperCAmelCase		)
       else:  # ignoring --lr_scheduler
             logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.'		)

 def       lowerCAmelCase_							(			self	:	str   ,							_UpperCAmelCase	:	Any		):
       _A        =       arg_to_scheduler[self.args.lr_scheduler]
       if self.args.lr_scheduler == "constant":
             _A        =       schedule_func(self.optimizer		)
       elif self.args.lr_scheduler == "constant_w_warmup":
             _A        =       schedule_func(self.optimizer   ,							num_warmup_steps=self.args.warmup_steps		)
       else:
             _A        =       schedule_func(
                 self.optimizer   ,							num_warmup_steps=self.args.warmup_steps   ,							num_training_steps=_UpperCAmelCase		)
       return scheduler

 def       lowerCAmelCase_							(			self	:	Any		):
       if isinstance(self.train_dataset   ,							torch.utils.data.IterableDataset		):
             return None
       elif is_torch_tpu_available():
             return get_tpu_sampler(self.train_dataset		)
       else:
             if self.args.sortish_sampler:
                   self.train_dataset.make_sortish_sampler(
                       self.args.per_device_train_batch_size   ,							distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED)   ,							)

             return (
                 RandomSampler(self.train_dataset		)
                 if self.args.local_rank == -1
                 else DistributedSampler(self.train_dataset		)
             )

 def       lowerCAmelCase_							(			self	:	Optional[int]   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	int		):
       if self.args.label_smoothing == 0:
             if self.data_args is not None and self.data_args.ignore_pad_token_for_loss:
                   # force training to ignore pad token
                   _A        =       model(**_UpperCAmelCase   ,							use_cache=_UpperCAmelCase		)[0]
                   _A        =       self.loss_fn(logits.view(-1   ,							logits.shape[-1]		)   ,							labels.view(-1		)		)
             else:
                   # compute usual loss via models
                   _A       ,   _A        =       model(**_UpperCAmelCase   ,							labels=_UpperCAmelCase   ,							use_cache=_UpperCAmelCase		)[:2]
       else:
             # compute label smoothed loss
             _A        =       model(**_UpperCAmelCase   ,							use_cache=_UpperCAmelCase		)[0]
             _A        =       torch.nn.functional.log_softmax(_UpperCAmelCase   ,							dim=-1		)
             _A       ,   _A        =       self.loss_fn(_UpperCAmelCase   ,							_UpperCAmelCase   ,							self.args.label_smoothing   ,							ignore_index=self.config.pad_token_id		)
       return loss, logits

 def       lowerCAmelCase_							(			self	:	Union[str, Any]   ,							_UpperCAmelCase	:	List[str]   ,							_UpperCAmelCase	:	Optional[int]		):
       _A        =       inputs.pop('labels'		)
       _A       ,   _A        =       self._compute_loss(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase		)
       return loss

 def       lowerCAmelCase_							(			self	:	Any   ,							_UpperCAmelCase	:	nn.Module   ,							_UpperCAmelCase	:	Dict[str, Union[torch.Tensor, Any]]   ,							_UpperCAmelCase	:	bool   ,							_UpperCAmelCase	:	Optional[List[str]] = None   ,							):
       _A        =       self._prepare_inputs(_UpperCAmelCase		)

       _A        =       {
           'max_length': self.data_args.val_max_target_length
           if self.data_args is not None
           else self.config.max_length,
           'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams,
       }

       if self.args.predict_with_generate and not self.args.prediction_loss_only:
             _A        =       self.model.generate(
                 inputs['input_ids']   ,							attention_mask=inputs['attention_mask']   ,							**_UpperCAmelCase   ,							)
             # in case the batch is shorter than max length, the output should be padded
             if generated_tokens.shape[-1] < gen_kwargs["max_length"]:
                   _A        =       self._pad_tensors_to_max_len(_UpperCAmelCase   ,							gen_kwargs['max_length']		)

       _A        =       inputs.pop('labels'		)
       with torch.no_grad():
             # compute loss on predict data
             _A       ,   _A        =       self._compute_loss(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase		)

       _A        =       loss.mean().detach()
       if self.args.prediction_loss_only:
             return (loss, None, None)

       _A        =       generated_tokens if self.args.predict_with_generate else logits

       if labels.shape[-1] < gen_kwargs["max_length"]:
             _A        =       self._pad_tensors_to_max_len(_UpperCAmelCase   ,							gen_kwargs['max_length']		)

       return (loss, logits, labels)



 def       lowerCAmelCase_							(			self	:	str   ,							_UpperCAmelCase	:	Tuple   ,							_UpperCAmelCase	:	Tuple		):
       # If PAD token is not defined at least EOS token has to be defined
       _A        =       self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id

       if pad_token_id is None:
             raise ValueError(
                 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be'
                 F''' padded to `max_length`={max_length}'''		)

       _A        =       pad_token_id * torch.ones(
           (tensor.shape[0], max_length)   ,							dtype=tensor.dtype   ,							device=tensor.device		)
       _A        =       tensor
       return padded_tensor

