



import argparse
import gc
import json
import os

import torch
from datasets import load_dataset
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
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler


__UpperCAmelCase			  =			16
__UpperCAmelCase			  =			32
def 						UpperCamelCase      (  snake_case__			:       Dict      )      ->	Any:
   return int(x / 2**20      )



class 							lowerCAmelCase_						:
       def __enter__(     self			)	->						Any:
          gc.collect()
          torch.cuda.empty_cache()
          torch.cuda.reset_max_memory_allocated()  # reset the peak gauge to zero
          UpperCamelCase       :    List[str]		      =      torch.cuda.memory_allocated()
          return self






       def __exit__(     self,     *SCREAMING_SNAKE_CASE_			)	->						List[Any]:
          gc.collect()
          torch.cuda.empty_cache()
          UpperCamelCase       :    Union[str, Any]		      =      torch.cuda.memory_allocated()
          UpperCamelCase       :    Dict		      =      torch.cuda.max_memory_allocated()
          UpperCamelCase       :    Tuple		      =      bamb(self.end - self.begin			)
          UpperCamelCase       :    Tuple		      =      bamb(self.peak - self.begin			)
          # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")






def 						UpperCamelCase      (  snake_case__			:       Accelerator			,	snake_case__			:       int = 16			,	snake_case__			:       str = "bert-base-cased"			,	snake_case__			:       int = 320			,	snake_case__			:       int = 160			,	)      ->	Any:
   UpperCamelCase       :    Tuple		      =      AutoTokenizer.from_pretrained(snake_case__      )
   UpperCamelCase       :    Optional[int]		      =      load_dataset(
       'glue'			,	'mrpc'			,	split={'train': F"""train[:{n_train}]""", 'validation': F"""validation[:{n_val}]"""}      )

   def tokenize_function(snake_case__			:       List[Any]      ):
      # max_length=None => use the model max length (it's actually the default)
      UpperCamelCase       :    Any		      =      tokenizer(examples['sentence1']			,	examples['sentence2']			,	truncation=snake_case__			,	max_length=snake_case__      )
      return outputs

   # Apply the method we just defined to all the examples in all the splits of the dataset
   UpperCamelCase       :    Dict		      =      datasets.map(
       snake_case__			,	batched=snake_case__			,	remove_columns=['idx', 'sentence1', 'sentence2']			,	load_from_cache_file=snake_case__      )

   # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
   # transformers library
   UpperCamelCase       :    Optional[Any]		      =      tokenized_datasets.rename_column('label'			,	'labels'      )

   def collate_fn(snake_case__			:       Optional[Any]      ):
      # On TPU it's best to pad everything to the same length or training will be very slow.
      if accelerator.distributed_type == DistributedType.TPU:
         return tokenizer.pad(snake_case__			,	padding='max_length'			,	max_length=128			,	return_tensors='pt'      )
      return tokenizer.pad(snake_case__			,	padding='longest'			,	return_tensors='pt'      )

   # Instantiate dataloaders.
   UpperCamelCase       :    int		      =      DataLoader(
       tokenized_datasets['train']			,	shuffle=snake_case__			,	collate_fn=snake_case__			,	batch_size=snake_case__      )
   UpperCamelCase       :    int		      =      DataLoader(
       tokenized_datasets['validation']			,	shuffle=snake_case__			,	collate_fn=snake_case__			,	batch_size=snake_case__      )

   return train_dataloader, eval_dataloader
