






'''simple docstring'''





import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_UpperCamelCase						:						List[str]  =					logging.getLogger(__name__)
def __UpperCAmelCase   (					A					:			List[Any]			,       A					:			Optional[Any]		)    ->   Optional[int]:
			return (preds == labels).mean()


@dataclass
class  snake_case__      :
					a_        =					field(
					    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"})
					a_        =					field(
					    default=UpperCamelCase     ,				metadata={"help": "Pretrained config name or path if not the same as model_name"})
					a_        =					field(
					    default=UpperCamelCase     ,				metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"})
					a_        =					field(
					    default=UpperCamelCase     ,				metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}     ,				)






@dataclass
class  snake_case__      :
					a_        =					field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys())})
					a_        =					field(metadata={"help": "Should contain the data files for the task."})
					a_        =					field(
					    default=128     ,				metadata={
					        "help": (
					            "The maximum total input sequence length after tokenization. Sequences longer "
					            "than this will be truncated, sequences shorter will be padded."
					        )
					    }     ,				)
					a_        =					field(
					    default=UpperCamelCase     ,				metadata={"help": "Overwrite the cached training and evaluation sets"})






def __UpperCAmelCase   (					)    ->   int:
			# See all possible arguments in src/transformers/training_args.py
			# or by passing the --help flag to this script.
			# We now keep distinct sets of args, for a cleaner separation of concerns.

			UpperCAmelCase_      :       List[Any]          =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
			UpperCAmelCase_    ,      UpperCAmelCase_    ,      UpperCAmelCase_      :       List[str]          =       parser.parse_args_into_dataclasses()

			if (
			    os.path.exists(training_args.output_dir		)
			    and os.listdir(training_args.output_dir		)
			    and training_args.do_train
			    and not training_args.overwrite_output_dir
			):
						raise ValueError(
						    F"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
						    ''' --overwrite_output_dir to overcome.'''		)

			# Setup logging
			logging.basicConfig(
			    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''			,       datefmt='''%m/%d/%Y %H:%M:%S'''			,       level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN			,       )
			logger.warning(
			    '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'''			,       training_args.local_rank			,       training_args.device			,       training_args.n_gpu			,       bool(training_args.local_rank != -1		)			,       training_args.fpaa			,       )
			# Set the verbosity to info of the Transformers logger (on main process only):
			if is_main_process(training_args.local_rank		):
						transformers.utils.logging.set_verbosity_info()
						transformers.utils.logging.enable_default_handler()
						transformers.utils.logging.enable_explicit_format()
			logger.info('''Training/evaluation parameters %s'''			,       A		)

			# Set seed
			set_seed(training_args.seed		)

			try:
						UpperCAmelCase_      :       int          =       processors[data_args.task_name]()
						UpperCAmelCase_      :       str          =       processor.get_labels()
						UpperCAmelCase_      :       Optional[int]          =       len(A		)
			except KeyError:
						raise ValueError('''Task not found: %s''' % (data_args.task_name)		)

			# Load pretrained model and tokenizer
			#
			# Distributed training:
			# The .from_pretrained methods guarantee that only one local process can concurrently
			# download model & vocab.

			UpperCAmelCase_      :       Dict          =       AutoConfig.from_pretrained(
			    model_args.config_name if model_args.config_name else model_args.model_name_or_path			,       num_labels=A			,       finetuning_task=data_args.task_name			,       cache_dir=model_args.cache_dir			,       )
			UpperCAmelCase_      :       Union[str, Any]          =       AutoTokenizer.from_pretrained(
			    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path			,       cache_dir=model_args.cache_dir			,       )
			UpperCAmelCase_      :       int          =       AutoModelForMultipleChoice.from_pretrained(
			    model_args.model_name_or_path			,       from_tf=bool('''.ckpt''' in model_args.model_name_or_path		)			,       config=A			,       cache_dir=model_args.cache_dir			,       )

			# Get datasets
			UpperCAmelCase_      :       str          =       (
			    MultipleChoiceDataset(
			        data_dir=data_args.data_dir			,       tokenizer=A			,       task=data_args.task_name			,       max_seq_length=data_args.max_seq_length			,       overwrite_cache=data_args.overwrite_cache			,       mode=Split.train			,       )
			    if training_args.do_train
			    else None
			)
			UpperCAmelCase_      :       Tuple          =       (
			    MultipleChoiceDataset(
			        data_dir=data_args.data_dir			,       tokenizer=A			,       task=data_args.task_name			,       max_seq_length=data_args.max_seq_length			,       overwrite_cache=data_args.overwrite_cache			,       mode=Split.dev			,       )
			    if training_args.do_eval
			    else None
			)

			def compute_metrics(A					:			EvalPrediction		) -> Dict:
						UpperCAmelCase_      :       Dict          =       np.argmax(p.predictions			,       axis=1		)
						return {"acc": simple_accuracy(A			,       p.label_ids		)}

			# Data collator
			UpperCAmelCase_      :       List[Any]          =       DataCollatorWithPadding(A			,       pad_to_multiple_of=8		) if training_args.fpaa else None

			# Initialize our Trainer
			UpperCAmelCase_      :       str          =       Trainer(
			    model=A			,       args=A			,       train_dataset=A			,       eval_dataset=A			,       compute_metrics=A			,       data_collator=A			,       )

			# Training
			if training_args.do_train:
						trainer.train(
						    model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path		) else None		)
						trainer.save_model()
						# For convenience, we also re-save the tokenizer to the same directory,
						# so that you can share your model easily on huggingface.co/models =)
						if trainer.is_world_master():
									tokenizer.save_pretrained(training_args.output_dir		)

    # Evaluation
			UpperCAmelCase_      :       Union[str, Any]          =       {}
			if training_args.do_eval:
						logger.info('''*** Evaluate ***'''		)

						UpperCAmelCase_      :       Tuple          =       trainer.evaluate()

						UpperCAmelCase_      :       Tuple          =       os.path.join(training_args.output_dir			,       '''eval_results.txt'''		)
						if trainer.is_world_master():
									with open(A			,       '''w'''		) as writer:
												logger.info('''***** Eval results *****'''		)
												for key, value in result.items():
															logger.info('''  %s = %s'''			,       A			,       A		)
															writer.write('''%s = %s\n''' % (key, value)		)

												results.update(A		)

			return results
