





import argparse
import json
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
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler


A   : List[str]			=			1_6
A   : Dict			=			3_2







def        __lowerCamelCase (							__a       :Accelerator   ,					__a       :int = 1_6   ,					__a       :str = "bert-base-cased"   )		->    Union[str, Any]:






		"""simple docstring"""

		A__  				=       AutoTokenizer.from_pretrained(lowercase__   )
		A__  				=       load_dataset("""glue"""   ,					"""mrpc"""   )

		def tokenize_function(__a       :List[str]   ):
				# max_length=None => use the model max length (it's actually the default)
				A__  				=       tokenizer(examples["""sentence1"""]   ,					examples["""sentence2"""]   ,					truncation=lowercase__   ,					max_length=lowercase__   )
				return outputs

		# Apply the method we just defined to all the examples in all the splits of the dataset
		A__  				=       datasets.map(
		    lowercase__   ,					batched=lowercase__   ,					remove_columns=["""idx""", """sentence1""", """sentence2"""]   ,					load_from_cache_file=lowercase__   )

		# 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(__a       :Union[str, Any]   ):
				# On TPU it's best to pad everything to the same length or training will be very slow.
				if accelerator.distributed_type == DistributedType.TPU:
						return tokenizer.pad(lowercase__   ,					padding="""max_length"""   ,					max_length=1_2_8   ,					return_tensors="""pt"""   )
				return tokenizer.pad(lowercase__   ,					padding="""longest"""   ,					return_tensors="""pt"""   )

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

		return train_dataloader, eval_dataloader







def        __lowerCamelCase (							__a       :Optional[Any]   ,					__a       :Union[str, Any]   ,					__a       :Tuple   ,					__a       :int   )		->    List[str]:






		"""simple docstring"""

		model.eval()
		A__  				=       0
		for step, batch in enumerate(lowercase__   ):
				# We could avoid this line since we set the accelerator with `device_placement=True`.
				batch.to(accelerator.device   )
				with torch.no_grad():
						A__  				=       model(**lowercase__   )
				A__  				=       outputs.logits.argmax(dim=-1   )
				# It is slightly faster to call this once, than multiple times
				A__  				=       accelerator.gather(
				    (predictions, batch["""labels"""])   )  # If we are in a multiprocess environment, the last batch has duplicates
				if accelerator.use_distributed:
						if step == len(lowercase__   ) - 1:
								A__  				=       predictions[: len(eval_dataloader.dataset   ) - samples_seen]
								A__  				=       references[: len(eval_dataloader.dataset   ) - samples_seen]
						else:
								samples_seen += references.shape[0]
				metric.add_batch(
				    predictions=lowercase__   ,					references=lowercase__   ,					)

		A__  				=       metric.compute()
		return eval_metric["accuracy"]