def 						UpperCamelCase      (  snake_case__			:       Any			,	snake_case__			:       int      )      ->	Any:
   # Initialize accelerator
   UpperCamelCase       :    int		      =      Accelerator()

   # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
   UpperCamelCase       :    Optional[Any]		      =      config['lr']
   UpperCamelCase       :    str		      =      int(config['num_epochs']      )
   UpperCamelCase       :    int		      =      int(config['seed']      )
   UpperCamelCase       :    Dict		      =      int(config['batch_size']      )
   UpperCamelCase       :    str		      =      args.model_name_or_path

   set_seed(snake_case__      )
   UpperCamelCase      ,	UpperCamelCase       :    int		      =      get_dataloaders(snake_case__			,	snake_case__			,	snake_case__			,	args.n_train			,	args.n_val      )

   # Instantiate the model (we build the model here so that the seed also control new weights initialization)
   UpperCamelCase       :    Optional[int]		      =      AutoModelForSequenceClassification.from_pretrained(snake_case__			,	return_dict=snake_case__      )

   # Instantiate optimizer
   UpperCamelCase       :    Tuple		      =      (
       AdamW
       if accelerator.state.deepspeed_plugin is None
       or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config
       else DummyOptim
   )
   UpperCamelCase       :    List[str]		      =      optimizer_cls(params=model.parameters()			,	lr=snake_case__      )

   if accelerator.state.deepspeed_plugin is not None:
      UpperCamelCase       :    Dict		      =      accelerator.state.deepspeed_plugin.deepspeed_config[
          'gradient_accumulation_steps'
      ]
   else:
      UpperCamelCase       :    Union[str, Any]		      =      1
   UpperCamelCase       :    List[Any]		      =      (len(snake_case__      ) * num_epochs) // gradient_accumulation_steps

   # Instantiate scheduler
   if (
       accelerator.state.deepspeed_plugin is None
       or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
   ):
      UpperCamelCase       :    List[Any]		      =      get_linear_schedule_with_warmup(
          optimizer=snake_case__			,	num_warmup_steps=0			,	num_training_steps=snake_case__			,	)
   else:
      UpperCamelCase       :    List[str]		      =      DummyScheduler(snake_case__			,	total_num_steps=snake_case__			,	warmup_num_steps=0      )

   # 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       :    str		      =      accelerator.prepare(
       snake_case__			,	snake_case__			,	snake_case__			,	snake_case__			,	snake_case__      )

   # We need to keep track of how many total steps we have iterated over
   UpperCamelCase       :    Optional[int]		      =      0
   # We also need to keep track of the stating epoch so files are named properly
   UpperCamelCase       :    Union[str, Any]		      =      0

   # Now we train the model
   UpperCamelCase       :    Union[str, Any]		      =      {}
   for epoch in range(snake_case__			,	snake_case__      ):
      with TorchTracemalloc() as tracemalloc:
         model.train()
         for step, batch in enumerate(snake_case__      ):
            UpperCamelCase       :    str		      =      model(**snake_case__      )
            UpperCamelCase       :    List[str]		      =      outputs.loss
            UpperCamelCase       :    int		      =      loss / gradient_accumulation_steps
            accelerator.backward(snake_case__      )
            if step % gradient_accumulation_steps == 0:
               optimizer.step()
               lr_scheduler.step()
               optimizer.zero_grad()

            overall_step += 1

        # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
      accelerator.print('Memory before entering the train : {}'.format(bamb(tracemalloc.begin      )      )      )
      accelerator.print('Memory consumed at the end of the train (end-begin): {}'.format(tracemalloc.used      )      )
      accelerator.print('Peak Memory consumed during the train (max-begin): {}'.format(tracemalloc.peaked      )      )
      accelerator.print(
          'Total Peak Memory consumed during the train (max): {}'.format(
              tracemalloc.peaked + bamb(tracemalloc.begin      )      )      )
      UpperCamelCase       :    Union[str, Any]		      =      tracemalloc.peaked + bamb(tracemalloc.begin      )
      if args.peak_memory_upper_bound is not None:
         assert (
             train_total_peak_memory[F"""epoch-{epoch}"""] <= args.peak_memory_upper_bound
         ), "Peak memory usage exceeded the upper bound"

   accelerator.wait_for_everyone()
   if accelerator.is_main_process:
      with open(os.path.join(args.output_dir			,	'peak_memory_utilization.json'      )			,	'w'      ) as f:
         json.dump(snake_case__			,	snake_case__      )
