




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


a_        =       1_6
a_        =       3_2







def      __UpperCAmelCase     ( __UpperCamelCase	,				__UpperCamelCase = 16	):
			__lowercase			:  Dict								=       AutoTokenizer.from_pretrained('''bert-base-cased'''	)
			__lowercase			:  Tuple								=       load_dataset('''glue'''	,				'''mrpc'''	)

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

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

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

			# Instantiate dataloaders.
			__lowercase			:  List[str]								=       DataLoader(
			    tokenized_datasets['''train''']	,				shuffle=UpperCAmelCase_	,				collate_fn=UpperCAmelCase_	,				batch_size=UpperCAmelCase_	)
			__lowercase			:  Optional[Any]								=       DataLoader(
			    tokenized_datasets['''validation''']	,				shuffle=UpperCAmelCase_	,				collate_fn=UpperCAmelCase_	,				batch_size=UpperCAmelCase_	)

			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

			a_        =       mocked_dataloaders  # noqa: F811







def      __UpperCAmelCase     ( __UpperCamelCase	,				__UpperCamelCase	):





			if os.environ.get('''TESTING_MOCKED_DATALOADERS'''	,				UpperCAmelCase_	) == "1":
						__lowercase			:  Dict								=       2
			# New Code #
			__lowercase			:  List[str]								=       int(args.gradient_accumulation_steps	)
			# Initialize accelerator
			__lowercase			:  str								=       Accelerator(
			    cpu=args.cpu	,				mixed_precision=args.mixed_precision	,				gradient_accumulation_steps=UpperCAmelCase_	)
			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
			__lowercase			:  str								=       config['''lr''']
			__lowercase			:  Optional[Any]								=       int(config['''num_epochs''']	)
			__lowercase			:  int								=       int(config['''seed''']	)
			__lowercase			:  Union[str, Any]								=       int(config['''batch_size''']	)

			__lowercase			:  str								=       evaluate.load('''glue'''	,				'''mrpc'''	)

			set_seed(UpperCAmelCase_	)
			__lowercase			,__lowercase			:  Optional[Any]								=       get_dataloaders(UpperCAmelCase_	,				UpperCAmelCase_	)
			# Instantiate the model (we build the model here so that the seed also control new weights initialization)
			__lowercase			:  List[str]								=       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).
			__lowercase			:  Any								=       model.to(accelerator.device	)

			# Instantiate optimizer
			__lowercase			:  List[Any]								=       AdamW(params=model.parameters()	,				lr=UpperCAmelCase_	)

			# Instantiate scheduler
			__lowercase			:  Union[str, Any]								=       get_linear_schedule_with_warmup(
			    optimizer=UpperCAmelCase_	,				num_warmup_steps=1_00	,				num_training_steps=(len(UpperCAmelCase_	) * 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.
			__lowercase			,__lowercase			,__lowercase			,__lowercase			,__lowercase			:  Optional[int]								=       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	)
									# 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(UpperCAmelCase_	):
												__lowercase			:  Dict								=       model(**UpperCAmelCase_	)
												__lowercase			:  int								=       output.loss
												accelerator.backward(UpperCAmelCase_	)
												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():
												__lowercase			:  Optional[int]								=       model(**UpperCAmelCase_	)
									__lowercase			:  Union[str, Any]								=       outputs.logits.argmax(dim=-1	)
									__lowercase			,__lowercase			:  Optional[int]								=       accelerator.gather_for_metrics((predictions, batch['''labels'''])	)
									metric.add_batch(
									    predictions=UpperCAmelCase_	,				references=UpperCAmelCase_	,				)

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







def      __UpperCAmelCase     ( ):
			__lowercase			:  List[str]								=       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.'''	,				)
			# New Code #
			parser.add_argument(
			    '''--gradient_accumulation_steps'''	,				type=UpperCAmelCase_	,				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.'''	)
			__lowercase			:  Any								=       parser.parse_args()
			__lowercase			:  int								=       {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
			training_function(UpperCAmelCase_	,				UpperCAmelCase_	)


if __name__ == "__main__":
			main()








"""simple docstring"""







import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_electra import ElectraTokenizer


UpperCamelCase     =							{"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

UpperCamelCase     =							{
    """vocab_file""": {
        """google/electra-small-generator""": (
            """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt"""
        ),
        """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""",
        """google/electra-large-generator""": (
            """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt"""
        ),
        """google/electra-small-discriminator""": (
            """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt"""
        ),
        """google/electra-base-discriminator""": (
            """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt"""
        ),
        """google/electra-large-discriminator""": (
            """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """google/electra-small-generator""": (
            """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-base-generator""": (
            """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-large-generator""": (
            """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-small-discriminator""": (
            """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json"""
        ),
        """google/electra-base-discriminator""": (
            """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json"""
        ),
        """google/electra-large-discriminator""": (
            """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json"""
        ),
    },
}

UpperCamelCase     =							{
    """google/electra-small-generator""": 512,
    """google/electra-base-generator""": 512,
    """google/electra-large-generator""": 512,
    """google/electra-small-discriminator""": 512,
    """google/electra-base-discriminator""": 512,
    """google/electra-large-discriminator""": 512,
}

UpperCamelCase     =							{
    """google/electra-small-generator""": {"""do_lower_case""": True},
    """google/electra-base-generator""": {"""do_lower_case""": True},
    """google/electra-large-generator""": {"""do_lower_case""": True},
    """google/electra-small-discriminator""": {"""do_lower_case""": True},
    """google/electra-base-discriminator""": {"""do_lower_case""": True},
    """google/electra-large-discriminator""": {"""do_lower_case""": True},
}






class       UpperCamelCase__			(   _lowerCAmelCase      ):

			"""simple docstring"""


			A__	:					Dict							  =     VOCAB_FILES_NAMES
			A__	:					str							  =     PRETRAINED_VOCAB_FILES_MAP
			A__	:					List[Any]							  =     PRETRAINED_INIT_CONFIGURATION
			A__	:					Any							  =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			A__	:					List[str]							  =     ElectraTokenizer


			def __init__(      self						,	SCREAMING_SNAKE_CASE__=None						,	SCREAMING_SNAKE_CASE__=None						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__="[UNK]"						,	SCREAMING_SNAKE_CASE__="[SEP]"						,	SCREAMING_SNAKE_CASE__="[PAD]"						,	SCREAMING_SNAKE_CASE__="[CLS]"						,	SCREAMING_SNAKE_CASE__="[MASK]"						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=None						,	**SCREAMING_SNAKE_CASE__						,	)      ->	str:
				super().__init__(
				    SCREAMING_SNAKE_CASE__						,	tokenizer_file=SCREAMING_SNAKE_CASE__						,	do_lower_case=SCREAMING_SNAKE_CASE__						,	unk_token=SCREAMING_SNAKE_CASE__						,	sep_token=SCREAMING_SNAKE_CASE__						,	pad_token=SCREAMING_SNAKE_CASE__						,	cls_token=SCREAMING_SNAKE_CASE__						,	mask_token=SCREAMING_SNAKE_CASE__						,	tokenize_chinese_chars=SCREAMING_SNAKE_CASE__						,	strip_accents=SCREAMING_SNAKE_CASE__						,	**SCREAMING_SNAKE_CASE__						,	)

				A__											=					json.loads(self.backend_tokenizer.normalizer.__getstate__()		)
				if (
				    normalizer_state.get("lowercase"						,	SCREAMING_SNAKE_CASE__		) != do_lower_case
				    or normalizer_state.get("strip_accents"						,	SCREAMING_SNAKE_CASE__		) != strip_accents
				    or normalizer_state.get("handle_chinese_chars"						,	SCREAMING_SNAKE_CASE__		) != tokenize_chinese_chars
				):
					A__											=					getattr(SCREAMING_SNAKE_CASE__						,	normalizer_state.pop("type"		)		)
					A__											=					do_lower_case
					A__											=					strip_accents
					A__											=					tokenize_chinese_chars
					A__											=					normalizer_class(**SCREAMING_SNAKE_CASE__		)

				A__											=					do_lower_case


			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__=None		)      ->	List[str]:
				A__											=					[self.cls_token_id] + token_ids_a + [self.sep_token_id]

				if token_ids_a:
					output += token_ids_a + [self.sep_token_id]

				return output


			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ = None		)      ->	List[int]:
				A__											=					[self.sep_token_id]
				A__											=					[self.cls_token_id]
				if token_ids_a is None:
					return len(cls + token_ids_a + sep		) * [0]
				return len(cls + token_ids_a + sep		) * [0] + len(token_ids_a + sep		) * [1]







			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ = None		)      ->	Tuple[str]:
				A__											=					self._tokenizer.model.save(SCREAMING_SNAKE_CASE__						,	name=SCREAMING_SNAKE_CASE__		)
				return tuple(SCREAMING_SNAKE_CASE__		)