def __UpperCAmelCase   (					A					:			Any		)    ->   List[str]:
			# For xla_spawn (TPUs)
			main()


if __name__ == "__main__":
						main()










'''simple docstring'''





from unittest.mock import patch

import pyspark

from datasets.packaged_modules.spark.spark import (
    Spark,
    SparkExamplesIterable,
    _generate_iterable_examples,
)

from ..utils import (
    require_dill_gt_0_3_2,
    require_not_windows,
)
def __UpperCAmelCase   (					A					:			Optional[int]			,       A					:			Optional[int]		)    ->   str:
			UpperCAmelCase_      :       List[Any]          =       []
			for part_id in partition_order:
						UpperCAmelCase_      :       Any          =       df.where(F"SPARK_PARTITION_ID() = {part_id}"		).collect()
						for row_idx, row in enumerate(A		):
									expected_row_ids_and_row_dicts.append((F"{part_id}_{row_idx}", row.asDict())		)
			return expected_row_ids_and_row_dicts
@require_not_windows
@require_dill_gt_0_3_2
def __UpperCAmelCase   (					)    ->   Any:
			UpperCAmelCase_      :       Any          =       pyspark.sql.SparkSession.builder.master('''local[*]'''		).appName('''pyspark'''		).getOrCreate()
			UpperCAmelCase_      :       List[str]          =       spark.range(1_0_0		).repartition(1		)
			UpperCAmelCase_      :       List[Any]          =       Spark(A		)
			# The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means
			# that each partition can hold 2 rows.
			spark_builder._repartition_df_if_needed(max_shard_size=1_6		)
			# Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions.
			assert spark_builder.df.rdd.getNumPartitions() == 5_0
@require_not_windows
@require_dill_gt_0_3_2
def __UpperCAmelCase   (					)    ->   str:
			UpperCAmelCase_      :       List[str]          =       pyspark.sql.SparkSession.builder.master('''local[*]'''		).appName('''pyspark'''		).getOrCreate()
			UpperCAmelCase_      :       Optional[Any]          =       spark.range(1_0		).repartition(2		)
			UpperCAmelCase_      :       int          =       [1, 0]
			UpperCAmelCase_      :       str          =       _generate_iterable_examples(A			,       A		)  # Reverse the partitions.
			UpperCAmelCase_      :       Optional[Any]          =       _get_expected_row_ids_and_row_dicts_for_partition_order(A			,       A		)

			for i, (row_id, row_dict) in enumerate(generate_fn()		):
						UpperCAmelCase_    ,      UpperCAmelCase_      :       int          =       expected_row_ids_and_row_dicts[i]
						assert row_id == expected_row_id
						assert row_dict == expected_row_dict
