



"""simple docstring"""
import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union

import datasets
import numpy as np
import torch
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

__a      =				logging.getLogger(__name__)
@dataclass
class 				lowerCamelCase  :






					'''simple docstring'''





					_A		:			str						=     field(
					    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}				)
					_A		:			Optional[str]						=     field(
					    default=_lowerCAmelCase    ,						metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}				)
					_A		:			Optional[str]						=     field(
					    default=_lowerCAmelCase    ,						metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}				)
					_A		:			Optional[str]						=     field(
					    default=_lowerCAmelCase    ,						metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}    ,						)
					_A		:			bool						=     field(
					    default=_lowerCAmelCase    ,						metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""}    ,						)
					_A		:			str						=     field(
					    default="""main"""    ,						metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}    ,						)
					_A		:			bool						=     field(
					    default=_lowerCAmelCase    ,						metadata={
					        """help""": (
					            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
					            """with private models)."""
					        )
					    }    ,						)

@dataclass
class 				lowerCamelCase  :






					'''simple docstring'''





					_A		:			Optional[str]						=     field(default=_lowerCAmelCase    ,						metadata={"""help""": """The input training data file (a text file)."""}				)
					_A		:			Optional[str]						=     field(
					    default=_lowerCAmelCase    ,						metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""}    ,						)
					_A		:			bool						=     field(
					    default=_lowerCAmelCase    ,						metadata={"""help""": """Overwrite the cached training and evaluation sets"""}				)
					_A		:			Optional[int]						=     field(
					    default=_lowerCAmelCase    ,						metadata={"""help""": """The number of processes to use for the preprocessing."""}    ,						)
					_A		:			Optional[int]						=     field(
					    default=_lowerCAmelCase    ,						metadata={
					        """help""": (
					            """The maximum total input sequence length after tokenization. If passed, sequences longer """
					            """than this will be truncated, sequences shorter will be padded."""
					        )
					    }    ,						)
					_A		:			bool						=     field(
					    default=_lowerCAmelCase    ,						metadata={
					        """help""": (
					            """Whether to pad all samples to the maximum sentence length. """
					            """If False, will pad the samples dynamically when batching to the maximum length in the batch. More """
					            """efficient on GPU but very bad for TPU."""
					        )
					    }    ,						)
					_A		:			Optional[int]						=     field(
					    default=_lowerCAmelCase    ,						metadata={
					        """help""": (
					            """For debugging purposes or quicker training, truncate the number of training examples to this """
					            """value if set."""
					        )
					    }    ,						)
					_A		:			Optional[int]						=     field(
					    default=_lowerCAmelCase    ,						metadata={
					        """help""": (
					            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
					            """value if set."""
					        )
					    }    ,						)






					def    lowerCAmelCase_				(       self:							List[str]						)   ->	Tuple:
											if self.train_file is not None:
																	snake_case_ :Optional[int]						=			self.train_file.split("""."""						)[-1]
																	assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
											if self.validation_file is not None:
																	snake_case_ :Tuple						=			self.validation_file.split("""."""						)[-1]
																	assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."

@dataclass
class 				lowerCamelCase  :






					'''simple docstring'''





					_A		:			PreTrainedTokenizerBase
					_A		:			Union[bool, str, PaddingStrategy]						=     True
					_A		:			Optional[int]						=     None
					_A		:			Optional[int]						=     None






					def __call__(       self:							Dict						,     snake_case:							Union[str, Any]						)   ->	Dict:
											snake_case_ :Dict						=			"""label""" if """label""" in features[0].keys() else """labels"""
											snake_case_ :Union[str, Any]						=			[feature.pop(snake_case						) for feature in features]
											snake_case_ :List[Any]						=			len(snake_case						)
											snake_case_ :Dict						=			len(features[0]["""input_ids"""]						)
											snake_case_ :Any						=			[
											    [{k: v[i] for k, v in feature.items()} for i in range(snake_case						)] for feature in features
											]
											snake_case_ :Union[str, Any]						=			list(chain(*snake_case						)						)

											snake_case_ :Optional[Any]						=			self.tokenizer.pad(
											    snake_case						,     padding=self.padding						,     max_length=self.max_length						,     pad_to_multiple_of=self.pad_to_multiple_of						,     return_tensors="""pt"""						,     )

											# Un-flatten
											snake_case_ :Optional[Any]						=			{k: v.view(snake_case						,     snake_case						,     -1						) for k, v in batch.items()}
											# Add back labels
											snake_case_ :Dict						=			torch.tensor(snake_case						,     dtype=torch.intaa						)
											return batch

