Data Augmentation
local graph
Chapter 3 — Data Augmentation
Section titled “Chapter 3 — Data Augmentation”Data augmentation plays a pivotal role in enhancing the performance and generalization capabilities of LLMs. By artificially expanding the training dataset, we can expose our models to a wider range of linguistic variations and contexts, improving their ability to handle diverse inputs and generate more coherent and contextually appropriate outputs.
In the context of LLMs, data augmentation takes on unique challenges and opportunities. Unlike image data, where simple transformations such as rotation or flipping can create valid new samples, text data requires more nuanced approaches to maintain semantic integrity and linguistic coherence. The main goals of data augmentation for LLMs include increasing dataset size and diversity, addressing data imbalance and bias, improving model robustness to variations in input, and enhancing generalization to unseen data.
In Figure 3*.1*, I illustrate the key aspects of data augmentation.

Figure 3.1 – Key elements of data augmentation
There are three main components, namely Techniques, Considerations, and Evaluation. Each has specific sub-components, which we’ll cover in detail in this chapter.
By the end of this chapter, you’ll have learned about the data augmentation pattern in depth, from increasing the diversity of your training dataset to maintaining its integrity:
- Text data augmentation techniques
- Leveraging existing LLMs for data generation
- Multilingual data augmentation strategies
- Semantic preservation in text augmentation
- Balancing augmentation and data quality
- Evaluating the impact of data augmentation
Text data augmentation techniques
Section titled “Text data augmentation techniques”Text data augmentation encompasses a wide range of techniques, from simple word-level manipulations to more complex semantic transformations.
Synonym replacement
Section titled “Synonym replacement”This technique involves replacing words in the original text with their synonyms. We can use WordNet, a lexical database for the English language, to find synonyms:
def synonym_replacement(text, n=1): words = text.split() new_words = words.copy() random_word_list = list( set([word for word in words if word.isalnum()]) ) random.shuffle(random_word_list) num_replaced = 0 for random_word in random_word_list: synonyms = get_synonyms(random_word) if len(synonyms) >= 1: synonym = random.choice(list(synonyms)) new_words = [ synonym if word == random_word else word for word in new_words ] num_replaced += 1 if num_replaced >= n: break return ' '.join(new_words)The synonym_replacement function takes a text input and replaces a specified number (the default is 1) of words with their synonyms. The default value of 1 is chosen to minimize text alteration, preserving meaning and readability while allowing easy experimentation. You can increase this number if you want more replacements.
The function splits the text into words, creates a list of unique alphanumeric words, shuffles this list, and then iterates through it. For each word, it attempts to find synonyms using an undefined get_synonyms function. If synonyms are found, it randomly selects one and replaces all occurrences of the original word in the text. The function keeps track of how many words have been replaced and stops when it reaches the specified number. Finally, it rejoins the modified words into a single string and returns it.
Back-translation
Section titled “Back-translation”This method involves translating the text to another language and then back to the original language. It’s particularly effective for introducing natural variations in sentence structure and word choice:
def back_translation(text, target_lang='fr'): translator = Translator() translated = translator.translate(text, dest=target_lang) back_translated = translator.translate(translated.text, dest='en') return back_translated.textText generation with T5
Section titled “Text generation with T5”The Text-To-Text Transfer Transformer (T5) model, developed by Google Research, is a versatile natural language processing (NLP) model based on the transformer architecture. Its key innovation is framing all NLP tasks as text-to-text problems, allowing it to handle multiple tasks without task-specific architectures. Pre-trained on a large web text corpus using a “span corruption” objective, T5 is available in various sizes and has demonstrated powerful performance across a wide range of NLP tasks.
T5 handles a wide range of text-based tasks by framing them all as text-to-text problems. This means that irrespective of the task, whether it’s summarization, translation, question answering, or classification, both the input and output are treated as text. This unified approach allows T5 to perform various tasks without needing task-specific modifications, making it highly adaptable for different use cases.
When it comes to data augmentation, T5 plays a key role by generating variations of existing text data, which is essential for expanding and diversifying datasets. Data augmentation is especially valuable when training machine learning models, as it helps them generalize better by exposing them to a wider variety of examples, reducing overfitting and improving robustness. Here’s how T5 aids in data augmentation:
- Paraphrasing: T5 can rephrase sentences while maintaining their original meaning. For example, if the input is “The movie was boring,” T5 could generate a paraphrased version such as “The film was dull.” This variety in expression provides additional examples for a model to learn from, helping it generalize better to different ways of phrasing the same idea.
- Synonym replacement: T5 can replace words with their synonyms, creating slight variations in meaning while retaining the overall sentiment or context. For instance, from “The movie was long and tedious,” T5 might generate “The film was lengthy and boring.” This simple modification increases the diversity of the dataset, offering more training examples for models that rely on understanding slight variations in language.
- Sentiment-based transformation: T5 can also transform the sentiment of a sentence. For example, given a negative sentence such as “The movie was very disappointing,” T5 can generate a neutral or positive version, such as “The movie had a slow start but improved later.” This capability allows for the creation of multiple examples across different sentiment categories, which is particularly useful in tasks such as sentiment analysis, where a model needs to distinguish between positive, neutral, and negative sentiments.
- Text expansion: T5 can take a short sentence and expand it by adding more context, details, or descriptions. For instance, from the sentence “The event was great,” T5 could generate a more detailed version such as “The event was great, with excellent speakers and engaging discussions.” By adding more context, T5 provides additional variations of the sentence that help in training models to handle more complex inputs.
We can use a pre-trained T5 model to generate variations of input text. This method is particularly powerful as it can produce more diverse and contextually rich augmentations. Let’s see this:
def t5_augmentation(text, model, tokenizer, num_return_sequences=1): input_ids = tokenizer.encode( f"paraphrase: {text}", return_tensors="pt", max_length=512, truncation=True ) outputs = model.generate( input_ids=input_ids, max_length=150, num_return_sequences=num_return_sequences, num_beams=5, no_repeat_ngram_size=2, top_k=50, top_p=0.95, ) return [ tokenizer.decode( output, skip_special_tokens=True ) for output in outputs ]This function takes a text input, a pre-trained T5 model, its tokenizer, and the number of paraphrases to generate (the default is 1). The default of 1 return sequence is chosen for simplicity, but you can request multiple paraphrases by increasing this value.
The function encodes the input text with a "paraphrase:" prefix, limiting it to 512 tokens. It then uses the model to generate paraphrases with a maximum length of 150 tokens. The generation process uses beam search with 5 beams, prevents repetition of 2-grams, and applies top-k (50) and top-p (0.95) sampling for diversity. The numerical parameters (512, 150, 5, 2, 50, 0.95) can also be adjusted based on specific use cases to control the length, diversity, and quality of the generated paraphrases.
The function decodes and returns the generated paraphrases, skipping any special tokens added during the process.
Using temperature control as an additional parameter in language generation systems allows fine-tuning the balance between creativity and coherence. Temperature is a scalar value, typically ranging from 0 to 1, that influences the probability distribution over the next token during generation. Low values (close to 0) concentrate the distribution, making the model more deterministic and coherent but potentially repetitive or conservative. High values (close to 1) flatten the distribution, increasing randomness and diversity at the cost of coherence.
Leveraging existing LLMs for data generation
Section titled “Leveraging existing LLMs for data generation”One of the most powerful approaches to data augmentation for LLMs is to use existing models to generate new training examples. This technique, often referred to as self-supervised learning or model-based data augmentation, allows us to create vast amounts of diverse, high-quality training data.
We’ll explore how to use GPT-4o and the OpenAI API for data generation:
def gpt4o_data_generation(prompt, num_samples=5): response = openai.ChatCompletion.create( model="gpt-4o", messages=[{"role": "user", "content": prompt}], max_tokens=150, n=num_samples, temperature=0.7, ) return [choice.message.content.strip() for choice in response.choices ]This function sends a single user message containing the provided prompt for a chat completion request. It limits the response to a maximum of 150 tokens, which balances between getting a substantive response and controlling the output length. The n parameter, set to num_samples, determines the number of alternative completions to generate. A temperature of 0.7 is used, which provides a balance between creativity and coherence in the generated text: high values increase randomness, while low values would make the output more deterministic. The function then extracts and returns the content of each generated completion, stripping any leading or trailing whitespace. These parameters (150 tokens, 0.7 temperature) can be adjusted based on specific needs for output length and creativity.
When using this approach, we need to consider the following:
- Prompt engineering: Crafting effective prompts is needed for generating relevant and diverse samples.
- Quality control: Implement filtering mechanisms to ensure the generated data meets your quality standards.
- Diversity: Use temperature and top-p sampling to control the randomness and diversity of generated samples.
We’ve explored data augmentation techniques using GPT-4o and examined essential considerations. Now, let’s turn our attention to strategies for multilingual data augmentation.
Multilingual data augmentation strategies
Section titled “Multilingual data augmentation strategies”For LLMs designed to handle multiple languages, multilingual data augmentation is essential. We can adapt our previous techniques to work across languages.
Cross-lingual back-translation
Section titled “Cross-lingual back-translation”Translate the text into multiple languages before translating it back to the original language:
def cross_lingual_back_translation(text, target_langs=['fr', 'de', 'es']): translator = Translator() augmented_texts = [] for lang in target_langs: translated = translator.translate(text, dest=lang) back_translated = translator.translate( translated.text, dest='en' ) augmented_texts.append(back_translated.text) return augmented_textsThe cross_lingual_back_translation function takes a text input and generates augmented versions of it by first translating it into multiple target languages (defaulting to French, German, and Spanish) and then back to English. The function uses the Translator object to perform these translations, storing each back-translated version in a list, which is returned as the output.
Multilingual T5 augmentation
Section titled “Multilingual T5 augmentation”You can use a multilingual T5 model to generate paraphrases in different languages:
def multilingual_t5_augmentation( text, model, tokenizer, target_langs=['fr', 'de', 'es']): augmented_texts = [] for lang in target_langs: input_ids = tokenizer.encode( f"translate English to {lang}: {text}", return_tensors="pt", max_length=512, truncation=True ) outputs = model.generate(input_ids=input_ids, max_length=150) translated = tokenizer.decode(outputs[0], skip_special_tokens=True) augmented_texts.append(translated) return augmented_textsThe multilingual_t5_augmentation function uses a T5 model to augment a given text by translating it into multiple target languages (defaulting to French, German, and Spanish). For each target language, it encodes the text with a prompt for translation, generates the translated output using the model, and decodes the result. The translated texts are collected in a list and returned as the augmented versions of the original text.
Semantic preservation in text augmentation
Section titled “Semantic preservation in text augmentation”Maintaining semantic integrity is crucial when augmenting data for LLMs. We must ensure that our techniques don’t alter the original meaning of the text.
Use of sentence embeddings
Section titled “Use of sentence embeddings”By comparing the sentence embeddings of the original and augmented texts, you can ensure semantic similarity:
def semantic_similarity(original, augmented, model): original_embedding = model.encode(original) augmented_embedding = model.encode(augmented) similarity = cosine_similarity( [original_embedding], [augmented_embedding] )[0][0] return similaritydef filter_by_semantic_similarity( original, augmented_list, model, threshold=0.8): return [ aug for aug in augmented_list if semantic_similarity(original, aug, model) >= threshold ]We define two functions for measuring and filtering text based on semantic similarity:
semantic_similarity(original, augmented, model)calculates the semantic similarity between two texts using the cosine similarity of their embeddings. It uses a provided model (probably a sentence embedding model) to encode the original and augmented texts into vector representations. The cosine similarity between these vectors is then computed, resulting in a value between -1 and 1, where 1 indicates perfect similarity.filter_by_semantic_similarity(original, augmented_list, model, threshold=0.8)filters a list of augmented texts based on their semantic similarity to the original. Thesemantic_similarityfunction compares each augmented text with the original. The default threshold is set to0.8: by default, it will keep only the augmented texts that have a similarity of0.8or higher to the original. This threshold is commonly used in NLP tasks, as it typically indicates a strong semantic similarity while allowing some variation. It can be adjusted based on how strict or lenient you want the filtering to be: a higher threshold will result in more similar (but possibly fewer) augmentations; a lower threshold will allow more diverse (but potentially less relevant) augmentations.
Contextual word embeddings for synonym replacement
Section titled “Contextual word embeddings for synonym replacement”You can use contextual word embeddings to find more appropriate synonyms based on the context. Contextual word embeddings refer to the use of word representations generated by language models that capture the meaning of a word within its specific sentence or passage, rather than treating the word as having a fixed meaning. Unlike traditional static embeddings where a word has the same vector regardless of context, contextual embeddings assign different vectors to the same word depending on its surrounding words. This allows for more accurate synonym replacement as the chosen synonym aligns not only with the dictionary meaning but also with how the word is used in a particular context. For example, the word “bank” in “river bank” versus “savings bank” would be represented differently, leading to contextually appropriate synonym suggestions such as “shore” or “financial institution,” respectively. The following code snippet shows how it works:
def contextual_synonym_replacement(text, model, tokenizer, n=1): words = text.split() new_words = words.copy() for i in range(n): word_index = random.randint(0, len(words) - 1) original_word = words[word_index] inputs = tokenizer(text, return_tensors="pt") with torch.no_grad(): outputs = model(inputs) word_embedding = outputs.last_hidden_state[0, word_index] similar_words = find_similar_words( word_embedding, model, tokenizer ) if similar_words: new_words[word_index] = random.choice(similar_words) return ' '.join(new_words)This function performs context-aware word replacement using a language model:
- It takes a text input, a pre-trained language model, its tokenizer, and the number of words to replace (the default is 1).
- The text is split into words, and a copy is made for modification.
- The function iterates
ntimes (the default is 1). It does the following each time:- Randomly selects a word index
2. Tokenizes the entire text
3. Runs it through the model to get contextualized embeddings
4. Extracts the embedding of the chosen word
5. Finds similar words based on this embedding (using an undefined
find_similar_wordsfunction) 6. If similar words are found, it randomly chooses one to replace the original
- Randomly selects a word index
2. Tokenizes the entire text
3. Runs it through the model to get contextualized embeddings
4. Extracts the embedding of the chosen word
5. Finds similar words based on this embedding (using an undefined
- Finally, it joins the modified words back into a string and returns it.
The default n =1 is chosen to make minimal changes while still introducing variation. This preserves most of the original meaning and structure. You can increase n to get more replacements, but higher values might alter the text’s meaning more significantly.
This method is more context-aware than simple synonym replacement as it considers the word’s usage in the full text when finding replacements. The exact behavior will depend on the model and tokenizer used, as well as the implementation of the find_similar_words function.
Balancing augmentation and data quality
Section titled “Balancing augmentation and data quality”While data augmentation can significantly improve LLM performance, we need to strike a balance between quantity and quality.
You should limit the proportion of augmented data in your training set. A common practice is to start with a 1:1 ratio of original to augmented data and adjust based on model performance.
Quality filtering
Section titled “Quality filtering”You can implement quality checks to filter out low-quality augmented samples:
def quality_filter( augmented_texts, original_text, similarity_threshold=0.8, perplexity_threshold=100): filtered_texts = [] for aug_text in augmented_texts: if ( semantic_similarity( original_text, aug_text, similarity_model ) >= similarity_threshold and calculate_perplexity( aug_text, perplexity_model ) <= perplexity_threshold ): filtered_texts.append(aug_text) return filtered_textsHuman-in-the-loop validation
Section titled “Human-in-the-loop validation”For critical applications, incorporate human validation into your augmentation pipeline.
Human-in-the-loop (HITL) validation is a control mechanism used in AI pipelines where humans are deliberately inserted into automated workflows to ensure correctness, especially in tasks involving subjective judgment, sensitive content, or critical decision-making. This is particularly important in applications where data quality directly affects safety, fairness, or compliance—for example, healthcare diagnostics, legal document analysis, or autonomous systems. In the context of data augmentation, where the goal is to expand the training dataset by generating variations of existing samples, HITL is used to validate whether the generated samples are coherent, accurate, and aligned with the intended label or task:
def human_validation(augmented_texts): validated_texts = [] for text in augmented_texts: if input( f"Is this text valid? (y/n)\n{text}\n" ).lower() == 'y': validated_texts.append(text) return validated_textsThis function is designed to manually validate a list of augmented text samples by soliciting binary feedback—yes or no—from a human operator. Its presence within an augmentation pipeline acknowledges that not all automatically generated data can be trusted at face value. The decision to retain or discard a given sample is made interactively, reinforcing human oversight in tasks where semantic integrity is non-negotiable.
Each iteration of the function’s loop represents a decision point. The human validator is shown the generated text and asked to assess whether it meets the expected criteria. These criteria are typically based on task-specific requirements such as grammaticality, semantic equivalence to the original data, tone appropriateness, or domain alignment. For example, in a medical text classification task, a paraphrased sentence must preserve all critical clinical entities. A slight shift in terminology introduced by an augmentation technique could mislead the model if not caught during validation. This is where human evaluation becomes indispensable.
The logic behind converting the input to lowercase is to handle inconsistent user input. Whether the user types Y, y, or any other casing, the comparison becomes case-agnostic. Only if the input is equivalent to y does the function accept the sample. This binary check is deliberately strict to prevent ambiguous approvals. The rejected samples are silently discarded and not logged or returned, implying that any further inspection or correction of rejected samples would need to be implemented separately.
The function concludes by returning a list of only those samples that have been explicitly validated. This output can then be used to expand the training dataset with higher confidence in the integrity of the new data points. Importantly, this approach does not replace automated quality checks but supplements them in high-stakes applications. HITL validation is particularly useful when deploying models in environments where false positives or negatives carry high costs, such as legal recommendation systems, fraud detection, or autonomous navigation. The manual validation process helps to mitigate risks that stem from over-reliance on generative augmentation methods that lack explicit semantic guarantees.
In a larger system, this kind of function would usually be embedded in a broader workflow where automated filters screen out obviously low-quality or irrelevant augmentations first. The human validator would only evaluate the borderline or high-impact cases. For operational efficiency, the interaction would typically be handled via a web interface or integrated annotation tool rather than a command-line prompt. However, the function demonstrates the principle in its simplest form: human judgment is used as the final arbiter of quality before incorporating augmented data into model training.
Evaluating the impact of data augmentation
Section titled “Evaluating the impact of data augmentation”To assess the effectiveness of our data augmentation techniques, we need to assess their impact on LLM performance.
Perplexity
Section titled “Perplexity”You can measure a model’s perplexity (see Chapter 2) on a held-out test set before and after data augmentation to assess whether it has improved the model’s ability to predict unseen text:
def evaluate_perplexity(model, tokenizer, test_data): model.eval() total_loss = 0 total_tokens = 0 with torch.no_grad(): for text in test_data: inputs = tokenizer( text, return_tensors="pt" ).to(model.device) outputs = model(inputs, labels=inputs["input_ids"]) total_loss += ( outputs.loss.item() * inputs["input_ids"].size(1) ) total_tokens += inputs["input_ids"].size(1) perplexity = math.exp(total_loss / total_tokens) return perplexityThis function, evaluate_perplexity, calculates the perplexity of a language model on a given test dataset. Here’s a breakdown:
- It takes a pre-trained language model, its tokenizer, and a test dataset as input.
- The model is set to evaluation mode to disable dropout and other training-specific behavior.
- It initializes variables to track the total loss and total number of tokens processed.
- For each text in the test data, the following is carried out:
- The text is tokenized and converted to tensors. 2. The model processes the input, calculating the loss. 3. The loss is accumulated, weighted by the number of tokens in the input.
- After processing all texts, it calculates the perplexity using the following formula:
exp(total_loss /total_tokens).
This implementation uses the model in a zero-shot manner, treating each input as both the context and the target to predict. The use of torch.no_grad() ensures that no gradients are computed, making the evaluation more efficient.
This function assumes the model and data are compatible (i.e., the model can handle the maximum sequence length of the data). In practice, you might need to add checks or truncation to handle very long sequences.
Task-specific metrics
Section titled “Task-specific metrics”You can evaluate the model on downstream tasks relevant to your use case, such as text classification or question answering:
def evaluate_classification( model, tokenizer, test_data, test_labels): model.eval() predictions = [] with torch.no_grad(): for text in test_data: inputs = tokenizer( text, return_tensors="pt" ).to(model.device) outputs = model(inputs) predictions.append(torch.argmax(outputs.logits).item()) accuracy = accuracy_score(test_labels, predictions) f1 = f1_score(test_labels, predictions, average='weighted') return accuracy, f1This function assesses the performance of a classification model on a test dataset:
- It takes a pre-trained classification model, its tokenizer, test data (text), and corresponding test labels as inputs.
- The model is set to evaluation mode to disable dropout and other training-specific behavior.
- It processes each text in the test data, tokenizing it and using the model to make predictions.
- After processing all texts, it calculates two evaluation metrics:
- Accuracy: The proportion of correct predictions out of all predictions made.
- F1 score: A balanced measure of the model’s precision and recall. The F1 score is the harmonic mean of precision (the ratio of true positive predictions to all positive predictions) and recall (the ratio of true positive predictions to all actual positive instances). The F1 score formula is F1 = 2 * (precision * recall) / (precision + recall). The F1 score ranges from 0 to 1, where 1 indicates perfect precision and recall. It’s particularly useful for imbalanced datasets where accuracy alone might be misleading. The weighted average calculates F1 for each class and averages them, weighted by the number of instances in each class.
- Accuracy: The proportion of correct predictions out of all predictions made.
- The function returns both the accuracy and F1 score, providing a more comprehensive evaluation of the model’s performance across potentially imbalanced classes.
This implementation also uses torch.no_grad() for efficiency and assumes that the necessary scikit-learn metrics are imported. In practice, you might want to add error handling for unexpected model outputs or mismatched prediction/label counts.
Diversity metrics
Section titled “Diversity metrics”It’s important to assess the diversity of your augmented dataset:
def calculate_diversity_metrics(texts): all_words = [word for text in texts for word in text.split()] vocab_size = len(set(all_words)) all_trigrams = [text[i:i+3] for text in texts for i in range(len(text)-2)] unique_trigrams = len(set(all_trigrams)) return { "vocabulary_size": vocab_size, "unique_trigrams": unique_trigrams }This function takes a collection of texts as input and computes diversity metrics. Once this has been done, this function returns a dictionary with these two metrics:
- Vocabulary size (ranging from 1 to the total number of words): This gives an idea of lexical diversity. A high number suggests diverse word usage across the texts. This metric splits each text into words, combines all words from all texts, and then counts the number of unique words using a set. In this context, a set refers to a data structure that automatically removes duplicate elements.
- Unique trigrams (ranging from 1 to the total number of trigrams): These indicate character-level diversity. A high number suggests varied character sequences, potentially indicating diverse sentence structures or word choices. This metric creates trigrams (sequences of three characters) from each text and counts the number of unique trigrams using a set that only contains unique elements.
These metrics are useful for comparing the diversity of original texts versus augmented texts or for assessing the variety in a dataset. However, the results should be interpreted in context, as high diversity might indicate incoherence or noise in the data.
By systematically applying these techniques, we can quantify the impact of our data augmentation strategies on LLM performance and make informed decisions about which techniques to use and how to fine-tune our augmentation pipeline.
Summary
Section titled “Summary”In this chapter, we explored advanced data augmentation techniques for LLMs, covering text manipulation methods, leveraging existing models for data generation, multilingual strategies, semantic preservation, quality control, and several metrics. We also discussed the importance of balancing augmentation with data quality and provided practical Python implementations for various techniques.
In the next chapter, we’ll focus on handling large datasets for LLM training.
Get This Book's PDF Version and Exclusive Extras
|