





'''simple docstring'''





import argparse
from typing import List

import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset

# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
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 perform Cross Validation,
# 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__											= 16
UpperCamelCase__											= 32





def     _UpperCamelCase     (a__   :Accelerator   ,			a__   :DatasetDict   ,			a__   :List[int]   ,			a__   :List[int]   ,			a__   :int = 16       ):






							"""simple docstring"""





							UpperCamelCase__				     =			AutoTokenizer.from_pretrained("""bert-base-cased"""       )
							UpperCamelCase__				     =			DatasetDict(
							    {
							        """train""": dataset["""train"""].select(a__       ),
							        """validation""": dataset["""train"""].select(a__       ),
							        """test""": dataset["""validation"""],
							    }       )

							def tokenize_function(a__   :Optional[int]       ):
														# 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__   :int       ):
														# 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__       )

							UpperCamelCase__				     =			DataLoader(
							    tokenized_datasets["""test"""]   ,			shuffle=a__   ,			collate_fn=a__   ,			batch_size=a__       )

							return train_dataloader, eval_dataloader, test_dataloader





def     _UpperCamelCase     (a__   :Any   ,			a__   :int       ):






							"""simple docstring"""





							UpperCamelCase__				     =			[]
							# Download the dataset
							UpperCamelCase__				     =			load_dataset("""glue"""   ,			"""mrpc"""       )
							# Create our splits
							UpperCamelCase__				     =			StratifiedKFold(n_splits=int(args.num_folds       )       )
							# Initialize accelerator
							UpperCamelCase__				     =			Accelerator(cpu=args.cpu   ,			mixed_precision=args.mixed_precision       )
							# 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"""       )

							# If the batch size is too big we use gradient accumulation
							UpperCamelCase__				     =			1
							if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
														UpperCamelCase__				     =			batch_size // MAX_GPU_BATCH_SIZE
														UpperCamelCase__				     =			MAX_GPU_BATCH_SIZE

							set_seed(a__       )

							# New Code #
							# Create our folds:
							UpperCamelCase__				     =			kfold.split(np.zeros(datasets["""train"""].num_rows       )   ,			datasets["""train"""]["""label"""]       )
							UpperCamelCase__				     =			[]
							# Iterate over them
							for i, (train_idxs, valid_idxs) in enumerate(a__       ):
														UpperCamelCase__     ,     UpperCamelCase__     ,     UpperCamelCase__				     =			get_fold_dataloaders(
														    a__   ,			a__   ,			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) // 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__				     =			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       )
																												UpperCamelCase__				     =			model(**a__       )
																												UpperCamelCase__				     =			outputs.loss
																												UpperCamelCase__				     =			loss / gradient_accumulation_steps
																												accelerator.backward(a__       )
																												if step % gradient_accumulation_steps == 0:
																																			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__       )

														# New Code #
														# We also run predictions on the test set at the very end
														UpperCamelCase__				     =			[]
														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
																					UpperCamelCase__     ,     UpperCamelCase__				     =			accelerator.gather_for_metrics((predictions, batch["""labels"""])       )
																					fold_predictions.append(predictions.cpu()       )
																					if i == 0:
																												# We need all of the test predictions
																												test_references.append(references.cpu()       )
        # Use accelerator.print to print only on the main process.
														test_predictions.append(torch.cat(a__   ,			dim=0       )       )
														# We now need to release all our memory and get rid of the current model, optimizer, etc
														accelerator.free_memory()
							# New Code #
							# Finally we check the accuracy of our folded results:
							UpperCamelCase__				     =			torch.cat(a__   ,			dim=0       )
							UpperCamelCase__				     =			torch.stack(a__   ,			dim=0       ).sum(dim=0       ).div(int(args.num_folds       )       ).argmax(dim=-1       )
							UpperCamelCase__				     =			metric.compute(predictions=a__   ,			references=a__       )
							accelerator.print("""Average test metrics from all folds:"""   ,			a__       )