def    A_  (			):







						'''simple docstring'''


						snake_case_ :str						=			HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)
						if len(sys.argv	) == 2 and sys.argv[1].endswith(""".json"""	):
												# If we pass only one argument to the script and it's the path to a json file,
												# let's parse it to get our arguments.
												snake_case_,       snake_case_,       snake_case_ :Any						=			parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]	)	)
						else:
												snake_case_,       snake_case_,       snake_case_ :List[Any]						=			parser.parse_args_into_dataclasses()

						# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
						# information sent is the one passed as arguments along with your Python/PyTorch versions.
						send_example_telemetry("""run_swag""",					_lowercase,					_lowercase	)

						# Setup logging
						logging.basicConfig(
						    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""",					datefmt="""%m/%d/%Y %H:%M:%S""",					handlers=[logging.StreamHandler(sys.stdout	)],					)

						if training_args.should_log:
												# The default of training_args.log_level is passive, so we set log level at info here to have that default.
												transformers.utils.logging.set_verbosity_info()

						snake_case_ :int						=			training_args.get_process_log_level()
						logger.setLevel(_lowercase	)
						datasets.utils.logging.set_verbosity(_lowercase	)
						transformers.utils.logging.set_verbosity(_lowercase	)
						transformers.utils.logging.enable_default_handler()
						transformers.utils.logging.enable_explicit_format()

						# Log on each process the small summary:
						logger.warning(
						    f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
						    + f"""distributed training: {bool(training_args.local_rank != -1	)}, 16-bits training: {training_args.fpaa}"""	)
						logger.info(f"""Training/evaluation parameters {training_args}"""	)

						# Detecting last checkpoint.
						snake_case_ :List[Any]						=			None
						if os.path.isdir(training_args.output_dir	) and training_args.do_train and not training_args.overwrite_output_dir:
												snake_case_ :Dict						=			get_last_checkpoint(training_args.output_dir	)
												if last_checkpoint is None and len(os.listdir(training_args.output_dir	)	) > 0:
																		raise ValueError(
																		    f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
																		    """Use --overwrite_output_dir to overcome."""	)
												elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
																		logger.info(
																		    f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
																		    """the `--output_dir` or add `--overwrite_output_dir` to train from scratch."""	)

    # Set seed before initializing model.
						set_seed(training_args.seed	)

						# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
						# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
						# (the dataset will be downloaded automatically from the datasets Hub).

						# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
						# 'text' is found. You can easily tweak this behavior (see below).

						# In distributed training, the load_dataset function guarantee that only one local process can concurrently
						# download the dataset.
						if data_args.train_file is not None or data_args.validation_file is not None:
												snake_case_ :int						=			{}
												if data_args.train_file is not None:
																		snake_case_ :Dict						=			data_args.train_file
												if data_args.validation_file is not None:
																		snake_case_ :Optional[Any]						=			data_args.validation_file
												snake_case_ :str						=			data_args.train_file.split("""."""	)[-1]
												snake_case_ :Any						=			load_dataset(
												    _lowercase,					data_files=_lowercase,					cache_dir=model_args.cache_dir,					use_auth_token=True if model_args.use_auth_token else None,					)
						else:
												# Downloading and loading the swag dataset from the hub.
												snake_case_ :str						=			load_dataset(
												    """swag""",					"""regular""",					cache_dir=model_args.cache_dir,					use_auth_token=True if model_args.use_auth_token else None,					)
						# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
						# https://huggingface.co/docs/datasets/loading_datasets.html.

						# Load pretrained model and tokenizer

						# Distributed training:
						# The .from_pretrained methods guarantee that only one local process can concurrently
						# download model & vocab.
						snake_case_ :List[str]						=			AutoConfig.from_pretrained(
						    model_args.config_name if model_args.config_name else model_args.model_name_or_path,					cache_dir=model_args.cache_dir,					revision=model_args.model_revision,					use_auth_token=True if model_args.use_auth_token else None,					)
						snake_case_ :str						=			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,					use_fast=model_args.use_fast_tokenizer,					revision=model_args.model_revision,					use_auth_token=True if model_args.use_auth_token else None,					)
						snake_case_ :int						=			AutoModelForMultipleChoice.from_pretrained(
						    model_args.model_name_or_path,					from_tf=bool(""".ckpt""" in model_args.model_name_or_path	),					config=_lowercase,					cache_dir=model_args.cache_dir,					revision=model_args.model_revision,					use_auth_token=True if model_args.use_auth_token else None,					)

						# When using your own dataset or a different dataset from swag, you will probably need to change this.
						snake_case_ :Optional[int]						=			[f"""ending{i}""" for i in range(4	)]
						snake_case_ :int						=			"""sent1"""
						snake_case_ :int						=			"""sent2"""

						if data_args.max_seq_length is None:
												snake_case_ :int						=			tokenizer.model_max_length
												if max_seq_length > 1024:
																		logger.warning(
																		    """The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value"""
																		    """ of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can"""
																		    """ override this default with `--block_size xxx`."""	)
																		snake_case_ :Optional[int]						=			1024
						else:
												if data_args.max_seq_length > tokenizer.model_max_length:
																		logger.warning(
																		    f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"""
																		    f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."""	)
												snake_case_ :Any						=			min(data_args.max_seq_length,					tokenizer.model_max_length	)

						# Preprocessing the datasets.
						def preprocess_function(_lowercase	):
												snake_case_ :Dict						=			[[context] * 4 for context in examples[context_name]]
												snake_case_ :Optional[Any]						=			examples[question_header_name]
												snake_case_ :Optional[int]						=			[
												    [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(_lowercase	)
												]

												# Flatten out
												snake_case_ :Optional[int]						=			list(chain(*_lowercase	)	)
												snake_case_ :Optional[int]						=			list(chain(*_lowercase	)	)

												# Tokenize
												snake_case_ :Any						=			tokenizer(
												    _lowercase,					_lowercase,					truncation=_lowercase,					max_length=_lowercase,					padding="""max_length""" if data_args.pad_to_max_length else False,					)
												# Un-flatten
												return {k: [v[i : i + 4] for i in range(0,					len(_lowercase	),					4	)] for k, v in tokenized_examples.items()}

						if training_args.do_train:
												if "train" not in raw_datasets:
																		raise ValueError("""--do_train requires a train dataset"""	)
												snake_case_ :Dict						=			raw_datasets["""train"""]
												if data_args.max_train_samples is not None:
																		snake_case_ :Optional[int]						=			min(len(_lowercase	),					data_args.max_train_samples	)
																		snake_case_ :Tuple						=			train_dataset.select(range(_lowercase	)	)
												with training_args.main_process_first(desc="""train dataset map pre-processing"""	):
																		snake_case_ :int						=			train_dataset.map(
																		    _lowercase,					batched=_lowercase,					num_proc=data_args.preprocessing_num_workers,					load_from_cache_file=not data_args.overwrite_cache,					)

						if training_args.do_eval:
												if "validation" not in raw_datasets:
																		raise ValueError("""--do_eval requires a validation dataset"""	)
												snake_case_ :str						=			raw_datasets["""validation"""]
												if data_args.max_eval_samples is not None:
																		snake_case_ :Any						=			min(len(_lowercase	),					data_args.max_eval_samples	)
																		snake_case_ :Optional[Any]						=			eval_dataset.select(range(_lowercase	)	)
												with training_args.main_process_first(desc="""validation dataset map pre-processing"""	):
																		snake_case_ :List[Any]						=			eval_dataset.map(
																		    _lowercase,					batched=_lowercase,					num_proc=data_args.preprocessing_num_workers,					load_from_cache_file=not data_args.overwrite_cache,					)

    # Data collator
						snake_case_ :List[str]						=			(
						    default_data_collator
						    if data_args.pad_to_max_length
						    else DataCollatorForMultipleChoice(tokenizer=_lowercase,					pad_to_multiple_of=8 if training_args.fpaa else None	)
						)

						# Metric
						def compute_metrics(_lowercase	):
												snake_case_,       snake_case_ :Dict						=			eval_predictions
												snake_case_ :Tuple						=			np.argmax(_lowercase,					axis=1	)
												return {"accuracy": (preds == label_ids).astype(np.floataa	).mean().item()}

						# Initialize our Trainer
						snake_case_ :int						=			Trainer(
						    model=_lowercase,					args=_lowercase,					train_dataset=train_dataset if training_args.do_train else None,					eval_dataset=eval_dataset if training_args.do_eval else None,					tokenizer=_lowercase,					data_collator=_lowercase,					compute_metrics=_lowercase,					)

						# Training
						if training_args.do_train:
												snake_case_ :Tuple						=			None
												if training_args.resume_from_checkpoint is not None:
																		snake_case_ :List[Any]						=			training_args.resume_from_checkpoint
												elif last_checkpoint is not None:
																		snake_case_ :List[Any]						=			last_checkpoint
												snake_case_ :Any						=			trainer.train(resume_from_checkpoint=_lowercase	)
												trainer.save_model()  # Saves the tokenizer too for easy upload
												snake_case_ :Tuple						=			train_result.metrics

												snake_case_ :List[Any]						=			(
												    data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowercase	)
												)
												snake_case_ :Optional[Any]						=			min(_lowercase,					len(_lowercase	)	)

												trainer.log_metrics("""train""",					_lowercase	)
												trainer.save_metrics("""train""",					_lowercase	)
												trainer.save_state()

						# Evaluation
						if training_args.do_eval:
												logger.info("""*** Evaluate ***"""	)

												snake_case_ :List[Any]						=			trainer.evaluate()
												snake_case_ :List[Any]						=			data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_lowercase	)
												snake_case_ :Union[str, Any]						=			min(_lowercase,					len(_lowercase	)	)

												trainer.log_metrics("""eval""",					_lowercase	)
												trainer.save_metrics("""eval""",					_lowercase	)

						snake_case_ :int						=			{
						    """finetuned_from""": model_args.model_name_or_path,
						    """tasks""": """multiple-choice""",
						    """dataset_tags""": """swag""",
						    """dataset_args""": """regular""",
						    """dataset""": """SWAG""",
						    """language""": """en""",
						}

						if training_args.push_to_hub:
												trainer.push_to_hub(**_lowercase	)
						else:
												trainer.create_model_card(**_lowercase	)
def    A_  (			_lowercase	):







						'''simple docstring'''


						main()


if __name__ == "__main__":
						main()



'''simple docstring'''






from __future__ import annotations


def 		_A     (    A__      ):






 """simple docstring"""



 __lowercase							  = len(A__      )
 # We need to create solution object to save path.
 __lowercase							  = [[0 for _ in range(A__      )] for _ in range(A__      )]
 __lowercase							  = run_maze(A__     ,				0     ,				0     ,				A__      )
 if solved:
  print('''\n'''.join(str(A__      ) for row in solutions      )      )
 else:
  print('''No solution exists!'''      )
 return solved


def 		_A     (    A__     ,				A__     ,				A__     ,				A__      ):






 """simple docstring"""



 __lowercase							  = len(A__      )
 # Final check point.
 if i == j == (size - 1):
  __lowercase							  = 1
  return True

 __lowercase							  = (not i < 0) and (not j < 0)  # Check lower bounds
 __lowercase							  = (i < size) and (j < size)  # Check upper bounds

 if lower_flag and upper_flag:
  # check for already visited and block points.
  __lowercase							  = (not solutions[i][j]) and (not maze[i][j])
  if block_flag:
   # check visited
   __lowercase							  = 1

   # check for directions
   if (
       run_maze(A__     ,				i + 1     ,				A__     ,				A__      )
       or run_maze(A__     ,				A__     ,				j + 1     ,				A__      )
       or run_maze(A__     ,				i - 1     ,				A__     ,				A__      )
       or run_maze(A__     ,				A__     ,				j - 1     ,				A__      )
   ):
    return True

   __lowercase							  = 0
   return False
 return False


if __name__ == "__main__":
 import doctest

 doctest.testmod()