def        __lowerCamelCase (							__a       :str   ,					__a       :List[str]   )		->    Any:






		"""simple docstring"""

		A__  				=       Accelerator()

		# 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__  				=       args.model_name_or_path

		set_seed(lowercase__   )
		A__  				=       get_dataloaders(lowercase__   ,					lowercase__   ,					lowercase__   )

		# Instantiate the model (we build the model here so that the seed also control new weights initialization)
		A__  				=       AutoModelForSequenceClassification.from_pretrained(lowercase__   ,					return_dict=lowercase__   )

		# Instantiate optimizer
		A__  				=       (
		    AdamW
		    if accelerator.state.deepspeed_plugin is None
		    or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config
		    else DummyOptim
		)
		A__  				=       optimizer_cls(params=model.parameters()   ,					lr=lowercase__   )

		if accelerator.state.deepspeed_plugin is not None:
				A__  				=       accelerator.state.deepspeed_plugin.deepspeed_config[
				    """gradient_accumulation_steps"""
				]
		else:
				A__  				=       1
		A__  				=       (len(lowercase__   ) * num_epochs) // gradient_accumulation_steps

		# Instantiate scheduler
		if (
		    accelerator.state.deepspeed_plugin is None
		    or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
		):
				A__  				=       get_linear_schedule_with_warmup(
				    optimizer=lowercase__   ,					num_warmup_steps=0   ,					num_training_steps=lowercase__   ,					)
		else:
				A__  				=       DummyScheduler(lowercase__   ,					total_num_steps=lowercase__   ,					warmup_num_steps=0   )

		# 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__  				=       accelerator.prepare(
		    lowercase__   ,					lowercase__   ,					lowercase__   ,					lowercase__   ,					lowercase__   )

		# We need to keep track of how many total steps we have iterated over
		A__  				=       0
		# We also need to keep track of the stating epoch so files are named properly
		A__  				=       0
		A__  				=       evaluate.load("""glue"""   ,					"""mrpc"""   )
		A__  				=       num_epochs

		if args.partial_train_epoch is not None:
				A__  				=       args.partial_train_epoch

		if args.resume_from_checkpoint:
				accelerator.load_state(args.resume_from_checkpoint   )
				A__  				=       args.resume_from_checkpoint.split("""epoch_"""   )[1]
				A__  				=       """"""
				for char in epoch_string:
						if char.isdigit():
								state_epoch_num += char
						else:
								break
				A__  				=       int(lowercase__   ) + 1
				A__  				=       evaluation_loop(lowercase__   ,					lowercase__   ,					lowercase__   ,					lowercase__   )
				accelerator.print("""resumed checkpoint performance:"""   ,					lowercase__   )
				accelerator.print("""resumed checkpoint's scheduler's lr:"""   ,					lr_scheduler.get_lr()[0]   )
				accelerator.print("""resumed optimizers's lr:"""   ,					optimizer.param_groups[0]["""lr"""]   )
				with open(os.path.join(args.output_dir   ,					F'state_{starting_epoch-1}.json'   )   ,					"""r"""   ) as f:
						A__  				=       json.load(lowercase__   )
						assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed"
						assert (
						    resumed_state["lr"] == lr_scheduler.get_lr()[0]
						), "Scheduler learning rate mismatch, loading from checkpoint failed"
						assert (
						    resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"]
						), "Optimizer learning rate mismatch, loading from checkpoint failed"
						assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed"
						return

    # Now we train the model
		A__  				=       {}
		for epoch in range(lowercase__   ,					lowercase__   ):
				model.train()
				for step, batch in enumerate(lowercase__   ):
						A__  				=       model(**lowercase__   )
						A__  				=       outputs.loss
						A__  				=       loss / gradient_accumulation_steps
						accelerator.backward(lowercase__   )
						if step % gradient_accumulation_steps == 0:
								optimizer.step()
								lr_scheduler.step()
								optimizer.zero_grad()

						overall_step += 1
				A__  				=       F'epoch_{epoch}'
				A__  				=       os.path.join(args.output_dir   ,					lowercase__   )
				accelerator.save_state(lowercase__   )
				A__  				=       evaluation_loop(lowercase__   ,					lowercase__   ,					lowercase__   ,					lowercase__   )
				A__  				=       accuracy
				A__  				=       lr_scheduler.get_lr()[0]
				A__  				=       optimizer.param_groups[0]["""lr"""]
				A__  				=       epoch
				A__  				=       overall_step
				accelerator.print(F'epoch {epoch}:'   ,					lowercase__   )

				accelerator.wait_for_everyone()
				if accelerator.is_main_process:
						with open(os.path.join(args.output_dir   ,					F'state_{epoch}.json'   )   ,					"""w"""   ) as f:
								json.dump(lowercase__   ,					lowercase__   )







def        __lowerCamelCase (							)		->    int:






		"""simple docstring"""

		A__  				=       argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage."""   )
		parser.add_argument(
		    """--model_name_or_path"""   ,					type=lowercase__   ,					default="""bert-base-cased"""   ,					help="""Path to pretrained model or model identifier from huggingface.co/models."""   ,					required=lowercase__   ,					)
		parser.add_argument(
		    """--output_dir"""   ,					type=lowercase__   ,					default="""."""   ,					help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory."""   ,					)
		parser.add_argument(
		    """--resume_from_checkpoint"""   ,					type=lowercase__   ,					default=lowercase__   ,					help="""If the training should continue from a checkpoint folder."""   ,					)
		parser.add_argument(
		    """--partial_train_epoch"""   ,					type=lowercase__   ,					default=lowercase__   ,					help="""If passed, the training will stop after this number of epochs."""   ,					)
		parser.add_argument(
		    """--num_epochs"""   ,					type=lowercase__   ,					default=2   ,					help="""Number of train epochs."""   ,					)
		A__  				=       parser.parse_args()
		A__  				=       {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 4_2, """batch_size""": 1_6}

		training_function(lowercase__   ,					lowercase__   )


if __name__ == "__main__":
					main()










import os
import re
import shutil
import sys
import tempfile
import unittest

import black


A   : Dict			=				os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
A   : Optional[int]			=				'''    def __init__(self, config):
        super().__init__()
        self.transform = BertPredictionHeadTransform(config)

        # The output weights are the same as the input embeddings, but there is
        # an output-only bias for each token.
        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        self.bias = nn.Parameter(torch.zeros(config.vocab_size))

        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
        self.decoder.bias = self.bias

    def forward(self, hidden_states):
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states)
        return hidden_states
'''


