A programming framework for agentic AI
adding logging of training loss (#406)
Xueqing Liucb9c7b0d1613
diff --git a/flaml/model.py b/flaml/model.pyindex 6dfdbc2b1..296721e5a 100644--- a/flaml/model.py+++ b/flaml/model.py@@ -378,7 +378,11 @@ class TransformersEstimator(BaseEstimator):if is_str or is_list_of_str:return tokenize_text(- X=X, Y=y, task=self._task, custom_hpo_args=self.custom_hpo_args+ X=X,+ Y=y,+ task=self._task,+ custom_hpo_args=self.custom_hpo_args,+ tokenizer=self._tokenizer,)else:return X, None@@ -398,9 +402,8 @@ class TransformersEstimator(BaseEstimator):transformers.logging.set_verbosity_error()- from transformers import EarlyStoppingCallback+ from transformers import TrainerCallbackfrom transformers.trainer_utils import set_seed- from transformers import AutoTokenizerfrom datasets import Datasetfrom .nlp.utils import (@@ -420,10 +423,11 @@ class TransformersEstimator(BaseEstimator):# else:from .nlp.huggingface.trainer import TrainerForAutofrom .nlp.huggingface.data_collator import DataCollatorForAuto+ from .nlp.utils import get_auto_tokenizerthis_params = self.params- class EarlyStoppingCallbackForAuto(EarlyStoppingCallback):+ class EarlyStoppingCallbackForAuto(TrainerCallback):def on_train_begin(self, args, state, control, **callback_kwargs):self.train_begin_time = time.time()@@ -457,6 +461,10 @@ class TransformersEstimator(BaseEstimator):set_seed(self.params.get("seed", self._TrainingArguments.seed))self._init_hpo_args(kwargs)+ self._tokenizer = get_auto_tokenizer(+ self.custom_hpo_args.model_path, self._task+ )+self._metric = kwargs["metric"]self.use_ray = kwargs.get("use_ray")@@ -487,13 +495,7 @@ class TransformersEstimator(BaseEstimator):else:eval_dataset = None- tokenizer = AutoTokenizer.from_pretrained(- self.custom_hpo_args.model_path, use_fast=True- )- self._tokenizer = tokenizer-num_labels = get_num_labels(self._task, self._y_train)-training_args_config, per_model_config = separate_config(self.params, self._task)@@ -530,6 +532,7 @@ class TransformersEstimator(BaseEstimator):eval_steps=ckpt_freq,evaluate_during_training=True,save_steps=ckpt_freq,+ logging_steps=ckpt_freq,save_total_limit=0,metric_for_best_model="loss",fp16=self.custom_hpo_args.fp16,@@ -545,6 +548,7 @@ class TransformersEstimator(BaseEstimator):do_eval=True,per_device_eval_batch_size=1,eval_steps=ckpt_freq,+ logging_steps=ckpt_freq,evaluation_strategy=IntervalStrategy.STEPS,save_steps=ckpt_freq,save_total_limit=0,@@ -558,9 +562,9 @@ class TransformersEstimator(BaseEstimator):model_init=partial(self._model_init, num_labels, per_model_config),train_dataset=train_dataset,eval_dataset=eval_dataset,- tokenizer=tokenizer,+ tokenizer=self._tokenizer,data_collator=DataCollatorForAuto(- tokenizer=tokenizer,+ tokenizer=self._tokenizer,pad_to_multiple_of=8 if training_args.fp16 else None,)if self._task == MULTICHOICECLASSIFICATION@@ -592,7 +596,12 @@ class TransformersEstimator(BaseEstimator):per_model_config=self._per_model_config,)if hasattr(self._trainer, "intermediate_results"):- self._intermediate_results = self._trainer.intermediate_results+ self.intermediate_results = [+ x[1]+ for x in sorted(+ self._trainer.intermediate_results.items(), key=lambda x: x[0]+ )+ ]self._trainer = Nonedef _delete_one_ckpt(self, ckpt_location):@@ -676,7 +685,6 @@ class TransformersEstimator(BaseEstimator):def _init_model_for_predict(self, X_test):from datasets import Dataset- from transformers import AutoTokenizerfrom .nlp.huggingface.trainer import TrainerForAutofrom .nlp.huggingface.data_collator import DataCollatorForPredict@@ -687,14 +695,11 @@ class TransformersEstimator(BaseEstimator):output_dir=self.custom_hpo_args.output_dir,**self._training_args_config,)- tokenizer = AutoTokenizer.from_pretrained(- self.custom_hpo_args.model_path, use_fast=True- )self._trainer = TrainerForAuto(model=self._model,args=training_args,data_collator=DataCollatorForPredict(- tokenizer=tokenizer,+ tokenizer=self._tokenizer,pad_to_multiple_of=8 if training_args.fp16 else None,)if self._task == MULTICHOICECLASSIFICATIONdiff --git a/flaml/nlp/huggingface/trainer.py b/flaml/nlp/huggingface/trainer.pyindex b657fc535..4534f4c63 100644--- a/flaml/nlp/huggingface/trainer.py+++ b/flaml/nlp/huggingface/trainer.py@@ -44,6 +44,19 @@ class TrainerForAuto(Seq2SeqTrainer):model, inputs, prediction_loss_only, ignore_keys)+ def log(self, logs) -> None:+ if getattr(self, "_is_seq2seq", None):+ super().log(logs)+ else:+ super(Seq2SeqTrainer, self).log(logs)+ if not hasattr(self, "intermediate_results"):+ self.intermediate_results = {}++ epoch_num = logs.get("epoch", None)+ if epoch_num:+ self.intermediate_results.setdefault(epoch_num, {})+ self.intermediate_results[epoch_num].update(logs)+def evaluate(self,eval_dataset=None,@@ -74,13 +87,6 @@ class TrainerForAuto(Seq2SeqTrainer):ignore_keys,metric_key_prefix,)- if not hasattr(self, "intermediate_results"):- self.intermediate_results = []- self.intermediate_results.append(metrics)- # if metrics:- # for key in list(metrics.keys()):- # if key.startswith("eval_"):- # metrics[key[5:]] = metrics.pop(key)if hasattr(self, "ckpt_to_global_step"):self.ckpt_to_global_step[ckpt_dir] = self.state.global_stepif metrics:diff --git a/flaml/nlp/utils.py b/flaml/nlp/utils.pyindex 144a1e560..ca897f2a9 100644--- a/flaml/nlp/utils.py+++ b/flaml/nlp/utils.py@@ -30,34 +30,61 @@ def load_default_huggingface_metric_for_task(task):global tokenized_column_names-def tokenize_text(X, Y=None, task=None, custom_hpo_args=None):+def get_auto_tokenizer(model_path, task):+ from transformers import AutoTokenizer++ if task == SUMMARIZATION:+ return AutoTokenizer.from_pretrained(+ model_path, # 'roberta-base'+ cache_dir=None,+ use_fast=True,+ revision="main",+ use_auth_token=None,+ )+ else:+ return AutoTokenizer.from_pretrained(model_path, use_fast=True)+++def tokenize_text(X, Y=None, task=None, custom_hpo_args=None, tokenizer=None):if task in (SEQCLASSIFICATION, SEQREGRESSION):- X_tokenized, _ = tokenize_onedataframe(- X, this_tokenizer=None, task=task, custom_hpo_args=custom_hpo_args+ X_tokenized = tokenize_onedataframe(+ X,+ tokenizer=tokenizer,+ task=task,+ custom_hpo_args=custom_hpo_args,+ prefix_str="",)return X_tokenized, Noneelif task == TOKENCLASSIFICATION:- return tokenize_text_tokclassification(X, Y, custom_hpo_args)+ return tokenize_text_tokclassification(+ X, Y, tokenizer=tokenizer, custom_hpo_args=custom_hpo_args+ )elif task in NLG_TASKS:- return tokenize_seq2seq(X, Y, task=task, custom_hpo_args=custom_hpo_args)+ return tokenize_seq2seq(+ X, Y, tokenizer=tokenizer, task=task, custom_hpo_args=custom_hpo_args+ )elif task == MULTICHOICECLASSIFICATION:- return tokenize_text_multiplechoice(X, custom_hpo_args)+ return tokenize_text_multiplechoice(+ X, tokenizer=tokenizer, custom_hpo_args=custom_hpo_args+ )-def tokenize_seq2seq(X, Y, task=None, custom_hpo_args=None):- model_inputs, tokenizer = tokenize_onedataframe(+def tokenize_seq2seq(X, Y, tokenizer, task=None, custom_hpo_args=None):+ model_inputs = tokenize_onedataframe(X,- this_tokenizer=None,+ tokenizer=tokenizer,task=task,custom_hpo_args=custom_hpo_args,+ prefix_str="summarize: ",)labels = Noneif Y is not None:- labels, _ = tokenize_onedataframe(+ labels = tokenize_onedataframe(Y.to_frame(),- this_tokenizer=tokenizer,+ tokenizer=tokenizer,task=task,custom_hpo_args=custom_hpo_args,+ prefix_str="",)labels["label"] = [[(each_l if each_l != tokenizer.pad_token_id else -100) for each_l in label]@@ -70,7 +97,7 @@ def tokenize_seq2seq(X, Y, task=None, custom_hpo_args=None):def tokenize_and_align_labels(- examples, tokenizer, custom_hpo_args, X_sent_key, Y_sent_key=None+ examples, tokenizer, custom_hpo_args=None, X_sent_key=None, Y_sent_key=None):global tokenized_column_names@@ -115,14 +142,10 @@ def tokenize_and_align_labels(return tokenized_input_and_labels-def tokenize_text_tokclassification(X, Y, custom_hpo_args):- from transformers import AutoTokenizer+def tokenize_text_tokclassification(X, Y, tokenizer, custom_hpo_args=None):import pandas as pdglobal tokenized_column_names- this_tokenizer = AutoTokenizer.from_pretrained(- custom_hpo_args.model_path, use_fast=True- )if Y is not None:X_and_Y = pd.concat([X, Y.to_frame()], axis=1)X_key = list(X.keys())[0]@@ -130,7 +153,7 @@ def tokenize_text_tokclassification(X, Y, custom_hpo_args):X_and_Y_tokenized = X_and_Y.apply(lambda x: tokenize_and_align_labels(x,- tokenizer=this_tokenizer,+ tokenizer=tokenizer,custom_hpo_args=custom_hpo_args,X_sent_key=X_key,Y_sent_key=Y_key,@@ -150,7 +173,7 @@ def tokenize_text_tokclassification(X, Y, custom_hpo_args):d = X.apply(lambda x: tokenize_and_align_labels(x,- tokenizer=this_tokenizer,+ tokenizer=tokenizer,custom_hpo_args=custom_hpo_args,X_sent_key=X_key,Y_sent_key=None,@@ -167,37 +190,21 @@ def tokenize_text_tokclassification(X, Y, custom_hpo_args):def tokenize_onedataframe(X,- this_tokenizer=None,+ tokenizer,task=None,custom_hpo_args=None,+ prefix_str=None,):- from transformers import AutoTokenizerimport pandasglobal tokenized_column_names- if this_tokenizer:- with this_tokenizer.as_target_tokenizer():- d = X.apply(- lambda x: tokenize_row(- x,- this_tokenizer,- prefix=("",) if task is SUMMARIZATION else None,- task=task,- custom_hpo_args=custom_hpo_args,- ),- axis=1,- result_type="expand",- )- else:- this_tokenizer = AutoTokenizer.from_pretrained(- custom_hpo_args.model_path, use_fast=True- )+ with tokenizer.as_target_tokenizer():d = X.apply(lambda x: tokenize_row(x,- this_tokenizer,- prefix=("summarize: ",) if task is SUMMARIZATION else None,+ tokenizer,+ prefix=(prefix_str,) if task is SUMMARIZATION else None,task=task,custom_hpo_args=custom_hpo_args,),@@ -206,7 +213,7 @@ def tokenize_onedataframe()X_tokenized = pandas.DataFrame(columns=tokenized_column_names)X_tokenized[tokenized_column_names] = d- return X_tokenized, this_tokenizer+ return X_tokenizeddef postprocess_text(preds, labels):@@ -223,9 +230,7 @@ def postprocess_text(preds, labels):return preds, labels-def tokenize_row(- this_row, this_tokenizer, prefix=None, task=None, custom_hpo_args=None-):+def tokenize_row(this_row, tokenizer, prefix=None, task=None, custom_hpo_args=None):global tokenized_column_namesassert ("max_seq_length" in custom_hpo_args.__dict__@@ -234,7 +239,7 @@ def tokenize_row(if prefix:this_row = tuple(["".join(x) for x in zip(prefix, this_row)])- tokenized_example = this_tokenizer(+ tokenized_example = tokenizer(*tuple(this_row),padding="max_length",max_length=custom_hpo_args.max_seq_length,@@ -246,22 +251,14 @@ def tokenize_row(return [tokenized_example[x] for x in tokenized_column_names]-def tokenize_text_multiplechoice(X, custom_hpo_args):- from transformers import AutoTokenizer+def tokenize_text_multiplechoice(X, tokenizer, custom_hpo_args=None):import pandasglobal tokenized_column_names- this_tokenizer = AutoTokenizer.from_pretrained(- custom_hpo_args.model_path, # 'roberta-base'- cache_dir=None,- use_fast=True,- revision="main",- use_auth_token=None,- )t = X[["sent1", "sent2", "ending0", "ending1", "ending2", "ending3"]]d = t.apply(- lambda x: tokenize_swag(x, this_tokenizer, custom_hpo_args),+ lambda x: tokenize_swag(x, tokenizer, custom_hpo_args),axis=1,result_type="expand",)@@ -272,7 +269,7 @@ def tokenize_text_multiplechoice(X, custom_hpo_args):return output, None-def tokenize_swag(this_row, this_tokenizer, custom_hpo_args):+def tokenize_swag(this_row, tokenizer, custom_hpo_args=None):global tokenized_column_namesfirst_sentences = [[this_row["sent1"]] * 4]@@ -289,7 +286,7 @@ def tokenize_swag(this_row, this_tokenizer, custom_hpo_args):# From 2 dimension to 1 dimension arrayfirst_sentences = list(chain(*first_sentences))- tokenized_example = this_tokenizer(+ tokenized_example = tokenizer(*tuple([first_sentences, second_sentences]),truncation=True,max_length=custom_hpo_args.max_seq_length,