


import unittest

from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


UpperCamelCase__   : Optional[int]					  = get_tests_dir("""fixtures/spiece.model""")







@require_sentencepiece
@require_tokenizers
class   _UpperCamelCase  (       A_						,       unittest.TestCase  ):







					'''simple docstring'''

					lowerCamelCase     :     str			    =       AlbertTokenizer
					lowerCamelCase     :     str			    =       AlbertTokenizerFast
					lowerCamelCase     :     Any			    =       True
					lowerCamelCase     :     Dict			    =       True
					lowerCamelCase     :     Tuple			    =       True





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						super().setUp()

						# We have a SentencePiece fixture for testing
						UpperCAmelCase_								=     AlbertTokenizer(__lowercase		)
						tokenizer.save_pretrained(self.tmpdirname		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any] ,					__lowercase    :  Tuple		):






						'''simple docstring'''







						UpperCAmelCase_								=     """this is a test"""
						UpperCAmelCase_								=     """this is a test"""
						return input_text, output_text





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     """<pad>"""
						UpperCAmelCase_								=     0

						self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase		) ,					__lowercase		)
						self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase		) ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     list(self.get_tokenizer().get_vocab().keys()		)

						self.assertEqual(vocab_keys[0] ,					"""<pad>"""		)
						self.assertEqual(vocab_keys[1] ,					"""<unk>"""		)
						self.assertEqual(vocab_keys[-1] ,					"""▁eloquent"""		)
						self.assertEqual(len(__lowercase		) ,					3_00_00		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						self.assertEqual(self.get_tokenizer().vocab_size ,					3_00_00		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any]		):






						'''simple docstring'''







						if not self.test_rust_tokenizer:
							return

						UpperCAmelCase_								=     self.get_tokenizer()
						UpperCAmelCase_								=     self.get_rust_tokenizer()

						UpperCAmelCase_								=     """I was born in 92000, and this is falsé."""

						UpperCAmelCase_								=     tokenizer.tokenize(__lowercase		)
						UpperCAmelCase_								=     rust_tokenizer.tokenize(__lowercase		)
						self.assertListEqual(__lowercase ,					__lowercase		)

						UpperCAmelCase_								=     tokenizer.encode(__lowercase ,					add_special_tokens=__lowercase		)
						UpperCAmelCase_								=     rust_tokenizer.encode(__lowercase ,					add_special_tokens=__lowercase		)
						self.assertListEqual(__lowercase ,					__lowercase		)

						UpperCAmelCase_								=     self.get_rust_tokenizer()
						UpperCAmelCase_								=     tokenizer.encode(__lowercase		)
						UpperCAmelCase_								=     rust_tokenizer.encode(__lowercase		)
						self.assertListEqual(__lowercase ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     AlbertTokenizer(__lowercase ,					keep_accents=__lowercase		)

						UpperCAmelCase_								=     tokenizer.tokenize("""This is a test"""		)
						self.assertListEqual(__lowercase ,					["""▁this""", """▁is""", """▁a""", """▁test"""]		)

						self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowercase		) ,					[48, 25, 21, 12_89]		)

						UpperCAmelCase_								=     tokenizer.tokenize("""I was born in 92000, and this is falsé."""		)
						self.assertListEqual(
						    __lowercase ,					["""▁i""", """▁was""", """▁born""", """▁in""", """▁9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """é""", """."""]		)
						UpperCAmelCase_								=     tokenizer.convert_tokens_to_ids(__lowercase		)
						self.assertListEqual(__lowercase ,					[31, 23, 3_86, 19, 5_61, 30_50, 15, 17, 48, 25, 82_56, 18, 1, 9]		)

						UpperCAmelCase_								=     tokenizer.convert_ids_to_tokens(__lowercase		)
						self.assertListEqual(
						    __lowercase ,					["""▁i""", """▁was""", """▁born""", """▁in""", """▁9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """<unk>""", """."""] ,					)





					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						UpperCAmelCase_								=     AlbertTokenizer(__lowercase		)

						UpperCAmelCase_								=     tokenizer.encode("""sequence builders"""		)
						UpperCAmelCase_								=     tokenizer.encode("""multi-sequence build"""		)

						UpperCAmelCase_								=     tokenizer.build_inputs_with_special_tokens(__lowercase		)
						UpperCAmelCase_								=     tokenizer.build_inputs_with_special_tokens(__lowercase ,					__lowercase		)

						assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
						assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
						    tokenizer.sep_token_id
						]





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     {"""attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """input_ids""": [[2, 2_19_70, 13, 5, 60_92, 1_67, 28, 71_03, 21_53, 6_73, 8, 70_28, 1_20_51, 18, 17, 71_03, 21_53, 6_73, 8, 35_15, 1_86_84, 8, 44_61, 6, 19_27, 2_97, 8, 1_20_60, 26_07, 18, 13, 5, 44_61, 15, 1_05_38, 38, 8, 1_35, 15, 8_22, 58, 15, 9_93, 1_03_63, 15, 14_60, 80_05, 44_61, 15, 9_93, 2_55, 23_28, 9, 9, 9, 6, 26, 11_12, 8_16, 32_60, 13, 5, 1_03, 23_77, 6, 17, 11_12, 8_16, 27_82, 13, 5, 1_03, 1_06_41, 6, 29, 84, 25_12, 24_30, 7_82, 1_86_84, 27_61, 19, 8_08, 24_30, 25_56, 17, 8_55, 14_80, 94_77, 40_91, 1_28, 1_17_12, 15, 71_03, 21_53, 6_73, 17, 2_48_83, 99_90, 9, 3], [2, 1_15_02, 25, 10_06, 20, 7_82, 8, 1_18_09, 8_55, 17_32, 1_93_93, 1_86_67, 37, 3_67, 2_10_18, 69, 18_54, 34, 1_18_60, 1_91_24, 27, 1_56, 2_25, 17, 1_93, 41_41, 19, 65, 91_24, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0,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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
						# fmt: on

						self.tokenizer_integration_test_util(
						    expected_encoding=__lowercase ,					model_name="""albert-base-v2""" ,					revision="""6b6560eaf5ff2e250b00c50f380c5389a9c2d82e""" ,					)









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


UpperCamelCase__   : Union[str, Any]					  = 16
UpperCamelCase__   : Tuple					  = 32




def    A_(			A				,      A = 16   ):
	UpperCAmelCase_								=     AutoTokenizer.from_pretrained("""bert-base-cased"""   )
	UpperCAmelCase_								=     load_dataset("""glue"""				,      """mrpc"""   )

	def tokenize_function(A   ):
		# 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   ):
		# On TPU it's best to pad everything to the same length or training will be very slow.
		UpperCAmelCase_								=     128 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_								=     16
		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   )

	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

				UpperCamelCase__   : str					  = mocked_dataloaders  # noqa: F811




def    A_(			A				,      A   ):
	# For testing only
	if os.environ.get("""TESTING_MOCKED_DATALOADERS"""				,      A   ) == "1":
		UpperCAmelCase_								=     2
	# New Code #
	UpperCAmelCase_								=     int(args.gradient_accumulation_steps   )
	# Initialize accelerator
	UpperCAmelCase_								=     Accelerator(
	    cpu=args.cpu				,      mixed_precision=args.mixed_precision				,      gradient_accumulation_steps=A   )
	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
	UpperCAmelCase_								=     config["""lr"""]
	UpperCAmelCase_								=     int(config["""num_epochs"""]   )
	UpperCAmelCase_								=     int(config["""seed"""]   )
	UpperCAmelCase_								=     int(config["""batch_size"""]   )

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

	set_seed(A   )
	UpperCAmelCase_						,	UpperCAmelCase_								=     get_dataloaders(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=100				,      num_training_steps=(len(A   ) * 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.
	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   )
			# 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(A   ):
				UpperCAmelCase_								=     model(**A   )
				UpperCAmelCase_								=     output.loss
				accelerator.backward(A   )
				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   )




def    A_(			):
	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."""				,      )
	# New Code #
	parser.add_argument(
	    """--gradient_accumulation_steps"""				,      type=A				,      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."""   )
	UpperCAmelCase_								=     parser.parse_args()
	UpperCAmelCase_								=     {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
	training_function(A				,      A   )


if __name__ == "__main__":
				main()


