Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Refactor training pipeline to support additional model types. Add QA models, closes #111

davidmezzetti780a78904e43
diff --git a/src/python/txtai/data/__init__.py b/src/python/txtai/data/__init__.py
new file mode 100644
index 00000000..3cfe00a9
--- /dev/null
+++ b/src/python/txtai/data/__init__.py
@@ -0,0 +1,8 @@
+"""
+Data imports
+"""
+
+from .base import Data
+from .labels import Labels
+from .questions import Questions
+from .tokens import Tokens
diff --git a/src/python/txtai/data/base.py b/src/python/txtai/data/base.py
new file mode 100644
index 00000000..ca9be58c
--- /dev/null
+++ b/src/python/txtai/data/base.py
@@ -0,0 +1,111 @@
+"""
+Data module
+"""
+
+from .tokens import Tokens
+
+
+class Data:
+ """
+ Base data tokenization class.
+ """
+
+ def __init__(self, tokenizer, columns, maxlength):
+ """
+ Creates new base instance for tokenizing data.
+
+ Args:
+ tokenizer: model tokenizer
+ columns: column names
+ maxlength: maximum sequence length
+ """
+
+ self.tokenizer = tokenizer
+ self.columns = columns
+ self.maxlength = maxlength
+
+ def __call__(self, train, validation):
+ """
+ Tokenizes training and validation data and returns processed datasets.
+
+ Args:
+ train: training data
+ validation: validation data
+
+ Returns:
+ (train, validation)
+ """
+
+ return (self.prepare(train, self.process), self.prepare(validation, self.process) if validation else None)
+
+ def prepare(self, data, fn):
+ """
+ Prepares and tokenizes data for training.
+
+ Args:
+ data: input data
+ fn: tokenize processing function to apply
+
+ Returns:
+ tokens
+ """
+
+ if hasattr(data, "map"):
+ # Hugging Face dataset
+ tokens = data.map(fn, batched=True)
+ else:
+ # pandas DataFrame
+ if hasattr(data, "to_dict"):
+ data = data.to_dict("records")
+
+ # Re-orient data into columns for efficient batch tokenization
+ columns = {}
+ for row in data:
+ for column in row.keys():
+ if column not in columns:
+ columns[column] = []
+
+ columns[column].append(row[column])
+
+ # Process column-oriented data
+ tokens = Tokens(fn(columns))
+
+ return tokens
+
+ def labels(self, data):
+ """
+ Extracts a list of unique labels from data.
+
+ Args:
+ data: input data
+
+ Returns:
+ list of unique labels
+ """
+
+ if hasattr(data, "map"):
+ # Hugging Face dataset
+ labels = sorted(data.unique(self.columns[-1]))
+ else:
+ # pandas DataFrame
+ if hasattr(data, "to_dict"):
+ data = data.to_dict("records")
+
+ # Process list of dicts
+ labels = sorted({row[self.columns[-1]] for row in data})
+
+ # Determine number of labels, account for regression tasks
+ return 1 if [x for x in labels if isinstance(x, float)] else len(labels)
+
+ def process(self, data):
+ """
+ Tokenizes batch of input data
+
+ Args:
+ data: input data batch
+
+ Returns:
+ tokenized data
+ """
+
+ return data
diff --git a/src/python/txtai/data/labels.py b/src/python/txtai/data/labels.py
new file mode 100644
index 00000000..50b1d7a0
--- /dev/null
+++ b/src/python/txtai/data/labels.py
@@ -0,0 +1,42 @@
+"""
+Labels module
+"""
+
+from .base import Data
+
+
+class Labels(Data):
+ """
+ Tokenizes text-classification datasets used as input for training text-classification models.
+ """
+
+ def __init__(self, tokenizer, columns, maxlength):
+ """
+ Creates a new instance for tokenizing Labels training data.
+
+ Args:
+ tokenizer: model tokenizer
+ columns: tuple of columns to use for text/label
+ maxlength: maximum sequence length
+ """
+
+ super().__init__(tokenizer, columns, maxlength)
+
+ # Standardize columns
+ if not self.columns:
+ self.columns = ("text", None, "label")
+ elif len(columns) < 3:
+ self.columns = (self.columns[0], None, self.columns[-1])
+
+ def process(self, data):
+ # Column keys
+ text1, text2, label = self.columns
+
+ # Tokenizer inputs can be single string or string pair, depending on task
+ text = (data[text1], data[text2]) if text2 else (data[text1],)
+
+ # Tokenize text and add label
+ inputs = self.tokenizer(*text, max_length=self.maxlength, padding=True, truncation=True)
+ inputs[label] = data[label]
+
+ return inputs
diff --git a/src/python/txtai/data/questions.py b/src/python/txtai/data/questions.py
new file mode 100644
index 00000000..045fb659
--- /dev/null
+++ b/src/python/txtai/data/questions.py
@@ -0,0 +1,140 @@
+"""
+Questions module
+"""
+
+from .base import Data
+
+
+class Questions(Data):
+ """
+ Tokenizes question-answering datasets used as input for training question-answering models.
+ """
+
+ def __init__(self, tokenizer, columns, maxlength, stride):
+ """
+ Creates a new instance for tokenizing Questions training data.
+
+ Args:
+ tokenizer: model tokenizer
+ columns: tuple of columns to use for question/context/answer
+ maxlength: maximum sequence length
+ stride: chunk size for splitting data for QA tasks
+ """
+
+ super().__init__(tokenizer, columns, maxlength)
+
+ if not self.columns:
+ self.columns = ("question", "context", "answers")
+
+ self.question, self.context, self.answer = self.columns
+ self.stride = stride
+ self.rpad = tokenizer.padding_side == "right"
+
+ def process(self, data):
+ # Tokenize data
+ tokenized = self.tokenize(data)
+
+ # Get mapping of overflowing tokens and answer offsets
+ samples = tokenized.pop("overflow_to_sample_mapping")
+ offsets = tokenized.pop("offset_mapping")
+
+ # Start/end positions
+ tokenized["start_positions"] = []
+ tokenized["end_positions"] = []
+
+ for x, offset in enumerate(offsets):
+ # Label NO ANSWER with CLS token
+ inputids = tokenized["input_ids"][x]
+ clstoken = inputids.index(self.tokenizer.cls_token_id)
+
+ # Sequence ids
+ sequences = tokenized.sequence_ids(x)
+
+ # Get and format answer
+ answers = self.answers(data, samples[x])
+
+ # If no answers are given, set the cls_index as answer.
+ if len(answers["answer_start"]) == 0:
+ tokenized["start_positions"].append(clstoken)
+ tokenized["end_positions"].append(clstoken)
+ else:
+ # Start/end character index of the answer in the text.
+ startchar = answers["answer_start"][0]
+ endchar = startchar + len(answers["text"][0])
+
+ # Start token index of the current span in the text.
+ start = 0
+ while sequences[start] != (1 if self.rpad else 0):
+ start += 1
+
+ # End token index of the current span in the text.
+ end = len(inputids) - 1
+ while sequences[end] != (1 if self.rpad else 0):
+ end -= 1
+
+ # Label with CLS token if out of span
+ if not (offset[start][0] <= startchar and offset[end][1] >= endchar):
+ tokenized["start_positions"].append(clstoken)
+ tokenized["end_positions"].append(clstoken)
+ else:
+ # Map start character and end character to matching token index
+ while start < len(offset) and offset[start][0] <= startchar:
+ start += 1
+ tokenized["start_positions"].append(start - 1)
+
+ while offset[end][1] >= endchar:
+ end -= 1
+ tokenized["end_positions"].append(end + 1)
+
+ return tokenized
+
+ def tokenize(self, data):
+ """
+ Tokenizes batch of data
+
+ Args:
+ data: input data batch
+
+ Returns:
+ tokenized data
+ """
+
+ # Trim question whitespace
+ data[self.question] = [x.lstrip() for x in data[self.question]]
+
+ # Tokenize records
+ return self.tokenizer(
+ data[self.question if self.rpad else self.context],
+ data[self.context if self.rpad else self.question],
+ truncation="only_second" if self.rpad else "only_first",
+ max_length=self.maxlength,
+ stride=self.stride,
+ return_overflowing_tokens=True,
+ return_offsets_mapping=True,
+ padding=True,
+ )
+
+ def answers(self, data, index):
+ """
+ Gets and formats an answer.
+
+ Args:
+ data: input examples
+ index: answer index to retrieve
+
+ Returns:
+ answers dict
+ """
+
+ # Answer mappings
+ answers = data[self.answer][index]
+ context = data[self.context][index]
+
+ # Handle mapping string answers to dict
+ if not isinstance(answers, dict):
+ if not answers:
+ answers = {"text": [], "answer_start": []}
+ else:
+ answers = {"text": [answers], "answer_start": [context.index(answers)]}
+
+ return answers
diff --git a/src/python/txtai/data/tokens.py b/src/python/txtai/data/tokens.py
new file mode 100644
index 00000000..f04bc996
--- /dev/null
+++ b/src/python/txtai/data/tokens.py
@@ -0,0 +1,28 @@
+"""
+Tokens module
+"""
+
+import torch
+
+
+class Tokens(torch.utils.data.Dataset):
+ """
+ Default dataset used to hold tokenized data.
+ """
+
+ def __init__(self, columns):
+ self.data = []
+
+ # Map column-oriented data to rows
+ for column in columns:
+ for x, value in enumerate(columns[column]):
+ if len(self.data) <= x:
+ self.data.append({})
+
+ self.data[x][column] = value
+
+ def __len__(self):
+ return len(self.data)
+
+ def __getitem__(self, index):
+ return self.data[index]
diff --git a/src/python/txtai/pipeline/hftrainer.py b/src/python/txtai/pipeline/hftrainer.py
index 3b458dd6..21736b7f 100644
--- a/src/python/txtai/pipeline/hftrainer.py
+++ b/src/python/txtai/pipeline/hftrainer.py
@@ -4,15 +4,14 @@ Hugging Face Transformers trainer wrapper module
import sys
-import torch
-
-from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer
+from transformers import AutoConfig, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer
from transformers import Trainer, set_seed
from transformers import TrainingArguments as HFTrainingArguments
-from .tensors import Tensors
+from ..data import Labels, Questions
from ..models import Models
+from .tensors import Tensors
class HFTrainer(Tensors):
@@ -20,7 +19,7 @@ class HFTrainer(Tensors):
Trains a new Hugging Face Transformer model using the Trainer framework.
"""
- def __call__(self, base, train, validation=None, columns=None, maxlength=None, **args):
+ def __call__(self, base, train, validation=None, columns=None, maxlength=None, stride=128, task="text-classification", **args):
"""
Builds a new model using arguments.
@@ -30,6 +29,8 @@ class HFTrainer(Tensors):
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
+ stride: chunk size for splitting data for QA tasks
+ task: optional model task or category, determines the model type, defaults to "text-classification"
args: training arguments
Returns:
@@ -45,11 +46,21 @@ class HFTrainer(Tensors):
# Load model configuration, tokenizer and max sequence length
config, tokenizer, maxlength = self.load(base, maxlength)
+ # List of labels (only for classification models)
+ labels = None
+
# Prepare datasets
- train, validation, labels = self.datasets(train, validation, columns, tokenizer, maxlength)
+ if task == "question-answering":
+ process = Questions(tokenizer, columns, maxlength, stride)
+ else:
+ process = Labels(tokenizer, columns, maxlength)
+ labels = process.labels(train)
+
+ # Tokenize training and validation data
+ train, validation = process(train, validation)
# Create model to train
- model = self.model(base, config, labels)
+ model = self.model(task, base, config, labels)
# Build trainer
trainer = Trainer(model=model, tokenizer=tokenizer, args=args, train_dataset=train, eval_dataset=validation if validation else None)
@@ -119,99 +130,12 @@ class HFTrainer(Tensors):
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.unique(columns[-1]))
- 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):
+ def model(self, task, base, config, labels):
"""
Loads the base model to train.
Args:
+ task: optional model task or category, determines the model type, defaults to "text-classification"
base: base model - supports a file path or (model, tokenizer) tuple
config: model configuration
labels: number of labels
@@ -220,26 +144,18 @@ class HFTrainer(Tensors):
model
"""
- # Add number of labels to config
- config.update({"num_labels": labels})
+ if labels is not None:
+ # Add number of labels to config
+ config.update({"num_labels": labels})
+ # pylint: disable=E1120
# 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)
+ if isinstance(base, tuple):
+ return base[0]
+ if task == "question-answering":
+ return AutoModelForQuestionAnswering.from_pretrained(base, config=config)
- def __getitem__(self, index):
- return self.data[index]
+ return AutoModelForSequenceClassification.from_pretrained(base, config=config)
class TrainingArguments(HFTrainingArguments):
diff --git a/test/python/testtrainer.py b/test/python/testtrainer.py
index 6fb85507..673ae66f 100644
--- a/test/python/testtrainer.py
+++ b/test/python/testtrainer.py
@@ -10,7 +10,7 @@ import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
-from txtai.pipeline import HFTrainer, Labels
+from txtai.pipeline import HFTrainer, Labels, Questions
class TestTrainer(unittest.TestCase):
@@ -42,6 +42,7 @@ class TestTrainer(unittest.TestCase):
Test training a model with custom parameters
"""
+ # pylint: disable=E1120
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")
@@ -96,12 +97,14 @@ class TestTrainer(unittest.TestCase):
def __getitem__(self, index):
return self.data[index]
- def map(self, fn):
+ # pylint: disable=W0613
+ def map(self, fn, batched):
"""
Map each dataset row using fn.
Args:
fn: function
+ batched: batch records
Returns:
updated Dataset
@@ -118,6 +121,28 @@ class TestTrainer(unittest.TestCase):
labels = Labels((model, tokenizer), dynamic=False)
self.assertEqual(labels("cat")[0][0], 1)
+ def testQA(self):
+ """
+ Tests training a QA model.
+ """
+
+ # Training data
+ data = [
+ {"question": "What ingredient?", "context": "1 can whole tomatoes", "answers": "tomatoes"},
+ {"question": "What ingredient?", "context": "1 yellow onion", "answers": "onion"},
+ {"question": "What ingredient?", "context": "1 red pepper", "answers": "pepper"},
+ {"question": "What ingredient?", "context": "1 clove garlic", "answers": "garlic"},
+ {"question": "What ingredient?", "context": "1/2 lb beef", "answers": "beef"},
+ {"question": "What ingredient?", "context": "a " * 500 + "1/2 lb beef", "answers": "beef"},
+ {"question": "What ingredient?", "context": "Forest through the trees", "answers": None},
+ ]
+
+ trainer = HFTrainer()
+ model, tokenizer = trainer("google/bert_uncased_L-2_H-128_A-2", data, data, task="question-answering", num_train_epochs=10)
+
+ questions = Questions((model, tokenizer), gpu=True)
+ self.assertEqual(questions(["What ingredient?"], ["Peel 1 onion"])[0], "onion")
+
def testRegression(self):
"""
Tests training a model with a regression (continuous) output.