


import json
import multiprocessing
import os
import re
from collections import defaultdict

import torch
from accelerate import Accelerator
from accelerate.utils import set_seed
from arguments import HumanEvalArguments
from datasets import load_dataset, load_metric
from torch.utils.data import IterableDataset
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm

import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList


snake_case_						:			Optional[Any]													=							['''\nclass''', '''\ndef''', '''\n#''', '''\n@''', '''\nprint''', '''\nif''']

class 						A__							(		__UpperCAmelCase  ):




      def __init__(       self					:      Optional[Any]				,    _a					:      Union[str, Any]				,    _a					:      Optional[int]				,    _a					:      List[Any]=None				,    _a					:      List[Any]=1  )							->     Any:


          """simple docstring"""





          _SCREAMING_SNAKE_CASE			  =tokenizer
          _SCREAMING_SNAKE_CASE			  =dataset
          _SCREAMING_SNAKE_CASE			  =len(__SCREAMING_SNAKE_CASE  ) if n_tasks is None else n_tasks
          _SCREAMING_SNAKE_CASE			  =n_copies




      def __iter__(       self					:      int  )							->     Tuple:


          """simple docstring"""





          _SCREAMING_SNAKE_CASE			  =[]
          for task in range(self.n_tasks  ):
              # without strip, the model generate commented codes ...
              prompts.append(self.tokenizer.eos_token + self.dataset[task]['''prompt'''].strip()  )
          _SCREAMING_SNAKE_CASE			  =self.tokenizer(__SCREAMING_SNAKE_CASE				,    padding=__SCREAMING_SNAKE_CASE				,    return_tensors='''pt'''  )
          for task in range(self.n_tasks  ):
              for _ in range(self.n_copies  ):
                  yield {
                      "ids": outputs.input_ids[task],
                      "task_id": task,
                      "input_len": outputs.attention_mask[task].sum(),
                  }

class 						A__							(		__UpperCAmelCase  ):




      def __init__(       self					:      Dict				,    _a					:      List[Any]				,    _a					:      Union[str, Any]				,    _a					:      Dict  )							->     int:


          """simple docstring"""





          _SCREAMING_SNAKE_CASE			  =start_length
          _SCREAMING_SNAKE_CASE			  =eof_strings
          _SCREAMING_SNAKE_CASE			  =tokenizer




      def __call__(       self					:      Union[str, Any]				,    _a					:      List[Any]				,    _a					:      str				,    **_a					:      Tuple  )							->     List[Any]:


          """simple docstring"""





          _SCREAMING_SNAKE_CASE			  =self.tokenizer.batch_decode(input_ids[:, self.start_length :]  )
          _SCREAMING_SNAKE_CASE			  =[]
          for decoded_generation in decoded_generations:
              done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings  )  )
          return all(__SCREAMING_SNAKE_CASE  )







def 						lowerCamelCase(   a__):
    _SCREAMING_SNAKE_CASE			  =re.split('''(%s)''' % '''|'''.join(_UpperCAmelCase)	,_UpperCAmelCase)
    # last string should be ""
    return "".join(string_list[:-2])







def 						lowerCamelCase(   a__	,a__	,a__	,a__	,a__	,a__=20	,**a__):
    _SCREAMING_SNAKE_CASE			  =defaultdict(_UpperCAmelCase)  # dict of list of generated tokens
    for step, batch in tqdm(enumerate(_UpperCAmelCase)):
        with torch.no_grad():
            _SCREAMING_SNAKE_CASE			  =batch['''ids'''].shape[-1]
            _SCREAMING_SNAKE_CASE			  =accelerator.unwrap_model(_UpperCAmelCase).generate(
                input_ids=batch['''ids'''][:, : batch['''input_len''']]	,num_return_sequences=_UpperCAmelCase	,**_UpperCAmelCase)
            # each task is generated batch_size times
            _SCREAMING_SNAKE_CASE			  =batch['''task_id'''].repeat(_UpperCAmelCase)
            _SCREAMING_SNAKE_CASE			  =accelerator.pad_across_processes(
                _UpperCAmelCase	,dim=1	,pad_index=tokenizer.pad_token_id)

            _SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE			  =accelerator.gather((generated_tokens, generated_tasks))
            _SCREAMING_SNAKE_CASE			  =generated_tokens.cpu().numpy()
            _SCREAMING_SNAKE_CASE			  =generated_tasks.cpu().numpy()

            for task, generated_tokens in zip(_UpperCAmelCase	,_UpperCAmelCase):
                gen_token_dict[task].append(_UpperCAmelCase)

    _SCREAMING_SNAKE_CASE			  =[[] for _ in range(_UpperCAmelCase)]
    for task, generated_tokens in gen_token_dict.items():
        for s in generated_tokens:
            _SCREAMING_SNAKE_CASE			  =tokenizer.decode(_UpperCAmelCase	,skip_special_tokens=_UpperCAmelCase	,clean_up_tokenization_spaces=_UpperCAmelCase)
            code_gens[task].append(remove_last_block(_UpperCAmelCase))
    return code_gens







