





import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()





def      _lowercase					(						_UpperCAmelCase			,      _UpperCAmelCase			,      _UpperCAmelCase			,      _UpperCAmelCase			,      _UpperCAmelCase			,      _UpperCAmelCase = None			,      )						->  Optional[int]:
				lowerCamelCase	 ={}

				if train_file is not None:
								lowerCamelCase	 =[train_file]
				if eval_file is not None:
								lowerCamelCase	 =[eval_file]
				if test_file is not None:
								lowerCamelCase	 =[test_file]

				lowerCamelCase	 =datasets.load_dataset("""csv"""			,      data_files=UpperCAmelCase__				)
				lowerCamelCase	 =list(ds[list(files.keys()				)[0]].features.keys()				)
				lowerCamelCase	 =features_name.pop(UpperCAmelCase__				)
				lowerCamelCase	 =list(set(ds[list(files.keys()				)[0]][label_name]				)				)
				lowerCamelCase	 ={label: i for i, label in enumerate(UpperCAmelCase__				)}
				lowerCamelCase	 =tokenizer.model_input_names
				lowerCamelCase	 ={}

				if len(UpperCAmelCase__				) == 1:
								for k in files.keys():
												lowerCamelCase	 =ds[k].map(
												    lambda _UpperCAmelCase				: tokenizer.batch_encode_plus(
												        example[features_name[0]]			,      truncation=UpperCAmelCase__			,      max_length=UpperCAmelCase__			,      padding="""max_length"""				)			,      batched=UpperCAmelCase__			,      )
				elif len(UpperCAmelCase__				) == 2:
								for k in files.keys():
												lowerCamelCase	 =ds[k].map(
												    lambda _UpperCAmelCase				: tokenizer.batch_encode_plus(
												        (example[features_name[0]], example[features_name[1]])			,      truncation=UpperCAmelCase__			,      max_length=UpperCAmelCase__			,      padding="""max_length"""			,      )			,      batched=UpperCAmelCase__			,      )

				def gen_train():
								for ex in transformed_ds[datasets.Split.TRAIN]:
												lowerCamelCase	 ={k: v for k, v in ex.items() if k in input_names}
												lowerCamelCase	 =labelaid[ex[label_name]]
												yield (d, label)

				def gen_val():
								for ex in transformed_ds[datasets.Split.VALIDATION]:
												lowerCamelCase	 ={k: v for k, v in ex.items() if k in input_names}
												lowerCamelCase	 =labelaid[ex[label_name]]
												yield (d, label)

				def gen_test():
								for ex in transformed_ds[datasets.Split.TEST]:
												lowerCamelCase	 ={k: v for k, v in ex.items() if k in input_names}
												lowerCamelCase	 =labelaid[ex[label_name]]
												yield (d, label)

				lowerCamelCase	 =(
				    tf.data.Dataset.from_generator(
				        UpperCAmelCase__			,      ({k: tf.intaa for k in input_names}, tf.intaa)			,      ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				))			,      )
				    if datasets.Split.TRAIN in transformed_ds
				    else None
				)

				if train_ds is not None:
								lowerCamelCase	 =train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]				)				)				)

				lowerCamelCase	 =(
				    tf.data.Dataset.from_generator(
				        UpperCAmelCase__			,      ({k: tf.intaa for k in input_names}, tf.intaa)			,      ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				))			,      )
				    if datasets.Split.VALIDATION in transformed_ds
				    else None
				)

				if val_ds is not None:
								lowerCamelCase	 =val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]				)				)				)

				lowerCamelCase	 =(
				    tf.data.Dataset.from_generator(
				        UpperCAmelCase__			,      ({k: tf.intaa for k in input_names}, tf.intaa)			,      ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				))			,      )
				    if datasets.Split.TEST in transformed_ds
				    else None
				)

				if test_ds is not None:
								lowerCamelCase	 =test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]				)				)				)

				return train_ds, val_ds, test_ds, labelaid


UpperCAmelCase__						:			Optional[Any]									=logging.getLogger(__name__)

@dataclass
class       __A     :
				__A      =				field(metadata={"""help""": """Which column contains the label"""}    )
				__A      =				field(default=_a    ,					metadata={"""help""": """The path of the training file"""}    )
				__A      =				field(default=_a    ,					metadata={"""help""": """The path of the development file"""}    )
				__A      =				field(default=_a    ,					metadata={"""help""": """The path of the test file"""}    )
				__A      =				field(
				    default=1_28    ,					metadata={
				        """help""": (
				            """The maximum total input sequence length after tokenization. Sequences longer """
				            """than this will be truncated, sequences shorter will be padded."""
				        )
				    }    ,					)
				__A      =				field(
				    default=_a    ,					metadata={"""help""": """Overwrite the cached training and evaluation sets"""}    )




