


"""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,
# specifically showcasing how to properly calculate the metrics on the
# validation dataset when in a distributed system, 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
#
########################################################################


UpperCAmelCase    :     Optional[Any]   						=		16
UpperCAmelCase    :     Dict   						=		32
def      lowerCamelCase       (     _UpperCamelCase		:      Accelerator       ,			_UpperCamelCase		:      int = 1_6							)		->       Optional[int]:

							'''simple docstring'''



							__UpperCAmelCase   :						str      							=					AutoTokenizer.from_pretrained("""bert-base-cased"""							)
							__UpperCAmelCase   :						str      							=					load_dataset("""glue"""       ,			"""mrpc"""							)

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

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

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

							# Instantiate dataloaders.
							__UpperCAmelCase   :						List[str]      							=					DataLoader(
							    tokenized_datasets["""train"""]       ,			shuffle=_UpperCamelCase       ,			collate_fn=_UpperCamelCase       ,			batch_size=_UpperCamelCase							)
							__UpperCAmelCase   :						Union[str, 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

							UpperCAmelCase    :     List[str]   						=		mocked_dataloaders  # noqa: F811
def      lowerCamelCase       (     _UpperCamelCase		:      str       ,			_UpperCamelCase		:      List[Any]							)		->       List[Any]:

							'''simple docstring'''



							if os.environ.get("""TESTING_MOCKED_DATALOADERS"""       ,			_UpperCamelCase							) == "1":
														__UpperCAmelCase   :						Tuple      							=					2
							# Initialize accelerator
							__UpperCAmelCase   :						Any      							=					Accelerator(cpu=args.cpu       ,			mixed_precision=args.mixed_precision							)
							# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
							__UpperCAmelCase   :						Any      							=					config["""lr"""]
							__UpperCAmelCase   :						str      							=					int(config["""num_epochs"""]							)
							__UpperCAmelCase   :						Tuple      							=					int(config["""seed"""]							)
							__UpperCAmelCase   :						Dict      							=					int(config["""batch_size"""]							)

							__UpperCAmelCase   :						Dict      							=					evaluate.load("""glue"""       ,			"""mrpc"""							)

							# If the batch size is too big we use gradient accumulation
							__UpperCAmelCase   :						Union[str, Any]      							=					1
							if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
														__UpperCAmelCase   :						List[Any]      							=					batch_size // MAX_GPU_BATCH_SIZE
														__UpperCAmelCase   :						Any      							=					MAX_GPU_BATCH_SIZE

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

							# Instantiate optimizer
							__UpperCAmelCase   :						Optional[Any]      							=					AdamW(params=model.parameters()       ,			lr=_UpperCamelCase							)

							# Instantiate scheduler
							__UpperCAmelCase   :						Dict      							=					get_linear_schedule_with_warmup(
							    optimizer=_UpperCamelCase       ,			num_warmup_steps=1_0_0       ,			num_training_steps=(len(_UpperCamelCase							) * 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   :						Tuple      							=					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							)
																					__UpperCAmelCase   :						List[str]      							=					model(**_UpperCamelCase							)
																					__UpperCAmelCase   :						int      							=					outputs.loss
																					__UpperCAmelCase   :						Tuple      							=					loss / gradient_accumulation_steps
																					accelerator.backward(_UpperCamelCase							)
																					if step % gradient_accumulation_steps == 0:
																												optimizer.step()
																												lr_scheduler.step()
																												optimizer.zero_grad()

														model.eval()
														__UpperCAmelCase   :						Optional[int]      							=					0
														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():
																												__UpperCAmelCase   :						Any      							=					model(**_UpperCamelCase							)
																					__UpperCAmelCase   :						Dict      							=					outputs.logits.argmax(dim=-1							)
																					__UpperCAmelCase							,__UpperCAmelCase   :						List[str]      							=					accelerator.gather((predictions, batch["""labels"""])							)
																					# New Code #
																					# First we check if it's a distributed system
																					if accelerator.use_distributed:
																												# Then see if we're on the last batch of our eval dataloader
																												if step == len(_UpperCamelCase							) - 1:
																																			# Last batch needs to be truncated on distributed systems as it contains additional samples
																																			__UpperCAmelCase   :						List[str]      							=					predictions[: len(eval_dataloader.dataset							) - samples_seen]
																																			__UpperCAmelCase   :						Tuple      							=					references[: len(eval_dataloader.dataset							) - samples_seen]
																												else:
																																			# Otherwise we add the number of samples seen
																																			samples_seen += references.shape[0]
            # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
            # accelerator.gather_for_metrics((predictions, batch["labels"]))
																					metric.add_batch(
																					    predictions=_UpperCamelCase       ,			references=_UpperCamelCase       ,			)

														__UpperCAmelCase   :						int      							=					metric.compute()
														# Use accelerator.print to print only on the main process.
														accelerator.print(f'''epoch {epoch}:'''       ,			_UpperCamelCase							)
def      lowerCamelCase       (     )		->       Tuple:

							'''simple docstring'''



							__UpperCAmelCase   :						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."""       ,			)
							parser.add_argument("""--cpu"""       ,			action="""store_true"""       ,			help="""If passed, will train on the CPU."""							)
							__UpperCAmelCase   :						Optional[int]      							=					parser.parse_args()
							__UpperCAmelCase   :						Any      							=					{"""lr""": 2E-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6}
							training_function(_UpperCamelCase       ,			_UpperCamelCase							)


