Data Versioning
local graph
Chapter 5 — Data Versioning
Section titled “Chapter 5 — Data Versioning”Data versioning refers to the systematic tracking and management of different iterations of datasets used throughout the life cycle of model development, including pre-training, fine-tuning, evaluation, and deployment. It involves assigning unique identifiers to datasets or subsets thereof, capturing changes over time, and enabling reproducibility by ensuring that any specific model version can be linked back to the exact data version used.
In this chapter, you’ll learn how to implement effective data versioning strategies for LLM development. For instance, when we want to add 10,000 new oncology research papers to a dataset, the system automatically creates a new dataset version. If the model performance then degrades, the dataset can instantly roll back to the previous verified dataset version, ensuring reproducibility and maintaining the integrity of the research process.
This design pattern transforms dataset management from a chaotic, manual process into a structured, trackable workflow in LLM model development.
In this chapter, we’ll be covering the following topics:
- Understanding the need for data versioning
- Data versioning strategies for large language datasets
- Tools for data versioning
- Integrating data versioning in training workflows
- Version control for text corpora
- Managing dataset variants and experiments
- Best practices for data versioning
Understanding the need for data versioning
Section titled “Understanding the need for data versioning”Data versioning is particularly important in LLM projects due to the massive scale and complexity of language datasets. As an LLM engineer, you need to track changes in your datasets to ensure the reproducibility of your models and maintain a clear history of data modifications.
Let’s start by implementing a basic data versioning system using Python:
from datetime import datetimeimport hashlibimport jsonclass DatasetVersion: def __init__(self, data, metadata=None): self.data = data self.metadata = metadata or {} self.timestamp = datetime.now().isoformat() //creation timestamp for each version self.version_hash = self._generate_hash() def _generate_hash(self): data_str = json.dumps(self.data, sort_keys=True).encode() return hashlib.sha256(data_str).hexdigest()This part of the DatasetVersion class initializes the basic structure for versioning your LLM datasets. It generates a unique hash for each version of the data and timestamps the version. The _generate_hash method creates a deterministic hash based on the sorted JSON representation of the data, ensuring that identical data always produces the same hash.
Now, let’s add the save and load methods for dataset versions:
class DatasetVersion: # ... (previous methods) def save(self, filename): with open(filename, 'w') as f: json.dump({ 'data': self.data, 'metadata': self.metadata, 'timestamp': self.timestamp, 'version_hash': self.version_hash }, f, indent=2) @classmethod def load(cls, filename): with open(filename, 'r') as f: data = json.load(f) instance = cls(data['data'], data['metadata']) instance.timestamp = data['timestamp'] instance.version_hash = data['version_hash'] return instanceThe save method serializes the dataset version to a JSON file, including all relevant information. The load method is a class method that reconstructs a DatasetVersion instance from a saved file. This allows you to easily store and retrieve different versions of your dataset.
Having discussed the need for data versioning, now let us outline key strategies for managing versioning in large language datasets to support traceability, reproducibility, and efficient storage.
Data versioning strategies for large language datasets
Section titled “Data versioning strategies for large language datasets”Among the various strategies available for handling data versioning—such as snapshotting, content-addressable storage, and checksum-based tracking—this section focuses on the delta-based system due to its potential for minimizing storage costs when dealing with iterative updates in large language datasets. Delta-based versioning stores only the differences between dataset versions rather than duplicating entire files, making it particularly effective in scenarios involving frequent but minor changes. However, its effectiveness decreases when the dataset structure undergoes significant reformatting or involves binary files. Schema changes, column reordering, or file splitting can disrupt the delta mechanism, often necessitating a full dataset rewrite. Similarly, binary files, due to their opaque structure and compression, tend to change globally with even minor edits, limiting the advantage of delta-based storage. This approach is discussed here for its relevance in typical LLM workflows where data evolves gradually but remains largely text-based and structured.
Here’s an example of how you might implement a delta-based versioning system:
import difflibclass DeltaDatasetVersion(DatasetVersion): def __init__( self, data, base_version=None, metadata=None ): super().__init__(data, metadata) self.base_version = base_version self.delta = self._compute_delta() if base_version else None def _compute_delta(self): base_data = json.dumps( self.base_version.data, sort_keys=True).splitlines() current_data = json.dumps( self.data, sort_keys=True).splitlines() diff = list( difflib.unified_diff( base_data, current_data, lineterm='') ) return '\n'.join(diff)This part of the DeltaDatasetVersion class extends our previous DatasetVersion class to implement delta-based versioning. The _compute_delta method calculates the differences between the current version and a base version using Python’s difflib. This approach can significantly reduce storage requirements for large datasets by only storing the changes.
Now, let’s add methods to save and load these delta-based versions:
class DeltaDatasetVersion(DatasetVersion): # ... (previous methods) def save(self, filename): with open(filename, 'w') as f: json.dump({ 'metadata': self.metadata, 'timestamp': self.timestamp, 'version_hash': self.version_hash, 'base_version_hash': ( self.base_version.version_hash if self.base_version else None ), 'delta': self.delta }, f, indent=2) @classmethod def load(cls, filename, base_version): with open(filename, 'r') as f: data = json.load(f) # Apply delta to base version base_data = json.dumps( base_version.data, sort_keys=True ).splitlines() patched_data = difflib.restore( base_data, data['delta'].splitlines(), 1 ) current_data = json.loads('\n'.join(patched_data)) instance = cls(current_data, base_version, data['metadata']) instance.timestamp = data['timestamp'] instance.version_hash = data['version_hash'] instance.delta = data['delta'] return instanceThe save method now stores only the delta and metadata, significantly reducing the file size of large datasets. The load method reconstructs the full dataset by applying the delta to the base version. This approach allows for the efficient storage and retrieval of multiple versions of large language datasets.
Tools for data versioning
Section titled “Tools for data versioning”While custom solutions can be effective, there are also specialized tools designed for data versioning in machine learning projects. One such tool is Data Version Control (DVC), which integrates with Git and provides powerful features for managing large datasets and is widely used. DVC is an open-source tool that extends Git to manage large datasets and machine learning artifacts by storing data in external storage while tracking metadata in the Git repository. It enables reproducible pipelines, efficient data sharing, and experiment tracking, making it a popular choice for managing LLM datasets and training workflows.
Given the scale of LLM models, DVC’s versioning approach must carefully balance comprehensive tracking with computational efficiency, requiring intelligent checksum and metadata calculation strategies that minimize latency and processing overhead to prevent versioning from becoming a bottleneck in the model development workflow.
Here’s an example of how you might use DVC in your LLM project:
import subprocessdef initialize_dvc(): subprocess.run(["dvc", "init"]) print("DVC initialized in the current directory.")def add_dataset_to_dvc(dataset_path): subprocess.run(["dvc", "add", dataset_path]) print(f"Dataset {dataset_path} added to DVC.")def commit_dataset_version(message): subprocess.run(["git", "add", ".dvc"]) subprocess.run(["git", "commit", "-m", message]) print(f"Dataset version committed with message: {message}")This part of the script demonstrates how to initialize DVC, add a dataset to DVC tracking, and commit a new version of the dataset. DVC works alongside Git, allowing you to version your data in a similar way to how you version your code.
Similar to Git, DVC uses init, add, commit, and push commands. The following list briefly describes each command:
dvc init: Initializes a new DVC project by creating a.dvcdirectory in your project and setting up the necessary metadata tracking infrastructure. This is analogous togit init, but specifically for data version control, preparing your project to track large datasets and model files.dvc add: Adds large data files to DVC tracking, creating a lightweight.dvcmetadata file that contains a hash of the file. This command moves the actual data to a separate storage location while maintaining a reference in your Git repository, allowing you to version large files without bloating your Git repository.dvc commit: Creates a snapshot of the current state of your tracked data files, similar to a Git commit but specifically for data files. This command helps you mark significant points in your data’s history and creates a clear record of when and how your datasets changed.dvc push: Uploads your tracked data files to a remote storage location (such as cloud storage, network drive, or local external storage). This command ensures that your data versions are safely backed up and can be retrieved by other team members or across different development environments.
Now, let’s add a function to push the dataset to remote storage:
def push_dataset_to_remote(): subprocess.run(["dvc", "push"]) subprocess.run(["git", "push"]) print("Dataset pushed to remote storage.")# Usage exampleif __name__ == "__main__": initialize_dvc() add_dataset_to_dvc("path/to/your/large_language_dataset.txt") commit_dataset_version("Add initial version of language dataset") push_dataset_to_remote()The push_dataset_to_remote function pushes both the DVC-tracked data and the Git repository to their respective remote storage locations. This allows you to store your large datasets separately from your code repository while maintaining version control for both.
Next, we will focus on integrating data versioning within the training workflow.
Integrating data versioning in training workflows
Section titled “Integrating data versioning in training workflows”To make data versioning an integral part of your LLM training workflow, you need to incorporate version checking and logging into your training scripts. Here’s an example of how you might do this:
import jsonfrom dataclasses import dataclassfrom typing import Dict, Any@dataclassclass DatasetInfo: version_hash: str metadata: Dict[str, Any]def load_dataset_info(filename: str) -> DatasetInfo: with open(filename, 'r') as f: data = json.load(f) return DatasetInfo(data['version_hash'], data['metadata'])def train_llm(model, dataset, dataset_info: DatasetInfo): # Log dataset version information print( f"Training model with dataset version: " f"{dataset_info.version_hash}" ) print(f"Dataset metadata: {dataset_info.metadata}") # Actual training code would go here # ... # Save model with dataset version information model.save(f"model_trained_on_{dataset_info.version_hash[:8]}.pt")This code snippet shows how to incorporate dataset version information into your LLM training workflow. The DatasetInfo class encapsulates the essential version information, while the load_dataset_info function retrieves this information from a JSON file. The train_llm function demonstrates how to log the dataset version and metadata during training, ensuring that each trained model is associated with a specific version of the data.
Here’s how you might use this in a training script:
# Usage in training scriptdataset_info = load_dataset_info("dataset_info.json")dataset = load_dataset() # Your dataset loading functionmodel = initialize_model() # Your model initialization functiontrain_llm(model, dataset, dataset_info)By integrating dataset version information into your training process, you enhance reproducibility and make it easier to track which version of the data was used for each trained model.
Version control for text corpora
Section titled “Version control for text corpora”When dealing with text corpora for LLM training, you often need to handle large collections of documents. Here’s an approach to version control for text corpora using a combination of file hashing and metadata tracking:
import osimport hashlibfrom typing import Dict, Listdef hash_file(filepath: str) -> str: with open(filepath, 'rb') as f: return hashlib.sha256(f.read()).hexdigest()def generate_corpus_manifest(corpus_dir: str) -> Dict[str, str]: manifest = {} for root, _, files in os.walk(corpus_dir): for file in files: filepath = os.path.join(root, file) manifest[os.path.relpath(filepath, corpus_dir)] = \ hash_file(filepath) return manifestThis part of the code defines functions to hash individual files and generate a manifest of all files in a corpus directory. The manifest is a dictionary mapping relative file paths to their corresponding hash values, providing a snapshot of the entire corpus. The manifest file is important because it serves as a compact, reproducible fingerprint of the entire dataset, enabling quick integrity checks, facilitating version tracking, and allowing researchers to verify the exact state of their corpus across different environments or points in time without needing to store or transfer the entire large dataset.
Now, let’s add a function to compare two manifests and identify changes:
def compare_manifests( old_manifest: Dict[str, str], new_manifest: Dict[str, str]) -> Dict[str, List[str]]: changes = { "added": [], "removed": [], "modified": [] } for file, hash in new_manifest.items(): if file not in old_manifest: changes["added"].append(file) elif old_manifest[file] != hash: changes["modified"].append(file) for file in old_manifest: if file not in new_manifest: changes["removed"].append(file) return changes# Usage exampleold_manifest = generate_corpus_manifest("path/to/old_corpus")new_manifest = generate_corpus_manifest("path/to/new_corpus")changes = compare_manifests(old_manifest, new_manifest)print("Corpus changes:")for change_type, files in changes.items(): print(f"{change_type.capitalize()}:") for file in files: print(f" - {file}")The compare_manifests function identifies added, removed, and modified files between two versions of the corpus. This approach allows you to track changes in your text corpus efficiently, even when dealing with large numbers of files.
Managing dataset variants and experiments
Section titled “Managing dataset variants and experiments”In LLM development, you often need to manage multiple variants of your dataset for different experiments. Here’s a simple system for managing dataset variants:
from typing import Dict, Anyimport jsonimport osclass DatasetVariantManager: def __init__(self, base_path: str): self.base_path = base_path self.variants: Dict[str, Dict[str, Any]] = {} self._load_variants() def _load_variants(self): if os.path.exists( os.path.join(self.base_path, "variants.json") ): with open( os.path.join(self.base_path, "variants.json"), 'r' ) as f: self.variants = json.load(f) def save_variants(self): with open( os.path.join(self.base_path, "variants.json"), 'w' ) as f: json.dump(self.variants, f, indent=2)This part of the DatasetVariantManager class sets up the basic structure for managing dataset variants. It initializes the manager with a base path and loads existing variants from a JSON file, if available.
Now, let’s add methods to create and retrieve variants:
class DatasetVariantManager: # ... (previous methods) def create_variant( self, name: str, base_variant: str, changes: Dict[str, Any] ): if name in self.variants: raise ValueError(f"Variant {name} already exists") self.variants[name] = { "base": base_variant, "changes": changes } self.save_variants() def get_variant(self, name: str) -> Dict[str, Any]: if name not in self.variants: raise ValueError(f"Variant {name} does not exist") variant = self.variants[name] base_data = self.get_variant(variant["base"]) if variant["base"] else {} return {base_data, variant["changes"]}# Usage examplemanager = DatasetVariantManager("path/to/dataset/variants")manager.create_variant( "base", None, {"size": 1000000, "language": "en"})manager.create_variant("large", "base", {"size": 5000000})manager.create_variant( "multilingual", "large", {"language": ["en", "es", "fr"]})print(manager.get_variant("multilingual"))The create_variant method allows you to create new dataset variants based on existing ones, specifying only the changes. The get_variant method retrieves a variant, applying all changes from its base variants recursively. This system allows you to efficiently manage and track different configurations of your dataset for various experiments.
A clear and consistent naming convention is recommended for managing dataset variants in LLM development to ensure traceability, reproducibility, and clarity. Here is a suggested naming convention that balances readability and scalability for managing dataset variants:
< base>_<modifier1>_<modifier2>_..._<description>
This format uses a base name to indicate the root dataset, followed by modifiers and optional descriptions to specify what changes or attributes differentiate the variant. Modifiers are concise and ordered hierarchically to reflect the transformation process.
Let’s look at the key components closely:
- Base name: Represents the initial dataset, such as
baseor a descriptive name (e.g.,cleanorraw). - Modifiers: Sequential changes or transformations applied to the base. Each modifier reflects an aspect of the dataset such as size, language, or preprocessing applied.
- Description: An optional part that provides extra context or details about the changes, typically used for experiments.
Best practices for data versioning
Section titled “Best practices for data versioning”Over the years, I have gathered the following best practices:
- Use a dedicated data versioning tool such as DVC for large-scale projects.
- Include dataset version information in your model metadata.
- Use delta-based versioning for large datasets to save storage space.
- Implement regular backups of your versioned datasets.
- Use consistent naming conventions for dataset versions and variants.
- Integrate data versioning checks into your continuous integration and continuous delivery (CI/CD) pipeline for LLM training. This can be achieved by adding DVC-specific validation steps in your CI/CD workflow, such as running
dvc statusto verify no unexpected modifications have occurred, automatically comparing dataset checksums against approved versions, and blocking model training if any data discrepancies are detected. Key steps include creating a pre-training validation stage that compares current dataset versions with expected reference versions, automatically triggering alerts or stopping the pipeline if unverified data modifications are detected, and maintaining a comprehensive audit trail of dataset changes throughout the machine learning development process.
Summary
Section titled “Summary”In this chapter, we explored various aspects of data versioning for LLM development. We implemented basic versioning systems and delta-based versioning for large datasets. We examined tools such as DVC for more advanced versioning needs. We also looked at integrating data versioning into LLM training workflows, managing text corpora versions, and handling dataset variants for experiments.
Data versioning is a critical practice in LLM development, ensuring reproducibility, facilitating collaboration, and enabling robust model governance. By implementing these techniques and best practices, you can significantly improve the manageability and reliability of your LLM projects.
In the upcoming chapter, we’ll explore dataset annotation and labeling techniques specifically tailored for LLMs. In particular, we’ll cover strategies for efficient annotation, quality control measures, and methods for scaling annotation processes to meet the demands of large language datasets.
Get This Book's PDF Version and Exclusive Extras
|