Skip to content
ImagineWorld

Cross-Validation

node_idnode-book_llm-design-patterns_chapter-14-cross-validation
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleCross-Validation
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Cross-validation is a statistical technique used to assess how well a machine learning model generalizes to unseen data. It involves partitioning a dataset into multiple subsets or “folds,” training the model on some of these subsets while testing it on the remaining ones. This process is repeated to ensure a reliable performance estimate. This helps detect overfitting and provides a more robust evaluation than a single train-test split. In the context of LLMs, cross-validation must be adapted to address the complexities of pre-training, fine-tuning, few-shot learning, and domain generalization, making it an essential tool for evaluating model performance across varied tasks and data distributions.

In this chapter, you will explore cross-validation strategies specifically designed for LLMs. We’ll delve into methods for creating appropriate data splits for pre-training and fine-tuning, as well as strategies for few-shot and zero-shot evaluation. You’ll learn how to assess domain and task generalization in LLMs and handle the unique challenges of cross-validation in the context of LLMs.

By the end of this chapter, you’ll be equipped with robust cross-validation techniques to reliably assess your LLM’s performance and generalization capabilities across various domains and tasks.

In this chapter, we’ll be covering the following topics:

  • Pre-training and fine-tuning data splits
  • Few-shot and zero-shot evaluation strategies
  • Domain and task generalization
  • Continual learning evaluation
  • Cross-validation challenges and best practices

In LLMs, data splits refer to the division of datasets into training, validation, and test sets to ensure the model learns generalizable patterns rather than memorizing data. This is essential for evaluating performance fairly, tuning model parameters, and preventing data leakage. Proper splitting is especially important in LLMs due to their scale, the diversity of tasks, and the need to assess domain and task generalization.

Stratified sampling is a sampling method that first divides the population into smaller subgroups (strata) based on shared characteristics and then randomly samples from within each stratum to ensure proportional representation of all groups in the final sample. This is particularly useful when dealing with imbalanced datasets.

When creating data splits for pre-training, it’s important to ensure that each split represents the diversity of the entire dataset. Here’s an example of how you might implement stratified sampling for pre-training data:

import pandas as pd
from sklearn.model_selection import StratifiedShuffleSplit
def stratified_pretraining_split(
data, text_column, label_column, test_size=0.1, random_state=42
):
sss = StratifiedShuffleSplit(
n_splits=1, test_size=test_size, random_state=random_state)
for train_index, test_index in sss.split(
data[text_column], data[label_column]
):
train_data = data.iloc[train_index]
test_data = data.iloc[test_index]
return train_data, test_data
# Example usage
data = pd.read_csv('your_pretraining_data.csv')
train_data, test_data = stratified_pretraining_split(
data, 'text', 'domain')
print(f"Training set size: {len(train_data)}")
print(f"Test set size: {len(test_data)}")

This code uses StratifiedShuffleSplit to create a stratified split of the pre-training data, ensuring that the distribution of domains (or any other relevant categorical variable) is similar in both the training and test sets.

For fine-tuning tasks that involve time-sensitive data, it’s often beneficial to use time-based splitting.

Time-based splitting is a data partitioning strategy where the dataset is divided according to chronological order, ensuring that earlier data is used for training and later data for validation or testing. This approach is especially important for fine-tuning tasks involving time-sensitive data—such as financial forecasting, user behavior modeling, or event prediction—where future information should not influence past training. By preserving the natural temporal sequence, time-based splitting helps evaluate how well a model can generalize to future, unseen scenarios, closely mimicking real-world deployment.

This approach helps evaluate how well the model generalizes to future data:

import pandas as pd
def time_based_finetuning_split(data, timestamp_column, split_date):
data[timestamp_column] = pd.to_datetime(data[timestamp_column])
train_data = data[data[timestamp_column] < split_date]
test_data = data[data[timestamp_column] >= split_date]
return train_data, test_data
# Example usage
data = pd.read_csv('your_finetuning_data.csv')
split_date = '2023-01-01'
train_data, test_data = time_based_finetuning_split(
data, 'timestamp', split_date)
print(f"Training set size: {len(train_data)}")
print(f"Test set size: {len(test_data)}")