if __name__ == "__main__":
							main()




"""simple docstring"""






import unittest

from datasets import load_dataset

from transformers import BloomTokenizerFast
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class      lowerCamelCase__   (     A     ,    unittest.TestCase				):







					"""simple docstring"""


					__a	       =							None
					__a	       =							BloomTokenizerFast
					__a	       =							BloomTokenizerFast
					__a	       =							True
					__a	       =							False
					__a	       =							"""tokenizer_file"""
					__a	       =							{"""bos_token""": """<s>""", """eos_token""": """</s>""", """unk_token""": """<unk>""", """pad_token""": """<pad>"""}






					def lowerCamelCase__							(       self    : int  ):
												'''simple docstring'''






												super().setUp()
												__UpperCAmelCase   :						Any      							=					BloomTokenizerFast.from_pretrained("""bigscience/tokenizer"""  )
												tokenizer.save_pretrained(self.tmpdirname  )






					def lowerCamelCase__							(       self    : Any ,       **UpperCamelCase    : Optional[int]  ):
												'''simple docstring'''






												kwargs.update(self.special_tokens_map  )
												return BloomTokenizerFast.from_pretrained(self.tmpdirname ,       **UpperCamelCase  )






					def lowerCamelCase__							(       self    : Optional[Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Any      							=					self.get_rust_tokenizer()

												__UpperCAmelCase   :						Optional[Any]      							=					["""The quick brown fox</s>""", """jumps over the lazy dog</s>"""]
												__UpperCAmelCase   :						int      							=					[[2_175, 23_714, 73_173, 144_252, 2], [77, 132_619, 3_478, 368, 109_586, 35_433, 2]]

												__UpperCAmelCase   :						Dict      							=					tokenizer.batch_encode_plus(UpperCamelCase  )["""input_ids"""]
												self.assertListEqual(UpperCamelCase ,       UpperCamelCase  )

												__UpperCAmelCase   :						int      							=					tokenizer.batch_decode(UpperCamelCase  )
												self.assertListEqual(UpperCamelCase ,       UpperCamelCase  )






					def lowerCamelCase__							(       self    : int ,       UpperCamelCase    : Any=6  ):
												'''simple docstring'''






												for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																			with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''  ):
																										__UpperCAmelCase   :						Optional[int]      							=					self.rust_tokenizer_class.from_pretrained(UpperCamelCase ,       **UpperCamelCase  )
																										# tokenizer_r.pad_token = None # Hotfixing padding = None
																										# Simple input
																										__UpperCAmelCase   :						Dict      							=					"""This is a simple input"""
																										__UpperCAmelCase   :						str      							=					["""This is a simple input 1""", """This is a simple input 2"""]
																										__UpperCAmelCase   :						List[str]      							=					("""This is a simple input""", """This is a pair""")
																										__UpperCAmelCase   :						Dict      							=					[
																										    ("""This is a simple input 1""", """This is a simple input 2"""),
																										    ("""This is a simple pair 1""", """This is a simple pair 2"""),
																										]

																										# Simple input tests
																										try:
																																	tokenizer_r.encode(UpperCamelCase ,       max_length=UpperCamelCase  )
																																	tokenizer_r.encode_plus(UpperCamelCase ,       max_length=UpperCamelCase  )

																																	tokenizer_r.batch_encode_plus(UpperCamelCase ,       max_length=UpperCamelCase  )
																																	tokenizer_r.encode(UpperCamelCase ,       max_length=UpperCamelCase  )
																																	tokenizer_r.batch_encode_plus(UpperCamelCase ,       max_length=UpperCamelCase  )
																										except ValueError:
																																	self.fail("""Bloom Tokenizer should be able to deal with padding"""  )

																										__UpperCAmelCase   :						Union[str, Any]      							=					None  # Hotfixing padding = None
																										self.assertRaises(UpperCamelCase ,       tokenizer_r.encode ,       UpperCamelCase ,       max_length=UpperCamelCase ,       padding="""max_length"""  )

																										# Simple input
																										self.assertRaises(UpperCamelCase ,       tokenizer_r.encode_plus ,       UpperCamelCase ,       max_length=UpperCamelCase ,       padding="""max_length"""  )

																										# Simple input
																										self.assertRaises(
																										    UpperCamelCase ,       tokenizer_r.batch_encode_plus ,       UpperCamelCase ,       max_length=UpperCamelCase ,       padding="""max_length""" ,       )

																										# Pair input
																										self.assertRaises(UpperCamelCase ,       tokenizer_r.encode ,       UpperCamelCase ,       max_length=UpperCamelCase ,       padding="""max_length"""  )

																										# Pair input
																										self.assertRaises(UpperCamelCase ,       tokenizer_r.encode_plus ,       UpperCamelCase ,       max_length=UpperCamelCase ,       padding="""max_length"""  )

																										# Pair input
																										self.assertRaises(
																										    UpperCamelCase ,       tokenizer_r.batch_encode_plus ,       UpperCamelCase ,       max_length=UpperCamelCase ,       padding="""max_length""" ,       )






					def lowerCamelCase__							(       self    : Any  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Union[str, Any]      							=					self.get_rust_tokenizer()
												__UpperCAmelCase   :						Optional[Any]      							=					load_dataset("""xnli""" ,       """all_languages""" ,       split="""test""" ,       streaming=UpperCamelCase  )

												__UpperCAmelCase   :						Optional[Any]      							=					next(iter(UpperCamelCase  )  )["""premise"""]  # pick up one data
												__UpperCAmelCase   :						Any      							=					list(sample_data.values()  )

												__UpperCAmelCase   :						Optional[Any]      							=					list(map(tokenizer.encode ,       UpperCamelCase  )  )
												__UpperCAmelCase   :						List[Any]      							=					[tokenizer.decode(UpperCamelCase ,       clean_up_tokenization_spaces=UpperCamelCase  ) for x in output_tokens]
												self.assertListEqual(UpperCamelCase ,       UpperCamelCase  )






					def lowerCamelCase__							(       self    : Optional[Any]  ):
												'''simple docstring'''






												self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map  ) ,       1  )
												self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values()  )[0]  ) ,       1  )
