


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__  :Union[str, Any]             =							1_6
lowerCAmelCase__  :Tuple             =							3_2

def 	lowerCAmelCase__			(      a__:		Accelerator      ,  a__:		DatasetDict      ,  a__:		List[int]      ,  a__:		List[int]      ,  a__:		int = 1_6	)  ->		int:


							'''simple docstring'''





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

							def tokenize_function(a__:		Any	):
														# max_length=None => use the model max length (it's actually the default)
														_UpperCAmelCase					=      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
							# starting with the main process first:
							with accelerator.main_process_first():
														_UpperCAmelCase					=      datasets.map(
														    a__      ,  batched=a__      ,  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
							_UpperCAmelCase					=      tokenized_datasets.rename_column('label'      ,  'labels'	)

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

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

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

							_UpperCAmelCase					=      DataLoader(
							    tokenized_datasets['test']      ,  shuffle=a__      ,  collate_fn=a__      ,  batch_size=a__	)

							return train_dataloader, eval_dataloader, test_dataloader

def 	lowerCAmelCase__			(      a__:		Any      ,  a__:		List[Any]	)  ->		List[str]:


							'''simple docstring'''





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

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

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

							set_seed(a__	)

							# New Code #
							# Create our folds:
							_UpperCAmelCase					=      kfold.split(np.zeros(datasets['train'].num_rows	)      ,  datasets['train']['label']	)
							_UpperCAmelCase					=      []
							# Iterate over them
							for i, (train_idxs, valid_idxs) in enumerate(a__	):
														_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase					=      get_fold_dataloaders(
														    a__      ,  a__      ,  a__      ,  a__      ,  )
														# Instantiate the model (we build the model here so that the seed also control new weights initialization)
														_UpperCAmelCase					=      AutoModelForSequenceClassification.from_pretrained('bert-base-cased'      ,  return_dict=a__	)

														# 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).
														_UpperCAmelCase					=      model.to(accelerator.device	)

														# Instantiate optimizer
														_UpperCAmelCase					=      AdamW(params=model.parameters()      ,  lr=a__	)

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

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

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

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

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

def 	lowerCAmelCase__			(      )  ->		List[str]:


							'''simple docstring'''





							_UpperCAmelCase					=      argparse.ArgumentParser(description='Simple example of training script.'	)
							parser.add_argument(
							    '--mixed_precision'      ,  type=a__      ,  default=a__      ,  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=a__      ,  default=3      ,  help='The number of splits to perform across the dataset'	)
							_UpperCAmelCase					=      parser.parse_args()
							_UpperCAmelCase					=      {'lr': 2e-5, 'num_epochs': 3, 'seed': 4_2, 'batch_size': 1_6}
							training_function(a__      ,  a__	)


if __name__ == "__main__":
		main()




# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import subprocess

from packaging.version import Version, parse

from accelerate.commands.config.config_args import default_config_file, load_config_from_file


lowerCAmelCase__  :Dict             =							'''Run commands across TPU VMs for initial setup before running `accelerate launch`.'''

def 	lowerCAmelCase__			(      a__:		Optional[Any]=None	)  ->		List[Any]:


							'''simple docstring'''





							if subparsers is not None:
														_UpperCAmelCase					=      subparsers.add_parser('tpu-config'      ,  description=_description	)
							else:
														_UpperCAmelCase					=      argparse.ArgumentParser('Accelerate tpu-config command'      ,  description=_description	)
							# Core arguments
							_UpperCAmelCase					=      parser.add_argument_group(
							    'Config Arguments'      ,  'Arguments that can be configured through `accelerate config`.'	)
							config_args.add_argument(
							    '--config_file'      ,  type=a__      ,  default=a__      ,  help='Path to the config file to use for accelerate.'      ,  )
							config_args.add_argument(
							    '--tpu_name'      ,  default=a__      ,  help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.'      ,  )
							config_args.add_argument(
							    '--tpu_zone'      ,  default=a__      ,  help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.'      ,  )
							_UpperCAmelCase					=      parser.add_argument_group('TPU Arguments'      ,  'Arguments for options ran inside the TPU.'	)
							pod_args.add_argument(
							    '--use_alpha'      ,  action='store_true'      ,  help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.'      ,  )
							pod_args.add_argument(
							    '--command_file'      ,  default=a__      ,  help='The path to the file containing the commands to run on the pod on startup.'      ,  )
							pod_args.add_argument(
							    '--command'      ,  action='append'      ,  nargs='+'      ,  help='A command to run on the pod. Can be passed multiple times.'      ,  )
							pod_args.add_argument(
							    '--install_accelerate'      ,  action='store_true'      ,  help='Whether to install accelerate on the pod. Defaults to False.'      ,  )
							pod_args.add_argument(
							    '--accelerate_version'      ,  default='latest'      ,  help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.'      ,  )
							pod_args.add_argument(
							    '--debug'      ,  action='store_true'      ,  help='If set, will print the command that would be run instead of running it.'	)

							if subparsers is not None:
														parser.set_defaults(func=a__	)
							return parser

def 	lowerCAmelCase__			(      a__:		str	)  ->		Any:


							'''simple docstring'''





							_UpperCAmelCase					=      None

							# Get the default from the config file if it exists.
							if args.config_file is not None or os.path.isfile(a__	):
														_UpperCAmelCase					=      load_config_from_file(args.config_file	)
														if not args.command_file and defaults.command_file is not None and not args.command:
																					_UpperCAmelCase					=      defaults.command_file
														if not args.command and defaults.commands is not None:
																					_UpperCAmelCase					=      defaults.commands
														if not args.tpu_name:
																					_UpperCAmelCase					=      defaults.tpu_name
														if not args.tpu_zone:
																					_UpperCAmelCase					=      defaults.tpu_zone
							if args.accelerate_version == "dev":
														_UpperCAmelCase					=      'git+https://github.com/huggingface/accelerate.git'
							elif args.accelerate_version == "latest":
														_UpperCAmelCase					=      'accelerate -U'
							elif isinstance(parse(args.accelerate_version	)      ,  a__	):
														_UpperCAmelCase					=      F'''accelerate=={args.accelerate_version}'''

							if not args.command_file and not args.command:
														raise ValueError('You must specify either a command file or a command to run on the pod.'	)

							if args.command_file:
														with open(args.command_file      ,  'r'	) as f:
																					_UpperCAmelCase					=      [f.read().splitlines()]

    # To turn list of lists into list of strings
							if isinstance(args.command[0]      ,  a__	):
														_UpperCAmelCase					=      [line for cmd in args.command for line in cmd]
							# Default to the shared folder and install accelerate
							_UpperCAmelCase					=      ['cd /usr/share']
							if args.install_accelerate:
														new_cmd += [F'''pip install {args.accelerate_version}''']
							new_cmd += args.command
							_UpperCAmelCase					=      '; '.join(a__	)

							# Then send it to gcloud
							# Eventually try to use google-api-core to do this instead of subprocess
							_UpperCAmelCase					=      ['gcloud']
							if args.use_alpha:
														cmd += ["alpha"]
							cmd += [
							    "compute",
							    "tpus",
							    "tpu-vm",
							    "ssh",
							    args.tpu_name,
							    "--zone",
							    args.tpu_zone,
							    "--command",
							    args.command,
							    "--worker",
							    "all",
							]
							if args.debug:
														print(F'''Running {" ".join(a__	)}'''	)
														return
							subprocess.run(a__	)
							print('Successfully setup pod.'	)







def 	lowerCAmelCase__			(      )  ->		Optional[Any]:


							'''simple docstring'''





							_UpperCAmelCase					=      tpu_command_parser()
							_UpperCAmelCase					=      parser.parse_args()

							tpu_command_launcher(a__	)