@require_not_windows
@require_dill_gt_0_3_2
def __UpperCAmelCase   (					)    ->   Union[str, Any]:
			UpperCAmelCase_      :       str          =       pyspark.sql.SparkSession.builder.master('''local[*]'''		).appName('''pyspark'''		).getOrCreate()
			UpperCAmelCase_      :       List[Any]          =       spark.range(1_0		).repartition(1		)
			UpperCAmelCase_      :       Optional[int]          =       SparkExamplesIterable(A		)
			assert it.n_shards == 1
			for i, (row_id, row_dict) in enumerate(A		):
						assert row_id == F"0_{i}"
						assert row_dict == {"id": i}
@require_not_windows
@require_dill_gt_0_3_2
def __UpperCAmelCase   (					)    ->   Union[str, Any]:
			UpperCAmelCase_      :       Dict          =       pyspark.sql.SparkSession.builder.master('''local[*]'''		).appName('''pyspark'''		).getOrCreate()
			UpperCAmelCase_      :       Dict          =       spark.range(3_0		).repartition(3		)
			# Mock the generator so that shuffle reverses the partition indices.
			with patch('''numpy.random.Generator'''		) as generator_mock:
						UpperCAmelCase_      :       Any          =       lambda A		: x.reverse()
						UpperCAmelCase_      :       Dict          =       _get_expected_row_ids_and_row_dicts_for_partition_order(A			,       [2, 1, 0]		)

						UpperCAmelCase_      :       List[Any]          =       SparkExamplesIterable(A		).shuffle_data_sources(A		)
						assert shuffled_it.n_shards == 3
						for i, (row_id, row_dict) in enumerate(A		):
									UpperCAmelCase_    ,      UpperCAmelCase_      :       Dict          =       expected_row_ids_and_row_dicts[i]
									assert row_id == expected_row_id
									assert row_dict == expected_row_dict
@require_not_windows
@require_dill_gt_0_3_2
def __UpperCAmelCase   (					)    ->   int:
			UpperCAmelCase_      :       Tuple          =       pyspark.sql.SparkSession.builder.master('''local[*]'''		).appName('''pyspark'''		).getOrCreate()
			UpperCAmelCase_      :       int          =       spark.range(2_0		).repartition(4		)

			# Partitions 0 and 2
			UpperCAmelCase_      :       int          =       SparkExamplesIterable(A		).shard_data_sources(worker_id=0			,       num_workers=2		)
			assert shard_it_a.n_shards == 2
			UpperCAmelCase_      :       Union[str, Any]          =       _get_expected_row_ids_and_row_dicts_for_partition_order(A			,       [0, 2]		)
			for i, (row_id, row_dict) in enumerate(A		):
						UpperCAmelCase_    ,      UpperCAmelCase_      :       Dict          =       expected_row_ids_and_row_dicts_a[i]
						assert row_id == expected_row_id
						assert row_dict == expected_row_dict

			# Partitions 1 and 3
			UpperCAmelCase_      :       Tuple          =       SparkExamplesIterable(A		).shard_data_sources(worker_id=1			,       num_workers=2		)
			assert shard_it_a.n_shards == 2
			UpperCAmelCase_      :       List[str]          =       _get_expected_row_ids_and_row_dicts_for_partition_order(A			,       [1, 3]		)
			for i, (row_id, row_dict) in enumerate(A		):
						UpperCAmelCase_    ,      UpperCAmelCase_      :       Union[str, Any]          =       expected_row_ids_and_row_dicts_a[i]
						assert row_id == expected_row_id
						assert row_dict == expected_row_dict







@require_not_windows
@require_dill_gt_0_3_2
def __UpperCAmelCase   (					)    ->   Any:
			UpperCAmelCase_      :       List[Any]          =       pyspark.sql.SparkSession.builder.master('''local[*]'''		).appName('''pyspark'''		).getOrCreate()
			UpperCAmelCase_      :       List[str]          =       spark.range(1_0_0		).repartition(1		)
			UpperCAmelCase_      :       int          =       Spark(A		)
			# Choose a small max_shard_size for maximum partitioning.
			spark_builder._repartition_df_if_needed(max_shard_size=1		)
			# The new number of partitions should not be greater than the number of rows.
			assert spark_builder.df.rdd.getNumPartitions() == 1_0_0


