


'''simple docstring'''







from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


A				:					List[str]    						=			logging.get_logger(__name__)


class 			__lowerCamelCase			(	a_	):
    """simple docstring"""


    def        A   (  self      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							str):
           if isinstance(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE):
                  _A					:     str     = [label.strip() for label in labels.split(',') if label.strip()]
           return labels


    def __call__(  self      :							Any				,							SCREAMING_SNAKE_CASE      :							Dict				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							Dict):
           if len(SCREAMING_SNAKE_CASE) == 0 or len(SCREAMING_SNAKE_CASE) == 0:
                  raise ValueError('You must include at least one label and at least one sequence.')
           if hypothesis_template.format(labels[0]) == hypothesis_template:
                  raise ValueError(
                      (
                          'The provided hypothesis_template "{}" was not able to be formatted with the target labels. '
                          'Make sure the passed template includes formatting syntax such as {{}} where the label should go.'
                      ).format(SCREAMING_SNAKE_CASE))

           if isinstance(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE):
                  _A					:     Optional[int]     = [sequences]

           _A					:     Any     = []
           for sequence in sequences:
                  sequence_pairs.extend([[sequence, hypothesis_template.format(SCREAMING_SNAKE_CASE)] for label in labels])

           return sequence_pairs, sequences




@add_end_docstrings(a_	)
class 			__lowerCamelCase			(	a_	):
    """simple docstring"""


    def __init__(  self      :							int				,							SCREAMING_SNAKE_CASE      :							Tuple=ZeroShotClassificationArgumentHandler()				,							*SCREAMING_SNAKE_CASE      :							Dict				,							**SCREAMING_SNAKE_CASE      :							List[Any]):
           _A					:     Tuple     = args_parser
           super().__init__(*SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)
           if self.entailment_id == -1:
                  logger.warning(
                      'Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to '
                      '-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.')


    @property
    def        A   (  self      :							str):
           for label, ind in self.model.config.labelaid.items():
                  if label.lower().startswith('entail'):
                         return ind
           return -1


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							Dict				,							SCREAMING_SNAKE_CASE      :							List[str]=True				,							SCREAMING_SNAKE_CASE      :							List[Any]=True				,							SCREAMING_SNAKE_CASE      :							Tuple=TruncationStrategy.ONLY_FIRST				,							**SCREAMING_SNAKE_CASE      :							List[str]):
           _A					:     Union[str, Any]     = self.framework
           if self.tokenizer.pad_token is None:
                  # Override for tokenizers not supporting padding
                  logger.error(
                      'Tokenizer was not supporting padding necessary for zero-shot, attempting to use '
                      ' `pad_token=eos_token`')
                  _A					:     int     = self.tokenizer.eos_token
           try:
                  _A					:     Union[str, Any]     = self.tokenizer(
                      SCREAMING_SNAKE_CASE				,							add_special_tokens=SCREAMING_SNAKE_CASE				,							return_tensors=SCREAMING_SNAKE_CASE				,							padding=SCREAMING_SNAKE_CASE				,							truncation=SCREAMING_SNAKE_CASE				,							)
           except Exception as e:
                  if "too short" in str(SCREAMING_SNAKE_CASE):
                         # tokenizers might yell that we want to truncate
                         # to a value that is not even reached by the input.
                         # In that case we don't want to truncate.
                         # It seems there's not a really better way to catch that
                         # exception.

                         _A					:     List[str]     = self.tokenizer(
                             SCREAMING_SNAKE_CASE				,							add_special_tokens=SCREAMING_SNAKE_CASE				,							return_tensors=SCREAMING_SNAKE_CASE				,							padding=SCREAMING_SNAKE_CASE				,							truncation=TruncationStrategy.DO_NOT_TRUNCATE				,							)
                  else:
                         raise e

           return inputs


    def        A   (  self      :							int				,							**SCREAMING_SNAKE_CASE      :							List[Any]):
           if kwargs.get('multi_class'				,							SCREAMING_SNAKE_CASE) is not None:
                  _A					:     str     = kwargs['multi_class']
                  logger.warning(
                      'The `multi_class` argument has been deprecated and renamed to `multi_label`. '
                      '`multi_class` will be removed in a future version of Transformers.')
           _A					:     Dict     = {}
           if "candidate_labels" in kwargs:
                  _A					:     Tuple     = self._args_parser._parse_labels(kwargs['candidate_labels'])
           if "hypothesis_template" in kwargs:
                  _A					:     Optional[int]     = kwargs['hypothesis_template']

           _A					:     int     = {}
           if "multi_label" in kwargs:
                  _A					:     Optional[int]     = kwargs['multi_label']
           return preprocess_params, {}, postprocess_params


    def __call__(  self      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							Union[str, List[str]]				,							*SCREAMING_SNAKE_CASE      :							int				,							**SCREAMING_SNAKE_CASE      :							int				,							):
           if len(SCREAMING_SNAKE_CASE) == 0:
                  pass
           elif len(SCREAMING_SNAKE_CASE) == 1 and "candidate_labels" not in kwargs:
                  _A					:     List[Any]     = args[0]
           else:
                  raise ValueError(F'Unable to understand extra arguments {args}')

           return super().__call__(SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Tuple				,							SCREAMING_SNAKE_CASE      :							List[str]				,							SCREAMING_SNAKE_CASE      :							int=None				,							SCREAMING_SNAKE_CASE      :							Any="This example is {}."):
           _A  ,			_A					:     Dict     = self._args_parser(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE)

           for i, (candidate_label, sequence_pair) in enumerate(zip(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE)):
                  _A					:     Dict     = self._parse_and_tokenize([sequence_pair])

                  yield {
                      "candidate_label": candidate_label,
                      "sequence": sequences[0],
                      "is_last": i == len(SCREAMING_SNAKE_CASE) - 1,
                      **model_input,
                  }


    def        A   (  self      :							str				,							SCREAMING_SNAKE_CASE      :							Optional[Any]):
           _A					:     Optional[int]     = inputs['candidate_label']
           _A					:     Optional[int]     = inputs['sequence']
           _A					:     Optional[Any]     = {k: inputs[k] for k in self.tokenizer.model_input_names}
           _A					:     Dict     = self.model(**SCREAMING_SNAKE_CASE)

           _A					:     int     = {
               'candidate_label': candidate_label,
               'sequence': sequence,
               'is_last': inputs['is_last'],
               **outputs,
           }
           return model_outputs


    def        A   (  self      :							Optional[Any]				,							SCREAMING_SNAKE_CASE      :							List[str]				,							SCREAMING_SNAKE_CASE      :							Tuple=False):
           _A					:     str     = [outputs['candidate_label'] for outputs in model_outputs]
           _A					:     Dict     = [outputs['sequence'] for outputs in model_outputs]
           _A					:     List[str]     = np.concatenate([output['logits'].numpy() for output in model_outputs])
           _A					:     Union[str, Any]     = logits.shape[0]
           _A					:     List[str]     = len(SCREAMING_SNAKE_CASE)
           _A					:     Dict     = N // n
           _A					:     Tuple     = logits.reshape((num_sequences, n, -1))

           if multi_label or len(SCREAMING_SNAKE_CASE) == 1:
                  # softmax over the entailment vs. contradiction dim for each label independently
                  _A					:     Dict     = self.entailment_id
                  _A					:     List[Any]     = -1 if entailment_id == 0 else 0
                  _A					:     Union[str, Any]     = reshaped_outputs[..., [contradiction_id, entailment_id]]
                  _A					:     List[str]     = np.exp(SCREAMING_SNAKE_CASE) / np.exp(SCREAMING_SNAKE_CASE).sum(-1				,							keepdims=SCREAMING_SNAKE_CASE)
                  _A					:     Optional[int]     = scores[..., 1]
           else:
                  # softmax the "entailment" logits over all candidate labels
                  _A					:     Union[str, Any]     = reshaped_outputs[..., self.entailment_id]
                  _A					:     Any     = np.exp(SCREAMING_SNAKE_CASE) / np.exp(SCREAMING_SNAKE_CASE).sum(-1				,							keepdims=SCREAMING_SNAKE_CASE)

           _A					:     Optional[int]     = list(reversed(scores[0].argsort()))
           return {
               "sequence": sequences[0],
               "labels": [candidate_labels[i] for i in top_inds],
               "scores": scores[0, top_inds].tolist(),
           }










