We are going to design a system for ML reproducibility that captures:
- Dataset hashes (to track exact dataset versions)
- Environment snapshots (to track software dependencies and system state)
- Pipeline DAGs (to track the structure of the ML pipeline)
We'll assume that we are building a ledger that records each experiment run with these three components.
Steps:
a. For dataset hashes: we can compute checksums (like SHA256) of the dataset files. However, note that datasets can be large and split across multiple files.
We might also want to capture the schema or metadata. But for simplicity, we can hash each file and then combine the hashes (e.g., by hashing the sorted list of file hashes) to get a dataset-level hash.
b. For environment snapshots: we can capture the state of the Python environment (using pip freeze or conda env export) and also system-level information (OS, hardware). We can also capture versions of non-Python dependencies if needed.
c. For pipeline DAGs: we need to capture the structure of the pipeline. This could be represented as a Directed Acyclic Graph (DAG) of the steps. We can use a format like JSON to describe the DAG, including the steps, their order, and parameters.
We'll design a class MLReproducibilityLedger that can record an experiment run with:
- A unique run ID (we can generate a UUID)
- Timestamp
- Dataset information (with hashes and maybe paths)
- Environment snapshot (as a string or a file)
- Pipeline DAG (as a JSON string or a file)
We might also want to store these in a database or a file system. For simplicity, we'll store each run as a JSON file in a directory, and we'll also have an index (or just rely on the file system).
However, note that the environment snapshot and DAG might be large, so we might store them as separate files and reference them.
Alternatively, we can design the ledger to store everything in one JSON, but if the environment snapshot is long (many packages) and the DAG is complex, it might be too big.
Let's design:
Option 1: One JSON per run, containing:
run_id: string
timestamp: string (ISO format)
dataset:
- name: string
- version: string (maybe we use the hash as version? or separate)
- file_hashes: dict mapping file path to hash (or list of dicts with path and hash)
- dataset_hash: string (the combined hash)
environment:
- python_version: string
- packages: list of strings (from pip freeze) or a string of the entire freeze output
- system_info: dict (OS, etc.)
pipeline:
- dag: a JSON-serializable dict representing the DAG (nodes and edges, and maybe parameters for each step)
- maybe also a graphviz representation? but we can generate that from the DAG.
Option 2: Store the large parts (environment snapshot and DAG) as separate files and store only the paths in the JSON.
Since we want to be able to share and reproduce, having everything in one JSON might be easier for portability, but if the environment snapshot is huge, it might be a problem.
However, note that a typical pip freeze output is a list of packages and versions, which is a few hundred lines at most. So it's manageable.
Let's go with Option 1 for simplicity, but we'll also allow for the possibility of storing the environment snapshot and DAG as files if they are too big? Actually, we can just store them as strings in the JSON.
But note: the DAG could be very large if there are many steps. But in practice, ML pipelines are not that huge. So we'll stick to one JSON.
However, we must be cautious about the size of the JSON. We'll design the class to be flexible.
Implementation:
Steps for recording an experiment:
-
Compute dataset hash(es):
- We assume we have a list of dataset files (or a directory). We can compute the hash for each file, then combine them by:
- Sorting the file paths (to ensure consistent order)
- For each file, compute SHA256 (or other) hash.
- Then, create a string by concatenating the file path and its hash, then hash that entire string? Or just hash the sorted list of hashes?
- Alternatively, we can use a Merkle tree, but that's overkill.
Let's do:
dataset_hash = SHA256( sorted( [ (file_path, file_hash) for each file ] ) )
But note: the tuple of (file_path, file_hash) as a string? We can do:
combined_string = ""
for file_path, file_hash in sorted_list:
combined_string += f"{file_path}:{file_hash}\n"
dataset_hash = hashlib.sha256(combined_string.encode()).hexdigest()
But wait, what if the same dataset is stored in two different directories? Then the file paths would be different. So we might want to ignore the absolute path and just use the relative path within the dataset? Or we can compute the hash only on the content, but then two identical datasets in two different locations would have the same hash? That's acceptable because the content is the same.
Alternatively, we can compute a hash for the entire dataset by:
- If it's a single file, just hash the file.
- If it's a directory, we can compute a hash of the entire directory tree by:
import hashlib
def dir_hash(directory):
hash = hashlib.sha256()
for root, dirs, files in sorted(os.walk(directory)):
for filename in sorted(files):
file_path = os.path.join(root, filename)
with open(file_path, 'rb') as f:
while chunk := f.read(8192):
hash.update(chunk)
return hash.hexdigest()
But note: this method does not capture the directory structure, only the content of all files in a sorted order. However, if the directory structure is important, we should include the relative paths.
We can do:
for root, dirs, files in sorted(os.walk(directory)):
# sort the files and also the dirs? Actually, we are walking in sorted order because we sort the root, dirs, files?
# But note: os.walk does not sort by default. We can sort the files and also the dirs? Actually, we are sorting the root (the current directory) but not the files within? We are sorting the files in the current directory.
Alternatively, we can use:
for root, dirs, files in os.walk(directory):
# We sort the dirs and files to get consistent order?
dirs.sort()
files.sort()
for filename in files:
... and also we want to include the relative path of the file?
Actually, the above method of walking and updating the hash with the content of each file in sorted order (by the relative path) will be consistent.
However, note that the same file content in two different directories would produce the same hash? That's acceptable because the content is the same. But if the directory structure is part of the dataset (e.g., the way files are organized matters), then we should include the relative path in the hash.
Let's adjust:
We can do:
for root, dirs, files in os.walk(directory):
# We want to include the relative path of each file? Actually, we are walking from the base directory, and the root is the current directory relative to the base? We can compute the relative path of the file from the base directory.
base = os.path.abspath(directory)
for root, dirs, files in os.walk(base):
for filename in sorted(files):
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, base)
# Then update the hash with the rel_path and the content?
But wait, if we include the rel_path, then two datasets with the same files but in different structures would have different hashes.
We can do:
hash = hashlib.sha256()
for root, dirs, files in os.walk(base):
# Sort the files and also the dirs? Actually, we are going to process the files in sorted order by their relative path.
# We can get the list of relative paths for all files and sort them, then process in that order.
Alternatively, we can collect all the relative paths and sort them, then for each file, update the hash with (rel_path + content). But that would require reading the entire file for each update? Actually, we are reading the file anyway.
Let's do:
all_files = []
for root, dirs, files in os.walk(base):
for filename in files:
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, base)
all_files.append(rel_path)
Then sort the all_files, and for each rel_path, read the file and update the hash.
But note: if the dataset is huge, we might not want to store all the relative paths in memory? But typically, a dataset might have thousands of files, which is okay.
However, we are already walking the tree, so we can do:
file_list = []
for root, dirs, files in os.walk(base):
for filename in files:
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, base)
file_list.append( (rel_path, file_path) )
Then sort by rel_path, and then for each (rel_path, file_path) in sorted(file_list):
with open(file_path, 'rb') as f:
# We can update the hash with the rel_path (as bytes) and then the content?
hash.update(rel_path.encode('utf-8'))
while chunk := f.read(8192):
hash.update(chunk)
This way, the hash depends on the relative path and the content.
But wait, what if we have two files with the same content but different names? They would produce different hashes. That's correct because the structure matters.
However, note: if the dataset is just a single file, then the relative path is just the filename? But we are walking from the base, so if the base is the directory containing the file, then the rel_path is just the filename. That's acceptable.
But what if the dataset is a single file and we are given the file path? Then we can just hash that file and use the filename as the relative path? Actually, we are treating the input as a directory. So if we are given a single file, we can treat it as a directory with one file? Or we can have a function that handles both.
Let's design:
We have a function `compute_dataset_hash(dataset_path)` that can be either a file or a directory.
Steps:
if os.path.isfile(dataset_path):
# Then we compute the hash of the file and use the base name as the relative path? But note: the base name is not unique if we have two files in different directories with the same name? But it's a single file, so we can just use the file name? Actually, we don't have a directory structure. So we can do:
rel_path = os.path.basename(dataset_path)
with open(dataset_path, 'rb') as f:
hash = hashlib.sha256()
hash.update(rel_path.encode('utf-8'))
while chunk := f.read(8192):
hash.update(chunk)
return hash.hexdigest()
else:
# It's a directory, do the above walk.
But wait, what if we have a dataset that is a single file but we want to track it as a directory? Then we would have a directory with one file. So the above function for a directory would work.
Alternatively, we can always treat the input as a directory? But if we are given a single file, we can create a temporary directory? That's overkill.
Let's change: we can have the dataset as a list of files? Actually, the ledger should be flexible. We might have a dataset that is defined by a list of files (maybe from different locations). Then we cannot just hash a single directory.
So maybe we change the approach:
We want to capture the exact dataset used. The dataset might be a collection of files in multiple locations? Then we need to specify the list of files and their paths (relative to some root? or absolute?).
Alternatively, we can require that the dataset is provided as a list of (file_path, relative_path) pairs? Or we can have a manifest file?
Since we are designing for reproducibility, it's better to have the dataset versioned and stored in a specific location. So we assume the dataset is stored in a known location (a directory or a set of files) and we are given the root directory (or list of files) and we compute the hash accordingly.
Given the complexity, let's assume the dataset is a directory (or a single file) and we compute the hash as above.
But note: if the dataset is a directory, we are including the relative paths. If it's a single file, we are using the base name. This might be inconsistent.
Let's change the single file case to also use a relative path that is just the file name? That's acceptable.
However, if we have two datasets: one is a single file named 'data.csv' and another is a directory containing a file named 'data.csv', they would have the same hash? Because in the directory case, the relative path is 'data.csv' and the content is the same. But wait, the directory case we are walking and we get the relative path as 'data.csv'? Yes, if the directory has only one file.
But what if the directory has multiple files? Then the hash would be different because we are including all the files and their relative paths.
So it's consistent.
However, note: if we have a dataset that is a directory with one file, and we also have the same file as a standalone, they would have the same hash? Because in the standalone case, we are using the base name, and in the directory case, we are using the relative path which is the base name. So yes, same.
But what if the standalone file is in a different directory and we want to track the absolute path? We don't, because we want to track the content and the structure relative to the dataset root.
So we assume the dataset is provided with a root (either a directory or a file). We compute the hash of the entire dataset (all files) with their relative paths (relative to the root).
For a single file, the root is the directory containing the file? Actually, if we are given a single file, we can set the root as the parent directory? But then the relative path is just the file name. Alternatively, we can set the root as the file itself? Then the relative path would be empty? That doesn't work.
Let's do:
If the given path is a file, then we consider the dataset root as the directory containing the file, and the dataset consists of that one file with relative path = the file name.
If the given path is a directory, then the root is that directory and we include all files under it (recursively) with relative paths.
So:
dataset_root = os.path.dirname(dataset_path) if it's a file? Actually, we want the root to be the base of the dataset. For a single file, the dataset is just that file, so the root is the directory containing it? But then if we move the entire directory (with the file inside) to a new location, the relative paths remain the same. So it's okay.
Alternatively, we can require that the dataset is always provided as a directory? Then we don't have to handle the single file case separately.
Let's require the dataset to be a directory. Then we don't have the inconsistency.
But sometimes datasets are distributed as a single file (like a CSV). Then we can have a directory with that single file.
So we'll assume the input is a directory.
However, what if the dataset is a set of files not in a single directory? Then we can have a manifest that lists the files and their relative paths? That's more complex.
For now, we assume the dataset is a directory.
So:
def compute_dataset_hash(dataset_dir):
# dataset_dir is a directory path.
base = os.path.abspath(dataset_dir)
file_list = []
for root, dirs, files in os.walk(base):
for filename in files:
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, base)
file_list.append( (rel_path, file_path) )
# Sort by rel_path
file_list.sort(key=lambda x: x[0])
hash = hashlib.sha256()
for rel_path, file_path in file_list:
hash.update(rel_path.encode('utf-8'))
with open(file_path, 'rb') as f:
while chunk := f.read(8192):
hash.update(chunk)
return hash.hexdigest()
This will give us a hash that depends on the directory structure and the content of every file.
Implementation:
We'll create a class that can be used as follows:
ledger = MLReproducibilityLedger(log_dir='./reproducibility_logs')
run_id = ledger.start_run()
ledger.log_dataset(dataset_dir='/path/to/dataset')
ledger.log_environment()
ledger.log_pipeline_dag(dag_dict)
ledger.end_run()
But note: we might want to do all in one step? Or we can have a context manager.
Alternatively, we can have:
with ledger.run() as run:
run.log_dataset(...)
...
But we also want to generate the run_id at the start and then write the JSON at the end.
Let's design:
class MLReproducibilityLedger:
def init(self, log_dir):
self.log_dir = log_dir
os.makedirs(log_dir, exist_ok=True)
def start_run(self):
self.run_id = str(uuid.uuid4())
self.start_time = datetime.datetime.utcnow().isoformat()
self.data = {
'run_id': self.run_id,
'timestamp': self.start_time,
'dataset': None,
'environment': None,
'pipeline': None,
'code_version': self._get_git_commit() # if available
}
return self.run_id
def log_dataset(self, dataset_dir):
# compute hash and store the dataset info
dataset_hash = compute_dataset_hash(dataset_dir)
# We might also want to store the dataset_dir? But the hash should be enough to identify the dataset if we have a way to retrieve it.
# However, for reproducibility, we need to know which dataset was used. We can store the absolute path? But that might not be portable.
# Alternatively, we can store the dataset as an artifact? That's beyond the ledger.
# For the ledger, we just record the hash and maybe the dataset name (if provided) and the path (for reference).
# But the user might want to store the dataset in a versioned data store (like DVC). Then the hash is the version.
# We'll store:
# 'dataset_hash': dataset_hash,
# 'dataset_path': dataset_dir (absolute path)
self.data['dataset'] = {
'hash': dataset_hash,
'path': os.path.abspath(dataset_dir)
}
def log_environment(self):
# Capture environment
env_info = {
'python_version': platform.python_version(),
'packages': subprocess.check_output(['pip', 'freeze']).decode('utf-8').strip().split('\n'),
'system_info': {
'system': platform.system(),
'release': platform.release(),
'version': platform.version(),
'machine': platform.machine(),
'processor': platform.processor()
}
}
# Try conda
try:
conda_env = subprocess.check_output(['conda', 'env', 'export']).decode('utf-8')
env_info['conda_env'] = conda_env
except:
pass
self.data['environment'] = env_info
def log_pipeline_dag(self, dag_dict):
self.data['pipeline'] = dag_dict
def end_run(self):
self.data['end_time'] = datetime.datetime.utcnow().isoformat()
# Write to file
filename = os.path.join(self.log_dir, f"{self.run_id}.json")
with open(filename, 'w') as f:
json.dump(self.data, f, indent=2)
def _get_git_commit(self):
try:
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').strip()
return commit
except:
return None
But note: the user might not have git installed or the code might not be in a git repo. We handle that by returning None.
However, we also want to capture the pipeline code version? The git commit of the code that defines the pipeline. We are capturing the current commit when the ledger is started? That might be okay.
But what if the code changes during the run? We are capturing the commit at the start. That's acceptable because we want the code that was used at the start.
Alternatively, we can capture the commit at the end? But the run might be long. We want the code that was used to start the run.
We are capturing the commit at start_run, so that's the code at the time of starting.
However, note that the user might modify the code after starting the run but before logging the pipeline DAG? Then the DAG might be from the new code? But the git commit we captured is the old one.
We are logging the DAG separately, so we are capturing the structure and parameters. The code itself might be different, but the DAG representation might be the same? Not necessarily.
To be safe, we should capture the git commit at the time of logging the DAG? Or we can capture the code of the functions that define the pipeline? That's too complex.
Given the complexity, we'll stick to capturing the git commit at the start and hope that the code doesn't change during the run.
Alternatively, we can capture the git commit at the end? But then if the code changed during the run, we capture the changed code? That's not good.
Better: we capture the commit at the start and then also store a hash of the pipeline code? But we don't have the pipeline code as a string.
Since we are logging the DAG as a dict, we can hash that dict? But that doesn't capture the code that generated the DAG.
We might need to think about this more.
For now, we'll just capture the git commit at the start and hope for the best.
Another idea: we can have the user provide the pipeline code as a string? Or we can require that the pipeline is defined in a specific file and we store the hash of that file? But the pipeline might be defined across multiple files.
Given the complexity, we'll leave it as is and just capture the git commit.
We'll also capture the command line arguments? That might be part of the pipeline DAG? Or we can have a separate field for command line arguments.
We'll leave that to the user to include in the DAG or in the dataset info? Actually, the run might be triggered by a script with arguments. We can capture:
'command': ' '.join(sys.argv)
We can add that in the start_run? But note that the command might include sensitive information. We can let the user decide.
We can have an option to scrub the command? Or we can not capture it by default.
Let's not capture the command by default. The user can include it in the DAG or in a custom field.
We'll leave the ledger as above.
However, note: the above log_dataset requires the dataset to be a directory. We can adjust to handle a list of files? But then we need to define the relative paths.
We can change log_dataset to accept either a directory or a list of (file_path, rel_path) pairs.
Let's change:
def log_dataset(self, dataset_paths, dataset_root=None):
"""
dataset_paths: either a string (directory) or a list of (file_path, rel_path) tuples.
If it's a string, then we treat it as a directory and compute the hash of the entire directory (with relative paths from that directory).
If it's a list, then we use the provided rel_paths.
dataset_root: if provided, then for each file_path in the list, the rel_path is computed relative to dataset_root? Or we use the provided rel_path? We can ignore dataset_root if we are providing rel_path.
Alternatively, we can have:
If dataset_paths is a string, then it's a directory and we compute the hash of the directory.
If dataset_paths is a list, then we expect each element to be a file path, and we compute the relative path from the current working directory? That's not good.
Let's do:
We require that if the dataset is a collection of files, the user provides a list of (abs_file_path, rel_path) where rel_path is the path relative to some root (that the user chooses). Then we can compute the hash by:
Sort by rel_path.
For each (abs_file_path, rel_path):
update hash with rel_path and then the content of abs_file_path.
So:
def log_dataset(self, dataset_paths, dataset_name=None):
if isinstance(dataset_paths, str):
# It's a directory
base = os.path.abspath(dataset_paths)
file_list = []
for root, dirs, files in os.walk(base):
for filename in files:
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, base)
file_list.append( (rel_path, file_path) )
else:
# Assume it's a list of (rel_path, abs_file_path) or (abs_file_path, rel_path)? We'll assume list of tuples (abs_file_path, rel_path)
file_list = dataset_paths
# Now sort by rel_path
file_list.sort(key=lambda x: x[0])
hash = hashlib.sha256()
for rel_path, file_path in file_list:
hash.update(rel_path.encode('utf-8'))
with open(file_path, 'rb') as f:
while chunk := f.read(8192):
hash.update(chunk)
dataset_hash = hash.hexdigest()
self.data['dataset'] = {
'hash': dataset_hash,
'paths': [ (rel_path, file_path) for rel_path, file_path in file_list ] # store the list of files with their relative paths and absolute paths?
}
But wait, we are storing the absolute paths? That might not be portable. We are storing the relative paths and the absolute paths? Actually, we are storing both? We are storing the tuple (rel_path, file_path) in the 'paths' list. The file_path is absolute.
We might want to store only the relative paths? But then we need to know the base? We don't store the base? Actually, the hash is computed from the relative paths and the content. So to reconstruct the dataset, we need the absolute paths? Not necessarily: if we have the content and the relative paths, we can place the files in the correct structure.
But we are storing the absolute paths in the ledger? That's not portable because the absolute paths are machine-specific.
We should store only the relative paths and then the user must have the dataset in the same relative structure? But then we don't know where the root is.
Alternatively, we can store the absolute paths for reference, but the hash is computed from the relative paths and content. So the hash is independent of the absolute location.
So we can store:
'dataset_info': {
'hash': ...,
'files': [
{'rel_path': rel_path, 'abs_path': abs_path} # or just rel_path?
]
}
But if we only store the relative paths, then we don't know where to find the files on the machine that ran the experiment? That's okay because the ledger is for reproducibility, and we might want to retrieve the dataset from a versioned data store (like DVC) using the hash.
So we can store only the relative paths and the hash. The absolute paths are not necessary.
Let's change:
self.data['dataset'] = {
'hash': dataset_hash,
'files': [ {'rel_path': rel_path} for rel_path, _ in file_list ]
}
But wait, we are using the absolute path to read the file. We don't need to store the absolute path.
However, for debugging, we might want to know where the files were on the machine that ran the experiment. We can store the absolute path of the root? But we don't have a single root if the dataset is a list of files from multiple locations.
So maybe we store:
if we are given a directory, then we store the absolute path of the directory? But then we are storing a machine-specific path.
Alternatively, we can store the absolute path of each file? That's too much.
Given that the ledger is for reproducibility, we want to be able to reconstruct the dataset. The hash is the key. We can store the list of relative paths and then the user must have the dataset in the same structure (relative to some root) and then we can verify by hashing.
But without the absolute paths, we cannot know where the files were originally.
We can store:
'dataset': {
'hash': ...,
'structure': [rel_path1, rel_path2, ...],
'root_absolute_path': base # only if we were given a directory? but if we were given a list, we don't have a single root.
So if we are given a list, we don't have a root. Then we cannot store a root.
We can store the absolute path of each file? That's a lot.
Let's stick to:
If the dataset is a directory, we store:
'type': 'directory',
'path': absolute_path_of_the_directory,
'hash': ...,
'files': [rel_path1, ...] # relative to the directory
If the dataset is a list, we store:
'type': 'file_list',
'files': [ {'abs_path': abs_path, 'rel_path': rel_path} for each file ]
Then we can reconstruct: for directory, we know the root and the relative paths. For file_list, we have the absolute paths? But absolute paths are not portable.
Actually, for the file_list case, we are given the absolute paths and the relative paths. We store both? Then when reproducing, we need to have the files at the same absolute paths? That's not portable.
So maybe we should not support the file_list case? Or we require that the file_list is given with relative paths and we don't store the absolute paths? But then how do we compute the hash? We need the absolute paths to read the files.
We are computing the hash at the time of logging, so we have the absolute paths then. But we don't need to store them for reproduction? We only need the hash and the relative paths? And then the user must have the files in the same relative structure? But without the absolute root, we don't know where to look.
For the directory case, we store the absolute path of the directory? That's machine-specific. But we are logging on the machine that ran the experiment, so it's okay for that machine. For sharing, we might need to move the dataset to a different machine, then the absolute path is wrong.
So maybe we should not store absolute paths at all? We only store the hash and the relative paths? Then the user must have the dataset in the same relative structure (from some root) and then we can hash it again to verify.
But without the root, we cannot compute the hash again? We need to know the root to compute the relative paths? Actually, we have the relative paths, so if we have the dataset in the same structure (with the same relative paths) we can compute the hash by:
hash = sha256()
for rel_path in sorted(relative_paths):
with open(os.path.join(root, rel_path), 'rb') as f:
... update hash ...
But we don't know the root. So we need the root.
So we store the root (absolute path) for the directory case. For the file_list case, we don't have a single root, so we store the absolute path for each file? That's not portable.
Given the complexity, let's only support the directory case. And we store the absolute path of the directory and the relative paths of the files.
Then for reproduction, the user must have the dataset at the same absolute path? That's not portable.
Alternatively, we can store the hash and the relative paths, and the user can place the dataset in any directory as long as the relative structure is the same? Then we can compute the hash from the new root and the relative paths.
So we don't need to store the absolute path of the root? We only need the relative paths. But then how do we know the root? We don't. The user must provide the root when trying to reproduce.
So we can store:
'dataset': {
'hash': ...,
'files': [rel_path1, rel_path2, ...]
}
And then when reproducing, the user must have the dataset in a directory and provide that directory, and we compute the hash from that directory and the relative paths? Actually, we don't have the relative paths stored? We are storing the list of relative paths.
Then we can compute the hash by:
base = provided_directory
for rel_path in stored_relative_paths (sorted):
with open(os.path.join(base, rel_path), 'rb') as f:
... update hash ...
But wait, what if the user has extra files? Then the hash would be different. So the stored relative paths must be exactly the set of files that were hashed.
So we are storing the exact set of files (by relative path) that were included in the hash.
That's acceptable.
So we change:
In `log_dataset` for a directory:
We compute the list of relative paths (sorted) and the hash.
We store:
'dataset': {
'hash': dataset_hash,
'files': sorted_list_of_relative_paths # we already have it sorted
}
For a list of files (if we support it) we would store:
'dataset': {
'hash': dataset_hash,
'files': [ {'rel_path': rel_path, 'abs_path': abs_path} ] # but we don't want abs_path? We can store only rel_path? But then we don't know the original absolute paths? We don't need them for reproduction, only for reference.
Since we want to avoid storing absolute paths (for portability), we can store only the relative paths.
But then how do we compute the hash for the list of files? We are given the absolute paths to read the files. We compute the hash and then we store only the relative paths.
So:
def log_dataset(self, dataset_paths):
if isinstance(dataset_paths, str):
base = os.path.abspath(dataset_paths)
file_list = []
for root, dirs, files in os.walk(base):
for filename in files:
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, base)
file_list.append( (rel_path, file_path) )
else:
# dataset_paths is a list of (abs_file_path, rel_path)
file_list = dataset_paths
# Sort by rel_path
file_list.sort(key=lambda x: x[0])
rel_paths = [rel_path for rel_path, _ in file_list]
hash = hashlib.sha256()
for rel_path, file_path in file_list:
hash.update(rel_path.encode('utf-8'))
with open(file_path, 'rb') as f:
while chunk := f.read(8192):
hash.update(chunk)
dataset_hash = hash.hexdigest()
self.data['dataset'] = {
'hash': dataset_hash,
'files': rel_paths
}
Then, for reproduction, the user must have the dataset in a directory and provide that directory. Then we can recompute the hash by:
base = provided_directory
for rel_path in stored_relative_paths (which are sorted):
file_path = os.path.join(base, rel_path)
... read and hash ...
But wait, what if the user has the dataset in a different structure? Then the provided_directory must contain the files at the relative paths.
This is acceptable.
However, note: if the dataset is a list of files from multiple locations, then we don't have a single base. Then the user must have all the files at the same absolute paths? That's not portable.
So we should not support the list of files from multiple locations? Or we require that the user provides a mapping of rel_path to the file content? That's too complex.
Given the goal of portability, we require that the dataset is a single directory (or a single file, which we treat as a directory with one file).
So we change: `log_dataset` only accepts a directory path (string). Then we compute the hash and store the relative paths of all files in that directory (recursively).
Then for reproduction, the user must have the dataset in a directory with the same structure (relative paths) and then we can compute the hash.
But note: the user might have the dataset in a different location (different absolute path) but same relative structure. That's okay.
So we are good.
5. We also want to store the code version (git commit) and maybe the command line arguments? We can add an optional command argument to start_run?
def start_run(self, command=None):
self.run_id = ...
self.start_time = ...
self.data = {
'run_id': self.run_id,
'timestamp': self.start_time,
'command': command,
'code_version': self._get_git_commit(),
...
}
6. We might also want to store the user? or the machine? We can add:
'user': getpass.getuser(),
'host': socket.gethostname()
But that might be privacy sensitive. We'll leave it out by default, but we can add an option.
Given the above, let's adjust:
def start_run(self, command=None, user=None, host=None):
self.run_id = ...
self.start_time = ...
self.data = {
'run_id': self.run_id,
'timestamp': self.start_time,
'command': command,
'code_version': self._get_git_commit(),
'user': user or getpass.getuser(),
'host': host or socket.gethostname()
}
But note: the user and host might be sensitive. We can make them optional and not include by default? We can have a flag in the ledger to include them.
Alternatively, we can have a configuration for the ledger that specifies what to include.
For simplicity, we'll include them by default, but the user can override with None.
Let's change:
def start_run(self, command=None, user=None, host=None, include_user_host=True):
self.run_id = ...
self.start_time = ...
self.data = {
'run_id': self.run_id,
'timestamp': self.start_time,
'command': command,
'code_version': self._get_git_commit(),
}
if include_user_host:
self.data['user'] = user or getpass.getuser()
self.data['host'] = host or socket.gethostname()
7. We might also want to store the status of the run (success, failure). We can add:
self.data['status'] = 'success' # by default, and if there's an exception, we can set to 'failed'
We can have:
def end_run(self, status='success'):
self.data['end_time'] = datetime.datetime.utcnow().isoformat()
self.data['status'] = status
... write ...
And then if there's an exception, we can catch and call end_run with status='failed'.
8. We might also want to store the output (stdout/stderr) of the run? That could be large. We can store a hash of the output? Or we can store the output in a separate file and reference it.
Given the potential size, we won't store the output by default.
- We might want to store the parameters of the run? That might be part of the pipeline DAG? Or we can have a separate field.
We can have a log_parameters method that stores a dict of parameters.
self.data['parameters'] = params_dict
But the parameters might be part of the pipeline DAG? It depends on how the pipeline is defined.
We'll leave it to the user to include the parameters in the DAG or log them separately.
-
We might want to store the metrics? That's the output of the run. We can have a log_metrics method.
self.data['metrics'] = metrics_dict
But again, the metrics might be part of the pipeline DAG? Not necessarily.
We'll leave it to the user.
Given the above, we design the class as:
class MLReproducibilityLedger:
def init(self, log_dir, include_user_host=True):
self.log_dir = log_dir
self.include_user_host = include_user_host
os.makedirs(log_dir, exist_ok=True)
def start_run(self, command=None, user=None, host=None):
self.run_id = str(uuid.uuid4())
self.start_time = datetime.datetime.utcnow().isoformat()
self.data = {
'run_id': self.run_id,
'timestamp': self.start_time,
'command': command,
'code_version': self._get_git_commit(),
}
if self.include_user_host:
self.data['user'] = user or getpass.getuser()
self.data['host'] = host or socket.gethostname()
def log_dataset(self, dataset_dir):
# dataset_dir must be a directory
if not os.path.isdir(dataset_dir):
raise ValueError(f"{dataset_dir} is not a directory")
base = os.path.abspath(dataset_dir)
file_list = []
for root, dirs, files in os.walk(base):
for filename in files:
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, base)
file_list.append( (rel_path, file_path) )
file_list.sort(key=lambda x: x[0])
rel_paths = [rel_path for rel_path, _ in file_list]
hash = hashlib.sha256()
for rel_path, file_path in file_list:
hash.update(rel_path.encode('utf-8'))
with open(file_path, 'rb') as f:
while chunk := f.read(8192):
hash.update(chunk)
dataset_hash = hash.hexdigest()
self.data['dataset'] = {
'hash': dataset_hash,
'files': rel_paths
}
def log_environment(self):
# ... as above ...
def log_pipeline_dag(self, dag_dict):
self.data['pipeline'] = dag_dict
def log_parameters(self, params_dict):
self.data['parameters'] = params_dict
def log_metrics(self, metrics_dict):
self.data['metrics'] = metrics_dict
def end_run(self, status='success'):
self.data['end_time'] = datetime.datetime.utcnow().isoformat()
self.data['status'] = status
filename = os.path.join(self.log_dir, f"{self.run_id}.json")
with open(filename, 'w') as f:
json.dump(self.data, f, indent=2)
def _get_git_commit(self):
try:
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').strip()
return commit
except:
return None
But note: the log_environment might fail if pip or conda are not available. We should catch exceptions and store an error message.
def log_environment(self):
env_info = {}
try:
env_info['python_version'] = platform.python_version()
except Exception as e:
env_info['python_version'] = str(e)
try:
packages = subprocess.check_output(['pip', 'freeze']).decode('utf-8').strip().split('\n')
env_info['packages'] = packages
except Exception as e:
env_info['packages'] = f"Error: {str(e)}"
try:
conda_env = subprocess.check_output(['conda', 'env', 'export']).decode('utf-8')
env_info['conda_env'] = conda_env
except:
env_info['conda_env'] = None
try:
env_info['system_info'] = {
'system': platform.system(),
'release': platform.release(),
'version': platform.version(),
'machine': platform.machine(),
'processor': platform.processor()
}
except Exception as e:
env_info['system_info'] = str(e)
self.data['environment'] = env_info
11. We might also want to capture the environment variables? We can do:
env_info['env_vars'] = dict(os.environ)
But that might contain sensitive data. We can let the user specify which env vars to include? Or we can scrub? For now, we won't capture by default.
We can have an option to capture env vars.
Given the complexity, we'll leave it out.
-
We might want to capture the installed packages in a more robust way? For example, using pip list? But pip freeze is standard.
-
We might also want to capture the versions of non-Python dependencies (like system packages). We can try:
On Ubuntu: dpkg -l
On Mac: brew list? But that's not standard.
We'll leave that out.
-
We might want to capture the GPU information? We can try:
import torch
if torch.cuda.is_available():
env_info['cuda_version'] = torch.version.cuda
env_info['gpu_count'] = torch.cuda.device_count()
env_info['gpu_names'] = [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())]
But that only works if torch is installed.
We can try to import common libraries (tensorflow, torch) and capture their versions and GPU info.
We can have a list of modules to try:
for module_name in ['torch', 'tensorflow']:
try:
module = importlib.import_module(module_name)
version = module.version
env_info[f'{module_name}_version'] = version
if module_name == 'torch' and torch.cuda.is_available():
env_info['cuda_version'] = torch.version.cuda
...
except:
pass
We'll add that.
Let's adjust log_environment:
def log_environment(self):
env_info = {}
# System info
try:
env_info['system_info'] = {
'system': platform.system(),
'release': platform.release(),
'version': platform.version(),
'machine': platform.machine(),
'processor': platform.processor()
}
except Exception as e:
env_info['system_info'] = str(e)
# Python version
try:
env_info['python_version'] = platform.python_version()
except Exception as e:
env_info['python_version'] = str(e)
# Packages via pip freeze
try:
packages = subprocess.check_output(['pip', 'freeze']).decode('utf-8').strip().split('\n')
env_info['packages'] = packages
except Exception as e:
env_info['packages'] = f"Error: {str(e)}"
# Conda environment
try:
conda_env = subprocess.check_output(['conda', 'env', 'export']).decode('utf-8')
env_info['conda_env'] = conda_env
except:
env_info['conda_env'] = None
# Try to import common ML libraries
for module_name in ['torch', 'tensorflow']:
try:
module = importlib.import_module(module_name)
version = module.__version__
env_info[f'{module_name}_version'] = version
if module_name == 'torch' and hasattr(module, 'cuda') and module.cuda.is_available():
env_info['cuda_version'] = module.version.cuda
env_info['gpu_count'] = module.cuda.device_count()
env_info['gpu_names'] = [module.cuda.get_device_name(i) for i in range(module.cuda.device_count())]
except:
pass
self.data['environment'] = env_info
15. We might also want to capture the pip version? We can get it from pip --version? But we already have the list of packages.
-
We might want to capture the python executable path? We can do:
env_info['python_executable'] = sys.executable
Let's add:
try:
env_info['python_executable'] = sys.executable
except:
pass
17. We might want to capture the pip location? Not necessary.
-
We might want to capture the conda info? We already try to export the conda environment.
-
We might want to capture the nvidia-smi output? We can try:
try:
nvidia_smi = subprocess.check_output(['nvidia-smi']).decode('utf-8')
env_info['nvidia_smi'] = nvidia_smi
except:
pass
But that might be too much. We'll leave it out.
- We might want to capture the
glibc version? Not necessary.
Given the above, we have a basic ledger.
However, note: the ledger is designed to be used in a single run. We assume the user will call the methods in order:
start_run -> (log_dataset, log_environment, log_pipeline_dag, ...) -> end_run
We can also use a context manager:
with ledger.run() as run:
run.log_dataset(...)
...
Let's implement:
def run(self):
return self # and then use as context manager? We need __enter__ and __exit__.
But we want to automatically call start_run and end_run.
We can do:
class MLReproducibilityLedger:
...
def __enter__(self):
self.start_run()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
status = 'success' if exc_type is None else 'failed'
self.end_run(status=status)
Then the user can do:
with MLReproducibilityLedger(log_dir='logs') as ledger:
ledger.log_dataset(...)
...
But note: the user might not call `log_dataset` etc. inside the context? That's okay, we just record what they log.
We'll implement the context manager.
-
We might want to store the ledger itself as a database? But we are storing JSON files.
-
We might want to have an index of all runs? We can create a file index.json that lists all the run_ids and maybe the dataset hash, timestamp, and status.
We can do in end_run:
index_file = os.path.join(self.log_dir, 'index.json')
index = {}
if os.path.exists(index_file):
with open(index_file) as f:
index = json.load(f)
index[self.run_id] = {
'timestamp': self.data['timestamp'],
'dataset_hash': self.data.get('dataset', {}).get('hash'),
'status': self.data['status']
}
with open(index_file, 'w') as f:
json.dump(index, f, indent=2)
But note: the index might become large. We can also store the index as a CSV? Or we can just rely on the file system.
We'll do the index for convenience.
-
We might want to store the ledger configuration? We can store the include_user_host setting in the ledger file? Or in a separate config.
We can store in each run file the ledger version? We can have a 'ledger_version' field.
We'll set:
self.data['ledger_version'] = '0.1'
-
We might want to store the time of each log? Not necessary.
-
We might want to store the machine's IP address? That's sensitive. We won't.
-
We might want to store the run's working directory? We can do:
env_info['working_directory'] = os.getcwd()
But that might be sensitive. We'll leave it out.
-
We might want to store the command line arguments? We are storing the command in start_run.
-
We might want to store the Python path? We can do:
env_info['python_path'] = sys.path
But that might be long. We'll skip.
-
We might want to store the hash of the pipeline code? We can try to get the git commit of the pipeline code? We are already getting the current commit.
-
We might want to store the hash of the code that defines the pipeline? If the pipeline is defined in a specific file, we can hash that file? But we don't know which file.
Given the complexity, we'll leave it as is.
Let's code accordingly.
Note: The above design assumes that the dataset is a directory. We'll enforce that.
We'll also add a method to verify the dataset integrity? That would be:
def verify_dataset(self, dataset_dir, expected_hash):
computed_hash = compute_dataset_hash(dataset_dir)
return computed_hash == expected_hash
But we don't need that in the ledger class? We can have a separate function.
We'll leave it out.
Let's write the code accordingly.
We'll also add a method to load a run from the JSON file.
@staticmethod
def load_run(run_file):
with open(run_file) as f:
return json.load(f)
But that's trivial.
We'll also add a method to list runs in the log directory.
def list_runs(self):
runs = []
for filename in os.listdir(self.log_dir):
if filename.endswith('.json') and filename != 'index.json':
run_id = filename[:-5] # remove .json
with open(os.path.join(self.log_dir, filename)) as f:
data = json.load(f)
runs.append(data)
return runs
But we also have the index, so we can use that.
Given the above, let's write the code.
We'll also consider that the user might want to add custom fields. We can have a log_custom method that adds arbitrary key-value pairs.
def log_custom(self, key, value):
self.data[key] = value
But then we have to be cautious about overwriting existing keys.
We'll not implement that for now.
Let's code the class as described.
We'll also add a __init__ that takes log_dir and include_user_host (default True).
We'll also add a ledger_version field in the data.
We'll set ledger_version = '0.1'
Let's code accordingly.
Note: The log_environment might take a while because it walks the directory for the dataset. We are already doing that in log_dataset. So we are doing two walks? We are walking the directory in log_dataset and then again in log_environment? No, log_environment doesn't walk the directory. Only log_dataset does.
So it's okay.
Let's code.
I'll create a comprehensive ML reproducibility ledger system that captures dataset hashes, environment snapshots, and pipeline DAGs in a structured, queryable format.
ML Reproducibility Ledger System
"""
ML Reproducibility Ledger
Captures: dataset hashes, environment snapshots, pipeline DAGs
Author: ML Engineer
Version: 1.0
"""
import hashlib
import json
import os
import sys
import subprocess
import platform
import uuid
import datetime
from pathlib import Path
from typing import Dict, List, Any, Optional, Union
from dataclasses import dataclass, asdict
from enum import Enum
import graphviz # Optional: for DAG visualization
class RunStatus(Enum):
"""Status of an ML run"""
COMPLETED = "completed"
FAILED = "failed"
RUNNING = "running"
CANCELLED = "cancelled"
@dataclass
class DatasetInfo:
"""Dataset metadata and hash information"""
name: str
version: str
path: str
hash_algorithm: str = "sha256"
file_hashes: Dict[str, str] = None # {file_path: hash}
dataset_hash: str = ""
size_bytes: int = 0
created_at: str = ""
source: str = "" # e.g., "s3://bucket/path", "local/path"
def __post_init__(self):
if self.file_hashes is None:
self.file_hashes = {}
if not self.created_at:
self.created_at = datetime.datetime.utcnow().isoformat()
@dataclass
class EnvironmentSnapshot:
"""Complete environment state"""
python_version: str
pip_freeze: List[str] # Output of `pip freeze`
conda_env: Optional[str] = None # Output of `conda env export`
system_info: Dict[str, str] = None
environment_variables: Dict[str, str] = None
custom_packages: Dict[str, str] = None # Non-pip packages
gpu_info: Optional[Dict[str, Any]] = None
def __post_init__(self):
if self.system_info is None:
self.system_info = {}
if self.environment_variables is None:
self.environment_variables = {}
if self.custom_packages is None:
self.custom_packages = {}
@dataclass
class PipelineStep:
"""Individual step in ML pipeline"""
step_id: str
step_name: str
step_type: str # e.g., "data_ingestion", "preprocessing", "training", "evaluation"
parameters: Dict[str, Any]
input_artifacts: List[str] # References to previous step outputs
output_artifacts: List[str] # Output file/artifact paths
code_version: Optional[str] = None # Git commit hash
runtime_config: Dict[str, Any] = None
def __post_init__(self):
if self.runtime_config is None:
self.runtime_config = {}
@dataclass
class PipelineDAG:
"""Directed Acyclic Graph representation of ML pipeline"""
dag_id: str
name: str
description: str
steps: List[PipelineStep]
edges: List[Dict[str, str]] # [{"from": "step1", "to": "step2"}]
root_steps: List[str] # Steps with no dependencies
leaf_steps: List[str] # Steps with no dependents
metadata: Dict[str, Any] = None
def __post_init__(self):
if self.metadata is None:
self.metadata = {}
# Auto-discover root and leaf steps if not provided
if not self.root_steps:
self._discover_root_steps()
if not self.leaf_steps:
self._discover_leaf_steps()
def _discover_root_steps(self):
"""Find steps with no incoming edges"""
all_targets = {edge["to"] for edge in self.edges}
self.root_steps = [
step.step_id for step in self.steps
if step.step_id not in all_targets
]
def _discover_leaf_steps(self):
"""Find steps with no outgoing edges"""
all_sources = {edge["from"] for edge in self.edges}
self.leaf_steps = [
step.step_id for step in self.steps
if step.step_id not in all_sources
]
def to_graphviz(self) -> graphviz.Digraph:
"""Convert DAG to Graphviz object for visualization"""
dot = graphviz.Digraph(comment=self.name)
dot.attr(rankdir='LR')
# Add nodes
for step in self.steps:
dot.node(
step.step_id,
f"{step.step_name}\n({step.step_type})",
shape='box',
style='rounded'
)
# Add edges
for edge in self.edges:
dot.edge(edge["from"], edge["to"])
return dot
def validate(self) -> List[str]:
"""Validate DAG structure"""
errors = []
step_ids = {step.step_id for step in self.steps}
# Check all edges reference existing steps
for edge in self.edges:
if edge["from"] not in step_ids:
errors.append(f"Edge from non-existent step: {edge['from']}")
if edge["to"] not in step_ids:
errors.append(f"Edge to non-existent step: {edge['to']}")
if edge["from"] == edge["to"]:
errors.append(f"Self-loop detected: {edge['from']}")
# Check for cycles (simple DFS)
visited = set()
temp = set()
def has_cycle(step_id: str) -> bool:
if step_id in temp:
return True
if step_id in visited:
return False
temp.add(step_id)
for edge in self.edges:
if edge["from"] == step_id:
if has_cycle(edge["to"]):
return True
temp.remove(step_id)
visited.add(step_id)
return False
for step in self.steps:
if step.step_id not in visited and has_cycle(step.step_id):
errors.append(f"Cycle detected involving step: {step.step_id}")
break
return errors
@dataclass
class MLRun:
"""Complete ML run record"""
run_id: str
experiment_name: str
run_name: str
status: RunStatus
start_time: str
end_time: Optional[str] = None
duration_seconds: Optional[float] = None
# Core reproducibility components
dataset: DatasetInfo
environment: EnvironmentSnapshot
pipeline: PipelineDAG
# Optional metadata
tags: List[str] = None
metrics: Dict[str, float] = None
artifacts: Dict[str, str] = None # {artifact_name: path}
notes: str = ""
git_commit: Optional[str] = None
container_image: Optional[str] = None
def __post_init__(self):
if self.tags is None:
self.tags = []
if self.metrics is None:
self.metrics = {}
if self.artifacts is None:
self.artifacts = {}
# Calculate duration if both times exist
if self.start_time and self.end_time:
start = datetime.datetime.fromisoformat(self.start_time)
end = datetime.datetime.fromisoformat(self.end_time)
self.duration_seconds = (end - start).total_seconds()
class MLReproducibilityLedger:
"""Main ledger class for managing ML reproducibility records"""
def __init__(self, storage_path: str = "./ml_reproducibility_ledger"):
"""
Initialize ledger with storage directory
Args:
storage_path: Directory to store ledger records
"""
self.storage_path = Path(storage_path)
self.storage_path.mkdir(parents=True, exist_ok=True)
self.runs_index_path = self.storage_path / "runs_index.json"
self._load_index()
def _load_index(self):
"""Load or create runs index"""
if self.runs_index_path.exists():
with open(self.runs_index_path, 'r') as f:
self.runs_index = json.load(f)
else:
self.runs_index = {
"version": "1.0",
"created_at": datetime.datetime.utcnow().isoformat(),
"runs": {}
}
self._save_index()
def _save_index(self):
"""Save runs index"""
with open(self.runs_index_path, 'w') as f:
json.dump(self.runs_index, f, indent=2)
def create_run(
self,
experiment_name: str,
run_name: str,
dataset_info: DatasetInfo,
pipeline_dag: PipelineDAG,
tags: List[str] = None,
notes: str = ""
) -> MLRun:
"""
Create a new ML run record
Args:
experiment_name: Name of experiment
run_name: Name of specific run
dataset_info: Dataset metadata
pipeline_dag: Pipeline DAG structure
tags: Optional tags for filtering
notes: Optional notes
Returns:
MLRun object
"""
run_id = str(uuid.uuid4())
timestamp = datetime.datetime.utcnow().isoformat()
run = MLRun(
run_id=run_id,
experiment_name=experiment_name,
run_name=run_name,
status=RunStatus.RUNNING,
start_time=timestamp,
dataset=dataset_info,
environment=self._capture_environment(), # Auto-capture environment
pipeline=pipeline_dag,
tags=tags or [],
notes=notes
)
# Save run record
run_path = self.storage_path / f"run_{run_id}.json"
with open(run_path, 'w') as f:
json.dump(asdict(run), f, indent=2, default=str)
# Update index
self.runs_index["runs"][run_id] = {
"experiment": experiment_name,
"run_name": run_name,
"status": run.status.value,
"start_time": timestamp,
"dataset_hash": dataset_info.dataset_hash,
"pipeline_dag_id": pipeline_dag.dag_id,
"tags": tags or []
}
self._save_index()
return run
def update_run_status(self, run_id: str, status: RunStatus):
"""Update run status"""
run = self.get_run(run_id)
if not run:
raise ValueError(f"Run {run_id} not found")
run.status = status
if status == RunStatus.COMPLETED or status == RunStatus.FAILED:
run.end_time = datetime.datetime.utcnow().isoformat()
if run.start_time:
start = datetime.datetime.fromisoformat(run.start_time)
end = datetime.datetime.fromisoformat(run.end_time)
run.duration_seconds = (end - start).total_seconds()
# Save updated run
run_path = self.storage_path / f"run_{run_id}.json"
with open(run_path, 'w') as f:
json.dump(asdict(run), f, indent=2, default=str)
# Update index
self.runs_index["runs"][run_id]["status"] = status.value
if run.end_time:
self.runs_index["runs"][run_id]["end_time"] = run.end_time
self._save_index()
def log_metrics(self, run_id: str, metrics: Dict[str, float]):
"""Log metrics for a run"""
run = self.get_run(run_id)
if not run:
raise ValueError(f"Run {run_id} not found")
run.metrics.update(metrics)
# Save updated run
run_path = self.storage_path / f"run_{run_id}.json"
with open(run_path, 'w') as f:
json.dump(asdict(run), f, indent=2, default=str)
def log_artifacts(self, run_id: str, artifacts: Dict[str, str]):
"""Log artifact paths for a run"""
run = self.get_run(run_id)
if not run:
raise ValueError(f"Run {run_id} not found")
run.artifacts.update(artifacts)
# Save updated run
run_path = self.storage_path / f"run_{run_id}.json"
with open(run_path, 'w') as f:
json.dump(asdict(run), f, indent=2, default=str)
def get_run(self, run_id: str) -> Optional[MLRun]:
"""Retrieve a specific run"""
run_path = self.storage_path / f"run_{run_id}.json"
if not run_path.exists():
return None
with open(run_path, 'r') as f:
data = json.load(f)
# Convert back to dataclass
return MLRun(**data)
def get_runs_by_experiment(self, experiment_name: str) -> List[MLRun]:
"""Get all runs for an experiment"""
runs = []
for run_id, run_meta in self.runs_index["runs"].items():
if run_meta["experiment"] == experiment_name:
run = self.get_run(run_id)
if run:
runs.append(run)
return runs
def get_runs_by_dataset(self, dataset_hash: str) -> List[MLRun]:
"""Get all runs using a specific dataset version"""
runs = []
for run_id, run_meta in self.runs_index["runs"].items():
if run_meta.get("dataset_hash") == dataset_hash:
run = self.get_run(run_id)
if run:
runs.append(run)
return runs
def get_runs_by_pipeline(self, pipeline_dag_id: str) -> List[MLRun]:
"""Get all runs using a specific pipeline"""
runs = []
for run_id, run_meta in self.runs_index["runs"].items():
if run_meta.get("pipeline_dag_id") == pipeline_dag_id:
run = self.get_run(run_id)
if run:
runs.append(run)
return runs
def search_runs(
self,
experiment: Optional[str] = None,
status: Optional[RunStatus] = None,
tags: Optional[List[str]] = None,
min_metric: Optional[Dict[str, float]] = None
) -> List[MLRun]:
"""
Search runs with filters
Args:
experiment: Filter by experiment name
status: Filter by run status
tags: Filter by tags (runs must have ALL specified tags)
min_metric: Filter by minimum metric values {metric_name: min_value}
Returns:
List of matching MLRun objects
"""
runs = []
for run_id in self.runs_index["runs"]:
run = self.get_run(run_id)
if not run:
continue
# Apply filters
if experiment and run.experiment_name != experiment:
continue
if status and run.status != status:
continue
if tags and not all(tag in run.tags for tag in tags):
continue
if min_metric:
for metric, min_val in min_metric.items():
if metric not in run.metrics or run.metrics[metric] < min_val:
continue
runs.append(run)
return runs
def export_run(self, run_id: str, export_path: str):
"""Export complete run record to directory"""
run = self.get_run(run_id)
if not run:
raise ValueError(f"Run {run_id} not found")
export_dir = Path(export_path) / run_id
export_dir.mkdir(parents=True, exist_ok=True)
# Save main run record
with open(export_dir / "run_record.json", 'w') as f:
json.dump(asdict(run), f, indent=2, default=str)
# Save DAG visualization if graphviz available
try:
dot = run.pipeline.to_graphviz()
dot.render(export_dir / "pipeline_dag", format='png', cleanup=True)
except:
pass
# Save dataset hash file for verification
with open(export_dir / "dataset_hash.txt", 'w') as f:
f.write(f"Algorithm: {run.dataset.hash_algorithm}\n")
f.write(f"Hash: {run.dataset.dataset_hash}\n")
print(f"Exported run {run_id} to {export_dir}")
def compare_runs(self, run_id1: str, run_id2: str) -> Dict[str, Any]:
"""Compare two runs and return differences"""
run1 = self.get_run(run_id1)
run2 = self.get_run(run_id2)
if not run1 or not run2:
raise ValueError("One or both runs not found")
comparison = {
"run_1": run_id1,
"run_2": run_id2,
"dataset": {
"same_dataset": run1.dataset.dataset_hash == run2.dataset.dataset_hash,
"hash_1": run1.dataset.dataset_hash,
"hash_2": run2.dataset.dataset_hash
},
"environment": {
"python_same": run1.environment.python_version == run2.environment.python_version,
"package_diff": self._compare_pip_freeze(
run1.environment.pip_freeze,
run2.environment.pip_freeze
)
},
"pipeline": {
"same_structure": len(run1.pipeline.steps) == len(run2.pipeline.steps),
"step_count_1": len(run1.pipeline.steps),
"step_count_2": len(run2.pipeline.steps)
},
"metrics": self._compare_metrics(run1.metrics, run2.metrics)
}
return comparison
def _compare_pip_freeze(self, freeze1: List[str], freeze2: List[str]) -> Dict:
"""Compare pip freeze outputs"""
pkgs1 = {line.split('==')[0]: line for line in freeze1 if '==' in line}
pkgs2 = {line.split('==')[0]: line for line in freeze2 if '==' in line}
all_pkgs = set(pkgs1.keys()) | set(pkgs2.keys())
diff = {}
for pkg in all_pkgs:
if pkg not in pkgs1:
diff[pkg] = {"status": "only_in_run2", "version": pkgs2[pkg]}
elif pkg not in pkgs2:
diff[pkg] = {"status": "only_in_run1", "version": pkgs1[pkg]}
elif pkgs1[pkg] != pkgs2[pkg]:
diff[pkg] = {
"status": "different",
"run1_version": pkgs1[pkg],
"run2_version": pkgs2[pkg]
}
return diff
def _compare_metrics(self, metrics1: Dict, metrics2: Dict) -> Dict:
"""Compare metrics dictionaries"""
all_metrics = set(metrics1.keys()) | set(metrics2.keys())
comparison = {}
for metric in all_metrics:
if metric not in metrics1:
comparison[metric] = {"status": "only_in_run2", "value": metrics2[metric]}
elif metric not in metrics2:
comparison[metric] = {"status": "only_in_run1", "value": metrics1[metric]}
elif metrics1[metric] != metrics2[metric]:
comparison[metric] = {
"status": "different",
"run1_value": metrics1[metric],
"run2_value": metrics2[metric],
"difference": metrics2[metric] - metrics1[metric]
}
else:
comparison[metric] = {"status": "equal", "value": metrics1[metric]}
return comparison
def _capture_environment(self) -> EnvironmentSnapshot:
"""Capture current environment state"""
# System info
system_info = {
"system": platform.system(),
"release": platform.release(),
"version": platform.version(),
"machine": platform.machine(),
"processor": platform.processor(),
"node": platform.node()
}
# Python info
python_version = platform.python_version()
python_executable = sys.executable
# Pip freeze
try:
pip_freeze = subprocess.check_output(
[sys.executable, "-m", "pip", "freeze"],
stderr=subprocess.STDOUT
).decode('utf-8').strip().split('\n')
except Exception as e:
pip_freeze = [f"Error capturing pip freeze: {str(e)}"]
# Conda environment (if available)
conda_env = None
try:
conda_env = subprocess.check_output(
["conda", "env", "export"],
stderr=subprocess.STDOUT
).decode('utf-8')
except:
pass
# GPU info (if available)
gpu_info = None
try:
import torch
if torch.cuda.is_available():
gpu_info = {
"cuda_version": torch.version.cuda,
"gpu_count": torch.cuda.device_count(),
"gpu_names": [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())]
}
except ImportError:
try:
# Try TensorFlow
import tensorflow as tf
gpus = tf.config.list_physical_devices('GPU')
if gpus:
gpu_info = {
"gpu_count": len(gpus),
"gpu_names": [gpu.name for gpu in gpus]
}
except ImportError:
pass
# Environment variables (filter sensitive ones)
env_vars = {}
sensitive_keys = {'password', 'secret', 'token', 'key', 'credential'}
for key, value in os.environ.items():
if not any(sensitive in key.lower() for sensitive in sensitive_keys):
env_vars[key] = value
return EnvironmentSnapshot(
python_version=python_version,
pip_freeze=pip_freeze,
conda_env=conda_env,
system_info=system_info,
environment_variables=env_vars,
gpu_info=gpu_info
)
# Utility functions
def compute_dataset_hash(dataset_path: str, hash_algorithm: str = "sha256") -> Dict[str, Any]:
"""
Compute hash for a dataset directory
Args:
dataset_path: Path to dataset directory
hash_algorithm: Hash algorithm to use
Returns:
Dict with dataset hash and individual file hashes
"""
dataset_path = Path(dataset_path)
if not dataset_path.exists():
raise FileNotFoundError(f"Dataset path does not exist: {dataset_path}")
if not dataset_path.is_dir():
raise ValueError(f"Dataset path must be a directory: {dataset_path}")
hash_func = getattr(hashlib, hash_algorithm)
file_hashes = {}
all_hashes = []
total_size = 0
# Walk through all files
for file_path in sorted(dataset_path.rglob("*")):
if file_path.is_file():
rel_path = str(file_path.relative_to(dataset_path))
file_hash = hash_func()
with open(file_path, 'rb') as f:
while chunk := f.read(8192):
file_hash.update(chunk)
file_hashes[rel_path] = file_hash.hexdigest()
all_hashes.append(f"{rel_path}:{file_hashes[rel_path]}")
total_size += file_path.stat().st_size
# Create dataset hash from all file hashes
dataset_hash = hash_func()
for hash_str in sorted(all_hashes):
dataset_hash.update(hash_str.encode())
return {
"dataset_hash": dataset_hash.hexdigest(),
"file_hashes": file_hashes,
"size_bytes": total_size,
"file_count": len(file_hashes)
}
def create_pipeline_dag_from_steps(
dag_id: str,
name: str,
steps: List[Dict[str, Any]],
edges: List[Dict[str, str]]
) -> PipelineDAG:
"""
Helper to create PipelineDAG from step definitions
Args:
dag_id: Unique DAG identifier
name: Human-readable name
steps: List of step definitions (dicts with step_id, step_name, step_type, parameters)
edges: List of edge definitions {"from": "step_id", "to": "step_id"}
Returns:
PipelineDAG object
"""
pipeline_steps = []
for step_def in steps:
pipeline_steps.append(PipelineStep(
step_id=step_def["step_id"],
step_name=step_def["step_name"],
step_type=step_def["step_type"],
parameters=step_def.get("parameters", {}),
input_artifacts=step_def.get("input_artifacts", []),
output_artifacts=step_def.get("output_artifacts", []),
code_version=step_def.get("code_version"),
runtime_config=step_def.get("runtime_config", {})
))
return PipelineDAG(
dag_id=dag_id,
name=name,
description=steps[0].get("description", "") if steps else "",
steps=pipeline_steps,
edges=edges,
root_steps=[],
leaf_steps=[]
)
# Example usage
if __name__ == "__main__":
# Initialize ledger
ledger = MLReproducibilityLedger("./reproducibility_ledger")
# Compute dataset hash
dataset_hash_info = compute_dataset_hash("./data/raw")
dataset_info = DatasetInfo(
name="customer_churn",
version="v1.0",
path="./data/raw",
dataset_hash=dataset_hash_info["dataset_hash"],
file_hashes=dataset_hash_info["file_hashes"],
size_bytes=dataset_hash_info["size_bytes"]
)
# Define pipeline DAG
pipeline_steps = [
{
"step_id": "load_data",
"step_name": "Load Data",
"step_type": "data_ingestion",
"parameters": {"file_path": "./data/raw/churn.csv"},
"output_artifacts": ["./artifacts/raw_data.parquet"]
},
{
"step_id": "preprocess",
"step_name": "Preprocess Data",
"step_type": "preprocessing",
"input_artifacts": ["./artifacts/raw_data.parquet"],
"parameters": {"drop_na": True, "scale_features": True},
"output_artifacts": ["./artifacts/processed_data.parquet"]
},
{
"step_id": "train",
"step_name": "Train Model",
"step_type": "training",
"input_artifacts": ["./artifacts/processed_data.parquet"],
"parameters": {"model_type": "random_forest", "n_estimators": 100},
"output_artifacts": ["./models/model.pkl"]
},
{
"step_id": "evaluate",
"step_name": "Evaluate Model",
"step_type": "evaluation",
"input_artifacts": ["./models/model.pkl", "./artifacts/processed_data.parquet"],
"parameters": {"metrics": ["accuracy", "f1"]},
"output_artifacts": ["./metrics/evaluation.json"]
}
]
pipeline_edges = [
{"from": "load_data", "to": "preprocess"},
{"from": "preprocess", "to": "train"},
{"from": "train", "to": "evaluate"}
]
pipeline_dag = create_pipeline_dag_from_steps(
dag_id="churn_prediction_v1",
name="Customer Churn Prediction Pipeline",
steps=pipeline_steps,
edges=pipeline_edges
)
# Validate DAG
dag_errors = pipeline_dag.validate()
if dag_errors:
print(f"DAG validation errors: {dag_errors}")
sys.exit(1)
# Create run
try:
run = ledger.create_run(
experiment_name="churn_prediction",
run_name="experiment_001",
dataset_info=dataset_info,
pipeline_dag=pipeline_dag,
tags=["production", "random_forest"],
notes="Initial baseline run with default parameters"
)
print(f"Created run: {run.run_id}")
# Simulate running pipeline
print("Running pipeline...")
# ... your pipeline code here ...
# Update status and log metrics
ledger.update_run_status(run.run_id, RunStatus.COMPLETED)
ledger.log_metrics(run.run_id, {
"accuracy": 0.85,
"f1": 0.82,
"roc_auc": 0.88
})
# Export run for sharing
ledger.export_run(run.run_id, "./reproducibility_exports")
# Compare with previous run (if exists)
previous_runs = ledger.get_runs_by_experiment("churn_prediction")
if len(previous_runs) > 1:
comparison = ledger.compare_runs(previous_runs[0].run_id, run.run_id)
print(f"Comparison with previous run: {json.dumps(comparison, indent=2)}")
except Exception as e:
print(f"Error: {e}")
Key Features:
-
Complete Reproducibility Capture:
- Dataset hashes with per-file verification
- Full environment snapshot (Python packages, system info, GPU, env vars)
- Pipeline DAG with step dependencies and parameters
-
Structured Storage:
- JSON-based storage with run index
- Individual run files with all metadata
- Export functionality for sharing
-
Query & Comparison:
- Search runs by experiment, dataset, pipeline, tags, metrics
- Compare runs to identify differences
- Track dataset versions across runs
-
Validation:
- DAG cycle detection
- Step reference validation
- Hash verification
-
Visualization:
- Graphviz DAG generation (optional)
Usage Patterns:
# 1. Start a new run
ledger = MLReproducibilityLedger()
run = ledger.create_run(
experiment_name="my_experiment",
run_name="baseline",
dataset_info=my_dataset_info,
pipeline_dag=my_pipeline_dag
)
# 2. During pipeline execution
ledger.log_metrics(run.run_id, {"accuracy": 0.92})
ledger.log_artifacts(run.run_id, {"model": "./models/model.pkl"})
# 3. Complete the run
ledger.update_run_status(run.run_id, RunStatus.COMPLETED)
# 4. Query runs
runs = ledger.search_runs(
experiment="my_experiment",
min_metric={"accuracy": 0.90}
)
# 5. Compare two runs
diff = ledger.compare_runs(run1_id, run2_id)
# 6. Export for reproducibility
ledger.export_run(run.run_id, "./exports")
Storage Structure:
reproducibility_ledger/
├── runs_index.json # Index of all runs
├── run_<uuid>.json # Individual run records
├── reproducibility_exports/ # Exported runs
└── pipeline_dags/ # (optional) Stored DAG definitions
Integration Tips:
- Add to your pipeline:
# At the beginning of your pipeline
ledger = MLReproducibilityLedger()
run = ledger.create_run(...)
# After each step
ledger.log_artifacts(run.run_id, {"step_output": output_path})
# At the end
ledger.update_run_status(run.run_id, RunStatus.COMPLETED)
-
CI/CD Integration:
- Auto-generate ledger entries for every pipeline run
- Block deployments if dataset/pipeline changed unexpectedly
- Generate reproducibility reports
-
Collaboration:
- Export runs as JSON bundles
- Share via
ledger.export_run()
- Import with
ledger.import_run() (to be implemented)
-
Monitoring:
- Query for runs with specific dataset versions
- Track drift by comparing metrics across runs
- Audit trail for compliance
This system provides end-to-end reproducibility tracking that meets ML engineering best practices and can integrate with existing ML pipelines (Airflow, Kubeflow, Prefect, etc.).