This function splits the data based on a specified date, which is particularly useful for tasks where the model needs to generalize to future events or trends.

Oversampling and weighting techniques for data balancing

Section titled “Oversampling and weighting techniques for data balancing”

When working with datasets that have an uneven distribution of categories, such as imbalanced domains or label frequencies, oversampling and weighting techniques can help ensure that the model learns effectively from all classes. Oversampling involves replicating examples from underrepresented categories to increase their presence in the training data, preventing the model from ignoring them. This can be done using methods such as random oversampling or synthetic data generation (e.g., SMOTE for structured data). On the other hand, weighting techniques adjust the loss function by assigning higher importance to underrepresented categories, so the model learns from them without necessarily increasing the dataset size. Both approaches help mitigate bias, improving the model’s ability to generalize across all categories, rather than favoring the most frequent ones.

Here’s a short code example demonstrating oversampling and class weighting techniques using PyTorch and sklearn, applied to a text classification task:

from sklearn.utils.class_weight import compute_class_weight
from torch.utils.data import DataLoader, WeightedRandomSampler
import torch
import numpy as np
# Example class distribution (e.g., from dataset labels)
labels = [0, 0, 0, 1, 1, 2] # Class 2 is underrepresented
# --- 1. Class Weighting ---
# Compute weights inversely proportional to class frequencies
class_weights = compute_class_weight(
'balanced', classes=np.unique(labels), y=labels)
class_weights = torch.tensor(class_weights, dtype=torch.float)
# Pass weights to loss function
loss_fn = torch.nn.CrossEntropyLoss(weight=class_weights)
# --- 2. Oversampling with Weighted Sampler ---
# Create sample weights: inverse of class frequency for each label
label_counts = np.bincount(labels)
sample_weights = [1.0 / label_counts[label] for label in labels]
# Create sampler for DataLoader
sampler = WeightedRandomSampler(
weights=sample_weights, num_samples=len(labels), replacement=True
)
# Use the sampler in your DataLoader
# Assuming \`train_dataset\` is a PyTorch Dataset object
train_loader = DataLoader(train_dataset, sampler=sampler,
batch_size=4)

The code demonstrates two common techniques for addressing class imbalance in classification tasks: class weighting and oversampling. First, it uses compute_class_weight of sklearn to calculate weights inversely proportional to class frequencies, assigning higher importance to underrepresented classes (e.g., class 2, which appears less often). These weights are passed to PyTorch’s CrossEntropyLoss, so that during training, misclassifying rare classes penalizes the model more than misclassifying common ones. Second, it performs oversampling by computing a per-sample weight based on the inverse frequency of each sample’s class, which ensures that samples from minority classes have a higher probability of being selected during training. These sample weights are used to initialize PyTorch’s WeightedRandomSampler, which enables the DataLoader to sample training data in a balanced way across classes without having to physically duplicate data. Together, these techniques help the model learn to treat all classes fairly, improving its generalization on imbalanced datasets.

Few-shot and zero-shot evaluation strategies

Section titled “Few-shot and zero-shot evaluation strategies”

Few-shot and zero-shot evaluation strategies enable LLMs to generalize across tasks without requiring extensive retraining. Zero-shot learning is useful for tasks where no labeled examples are available, while few-shot learning enhances performance by providing limited guidance. These methods are key to making LLMs adaptable and scalable for real-world applications.

Here is a comparison between the two strategies:

AspectZero-shotFew-shot
DescriptionNo examples; model must infer task from prompt aloneProvides a small number of labeled examples in the prompt
StrengthsNo labeled data needed, highly flexibleHigher accuracy, better task comprehension
WeaknessesLower accuracy, risk of ambiguityRequires careful example selection, still less effective than fine-tuning
Use CasesOpen-ended Q&A, commonsense reasoning, general-knowledge tasksText classification, translation, summarization, code generation