def 						lowerCamelCase(   ):
    # Setup configuration
    _SCREAMING_SNAKE_CASE			  =HfArgumentParser(_UpperCAmelCase)
    _SCREAMING_SNAKE_CASE			  =parser.parse_args()

    transformers.logging.set_verbosity_error()
    # enables code execution in code_eval metric
    _SCREAMING_SNAKE_CASE			  =args.HF_ALLOW_CODE_EVAL
    # make sure tokenizer plays nice with multiprocessing
    _SCREAMING_SNAKE_CASE			  ='''false'''

    if args.num_workers is None:
        _SCREAMING_SNAKE_CASE			  =multiprocessing.cpu_count()

    # Use dataset load to feed to accelerate
    _SCREAMING_SNAKE_CASE			  =Accelerator()
    set_seed(args.seed	,device_specific=_UpperCAmelCase)

    # Load model and tokenizer
    _SCREAMING_SNAKE_CASE			  =AutoTokenizer.from_pretrained(args.model_ckpt)
    _SCREAMING_SNAKE_CASE			  =tokenizer.eos_token
    _SCREAMING_SNAKE_CASE			  =AutoModelForCausalLM.from_pretrained(args.model_ckpt)

    # Generation settings
    _SCREAMING_SNAKE_CASE			  ={
        '''do_sample''': args.do_sample,
        '''temperature''': args.temperature,
        '''max_new_tokens''': args.max_new_tokens,
        '''top_p''': args.top_p,
        '''top_k''': args.top_k,
        '''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0	,_UpperCAmelCase	,_UpperCAmelCase)]),
    }

    # Load evaluation dataset and metric
    _SCREAMING_SNAKE_CASE			  =load_dataset('''openai_humaneval''')
    _SCREAMING_SNAKE_CASE			  =load_metric('''code_eval''')

    _SCREAMING_SNAKE_CASE			  =args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''])
    _SCREAMING_SNAKE_CASE			  =args.n_samples // args.batch_size

    _SCREAMING_SNAKE_CASE			  =TokenizedDataset(_UpperCAmelCase	,human_eval['''test''']	,n_copies=_UpperCAmelCase	,n_tasks=_UpperCAmelCase)
    # do not confuse args.batch_size, which is actually the num_return_sequences
    _SCREAMING_SNAKE_CASE			  =DataLoader(_UpperCAmelCase	,batch_size=1)

    # Run a quick test to see if code evaluation is enabled
    try:
        _SCREAMING_SNAKE_CASE			  =code_eval_metric.compute(references=['''''']	,predictions=[['''''']])
    except ValueError as exception:
        print(
            '''Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`'''
            ''' flag to enable code evaluation.''')
        raise exception

    _SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE			  =accelerator.prepare(_UpperCAmelCase	,_UpperCAmelCase)

    _SCREAMING_SNAKE_CASE			  =complete_code(
        _UpperCAmelCase	,_UpperCAmelCase	,_UpperCAmelCase	,_UpperCAmelCase	,n_tasks=_UpperCAmelCase	,batch_size=args.batch_size	,**_UpperCAmelCase	,)

    if accelerator.is_main_process:
        _SCREAMING_SNAKE_CASE			  =[]

        for task in tqdm(range(_UpperCAmelCase)):
            _SCREAMING_SNAKE_CASE			  =human_eval['''test'''][task]['''test''']
            _SCREAMING_SNAKE_CASE			  =f"check({human_eval['test'][task]['entry_point']})"
            references.append('''\n''' + test_func + '''\n''' + entry_point)

        # Evaluate completions with "code_eval" metric
        _SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE			  =code_eval_metric.compute(
            references=_UpperCAmelCase	,predictions=_UpperCAmelCase	,num_workers=args.num_workers)
        print(f"Results: {pass_at_k}")

        # Save results to json file
        with open(args.output_file	,'''w''') as fp:
            json.dump(_UpperCAmelCase	,_UpperCAmelCase)


# For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing
# https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script
if __name__ == "__main__":
       main()



from collections.abc import Generator







def 						lowerCamelCase(   ):
				_SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE			  =0, 1
				while True:
								_SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE			  =b, a + b
								yield b







def 						lowerCamelCase(   a__ = 1000):
				_SCREAMING_SNAKE_CASE			  =1
				_SCREAMING_SNAKE_CASE			  =fibonacci_generator()
				while len(str(next(a__))) < n:
								answer += 1
				return answer + 1


if __name__ == "__main__":
							print(solution(int(str(input()).strip())))