Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Add input merging modes for language modeling training, closes #1021. Closes #1020

davidmezzetti4758907f3bc9
diff --git a/docs/pipeline/train/trainer.md b/docs/pipeline/train/trainer.md
index 78aac820..6aaa6ffe 100644
--- a/docs/pipeline/train/trainer.md
+++ b/docs/pipeline/train/trainer.md
@@ -98,6 +98,20 @@ See the following PEFT documentation links for more information.
- [Quantization](https://huggingface.co/docs/peft/developer_guides/quantization)
- [LoRA](https://huggingface.co/docs/peft/developer_guides/lora)
+## Merge
+
+An important parameter for `language-generation` and `language-modeling` tasks is `merge` or the packing of data into chunks.
+
+It supports the following options.
+
+- `concat` (default) - text is split into chunks up to maxlength, data can be split across multiple chunks
+- `pack` - text is split into chunks up to maxlength, data guaranteed to be in same chunk, chunks can be smaller than maxlength
+- `None` - disables merging
+
+Merging helps reduce training time as data can be processed efficiently without padding. `concat` maximizes this as it guarantees each chunk will be up to maxlength size. `pack` is a middle ground where data is combined but records are preserved.
+
+For general language modeling tasks like masked language modeling, `concat` is the best choice. For instruction/prompt fine-tuning, `pack` or None are the better choices as it guarantees complex logic is not split across chunks.
+
## Methods
Python documentation for the pipeline.
diff --git a/src/python/txtai/data/texts.py b/src/python/txtai/data/texts.py
index 852f219c..4817efae 100644
--- a/src/python/txtai/data/texts.py
+++ b/src/python/txtai/data/texts.py
@@ -12,7 +12,7 @@ class Texts(Data):
Tokenizes text datasets as input for training language models.
"""
- def __init__(self, tokenizer, columns, maxlength):
+ def __init__(self, tokenizer, columns, maxlength, merge):
"""
Creates a new instance for tokenizing Texts training data.
@@ -20,6 +20,7 @@ class Texts(Data):
tokenizer: model tokenizer
columns: tuple of columns to use for text
maxlength: maximum sequence length
+ merge: determines how chunks are combined for language modeling tasks - "concat" (default), "pack" or None
"""
super().__init__(tokenizer, columns, maxlength)
@@ -28,6 +29,9 @@ class Texts(Data):
if not self.columns:
self.columns = ("text", None)
+ # Method to combine chunks
+ self.merge = merge
+
def process(self, data):
# Column keys
text1, text2 = self.columns
@@ -38,12 +42,15 @@ class Texts(Data):
# Tokenize text and add label
inputs = self.tokenizer(*text, return_special_tokens_mask=True)
- # Concat and return tokenized inputs
- return self.concat(inputs)
+ # Combine inputs based on parameters
+ return self.concat(inputs) if self.merge == "concat" else self.pack(inputs) if self.merge == "pack" else inputs
def concat(self, inputs):
"""
- Concatenates tokenized text into chunks of maxlength.
+ Concatenates tokenized text into chunks of maxlength. This method guarantees that each chunk is maxlength
+ size and splits data across multiple chunks if needed.
+
+ This is best with general language modeling tasks like masked language modeling that are streams of text.
Args:
inputs: tokenized input
@@ -66,3 +73,47 @@ class Texts(Data):
result = {k: [v[x : x + self.maxlength] for x in range(0, length, self.maxlength)] for k, v in concat.items()}
return result
+
+ def pack(self, inputs):
+ """
+ Packs tokenized text into chunks up to maxlength. This method guarantees that data is never split across
+ multiple chunks.
+
+ This is best with instruction/prompt learning where it's crucial to ensure entire records are preserved.
+
+ Args:
+ inputs: tokenized input
+
+ Returns:
+ Chunks of tokenized text each with a size of maxlength
+ """
+
+ # Sort lists by length descending
+ inputs = {k: sorted(v, key=len, reverse=True) for k, v in inputs.items()}
+
+ # Inputs has lists of equal length per column
+ columns = list(inputs.keys())
+
+ # Create empty results dict
+ results = {column: [] for column in columns}
+
+ # Iterate over values in first column since all column lengths per row are equal
+ length, index, rows = 0, 0, inputs[columns[0]]
+ for x, row in enumerate(rows):
+ length += len(row)
+ nextlength = len(rows[x + 1]) if x < len(rows) - 1 else 0
+
+ # New row
+ if (length + nextlength) >= self.maxlength:
+ for column in columns:
+ results[column].append(list(chain(*inputs[column][index : x + 1])))
+
+ # Reset length and index
+ length, index = 0, x + 1
+
+ # Last row
+ if length:
+ for column in columns:
+ results[column].append(list(chain(*inputs[column][index : len(rows)])))
+
+ return results
diff --git a/src/python/txtai/pipeline/train/hftrainer.py b/src/python/txtai/pipeline/train/hftrainer.py
index 776a52aa..64a9b1e8 100644
--- a/src/python/txtai/pipeline/train/hftrainer.py
+++ b/src/python/txtai/pipeline/train/hftrainer.py
@@ -57,6 +57,7 @@ class HFTrainer(Tensors):
checkpoint=None,
quantize=None,
lora=None,
+ merge="concat",
**args
):
"""
@@ -76,6 +77,7 @@ class HFTrainer(Tensors):
checkpoint: optional resume from checkpoint flag or path to checkpoint directory, defaults to None
quantize: quantization configuration to pass to base model
lora: lora configuration to pass to PEFT model
+ merge: determines how chunks are combined for language modeling tasks - "concat" (default), "pack" or None
args: training arguments
Returns:
@@ -99,7 +101,7 @@ class HFTrainer(Tensors):
tokenizer.pad_token = tokenizer.pad_token if tokenizer.pad_token is not None else tokenizer.eos_token
# Prepare parameters
- process, collator, labels = self.prepare(task, train, tokenizer, columns, maxlength, stride, prefix, args)
+ process, collator, labels = self.prepare(task, train, tokenizer, columns, maxlength, stride, prefix, merge, args)
# Tokenize training and validation data
train, validation = process(train, validation, os.cpu_count() if tokenizers and isinstance(tokenizers, bool) else tokenizers)
@@ -193,7 +195,7 @@ class HFTrainer(Tensors):
return (config, tokenizer, maxlength)
- def prepare(self, task, train, tokenizer, columns, maxlength, stride, prefix, args):
+ def prepare(self, task, train, tokenizer, columns, maxlength, stride, prefix, merge, args):
"""
Prepares data for model training.
@@ -205,22 +207,26 @@ class HFTrainer(Tensors):
maxlength: maximum sequence length, defaults to tokenizer.model_max_length
stride: chunk size for splitting data for QA tasks
prefix: optional source prefix
+ merge: determines how chunks are combined for language modeling tasks - "concat" (default), "pack" or None
args: training arguments
"""
process, collator, labels = None, None, None
+ # 16-bit training
+ fp16 = args.fp16 or args.bf16
+
if task == "language-generation":
- process = Texts(tokenizer, columns, maxlength)
- collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8 if args.fp16 else None)
+ process = Texts(tokenizer, columns, maxlength, merge)
+ collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8 if fp16 else None)
elif task in ("language-modeling", "token-detection"):
- process = Texts(tokenizer, columns, maxlength)
- collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8 if args.fp16 else None)
+ process = Texts(tokenizer, columns, maxlength, merge)
+ collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8 if fp16 else None)
elif task == "question-answering":
process = Questions(tokenizer, columns, maxlength, stride)
elif task == "sequence-sequence":
process = Sequences(tokenizer, columns, maxlength, prefix)
- collator = DataCollatorForSeq2Seq(tokenizer, pad_to_multiple_of=8 if args.fp16 else None)
+ collator = DataCollatorForSeq2Seq(tokenizer, pad_to_multiple_of=8 if fp16 else None)
else:
process = Labels(tokenizer, columns, maxlength)
labels = process.labels(train)
diff --git a/test/python/testpipeline/testtrain/testtrainer.py b/test/python/testpipeline/testtrain/testtrainer.py
index 1ac7a459..7e204d2e 100644
--- a/test/python/testpipeline/testtrain/testtrainer.py
+++ b/test/python/testpipeline/testtrain/testtrainer.py
@@ -46,9 +46,17 @@ class TestTrainer(unittest.TestCase):
"""
trainer = HFTrainer()
+
+ # Test default parameters
model, _ = trainer("hf-internal-testing/tiny-random-gpt2", self.data, maxlength=16, task="language-generation")
+ self.assertIsNotNone(model)
- # Test model completed successfully
+ # Test pack merging
+ model, _ = trainer("hf-internal-testing/tiny-random-gpt2", self.data, maxlength=16, task="language-generation", merge="pack")
+ self.assertIsNotNone(model)
+
+ # Test no merging
+ model, _ = trainer("hf-internal-testing/tiny-random-gpt2", self.data, maxlength=16, task="language-generation", merge=None)
self.assertIsNotNone(model)
def testCustom(self):