Table 15.1 – Few-shot vs. zero-shot

Let’s see how to implement each of these strategies.

In few-shot evaluation, we provide the model with a small number of examples before asking it to perform a task. Here’s an example of how you might implement few-shot evaluation:

from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch
def few_shot_evaluate(
model, tokenizer, task_description, examples, test_instance
):
prompt = f"{task_description}\n\nExamples:\n"
for example in examples:
prompt += (
f"Input: {example['input']}\n"
f"Output: {example['output']}\n\n"
)
prompt += f"Input: {test_instance}\nOutput:"
input_ids = tokenizer.encode(prompt, return_tensors='pt')
with torch.no_grad():
output = model.generate(input_ids, max_length=100,
num_return_sequences=1)
generated_text = tokenizer.decode(output[0],
skip_special_tokens=True)
return generated_text.split("Output:")[-1].strip()
# Example usage
model = GPT2LMHeadModel.from_pretrained('gpt2-large')
tokenizer = GPT2Tokenizer.from_pretrained('gpt2-large')
task_description = "Classify the sentiment of the following movie reviews as positive or negative."
examples = [
{"input": "This movie was fantastic!", "output": "Positive"},
{"input": "I hated every minute of it.", "output": "Negative"}
]
test_instance = "The acting was superb, but the plot was confusing."
result = few_shot_evaluate(
model, tokenizer, task_description, examples, test_instance
)
print(f"Few-shot evaluation result: {result}")

This code demonstrates how to perform few-shot evaluation on a sentiment analysis task using a pre-trained GPT-2 model.

The few_shot_evaluate function takes a GPT-2 model, tokenizer, task description, examples, and a test instance as input. It constructs a few-shot prompt by formatting the task description and adding multiple input-output example pairs to help the model understand the task. The function then appends the test instance, leaving the output blank so the model can complete it. The prompt is tokenized using tokenizer.encode, converting it into numerical tokens suitable for the model. The function then uses model.generate inside a torch.no_grad() block to generate text without computing gradients, making inference more efficient. The model generates a response with a maximum length of 100 tokens, ensuring it stays concise. The generated text is then decoded using tokenizer.decode, with skip_special_tokens=True to remove unwanted tokens. Finally, the function extracts the part of the response after the last occurrence of "Output:" to isolate the model’s generated answer, trimming any extra whitespace. This approach effectively enables few-shot learning, where the model leverages provided examples to make a more informed prediction.

Zero-shot evaluation tests a model’s ability to perform a task without any specific examples. Here’s how you might implement zero-shot evaluation:

def zero_shot_evaluate(
model, tokenizer, task_description, test_instance
):
prompt = f"{task_description}\n\nInput: {test_instance}\nOutput:"
input_ids = tokenizer.encode(prompt, return_tensors='pt')
with torch.no_grad():
output = model.generate(
input_ids, max_length=100, num_return_sequences=1
)
generated_text = tokenizer.decode(output[0],
skip_special_tokens=True)
return generated_text.split("Output:")[-1].strip()
# Example usage
task_description = "Classify the following text into one of these categories: Science, Politics, Sports, Entertainment."
test_instance = "NASA's Mars rover has discovered traces of ancient microbial life."
result = zero_shot_evaluate(
model, tokenizer, task_description, test_instance
)
print(f"Zero-shot evaluation result: {result}")

This function demonstrates zero-shot evaluation on a text classification task.

