




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


########################################################################
# This is a fully working simple example to use Accelerate
# and perform 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
#
########################################################################


_SCREAMING_SNAKE_CASE							:       Dict						=			16
_SCREAMING_SNAKE_CASE							:       Optional[int]						=			32


def 					UpperCamelCase_(     snake_case							:	Accelerator							,    snake_case							:	int = 1_6					):

							'''simple docstring'''






							snake_case_      =				AutoTokenizer.from_pretrained("bert-base-cased"					)
							snake_case_      =				load_dataset("glue"							,    "mrpc"					)

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

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

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

							# Instantiate dataloaders.
							snake_case_      =				DataLoader(
							    tokenized_datasets["train"]							,    shuffle=snake_case							,    collate_fn=snake_case							,    batch_size=snake_case					)
							snake_case_      =				DataLoader(
							    tokenized_datasets["validation"]							,    shuffle=snake_case							,    collate_fn=snake_case							,    batch_size=snake_case					)

							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

		_SCREAMING_SNAKE_CASE							:       List[str]						=			mocked_dataloaders  # noqa: F811


def 					UpperCamelCase_(     snake_case							:	str							,    snake_case							:	Optional[int]					):

							'''simple docstring'''






							if os.environ.get("TESTING_MOCKED_DATALOADERS"							,    snake_case					) == "1":
														snake_case_      =				2
							# New Code #
							snake_case_      =				int(args.gradient_accumulation_steps					)
							# Initialize accelerator
							snake_case_      =				Accelerator(
							    cpu=args.cpu							,    mixed_precision=args.mixed_precision							,    gradient_accumulation_steps=snake_case					)
							if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1:
														raise NotImplementedError(
														    "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`"					)
							# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
							snake_case_      =				config["lr"]
							snake_case_      =				int(config["num_epochs"]					)
							snake_case_      =				int(config["seed"]					)
							snake_case_      =				int(config["batch_size"]					)

							snake_case_      =				evaluate.load("glue"							,    "mrpc"					)

							set_seed(snake_case					)
							snake_case_ ,				snake_case_      =				get_dataloaders(snake_case							,    snake_case					)
							# Instantiate the model (we build the model here so that the seed also control new weights initialization)
							snake_case_      =				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).
							snake_case_      =				model.to(accelerator.device					)

							# Instantiate optimizer
							snake_case_      =				AdamW(params=model.parameters()							,    lr=snake_case					)

							# Instantiate scheduler
							snake_case_      =				get_linear_schedule_with_warmup(
							    optimizer=snake_case							,    num_warmup_steps=1_0_0							,    num_training_steps=(len(snake_case					) * 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.
							snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_      =				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					)
																					# 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(snake_case					):
																												snake_case_      =				model(**snake_case					)
																												snake_case_      =				output.loss
																												accelerator.backward(snake_case					)
																												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():
																												snake_case_      =				model(**snake_case					)
																					snake_case_      =				outputs.logits.argmax(dim=-1					)
																					snake_case_ ,				snake_case_      =				accelerator.gather_for_metrics((predictions, batch["labels"])					)
																					metric.add_batch(
																					    predictions=snake_case							,    references=snake_case							,    )

														snake_case_      =				metric.compute()
														# Use accelerator.print to print only on the main process.
														accelerator.print(f'epoch {epoch}:'							,    snake_case					)


def 					UpperCamelCase_(     ):

							'''simple docstring'''






							snake_case_      =				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."							,    )
							# New Code #
							parser.add_argument(
							    "--gradient_accumulation_steps"							,    type=snake_case							,    default=1							,    help="The number of minibatches to be ran before gradients are accumulated."							,    )
							parser.add_argument("--cpu"							,    action="store_true"							,    help="If passed, will train on the CPU."					)
							snake_case_      =				parser.parse_args()
							snake_case_      =				{"lr": 2e-5, "num_epochs": 3, "seed": 4_2, "batch_size": 1_6}
							training_function(snake_case							,    snake_case					)


if __name__ == "__main__":
		main()










'''simple docstring'''





import os

import torch

from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version


if is_torch_version(">=", FSDP_PYTORCH_VERSION):
		import torch.distributed.checkpoint as dist_cp
		from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
		from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
		from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
		from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType


_SCREAMING_SNAKE_CASE							:       Tuple						=			get_logger(__name__)


def 					UpperCamelCase_(     snake_case							:	Optional[Any]							,    snake_case							:	Optional[Any]							,    snake_case							:	Optional[Any]							,    snake_case							:	int							,    snake_case							:	List[Any]=0					):

							'''simple docstring'''






							os.makedirs(snake_case							,    exist_ok=snake_case					)
							with FSDP.state_dict_type(
							    snake_case							,    fsdp_plugin.state_dict_type							,    fsdp_plugin.state_dict_config							,    fsdp_plugin.optim_state_dict_config					):
														snake_case_      =				model.state_dict()
														if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
																					snake_case_      =				f'{MODEL_NAME}.bin' if model_index == 0 else f'{MODEL_NAME}_{model_index}.bin'
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					if accelerator.process_index == 0:
																												logger.info(f'Saving model to {output_model_file}'					)
																												torch.save(snake_case							,    snake_case					)
																												logger.info(f'Model saved to {output_model_file}'					)
														elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
																					snake_case_      =				(
																					    f'{MODEL_NAME}_rank{accelerator.process_index}.bin'
																					    if model_index == 0
																					    else f'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'
																					)
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					logger.info(f'Saving model to {output_model_file}'					)
																					torch.save(snake_case							,    snake_case					)
																					logger.info(f'Model saved to {output_model_file}'					)
														elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
																					snake_case_      =				os.path.join(snake_case							,    f'{MODEL_NAME}_{model_index}'					)
																					os.makedirs(snake_case							,    exist_ok=snake_case					)
																					logger.info(f'Saving model to {ckpt_dir}'					)
																					snake_case_      =				{"model": state_dict}

																					dist_cp.save_state_dict(
																					    state_dict=snake_case							,    storage_writer=dist_cp.FileSystemWriter(snake_case					)							,    planner=DefaultSavePlanner()							,    )
																					logger.info(f'Model saved to {ckpt_dir}'					)


def 					UpperCamelCase_(     snake_case							:	Optional[int]							,    snake_case							:	Optional[Any]							,    snake_case							:	int							,    snake_case							:	Union[str, Any]							,    snake_case							:	Any=0					):

							'''simple docstring'''






							accelerator.wait_for_everyone()
							with FSDP.state_dict_type(
							    snake_case							,    fsdp_plugin.state_dict_type							,    fsdp_plugin.state_dict_config							,    fsdp_plugin.optim_state_dict_config					):
														if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
																					if type(snake_case					) != FSDP and accelerator.process_index != 0:
																												if not fsdp_plugin.sync_module_states:
																																			raise ValueError(
																																			    "Set the `sync_module_states` flag to `True` so that model states are synced across processes when "
																																			    "initializing FSDP object"					)
																												return
																					snake_case_      =				f'{MODEL_NAME}.bin' if model_index == 0 else f'{MODEL_NAME}_{model_index}.bin'
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					logger.info(f'Loading model from {input_model_file}'					)
																					snake_case_      =				torch.load(snake_case					)
																					logger.info(f'Model loaded from {input_model_file}'					)
														elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
																					snake_case_      =				(
																					    f'{MODEL_NAME}_rank{accelerator.process_index}.bin'
																					    if model_index == 0
																					    else f'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'
																					)
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					logger.info(f'Loading model from {input_model_file}'					)
																					snake_case_      =				torch.load(snake_case					)
																					logger.info(f'Model loaded from {input_model_file}'					)
														elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
																					snake_case_      =				(
																					    os.path.join(snake_case							,    f'{MODEL_NAME}_{model_index}'					)
																					    if f'{MODEL_NAME}' not in input_dir
																					    else input_dir
																					)
																					logger.info(f'Loading model from {ckpt_dir}'					)
																					snake_case_      =				{"model": model.state_dict()}
																					dist_cp.load_state_dict(
																					    state_dict=snake_case							,    storage_reader=dist_cp.FileSystemReader(snake_case					)							,    planner=DefaultLoadPlanner()							,    )
																					snake_case_      =				state_dict["model"]
																					logger.info(f'Model loaded from {ckpt_dir}'					)
														model.load_state_dict(snake_case					)


def 					UpperCamelCase_(     snake_case							:	str							,    snake_case							:	List[str]							,    snake_case							:	Any							,    snake_case							:	Tuple							,    snake_case							:	Optional[Any]							,    snake_case							:	Tuple=0					):

							'''simple docstring'''






							os.makedirs(snake_case							,    exist_ok=snake_case					)
							with FSDP.state_dict_type(
							    snake_case							,    fsdp_plugin.state_dict_type							,    fsdp_plugin.state_dict_config							,    fsdp_plugin.optim_state_dict_config					):
														snake_case_      =				FSDP.optim_state_dict(snake_case							,    snake_case					)
														if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
																					if accelerator.process_index == 0:
																												snake_case_      =				(
																												    f'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else f'{OPTIMIZER_NAME}_{optimizer_index}.bin'
																												)
																												snake_case_      =				os.path.join(snake_case							,    snake_case					)
																												logger.info(f'Saving Optimizer state to {output_optimizer_file}'					)
																												torch.save(snake_case							,    snake_case					)
																												logger.info(f'Optimizer state saved in {output_optimizer_file}'					)
														else:
																					snake_case_      =				os.path.join(snake_case							,    f'{OPTIMIZER_NAME}_{optimizer_index}'					)
																					os.makedirs(snake_case							,    exist_ok=snake_case					)
																					logger.info(f'Saving Optimizer state to {ckpt_dir}'					)
																					dist_cp.save_state_dict(
																					    state_dict={"optimizer": optim_state}							,    storage_writer=dist_cp.FileSystemWriter(snake_case					)							,    planner=DefaultSavePlanner()							,    )
																					logger.info(f'Optimizer state saved in {ckpt_dir}'					)




def 					UpperCamelCase_(     snake_case							:	Optional[Any]							,    snake_case							:	List[str]							,    snake_case							:	Union[str, Any]							,    snake_case							:	int							,    snake_case							:	Optional[int]							,    snake_case							:	Union[str, Any]=0					):

							'''simple docstring'''






							accelerator.wait_for_everyone()
							with FSDP.state_dict_type(
							    snake_case							,    fsdp_plugin.state_dict_type							,    fsdp_plugin.state_dict_config							,    fsdp_plugin.optim_state_dict_config					):
														if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
																					snake_case_      =				None
																					# below check should work but currently it isn't working (mostly opytorch issue),
																					# in the meantime disabling it at the cost of excess memory usage
																					# if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
																					snake_case_      =				(
																					    f'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else f'{OPTIMIZER_NAME}_{optimizer_index}.bin'
																					)
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					logger.info(f'Loading Optimizer state from {input_optimizer_file}'					)
																					snake_case_      =				torch.load(snake_case					)
																					logger.info(f'Optimizer state loaded from {input_optimizer_file}'					)
														else:
																					snake_case_      =				(
																					    os.path.join(snake_case							,    f'{OPTIMIZER_NAME}_{optimizer_index}'					)
																					    if f'{OPTIMIZER_NAME}' not in input_dir
																					    else input_dir
																					)
																					logger.info(f'Loading Optimizer from {ckpt_dir}'					)
																					snake_case_      =				load_sharded_optimizer_state_dict(
																					    model_state_dict=model.state_dict()							,    optimizer_key="optimizer"							,    storage_reader=dist_cp.FileSystemReader(snake_case					)							,    )
																					snake_case_      =				optim_state["optimizer"]
																					logger.info(f'Optimizer loaded from {ckpt_dir}'					)
														snake_case_      =				FSDP.optim_state_dict_to_load(snake_case							,    snake_case							,    snake_case					)
														optimizer.load_state_dict(snake_case					)