class   A      (unittest.TestCase   ):
			'''simple docstring'''




			def        a_	(      self       :   Union[str, Any]       )     ->     List[str]:







					"""simple docstring"""






					A__  				=       tempfile.mkdtemp()
					os.makedirs(os.path.join(self.transformer_dir							,     """models/bert/"""       )       )
					A__  				=       self.transformer_dir
					shutil.copy(
					    os.path.join(__lowerCAmelCase							,     """src/transformers/models/bert/modeling_bert.py"""       )							,     os.path.join(self.transformer_dir							,     """models/bert/modeling_bert.py"""       )							,     )






			def        a_	(      self       :   str       )     ->     Optional[int]:







					"""simple docstring"""






					A__  				=       """src/transformers"""
					shutil.rmtree(self.transformer_dir       )






			def        a_	(      self       :   List[str]							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   Optional[int]							,     __lowerCAmelCase       :   int							,     __lowerCAmelCase       :   Tuple=None       )     ->     Dict:







					"""simple docstring"""






					A__  				=       comment + f'\nclass {class_name}(nn.Module):\n' + class_code
					if overwrite_result is not None:
							A__  				=       comment + f'\nclass {class_name}(nn.Module):\n' + overwrite_result
					A__  				=       black.Mode(target_versions={black.TargetVersion.PYaa}							,     line_length=1_19       )
					A__  				=       black.format_str(__lowerCAmelCase							,     mode=__lowerCAmelCase       )
					A__  				=       os.path.join(self.transformer_dir							,     """new_code.py"""       )
					with open(__lowerCAmelCase							,     """w"""							,     newline="""\n"""       ) as f:
							f.write(__lowerCAmelCase       )
					if overwrite_result is None:
							self.assertTrue(len(check_copies.is_copy_consistent(__lowerCAmelCase       )       ) == 0       )
					else:
							check_copies.is_copy_consistent(f.name							,     overwrite=__lowerCAmelCase       )
							with open(__lowerCAmelCase							,     """r"""       ) as f:
									self.assertTrue(f.read()							,     __lowerCAmelCase       )






			def        a_	(      self       :   Tuple       )     ->     List[Any]:







					"""simple docstring"""






					A__  				=       check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead"""       )
					self.assertEqual(__lowerCAmelCase							,     __lowerCAmelCase       )






			def        a_	(      self       :   Tuple       )     ->     Any:







					"""simple docstring"""






					self.check_copy_consistency(
					    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"""							,     """BertLMPredictionHead"""							,     REFERENCE_CODE + """\n"""							,     )

					# With no empty line at the end
					self.check_copy_consistency(
					    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"""							,     """BertLMPredictionHead"""							,     __lowerCAmelCase							,     )

					# Copy consistency with rename
					self.check_copy_consistency(
					    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"""							,     """TestModelLMPredictionHead"""							,     re.sub("""Bert"""							,     """TestModel"""							,     __lowerCAmelCase       )							,     )

					# Copy consistency with a really long name
					A__  				=       """TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"""
					self.check_copy_consistency(
					    f'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}'							,     f'{long_class_name}LMPredictionHead'							,     re.sub("""Bert"""							,     __lowerCAmelCase							,     __lowerCAmelCase       )							,     )

					# Copy consistency with overwrite
					self.check_copy_consistency(
					    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"""							,     """TestModelLMPredictionHead"""							,     __lowerCAmelCase							,     overwrite_result=re.sub("""Bert"""							,     """TestModel"""							,     __lowerCAmelCase       )							,     )







			def        a_	(      self       :   Optional[int]       )     ->     Optional[int]:







					"""simple docstring"""






					A__  				=       check_copies.LOCALIZED_READMES["""README_zh-hans.md"""]

					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"""
					    """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"""
					    """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"""
					    """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."""
					    """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"""
					    """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"""
					    """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"""
					    """ method has been applied to compress GPT2 into"""
					    """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"""
					    """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"""
					    """ Multilingual BERT into"""
					    """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"""
					    """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"""
					    """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"""
					    """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"""
					    """ Luong, Quoc V. Le, Christopher D. Manning."""
					)
					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
					    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
					    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
					    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
					)
					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
					    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
					    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
					    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."""
					    """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"""
					    """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"""
					    """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"""
					    """ method has been applied to compress GPT2 into"""
					    """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"""
					    """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"""
					    """ Multilingual BERT into"""
					    """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"""
					    """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"""
					    """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"""
					    """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"""
					    """ Christopher D. Manning 发布。\n"""
					)

					A__				,      A__  				=       check_copies.convert_to_localized_md(
					    __lowerCAmelCase							,     __lowerCAmelCase							,     localized_readme["""format_model_list"""]       )

					self.assertFalse(__lowerCAmelCase       )
					self.assertEqual(__lowerCAmelCase							,     __lowerCAmelCase       )

					A__				,      A__  				=       check_copies.convert_to_localized_md(
					    __lowerCAmelCase							,     __lowerCAmelCase							,     localized_readme["""format_model_list"""]       )

					# Check whether the number of models is equal to README.md after conversion.
					self.assertTrue(__lowerCAmelCase       )

					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"""
					    """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"""
					    """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"""
					    """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."""
					)
					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"""
					    """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
					    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
					    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
					)
					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
					    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
					    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
					    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
					)

					A__				,      A__  				=       check_copies.convert_to_localized_md(
					    __lowerCAmelCase							,     __lowerCAmelCase							,     localized_readme["""format_model_list"""]       )

					# Check if the model link is synchronized.
					self.assertEqual(__lowerCAmelCase							,     __lowerCAmelCase       )