The zero_shot_evaluate function performs zero-shot inference using a pre-trained language model by constructing a prompt that describes the task and presents an input without any labeled examples. It first formats the prompt by combining task_description with test_instance, ensuring that the model understands the task and what it needs to classify. The phrase "Output:" is appended to signal where the model should generate its response. The prompt is then tokenized using tokenizer.encode, converting it into numerical input tensors that the model can process. The function uses torch.no_grad() to disable gradient computation, making inference more efficient. The model.generate function takes the tokenized prompt and generates an output sequence with a maximum length of 100 tokens while returning only one sequence. The generated output is then decoded back into text using tokenizer.decode, ensuring that any special tokens are removed. Finally, the function extracts and returns the portion of the generated text that appears after "Output:", which represents the model’s predicted classification. In the example usage, the function is applied to a classification task where the model is asked to categorize a given text snippet —"NASA's Mars rover has discovered traces of ancient microbial life." —into one of the predefined categories: Science, Politics, Sports, or Entertainment. The model, without seeing any labeled examples, infers the correct category based on its prior knowledge. The output is then printed, demonstrating the model’s zero-shot classification ability.

Assessing how well an LLM generalizes across different domains and tasks is crucial for understanding its true capabilities. Let’s explore some techniques for this purpose.

To evaluate domain adaptation, we can test the model on data from a different domain than it was trained on. Here’s an example:

def evaluate_domain_adaptation(
model, tokenizer, source_domain_data, target_domain_data
):
def predict(text):
inputs = tokenizer(
text, return_tensors='pt', truncation=True, padding=True
)
outputs = model(inputs)
return torch.argmax(outputs.logits, dim=1).item()
# Evaluate on source domain
source_predictions = [
predict(text) for text in source_domain_data['text']
]
source_accuracy = accuracy_score(
source_domain_data['label'], source_predictions
)
# Evaluate on target domain
target_predictions = [
predict(text) for text in target_domain_data['text']
]
target_accuracy = accuracy_score(
target_domain_data['label'], target_predictions
)
return {
'source_accuracy': source_accuracy,
'target_accuracy': target_accuracy,
'adaptation_drop': source_accuracy - target_accuracy
}

The following is how we evaluate domain adaptation and print out the result:

source_domain_data = load_source_domain_data() # Replace with actual data loading
target_domain_data = load_target_domain_data() # Replace with actual data loading
results = evaluate_domain_adaptation(
model, tokenizer, source_domain_data, target_domain_data
)
print(f"Source domain accuracy: {results['source_accuracy']:.2f}")
print(f"Target domain accuracy: {results['target_accuracy']:.2f}")
print(f"Adaptation drop: {results['adaptation_drop']:.2f}")

Putting it together, we can use the preceding code to evaluate the model’s performance on both the source domain (what it was trained on) and the target domain, calculating the drop in performance as a measure of domain adaptation.

To assess task generalization, we can evaluate the model on a variety of tasks it wasn’t specifically fine-tuned for. Here’s an example using the GLUE benchmark (which we discussed in Chapter 14):

