





import argparse
import os

# New Code #
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 import find_executable_batch_size


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to ensure out-of-memory errors never
# interrupt training, 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)
#
# 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
#
########################################################################


__lowercase       :Tuple  =  16
__lowercase       :Dict  =  32







def       UpperCAmelCase							(     _lowerCamelCase      :  Accelerator			,   _lowerCamelCase      :  int = 16     ):





						'''simple docstring'''


						SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoTokenizer.from_pretrained("bert-base-cased"     )
						SCREAMING_SNAKE_CASE__     :				Tuple   =					load_dataset("glue"			,   "mrpc"     )

						def tokenize_function(_lowerCamelCase      :  str     ):
												# max_length=None => use the model max length (it's actually the default)
												SCREAMING_SNAKE_CASE__     :				List[str]   =					tokenizer(examples["sentence1"]			,   examples["sentence2"]			,   truncation=_lowerCamelCase			,   max_length=_lowerCamelCase     )
												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():
												SCREAMING_SNAKE_CASE__     :				Dict   =					datasets.map(
												    _lowerCamelCase			,   batched=_lowerCamelCase			,   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
						SCREAMING_SNAKE_CASE__     :				List[Any]   =					tokenized_datasets.rename_column("label"			,   "labels"     )

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

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

						# Instantiate dataloaders.
						SCREAMING_SNAKE_CASE__     :				List[str]   =					DataLoader(
						    tokenized_datasets["train"]			,   shuffle=_lowerCamelCase			,   collate_fn=_lowerCamelCase			,   batch_size=_lowerCamelCase     )
						SCREAMING_SNAKE_CASE__     :				List[Any]   =					DataLoader(
						    tokenized_datasets["validation"]			,   shuffle=_lowerCamelCase			,   collate_fn=_lowerCamelCase			,   batch_size=_lowerCamelCase     )

						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

				__lowercase       :List[Any]  =  mocked_dataloaders  # noqa: F811







def       UpperCAmelCase							(     _lowerCamelCase      :  str			,   _lowerCamelCase      :  Any     ):





						'''simple docstring'''


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

						SCREAMING_SNAKE_CASE__     :				Any   =					evaluate.load("glue"			,   "mrpc"     )

						# New Code #
						# We now can define an inner training loop function. It should take a batch size as the only parameter,
						# and build the dataloaders in there.
						# It also gets our decorator
						@find_executable_batch_size(starting_batch_size=_lowerCamelCase     )
						def inner_training_loop(_lowerCamelCase      :  Any     ):
												# And now just move everything below under this function
												# We need to bring in the Accelerator object from earlier
												nonlocal accelerator
												# And reset all of its attributes that could hold onto any memory:
												accelerator.free_memory()

												# Then we can declare the model, optimizer, and everything else:
												set_seed(_lowerCamelCase     )

												# Instantiate the model (we build the model here so that the seed also control new weights initialization)
												SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoModelForSequenceClassification.from_pretrained("bert-base-cased"			,   return_dict=_lowerCamelCase     )

												# 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).
												SCREAMING_SNAKE_CASE__     :				Optional[int]   =					model.to(accelerator.device     )

												# Instantiate optimizer
												SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					AdamW(params=model.parameters()			,   lr=_lowerCamelCase     )
												SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					get_dataloaders(_lowerCamelCase			,   _lowerCamelCase     )

												# Instantiate scheduler
												SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					get_linear_schedule_with_warmup(
												    optimizer=_lowerCamelCase			,   num_warmup_steps=100			,   num_training_steps=(len(_lowerCamelCase     ) * 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.
												SCREAMING_SNAKE_CASE__     :				Optional[int]   =					accelerator.prepare(
												    _lowerCamelCase			,   _lowerCamelCase			,   _lowerCamelCase			,   _lowerCamelCase			,   _lowerCamelCase     )

												# Now we train the model
												for epoch in range(_lowerCamelCase     ):
																		model.train()
																		for step, batch in enumerate(_lowerCamelCase     ):
																								# We could avoid this line since we set the accelerator with `device_placement=True`.
																								batch.to(accelerator.device     )
																								SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					model(**_lowerCamelCase     )
																								SCREAMING_SNAKE_CASE__     :				Dict   =					outputs.loss
																								accelerator.backward(_lowerCamelCase     )
																								optimizer.step()
																								lr_scheduler.step()
																								optimizer.zero_grad()

																		model.eval()
																		for step, batch in enumerate(_lowerCamelCase     ):
																								# We could avoid this line since we set the accelerator with `device_placement=True`.
																								batch.to(accelerator.device     )
																								with torch.no_grad():
																														SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					model(**_lowerCamelCase     )
																								SCREAMING_SNAKE_CASE__     :				Any   =					outputs.logits.argmax(dim=-1     )
																								SCREAMING_SNAKE_CASE__     :				List[Any]   =					accelerator.gather_for_metrics((predictions, batch["labels"])     )
																								metric.add_batch(
																								    predictions=_lowerCamelCase			,   references=_lowerCamelCase			,   )

																		SCREAMING_SNAKE_CASE__     :				List[str]   =					metric.compute()
																		# Use accelerator.print to print only on the main process.
																		accelerator.print(f"""epoch {epoch}:"""			,   _lowerCamelCase     )

    # New Code #
    # And call it at the end with no arguments
    # Note: You could also refactor this outside of your training loop function
						inner_training_loop()







def       UpperCAmelCase							(     ):





						'''simple docstring'''


						SCREAMING_SNAKE_CASE__     :				List[str]   =					argparse.ArgumentParser(description="Simple example of training script."     )
						parser.add_argument(
						    "--mixed_precision"			,   type=_lowerCamelCase			,   default=_lowerCamelCase			,   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."     )
						SCREAMING_SNAKE_CASE__     :				str   =					parser.parse_args()
						SCREAMING_SNAKE_CASE__     :				Optional[int]   =					{"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
						training_function(_lowerCamelCase			,   _lowerCamelCase     )


if __name__ == "__main__":
				main()






import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


__lowercase       :List[str]       =  get_tests_dir("fixtures/dummy_feature_extractor_config.json")
__lowercase       :str       =  get_tests_dir("fixtures/vocab.json")
__lowercase       :Optional[int]       =  get_tests_dir("fixtures")



class    _a     (				unittest.TestCase							):






							"""simple docstring"""

							snake_case_							 =						["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]

							def      A_  (      self				:     Optional[Any]    )	->int:
													SCREAMING_SNAKE_CASE__     :				Dict   =					0

							def      A_  (      self				:     Any    )	->Optional[int]:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h"    )
													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     Union[str, Any]    )	->List[str]:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			SCREAMING_SNAKE_CASE__     :				Dict   =					WavaVecaConfig()
																			SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h"    )

																			# save in new folder
																			model_config.save_pretrained(a    )
																			processor.save_pretrained(a    )

																			SCREAMING_SNAKE_CASE__     :				str   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     int    )	->List[str]:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			# copy relevant files
																			copyfile(a							,	os.path.join(a							,	a    )    )
																			copyfile(a							,	os.path.join(a							,	"vocab.json"    )    )

																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     List[Any]    )	->Tuple:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					WavaVecaFeatureExtractor()
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h"    )

																			SCREAMING_SNAKE_CASE__     :				Any   =					WavaVecaProcessor(a							,	a    )

																			# save in new folder
																			processor.save_pretrained(a    )

																			# drop `processor_class` in tokenizer
																			with open(os.path.join(a							,	a    )							,	"r"    ) as f:
																									SCREAMING_SNAKE_CASE__     :				Optional[int]   =					json.load(a    )
																									config_dict.pop("processor_class"    )

																			with open(os.path.join(a							,	a    )							,	"w"    ) as f:
																									f.write(json.dumps(a    )    )

																			SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     List[str]    )	->Optional[Any]:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					WavaVecaFeatureExtractor()
																			SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h"    )

																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					WavaVecaProcessor(a							,	a    )

																			# save in new folder
																			processor.save_pretrained(a    )

																			# drop `processor_class` in feature extractor
																			with open(os.path.join(a							,	a    )							,	"r"    ) as f:
																									SCREAMING_SNAKE_CASE__     :				List[Any]   =					json.load(a    )
																									config_dict.pop("processor_class"    )

																			with open(os.path.join(a							,	a    )							,	"w"    ) as f:
																									f.write(json.dumps(a    )    )

																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     Union[str, Any]    )	->str:
													with tempfile.TemporaryDirectory() as tmpdirname:
																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					WavaVecaConfig(processor_class="Wav2Vec2Processor"    )
																			model_config.save_pretrained(a    )
																			# copy relevant files
																			copyfile(a							,	os.path.join(a							,	"vocab.json"    )    )
																			# create emtpy sample processor
																			with open(os.path.join(a							,	a    )							,	"w"    ) as f:
																									f.write("{}"    )

																			SCREAMING_SNAKE_CASE__     :				Tuple   =					AutoProcessor.from_pretrained(a    )

													self.assertIsInstance(a							,	a    )

							def      A_  (      self				:     Optional[Any]    )	->Optional[int]:
													# If remote code is not set, we will time out when asking whether to load the model.
													with self.assertRaises(a    ):
																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor"    )
													# If remote code is disabled, we can't load this config.
													with self.assertRaises(a    ):
																			SCREAMING_SNAKE_CASE__     :				Any   =					AutoProcessor.from_pretrained(
																			    "hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a    )

													SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a    )
													self.assertTrue(processor.special_attribute_present    )
													self.assertEqual(processor.__class__.__name__							,	"NewProcessor"    )

													SCREAMING_SNAKE_CASE__     :				Dict   =					processor.feature_extractor
													self.assertTrue(feature_extractor.special_attribute_present    )
													self.assertEqual(feature_extractor.__class__.__name__							,	"NewFeatureExtractor"    )

													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					processor.tokenizer
													self.assertTrue(tokenizer.special_attribute_present    )
													if is_tokenizers_available():
																			self.assertEqual(tokenizer.__class__.__name__							,	"NewTokenizerFast"    )

																			# Test we can also load the slow version
																			SCREAMING_SNAKE_CASE__     :				int   =					AutoProcessor.from_pretrained(
																			    "hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a							,	use_fast=a    )
																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					new_processor.tokenizer
																			self.assertTrue(new_tokenizer.special_attribute_present    )
																			self.assertEqual(new_tokenizer.__class__.__name__							,	"NewTokenizer"    )
													else:
																			self.assertEqual(tokenizer.__class__.__name__							,	"NewTokenizer"    )

							def      A_  (      self				:     Tuple    )	->List[Any]:
													try:
																			AutoConfig.register("custom"							,	a    )
																			AutoFeatureExtractor.register(a							,	a    )
																			AutoTokenizer.register(a							,	slow_tokenizer_class=a    )
																			AutoProcessor.register(a							,	a    )
																			# Trying to register something existing in the Transformers library will raise an error
																			with self.assertRaises(a    ):
																									AutoProcessor.register(a							,	a    )

																			# Now that the config is registered, it can be used as any other config with the auto-API
																			SCREAMING_SNAKE_CASE__     :				List[str]   =					CustomFeatureExtractor.from_pretrained(a    )

																			with tempfile.TemporaryDirectory() as tmp_dir:
																									SCREAMING_SNAKE_CASE__     :				int   =					os.path.join(a							,	"vocab.txt"    )
																									with open(a							,	"w"							,	encoding="utf-8"    ) as vocab_writer:
																															vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]    )    )
																									SCREAMING_SNAKE_CASE__     :				Optional[int]   =					CustomTokenizer(a    )

																			SCREAMING_SNAKE_CASE__     :				List[Any]   =					CustomProcessor(a							,	a    )

																			with tempfile.TemporaryDirectory() as tmp_dir:
																									processor.save_pretrained(a    )
																									SCREAMING_SNAKE_CASE__     :				Any   =					AutoProcessor.from_pretrained(a    )
																									self.assertIsInstance(a							,	a    )

													finally:
																			if "custom" in CONFIG_MAPPING._extra_content:
																									del CONFIG_MAPPING._extra_content["custom"]
																			if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																									del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
																			if CustomConfig in TOKENIZER_MAPPING._extra_content:
																									del TOKENIZER_MAPPING._extra_content[CustomConfig]
																			if CustomConfig in PROCESSOR_MAPPING._extra_content:
																									del PROCESSOR_MAPPING._extra_content[CustomConfig]

							def      A_  (      self				:     Union[str, Any]    )	->int:



													class    _a     (				lowercase__							):






																				"""simple docstring"""

																				snake_case_							 =						False







													class    _a     (				lowercase__							):






																				"""simple docstring"""

																				snake_case_							 =						False







													class    _a     (				lowercase__							):






																				"""simple docstring"""

																				snake_case_							 =						"AutoFeatureExtractor"
																				snake_case_							 =						"AutoTokenizer"
																				snake_case_							 =						False

													try:
																			AutoConfig.register("custom"							,	a    )
																			AutoFeatureExtractor.register(a							,	a    )
																			AutoTokenizer.register(a							,	slow_tokenizer_class=a    )
																			AutoProcessor.register(a							,	a    )
																			# If remote code is not set, the default is to use local classes.
																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor"    )
																			self.assertEqual(processor.__class__.__name__							,	"NewProcessor"    )
																			self.assertFalse(processor.special_attribute_present    )
																			self.assertFalse(processor.feature_extractor.special_attribute_present    )
																			self.assertFalse(processor.tokenizer.special_attribute_present    )

																			# If remote code is disabled, we load the local ones.
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					AutoProcessor.from_pretrained(
																			    "hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a    )
																			self.assertEqual(processor.__class__.__name__							,	"NewProcessor"    )
																			self.assertFalse(processor.special_attribute_present    )
																			self.assertFalse(processor.feature_extractor.special_attribute_present    )
																			self.assertFalse(processor.tokenizer.special_attribute_present    )

																			# If remote is enabled, we load from the Hub.
																			SCREAMING_SNAKE_CASE__     :				Any   =					AutoProcessor.from_pretrained(
																			    "hf-internal-testing/test_dynamic_processor"							,	trust_remote_code=a    )
																			self.assertEqual(processor.__class__.__name__							,	"NewProcessor"    )
																			self.assertTrue(processor.special_attribute_present    )
																			self.assertTrue(processor.feature_extractor.special_attribute_present    )
																			self.assertTrue(processor.tokenizer.special_attribute_present    )

													finally:
																			if "custom" in CONFIG_MAPPING._extra_content:
																									del CONFIG_MAPPING._extra_content["custom"]
																			if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																									del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
																			if CustomConfig in TOKENIZER_MAPPING._extra_content:
																									del TOKENIZER_MAPPING._extra_content[CustomConfig]
																			if CustomConfig in PROCESSOR_MAPPING._extra_content:
																									del PROCESSOR_MAPPING._extra_content[CustomConfig]

							def      A_  (      self				:     Optional[Any]    )	->Dict:
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-bert"    )
													self.assertEqual(processor.__class__.__name__							,	"BertTokenizerFast"    )






							def      A_  (      self				:     Dict    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :				Dict   =					AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-convnext"    )
													self.assertEqual(processor.__class__.__name__							,	"ConvNextImageProcessor"    )







@is_staging_test
class    _a     (				unittest.TestCase							):






							"""simple docstring"""

							snake_case_							 =						["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]

							@classmethod
							def      A_  (      cls				:     List[str]    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :				int   =					TOKEN
													HfFolder.save_token(a    )

							@classmethod
							def      A_  (      cls				:     List[str]    )	->Optional[int]:
													try:
																			delete_repo(token=cls._token							,	repo_id="test-processor"    )
													except HTTPError:
																			pass

													try:
																			delete_repo(token=cls._token							,	repo_id="valid_org/test-processor-org"    )
													except HTTPError:
																			pass

													try:
																			delete_repo(token=cls._token							,	repo_id="test-dynamic-processor"    )
													except HTTPError:
																			pass

							def      A_  (      self				:     Dict    )	->Dict:
													SCREAMING_SNAKE_CASE__     :				Tuple   =					WavaVecaProcessor.from_pretrained(a    )
													with tempfile.TemporaryDirectory() as tmp_dir:
																			processor.save_pretrained(
																			    os.path.join(a							,	"test-processor"    )							,	push_to_hub=a							,	use_auth_token=self._token    )

																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					WavaVecaProcessor.from_pretrained(f"""{USER}/test-processor"""    )
																			for k, v in processor.feature_extractor.__dict__.items():
																									self.assertEqual(a							,	getattr(new_processor.feature_extractor							,	a    )    )
																			self.assertDictEqual(new_processor.tokenizer.get_vocab()							,	processor.tokenizer.get_vocab()    )

							def      A_  (      self				:     List[str]    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					WavaVecaProcessor.from_pretrained(a    )

													with tempfile.TemporaryDirectory() as tmp_dir:
																			processor.save_pretrained(
																			    os.path.join(a							,	"test-processor-org"    )							,	push_to_hub=a							,	use_auth_token=self._token							,	organization="valid_org"							,	)

																			SCREAMING_SNAKE_CASE__     :				Dict   =					WavaVecaProcessor.from_pretrained("valid_org/test-processor-org"    )
																			for k, v in processor.feature_extractor.__dict__.items():
																									self.assertEqual(a							,	getattr(new_processor.feature_extractor							,	a    )    )
																			self.assertDictEqual(new_processor.tokenizer.get_vocab()							,	processor.tokenizer.get_vocab()    )






							def      A_  (      self				:     Any    )	->int:
													CustomFeatureExtractor.register_for_auto_class()
													CustomTokenizer.register_for_auto_class()
													CustomProcessor.register_for_auto_class()

													SCREAMING_SNAKE_CASE__     :				Any   =					CustomFeatureExtractor.from_pretrained(a    )

													with tempfile.TemporaryDirectory() as tmp_dir:
																			SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					os.path.join(a							,	"vocab.txt"    )
																			with open(a							,	"w"							,	encoding="utf-8"    ) as vocab_writer:
																									vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]    )    )
																			SCREAMING_SNAKE_CASE__     :				str   =					CustomTokenizer(a    )

													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					CustomProcessor(a							,	a    )

													with tempfile.TemporaryDirectory() as tmp_dir:
																			create_repo(f"""{USER}/test-dynamic-processor"""							,	token=self._token    )
																			SCREAMING_SNAKE_CASE__     :				str   =					Repository(a							,	clone_from=f"""{USER}/test-dynamic-processor"""							,	token=self._token    )
																			processor.save_pretrained(a    )

																			# This has added the proper auto_map field to the feature extractor config
																			self.assertDictEqual(
																			    processor.feature_extractor.auto_map							,	{
																			        "AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor",
																			        "AutoProcessor": "custom_processing.CustomProcessor",
																			    }							,	)

																			# This has added the proper auto_map field to the tokenizer config
																			with open(os.path.join(a							,	"tokenizer_config.json"    )    ) as f:
																									SCREAMING_SNAKE_CASE__     :				str   =					json.load(a    )
																			self.assertDictEqual(
																			    tokenizer_config["auto_map"]							,	{
																			        "AutoTokenizer": ["custom_tokenization.CustomTokenizer", None],
																			        "AutoProcessor": "custom_processing.CustomProcessor",
																			    }							,	)

																			# The code has been copied from fixtures
																			self.assertTrue(os.path.isfile(os.path.join(a							,	"custom_feature_extraction.py"    )    )    )
																			self.assertTrue(os.path.isfile(os.path.join(a							,	"custom_tokenization.py"    )    )    )
																			self.assertTrue(os.path.isfile(os.path.join(a							,	"custom_processing.py"    )    )    )

																			repo.push_to_hub()

													SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoProcessor.from_pretrained(f"""{USER}/test-dynamic-processor"""							,	trust_remote_code=a    )
													# Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
													self.assertEqual(new_processor.__class__.__name__							,	"CustomProcessor"    )