def     _UpperCamelCase     ():






							"""simple docstring"""





							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."""   ,			)
							parser.add_argument("""--cpu"""   ,			action="""store_true"""   ,			help="""If passed, will train on the CPU."""       )
							# New Code #
							parser.add_argument("""--num_folds"""   ,			type=a__   ,			default=3   ,			help="""The number of splits to perform across the dataset"""       )
							UpperCamelCase__				     =			parser.parse_args()
							UpperCamelCase__				     =			{"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
							training_function(a__   ,			a__       )


if __name__ == "__main__":
					main()











import math

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase__											= logging.get_logger(__name__)

UpperCamelCase__											= {
    "facebook/data2vec-base-960h": "https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json",
    # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio
}

class        __SCREAMING_SNAKE_CASE					(     _a       ):
							snake_case     :      Optional[Any]						     =       """data2vec-audio"""






							def __init__(						self  , __lowerCAmelCase=32  , __lowerCAmelCase=768  , __lowerCAmelCase=12  , __lowerCAmelCase=12  , __lowerCAmelCase=3072  , __lowerCAmelCase="gelu"  , __lowerCAmelCase=0.1  , __lowerCAmelCase=0.1  , __lowerCAmelCase=0.1  , __lowerCAmelCase=0.0  , __lowerCAmelCase=0.1  , __lowerCAmelCase=0.1  , __lowerCAmelCase=0.02  , __lowerCAmelCase=1E-5  , __lowerCAmelCase="gelu"  , __lowerCAmelCase=(512, 512, 512, 512, 512, 512, 512)  , __lowerCAmelCase=(5, 2, 2, 2, 2, 2, 2)  , __lowerCAmelCase=(10, 3, 3, 3, 3, 2, 2)  , __lowerCAmelCase=False  , __lowerCAmelCase=16  , __lowerCAmelCase=19  , __lowerCAmelCase=5  , __lowerCAmelCase=0.05  , __lowerCAmelCase=10  , __lowerCAmelCase=2  , __lowerCAmelCase=0.0  , __lowerCAmelCase=10  , __lowerCAmelCase=0  , __lowerCAmelCase="sum"  , __lowerCAmelCase=False  , __lowerCAmelCase=False  , __lowerCAmelCase=256  , __lowerCAmelCase=(512, 512, 512, 512, 1500)  , __lowerCAmelCase=(5, 3, 3, 1, 1)  , __lowerCAmelCase=(1, 2, 3, 1, 1)  , __lowerCAmelCase=512  , __lowerCAmelCase=0  , __lowerCAmelCase=1  , __lowerCAmelCase=2  , __lowerCAmelCase=False  , __lowerCAmelCase=3  , __lowerCAmelCase=2  , __lowerCAmelCase=3  , __lowerCAmelCase=None  , **__lowerCAmelCase  , ):
														super().__init__(**__lowerCAmelCase  , pad_token_id=__lowerCAmelCase  , bos_token_id=__lowerCAmelCase  , eos_token_id=__lowerCAmelCase  )
														UpperCamelCase__				     =			hidden_size
														UpperCamelCase__				     =			feat_extract_activation
														UpperCamelCase__				     =			list(__lowerCAmelCase  )
														UpperCamelCase__				     =			list(__lowerCAmelCase  )
														UpperCamelCase__				     =			list(__lowerCAmelCase  )
														UpperCamelCase__				     =			conv_bias
														UpperCamelCase__				     =			num_conv_pos_embeddings
														UpperCamelCase__				     =			num_conv_pos_embedding_groups
														UpperCamelCase__				     =			conv_pos_kernel_size
														UpperCamelCase__				     =			len(self.conv_dim  )
														UpperCamelCase__				     =			num_hidden_layers
														UpperCamelCase__				     =			intermediate_size
														UpperCamelCase__				     =			hidden_act
														UpperCamelCase__				     =			num_attention_heads
														UpperCamelCase__				     =			hidden_dropout
														UpperCamelCase__				     =			attention_dropout
														UpperCamelCase__				     =			activation_dropout
														UpperCamelCase__				     =			feat_proj_dropout
														UpperCamelCase__				     =			final_dropout
														UpperCamelCase__				     =			layerdrop
														UpperCamelCase__				     =			layer_norm_eps
														UpperCamelCase__				     =			initializer_range
														UpperCamelCase__				     =			vocab_size
														UpperCamelCase__				     =			use_weighted_layer_sum

														if (
														    (len(self.conv_stride  ) != self.num_feat_extract_layers)
														    or (len(self.conv_kernel  ) != self.num_feat_extract_layers)
														    or (len(self.conv_dim  ) != self.num_feat_extract_layers)
														):
																					raise ValueError(
																					    """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
																					    """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
																					    f""" {len(self.conv_dim  )}`, `len(config.conv_stride) = {len(self.conv_stride  )}`,"""
																					    f""" `len(config.conv_kernel) = {len(self.conv_kernel  )}`."""  )

														# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
														UpperCamelCase__				     =			mask_time_prob
														UpperCamelCase__				     =			mask_time_length
														UpperCamelCase__				     =			mask_time_min_masks
														UpperCamelCase__				     =			mask_feature_prob
														UpperCamelCase__				     =			mask_feature_length
														UpperCamelCase__				     =			mask_feature_min_masks

														# ctc loss
														UpperCamelCase__				     =			ctc_loss_reduction
														UpperCamelCase__				     =			ctc_zero_infinity

														# adapter
														UpperCamelCase__				     =			add_adapter
														UpperCamelCase__				     =			adapter_kernel_size
														UpperCamelCase__				     =			adapter_stride
														UpperCamelCase__				     =			num_adapter_layers
														UpperCamelCase__				     =			output_hidden_size or hidden_size

														# SequenceClassification-specific parameter. Feel free to ignore for other classes.
														UpperCamelCase__				     =			classifier_proj_size

														# XVector-specific parameters. Feel free to ignore for other classes.
														UpperCamelCase__				     =			list(__lowerCAmelCase  )
														UpperCamelCase__				     =			list(__lowerCAmelCase  )
														UpperCamelCase__				     =			list(__lowerCAmelCase  )
														UpperCamelCase__				     =			xvector_output_dim







							@property
							def 				_lowerCamelCase		(						self  ):
														return math.prod(self.conv_stride  )




