





'''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


_SCREAMING_SNAKE_CASE	 =							logging.getLogger(__name__)


def 	__a(SCREAMING_SNAKE_CASE_  :					Dict		,       SCREAMING_SNAKE_CASE_  :					str    ):



    '''simple docstring'''





    return (preds == labels).mean()

@dataclass
class    lowerCAmelCase_		:
    __lowerCamelCase						:							Optional[int]         =					field(
        metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}		)
    __lowerCamelCase						:							str         =					field(
        default=lowercase__						,metadata={"help": "Pretrained config name or path if not the same as model_name"}		)
    __lowerCamelCase						:							Dict         =					field(
        default=lowercase__						,metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}		)
    __lowerCamelCase						:							Optional[int]         =					field(
        default=lowercase__						,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}						,)







@dataclass
class    lowerCAmelCase_		:
    __lowerCamelCase						:							str         =					field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys()		)}		)
    __lowerCamelCase						:							Optional[int]         =					field(metadata={"help": "Should contain the data files for the task."}		)
    __lowerCamelCase						:							List[str]         =					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."
            )
        }						,)
    __lowerCamelCase						:							Tuple         =					field(
        default=lowercase__						,metadata={"help": "Overwrite the cached training and evaluation sets"}		)







def 	__a():



    '''simple docstring'''





    _lowerCAmelCase				=      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)    )
    _lowerCAmelCase				=      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:
        _lowerCAmelCase				=      processors[data_args.task_name]()
        _lowerCAmelCase				=      processor.get_labels()
        _lowerCAmelCase				=      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.

    _lowerCAmelCase				=      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		,       )
    _lowerCAmelCase				=      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		,       )
    _lowerCAmelCase				=      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
    _lowerCAmelCase				=      (
        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
    )
    _lowerCAmelCase				=      (
        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(SCREAMING_SNAKE_CASE_  :					EvalPrediction    ) -> Dict:
        _lowerCAmelCase				=      np.argmax(p.predictions		,       axis=1    )
        return {"acc": simple_accuracy(_A		,       p.label_ids    )}

    # Data collator
    _lowerCAmelCase				=      DataCollatorWithPadding(_A		,       pad_to_multiple_of=8    ) if training_args.fpaa else None

    # Initialize our Trainer
    _lowerCAmelCase				=      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
    _lowerCAmelCase				=      {}
    if training_args.do_eval:
        logger.info("*** Evaluate ***"    )

        _lowerCAmelCase				=      trainer.evaluate()

        _lowerCAmelCase				=      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 	__a(SCREAMING_SNAKE_CASE_  :					Tuple    ):



    '''simple docstring'''





    main()


if __name__ == "__main__":
       main()









'''simple docstring'''


_SCREAMING_SNAKE_CASE	 =							range(2, 20 + 1)
_SCREAMING_SNAKE_CASE	 =							[10**k for k in range(ks[-1] + 1)]
_SCREAMING_SNAKE_CASE	 =							{}


def 	__a(SCREAMING_SNAKE_CASE_  :					Tuple		,       SCREAMING_SNAKE_CASE_  :					str		,       SCREAMING_SNAKE_CASE_  :					Any		,       SCREAMING_SNAKE_CASE_  :					List[str]    ):



    '''simple docstring'''





    _lowerCAmelCase				=      sum(a_i[j] for j in range(SCREAMING_SNAKE_CASE_		,       len(SCREAMING_SNAKE_CASE_    )    )    )
    _lowerCAmelCase				=      sum(a_i[j] * base[j] for j in range(min(len(SCREAMING_SNAKE_CASE_    )		,       SCREAMING_SNAKE_CASE_    )    )    )

    _lowerCAmelCase			,			_lowerCAmelCase				=      0, 0
    _lowerCAmelCase				=      n - i

    _lowerCAmelCase				=      memo.get(SCREAMING_SNAKE_CASE_    )

    if sub_memo is not None:
        _lowerCAmelCase				=      sub_memo.get(SCREAMING_SNAKE_CASE_    )

        if jumps is not None and len(SCREAMING_SNAKE_CASE_    ) > 0:
            # find and make the largest jump without going over
            _lowerCAmelCase				=      -1
            for _k in range(len(SCREAMING_SNAKE_CASE_    ) - 1		,       -1		,       -1    ):
                if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
                    _lowerCAmelCase				=      _k
                    break

            if max_jump >= 0:
                _lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase				=      jumps[max_jump]
                # since the difference between jumps is cached, add c
                _lowerCAmelCase				=      diff + c
                for j in range(min(SCREAMING_SNAKE_CASE_		,       len(SCREAMING_SNAKE_CASE_    )    )    ):
                    _lowerCAmelCase			,			_lowerCAmelCase				=      divmod(SCREAMING_SNAKE_CASE_		,       10    )
                if new_c > 0:
                    add(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_    )

        else:
            _lowerCAmelCase				=      []
    else:
        _lowerCAmelCase				=      {c: []}
        _lowerCAmelCase				=      sub_memo

    if dn >= max_dn or c + diff >= base[k]:
        return diff, dn

    if k > ks[0]:
        while True:
            # keep doing smaller jumps
            _lowerCAmelCase			,			_lowerCAmelCase				=      next_term(SCREAMING_SNAKE_CASE_		,       k - 1		,       i + dn		,       SCREAMING_SNAKE_CASE_    )
            diff += _diff
            dn += terms_jumped

            if dn >= max_dn or c + diff >= base[k]:
                break
    else:
        # would be too small a jump, just compute sequential terms instead
        _lowerCAmelCase			,			_lowerCAmelCase				=      compute(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_		,       i + dn		,       SCREAMING_SNAKE_CASE_    )
        diff += _diff
        dn += terms_jumped

    _lowerCAmelCase				=      sub_memo[c]

    # keep jumps sorted by # of terms skipped
    _lowerCAmelCase				=      0
    while j < len(SCREAMING_SNAKE_CASE_    ):
        if jumps[j][1] > dn:
            break
        j += 1

    # cache the jump for this value digitsum(b) and c
    sub_memo[c].insert(SCREAMING_SNAKE_CASE_		,       (diff, dn, k)    )
    return (diff, dn)


def 	__a(SCREAMING_SNAKE_CASE_  :					Dict		,       SCREAMING_SNAKE_CASE_  :					int		,       SCREAMING_SNAKE_CASE_  :					Dict		,       SCREAMING_SNAKE_CASE_  :					Union[str, Any]    ):



    '''simple docstring'''





    if i >= n:
        return 0, i
    if k > len(SCREAMING_SNAKE_CASE_    ):
        a_i.extend([0 for _ in range(k - len(SCREAMING_SNAKE_CASE_    )    )]    )

    # note: a_i -> b * 10^k + c
    # ds_b -> digitsum(b)
    # ds_c -> digitsum(c)
    _lowerCAmelCase				=      i
    _lowerCAmelCase			,			_lowerCAmelCase			,			_lowerCAmelCase				=      0, 0, 0
    for j in range(len(SCREAMING_SNAKE_CASE_    )    ):
        if j >= k:
            ds_b += a_i[j]
        else:
            ds_c += a_i[j]

    while i < n:
        i += 1
        _lowerCAmelCase				=      ds_c + ds_b
        diff += addend
        _lowerCAmelCase				=      0
        for j in range(SCREAMING_SNAKE_CASE_    ):
            _lowerCAmelCase				=      a_i[j] + addend
            _lowerCAmelCase			,			_lowerCAmelCase				=      divmod(SCREAMING_SNAKE_CASE_		,       10    )

            ds_c += a_i[j]

        if addend > 0:
            break

    if addend > 0:
        add(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_    )
    return diff, i - start_i


def 	__a(SCREAMING_SNAKE_CASE_  :					List[Any]		,       SCREAMING_SNAKE_CASE_  :					int		,       SCREAMING_SNAKE_CASE_  :					Any    ):



    '''simple docstring'''





    for j in range(SCREAMING_SNAKE_CASE_		,       len(SCREAMING_SNAKE_CASE_    )    ):
        _lowerCAmelCase				=      digits[j] + addend
        if s >= 10:
            _lowerCAmelCase			,			_lowerCAmelCase				=      divmod(SCREAMING_SNAKE_CASE_		,       10    )
            _lowerCAmelCase				=      addend // 10 + quotient
        else:
            _lowerCAmelCase				=      s
            _lowerCAmelCase				=      addend // 10

        if addend == 0:
            break

    while addend > 0:
        _lowerCAmelCase			,			_lowerCAmelCase				=      divmod(SCREAMING_SNAKE_CASE_		,       10    )
        digits.append(SCREAMING_SNAKE_CASE_    )


def 	__a(SCREAMING_SNAKE_CASE_  :					int = 10**15    ):



    '''simple docstring'''





    _lowerCAmelCase				=      [1]
    _lowerCAmelCase				=      1
    _lowerCAmelCase				=      0
    while True:
        _lowerCAmelCase			,			_lowerCAmelCase				=      next_term(SCREAMING_SNAKE_CASE_		,       20		,       i + dn		,       SCREAMING_SNAKE_CASE_    )
        dn += terms_jumped
        if dn == n - i:
            break

    _lowerCAmelCase				=      0
    for j in range(len(SCREAMING_SNAKE_CASE_    )    ):
        a_n += digits[j] * 10**j
    return a_n


if __name__ == "__main__":
       print(f'''{solution() = }''')


