💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add trainer pipeline, closes #96
davidmezzetti6ff95297b787
diff --git a/setup.py b/setup.pyindex 9e527ecf..1f9f6d1d 100644--- a/setup.py+++ b/setup.py@@ -44,7 +44,7 @@ setup("tika>=1.24","torch>=1.4.0","tqdm>=4.46.0",- "transformers>=4.4.2",+ "transformers>=4.8.2","uvicorn>=0.12.1",],extras_require={"dev": ["black", "coverage", "pre-commit", "pylint"]},diff --git a/src/python/txtai/models/models.py b/src/python/txtai/models/models.pyindex 038872c2..6cd3b813 100644--- a/src/python/txtai/models/models.py+++ b/src/python/txtai/models/models.py@@ -9,16 +9,20 @@ class Models:"""@staticmethod- def checklength(model, tokenizer):+ def checklength(config, tokenizer):"""- Checks the length for a Hugging Face Transformers tokenizer using a Hugging Face Transformers model. Copies the+ Checks the length for a Hugging Face Transformers tokenizer using a Hugging Face Transformers config. Copies themax_position_embeddings parameter if the tokenizer has no max_length set. This helps with backwards compatibilitywith older tokenizers.Args:- model: Transformers model+ config: Transformers configtokenizer: Transformers tokenizer"""- if hasattr(model, "config") and hasattr(model.config, "max_position_embeddings") and tokenizer.model_max_length == int(1e30):- tokenizer.model_max_length = model.config.max_position_embeddings+ # Unpack nested config, handles passing model directly+ if hasattr(config, "config"):+ config = config.config++ if hasattr(config, "max_position_embeddings") and tokenizer.model_max_length == int(1e30):+ tokenizer.model_max_length = config.max_position_embeddingsdiff --git a/src/python/txtai/pipeline/__init__.py b/src/python/txtai/pipeline/__init__.pyindex c12506f4..24d76a56 100644--- a/src/python/txtai/pipeline/__init__.py+++ b/src/python/txtai/pipeline/__init__.py@@ -7,6 +7,7 @@ from .extractor import Extractorfrom .factory import PipelineFactoryfrom .hfmodel import HFModelfrom .hfpipeline import HFPipeline+from .hftrainer import HFTrainerfrom .labels import Labelsfrom .questions import Questionsfrom .segmentation import Segmentationdiff --git a/src/python/txtai/pipeline/hfpipeline.py b/src/python/txtai/pipeline/hfpipeline.pyindex cc7a375c..9427f6ff 100644--- a/src/python/txtai/pipeline/hfpipeline.py+++ b/src/python/txtai/pipeline/hfpipeline.py@@ -35,7 +35,10 @@ class HFPipeline(Tensors):deviceid = self.deviceid(gpu)# Transformer pipeline task- self.pipeline = pipeline(task, model=path, tokenizer=path, device=deviceid)+ if isinstance(path, tuple):+ self.pipeline = pipeline(task, model=path[0], tokenizer=path[1], device=deviceid)+ else:+ self.pipeline = pipeline(task, model=path, tokenizer=path, device=deviceid)# Model quantization. Compresses model to int8 precision, improves runtime performance. Only supported on CPU.if deviceid == -1 and quantize:diff --git a/src/python/txtai/pipeline/hftrainer.py b/src/python/txtai/pipeline/hftrainer.pynew file mode 100644index 00000000..0cd075b2--- /dev/null+++ b/src/python/txtai/pipeline/hftrainer.py@@ -0,0 +1,259 @@+"""+Hugging Face Transformers trainer wrapper module+"""++import sys++import torch++from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer+from transformers import Trainer, set_seed++from transformers import TrainingArguments as HFTrainingArguments++from .tensors import Tensors+from ..models import Models+++class HFTrainer(Tensors):+ """+ Trains a new Hugging Face Transformer model using the Trainer API.+ """++ def __call__(self, base, train, validation=None, columns=None, maxlength=None, **args):+ """+ Builds a new model using arguments.++ Args:+ base: base model - supports a file path or (model, tokenizer) tuple+ train: training data+ validation: validation data+ columns: tuple of columns to use for text/label, defaults to (text, None, label)+ maxlength: maximum sequence length, defaults to tokenizer.model_max_length+ args: training arguments++ Returns:+ (model, tokenizer)+ """++ # Parse TrainingArguments+ args = self.parse(args)++ # Set seed for model reproducibility+ set_seed(args.seed)++ # Load model configuration, tokenizer and max sequence length+ config, tokenizer, maxlength = self.load(base, maxlength)++ # Prepare datasets+ train, validation, labels = self.datasets(train, validation, columns, tokenizer, maxlength)++ # Create model to train+ model = self.model(base, config, labels)++ # Build trainer+ trainer = Trainer(model=model, tokenizer=tokenizer, args=args, train_dataset=train, eval_dataset=validation if validation else None)++ # Run training+ trainer.train()++ # Run evaluation+ if validation:+ trainer.evaluate()++ # Save model outputs+ if args.should_save:+ trainer.save_model()+ trainer.save_state()++ # Put model in eval mode to disable weight updates and return (model, tokenizer)+ return (model.eval(), tokenizer)++ def parse(self, updates):+ """+ Parses and merges custom arguments with defaults.++ Args:+ updates: custom arguments++ Returns:+ TrainingArguments+ """++ # Default training arguments+ args = {"output_dir": "", "save_strategy": "no", "report_to": "none", "log_level": "warning"}++ # Apply custom arguments+ args.update(updates)++ return TrainingArguments(**args)++ def load(self, base, maxlength):+ """+ Loads the base config and tokenizer.++ Args:+ base: base model - supports a file path or (model, tokenizer) tuple+ maxlength: maximum sequence length++ Returns:+ (config, tokenizer, maxlength)+ """++ if isinstance(base, tuple):+ # Unpack existing config and tokenizer+ model, tokenizer = base+ config = model.config+ else:+ # Load config+ config = AutoConfig.from_pretrained(base)++ # Load tokenizer+ tokenizer = AutoTokenizer.from_pretrained(base)++ # Detect unbounded tokenizer+ Models.checklength(config, tokenizer)++ # Derive max sequence length+ maxlength = min(maxlength if maxlength else sys.maxsize, tokenizer.model_max_length)++ return (config, tokenizer, maxlength)++ def datasets(self, train, validation, columns, tokenizer, maxlength):+ """+ Prepares training and validation datasets for training.++ Args:+ train: training data+ validation: validation data+ columns: tuple of columns to use for text/label+ tokenizer: model tokenizer+ maxlength: maximum sequence length++ Returns:+ (train, validation, labels)+ """++ # Standardize columns+ if not columns:+ columns = ("text", None, "label")+ elif len(columns) < 3:+ columns = (columns[0], None, columns[-1])++ # Prepare training data and labels+ train, labels = self.prepare(train, columns, tokenizer, maxlength)++ # Prepare validation data+ if validation:+ validation, _ = self.prepare(validation, columns, tokenizer, maxlength)++ return (train, validation, labels)++ def prepare(self, data, columns, tokenizer, maxlength):+ """+ Prepares and tokenizes data for training.++ Args:+ data: input data+ columns: tuple of columns to use for text/label+ tokenizer: model tokenizer+ maxlength: maximum sequence length++ Returns:+ (tokens, labels)+ """++ if hasattr(data, "map"):+ # Hugging Face dataset+ tokens = data.map(lambda row: self.tokenize(row, columns, tokenizer, maxlength))+ labels = sorted(data.features[columns[-1]].names)+ else:+ # pandas DataFrame+ if hasattr(data, "to_dict"):+ data = data.to_dict("records")++ # Process list of dicts+ tokens = TokenDataset([self.tokenize(row, columns, tokenizer, maxlength) for row in data])+ labels = sorted({row[columns[-1]] for row in data})++ # Determine number of labels, account for regression tasks+ labels = 1 if [x for x in labels if isinstance(x, float)] else len(labels)++ return (tokens, labels)++ def tokenize(self, row, columns, tokenizer, maxlength):+ """+ Tokenizes data row.++ Args:+ row: input data+ columns: tuple of columns to use for text/label+ tokenizer: model tokenizer+ maxlength: maximum sequence length++ Returns:+ tokens+ """++ # Column keys+ text1, text2, label = columns++ # Tokenizer inputs can be single string or string pair, depending on task+ text = (row[text1], row[text2]) if text2 else (row[text1],)++ # Tokenize text and add label+ inputs = tokenizer(*text, max_length=maxlength, padding=True, truncation=True)+ inputs[label] = row[label]++ return inputs++ def model(self, base, config, labels):+ """+ Loads the base model to train.++ Args:+ base: base model - supports a file path or (model, tokenizer) tuple+ config: model configuration+ labels: number of labels++ Returns:+ model+ """++ # Add number of labels to config+ config.update({"num_labels": labels})++ # Unpack existing model or create new model from config+ return base[0] if isinstance(base, tuple) else AutoModelForSequenceClassification.from_pretrained(base, config=config)+++class TokenDataset(torch.utils.data.Dataset):+ """+ Default dataset used to hold tokenized data.+ """++ def __init__(self, data):+ self.data = data++ def __len__(self):+ return len(self.data)++ def __getitem__(self, index):+ return self.data[index]+++class TrainingArguments(HFTrainingArguments):+ """+ Extends standard TrainingArguments to make the output directory optional for transient models.+ """++ @property+ def should_save(self):+ """+ Override should_save to disable model saving when output directory is None.++ Returns:+ If model should be saved+ """++ return super().should_save if self.output_dir else Falsediff --git a/test/python/testtrainer.py b/test/python/testtrainer.pynew file mode 100644index 00000000..7779f4c0--- /dev/null+++ b/test/python/testtrainer.py@@ -0,0 +1,141 @@+"""+Trainer module tests+"""++import os+import unittest+import tempfile++import torch++from transformers import AutoTokenizer, AutoModelForSequenceClassification++from txtai.pipeline import HFTrainer, Labels+++class TestTrainer(unittest.TestCase):+ """+ Trainer tests+ """++ @classmethod+ def setUpClass(cls):+ """+ Create default datasets+ """++ cls.data = [{"text": "Dogs", "label": 0}, {"text": "dog", "label": 0}, {"text": "Cats", "label": 1}, {"text": "cat", "label": 1}] * 100++ def testBasic(self):+ """+ Test training a model with basic parameters+ """++ trainer = HFTrainer()+ model, tokenizer = trainer("google/bert_uncased_L-2_H-128_A-2", self.data)++ labels = Labels((model, tokenizer), dynamic=False)+ self.assertEqual(labels("cat")[0][0], 1)++ def testCustom(self):+ """+ Test training a model with custom parameters+ """++ model = AutoModelForSequenceClassification.from_pretrained("google/bert_uncased_L-2_H-128_A-2")+ tokenizer = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")++ trainer = HFTrainer()+ model, tokenizer = trainer(+ (model, tokenizer),+ self.data,+ self.data,+ columns=("text", "label"),+ do_eval=True,+ output_dir=os.path.join(tempfile.gettempdir(), "trainer"),+ )++ labels = Labels((model, tokenizer), dynamic=False)+ self.assertEqual(labels("cat")[0][0], 1)++ def testDataframe(self):+ """+ Test training a model with a mock pandas DataFrame+ """++ # pylint: disable=W0613+ def to_dict(orient):+ return self.data++ df = unittest.mock.Mock(spec=["to_dict"])+ df.to_dict = to_dict++ trainer = HFTrainer()+ model, tokenizer = trainer("google/bert_uncased_L-2_H-128_A-2", df)++ labels = Labels((model, tokenizer), dynamic=False)+ self.assertEqual(labels("cat")[0][0], 1)++ def testDataset(self):+ """+ Test training a model with a mock Hugging Face Dataset+ """++ class TestDataset(torch.utils.data.Dataset):+ """+ Test Dataset+ """++ def __init__(self, data):+ self.data = data++ label = unittest.mock.Mock()+ label.names = [0, 1]++ self.features = {"label": label}++ def __len__(self):+ return len(self.data)++ def __getitem__(self, index):+ return self.data[index]++ def map(self, fn):+ """+ Map each dataset row using fn.++ Args:+ fn: function++ Returns:+ updated Dataset+ """++ self.data = [fn(x) for x in self.data]+ return self++ ds = TestDataset(self.data)++ trainer = HFTrainer()+ model, tokenizer = trainer("google/bert_uncased_L-2_H-128_A-2", ds)++ labels = Labels((model, tokenizer), dynamic=False)+ self.assertEqual(labels("cat")[0][0], 1)++ def testRegression(self):+ """+ Tests training a model with a regression (continuous) output.+ """++ data = []+ for x in self.data:+ x["label"] = float(x["label"])+ data.append(x)++ trainer = HFTrainer()+ model, tokenizer = trainer("google/bert_uncased_L-2_H-128_A-2", data)++ labels = Labels((model, tokenizer), dynamic=False)++ # Regression tasks return a single entry with the regression output+ self.assertGreater(labels("cat")[0][1], 0.5)