def 						UpperCamelCase      (  )      ->	str:
   UpperCamelCase       :    Optional[int]		      =      argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.'      )
   parser.add_argument(
       '--model_name_or_path'			,	type=snake_case__			,	default='bert-base-cased'			,	help='Path to pretrained model or model identifier from huggingface.co/models.'			,	required=snake_case__			,	)
   parser.add_argument(
       '--output_dir'			,	type=snake_case__			,	default='.'			,	help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.'			,	)
   parser.add_argument(
       '--peak_memory_upper_bound'			,	type=snake_case__			,	default=snake_case__			,	help='The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.'			,	)
   parser.add_argument(
       '--n_train'			,	type=snake_case__			,	default=320			,	help='Number of training examples to use.'			,	)
   parser.add_argument(
       '--n_val'			,	type=snake_case__			,	default=160			,	help='Number of validation examples to use.'			,	)
   parser.add_argument(
       '--num_epochs'			,	type=snake_case__			,	default=1			,	help='Number of train epochs.'			,	)
   UpperCamelCase       :    List[Any]		      =      parser.parse_args()
   UpperCamelCase       :    Optional[Any]		      =      {'lr': 2E-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16}
   training_function(snake_case__			,	snake_case__      )


if __name__ == "__main__":
    main()











import itertools
import os
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed

import numpy as np

import datasets

from .execute import check_correctness


lowerCamelCase      :       Tuple    =						'''\
@misc{chen2021evaluating,
      title={Evaluating Large Language Models Trained on Code},
      author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
and William Saunders and Christopher Hesse and Andrew N. Carr \
and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
      year={2021},
      eprint={2107.03374},
      archivePrefix={arXiv},
      primaryClass={cs.LG}
}
'''

lowerCamelCase      :       List[str]    =						'''\
This metric implements the evaluation harness for the HumanEval problem solving dataset
described in the paper "Evaluating Large Language Models Trained on Code"
(https://arxiv.org/abs/2107.03374).
'''


lowerCamelCase      :       List[str]    =						'''
Calculates how good are predictions given some references, using certain scores
Args:
    predictions: list of candidates to evaluate. Each candidates should be a list
        of strings with several code candidates to solve the problem.
    references: a list with a test for each prediction. Each test should evaluate the
        correctness of a code candidate.
    k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])
    num_workers: number of workers used to evaluate the canidate programs (Default: 4).
    timeout:
Returns:
    pass_at_k: dict with pass rates for each k
    results: dict with granular results of each unittest
Examples:
    >>> code_eval = datasets.load_metric("code_eval")
    >>> test_cases = ["assert add(2,3)==5"]
    >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]
    >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
    >>> print(pass_at_k)
    {\'pass@1\': 0.5, \'pass@2\': 1.0}
'''


lowerCamelCase      :       Optional[Any]    =						'''
################################################################################
                                  !!!WARNING!!!
################################################################################
The "code_eval" metric executes untrusted model-generated code in Python.
Although it is highly unlikely that model-generated code will do something
overtly malicious in response to this test suite, model-generated code may act
destructively due to a lack of model capability or alignment.
Users are strongly encouraged to sandbox this evaluation suite so that it
does not perform destructive actions on their host or network. For more
information on how OpenAI sandboxes its code, see the paper "Evaluating Large
Language Models Trained on Code" (https://arxiv.org/abs/2107.03374).

Once you have read this disclaimer and taken appropriate precautions,
set the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this
with:

>>> import os
>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"

################################################################################\
'''

lowerCamelCase      :       Union[str, Any]    =						'''The MIT License

Copyright (c) OpenAI (https://openai.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.'''



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,		_KWARGS_DESCRIPTION      )
class 				_UpperCamelCase      (datasets.Metric      ):


      def 			__UpperCAmelCase		(						self						)->						str:
           return datasets.MetricInfo(
               # This is the description that will appear on the metrics page.
               description=_DESCRIPTION       ,    citation=_CITATION       ,    inputs_description=_KWARGS_DESCRIPTION       ,    features=datasets.Features(
                   {
                       "predictions": datasets.Sequence(datasets.Value("string"						)						),
                       "references": datasets.Value("string"						),
                   }						)       ,    homepage="https://github.com/openai/human-eval"       ,    codebase_urls=["https://github.com/openai/human-eval"]       ,    reference_urls=["https://github.com/openai/human-eval"]       ,    license=_LICENSE       ,    )


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase=[1, 1_0, 1_0_0]       ,    __UpperCamelCase=4       ,    __UpperCamelCase=3.0						)->						str:

           if os.getenv("HF_ALLOW_CODE_EVAL"       ,    0						) != "1":
                raise ValueError(_WARNING						)

           if os.name == "nt":
                raise NotImplementedError("This metric is currently not supported on Windows."						)

           with ThreadPoolExecutor(max_workers=__UpperCamelCase						) as executor:
                __lowerCAmelCase             =       []
                __lowerCAmelCase             =       Counter()
                __lowerCAmelCase             =       0
                __lowerCAmelCase             =       defaultdict(__UpperCamelCase						)

                for task_id, (candidates, test_case) in enumerate(zip(__UpperCamelCase       ,    __UpperCamelCase						)						):
                     for candidate in candidates:
                          __lowerCAmelCase             =       candidate + "\n" + test_case
                          __lowerCAmelCase             =       (test_program, timeout, task_id, completion_id[task_id])
                          __lowerCAmelCase             =       executor.submit(__UpperCamelCase       ,    *__UpperCamelCase						)
                          futures.append(__UpperCamelCase						)
                          completion_id[task_id] += 1
                          n_samples += 1

                for future in as_completed(__UpperCamelCase						):
                     __lowerCAmelCase             =       future.result()
                     results[result["task_id"]].append((result["completion_id"], result)						)

           __lowerCAmelCase      ,			__lowerCAmelCase             =       [], []
           for result in results.values():
                result.sort()
                __lowerCAmelCase             =       [r[1]["passed"] for r in result]
                total.append(len(__UpperCamelCase						)						)
                correct.append(sum(__UpperCamelCase						)						)
           __lowerCAmelCase             =       np.array(__UpperCamelCase						)
           __lowerCAmelCase             =       np.array(__UpperCamelCase						)

           __lowerCAmelCase             =       k
           __lowerCAmelCase             =       {F"""pass@{k}""": estimate_pass_at_k(__UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase						).mean() for k in ks if (total >= k).all()}

           return pass_at_k, results





def    __lowerCAmelCase   (    __snake_case       ,			__snake_case       ,			__snake_case							):

     def estimator(__snake_case       ,			__snake_case       ,			__snake_case							) -> float:
          if n - c < k:
               return 1.0
          return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1       ,			n + 1							)							)

     if isinstance(__snake_case       ,			__snake_case							):
          __lowerCAmelCase             =       itertools.repeat(__snake_case       ,			len(__snake_case							)							)
     else:
          assert len(__snake_case							) == len(__snake_case							)
          __lowerCAmelCase             =       iter(__snake_case							)

     return np.array([estimator(int(__snake_case							)       ,			int(__snake_case							)       ,			__snake_case							) for n, c in zip(__snake_case       ,			__snake_case							)]							)