'''simple docstring'''







from dataclasses import dataclass, field
from typing import Optional


@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Model name or path of model to be trained."}	)
    a													=   field(
        default="./"    , metadata={"help": "Save dir where model repo is cloned and models updates are saved to."}	)
    a													=   field(
        default="codeparrot/codeparrot-clean-train"    , metadata={"help": "Name or path of training dataset."}	)
    a													=   field(
        default="codeparrot/codeparrot-clean-valid"    , metadata={"help": "Name or path of validation dataset."}	)
    a													=   field(default=2    , metadata={"help": "Batch size for training."}	)
    a													=   field(default=2    , metadata={"help": "Batch size for evaluation."}	)
    a													=   field(default=0.1    , metadata={"help": "Value of weight decay."}	)
    a													=   field(
        default=1_0000    , metadata={"help": "Size of buffer used to shuffle streaming dataset."}	)
    a													=   field(default=2E-4    , metadata={"help": "Learning rate fo training."}	)
    a													=   field(default="cosine"    , metadata={"help": "Learning rate."}	)
    a													=   field(
        default=750    , metadata={"help": "Number of warmup steps in the learning rate schedule."}	)
    a													=   field(
        default=16    , metadata={"help": "Number of gradient accumulation steps."}	)
    a													=   field(
        default=a_    , metadata={"help": "Use gradient checkpointing to reduce memory footprint."}	)
    a													=   field(default=5_0000    , metadata={"help": "Maximum number of training steps."}	)
    a													=   field(
        default=-1    , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."}	)
    a													=   field(default=1024    , metadata={"help": "Sequence lengths used for training."}	)
    a													=   field(default=1    , metadata={"help": "Training seed."}	)
    a													=   field(
        default=1024    , metadata={"help": "Interval to save checkpoints. Measured as number of forward passes not training steps."}    , )
    a													=   field(
        default=a_    , metadata={"help": "States path if the training should continue from a checkpoint folder."}	)
    a													=   field(default=a_    , metadata={"help": "If True the data is pretokenized."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Model name or path of model to be evaluated."}	)
    a													=   field(
        default="codeparrot/codeparrot-clean-valid"    , metadata={"help": "Name or path of validation dataset."}	)
    a													=   field(default=2    , metadata={"help": "Batch size used for evaluation."}	)
    a													=   field(
        default=-1    , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."}	)
    a													=   field(default=1024    , metadata={"help": "Length of sequences to be evaluated."}	)
    a													=   field(default=1    , metadata={"help": "Random seed used for evaluation."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Model name or path of model to be evaluated."}	)
    a													=   field(default=a_    , metadata={"help": "Number of workers used for code evaluation."}	)
    a													=   field(
        default=a_    , metadata={"help": "The number of human-eval tasks to run. If not included all tasks are evaluated."}    , )
    a													=   field(
        default=a_    , metadata={"help": "Sample from the language model's output distribution."}	)
    a													=   field(default=0.2    , metadata={"help": "Sampling temperature used for generation."}	)
    a													=   field(default=256    , metadata={"help": "Maximum number of newly generated tokens."}	)
    a													=   field(default=0    , metadata={"help": "Top-k parameter used for generation."}	)
    a													=   field(default=0.95    , metadata={"help": "Top-p parameter used for nucleus sampling."}	)
    a													=   field(default=10    , metadata={"help": "Number of generations to run in parallel."}	)
    a													=   field(
        default=200    , metadata={"help": "Number of completions to generate for each sample."}	)
    a													=   field(default=1    , metadata={"help": "Random seed used for evaluation."}	)
    a													=   field(
        default="eval_results.json"    , metadata={"help": "Random seed used for evaluation."}	)
    a													=   field(
        default="0"    , metadata={"help": "Allow `code_eval` to execute Python code on machine"}	)
    a													=   field(
        default=-1    , metadata={
            "help": (
                "Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive"
                " number corresponds to which GPU device id to run on."
            )
        }    , )




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default=a_    , metadata={
            "help": "The number of CPU cores to use for parallel preprocessing. Default uses the maximum available."
        }    , )
    a													=   field(
        default="transformersbook/codeparrot"    , metadata={"help": "Folder or name of dataset to process."}	)
    a													=   field(
        default="codeparrot-clean"    , metadata={"help": "Folder to save processed processed dataset."}	)
    a													=   field(
        default=10_0000    , metadata={"help": "Number of files to save per JSON output file."}	)
    a													=   field(default="content"    , metadata={"help": "Column containing text data to process."}	)
    a													=   field(
        default=1000    , metadata={"help": "Maximum line length in file, otherwise file is filtered."}	)
    a													=   field(
        default=100    , metadata={"help": "Maximum mean line length in file, otherwise file is filtered."}	)
    a													=   field(
        default=0.25    , metadata={"help": "Maximum fraction of non-alphanumeric characters, otherwise file is filtered."}	)
    a													=   field(
        default=1.5    , metadata={"help": "Minimum character token ratio for the file, otherwise file is filtered."}	)
    a													=   field(
        default=0.7    , metadata={"help": "Probability for filtering config, test and uncommon files."}	)
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Name or path to the tokenizer."}    , )
    a													=   field(
        default=a_    , metadata={"help": "If True, near-duplicate samples are removed."}	)
    a													=   field(
        default=0.85    , metadata={"help": "Jaccard threshold for near-duplicate samples."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="gpt2"    , metadata={"help": "Base tokenizer to build new tokenizer from."}	)
    a													=   field(
        default="transformersbook/codeparrot-train"    , metadata={"help": "Dataset to train tokenizer on."}	)
    a													=   field(default="content"    , metadata={"help": "Column containing text data to process."}	)
    a													=   field(default=20_0000    , metadata={"help": "Number of examples to train tokenizer on."}	)
    a													=   field(
        default=3_2768    , metadata={"help": "Number of examples to train the tokenizer on."}	)
    a													=   field(default="codeparrot"    , metadata={"help": "Name of new tokenizer."}	)
    a													=   field(default=a_    , metadata={"help": "Push saved tokenizer to the hub."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Name or path to the tokenizer."}	)
    a													=   field(
        default="codeparrot/codeparrot-clean-train"    , metadata={"help": "Name or path to the dataset to pretokenize."}	)
    a													=   field(
        default="tokenized-codeparrot-train"    , metadata={"help": "Repo name of the pretokenized data."}	)
    a													=   field(default=a_    , metadata={"help": "Number of workers used for code evaluation."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="gpt2-large"    , metadata={"help": "Configuration to use for model initialization."}	)
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Tokenizer attached to model."}	)
    a													=   field(default="codeparrot"    , metadata={"help": "Name of the created model."}	)
    a													=   field(default=a_    , metadata={"help": "Push saved tokenizer to the hub."}	)






