




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
#
########################################################################


lowerCamelCase__ :   List[str]					=							16
lowerCamelCase__ :   int					=							32

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Accelerator			,			__UpperCAmelCase						:	DatasetDict			,			__UpperCAmelCase						:	List[int]			,			__UpperCAmelCase						:	List[int]			,			__UpperCAmelCase						:	int = 16							)					-> Optional[int]:
      SCREAMING_SNAKE_CASE_							=			AutoTokenizer.from_pretrained('bert-base-cased'							)
      SCREAMING_SNAKE_CASE_							=			DatasetDict(
          {
              'train': dataset['train'].select(__UpperCAmelCase							),
              'validation': dataset['train'].select(__UpperCAmelCase							),
              'test': dataset['validation'],
          }							)

      def tokenize_function(__UpperCAmelCase						:	Union[str, Any]							):
            # max_length=None => use the model max length (it's actually the default)
            SCREAMING_SNAKE_CASE_							=			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():
            SCREAMING_SNAKE_CASE_							=			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
      SCREAMING_SNAKE_CASE_							=			tokenized_datasets.rename_column('label'			,			'labels'							)

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

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

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

      SCREAMING_SNAKE_CASE_							=			DataLoader(
          tokenized_datasets['test']			,			shuffle=__UpperCAmelCase			,			collate_fn=__UpperCAmelCase			,			batch_size=__UpperCAmelCase							)

      return train_dataloader, eval_dataloader, test_dataloader

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Union[str, Any]			,			__UpperCAmelCase						:	Any							)					-> Any:
      # New Code #
      SCREAMING_SNAKE_CASE_							=			[]
      # Download the dataset
      SCREAMING_SNAKE_CASE_							=			load_dataset('glue'			,			'mrpc'							)
      # Create our splits
      SCREAMING_SNAKE_CASE_							=			StratifiedKFold(n_splits=int(args.num_folds							)							)
      # Initialize accelerator
      SCREAMING_SNAKE_CASE_							=			Accelerator(cpu=args.cpu			,			mixed_precision=args.mixed_precision							)
      # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
      SCREAMING_SNAKE_CASE_							=			config['lr']
      SCREAMING_SNAKE_CASE_							=			int(config['num_epochs']							)
      SCREAMING_SNAKE_CASE_							=			int(config['seed']							)
      SCREAMING_SNAKE_CASE_							=			int(config['batch_size']							)

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

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

      set_seed(__UpperCAmelCase							)

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

            # Instantiate optimizer
            SCREAMING_SNAKE_CASE_							=			AdamW(params=model.parameters()			,			lr=__UpperCAmelCase							)

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

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

                  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():
                              SCREAMING_SNAKE_CASE_							=			model(**__UpperCAmelCase							)
                        SCREAMING_SNAKE_CASE_							=			outputs.logits.argmax(dim=-1							)
                        SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			accelerator.gather_for_metrics((predictions, batch['labels'])							)
                        metric.add_batch(
                            predictions=__UpperCAmelCase			,			references=__UpperCAmelCase			,			)

                  SCREAMING_SNAKE_CASE_							=			metric.compute()
                  # Use accelerator.print to print only on the main process.
                  accelerator.print(f"epoch {epoch}:"			,			__UpperCAmelCase							)

            # New Code #
            # We also run predictions on the test set at the very end
            SCREAMING_SNAKE_CASE_							=			[]
            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():
                        SCREAMING_SNAKE_CASE_							=			model(**__UpperCAmelCase							)
                  SCREAMING_SNAKE_CASE_							=			outputs.logits
                  SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			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(__UpperCAmelCase			,			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:
      SCREAMING_SNAKE_CASE_							=			torch.cat(__UpperCAmelCase			,			dim=0							)
      SCREAMING_SNAKE_CASE_							=			torch.stack(__UpperCAmelCase			,			dim=0							).sum(dim=0							).div(int(args.num_folds							)							).argmax(dim=-1							)
      SCREAMING_SNAKE_CASE_							=			metric.compute(predictions=__UpperCAmelCase			,			references=__UpperCAmelCase							)
      accelerator.print('Average test metrics from all folds:'			,			__UpperCAmelCase							)

def 					UpperCAmelCase_							(      )					-> str:
      SCREAMING_SNAKE_CASE_							=			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.'			,			)
      parser.add_argument('--cpu'			,			action='store_true'			,			help='If passed, will train on the CPU.'							)
      # New Code #
      parser.add_argument('--num_folds'			,			type=__UpperCAmelCase			,			default=3			,			help='The number of splits to perform across the dataset'							)
      SCREAMING_SNAKE_CASE_							=			parser.parse_args()
      SCREAMING_SNAKE_CASE_							=			{'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
      training_function(__UpperCAmelCase			,			__UpperCAmelCase							)


if __name__ == "__main__":
   main()





import datetime
import platform
import subprocess
from typing import Optional, Tuple, Union

import numpy as np

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	bytes			,			__UpperCAmelCase						:	int							)					-> np.array:
      SCREAMING_SNAKE_CASE_							=			f"{sampling_rate}"
      SCREAMING_SNAKE_CASE_							=			'1'
      SCREAMING_SNAKE_CASE_							=			'f32le'
      SCREAMING_SNAKE_CASE_							=			[
          'ffmpeg',
          '-i',
          'pipe:0',
          '-ac',
          ac,
          '-ar',
          ar,
          '-f',
          format_for_conversion,
          '-hide_banner',
          '-loglevel',
          'quiet',
          'pipe:1',
      ]

      try:
            with subprocess.Popen(__UpperCAmelCase			,			stdin=subprocess.PIPE			,			stdout=subprocess.PIPE							) as ffmpeg_process:
                  SCREAMING_SNAKE_CASE_							=			ffmpeg_process.communicate(__UpperCAmelCase							)
      except FileNotFoundError as error:
            raise ValueError('ffmpeg was not found but is required to load audio files from filename'							) from error
      SCREAMING_SNAKE_CASE_							=			output_stream[0]
      SCREAMING_SNAKE_CASE_							=			np.frombuffer(__UpperCAmelCase			,			np.floataa							)
      if audio.shape[0] == 0:
            raise ValueError('Malformed soundfile'							)
      return audio

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	int			,			__UpperCAmelCase						:	float			,			__UpperCAmelCase						:	str = "f32le"			,			)					-> int:
      SCREAMING_SNAKE_CASE_							=			f"{sampling_rate}"
      SCREAMING_SNAKE_CASE_							=			'1'
      if format_for_conversion == "s16le":
            SCREAMING_SNAKE_CASE_							=			2
      elif format_for_conversion == "f32le":
            SCREAMING_SNAKE_CASE_							=			4
      else:
            raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"							)

      SCREAMING_SNAKE_CASE_							=			platform.system()
      if system == "Linux":
            SCREAMING_SNAKE_CASE_							=			'alsa'
            SCREAMING_SNAKE_CASE_							=			'default'
      elif system == "Darwin":
            SCREAMING_SNAKE_CASE_							=			'avfoundation'
            SCREAMING_SNAKE_CASE_							=			':0'
      elif system == "Windows":
            SCREAMING_SNAKE_CASE_							=			'dshow'
            SCREAMING_SNAKE_CASE_							=			'default'

      SCREAMING_SNAKE_CASE_							=			[
          'ffmpeg',
          '-f',
          format_,
          '-i',
          input_,
          '-ac',
          ac,
          '-ar',
          ar,
          '-f',
          format_for_conversion,
          '-fflags',
          'nobuffer',
          '-hide_banner',
          '-loglevel',
          'quiet',
          'pipe:1',
      ]
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * chunk_length_s							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			_ffmpeg_stream(__UpperCAmelCase			,			__UpperCAmelCase							)
      for item in iterator:
            yield item

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	int			,			__UpperCAmelCase						:	float			,			__UpperCAmelCase						:	Optional[int] = None			,			__UpperCAmelCase						:	Optional[Union[Tuple[float, float], float]] = None			,			__UpperCAmelCase						:	str = "f32le"			,			)					-> Tuple:
      if stream_chunk_s is not None:
            SCREAMING_SNAKE_CASE_							=			stream_chunk_s
      else:
            SCREAMING_SNAKE_CASE_							=			chunk_length_s

      SCREAMING_SNAKE_CASE_							=			ffmpeg_microphone(__UpperCAmelCase			,			__UpperCAmelCase			,			format_for_conversion=__UpperCAmelCase							)
      if format_for_conversion == "s16le":
            SCREAMING_SNAKE_CASE_							=			np.intaa
            SCREAMING_SNAKE_CASE_							=			2
      elif format_for_conversion == "f32le":
            SCREAMING_SNAKE_CASE_							=			np.floataa
            SCREAMING_SNAKE_CASE_							=			4
      else:
            raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"							)

      if stride_length_s is None:
            SCREAMING_SNAKE_CASE_							=			chunk_length_s / 6
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * chunk_length_s							)							) * size_of_sample
      if isinstance(__UpperCAmelCase			,			(int, float)							):
            SCREAMING_SNAKE_CASE_							=			[stride_length_s, stride_length_s]

      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * stride_length_s[0]							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * stride_length_s[1]							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			datetime.datetime.now()
      SCREAMING_SNAKE_CASE_							=			datetime.timedelta(seconds=__UpperCAmelCase							)
      for item in chunk_bytes_iter(__UpperCAmelCase			,			__UpperCAmelCase			,			stride=(stride_left, stride_right)			,			stream=__UpperCAmelCase							):
            # Put everything back in numpy scale
            SCREAMING_SNAKE_CASE_							=			np.frombuffer(item['raw']			,			dtype=__UpperCAmelCase							)
            SCREAMING_SNAKE_CASE_							=			(
                item['stride'][0] // size_of_sample,
                item['stride'][1] // size_of_sample,
            )
            SCREAMING_SNAKE_CASE_							=			sampling_rate
            audio_time += delta
            if datetime.datetime.now() > audio_time + 10 * delta:
                  # We're late !! SKIP
                  continue
            yield item

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Optional[Any]			,			__UpperCAmelCase						:	int			,			__UpperCAmelCase						:	Tuple[int, int]			,			__UpperCAmelCase						:	bool = False							)					-> Union[str, Any]:
      SCREAMING_SNAKE_CASE_							=			b''
      SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			stride
      if stride_left + stride_right >= chunk_len:
            raise ValueError(
                f"Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}"							)
      SCREAMING_SNAKE_CASE_							=			0
      for raw in iterator:
            acc += raw
            if stream and len(__UpperCAmelCase							) < chunk_len:
                  SCREAMING_SNAKE_CASE_							=			(_stride_left, 0)
                  yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
            else:
                  while len(__UpperCAmelCase							) >= chunk_len:
                        # We are flushing the accumulator
                        SCREAMING_SNAKE_CASE_							=			(_stride_left, stride_right)
                        SCREAMING_SNAKE_CASE_							=			{'raw': acc[:chunk_len], 'stride': stride}
                        if stream:
                              SCREAMING_SNAKE_CASE_							=			False
                        yield item
                        SCREAMING_SNAKE_CASE_							=			stride_left
                        SCREAMING_SNAKE_CASE_							=			acc[chunk_len - stride_left - stride_right :]
    # Last chunk
      if len(__UpperCAmelCase							) > stride_left:
            SCREAMING_SNAKE_CASE_							=			{'raw': acc, 'stride': (_stride_left, 0)}
            if stream:
                  SCREAMING_SNAKE_CASE_							=			False
            yield item





def 					UpperCAmelCase_							(      __UpperCAmelCase						:	List[str]			,			__UpperCAmelCase						:	int							)					-> Optional[Any]:
      SCREAMING_SNAKE_CASE_							=			2**24  # 16Mo
      try:
            with subprocess.Popen(__UpperCAmelCase			,			stdout=subprocess.PIPE			,			bufsize=__UpperCAmelCase							) as ffmpeg_process:
                  while True:
                        SCREAMING_SNAKE_CASE_							=			ffmpeg_process.stdout.read(__UpperCAmelCase							)
                        if raw == b"":
                              break
                        yield raw
      except FileNotFoundError as error:
            raise ValueError('ffmpeg was not found but is required to stream audio files from filename'							) from error