We are going to design a testbed for numerical reproducibility in ML pipelines. The goal is to detect floating-point drift across different hardware (e.g., CPU vs GPU, or different GPU models) and software versions (e.g., different versions of CUDA, cuDNN, or deep learning frameworks).
The testbed should have the following components:
-
Instrumentation: We need to capture the numerical outputs (tensors) at key points in the ML pipeline (e.g., after each layer, or at the end of the model). We'll also capture the hardware and software environment.
-
Tolerance Policy: Define what level of numerical difference is acceptable. This might be a relative or absolute tolerance, and possibly with a tolerance per data type (float16, float32, etc.). We might also want to consider the magnitude of the values (e.g., a tolerance that scales with the magnitude).
-
CI Integration: The testbed should be integrable into a continuous integration system (like GitHub Actions, GitLab CI, etc.) so that we can run the same test on different hardware/software configurations and compare the results.
Steps:
a. Test Definition: We define a set of test cases (models and inputs) that are representative of the pipeline. We also define the points of instrumentation (which layers to check).
b. Instrumentation Code: We modify the model to output intermediate tensors at the specified points. We also capture the environment (hardware, software versions).
c. Execution on Multiple Platforms: We run the same test on different hardware/software configurations.
d. Comparison and Reporting: We compare the outputs from the different runs according to the tolerance policy. We report any drift that exceeds the tolerance.
e. CI Integration: We set up the CI to run the tests on multiple platforms and collect the results.
Implementation Plan:
-
Test Definition:
- We can have a configuration file (YAML or JSON) that defines:
- model architecture (or a way to load a model, e.g., from a file)
- input data (random or fixed seeds)
- list of layer names (or indices) to instrument
- tolerance policy per data type (or global)
-
Instrumentation:
- We can use hooks or forward hooks in PyTorch (or similar in TensorFlow) to capture the outputs of the specified layers.
- We will also capture the final output and the loss (if any).
- We need to save the tensors in a way that we can compare them later. We can save them as numpy arrays or in a serialized format (like HDF5, or just .npy files). We also need to store the metadata (environment, test configuration, etc.).
-
Execution:
- We run the same test on different machines (or in different CI jobs) and save the outputs (and environment) in a known location (e.g., an artifact directory).
-
Comparison:
- We have a baseline (maybe the first run, or a designated reference run) and then compare other runs against the baseline.
- We use the tolerance policy to check if the maximum absolute or relative difference (over all elements) is within tolerance.
- We might want to compute statistics (max, mean, median of absolute/relative differences) and then check if they are within tolerance.
-
CI Integration:
- We set up a matrix of jobs in CI (e.g., one job for CPU, one for GPU with specific CUDA version, etc.).
- Each job runs the test and saves the outputs as artifacts.
- Then we have a job that collects the artifacts from all jobs and runs the comparison.
- We can also set up a baseline run (maybe on a reference machine) and then compare every other run against that baseline.
-
Tolerance Policy:
- We can define a tolerance for each data type (e.g., float16: atol=1e-3, rtol=1e-3; float32: atol=1e-6, rtol=1e-5). We might also have a global policy that overrides per data type.
- We can use
numpy.allclose or torch.allclose with the given tolerances.
-
Reporting:
- We want a clear report that shows which test failed, which layers, and the maximum difference.
Let's design a modular system:
We'll have:
testbed/config.py: defines the configuration (using a config file and environment).
testbed/instrument.py: for instrumenting the model and capturing outputs.
testbed/runner.py: runs the model with the given configuration and saves the outputs.
testbed/comparator.py: compares two sets of outputs (from two runs) and reports differences.
testbed/ci.py: CI integration scripts (or we can use the CI configuration files directly, but we can have a helper script to set up the matrix and collect artifacts).
However, note that the CI integration might be specific to the CI system. We can provide examples for GitHub Actions and GitLab CI.
Alternatively, we can design it as a Python package that can be installed and then run from the command line.
Let's design a command line interface:
We have two main commands:
-
testbed run <config_file> [--output-dir OUTPUT_DIR]: runs the test and saves the outputs (and environment) to the output directory.
-
testbed compare <run1_dir> <run2_dir> [--tolerance-file TOLERANCE_FILE]: compares two runs and reports.
Then, in CI, we can:
- In each job, run
testbed run with the same config but on different hardware.
- Then, have a job that runs
testbed compare for each pair (or against a baseline) and fails if any difference exceeds tolerance.
But note: we might want to compare multiple runs (more than two). So we can have:
testbed compare-group <run_dir1> <run_dir2> ... [--baseline BASELINE_DIR]
which will compare every run in the group to the baseline (or all against all?).
Alternatively, we can have a baseline run and then compare each subsequent run to the baseline.
We can also have a testbed summary that generates a markdown or HTML report.
Let's break down:
Configuration file (YAML) example:
model:
type: "torchvision.models.resnet50"
pretrained: true
# or we can load from a file: checkpoint: "path/to/model.pth"
input:
type: "random"
shape: [1, 3, 224, 224]
seed: 1234
# or from a file: path: "input.npy"
instrumentation:
layers:
- "conv1"
- "layer1.0.conv1"
- "fc"
# we can also specify by type? or by index?
# we can also have a list of layer types to capture.
tolerance:
float16:
atol: 1e-3
rtol: 1e-3
float32:
atol: 1e-6
rtol: 1e-5
# default for other types? or global default?
# We can also have an option to include the environment (which is always captured) but we might want to ignore certain environment variables?
Running the test:
We'll create a directory structure for the output:
run-/
config.yaml (copy of the config)
environment.json (hardware, software versions)
outputs/
layer_name0.npy
layer_name1.npy
...
final_output.npy
# maybe also the loss?
Comparison:
We compare the same layer outputs (by name) between two runs.
Steps for comparison:
-
Load the outputs for both runs (for each layer that is in both runs).
-
For each layer, check the data type and use the corresponding tolerance (or global if not specified).
-
Compute the absolute and relative differences (if the values are not near zero?).
-
Report:
- Pass/Fail for each layer.
- Maximum absolute difference and maximum relative difference (and maybe mean, median).
- The indices (if any) where the tolerance is exceeded.
-
If any layer fails, the comparison returns non-zero.
CI Example (GitHub Actions):
We can have a matrix:
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
# For GPU, we can specify a GPU runner? But note: GitHub Actions has limited GPU runners.
# Alternatively, we can have separate jobs for CPU and GPU.
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install dependencies
run: |
pip install torch torchvision
pip install -e . # if we are installing our testbed package
- name: Run test
run: |
testbed run config.yaml --output-dir output_${{ matrix.os }}
- name: Upload artifact
uses: actions/upload-artifact@v2
with:
name: outputs_${{ matrix.os }}
path: output_${{ matrix.os }}/
Then a separate job to compare:
compare:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Download artifacts
uses: actions/download-artifact@v2
with:
path: artifacts/
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install dependencies
run: |
pip install torch torchvision
pip install -e .
- name: Compare runs
run: |
# We assume the artifacts are in artifacts/outputs_os1, artifacts/outputs_os2, etc.
# We want to compare all against the first one (or a designated baseline).
# Let's say we have two runs: ubuntu and windows.
testbed compare-group artifacts/outputs_ubuntu-latest artifacts/outputs_windows-latest --baseline artifacts/outputs_ubuntu-latest
But note: we might have more than two. We can have a matrix of multiple configurations (different CUDA versions, etc.). Then we want to compare each non-baseline to the baseline.
Alternatively, we can have a job that runs on a reference machine (the baseline) and then the other jobs compare to that.
We can also have a job that runs the comparison only if there are multiple runs (by checking the number of artifacts).
However, note that the baseline run might be on a different machine (and we might not have the baseline artifact in the same workflow). So we might need to store the baseline in a separate location (like a release artifact) and then compare against that.
For simplicity, in the same workflow we can have:
- job1: run on CPU (or a reference GPU) -> baseline
- job2: run on GPU1
- job3: run on GPU2
Then the compare job runs after all and compares job2 and job3 to job1.
But what if we want to compare GPU1 vs GPU2? That might be useful too.
We can design the compare-group command to compare every run in the group to every other run? That might be too many. Instead, we can have:
testbed compare-group --baseline baseline_dir run1_dir run2_dir ...
and then compare each run to the baseline.
Alternatively, we can have:
testbed compare-matrix that takes a list of directories and generates a matrix of comparisons.
But for CI, we usually want to compare against a known good baseline (the reference) and then report if any drift.
Let's stick to comparing each run to the baseline.
Implementation Details:
We'll write the code in Python, and we assume the user is using PyTorch (but we can extend to TensorFlow later). We'll design the instrumentation for PyTorch.
Steps for testbed run:
- Load the configuration.
- Set up the model (and load pretrained weights if specified).
- Set up the input (random or from file) with the given seed.
- Register forward hooks on the specified layers (by name). We need a way to get the layer by name. We can traverse the model's modules and match by name (using the full module name as in
model.named_modules()).
- Run the model (forward pass) and capture the outputs of the hooked layers and the final output.
- Save the outputs (as numpy arrays) in the output directory, with the layer name as the filename (and maybe append the data type?).
- Save the environment information (using
platform and torch and cuda if available, etc.) as JSON.
- Save the configuration.
Steps for testbed compare:
- Load the two runs (their output directories).
- For each layer that is present in both runs, load the two numpy arrays.
- Check the data type and get the tolerance (from the tolerance policy). If the tolerance is not specified for that data type, use a global default (or fail?).
- Use
np.allclose with atol and rtol to check. But note: allclose returns a single boolean for the entire array. We might want to know the maximum difference and where it occurs.
We can do:
diff = np.abs(a - b)
max_abs_diff = np.max(diff)
rel_diff = diff / (np.abs(b) + 1e-12) # avoid division by zero
max_rel_diff = np.max(rel_diff)
Then we check:
if max_abs_diff > atol and max_rel_diff > rtol:
# fail? Actually, the condition in allclose is:
# all(|a - b| <= atol + rtol * |b|)
# So we need to check for each element? But we want to know the maximum violation.
# We can compute the condition per element and then find the maximum violation.
tol = atol + rtol * np.abs(b)
violation = diff - tol
max_violation = np.max(violation)
Then we report:
- For each layer, the maximum absolute difference, maximum relative difference, and maximum violation (how much we exceed the tolerance).
If max_violation > 0, then the layer fails.
- Report per layer and overall (if any layer fails, then the comparison fails).
Tolerance Policy:
We can have a hierarchy:
- Global default (atol, rtol) for any data type not specified.
- Per data type (like float16, float32, bfloat16, etc.)
We can store the tolerance in the configuration file, but also allow an external tolerance file (so that we can adjust without changing the test config).
The tolerance file could be a YAML with:
default:
atol: 1e-6
rtol: 1e-5
float16:
atol: 1e-3
rtol: 1e-3
Then, when comparing, we look up the tolerance by the data type of the array (using a.dtype). We can map numpy dtypes to string keys (e.g., 'float16', 'float32').
We might also consider that the same layer might have different dtypes in different runs? That would be a failure.
Environment Capture:
We'll capture:
- Python version
- PyTorch version (and CUDA version if available)
- CUDA version (from
torch.version.cuda)
- cuDNN version (if available, from
torch.backends.cudnn.version())
- GPU model (if available, using
torch.cuda.get_device_name(0) if CUDA available)
- CPU info (using
platform and cpuinfo if installed)
- OS information (from
platform)
We can also capture the command line arguments and the configuration.
Extensibility:
We might want to support TensorFlow in the future. We can design the instrumentation to be framework-agnostic by having a base class and then implementations for PyTorch and TensorFlow.
But for now, we focus on PyTorch.
Code Structure:
We'll create a package testbed:
testbed/
init.py
config.py
instrument.py
runner.py
comparator.py
ci.py (maybe not needed, we can have example CI configs in a separate directory)
We'll use argparse for the command line.
Let's write the code for each module.
config.py:
This will load the configuration from a YAML file and also the tolerance file (if provided). We'll define a class TestConfig that holds:
- model: a string (module path) or a checkpoint path? We can have two ways: either by model name (from torchvision) or by a script that returns a model. We can also allow a custom model script.
We'll keep it simple: the model is a string that we can import and then call with pretrained=True if specified? Or we can have:
model:
import_path: "torchvision.models.resnet50"
pretrained: true
checkpoint: null # if provided, load from checkpoint
But then we need to handle the checkpoint loading.
Alternatively, we can have:
model:
type: "resnet50"
library: "torchvision"
pretrained: true
and then we have a mapping from library and type to a function that returns the model.
We can also allow a custom script:
model:
script: "path/to/model.py"
function: "get_model"
args: {}
We'll design the config to be flexible.
For the input:
input:
type: "random" # or "file"
shape: [1, 3, 224, 224]
seed: 1234
path: null # if type is file
For instrumentation:
instrumentation:
layers: [] # list of layer names (as in named_modules)
# or we can have a list of regex patterns?
For tolerance:
tolerance:
default:
atol: 1e-6
rtol: 1e-5
float16:
atol: 1e-3
rtol: 1e-3
We'll also capture the data type of the model's parameters? Not necessary.
instrument.py:
We'll have a function instrument_model(model, layer_names) that returns a dictionary mapping layer name to the output tensor.
We can use forward hooks:
def get_layer_output(name):
def hook(module, input, output):
# store output in a dictionary
layer_outputs[name] = output.detach().cpu().numpy()
return hook
layer_outputs = {}
handles = []
for name, module in model.named_modules():
if name in layer_names:
handle = module.register_forward_hook(get_layer_output(name))
handles.append(handle)
# Then after forward, we remove the hooks.
for handle in handles:
handle.remove()
But note: we might want to capture the output of a layer even if it's called multiple times? Then we might need to capture each time? But in a typical model, each layer is called once in the forward pass. We assume that.
Alternatively, we can capture the output of the layer by overriding the forward method? But hooks are simpler.
Also, note that some layers might have multiple outputs (like a tuple). We'll assume the output is a tensor, or we can convert a tuple to a tuple of numpy arrays? But then the comparison becomes more complex. We'll assume the output is a single tensor for now.
We can also capture the input to the layer? But the requirement is for outputs.
runner.py:
Steps:
- Load config.
- Set up the model (and device).
- Set up the input.
- Instrument the model.
- Run forward.
- Save the outputs (and final output) and environment.
We'll save:
- For each layer in the instrumentation list, save a numpy array with the name of the layer (replace dots with underscores? or keep as is? but file system might not like dots). We can replace '/' and '.' with '_'.
But note: the layer names might have '.' (like 'layer1.0.conv1'). We can use a safe filename by replacing non-alphanumeric with '_'.
Alternatively, we can save in a structured format (like HDF5) with the layer name as the key. But then we need to read HDF5 in the comparator. Let's use numpy for simplicity.
We'll create a directory outputs/ and save each layer as layer_name.npy.
Also save the final output as final_output.npy.
And save the environment as environment.json.
comparator.py:
We'll have a function compare_runs(run1_dir, run2_dir, tolerance_config) that returns a report.
Steps:
- Load the environment for both runs (just for information?).
- For each layer file in the
outputs/ directory of run1, check if the same layer exists in run2.
- Load the two arrays.
- Check if the data types match? If not, fail.
- Get the tolerance for the data type (from tolerance_config).
- Compute the maximum absolute and relative differences and check against the tolerance.
- Record the results.
We'll also compare the final output.
We'll return a dictionary with:
{
"run1": run1_dir,
"run2": run2_dir,
"layers": {
"layer_name": {
"max_abs_diff": ...,
"max_rel_diff": ...,
"max_violation": ...,
"pass": True/False,
"shape": ...,
"dtype": ...
}
},
"final_output": { ... same as above ... },
"overall": True/False # if all layers and final output pass
}
And print a summary.
ci.py:
We might not need a separate module for CI. We can have example CI configuration files in a ci/ directory.
Command Line Interface:
We'll use argparse:
import argparse
parser = argparse.ArgumentParser(description='Numerical Reproducibility Testbed')
subparsers = parser.add_subparsers(dest='command')
# run command
parser_run = subparsers.add_parser('run', help='Run a test')
parser_run.add_argument('config', type=str, help='Path to the configuration YAML file')
parser_run.add_argument('--output-dir', type=str, default='output', help='Output directory')
# compare command
parser_compare = subparsers.add_parser('compare', help='Compare two runs')
parser_compare.add_argument('run1', type=str, help='First run directory')
parser_compare.add_argument('run2', type=str, help='Second run directory')
parser_compare.add_argument('--tolerance-file', type=str, default=None, help='Tolerance configuration file (YAML)')
# compare-group command
parser_compare_group = subparsers.add_parser('compare-group', help='Compare multiple runs against a baseline')
parser_compare_group.add_argument('--baseline', type=str, required=True, help='Baseline run directory')
parser_compare_group.add_argument('runs', type=str, nargs='+', help='List of run directories to compare against baseline')
parser_compare_group.add_argument('--tolerance-file', type=str, default=None, help='Tolerance configuration file (YAML)')
Tolerance Configuration:
We'll have a default tolerance configuration in the code, and we can override with a tolerance file.
Example Tolerances:
For float32, we might use atol=1e-6, rtol=1e-5 (like numpy default).
For float16, we use atol=1e-3, rtol=1e-3.
Environment Capture:
We'll create a dictionary with:
env = {
'python_version': platform.python_version(),
'os': platform.platform(),
'torch_version': torch.__version__,
'cuda_version': torch.version.cuda,
'cudnn_version': torch.backends.cudnn.version() if torch.backends.cudnn.is_available() else None,
'gpu_name': torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,
'cpu_info': ... # we can use `cpuinfo.get_cpu_info()` if cpuinfo is installed, else skip.
}
Putting it together:
We'll write the main function that parses the arguments and calls the appropriate function.
Challenges:
- How to handle models that have state (like BatchNorm) that behave differently in train and eval? We should run in eval mode by default? Or let the user specify.
We can add in the config:
model:
eval_mode: true
-
How to handle randomness? We set the seed for the input, but what about the model's internal randomness (like dropout)? We should set the model to eval mode to disable dropout and use running statistics for BatchNorm.
-
We might want to capture the output of a layer after every forward pass? But we assume one forward.
-
We might want to run multiple forward passes (like with different inputs) and then compare? That's more complex. We can start with one forward.
-
We might want to compare the gradients too? That's another dimension. We can extend later.
Future Work:
- Support for TensorFlow.
- Support for multiple inputs and multiple forward passes.
- Support for capturing gradients.
- Support for different tolerance policies (like per-layer tolerance).
Let's start with the basic version.
We'll write the code in a single script for now? Or as a package. Since we want to install it in CI, we should make it a package.
We can create a setup.py and then install with pip install -e ..
But for the purpose of this design, we can write the code as a module.
Let's create the files:
testbed/
init.py
config.py
instrument.py
runner.py
comparator.py
cli.py
And then in setup.py:
from setuptools import setup, find_packages
setup(
name='testbed',
version='0.1',
packages=find_packages(),
install_requires=[
'pyyaml',
'torch',
'torchvision',
'numpy',
'cpuinfo', # optional? we can catch ImportError
],
entry_points={
'console_scripts': [
'testbed=testbed.cli:main',
],
},
)
Now, we write each module.
config.py:
We'll define a class TestConfig that loads the YAML and validates.
instrument.py:
We'll have a function get_layer_outputs(model, input, layer_names) that returns a dictionary of layer outputs (as numpy arrays) and the final output.
runner.py:
We'll have a function run_test(config, output_dir) that does everything and saves the results.
comparator.py:
We'll have:
load_run(run_dir) -> returns a dictionary with:
- 'config': the config used (if saved)
- 'environment': the environment dict
- 'outputs': a dictionary of layer names to numpy arrays (including 'final_output')
`compare_runs(run1, run2, tolerance_config)` -> returns a report.
cli.py:
The main function that parses arguments and calls the appropriate function.
Let's write the code.
Note: This is a design and we are going to write a simplified version.
We assume the model is a PyTorch model and we are doing a single forward pass.
Let's start with config.py:
We'll use yaml.safe_load and then validate the keys.
We'll define a nested class for the configuration? Or just a dictionary. We can use dataclasses for better structure.
But for simplicity, we can use a dictionary and just check for required keys.
However, let's use a dataclass for the top-level config and then nested dataclasses for model, input, etc.
Alternatively, we can use pydantic but that's an extra dependency. We'll stick to standard library and just validate manually.
We'll do:
import yaml
class TestConfig:
def __init__(self, config_dict):
self.model = config_dict['model']
self.input = config_dict['input']
self.instrumentation = config_dict.get('instrumentation', {'layers': []})
self.tolerance = config_dict.get('tolerance', {})
# We can also have a field for eval_mode?
self.eval_mode = config_dict.get('eval_mode', True)
@classmethod
def from_yaml(cls, path):
with open(path) as f:
config_dict = yaml.safe_load(f)
return cls(config_dict)
But we should validate the structure. We'll skip deep validation for now.
instrument.py:
import torch
def get_layer_outputs(model, input_tensor, layer_names, device='cpu'):
model = model.to(device)
input_tensor = input_tensor.to(device)
layer_outputs = {}
# We need to get the full module name for each layer in layer_names.
# We'll create a mapping from module name to module.
named_modules = dict(model.named_modules())
# We'll create a dictionary to store the outputs for each layer name.
# But note: the layer_names might be a subset of the named_modules.
# We define a hook that will store the output for a given layer name.
def make_hook(name):
def hook(module, input, output):
# We assume output is a tensor. If it's a tuple, we take the first? Or we can convert to numpy?
# For now, we only support tensor output.
if isinstance(output, torch.Tensor):
layer_outputs[name] = output.detach().cpu().numpy()
else:
# If it's a tuple, we take the first element? But that might not be what we want.
# We can try to convert the entire output to numpy? But if it's a tuple of tensors, we can convert each.
# However, for comparison we need to have a consistent structure.
# Let's only support tensor for now.
raise NotImplementedError(f"Layer {name} output is not a tensor. Currently only tensor outputs are supported.")
return hook
handles = []
for name in layer_names:
if name not in named_modules:
raise ValueError(f"Layer {name} not found in model.")
module = named_modules[name]
handle = module.register_forward_hook(make_hook(name))
handles.append(handle)
# Run forward
model.eval() # we set to eval mode by default? But the config might have eval_mode.
# Actually, we should set according to config. We'll do that in runner.
with torch.no_grad():
output = model(input_tensor)
# Remove hooks
for handle in handles:
handle.remove()
# Also capture the final output
if isinstance(output, torch.Tensor):
final_output = output.detach().cpu().numpy()
else:
# We can handle tuple? But then we need to save multiple arrays? We'll leave for future.
raise NotImplementedError("Model output is not a tensor. Currently only tensor outputs are supported.")
return layer_outputs, final_output
But note: we are setting the model to eval mode in the function. We should do it outside? Actually, we want to set the model to the mode specified in the config. So we'll do that in the runner.
Alternatively, we can pass a model_mode (train or eval) to the function.
Let's change:
def get_layer_outputs(model, input_tensor, layer_names, device='cpu', model_mode='eval'):
if model_mode == 'eval':
model.eval()
else:
model.train()
... same ...
But note: we are using torch.no_grad() which is typical for evaluation. We might want to compute gradients? Not for now.
runner.py:
Steps:
-
Load config.
-
Set device (if CUDA available, use it? or let the user specify? We can have in config: device: cuda or cpu). We can default to 'cuda' if available, else 'cpu'.
-
Set the random seed for Python, numpy, and torch? We are given a seed for the input, but we might want to set the global seed for reproducibility? We can set:
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
But note: the model might have its own initialization. We are using a pretrained model, so that's fixed. But if we train, we want reproducibility. We are only doing inference.
However, the input is random with a seed. We set that.
-
Create the model (from config).
-
Create the input (from config).
-
Get the layer outputs and final output.
-
Save the outputs.
How to create the model?
We can have:
if 'import_path' in config.model:
# import the model
module = importlib.import_module(config.model['import_path'])
model_class = getattr(module, config.model.get('class', 'model'))
model = model_class(**config.model.get('args', {}))
if config.model.get('pretrained', False):
# how to load pretrained? We can use torchvision.models
# but if it's a custom model, we might need to load from a checkpoint.
# We can have:
if 'checkpoint' in config.model:
model.load_state_dict(torch.load(config.model['checkpoint']))
else:
# try to load pretrained from torchvision? Not generic.
pass
This is getting complex. Let's assume the model is from torchvision and we can load by name.
We can have:
model:
library: torchvision
name: resnet50
pretrained: true
Then:
if config.model['library'] == 'torchvision':
import torchvision.models as models
model = getattr(models, config.model['name'])(pretrained=config.model.get('pretrained', False))
But what about other libraries? We can support:
- torchvision
- custom script
For custom script:
model:
script: "my_model.py"
function: "create_model"
args: {"arg1": value1}
Then:
spec = importlib.util.spec_from_file_location("custom_model", config.model['script'])
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
model = getattr(module, config.model['function'])(**config.model.get('args', {}))
We'll do that.
Similarly for input:
- random: generate random tensor with given shape and seed.
- file: load from a .npy file.
We'll write helper functions.
environment capture:
We'll define a function capture_environment() that returns a dict.
saving:
We'll create the output directory and save:
- config.yaml (the original config)
- environment.json
- outputs/ with each layer as a .npy file and final_output.npy
comparator.py:
We'll define:
def load_run(run_dir):
# load config.yaml? not necessary for comparison, but might be useful.
# load environment.json
# load all .npy files in outputs/ and final_output.npy
pass
def compare_two_runs(run1, run2, tolerance_config):
# run1 and run2 are dictionaries from load_run.
# We compare the outputs.
pass
Tolerance Lookup:
We'll have:
def get_tolerance(dtype, tolerance_config):
# dtype is a numpy dtype (like np.float32)
# Convert to string: dtype.name -> 'float32'
dtype_str = dtype.name
# Look in tolerance_config:
# tolerance_config is a dict with keys like 'float16', 'float32', and 'default'
if dtype_str in tolerance_config:
return tolerance_config[dtype_str]
else:
return tolerance_config.get('default', {'atol': 1e-6, 'rtol': 1e-5})
But note: the tolerance_config might be nested? We have:
tolerance:
default: {atol: 1e-6, rtol: 1e-5}
float16: {atol: 1e-3, rtol: 1e-3}
So in Python, it's a dict with keys 'default', 'float16', etc.
Comparison:
For each layer (and final output) we have two arrays: a and b.
We compute:
diff = np.abs(a - b)
max_abs_diff = np.max(diff)
# For relative, we use the maximum of |b|? Or the maximum of |a| and |b|? We'll use |b| as in numpy allclose.
# But note: if b is zero, then relative difference is infinite? We can avoid by adding a small epsilon.
rel_diff = diff / (np.abs(b) + 1e-12)
max_rel_diff = np.max(rel_diff)
Then we compute the violation per element:
tol = atol + rtol * np.abs(b)
violation = diff - tol
max_violation = np.max(violation)
Then:
pass = max_violation <= 0
But note: np.allclose uses:
np.allclose(a, b, atol=atol, rtol=rtol) # which is equivalent to:
np.all(np.abs(a - b) <= atol + rtol * np.abs(b))
So we can use:
pass = np.allclose(a, b, atol=atol, rtol=rtol)
But then we don't get the max violation. We want to report the max violation even if it passes? Maybe not necessary.
We can do:
if not pass:
# then we report the max violation.
We'll do:
is_close = np.allclose(a, b, atol=atol, rtol=rtol)
max_abs_diff = np.max(diff)
max_rel_diff = np.max(rel_diff)
# We can also compute the maximum violation (how much we exceed the tolerance) only if not close?
But we want to know the max violation even if it passes? It might be positive but very small? Actually, if it passes, then max_violation <= 0.
We can compute:
max_violation = np.max(diff - (atol + rtol * np.abs(b)))
Then:
pass = max_violation <= 0
This is equivalent to allclose.
So we'll use that.
Reporting:
We'll generate a dictionary for each layer and then an overall.
Example:
Let's say we have two runs:
run1 (baseline) and run2.
We compare each layer in run1 that exists in run2.
We also compare the final output.
We'll report:
- For each layer: pass/fail, max_abs_diff, max_rel_diff, max_violation (if fail, then positive).
- Overall: pass if all layers and final output pass.
Implementation:
We'll write the code accordingly.
This is a high-level design. Now we can start implementing.
However, note that the problem asks for a "testbed", so we are expected to provide a working solution.
But since this is a design question, we can stop at the design and maybe write some pseudocode.
Given the complexity, we might want to start with a minimal version and then extend.
Let's summarize the steps for the user:
- Write a configuration file (config.yaml) for the model and input.
- Run
testbed run config.yaml --output-dir run1 on the baseline machine.
- Run the same on other machines, saving to different directories.
- Compare the runs with
testbed compare run1 run2 (or compare-group).
We'll now write the code for each module in a simplified manner.
config.py:
import yaml
class TestConfig:
def __init__(self, config_dict):
self.model = config_dict['model']
self.input = config_dict['input']
self.instrumentation = config_dict.get('instrumentation', {'layers': []})
self.tolerance = config_dict.get('tolerance', {})
self.eval_mode = config_dict.get('eval_mode', True)
self.device = config_dict.get('device', 'cuda' if torch.cuda.is_available() else 'cpu')
@classmethod
def from_yaml(cls, path):
with open(path) as f:
config_dict = yaml.safe_load(f)
return cls(config_dict)
But note: we need to import torch to check for cuda? We can do that in the runner when we create the config? Or we can leave the device as a string and let the runner decide.
Alternatively, we can have the device in the config as a string and then in the runner we set:
device = torch.device(config.device)
But if the config says 'cuda' and there's no CUDA, we should fallback? We can do:
if config.device == 'cuda' and not torch.cuda.is_available():
device = torch.device('cpu')
else:
device = torch.device(config.device)
We'll do that in the runner.
instrument.py:
We'll adjust to use the device and model_mode.
import torch
def get_layer_outputs(model, input_tensor, layer_names, device='cpu', model_mode='eval'):
model = model.to(device)
input_tensor = input_tensor.to(device)
if model_mode == 'eval':
model.eval()
else:
model.train()
layer_outputs = {}
named_modules = dict(model.named_modules())
def make_hook(name):
def hook(module, input, output):
if isinstance(output, torch.Tensor):
layer_outputs[name] = output.detach().cpu().numpy()
else:
raise NotImplementedError(f"Layer {name} output is not a tensor. Currently only tensor outputs are supported.")
return hook
handles = []
for name in layer_names:
if name not in named_modules:
raise ValueError(f"Layer {name} not found in model.")
module = named_modules[name]
handle = module.register_forward_hook(make_hook(name))
handles.append(handle)
with torch.no_grad():
output = model(input_tensor)
for handle in handles:
handle.remove()
if isinstance(output, torch.Tensor):
final_output = output.detach().cpu().numpy()
else:
raise NotImplementedError("Model output is not a tensor. Currently only tensor outputs are supported.")
return layer_outputs, final_output
runner.py:
import os
import json
import torch
import numpy as np
import random
import importlib
import platform
from .config import TestConfig
def capture_environment():
env = {
'python_version': platform.python_version(),
'os': platform.platform(),
'torch_version': torch.__version__,
'cuda_version': torch.version.cuda,
'cudnn_version': torch.backends.cudnn.version() if torch.backends.cudnn.is_available() else None,
'gpu_name': torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,
}
try:
import cpuinfo
env['cpu_info'] = cpuinfo.get_cpu_info()
except ImportError:
env['cpu_info'] = None
return env
def create_model(config):
model_config = config.model
if model_config.get('library') == 'torchvision':
import torchvision.models as models
model = getattr(models, model_config['name'])(pretrained=model_config.get('pretrained', False))
elif 'script' in model_config:
spec = importlib.util.spec_from_file_location("custom_model", model_config['script'])
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
model = getattr(module, model_config.get('function', 'create_model'))(**model_config.get('args', {}))
else:
raise ValueError("Unsupported model configuration. Must specify either 'library' and 'name' or 'script'.")
return model
def create_input(config, device):
input_config = config.input
if input_config['type'] == 'random':
shape = input_config['shape']
seed = input_config.get('seed', None)
if seed is not None:
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
# Generate random tensor between 0 and 1
input_tensor = torch.rand(shape, device=device)
elif input_config['type'] == 'file':
path = input_config['path']
input_tensor = torch.from_numpy(np.load(path)).to(device)
else:
raise ValueError(f"Unsupported input type: {input_config['type']}")
return input_tensor
def run_test(config, output_dir):
os.makedirs(output_dir, exist_ok=True)
# Save the config
with open(os.path.join(output_dir, 'config.yaml'), 'w') as f:
yaml.dump(config.__dict__, f) # but note: config is an object, we can save as dict?
# Set device
if config.device == 'cuda' and not torch.cuda.is_available():
device = torch.device('cpu')
else:
device = torch.device(config.device)
# Create model
model = create_model(config)
model = model.to(device)
# Create input
input_tensor = create_input(config, device)
# Get layer outputs
layer_names = config.instrumentation['layers']
layer_outputs, final_output = get_layer_outputs(model, input_tensor, layer_names, device, model_mode='eval' if config.eval_mode else 'train')
# Save outputs
outputs_dir = os.path.join(output_dir, 'outputs')
os.makedirs(outputs_dir, exist_ok=True)
for name, output in layer_outputs.items():
# Sanitize layer name for filename
safe_name = name.replace('/', '_').replace('.', '_')
np.save(os.path.join(outputs_dir, f'{safe_name}.npy'), output)
np.save(os.path.join(output_dir, 'final_output.npy'), final_output)
# Save environment
env = capture_environment()
with open(os.path.join(output_dir, 'environment.json'), 'w') as f:
json.dump(env, f, indent=2)
print(f"Test run completed. Outputs saved to {output_dir}")
comparator.py:
import os
import json
import numpy as np
def load_run(run_dir):
# Load environment
with open(os.path.join(run_dir, 'environment.json')) as f:
environment = json.load(f)
# Load outputs
outputs_dir = os.path.join(run_dir, 'outputs')
outputs = {}
for filename in os.listdir(outputs_dir):
if filename.endswith('.npy'):
layer_name = filename[:-4] # remove .npy
# We might have sanitized names, but we want to compare by the original layer name?
# Actually, when we save, we sanitize. But when we compare, we need to know which layers correspond.
# We can store a mapping? Or we can just use the sanitized name as the key and then when comparing, we use the same sanitized name.
# But the config might have the original names. We are comparing runs that were run with the same config? Yes, same config.
# So the layer names in the instrumentation list are the same. We sanitize the same way in both runs.
# So we can use the sanitized name as the key.
path = os.path.join(outputs_dir, filename)
outputs[layer_name] = np.load(path)
# Load final output
final_output = np.load(os.path.join(run_dir, 'final_output.npy'))
outputs['final_output'] = final_output
return {
'environment': environment,
'outputs': outputs
}
def get_tolerance(dtype, tolerance_config):
dtype_str = dtype.name
if dtype_str in tolerance_config:
return tolerance_config[dtype_str]
else:
return tolerance_config.get('default', {'atol': 1e-6, 'rtol': 1e-5})
def compare_two_runs(run1, run2, tolerance_config):
report = {
'run1': run1,
'run2': run2,
'layers': {},
'overall': True
}
# Compare each layer that is in both runs
for layer_name in run1['outputs']:
if layer_name not in run2['outputs']:
print(f"Warning: layer {layer_name} not found in run2. Skipping.")
continue
a = run1['outputs'][layer_name]
b = run2['outputs'][layer_name]
if a.dtype != b.dtype:
print(f"Error: dtype mismatch for layer {layer_name}: {a.dtype} vs {b.dtype}")
report['layers'][layer_name] = {
'pass': False,
'error': f'dtype mismatch: {a.dtype} vs {b.dtype}'
}
report['overall'] = False
continue
tol = get_tolerance(a.dtype, tolerance_config)
atol = tol['atol']
rtol = tol['rtol']
# Compute max violation
diff = np.abs(a - b)
tol_per_element = atol + rtol * np.abs(b)
violation = diff - tol_per_element
max_violation = np.max(violation)
pass_layer = max_violation <= 0
if not pass_layer:
report['overall'] = False
report['layers'][layer_name] = {
'pass': pass_layer,
'max_abs_diff': float(np.max(diff)),
'max_rel_diff': float(np.max(diff / (np.abs(b) + 1e-12))),
'max_violation': float(max_violation),
'shape': a.shape,
'dtype': str(a.dtype)
}
return report
def print_report(report):
print(f"Comparing {report['run1']} vs {report['run2']}")
print(f"Overall: {'PASS' if report['overall'] else 'FAIL'}")
for layer_name, layer_report in report['layers'].items():
status = "PASS" if layer_report['pass'] else "FAIL"
print(f"Layer {layer_name}: {status}")
if not layer_report['pass']:
print(f" Max abs diff: {layer_report['max_abs_diff']}")
print(f" Max rel diff: {layer_report['max_rel_diff']}")
print(f" Max violation: {layer_report['max_violation']}")
return report['overall']
cli.py:
import argparse
import yaml
from .runner import run_test
from .comparator import load_run, compare_two_runs, print_report
def main():
parser = argparse.ArgumentParser(description='Numerical Reproducibility Testbed')
subparsers = parser.add_subparsers(dest='command', required=True)
# run command
parser_run = subparsers.add_parser('run', help='Run a test')
parser_run.add_argument('config', type=str, help='Path to the configuration YAML file')
parser_run.add_argument('--output-dir', type=str, default='output', help='Output directory')
# compare command
parser_compare = subparsers.add_parser('compare', help='Compare two runs')
parser_compare.add_argument('run1', type=str, help='First run directory')
parser_compare.add_argument('run2', type=str, help='Second run directory')
parser_compare.add_argument('--tolerance-file', type=str, default=None, help='Tolerance configuration file (YAML)')
# compare-group command
parser_compare_group = subparsers.add_parser('compare-group', help='Compare multiple runs against a baseline')
parser_compare_group.add_argument('--baseline', type=str, required=True, help='Baseline run directory')
parser_compare_group.add_argument('runs', type=str, nargs='+', help='List of run directories to compare against baseline')
parser_compare_group.add_argument('--tolerance-file', type=str, default=None, help='Tolerance configuration file (YAML)')
args = parser.parse_args()
if args.command == 'run':
from .config import TestConfig
config = TestConfig.from_yaml(args.config)
run_test(config, args.output_dir)
elif args.command == 'compare':
# Load tolerance config
if args.tolerance_file:
with open(args.tolerance_file) as f:
tolerance_config = yaml.safe_load(f)
else:
# Use default from the config? But we don't have the config for the runs? We can use a built-in default.
tolerance_config = {
'default': {'atol': 1e-6, 'rtol': 1e-5},
'float16': {'atol': 1e-3, 'rtol': 1e-3}
}
run1_data = load_run(args.run1)
run2_data = load_run(args.run2)
report = compare_two_runs(run1_data, run2_data, tolerance_config)
print_report(report)
elif args.command == 'compare-group':
if args.tolerance_file:
with open(args.tolerance_file) as f:
tolerance_config = yaml.safe_load(f)
else:
tolerance_config = {
'default': {'atol': 1e-6, 'rtol': 1e-5},
'float16': {'atol': 1e-3, 'rtol': 1e-3}
}
baseline_data = load_run(args.baseline)
all_passed = True
for run_dir in args.runs:
run_data = load_run(run_dir)
report = compare_two_runs(baseline_data, run_data, tolerance_config)
passed = print_report(report)
if not passed:
all_passed = False
if all_passed:
print("All runs passed.")
else:
print("Some runs failed.")
exit(1)
if __name__ == '__main__':
main()
Note: The above code is a simplified version. We need to handle errors and edge cases.
For example, in compare_two_runs, we might have layers in run2 that are not in run1? We only compare the layers that are in run1 and also in run2. We could also report extra layers in run2? But since we are using the same config, they should be the same.
We are using the sanitized layer names when saving, so we compare by the sanitized name. But what if two different layer names sanitize to the same? Then we have a collision. We can use a more robust sanitization (like replacing non-alphanumeric with '_' and then appending a number if collision). But for simplicity, we assume no collision.
Also, we are not comparing the environment. We might want to check if the environment is the same? That's up to the user.
This is a basic testbed. We can extend it.
CI Integration:
We can have a directory ci/ with example workflows.
For GitHub Actions, we can have:
.github/workflows/test.yml:
name: Numerical Reproducibility Test
on:
push:
branches: [ main ]
pull_request:
jobs:
test-cpu:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install dependencies
run: |
pip install torch torchvision
pip install -e .
- name: Run test
run: |
testbed run config.yaml --output-dir output_cpu
- name: Upload artifact
uses: actions/upload-artifact@v2
with:
name: output_cpu
path: output_cpu/
test-gpu:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install dependencies
run: |
pip install torch torchvision
pip install -e .
- name: Run test on GPU
run: |
testbed run config.yaml --output-dir output_gpu
env:
CUDA_VISIBLE_DEVICES: 0
- name: Upload artifact
uses: actions/upload-artifact@v2
with:
name: output_gpu
path: output_gpu/
compare:
needs: [test-cpu, test-gpu]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install dependencies
run: |
pip install torch torchvision
pip install -e .
- name: Download artifacts
uses: actions/download-artifact@v2
with:
path: artifacts/
- name: Compare runs
run: |
testbed compare-group --baseline artifacts/output_cpu artifacts/output_gpu
But note: the GPU job might fail if there's no GPU in the runner. GitHub Actions does have GPU runners but they are limited. We might need to request a GPU runner.
Alternatively, we can use a self-hosted runner with GPU.
This is just an example.
Conclusion:
We have designed a testbed for numerical reproducibility in ML pipelines. It instruments the model at specified layers, runs the model on different hardware, and compares the outputs with a tolerance policy. It can be integrated into CI.
This is a starting point and can be extended to support more features (like TensorFlow, multiple inputs, training, etc.).
I'll design a comprehensive numerical reproducibility testbed for ML pipelines. This system will detect floating-point drift across different hardware configurations and provide CI integration with configurable tolerance policies.
System Architecture
┌─────────────────────────────────────────────────────────────┐
│ CI/CD Pipeline │
├─────────────┬─────────────┬─────────────┬─────────────────┤
│ Job 1 │ Job 2 │ Job 3 │ Comparison │
│ (CPU x86) │ (GPU A100) │ (GPU V100) │ & Report │
└──────┬──────┴──────┬──────┴──────┬──────┴────────┬────────┘
│ │ │ │
└─────────────┴─────────────┴───────────────┘
Shared Artifact Storage (S3/GCS/Azure)
Core Components
1. Instrumentation Layer
# instrumentation/drift_tracker.py
import numpy as np
import torch
import tensorflow as tf
from typing import Dict, List, Tuple, Any
from dataclasses import dataclass
from abc import ABC, abstractmethod
@dataclass
class TensorMetadata:
"""Metadata for captured tensors"""
layer_name: str
shape: Tuple[int, ...]
dtype: str
device: str
statistics: Dict[str, float] # min, max, mean, std, norm
hash_suffix: str # Partial hash for drift detection
class FrameworkAdapter(ABC):
"""Abstract adapter for different ML frameworks"""
@abstractmethod
def register_hooks(self, model, layer_names: List[str]) -> List[Any]:
"""Register forward hooks for specified layers"""
pass
@abstractmethod
def extract_tensor(self, hook_output) -> np.ndarray:
"""Extract numpy array from hook output"""
pass
@abstractmethod
def get_model_device(self, model) -> str:
"""Get device string for model"""
pass
class PyTorchAdapter(FrameworkAdapter):
def register_hooks(self, model, layer_names):
hooks = []
outputs = {}
def make_hook(name):
def hook(module, input, output):
outputs[name] = output
return hook
for name, module in model.named_modules():
if name in layer_names:
hooks.append(module.register_forward_hook(make_hook(name)))
return hooks, outputs
def extract_tensor(self, hook_output):
if isinstance(hook_output, torch.Tensor):
return hook_output.detach().cpu().numpy()
elif isinstance(hook_output, (tuple, list)):
return [t.detach().cpu().numpy() for t in hook_output]
return hook_output
class TensorFlowAdapter(FrameworkAdapter):
# Similar implementation for TensorFlow
pass
class DriftTracker:
"""Main instrumentation class"""
def __init__(self,
tolerance_policy: 'TolerancePolicy',
capture_layers: List[str] = None,
capture_frequency: int = 1):
self.tolerance_policy = tolerance_policy
self.capture_layers = capture_layers or []
self.capture_frequency = capture_frequency
self.step_count = 0
self.captured_data: Dict[str, List[TensorMetadata]] = {}
def start_tracking(self, model, framework: str = 'pytorch'):
"""Initialize tracking for a model"""
if framework == 'pytorch':
self.adapter = PyTorchAdapter()
elif framework == 'tensorflow':
self.adapter = TensorFlowAdapter()
self.hooks, self.outputs = self.adapter.register_hooks(
model, self.capture_layers
)
self.device = self.adapter.get_model_device(model)
self.framework = framework
def capture_step(self, step: int, additional_data: Dict = None):
"""Capture tensors at current step"""
if step % self.capture_frequency != 0:
return
self.step_count += 1
timestamp = f"step_{step}_{self.step_count}"
for layer_name, tensor in self.outputs.items():
numpy_tensor = self.adapter.extract_tensor(tensor)
metadata = self._compute_metadata(layer_name, numpy_tensor, timestamp)
if layer_name not in self.captured_data:
self.captured_data[layer_name] = []
self.captured_data[layer_name].append(metadata)
# Capture additional metrics
if additional_data:
self._capture_additional(additional_data, timestamp)
def _compute_metadata(self, layer_name: str, tensor: np.ndarray,
timestamp: str) -> TensorMetadata:
"""Compute metadata for tensor including robust hash"""
# Use stable hashing that's hardware-independent
hash_input = {
'shape': tensor.shape,
'dtype': str(tensor.dtype),
'statistics': {
'min': float(np.min(tensor)),
'max': float(np.max(tensor)),
'mean': float(np.mean(tensor)),
'std': float(np.std(tensor)),
'norm': float(np.linalg.norm(tensor))
}
}
# Create deterministic hash (not cryptographic)
hash_str = f"{hash_input['shape']}_{hash_input['dtype']}"
hash_str += f"_{hash_input['statistics']['mean']:.6e}"
hash_str += f"_{hash_input['statistics']['std']:.6e}"
return TensorMetadata(
layer_name=layer_name,
shape=tensor.shape,
dtype=str(tensor.dtype),
device=self.device,
statistics=hash_input['statistics'],
hash_suffix=hash_str[-16:] # Last 16 chars for compactness
)
2. Tolerance Policy System
# tolerance/policy.py
from enum import Enum
from typing import Dict, Callable, Optional
import numpy as np
class ToleranceStrategy(Enum):
ABSOLUTE = "absolute"
RELATIVE = "relative"
COMBINED = "combined" # atol + rtol * |b|
STATISTICAL = "statistical" #基于统计分布
COMPONENT_WISE = "component_wise" # Per-dimension tolerance
@dataclass
class ToleranceConfig:
strategy: ToleranceStrategy
threshold: float
per_dtype: Dict[str, float] # dtype-specific overrides
per_layer: Dict[str, float] # layer-specific overrides
ignore_layers: List[str] = []
warmup_steps: int = 0 # Skip first N steps
class TolerancePolicy:
"""Pluggable tolerance policy with multiple strategies"""
def __init__(self, config: ToleranceConfig):
self.config = config
self.history: Dict[str, List[float]] = {}
def check_drift(self,
ref_meta: TensorMetadata,
test_meta: TensorMetadata,
step: int) -> DriftReport:
"""Check if drift exceeds tolerance"""
if step < self.config.warmup_steps:
return DriftReport(False, 0.0, "warmup")
if ref_meta.layer_name in self.config.ignore_layers:
return DriftReport(False, 0.0, "ignored")
# Get appropriate threshold
threshold = self._get_threshold(ref_meta.dtype, ref_meta.layer_name)
# Compute drift metric
drift_value = self._compute_drift(ref_meta, test_meta)
# Check against threshold
passed = drift_value <= threshold
return DriftReport(
passed=passed,
drift_value=drift_value,
threshold=threshold,
strategy=self.config.strategy.value,
layer=ref_meta.layer_name
)
def _compute_drift(self, ref: TensorMetadata, test: TensorMetadata) -> float:
"""Compute drift metric between two tensor metadata"""
# Primary: Compare hash suffixes (fast rejection)
if ref.hash_suffix != test.hash_suffix:
# Compute actual difference
return self._detailed_comparison(ref, test)
return 0.0
def _detailed_comparison(self, ref: TensorMetadata, test: TensorMetadata) -> float:
"""Detailed numerical comparison"""
strategy = self.config.strategy
if strategy == ToleranceStrategy.ABSOLUTE:
return abs(ref.statistics['mean'] - test.statistics['mean'])
elif strategy == ToleranceStrategy.RELATIVE:
if abs(ref.statistics['mean']) < 1e-12:
return abs(test.statistics['mean'])
return abs((test.statistics['mean'] - ref.statistics['mean']) /
ref.statistics['mean'])
elif strategy == ToleranceStrategy.COMBINED:
atol = self.config.threshold
rtol = self.config.threshold
diff = abs(ref.statistics['mean'] - test.statistics['mean'])
return diff - (atol + rtol * abs(ref.statistics['mean']))
elif strategy == ToleranceStrategy.COMPONENT_WISE:
# Would need full tensors - stored separately
return 0.0
return 0.0
def _get_threshold(self, dtype: str, layer_name: str) -> float:
"""Resolve threshold with overrides"""
# Layer-specific override
if layer_name in self.config.per_layer:
return self.config.per_layer[layer_name]
# dtype-specific override
if dtype in self.config.per_dtype:
return self.config.per_dtype[dtype]
return self.config.threshold
@dataclass
class DriftReport:
passed: bool
drift_value: float
threshold: float
strategy: str
layer: str
details: Dict = None
3. Comparison Engine
# comparison/engine.py
from typing import List, Dict, Tuple
import pandas as pd
import json
from pathlib import Path
class ComparisonEngine:
"""Compare multiple runs and generate reports"""
def __init__(self, baseline_run: str, tolerance_policy: TolerancePolicy):
self.baseline_run = Path(baseline_run)
self.tolerance_policy = tolerance_policy
self.reports: List[DriftReport] = []
def compare_runs(self, run_paths: List[str]) -> pd.DataFrame:
"""Compare multiple runs against baseline"""
all_results = []
for run_path in run_paths:
result = self._compare_single_run(run_path)
all_results.append(result)
return pd.DataFrame(all_results)
def _compare_single_run(self, run_path: str) -> Dict:
"""Compare one run against baseline"""
run_meta = self._load_run_metadata(run_path)
baseline_meta = self._load_run_metadata(self.baseline_run)
layer_comparisons = []
max_drift = 0.0
failed_layers = []
# Compare common layers
common_layers = set(baseline_meta.keys()) & set(run_meta.keys())
for layer in common_layers:
for i, (ref_meta, test_meta) in enumerate(zip(
baseline_meta[layer], run_meta[layer])):
report = self.tolerance_policy.check_drift(
ref_meta, test_meta, step=i
)
layer_comparisons.append({
'layer': layer,
'step': i,
'passed': report.passed,
'drift': report.drift_value,
'threshold': report.threshold,
'ref_device': ref_meta.device,
'test_device': test_meta.device,
'ref_stats': ref_meta.statistics,
'test_stats': test_meta.statistics
})
if not report.passed:
failed_layers.append(f"{layer}_step{i}")
max_drift = max(max_drift, report.drift_value)
return {
'run_id': Path(run_path).name,
'baseline_id': self.baseline_run.name,
'total_layers_compared': len(common_layers) * min(
len(baseline_meta.get(next(iter(common_layers)), [])),
len(run_meta.get(next(iter(common_layers)), []))
),
'failed_layers': failed_layers,
'max_drift': max_drift,
'passed': len(failed_layers) == 0,
'details': layer_comparisons
}
def _load_run_metadata(self, run_path: str) -> Dict[str, List[TensorMetadata]]:
"""Load metadata from run directory"""
metadata_file = Path(run_path) / "metadata" / "tensors.json"
with open(metadata_file) as f:
data = json.load(f)
# Reconstruct TensorMetadata objects
result = {}
for layer, items in data.items():
result[layer] = [
TensorMetadata(**item) for item in items
]
return result
4. Artifact Storage & Versioning
# storage/artifact_manager.py
import hashlib
import json
from datetime import datetime
from pathlib import Path
class ArtifactManager:
"""Manage run artifacts with content-addressable storage"""
def __init__(self, storage_root: str):
self.storage_root = Path(storage_root)
self.storage_root.mkdir(exist_ok=True)
def save_run(self,
run_id: str,
metadata: Dict,
tensors: Dict[str, np.ndarray],
config: Dict) -> str:
"""Save complete run artifact"""
# Create run directory
run_dir = self.storage_root / run_id
run_dir.mkdir(exist_ok=True)
# Save config
with open(run_dir / "config.json", "w") as f:
json.dump(config, f, indent=2)
# Save metadata
metadata_dir = run_dir / "metadata"
metadata_dir.mkdir(exist_ok=True)
# Serialize metadata for storage
serializable_meta = {}
for layer, meta_list in metadata.items():
serializable_meta[layer] = [
{
'layer_name': m.layer_name,
'shape': m.shape,
'dtype': m.dtype,
'device': m.device,
'statistics': m.statistics,
'hash_suffix': m.hash_suffix
} for m in meta_list
]
with open(metadata_dir / "tensors.json", "w") as f:
json.dump(serializable_meta, f, indent=2)
# Save environment info
env_file = run_dir / "environment.json"
self._save_environment(env_file)
# Create content hash for deduplication
content_hash = self._compute_content_hash(run_dir)
(run_dir / "content_hash.txt").write_text(content_hash)
return str(run_dir)
def _compute_content_hash(self, run_dir: Path) -> str:
"""Compute deterministic hash of run contents"""
hasher = hashlib.sha256()
# Hash config first (most important)
config_file = run_dir / "config.json"
if config_file.exists():
hasher.update(config_file.read_bytes())
# Hash metadata
metadata_file = run_dir / "metadata" / "tensors.json"
if metadata_file.exists():
hasher.update(metadata_file.read_bytes())
return hasher.hexdigest()[:16]
5. CI/CD Integration
# .github/workflows/reproducibility-test.yml
name: Numerical Reproducibility Test
on:
push:
branches: [main, develop]
pull_request:
jobs:
test-cpu:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
pip install torch torchvision
pip install -e .[test]
- name: Run CPU test
run: |
python -m testbed.run \
--config tests/configs/resnet50.yaml \
--output cpu_run_${{ github.run_number }} \
--framework pytorch \
--device cpu
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: cpu-run-${{ github.run_number }}
path: cpu_run_${{ github.run_number }}/
test-gpu-a100:
runs-on: [self-hosted, gpu-a100] # Requires self-hosted runner
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install CUDA 11.8
run: |
# Install specific CUDA version
- name: Run GPU A100 test
run: |
python -m testbed.run \
--config tests/configs/resnet50.yaml \
--output gpu_a100_run_${{ github.run_number }} \
--framework pytorch \
--device cuda:0
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: gpu-a100-run-${{ github.run_number }}
path: gpu_a100_run_${{ github.run_number }}/
compare-and-report:
needs: [test-cpu, test-gpu-a100]
runs-on: ubuntu-latest
steps:
- name: Download artifacts
uses: actions/download-artifact@v3
with:
path: artifacts/
- name: Compare runs
run: |
python -m testbed.compare \
--baseline artifacts/cpu-run-${{ github.run_number }} \
--runs artifacts/gpu-a100-run-${{ github.run_number }} \
--tolerance tests/tolerances/resnet50.yaml \
--output comparison_report.json
- name: Generate HTML report
run: |
python -m testbed.report \
--input comparison_report.json \
--output report.html
- name: Upload report
uses: actions/upload-artifact@v3
with:
name: reproducibility-report-${{ github.run_number }}
path: |
comparison_report.json
report.html
- name: Check drift threshold
run: |
python -m testbed.check_threshold \
--report comparison_report.json \
--max-drift 1e-5 # Fail if max drift exceeds this
6. Configuration Examples
# tests/configs/resnet50.yaml
model:
name: "resnet50"
framework: "pytorch"
pretrained: true
input:
shape: [32, 3, 224, 224]
type: "random"
seed: 42
distribution: "uniform"
range: [0, 1]
instrumentation:
capture_layers:
- "conv1"
- "layer1.0.conv1"
- "layer4.2.conv3"
- "fc"
capture_frequency: 1
capture_gradients: false
tolerance:
strategy: "combined"
default_threshold: 1e-5
per_dtype:
"float16": 1e-3
"bfloat16": 1e-2
per_layer:
"fc": 1e-6 # Stricter for final layer
ignore_layers: []
warmup_steps: 0
ci:
baseline: "cpu"
target_devices:
- "cuda:0"
- "cuda:1"
required_significant_digits: 4
7. Main CLI Interface
# testbed/cli.py
import click
from pathlib import Path
import yaml
@click.group()
def cli():
"""Numerical Reproducibility Testbed for ML Pipelines"""
pass
@cli.command()
@click.option('--config', required=True, type=click.Path(exists=True))
@click.option('--output', default='run_artifact', type=click.Path())
@click.option('--framework', type=click.Choice(['pytorch', 'tensorflow']), default='pytorch')
@click.option('--device', default='auto')
def run(config, output, framework, device):
"""Run instrumented training/inference"""
from .runner import InstrumentedRunner
config_data = yaml.safe_load(open(config))
runner = InstrumentedRunner(config_data, framework, device)
runner.run(output)
@cli.command()
@click.option('--baseline', required=True, type=click.Path(exists=True))
@click.option('--runs', required=True, multiple=True, type=click.Path(exists=True))
@click.option('--tolerance', type=click.Path(exists=True))
@click.option('--output', default='comparison.json')
def compare(baseline, runs, tolerance, output):
"""Compare multiple runs against baseline"""
from .comparison import compare_multiple_runs
tolerance_config = yaml.safe_load(open(tolerance)) if tolerance else None
results = compare_multiple_runs(baseline, list(runs), tolerance_config)
with open(output, 'w') as f:
json.dump(results, f, indent=2)
# Print summary
_print_summary(results)
@cli.command()
@click.option('--report', required=True, type=click.Path(exists=True))
@click.option('--threshold', type=float, help='Max allowed drift')
def check_threshold(report, threshold):
"""Check if report passes threshold"""
with open(report) as f:
data = json.load(f)
max_drift = max(r['max_drift'] for r in data['runs'])
if threshold and max_drift > threshold:
click.echo(f"❌ FAILED: Max drift {max_drift:.2e} exceeds threshold {threshold:.2e}")
exit(1)
else:
click.echo(f"✅ PASSED: Max drift {max_drift:.2e} within threshold")
8. Advanced Features
# advanced/failure_prediction.py
from sklearn.ensemble import IsolationForest
from typing import List
class DriftPredictor:
"""Predict potential future drift based on patterns"""
def __init__(self):
self.model = IsolationForest(contamination=0.1)
self.history: List[Dict] = []
def update(self, drift_metrics: List[float], layer_names: List[str]):
"""Update with new drift observations"""
features = self._extract_features(drift_metrics, layer_names)
self.history.append(features)
def predict_risk(self, new_metrics: List[float]) -> float:
"""Predict risk score for new configuration"""
if len(self.history) < 10:
return 0.0
features = self._extract_features(new_metrics, [])
return self.model.decision_function([features])[0]
Deployment & Setup
Docker Support
# Dockerfile
FROM nvidia/cuda:11.8-devel-ubuntu22.04
# Install specific CUDA toolkit, cuDNN, etc.
RUN apt-get update && apt-get install -y \
python3.9 \
python3-pip \
git
# Install framework versions
RUN pip install torch==2.0.1+cu118 torchvision==0.15.2+cu118 --extra-index-url https://download.pytorch.org/whl/cu118
COPY . /testbed
RUN pip install -e /testbed
Requirements
# requirements.txt
torch>=2.0.0
tensorflow>=2.12.0
numpy>=1.24.0
pandas>=2.0.0
pyyaml>=6.0
click>=8.1.0
scikit-learn>=1.2.0
plotly>=5.14.0 # For visualization
Usage Workflow
- Define Test Configuration:
testbed run --config experiments/resnet50_cifar10.yaml --output run_001
- Run on Multiple Platforms:
# CPU
CUDA_VISIBLE_DEVICES="" testbed run ...
# GPU1 (A100)
CUDA_VISIBLE_DEVICES=0 testbed run ...
# GPU2 (V100)
CUDA_VISIBLE_DEVICES=1 testbed run ...
- Compare Results:
testbed compare \
--baseline run_cpu_001 \
--runs run_gpu_a100_001 run_gpu_v100_001 \
--tolerance tolerances/resnet50.yaml \
--output drift_report.json
- CI Integration: Push to trigger automated comparison in CI pipeline.
Key Design Decisions
-
Content-Addressable Storage: Uses hash-based deduplication to avoid storing identical tensors multiple times.
-
Stateless Comparison: All necessary information stored in metadata, no need to keep full tensors for comparison.
-
Framework Agnostic: Adapter pattern supports PyTorch/TensorFlow/JAX.
-
Configurable Tolerance: Multiple strategies with per-dtype and per-layer overrides.
-
CI-Native: Designed for parallel execution in CI matrices with artifact sharing.
-
Progressive Disclosure: Fast hash-based rejection first, detailed computation only when needed.
-
Warmup Period: Optional initial steps ignored to account for initialization differences.
Monitoring & Alerting
# monitoring/alerting.py
class AlertManager:
def __init__(self, thresholds: Dict[str, float]):
self.thresholds = thresholds
def check_alerts(self, report: Dict) -> List[Alert]:
alerts = []
if report['max_drift'] > self.thresholds['critical']:
alerts.append(Alert(
level="CRITICAL",
message=f"Critical drift detected: {report['max_drift']:.2e}",
run_id=report['run_id']
))
elif report['max_drift'] > self.thresholds['warning']:
alerts.append(Alert(
level="WARNING",
message=f"Significant drift: {report['max_drift']:.2e}",
run_id=report['run_id']
))
return alerts
This testbed provides:
- Hardware-agnostic reproducibility checks
- Configurable tolerance policies per layer/dtype
- CI/CD integration with matrix testing
- Content-addressable storage for efficiency
- Statistical analysis and failure prediction
- Rich reporting with HTML output
The system can be extended to support new frameworks, additional drift metrics (gradient comparison, weight initialization), and integration with MLflow/Weights & Biases for tracking across experiments.