def evaluate_task_generalization(
model_name, tasks=['mnli', 'qqp', 'qnli', 'sst2']
):
results = {}
for task in tasks:
model = \
AutoModelForSequenceClassification.from_pretrained(
model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
dataset = load_dataset('glue', task)
def tokenize_function(examples):
return tokenizer(
examples['sentence'], truncation=True, padding=True)
tokenized_datasets = dataset.map(tokenize_function,
batched=True)
training_args = TrainingArguments(
output_dir=f"./results_{task}",
evaluation_strategy="epoch",
num_train_epochs=1,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets['train'],
eval_dataset=tokenized_datasets['validation'],
)
eval_results = trainer.evaluate()
results[task] = eval_results['eval_accuracy']
return results

The following is how to run the evaluation based on the previously defined function:

model_name = "bert-base-uncased" # Replace with your model
generalization_results = evaluate_task_generalization(model_name)
for task, accuracy in generalization_results.items():
print(f"{task} accuracy: {accuracy:.2f}")

Putting together the preceding code, we can evaluate the model on multiple GLUE tasks to assess its ability to generalize across different NLP tasks.

Continual learning is the ability of a model to learn new tasks without forgetting previously learned ones. Here’s an example of how you might evaluate continual learning in LLMs:

  1. Set up our continual learning framework by initializing the model, the tokenizer, and the main
    def evaluate_continual_learning(
    model_name, tasks=['sst2', 'qnli', 'qqp'], num_epochs=3
    ):
    model = \
    AutoModelForSequenceClassification.from_
    pretrained(model_name)
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    results = {}
  2. Define the preprocessing function that handles different input formats for various
    def preprocess_function(examples, task):
    # Different tasks have different input formats
    if task == 'qqp':
    texts = (examples['question1'], examples['question2'])
    elif task == 'qnli':
    texts = (examples['question'], examples['sentence'])
    else: # sst2
    texts = (examples['sentence'], None)
    tokenized = tokenizer(*texts, padding=True, truncation=True)
    tokenized['labels'] = examples['label']
    return tokenized
  3. Preprocess and prepare the dataset for
    for task in tasks:
    dataset = load_dataset('glue', task)
    tokenized_dataset = dataset.map(
    lambda x: preprocess_function(x, task),
    batched=True,
    remove_columns=dataset['train'].column_names
    )
    model.config.num_labels = 3 if task == 'mnli' else 2
  4. Provide the training setup and execution for
    trainer = Trainer(
    model=model,
    args=TrainingArguments(
    output_dir=f"./results_{task}",
    num_train_epochs=num_epochs,
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    evaluation_strategy="epoch"
    ),
    train_dataset=tokenized_dataset['train'],
    eval_dataset=tokenized_dataset['validation']
    )
    trainer.train()
  5. Conduct an evaluation across all previously
    task_results = {}
    for eval_task in tasks[:tasks.index(task)+1]:
    eval_dataset = load_dataset('glue', eval_task)['validation']
    eval_tokenized = eval_dataset.map(
    lambda x: preprocess_function(x, eval_task),
    batched=True,
    remove_columns=eval_dataset.column_names
    )
    eval_results = trainer.evaluate(eval_dataset=eval_tokenized)
    task_results[eval_task] = eval_results['eval_accuracy']
    results[task] = task_results
  6. Run the evaluation and display
    model_name = "bert-base-uncased" # Replace with your model
    cl_results = evaluate_continual_learning(model_name)
    for task, task_results in cl_results.items():
    print(f"\nAfter training on {task}:")
    for eval_task, accuracy in task_results.items():
    print(f" {eval_task} accuracy: {accuracy:.2f}")

Putting the preceding code blocks together, we show how to fine-tune the model on a sequence of tasks and evaluate its performance on all previously seen tasks after each fine-tuning step, allowing us to assess how well it retains knowledge of earlier tasks.

Cross-validation challenges and best practices

Section titled “Cross-validation challenges and best practices”

LLMs present unique challenges for cross-validation due to their scale and the nature of their training data. Here are some key challenges:

  • Data contamination: Avoiding test set overlap with pre-training data is difficult given the vast and diverse web data LLMs are trained on, making it hard to ensure a truly unseen validation set
  • Computational cost: Traditional methods such as k-fold cross-validation are often infeasible due to the immense computational resources required for models of this scale
  • Domain shift: LLMs may show inconsistent performance when exposed to data from underrepresented or entirely new domains, complicating the evaluation of generalizability
  • Prompt sensitivity: The performance of LLMs can vary significantly based on subtle differences in prompt wording, adding another layer of variability to the validation process

Based on these challenges, here are some best practices for LLM cross-validation:

  • Mitigate data contamination: Use rigorous data deduplication methods to identify and remove overlaps between the pre-training corpus and validation datasets. Tools such as MinHash or Bloom filters can efficiently detect near-duplicates in large datasets.

MinHash

MinHash is a probabilistic technique for quickly estimating how similar two sets are by converting large sets into smaller, representative fingerprints (hashes) where the probability of hash collision is proportional to the similarity between the original sets, making it particularly useful for detecting near-duplicate content in large datasets.

MinHashLSH is based on MinHash and locality-sensitive hashing (LSH), which groups similar items into the same “buckets” to enable fast lookup and comparison.

The following code example demonstrates data deduplication using MinHash and MinHashLSH for detecting near-duplicates in datasets:

from datasketch import MinHash, MinHashLSH
import numpy as np
def deduplicate_data(texts, threshold=0.8):
# Initialize LSH index for fast similarity search
lsh = MinHashLSH(threshold=threshold, num_perm=128)
unique_texts = []
for idx, text in enumerate(texts):
minhash = MinHash(num_perm=128)
for ngram in get_ngrams(text):
minhash.update(ngram.encode('utf8'))
if not lsh.query(minhash): # Check if similar text exists
lsh.insert(str(idx), minhash)
unique_texts.append(text)
return unique_texts
  • Reduce computational cost: Use stratified sampling or a single-split validation (e.g., train-validation-test) approach to minimize computational overhead. Alternatively, employ smaller model checkpoints or distilled versions of the LLM during experimentation before The following code example shows stratified sampling for efficient validation:
    from sklearn.model_selection import StratifiedKFold
    from collections import defaultdict
    def create_efficient_splits(data, labels, n_splits=5):
    # Group data by domain
    domain_data = defaultdict(list)
    for text, domain in zip(data, labels):
    domain_data[domain].append(text)
    # Create stratified splits
    skf = StratifiedKFold(n_splits=n_splits, shuffle=True)
    splits = []
    for train_idx, val_idx in skf.split(data, labels):
    splits.append((train_idx, val_idx))
    return splits
  • Handle domain shift: Construct validation datasets with explicit representation from diverse domains. Fine-tune models with representative domain-specific data to reduce performance gaps in This code example demonstrates handling domain shift through domain-specific validation:
    def evaluate_domain_performance(model, tokenizer, eval_data):
    domain_scores = defaultdict(list)
    for text, domain in eval_data:
    inputs = tokenizer(text, return_tensors='pt')
    with torch.no_grad():
    outputs = model(inputs)
    score = outputs.logits.mean().item()
    domain_scores[domain].append(score)
    # Calculate domain-specific metrics
    return {domain: np.mean(scores)
    for domain, scores in domain_scores.items()}
  • Address prompt sensitivity: Perform prompt engineering systematically. Use techniques such as prompt paraphrasing, instruction tuning, or ensemble evaluation across multiple prompts to ensure robustness and minimize the variability introduced by The following code example shows systematic prompt engineering with multiple variants:
    def evaluate_with_prompt_ensemble(
    model, tokenizer, text, base_prompt
    ):
    prompt_variants = [
    f"{base_prompt}: {text}",
    f"Please {base_prompt.lower()}: {text}",
    f"I want you to {base_prompt.lower()}: {text}"
    ]
    responses = []
    for prompt in prompt_variants:
    inputs = tokenizer(prompt, return_tensors='pt')
    with torch.no_grad():
    output = model.generate(inputs, max_length=100)
    responses.append(tokenizer.decode(output[0]))
    # Aggregate responses (e.g., by voting or averaging)
    return aggregate_responses(responses)

The following code example shows how to combine all these approaches into a single evaluation pipeline:

def robust_evaluation_pipeline(model, data, domains):
# First deduplicate the data
clean_data = deduplicate_data(data)
# Create efficient splits
splits = create_efficient_splits(clean_data, domains)
# Evaluate across domains with prompt ensembles
results = defaultdict(dict)
for domain in domains:
domain_data = [d for d, dom in zip(clean_data, domains)
if dom == domain]
scores = evaluate_with_prompt_ensemble(model, tokenizer,
domain_data, "analyze")
results[domain] = scores
return results

Cross-validation for LLMs requires careful consideration of their unique characteristics and capabilities. By implementing these advanced techniques and best practices, you can obtain a more robust and comprehensive assessment of your LLM’s performance across various domains and tasks.

As we move forward, the next chapter will delve into the crucial topic of interpretability in LLMs. We’ll explore techniques for understanding and explaining the outputs and behaviors of LLMs.

Get This Book's PDF Version and Exclusive Extras