Skip to content

A programming framework for agentic AI

Adding the NLP task summarization (#346)

Xueqing Liuee3162e23281
diff --git a/flaml/automl.py b/flaml/automl.py
index 2b56650d1..ed72ec77d 100644
--- a/flaml/automl.py
+++ b/flaml/automl.py
@@ -44,6 +44,8 @@ from .data import (
FORECAST,
REGRESSION,
_is_nlp_task,
+ SUMMARIZATION,
+ NLG_TASKS,
)
from . import tune
from .training_log import training_log_reader, training_log_writer
@@ -459,7 +461,7 @@ class AutoML(BaseEstimator):
```
task: A string of the task type, e.g.,
'classification', 'regression', 'ts_forecast', 'rank',
- 'seq-classification', 'seq-regression'.
+ 'seq-classification', 'seq-regression', 'summarization'.
n_jobs: An integer of the number of threads for training.
gpu_per_trial: A float of the number of gpus per trial, only used by TransformersEstimator.
log_file_name: A string of the log file name. To disable logging,
@@ -740,7 +742,11 @@ class AutoML(BaseEstimator):
return None
X_test = self._preprocess(X_test)
y_pred = estimator.predict(X_test)
- if y_pred.ndim > 1 and isinstance(y_pred, np.ndarray):
+ if (
+ isinstance(y_pred, np.ndarray)
+ and y_pred.ndim > 1
+ and isinstance(y_pred, np.ndarray)
+ ):
y_pred = y_pred.flatten()
if self._label_transformer:
return self._label_transformer.inverse_transform(
@@ -920,6 +926,8 @@ class AutoML(BaseEstimator):
self._state.X_val = self._transformer.transform(X_val)
else:
self._state.X_val = X_val
+ # If it's NLG_TASKS, y_val is a pandas series containing the output sequence tokens,
+ # so we cannot use label_transformer.transform to process it
if self._label_transformer:
self._state.y_val = self._label_transformer.transform(y_val)
else:
@@ -1273,7 +1281,7 @@ class AutoML(BaseEstimator):
time_budget: A float number of the time budget in seconds.
task: A string of the task type, e.g.,
'classification', 'regression', 'ts_forecast', 'rank',
- 'seq-classification', 'seq-regression'.
+ 'seq-classification', 'seq-regression', 'summarization'.
eval_method: A string of resampling strategy, one of
['auto', 'cv', 'holdout'].
split_ratio: A float of the validation data percentage for holdout.
@@ -1431,6 +1439,9 @@ class AutoML(BaseEstimator):
), "groups must be specified for ranking task."
assert split_type in ["auto", "group"]
self._split_type = "group"
+ elif self._state.task in NLG_TASKS:
+ assert split_type in ["auto", "uniform", "time", "group"]
+ self._split_type = split_type if split_type != "auto" else "uniform"
def _decide_eval_method(self, time_budget):
if self._state.X_val is not None:
@@ -1742,7 +1753,7 @@ class AutoML(BaseEstimator):
task: A string of the task type, e.g.,
'classification', 'regression', 'ts_forecast', 'rank',
- 'seq-classification', 'seq-regression'.
+ 'seq-classification', 'seq-regression', 'summarization'
n_jobs: An integer of the number of threads for training.
gpu_per_trial: A float of the number of gpus per trial, only used by TransformersEstimator.
log_file_name: A string of the log file name. To disable logging,
diff --git a/flaml/data.py b/flaml/data.py
index 321041adc..59b2f4d17 100644
--- a/flaml/data.py
+++ b/flaml/data.py
@@ -30,7 +30,7 @@ NLU_TASKS = (
def _is_nlp_task(task):
- if task in NLU_TASKS + NLG_TASKS:
+ if task in NLU_TASKS or task in NLG_TASKS:
return True
else:
return False
@@ -347,7 +347,11 @@ class DataTransformer:
)
self._drop = drop
- if task in CLASSIFICATION or not pd.api.types.is_numeric_dtype(y):
+ if (
+ task in CLASSIFICATION
+ or not pd.api.types.is_numeric_dtype(y)
+ and task not in NLG_TASKS
+ ):
from sklearn.preprocessing import LabelEncoder
self.label_transformer = LabelEncoder()
diff --git a/flaml/ml.py b/flaml/ml.py
index 480eb42db..67c7015b7 100644
--- a/flaml/ml.py
+++ b/flaml/ml.py
@@ -83,6 +83,7 @@ huggingface_metric_to_mode = {
"ter": "min",
"wer": "min",
}
+huggingface_submetric_to_metric = {"rouge1": "rouge", "rouge2": "rouge"}
def get_estimator_class(task, estimator_name):
@@ -153,11 +154,21 @@ def metric_loss_score(
try:
import datasets
- metric = datasets.load_metric(metric_name)
- metric_mode = huggingface_metric_to_mode[metric_name]
- score = metric.compute(predictions=y_predict, references=y_true)[
- metric_name
- ]
+ datasets_metric_name = huggingface_submetric_to_metric.get(
+ metric_name, metric_name
+ )
+ metric = datasets.load_metric(datasets_metric_name)
+ metric_mode = huggingface_metric_to_mode[datasets_metric_name]
+
+ if "rouge" in metric_name:
+ score = metric.compute(predictions=y_predict, references=y_true)[
+ metric_name
+ ].mid.fmeasure
+ else:
+ score = metric.compute(predictions=y_predict, references=y_true)[
+ metric_name
+ ]
+
except ImportError:
raise Exception(
metric_name
diff --git a/flaml/model.py b/flaml/model.py
index dbcc3ca08..3e08cb214 100644
--- a/flaml/model.py
+++ b/flaml/model.py
@@ -25,6 +25,8 @@ from .data import (
TS_VALUE_COL,
SEQCLASSIFICATION,
SEQREGRESSION,
+ SUMMARIZATION,
+ NLG_TASKS,
)
import pandas as pd
@@ -227,9 +229,8 @@ class BaseEstimator:
Each element at (i,j) is the probability for instance i to be in
class j.
"""
- assert (
- self._task in CLASSIFICATION
- ), "predict_prob() only for classification task."
+ assert self._task in CLASSIFICATION, "predict_proba() only for classification."
+
X_test = self._preprocess(X_test)
return self._model.predict_proba(X_test)
@@ -300,6 +301,11 @@ class TransformersEstimator(BaseEstimator):
import uuid
self.trial_id = str(uuid.uuid1().hex)[:8]
+ if task in NLG_TASKS:
+ from transformers import Seq2SeqTrainingArguments as TrainingArguments
+ else:
+ from transformers import TrainingArguments
+ self._TrainingArguments = TrainingArguments
def _join(self, X_train, y_train):
y_train = DataFrame(y_train, columns=["label"], index=X_train.index)
@@ -335,12 +341,16 @@ class TransformersEstimator(BaseEstimator):
"seed": {"domain": tune.choice(list(range(40, 45))), "init_value": 42},
"global_max_steps": {"domain": sys.maxsize, "init_value": sys.maxsize},
}
- # TODO: if self._task == SUMMARIZATION, uncomment the code below, SET the search space for
- # "num_beams" in search_space_dict using
- # search_space_dict["num_beams"] = {...}
- # if task in NLG_TASKS:
- # search_space_dict["num_beams"] = {"domain": tune.choice(...)}
+ if task in NLG_TASKS:
+ search_space_dict["generation_num_beams"] = {
+ "domain": tune.randint(2, 5),
+ "init_value": 3,
+ }
+ search_space_dict["generation_max_length"] = {
+ "domain": tune.choice([16, 32, 64, 128]),
+ "init_value": 64,
+ }
return search_space_dict
@@ -357,26 +367,21 @@ class TransformersEstimator(BaseEstimator):
setattr(custom_hpo_args, key, val)
self.custom_hpo_args = custom_hpo_args
- def _preprocess(self, X, task, **kwargs):
+ def _preprocess(self, X, y=None, task=None, **kwargs):
from .nlp.utils import tokenize_text
if X.dtypes[0] == "string":
- return tokenize_text(X, task, self.custom_hpo_args)
+ return tokenize_text(
+ X=X, Y=y, task=task, custom_hpo_args=self.custom_hpo_args
+ )
else:
- return X
+ return X, None
def fit(self, X_train: DataFrame, y_train: Series, budget=None, **kwargs):
from transformers import EarlyStoppingCallback
from transformers.trainer_utils import set_seed
from transformers import AutoTokenizer
- # TODO: if self._task == SUMMARIZATION, uncomment the code below (add indentation before
- # from transformers import TrainingArguments)
- # if self._task in NLG_TASKS:
- # from transformers import Seq2SeqTrainingArguments as TrainingArguments
- # else:
- from transformers import TrainingArguments
-
import transformers
from datasets import Dataset
from .nlp.utils import (
@@ -429,7 +434,7 @@ class TransformersEstimator(BaseEstimator):
control.should_save = True
control.should_evaluate = True
- set_seed(self.params.get("seed", TrainingArguments.seed))
+ set_seed(self.params.get("seed", self._TrainingArguments.seed))
self._init_hpo_args(kwargs)
self._metric_name = kwargs["metric"]
@@ -439,7 +444,13 @@ class TransformersEstimator(BaseEstimator):
X_val = kwargs.get("X_val")
y_val = kwargs.get("y_val")
- X_train = self._preprocess(X_train, self._task, **kwargs)
+ if self._task not in NLG_TASKS:
+ X_train, _ = self._preprocess(X=X_train, task=self._task, **kwargs)
+ else:
+ X_train, y_train = self._preprocess(
+ X=X_train, y=y_train, task=self._task, **kwargs
+ )
+
train_dataset = Dataset.from_pandas(self._join(X_train, y_train))
# TODO: set a breakpoint here, observe the resulting train_dataset,
@@ -449,7 +460,12 @@ class TransformersEstimator(BaseEstimator):
# make sure they are the same
if X_val is not None:
- X_val = self._preprocess(X_val, self._task, **kwargs)
+ if self._task not in NLG_TASKS:
+ X_val, _ = self._preprocess(X=X_val, task=self._task, **kwargs)
+ else:
+ X_val, y_val = self._preprocess(
+ X=X_val, y=y_val, task=self._task, **kwargs
+ )
eval_dataset = Dataset.from_pandas(self._join(X_val, y_val))
else:
eval_dataset = None
@@ -457,25 +473,22 @@ class TransformersEstimator(BaseEstimator):
tokenizer = AutoTokenizer.from_pretrained(
self.custom_hpo_args.model_path, use_fast=True
)
+ self._tokenizer = tokenizer
num_labels = get_num_labels(self._task, y_train)
- training_args_config, per_model_config = separate_config(self.params)
- this_model = load_model(
- checkpoint_path=self.custom_hpo_args.model_path,
- task=self._task,
- num_labels=num_labels,
- per_model_config=per_model_config,
+ training_args_config, per_model_config = separate_config(
+ self.params, self._task
)
ckpt_freq = compute_checkpoint_freq(
train_data_size=len(X_train),
custom_hpo_args=self.custom_hpo_args,
num_train_epochs=training_args_config.get(
- "num_train_epochs", TrainingArguments.num_train_epochs
+ "num_train_epochs", self._TrainingArguments.num_train_epochs
),
batch_size=training_args_config.get(
"per_device_train_batch_size",
- TrainingArguments.per_device_train_batch_size,
+ self._TrainingArguments.per_device_train_batch_size,
),
)
@@ -492,7 +505,7 @@ class TransformersEstimator(BaseEstimator):
trial_dir = ray.tune.get_trial_dir()
if transformers.__version__.startswith("3"):
- training_args = TrainingArguments(
+ training_args = self._TrainingArguments(
report_to=[],
output_dir=trial_dir,
do_train=True,
@@ -508,7 +521,7 @@ class TransformersEstimator(BaseEstimator):
else:
from transformers import IntervalStrategy
- training_args = TrainingArguments(
+ training_args = self._TrainingArguments(
report_to=[],
output_dir=trial_dir,
do_train=True,
@@ -532,7 +545,6 @@ class TransformersEstimator(BaseEstimator):
)
self._model = TrainerForAuto(
- model=this_model,
args=training_args,
model_init=_model_init,
train_dataset=train_dataset,
@@ -543,6 +555,8 @@ class TransformersEstimator(BaseEstimator):
)
setattr(self._model, "_use_ray", self.use_ray)
+ if self._task in NLG_TASKS:
+ setattr(self._model, "_is_seq2seq", True)
self._model.train()
self.params[self.ITER_HP] = self._model.state.global_step
@@ -551,6 +565,7 @@ class TransformersEstimator(BaseEstimator):
self._kwargs = kwargs
self._num_labels = num_labels
self._per_model_config = per_model_config
+ self._training_args_config = training_args_config
self._ckpt_remains = list(self._model.ckpt_to_metric.keys())
@@ -593,13 +608,27 @@ class TransformersEstimator(BaseEstimator):
def _compute_metrics_by_dataset_name(self, eval_pred):
from .ml import metric_loss_score
+ from .nlp.utils import postprocess_text
predictions, labels = eval_pred
- predictions = (
- np.squeeze(predictions)
- if self._task == SEQREGRESSION
- else np.argmax(predictions, axis=1)
- )
+
+ if self._task in NLG_TASKS:
+ if isinstance(predictions, tuple):
+ predictions = np.argmax(predictions[0], axis=2)
+ decoded_preds = self._tokenizer.batch_decode(
+ predictions, skip_special_tokens=True
+ )
+ labels = np.where(labels != -100, labels, self._tokenizer.pad_token_id)
+ decoded_labels = self._tokenizer.batch_decode(
+ labels, skip_special_tokens=True
+ )
+ predictions, labels = postprocess_text(decoded_preds, decoded_labels)
+ else:
+ predictions = (
+ np.squeeze(predictions)
+ if self._task == SEQREGRESSION
+ else np.argmax(predictions, axis=1)
+ )
return {
"val_loss": metric_loss_score(
@@ -608,16 +637,16 @@ class TransformersEstimator(BaseEstimator):
}
def predict_proba(self, X_test):
+ assert (
+ self._task in CLASSIFICATION
+ ), "predict_proba() only for classification tasks."
+
from datasets import Dataset
from .nlp.huggingface.trainer import TrainerForAuto
from transformers import TrainingArguments
from .nlp.utils import load_model
- assert (
- self._task in CLASSIFICATION
- ), "predict_proba is only available in classification tasks"
-
- X_test = self._preprocess(X_test, self._task, **self._kwargs)
+ X_test, _ = self._preprocess(X_test, task=self._task, **self._kwargs)
test_dataset = Dataset.from_pandas(X_test)
best_model = load_model(
@@ -636,11 +665,10 @@ class TransformersEstimator(BaseEstimator):
def predict(self, X_test):
from datasets import Dataset
- from transformers import TrainingArguments
from .nlp.utils import load_model
from .nlp.huggingface.trainer import TrainerForAuto
- X_test = self._preprocess(X_test, self._task, **self._kwargs)
+ X_test, _ = self._preprocess(X=X_test, task=self._task, **self._kwargs)
test_dataset = Dataset.from_pandas(X_test)
best_model = load_model(
@@ -649,20 +677,35 @@ class TransformersEstimator(BaseEstimator):
num_labels=self._num_labels,
per_model_config=self._per_model_config,
)
- training_args = TrainingArguments(
+ training_args = self._TrainingArguments(
per_device_eval_batch_size=1,
output_dir=self.custom_hpo_args.output_dir,
+ **self._training_args_config,
)
self._model = TrainerForAuto(model=best_model, args=training_args)
- predictions = self._model.predict(test_dataset)
+ if self._task not in NLG_TASKS:
+ predictions = self._model.predict(test_dataset)
+ else:
+ predictions = self._model.predict(
+ test_dataset,
+ max_length=training_args.generation_max_length,
+ num_beams=training_args.generation_num_beams,
+ )
if self._task == SEQCLASSIFICATION:
return np.argmax(predictions.predictions, axis=1)
elif self._task == SEQREGRESSION:
- return predictions.predictions.reshape((len(predictions.predictions),))
+ return predictions.predictions
# TODO: elif self._task == your task, return the corresponding prediction
# e.g., if your task == QUESTIONANSWERING, you need to return the answer instead
# of the index
+ elif self._task == SUMMARIZATION:
+ if isinstance(predictions.predictions, tuple):
+ predictions = np.argmax(predictions.predictions[0], axis=2)
+ decoded_preds = self._tokenizer.batch_decode(
+ predictions, skip_special_tokens=True
+ )
+ return decoded_preds
def config2params(self, config: dict) -> dict:
params = config.copy()
diff --git a/flaml/nlp/huggingface/trainer.py b/flaml/nlp/huggingface/trainer.py
index 7b944074f..98bb6dd34 100644
--- a/flaml/nlp/huggingface/trainer.py
+++ b/flaml/nlp/huggingface/trainer.py
@@ -1,19 +1,54 @@
import os
try:
- from transformers import Trainer as TFTrainer
from transformers import Seq2SeqTrainer
except ImportError:
- TFTrainer = object
+ Seq2SeqTrainer = object
-class TrainerForAuto(TFTrainer):
+class TrainerForAuto(Seq2SeqTrainer):
+ def predict(
+ self,
+ test_dataset,
+ ignore_keys=None,
+ metric_key_prefix=None,
+ max_length=None,
+ num_beams=None,
+ ):
+ if getattr(self, "_is_seq2seq", None):
+ return super().predict(
+ test_dataset,
+ ignore_keys,
+ metric_key_prefix,
+ max_length,
+ num_beams,
+ )
+ else:
+ return super(Seq2SeqTrainer, self).predict(
+ test_dataset, ignore_keys, metric_key_prefix
+ )
+
+ def prediction_step(
+ self,
+ model,
+ inputs,
+ prediction_loss_only,
+ ignore_keys,
+ ):
+ if getattr(self, "_is_seq2seq", None):
+ return super().prediction_step(
+ model, inputs, prediction_loss_only, ignore_keys
+ )
+ else:
+ return super(Seq2SeqTrainer, self).prediction_step(
+ model, inputs, prediction_loss_only, ignore_keys
+ )
+
def evaluate(
self,
eval_dataset=None,
ignore_keys=None,
metric_key_prefix="eval",
- is_seq2seq=False,
):
"""Overriding transformers.Trainer.evaluate by saving metrics and checkpoint path."""
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
@@ -25,19 +60,20 @@ class TrainerForAuto(TFTrainer):
# TODO: if your task is seq2seq (i.e., SUMMARIZATION), uncomment the code below (add indentation before metrics = eval_dataset...
- # if is_seq2seq:
- # metrics = eval_dataset and super().evaluate(
- # eval_dataset,
- # ignore_keys,
- # metric_key_prefix,
- # num_beams=self.args.num_beams,
- # )
- # else:
- metrics = eval_dataset and super().evaluate(
- eval_dataset,
- ignore_keys,
- metric_key_prefix,
- )
+ if getattr(self, "_is_seq2seq", None):
+ metrics = eval_dataset and super().evaluate(
+ eval_dataset,
+ ignore_keys,
+ metric_key_prefix,
+ max_length=self.args.generation_max_length,
+ num_beams=self.args.generation_num_beams,
+ )
+ else:
+ metrics = eval_dataset and super(Seq2SeqTrainer, self).evaluate(
+ eval_dataset,
+ ignore_keys,
+ metric_key_prefix,
+ )
if metrics:
for key in list(metrics.keys()):
if key.startswith("eval_"):
@@ -58,12 +94,14 @@ class TrainerForAuto(TFTrainer):
# Seq2SeqTrainerForAuto to make sure it's correct
-# class Seq2SeqTrainerForAuto(Seq2SeqTrainer, TrainerForAuto):
+# class Seq2SeqTrainerForAuto(TrainerForAuto):
# def evaluate(self, eval_dataset=None, ignore_keys=None, metric_key_prefix="eval"):
# """Overriding transformers.Trainer.evaluate by saving metrics and checkpoint path"""
-# super(TrainerForAuto).evaluate(
-# eval_dataset, ignore_keys, metric_key_prefix, is_seq2seq=True
-# )
+# self._is_seq2seq = True
+# TrainerForAuto.evaluate(self, eval_dataset, ignore_keys, metric_key_prefix)
+# # super(TrainerForAuto, self).evaluate(
+# # eval_dataset, ignore_keys, metric_key_prefix
+# # )
# TODO: if your task is QUESTIONANSWERING, uncomment the code below
diff --git a/flaml/nlp/utils.py b/flaml/nlp/utils.py
index 171d98afa..63ac1816a 100644
--- a/flaml/nlp/utils.py
+++ b/flaml/nlp/utils.py
@@ -2,23 +2,16 @@ import argparse
from dataclasses import dataclass, field
from typing import Dict, Any
-from ..data import (
- SUMMARIZATION,
- SEQREGRESSION,
- SEQCLASSIFICATION,
- NLG_TASKS
-)
+from ..data import SUMMARIZATION, SEQREGRESSION, SEQCLASSIFICATION, NLG_TASKS
def load_default_huggingface_metric_for_task(task):
- from ..data import SEQCLASSIFICATION, SEQREGRESSION
-
if task == SEQCLASSIFICATION:
- return "accuracy"
+ return "accuracy", "max"
elif task == SEQREGRESSION:
- return "rmse"
+ return "rmse", "max"
elif task == SUMMARIZATION:
- return "rouge"
+ return "rouge", "max"
# TODO: elif task == your task, return the default metric name for your task,
# e.g., if task == MULTIPLECHOICE, return "accuracy"
# notice this metric name has to be in ['accuracy', 'bertscore', 'bleu', 'bleurt',
@@ -32,61 +25,138 @@ def load_default_huggingface_metric_for_task(task):
global tokenized_column_names
-def tokenize_text(X, task, custom_hpo_task):
- from ..data import SEQCLASSIFICATION, SEQREGRESSION
-
+def tokenize_text(X, Y=None, task=None, custom_hpo_args=None):
if task in (SEQCLASSIFICATION, SEQREGRESSION):
- return tokenize_text_seqclassification(X, custom_hpo_task)
- # TODO: elif task == your task, return the tokenized result
- # for example, if your task == MULTIPLE CHOICE, you should
- # create a function named tokenize_text_multiplechoice(X, custom_hpo_args)
- # and what it does is the same as preprocess_function at
- # https://github.com/huggingface/transformers/blob/master/examples/pytorch/multiple-choice/run_swag.py#L329
+ X_tokenized, _ = tokenize_onedataframe(
+ X, this_tokenizer=None, task=task, custom_hpo_args=custom_hpo_args
+ )
+ return X_tokenized, None
+ elif task in NLG_TASKS:
+ return tokenize_seq2seq(X, Y, task=task, custom_hpo_args=custom_hpo_args)
+
+
+def tokenize_seq2seq(X, Y, task=None, custom_hpo_args=None):
+ model_inputs, tokenizer = tokenize_onedataframe(
+ X,
+ this_tokenizer=None,
+ task=task,
+ custom_hpo_args=custom_hpo_args,
+ )
+ labels = None
+ if Y is not None:
+ labels, _ = tokenize_onedataframe(
+ Y.to_frame(),
+ this_tokenizer=tokenizer,
+ task=task,
+ custom_hpo_args=custom_hpo_args,
+ )
+ labels["label"] = [
+ [(each_l if each_l != tokenizer.pad_token_id else -100) for each_l in label]
+ for label in labels["input_ids"]
+ ]
+ labels = labels.drop(
+ columns=["attention_mask", "input_ids", "decoder_input_ids"]
+ )
+ return model_inputs, labels
-def tokenize_text_seqclassification(X, custom_hpo_args):
+def tokenize_onedataframe(
+ X,
+ this_tokenizer=None,
+ task=None,
+ custom_hpo_args=None,
+):
from transformers import AutoTokenizer
import pandas
global tokenized_column_names
- this_tokenizer = AutoTokenizer.from_pretrained(
- custom_hpo_args.model_path, use_fast=True
- )
- d = X.apply(
- lambda x: tokenize_glue(x, this_tokenizer, custom_hpo_args),
- axis=1,
- result_type="expand",
- )
+ 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
+ )
+ d = X.apply(
+ lambda x: tokenize_row(
+ x,
+ this_tokenizer,
+ prefix=("summarize: ",) if task is SUMMARIZATION else None,
+ task=task,
+ custom_hpo_args=custom_hpo_args,
+ ),
+ axis=1,
+ result_type="expand",
+ )
X_tokenized = pandas.DataFrame(columns=tokenized_column_names)
X_tokenized[tokenized_column_names] = d
- return X_tokenized
+ return X_tokenized, this_tokenizer
+
+def postprocess_text(preds, labels):
+ import nltk
-def tokenize_glue(this_row, this_tokenizer, custom_hpo_args):
+ nltk.download("punkt")
+ preds = [pred.strip() for pred in preds]
+ labels = [label.strip() for label in labels]
+
+ # rougeLSum expects newline after each sentence
+ preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds]
+ labels = ["\n".join(nltk.sent_tokenize(label)) for label in labels]
+
+ return preds, labels
+
+
+def tokenize_row(
+ this_row, this_tokenizer, prefix=None, task=None, custom_hpo_args=None
+):
global tokenized_column_names
assert (
"max_seq_length" in custom_hpo_args.__dict__
), "max_seq_length must be provided for glue"
+ if prefix:
+ this_row = tuple(["".join(x) for x in zip(prefix, this_row)])
+
tokenized_example = this_tokenizer(
*tuple(this_row),
padding="max_length",
max_length=custom_hpo_args.max_seq_length,
truncation=True,
)
+ if task in NLG_TASKS:
+ tokenized_example["decoder_input_ids"] = tokenized_example["input_ids"]
tokenized_column_names = sorted(tokenized_example.keys())
return [tokenized_example[x] for x in tokenized_column_names]
-def separate_config(config):
- from transformers import TrainingArguments
+def separate_config(config, task):
+ if task in NLG_TASKS:
+ from transformers import Seq2SeqTrainingArguments, TrainingArguments
+
+ trainargs_class_list = [Seq2SeqTrainingArguments, TrainingArguments]
+ else:
+ from transformers import TrainingArguments
+
+ trainargs_class_list = [TrainingArguments]
training_args_config = {}
per_model_config = {}
for key, val in config.items():
- if key in TrainingArguments.__dict__:
+ is_in_training_args = any(key in x.__dict__ for x in trainargs_class_list)
+ if is_in_training_args:
training_args_config[key] = val
else:
per_model_config[key] = val
@@ -176,24 +246,25 @@ def load_model(checkpoint_path, task, num_labels, per_model_config=None):
this_model_type = AutoConfig.from_pretrained(checkpoint_path).model_type
this_vocab_size = AutoConfig.from_pretrained(checkpoint_path).vocab_size
- def get_this_model():
+ def get_this_model(task):
from transformers import AutoModelForSequenceClassification
+ from transformers import AutoModelForSeq2SeqLM
if task in (SEQCLASSIFICATION, SEQREGRESSION):
return AutoModelForSequenceClassification.from_pretrained(
checkpoint_path, config=model_config
)
- # TODO: elif task == your task, fill in the line in your transformers example
- # that loads the model, e.g., if task == MULTIPLE CHOICE, according to
- # https://github.com/huggingface/transformers/blob/master/examples/pytorch/multiple-choice/run_swag.py#L298
- # you can return AutoModelForMultipleChoice.from_pretrained(checkpoint_path, config=model_config)
+ elif task in NLG_TASKS:
+ return AutoModelForSeq2SeqLM.from_pretrained(
+ checkpoint_path, config=model_config
+ )
def is_pretrained_model_in_classification_head_list(model_type):
return model_type in MODEL_CLASSIFICATION_HEAD_MAPPING
def _set_model_config(checkpoint_path):
if task in (SEQCLASSIFICATION, SEQREGRESSION):
- if per_model_config and len(per_model_config) > 0:
+ if per_model_config:
model_config = AutoConfig.from_pretrained(
checkpoint_path,
num_labels=model_config_num_labels,
@@ -204,18 +275,15 @@ def load_model(checkpoint_path, task, num_labels, per_model_config=None):
checkpoint_path, num_labels=model_config_num_labels
)
return model_config
- # TODO: elif task == your task, uncomment the code below:
- # else:
- # if per_model_config and len(per_model_config) > 0:
- # model_config = AutoConfig.from_pretrained(
- # checkpoint_path,
- # **per_model_config,
- # )
- # else:
- # model_config = AutoConfig.from_pretrained(
- # checkpoint_path
- # )
- # return model_config
+ else:
+ if per_model_config:
+ model_config = AutoConfig.from_pretrained(
+ checkpoint_path,
+ **per_model_config,
+ )
+ else:
+ model_config = AutoConfig.from_pretrained(checkpoint_path)
+ return model_config
if task == SEQCLASSIFICATION:
num_labels_old = AutoConfig.from_pretrained(checkpoint_path).num_labels
@@ -227,7 +295,7 @@ def load_model(checkpoint_path, task, num_labels, per_model_config=None):
if is_pretrained_model_in_classification_head_list(this_model_type):
if num_labels != num_labels_old:
- this_model = get_this_model()
+ this_model = get_this_model(task)
model_config.num_labels = num_labels
this_model.num_labels = num_labels
this_model.classifier = (
@@ -236,16 +304,16 @@ def load_model(checkpoint_path, task, num_labels, per_model_config=None):
)
)
else:
- this_model = get_this_model()
+ this_model = get_this_model(task)
else:
- this_model = get_this_model()
+ this_model = get_this_model(task)
this_model.resize_token_embeddings(this_vocab_size)
return this_model
else:
if task == SEQREGRESSION:
model_config_num_labels = 1
model_config = _set_model_config(checkpoint_path)
- this_model = get_this_model()
+ this_model = get_this_model(task)
return this_model
diff --git a/setup.py b/setup.py
index 0ea3c50a6..d1f82f8fd 100644
--- a/setup.py
+++ b/setup.py
@@ -56,8 +56,10 @@ setuptools.setup(
"psutil==5.8.0",
"dataclasses",
"transformers",
- "datasets==1.4.1",
+ "datasets",
"torch",
+ "nltk",
+ "rouge_score",
],
"catboost": ["catboost>=0.26"],
"blendsearch": ["optuna==2.8.0"],
@@ -74,7 +76,7 @@ setuptools.setup(
"vw": [
"vowpalwabbit",
],
- "nlp": ["transformers", "datasets==1.4.1", "torch"],
+ "nlp": ["transformers", "datasets", "torch", "nltk", "rouge_score"],
"ts_forecast": ["prophet>=1.0.1", "statsmodels>=0.12.2"],
"forecast": ["prophet>=1.0.1", "statsmodels>=0.12.2"],
"benchmark": ["catboost>=0.26", "psutil==5.8.0", "xgboost==1.3.3"],
diff --git a/test/nlp/test_autohf.py b/test/nlp/test_autohf.py
index 6250df5ce..32d116834 100644
--- a/test/nlp/test_autohf.py
+++ b/test/nlp/test_autohf.py
@@ -103,8 +103,8 @@ def _test_custom_data():
automl_settings = {
"gpu_per_trial": 0,
- "max_iter": 10,
- "time_budget": 300,
+ "max_iter": 3,
+ "time_budget": 5,
"task": "seq-classification",
"metric": "accuracy",
}
diff --git a/test/nlp/test_autohf_summarization.py b/test/nlp/test_autohf_summarization.py
new file mode 100644
index 000000000..0bc531f1d
--- /dev/null
+++ b/test/nlp/test_autohf_summarization.py
@@ -0,0 +1,82 @@
+import os
+import pytest
+
+
[email protected](os.name == "darwin", reason="do not run on mac os")
+def test_summarization():
+ from flaml import AutoML
+ from pandas import DataFrame
+
+ train_dataset = DataFrame(
+ [
+ ("The cat is alive", "The cat is dead"),
+ ("The cat is alive", "The cat is dead"),
+ ("The cat is alive", "The cat is dead"),
+ ("The cat is alive", "The cat is dead"),
+ ]
+ )
+ dev_dataset = DataFrame(
+ [
+ ("The old woman is beautiful", "The old woman is ugly"),
+ ("The old woman is beautiful", "The old woman is ugly"),
+ ("The old woman is beautiful", "The old woman is ugly"),
+ ("The old woman is beautiful", "The old woman is ugly"),
+ ]
+ )
+ test_dataset = DataFrame(
+ [
+ ("The purse is cheap", "The purse is expensive"),
+ ("The purse is cheap", "The purse is expensive"),
+ ("The purse is cheap", "The purse is expensive"),
+ ("The purse is cheap", "The purse is expensive"),
+ ]
+ )
+
+ for each_dataset in [train_dataset, dev_dataset, test_dataset]:
+ each_dataset.columns = ["document", "summary"]
+
+ custom_sent_keys = ["document"]
+ label_key = "summary"
+
+ X_train = train_dataset[custom_sent_keys]
+ y_train = train_dataset[label_key]
+
+ X_val = dev_dataset[custom_sent_keys]
+ y_val = dev_dataset[label_key]
+
+ X_test = test_dataset[custom_sent_keys]
+
+ automl = AutoML()
+
+ automl_settings = {
+ "gpu_per_trial": 0,
+ "max_iter": 3,
+ "time_budget": 20,
+ "task": "summarization",
+ "metric": "rouge1",
+ "log_file_name": "seqclass.log",
+ }
+
+ automl_settings["custom_hpo_args"] = {
+ "model_path": "patrickvonplaten/t5-tiny-random",
+ "output_dir": "test/data/output/",
+ "ckpt_per_epoch": 5,
+ "fp16": False,
+ }
+
+ automl.fit(
+ X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, **automl_settings
+ )
+ automl = AutoML()
+ automl.retrain_from_log(
+ X_train=X_train,
+ y_train=y_train,
+ train_full=True,
+ record_id=0,
+ **automl_settings
+ )
+ automl.predict(X_test)
+
+
+if __name__ == "__main__":
+ test_summarization()
diff --git a/website/docs/Examples/AutoML-NLP.md b/website/docs/Examples/AutoML-NLP.md
index 2490c8a75..9390fcced 100644
--- a/website/docs/Examples/AutoML-NLP.md
+++ b/website/docs/Examples/AutoML-NLP.md
@@ -58,10 +58,10 @@ from flaml import AutoML
from datasets import load_dataset
train_dataset = (
- load_dataset("glue", "stsb", split="train[:1%]").to_pandas().iloc[0:4]
+ load_dataset("glue", "stsb", split="train").to_pandas()
)
dev_dataset = (
- load_dataset("glue", "stsb", split="train[1%:2%]").to_pandas().iloc[0:4]
+ load_dataset("glue", "stsb", split="train").to_pandas()
)
custom_sent_keys = ["sentence1", "sentence2"]
label_key = "label"
@@ -86,4 +86,121 @@ automl_settings["custom_hpo_args"] = {
automl.fit(
X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, **automl_settings
)
+```
+
+### Sample output
+
+```
+[flaml.automl: 12-20 11:47:28] {1965} INFO - task = seq-regression
+[flaml.automl: 12-20 11:47:28] {1967} INFO - Data split method: uniform
+[flaml.automl: 12-20 11:47:28] {1971} INFO - Evaluation method: holdout
+[flaml.automl: 12-20 11:47:28] {2063} INFO - Minimizing error metric: rmse
+[flaml.automl: 12-20 11:47:28] {2115} INFO - List of ML learners in AutoML Run: ['transformer']
+[flaml.automl: 12-20 11:47:28] {2355} INFO - iteration 0, current learner transformer
+```
+
+### A simple summarization example
+
+```python
+from flaml import AutoML
+from datasets import load_dataset
+
+train_dataset = (
+ load_dataset("xsum", split="train").to_pandas()
+)
+dev_dataset = (
+ load_dataset("xsum", split="validation").to_pandas()
+)
+custom_sent_keys = ["document"]
+label_key = "summary"
+
+X_train = train_dataset[custom_sent_keys]
+y_train = train_dataset[label_key]
+
+X_val = dev_dataset[custom_sent_keys]
+y_val = dev_dataset[label_key]
+
+automl = AutoML()
+automl_settings = {
+ "gpu_per_trial": 1,
+ "time_budget": 20,
+ "task": "summarization",
+ "metric": "rouge1",
+}
+automl_settings["custom_hpo_args"] = {
+ "model_path": "t5-small",
+ "output_dir": "data/output/",
+ "ckpt_per_epoch": 5,
+ "fp16": False,
+}
+automl.fit(
+ X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, **automl_settings
+)
+```
+### Sample Output
+
+```
+[flaml.automl: 12-20 11:44:03] {1965} INFO - task = summarization
+[flaml.automl: 12-20 11:44:03] {1967} INFO - Data split method: uniform
+[flaml.automl: 12-20 11:44:03] {1971} INFO - Evaluation method: holdout
+[flaml.automl: 12-20 11:44:03] {2063} INFO - Minimizing error metric: -rouge
+[flaml.automl: 12-20 11:44:03] {2115} INFO - List of ML learners in AutoML Run: ['transformer']
+[flaml.automl: 12-20 11:44:03] {2355} INFO - iteration 0, current learner transformer
+loading configuration file https://huggingface.co/t5-small/resolve/main/config.json from cache at /home/xliu127/.cache/huggingface/transformers/fe501e8fd6425b8ec93df37767fcce78ce626e34cc5edc859c662350cf712e41.406701565c0afd9899544c1cb8b93185a76f00b31e5ce7f6e18bbaef02241985
+Model config T5Config {
+ "_name_or_path": "t5-small",
+ "architectures": [
+ "T5WithLMHeadModel"
+ ],
+ "d_ff": 2048,
+ "d_kv": 64,
+ "d_model": 512,
+ "decoder_start_token_id": 0,
+ "dropout_rate": 0.1,
+ "eos_token_id": 1,
+ "feed_forward_proj": "relu",
+ "initializer_factor": 1.0,
+ "is_encoder_decoder": true,
+ "layer_norm_epsilon": 1e-06,
+ "model_type": "t5",
+ "n_positions": 512,
+ "num_decoder_layers": 6,
+ "num_heads": 8,
+ "num_layers": 6,
+ "output_past": true,
+ "pad_token_id": 0,
+ "relative_attention_num_buckets": 32,
+ "task_specific_params": {
+ "summarization": {
+ "early_stopping": true,
+ "length_penalty": 2.0,
+ "max_length": 200,
+ "min_length": 30,
+ "no_repeat_ngram_size": 3,
+ "num_beams": 4,
+ "prefix": "summarize: "
+ },
+ "translation_en_to_de": {
+ "early_stopping": true,
+ "max_length": 300,
+ "num_beams": 4,
+ "prefix": "translate English to German: "
+ },
+ "translation_en_to_fr": {
+ "early_stopping": true,
+ "max_length": 300,
+ "num_beams": 4,
+ "prefix": "translate English to French: "
+ },
+ "translation_en_to_ro": {
+ "early_stopping": true,
+ "max_length": 300,
+ "num_beams": 4,
+ "prefix": "translate English to Romanian: "
+ }
+ },
+ "transformers_version": "4.14.1",
+ "use_cache": true,
+ "vocab_size": 32128
+}
```
\ No newline at end of file
diff --git a/website/docs/Use-Cases/Task-Oriented-AutoML.md b/website/docs/Use-Cases/Task-Oriented-AutoML.md
index 3850d700b..22b8e7798 100644
--- a/website/docs/Use-Cases/Task-Oriented-AutoML.md
+++ b/website/docs/Use-Cases/Task-Oriented-AutoML.md
@@ -14,6 +14,7 @@
- 'rank': learning to rank.
- 'seq-classification': sequence classification.
- 'seq-regression': sequence regression.
+ - 'summarization': text summarization.
An optional input is `time_budget` for searching models and hyperparameters. When not specified, a default budget of 60 seconds will be used.