@dataclass
class       __A     :
				__A      =				field(
				    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}    )
				__A      =				field(
				    default=_a    ,					metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}    )
				__A      =				field(
				    default=_a    ,					metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}    )
				__A      =				field(default=_a    ,					metadata={"""help""": """Set this flag to use fast tokenization."""}    )
				# If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
				# or just modify its tokenizer_config.json.
				__A      =				field(
				    default=_a    ,					metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}    ,					)





def      _lowercase					(						)						->  List[Any]:
				lowerCamelCase	 =HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)				)
				lowerCamelCase ,  lowerCamelCase ,  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			,      )
				logger.info(
				    F"""n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1				)}, """
				    F"""16-bits training: {training_args.fpaa}"""				)
				logger.info(F"""Training/evaluation parameters {training_args}"""				)

				# Load pretrained model and tokenizer
				#
				# Distributed training:
				# The .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.

				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 ,  lowerCamelCase ,  lowerCamelCase ,  lowerCamelCase	 =get_tfds(
				    train_file=data_args.train_file			,      eval_file=data_args.dev_file			,      test_file=data_args.test_file			,      tokenizer=UpperCAmelCase__			,      label_column_id=data_args.label_column_id			,      max_seq_length=data_args.max_seq_length			,      )

				lowerCamelCase	 =AutoConfig.from_pretrained(
				    model_args.config_name if model_args.config_name else model_args.model_name_or_path			,      num_labels=len(UpperCAmelCase__				)			,      labelaid=UpperCAmelCase__			,      idalabel={id: label for label, id in labelaid.items()}			,      finetuning_task="""text-classification"""			,      cache_dir=model_args.cache_dir			,      )

				with training_args.strategy.scope():
								lowerCamelCase	 =TFAutoModelForSequenceClassification.from_pretrained(
								    model_args.model_name_or_path			,      from_pt=bool(""".bin""" in model_args.model_name_or_path				)			,      config=UpperCAmelCase__			,      cache_dir=model_args.cache_dir			,      )

				def compute_metrics(_UpperCAmelCase				) -> Dict:
								lowerCamelCase	 =np.argmax(p.predictions			,      axis=1				)

								return {"acc": (preds == p.label_ids).mean()}

				# Initialize our Trainer
				lowerCamelCase	 =TFTrainer(
				    model=UpperCAmelCase__			,      args=UpperCAmelCase__			,      train_dataset=UpperCAmelCase__			,      eval_dataset=UpperCAmelCase__			,      compute_metrics=UpperCAmelCase__			,      )

				# Training
				if training_args.do_train:
								trainer.train()
								trainer.save_model()
								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"""				)

								with open(UpperCAmelCase__			,      """w"""				) as writer:
												logger.info("""***** Eval results *****"""				)

												for key, value in result.items():
																logger.info(F"""  {key} = {value}"""				)
																writer.write(F"""{key} = {value}\n"""				)

												results.update(UpperCAmelCase__				)

				return results


if __name__ == "__main__":
							main()












import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
							if is_torch_available():
														import torch
							if is_tf_available():
														import tensorflow as tf

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer


UpperCAmelCase__						:			Optional[Any]									=logging.get_logger(__name__)

UpperCAmelCase__						:			Union[str, Any]									={'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}

UpperCAmelCase__						:			str									={
    '''vocab_file''': {
        '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''',
    },
    '''merges_file''': {
        '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''',
    },
    '''tokenizer_file''': {
        '''Salesforce/codegen-350M-mono''': (
            '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json'''
        ),
    },
}

UpperCAmelCase__						:			Union[str, Any]									={
    '''Salesforce/codegen-350M-mono''': 20_48,
}

class       __A     (						a    ):
				__A      =				VOCAB_FILES_NAMES
				__A      =				PRETRAINED_VOCAB_FILES_MAP
				__A      =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				__A      =				["""input_ids""", """attention_mask"""]
				__A      =				CodeGenTokenizer


				def __init__(		self   , UpperCAmelCase_=None   , UpperCAmelCase_=None   , UpperCAmelCase_=None   , UpperCAmelCase_="<|endoftext|>"   , UpperCAmelCase_="<|endoftext|>"   , UpperCAmelCase_="<|endoftext|>"   , UpperCAmelCase_=False   , **UpperCAmelCase_   , ):
								super().__init__(
								    UpperCAmelCase_   , UpperCAmelCase_   , tokenizer_file=UpperCAmelCase_   , unk_token=UpperCAmelCase_   , bos_token=UpperCAmelCase_   , eos_token=UpperCAmelCase_   , add_prefix_space=UpperCAmelCase_   , **UpperCAmelCase_   , )

								if kwargs.pop("""add_bos_token"""   , UpperCAmelCase_							):
												lowerCamelCase	 =kwargs.pop("""name_or_path"""   , """"""							)
												raise ValueError(
												    """Currenty GPT2's fast tokenizer does NOT support adding a BOS token."""
												    """Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n"""
												    f"""`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n"""
												    f"""`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n"""
												    """This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005."""
												    """ so that the fast tokenizer works correctly."""							)

								lowerCamelCase	 =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()							)
								if pre_tok_state.get("""add_prefix_space"""   , UpperCAmelCase_							) != add_prefix_space:
												lowerCamelCase	 =getattr(UpperCAmelCase_   , pre_tok_state.pop("""type"""							)							)
												lowerCamelCase	 =add_prefix_space
												lowerCamelCase	 =pre_tok_class(**UpperCAmelCase_							)

								lowerCamelCase	 =add_prefix_space


				def _snake_case       (		self   , *UpperCAmelCase_   , **UpperCAmelCase_							):
								lowerCamelCase	 =kwargs.get("""is_split_into_words"""   , UpperCAmelCase_							)
								assert self.add_prefix_space or not is_split_into_words, (
								    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
								    "to use it with pretokenized inputs."
								)

								return super()._batch_encode_plus(*UpperCAmelCase_   , **UpperCAmelCase_							)


				def _snake_case       (		self   , *UpperCAmelCase_   , **UpperCAmelCase_							):
								lowerCamelCase	 =kwargs.get("""is_split_into_words"""   , UpperCAmelCase_							)

								assert self.add_prefix_space or not is_split_into_words, (
								    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
								    "to use it with pretokenized inputs."
								)

								return super()._encode_plus(*UpperCAmelCase_   , **UpperCAmelCase_							)


				def _snake_case       (		self   , UpperCAmelCase_   , UpperCAmelCase_ = None							):
								lowerCamelCase	 =self._tokenizer.model.save(UpperCAmelCase_   , name=UpperCAmelCase_							)
								return tuple(UpperCAmelCase_							)


				def _snake_case       (		self   , UpperCAmelCase_   , UpperCAmelCase_ = False   , UpperCAmelCase_ = None   , UpperCAmelCase_ = None   , **UpperCAmelCase_   , ):
								lowerCamelCase	 =super().decode(
								    token_ids=UpperCAmelCase_   , skip_special_tokens=UpperCAmelCase_   , clean_up_tokenization_spaces=UpperCAmelCase_   , **UpperCAmelCase_   , )

								if truncate_before_pattern is not None and len(UpperCAmelCase_							) > 0:
												lowerCamelCase	 =self.truncate(UpperCAmelCase_   , UpperCAmelCase_							)

								return decoded_text


				def _snake_case       (		self   , UpperCAmelCase_   , UpperCAmelCase_							):
								def find_re(UpperCAmelCase_   , UpperCAmelCase_   , UpperCAmelCase_							):
												lowerCamelCase	 =pattern.search(UpperCAmelCase_   , UpperCAmelCase_							)
												return m.start() if m else -1

								lowerCamelCase	 =[re.compile(UpperCAmelCase_   , re.MULTILINE							) for pattern in truncate_before_pattern]

								lowerCamelCase	 =list(re.finditer("""^print"""   , UpperCAmelCase_   , re.MULTILINE							)							)

								if len(UpperCAmelCase_							) > 1:
												lowerCamelCase	 =completion[: prints[1].start()]

								lowerCamelCase	 =list(re.finditer("""^def"""   , UpperCAmelCase_   , re.MULTILINE							)							)

								if len(UpperCAmelCase_							) > 1:
												lowerCamelCase	 =completion[: defs[1].start()]

								lowerCamelCase	 =0

								lowerCamelCase	 =[
								    pos for pos in [find_re(UpperCAmelCase_   , UpperCAmelCase_   , UpperCAmelCase_							) for terminal in terminals] if pos != -1
								]

								if len(UpperCAmelCase_							) > 0:
												return completion[: min(UpperCAmelCase_							)]
								else:
												return completion





