We are going to design a system to monitor reproducibility in training runs.
We want to compare:
Seeds: Track the random seeds used (Python, NumPy, PyTorch, etc.) and any other sources of randomness.
Metrics Variance: Compare the same metrics across different runs to see if there is significant variance.
Environment Drift: Check for changes in the environment (library versions, hardware, etc.) that might cause drift.
Steps:
Define what we consider a "run". A run should have:
A unique run ID (maybe timestamp or UUID)
A set of seeds (for each library)
A set of hyperparameters (optional, but useful for context)
A set of metrics (with timestamps or steps)
Environment information (versions of libraries, system info)
We want to compare multiple runs. We might have a baseline run and then compare new runs to it.
For metrics variance:
We can collect the same metrics from multiple runs (with same hyperparameters and seeds? but we are comparing if same seeds and hyperparameters yield same results?).
Actually, we want to see if changing the seed (but keeping everything else same) leads to the same performance? That's one aspect.
Also, if we change the environment (e.g., upgrade a library) but keep the same seed and hyperparameters, do we get the same results?
We can break down the comparisons:
a) Same hyperparameters, same seeds (but maybe different runs due to non-determinism?):
- We expect the metrics to be very similar (within a small variance). We can set a threshold.
b) Same hyperparameters, different seeds:
- We expect some variance, but if the variance is too high, it might indicate instability.
c) Same hyperparameters, same seeds, but different environment (e.g., different library versions):
- We expect the metrics to be the same? But sometimes library updates change behavior. We want to detect such drift.
We need to store the runs in a structured way. We can use a database or a file store (like JSON or YAML per run). But for simplicity, let's assume we have a central store (maybe a dictionary or a pandas DataFrame) that we can query.
We'll design a class that can:
Register a run (with all the required info)
Compare a new run against a set of baseline runs (or against all runs with same hyperparameters?).
The comparison can be:
For each metric, compute the mean and standard deviation across runs that are supposed to be the same (same hyperparameters and same seeds?).
But note: if we are comparing for same hyperparameters and same seeds, then we expect the runs to be identical. So we might compare multiple runs with same seeds and hyperparameters to see if there is any non-determinism.
However, note that even with same seeds, if the code uses parallel operations (like multiple threads) we might get non-determinism. So we might want to allow a very small tolerance.
We also want to flag environment drift. So we need to store the environment for each run and then compare the environment of the runs we are comparing.
Let's say we have a baseline run (or a set of baseline runs). We want to check a new run.
Step 1: Check if the hyperparameters match any baseline run's hyperparameters (within a tolerance for floating point?).
Step 2: If we find matching hyperparameters, then:
a) Compare seeds: are they the same?
- If same, then we expect the metrics to be very close. We can compute the difference for each metric at each step (or at the same step if steps are logged) and see if it's within a tolerance (e.g., 1e-5).
- If the seeds are different, then we expect the metrics to be within a larger tolerance (but we might not have a baseline for that?).
b) Compare environment: if the environment (key library versions) are different, then we expect the metrics to be different? But we want to flag that as drift.
However, note that the same hyperparameters and same seeds but different environment (because of library version change) might lead to different results. We want to detect that.
We might want to group runs by hyperparameters and then within that group, we can see:
Group by seeds: if we have multiple runs with the same seeds, then we can compute the variance within that group. That variance should be very small (non-determinism).
Then, for runs with different seeds (but same hyperparameters) we can compute the variance and see if it's acceptable.
Then, for runs with same hyperparameters but different environment (and maybe same or different seeds) we can see if the metrics are significantly different from the baseline group.
Implementation:
We'll have a class ReproducibilityMonitor that:
Has a storage (list of runs or a database connection)
Methods to add a run
Methods to query runs by hyperparameters (with tolerance for floats)
Methods to compare a given run against the stored runs.
Let's design the comparison method:
Given a run R (the one we want to check), we:
Step 1: Find all runs in storage that have hyperparameters matching R's hyperparameters (with tolerance for floats, maybe using a hash of hyperparameters after rounding?).
Step 2: Among these, we can further split by seeds (if we want to compare same seeds) or by environment.
Step 3: For each metric in R, we compare with the same metric in the baseline runs.
How to compare?
Option 1: Compare at the same step. But note: runs might not have the same steps logged? We might have to interpolate or compare at the last step? Or compare the entire curve?
Option 2: Compare the final value of the metric (at the last step). But sometimes the curve might be different even if the final value is same.
Option 3: Compare the entire curve by resampling to common steps? That might be heavy.
Since we are interested in reproducibility, we might care about the final metric (e.g., accuracy at the end of training). But also, we might care about the learning curve.
Let's assume we are given a metric and we want to compare the entire curve. We can:
code
- For each step in the baseline run (or the common steps), compute the mean and std of the metric across the baseline runs at that step.
- Then for the new run, at the same step, check if it's within, say, 3 standard deviations of the baseline mean?
But note: if we have only one baseline run, then std is 0. So we need a tolerance.
Alternatively, we can define:
code
- If we have multiple runs with the same hyperparameters and same seeds (and same environment?), then we expect them to be identical. So we can set a tolerance (like 1e-6) and check if the difference at each step is within that.
- If we have multiple runs with same hyperparameters but different seeds, then we compute the mean and std across those runs (at each step) and then check if the new run is within, say, 3 stds.
But note: if we have only one baseline run, then we cannot compute std. So we might have to rely on a fixed tolerance.
Let's simplify:
code
We need to define tolerance for hyperparameters matching. We'll round the hyperparameters to a certain number of decimal places? Or we can use a relative tolerance.
Let's assume hyperparameters are floats or integers. We'll convert to a string with a fixed format? Or we can use:
def hyperparameter_match(h1, h2, tol=1e-6):
for key in h1:
if key not in h2:
return False
if abs(h1[key] - h2[key]) > tol:
return False
for key in h2:
if key not in h1:
return False
return True
We also need to handle metrics that are lists of (step, value). We might need to align the steps. We can:
Find the common steps (intersection of steps) and compare only those.
Or, we can interpolate? But that might be overkill.
Let's assume we only compare at steps that are present in both the run and the baseline.
So for each baseline run, we extract the steps that are in R and in the baseline run.
Then for each step, we have a list of values from the baseline runs (for that step). Then compute mean and std.
Then for R, at that step, we have one value. Then we check.
But note: if the baseline runs have different steps? Then we only compare at the common steps.
Alternatively, we can resample to a common set of steps? But that might be complex.
Let's do:
code
For a given metric, let steps_R = set of steps in R.
For each baseline run b, let steps_b = set of steps in b.
common_steps = steps_R.intersection(steps_b)
Then for each step in common_steps, we collect the values from all baseline runs that have that step.
Then we compute mean and std for that step.
Then we compare R's value at that step.
But note: what if for a step, only some baseline runs have it? Then we use the ones that have it.
This might lead to different number of samples at different steps.
Alternatively, we can require that all baseline runs have the same steps? That might be too strict.
Given time, we'll assume that the baseline runs and R have the same steps (same logging frequency). Then we can just use the steps from R.
class ReproducibilityMonitor:
def init(self):
self.runs = [] # list of Run objects
code
This is a basic design. We can improve:
We might want to compare the entire curve, not just per step? But per step is okay.
We might want to have a way to set the tolerance for hyperparameters and for non-determinism.
We might want to have a way to specify which metrics are important.
We might want to have a way to handle missing steps (interpolation?).
We might want to store the runs in a database and have more efficient queries.
We might want to have a way to define the baseline runs (maybe by tags?).
Given the time, we'll stop here.
This is a starting point. In practice, we might need to adjust the thresholds and the way we compare.
Also, note that the environment might be a dict with many keys. We might want to compare only the important ones (like torch version, cuda version, etc.). We can define a list of environment keys to compare.
We can change the environment comparison to:
same environment: if for a set of critical keys, the values are the same.
We'll leave that as an extension.
Let's write the code accordingly.
We'll assume the environment dict has keys like 'torch', 'numpy', 'python', etc.
We can define a list of critical environment keys:
def _environments_match(self, env1, env2):
for key in CRITICAL_ENV_KEYS:
if key not in env1 or key not in env2:
continue
if env1[key] != env2[key]:
return False
return True
But note: we might have other keys? We can also allow a tolerance? For versions, we might want to compare major and minor? But that's complex.
We'll stick to exact string match for the critical keys.
same_hyper_same_seed_same_env = [r for r in same_hyper if r.seeds == run.seeds and self._environments_match(r.environment, run.environment) and r.run_id != run.run_id]
similarly for others.
We also need to handle the case where the environment dict might not have all the critical keys. We'll only compare the keys that are present in both? Or we require that both have all critical keys? Let's require that both have all critical keys? Otherwise, we consider them different.
Alternatively, we can:
for key in CRITICAL_ENV_KEYS:
if key in env1 and key in env2:
if env1[key] != env2[key]:
return False
elif key in env1 or key in env2:
# one has it and the other doesn't -> different
return False
return True
But that might be too strict. Maybe we only care about the keys that are present in both?
Let's do:
for key in CRITICAL_ENV_KEYS:
if key in env1 and key in env2:
if env1[key] != env2[key]:
return False
else:
# if one of them doesn't have the key, we consider them different?
# But maybe one environment didn't record that key. We might want to ignore.
# Let's ignore if at least one doesn't have the key? Then we cannot compare, so we return False?
# Actually, if we don't have the key, we cannot say they are the same. So return False.
return False
return True
But that means if either environment is missing a critical key, they are considered different.
Alternatively, we can:
for key in CRITICAL_ENV_KEYS:
if key in env1 and key in env2:
if env1[key] != env2[key]:
return False
# if one is missing, we ignore? Then we only compare the common keys?
# But then two environments that are missing the same key would be considered same? That might be dangerous.
So let's require that both have all the critical keys.
We can check:
code
if not all(key in env1 and key in env2 for key in CRITICAL_ENV_KEYS):
return False
then compare.
But note: what if we have a new environment that doesn't have all keys? Then we cannot compare.
Given the time, we'll do:
def _environments_match(self, env1, env2):
for key in CRITICAL_ENV_KEYS:
if key not in env1 or key not in env2:
return False
if env1[key] != env2[key]:
return False
return True
Now, let's code the entire thing.
We'll use numpy for mean and std.
We assume the runs are stored in memory.
This is a prototype.
We'll also add a method to set the critical environment keys.
Let's write the code.
Note: We are not handling the case where the same run is added twice? We assume unique run_id.
We are also not handling the case where the metrics have different names? We only compare the metrics that are in the run and in the baseline.
We'll write the code accordingly.
Due to the complexity and time, we'll leave some parts as comments and focus on the structure.
Let's code.
I'll design a comprehensive Training Run Reproducibility Monitor that tracks seeds, metrics variance, and environment drift across ML experiments. This system helps detect reproducibility issues and track experiment provenance.
Track Python version (subtle changes between patch versions can matter)
Record whether using Docker/conda environment
When to Flag:
Same seeds + same env → variance > 0.1% (accuracy) or 0.01 (loss) ❌
Same seeds + different env → any significant variance (even if small) ❌
Different seeds → variance within expected seed sensitivity ✅
Integration Points:
Hook into training loop at checkpoint/evaluation steps
Integrate with experiment trackers (WandB, MLFlow)
Add to CI/CD pipeline for regression testing
This system provides scientific rigor for ML reproducibility by:
Quantifying exactly what differs between runs
Distinguishing between acceptable variance (seed sensitivity) and problematic drift (environment changes)
Providing actionable alerts with specific drift sources
Enabling historical comparisons across time
Would you like me to elaborate on any specific component or add integration with particular frameworks (PyTorch Lightning, HuggingFace, etc.)?
We'll have two types of baselines:
Type A: Same hyperparameters, same seeds, and same environment (or at least same library versions?).
Type B: Same hyperparameters, same seeds, but different environment? (We might not want to group by environment? Actually, we want to detect environment drift, so we want to compare runs with same hyperparameters and seeds but different environment.)
Actually, we might want to compare:
code
Group 1: Baseline set with same hyperparameters and same seeds and same environment (or as close as possible).
Then, when a new run comes:
- If it has same hyperparameters and same seeds and same environment as Group 1, then we expect it to be very close to the mean of Group 1.
- If it has same hyperparameters and same seeds but different environment, then we expect it to be different? We want to flag that.
- If it has same hyperparameters but different seeds, then we compare to a different group (Group 2: same hyperparameters, different seeds, same environment?).
This is getting complex.
Alternatively, we can do:
code
For a given run R:
Step 1: Find all runs that have the same hyperparameters (with tolerance) and the same seeds (exact match). Call this group S.
Step 2: Within S, we can further split by environment (if we want). But let's assume we want to check if the environment is the same? Actually, we are interested in environment drift, so we want to compare runs with same hyperparameters and seeds but different environment.
So:
Let S_env1 = runs in S with environment E1 (the environment of R)
Let S_env2 = runs in S with environment different from E1.
Then:
- Compare R to S_env1 (if S_env1 has more than one run, compute mean and std at each step; if only one, then use a fixed tolerance). If R is outside, say, 3 stds (or fixed tolerance) then flag as non-reproducible.
- Compare R to S_env2: if there are runs with same hyperparameters and seeds but different environment, then we expect R to be different from S_env2? Actually, we want to see if the environment change caused a drift. So we can check if R is more similar to S_env1 than to S_env2? Or just note that there is a difference.
But note: if we have no runs in S_env1 (because R is the first with that environment) then we cannot compare. We might need to have a baseline environment.
Alternatively, we can define:
code
We have a baseline run (or set of runs) that we consider the reference. Then, for a new run, we:
- Check if hyperparameters match the baseline (within tolerance).
- Check if seeds match the baseline (exact).
- Check if environment matches the baseline (exact? or at least the same major versions?).
Then:
If all match: expect very small difference (tolerance 1e-6).
If hyperparameters and seeds match but environment does not: expect difference -> flag as environment drift.
If hyperparameters match but seeds do not: then we are in the case of seed variance. We can have a separate baseline for seed variance? Or we can have a group of runs with same hyperparameters but different seeds and same environment to compute the expected variance.
This suggests we need to pre-define groups:
code
Group G1: same hyperparameters, same seeds, same environment -> variance should be very low.
Group G2: same hyperparameters, different seeds, same environment -> variance should be within a range (we compute from G2).
Group G3: same hyperparameters, same seeds, different environment -> we expect the runs in G3 to be different from G1? Actually, we want to see if the environment change causes a shift.
But note: we might not have runs in G3 until we change the environment.
So, for a new run R:
code
Step 1: Find the group of runs that have the same hyperparameters (with tolerance) and same environment as R. Among these, split by seeds:
- If R's seeds are the same as some runs in that group, then we compare R to those runs (with same seeds). If the variance is too high, then flag non-determinism.
- If R's seeds are different, then we compare R to the runs with same hyperparameters and same environment but different seeds? But note: we are not necessarily expecting R to match the runs with different seeds? Actually, we are expecting R to be within the seed variance of the runs with same seeds? Wait, no: if R has different seeds, then we don't have a same-seed baseline in the same environment? Then we might compare to the entire group (all seeds) and see if R is within the overall variance.
Step 2: Also, we can check if there are runs with same hyperparameters and same seeds but different environment. If so, we can compare R (with its environment) to those runs (with different environment) and see if they are more different than the within-environment variance.
This is getting very complex.
Let's simplify the goal:
code
We want to answer:
1. Is this run reproducible? i.e., if we run again with the same seeds and same environment, do we get the same results?
2. How much variance do we expect from changing the seed?
3. How much does the environment affect the results?
We can do:
code
For a given set of hyperparameters, we run multiple times with same seeds and same environment (to check non-determinism) -> group A.
Then we run with same hyperparameters but different seeds (same environment) -> group B.
Then we run with same hyperparameters and same seeds but different environment -> group C.
Then, for a new run R:
code
If it matches hyperparameters and seeds and environment of group A, then we compare to group A and expect small difference.
If it matches hyperparameters and seeds but environment of group C, then we compare to group C? Actually, we want to see if it's different from group A? So we compare R to group A (same hyperparameters and seeds but different environment) and flag if it's significantly different.
If it matches hyperparameters but different seeds (and same environment as group B) then we compare to group B (which has same hyperparameters and environment but different seeds) and see if R is within the variance of group B.
But note: we might not have all groups.
So, we can do:
code
Let's define:
Baseline: the set of runs that we consider the reference (maybe the first run with given hyperparameters and seeds and environment?).
Then for a new run:
Step 1: Find runs with same hyperparameters (tolerance) and same seeds.
Step 2: Among these, find runs with the same environment as the new run. If there are at least N (say 2) runs in this subset, then we can compute the mean and std of the metric at each step and check if the new run is within 3 stds.
If there are less than N runs, then we might use a fixed tolerance.
Step 3: Also, we can look at runs with same hyperparameters and same seeds but different environment. If we have at least one such run, we can compute the difference between the new run and that run, and see if it's larger than the within-environment variance.
But note: we are comparing a new run to a set of runs that have the same seeds and same hyperparameters. If the seeds are the same, then the only source of variance should be non-determinism (if same environment) or environment drift (if different environment). So:
- If same environment: we are checking non-determinism.
- If different environment: we are checking environment drift.
But what if we have same hyperparameters and same seeds but the environment is different? Then we expect a drift. So we can flag that the environment is different and then check if the metrics are also different.
Alternatively, we can have two separate checks:
code
Check 1: Non-determinism check.
- Find runs with same hyperparameters, same seeds, and same environment (as the new run).
- If we have at least 2 runs (including the new one? or excluding?), compute the variance. If the variance is above a threshold, flag non-determinism.
Check 2: Environment drift check.
- Find runs with same hyperparameters, same seeds, but different environment (from the new run).
- If we have at least one such run, compute the difference between the new run and that run (at each step) and see if it's larger than the non-determinism threshold? Or just flag that the environment is different and the metrics are different.
But note: the non-determinism threshold should be very small (like 1e-6). The environment drift might be larger.
So:
code
For a new run R:
Let S_same_env = all runs with same hyperparameters (tolerance) and same seeds and same environment as R.
Let S_diff_env = all runs with same hyperparameters (tolerance) and same seeds but different environment as R.
Then:
If len(S_same_env) >= 2 (including R? or excluding? Let's exclude R for now, so we need at least 2 other runs?):
Compute the mean and std of each metric at each step across S_same_env (without R). Then check R at each step: if |R[metric][step] - mean| > 3 * std, then flag non-determinism.
If we don't have enough runs in S_same_env, then we can use a fixed tolerance (say 1e-5) and check if R is within that tolerance of the mean of S_same_env (if any) or just flag that we don't have enough baseline.
For environment drift:
If S_diff_env is not empty, then for each run in S_diff_env, compute the difference at each step. Then we can see if the difference between R and S_diff_env is larger than the non-determinism threshold? Actually, we expect the difference to be larger. We can compute the mean difference and see if it's above, say, 10 times the non-determinism threshold? Or just report the difference.
Also, we might want to check the seed variance: runs with same hyperparameters and same environment but different seeds.
But note: the new run R might have different seeds. Then we are not in the same-seed group. So we might want to compare R to runs with same hyperparameters and same environment but different seeds? That would be the seed variance group.
So, we might need to adjust:
We are given R. We want to check:
a) If R is reproducible (same seeds and environment) -> compare to same seed and same environment group.
b) If R has different seeds, then we are in the seed variance scenario. So we compare to runs with same hyperparameters and same environment but different seeds? But note: if R has different seeds, then by definition it's not in the same-seed group. So we cannot use the same-seed group for comparison.
So for R with different seeds:
We want to see if the metrics are within the expected seed variance.
So we need a group of runs with same hyperparameters and same environment but different seeds (and not R's seeds). Then we compute the mean and std across that group (at each step) and check if R is within 3 stds.
So, we have three groups for a given hyperparameter set and environment:
Group1: same seeds (non-determinism group)
Group2: different seeds (seed variance group)
But note: Group1 should be very tight, Group2 might be looser.
So, for R:
Let G1 = runs with same hyperparameters, same seeds, same environment (excluding R)
Let G2 = runs with same hyperparameters, same environment, but different seeds (excluding R? and also excluding the runs in G1? Actually, G1 and G2 are disjoint by seeds)
Then:
If R's seeds are the same as the baseline (i.e., we have G1), then we compare R to G1 (non-determinism check).
If R's seeds are different, then we compare R to G2 (seed variance check).
And then, we also have the environment drift check: if we have runs with same hyperparameters and same seeds but different environment, we compare R (with its environment) to those runs.
But note: if R has different seeds, then we are not comparing same seeds for environment drift? We might want to compare same seeds for environment drift, so we only consider runs with same seeds as R? Then:
For environment drift, we look at runs with same hyperparameters and same seeds as R, but different environment.
So, we have:
For R:
Check 1 (non-determinism or seed variance depending on R's seeds):
Let G =
if R's seeds are in the baseline seeds (i.e., we have runs with same seeds and same environment):
then G = runs with same hyperparameters, same seeds, same environment (excluding R)
else:
then G = runs with same hyperparameters, same environment, but with seeds not equal to R's seeds? Actually, we want to compare to runs that have same hyperparameters and same environment but different seeds. But note: we might have multiple seed sets. We want to compare to the distribution of runs with same hyperparameters and same environment but any seeds (except R's seeds?).
Actually, we want to know: if we have a distribution of runs with same hyperparameters and same environment (regardless of seeds) then we can compute the overall mean and std. But then if R has same seeds as some of them, we are in the non-determinism case?
Alternatively, we can have two distributions:
Dist1: same hyperparameters, same environment, same seeds (across multiple runs with those seeds) -> very small std.
Dist2: same hyperparameters, same environment, different seeds -> larger std.
Then for R:
If R's seeds are the same as the seeds used in Dist1, then we expect R to be in Dist1.
If R's seeds are not in Dist1, then we expect R to be in Dist2.
But what if we have Dist1 for seed set A, and R has seed set B (which we don't have in Dist1)? Then we don't have a Dist1 for seed set B? Then we might have to use Dist2 for seed set B? But we might not have any runs with seed set B in Dist2? Then we cannot compare.
So, we need to have at least one run with the same seeds as R in the same environment to do the non-determinism check? Otherwise, we fall back to the seed variance check (using Dist2) but note: Dist2 includes multiple seed sets. We are then comparing R to a distribution that includes runs with different seeds from R and also possibly same seeds? We want to exclude runs with same seeds? Actually, if we have Dist2 that includes runs with same seeds as R, then that would be wrong because we are in the non-determinism case.
So, we must split Dist2 by seeds? That is, we need to have at least a few runs with the same seeds as R to compute the non-determinism?
Alternatively, we can have:
For a given hyperparameter set and environment, we group by seed.
Then, for each seed group, we compute the mean and std across runs in that group (non-determinism). If a group has only one run, then we cannot compute std? Then we might have to use a fixed tolerance.
Then, for a new run R:
Find the group with same seeds (in the same hyperparameters and environment). If that group exists and has at least 2 runs (excluding R), then we use that group's mean and std.
If that group has only one run (or none), then we might use the overall distribution (across all seeds) for that hyperparameter set and environment? But note: the overall distribution will have a larger std because of seed variance. Then we might be too lenient.
This is getting too complicated.
Given the complexity, let's simplify the problem:
code
We assume that for a given set of hyperparameters and environment, we have a baseline run (or a set of baseline runs) that we trust.
Then, for a new run R:
We compare R to the baseline runs that have the same hyperparameters (tolerance) and same environment and same seeds? But then we are only checking non-determinism.
But we also want to check seed variance and environment drift.
Maybe we need to run multiple experiments:
code
Experiment 1: Same hyperparameters, same seeds, same environment -> multiple runs to measure non-determinism.
Experiment 2: Same hyperparameters, different seeds, same environment -> multiple runs to measure seed variance.
Experiment 3: Same hyperparameters, same seeds, different environment -> multiple runs to measure environment drift.
Then, for a new run R, we can:
code
If R matches the hyperparameters and seeds and environment of Experiment 1, then we compare to Experiment 1 and expect non-determinism level.
If R matches the hyperparameters and seeds but environment of Experiment 3, then we compare to Experiment 3 and expect environment drift.
If R matches the hyperparameters and environment but seeds of Experiment 2, then we compare to Experiment 2 and expect seed variance.
So, we need to store the experiments and their purpose? Or we can infer from the data.
Given the time, let's design a simpler version:
code
We'll assume we have a baseline run (or set of runs) for a given hyperparameter set, seed set, and environment.
We'll store:
baseline_runs: list of runs that are considered baseline (maybe the first run for a given hyperparameter set and environment?).
Then, for a new run R:
Step 1: Find the baseline run(s) with the same hyperparameters (tolerance) and same environment and same seeds.
If found:
Compare R to the baseline run(s) (with same hyperparameters, seeds, environment). If the difference is above a non-determinism threshold (say 1e-5) then flag.
Step 2: Find runs with same hyperparameters and same environment but different seeds (the seed variance baseline). If we have a set of such runs, compute the mean and std of metrics at each step (across those runs). Then check if R (which might have different seeds) is within 3 stds of that mean.
Step 3: Find runs with same hyperparameters and same seeds but different environment (the environment drift baseline). If we have such runs, compute the difference between R and those runs and see if it's larger than the non-determinism threshold.
But note: in Step 1, we are comparing R to runs with same seeds and same environment. That's the non-determinism check.
In Step 2, we are checking seed variance: if R has different seeds, then we expect it to be within the seed variance of the seed variance baseline.
In Step 3, we are checking environment drift: if R has the same seeds as some baseline but different environment, then we expect it to be different.
However, note that Step 2 and Step 3 might conflict? For example, if R has different seeds and different environment, then we would do both Step 2 and Step 3? Actually, Step 3 requires same seeds, so if R has different seeds, then Step 3 doesn't apply.
So:
code
For R:
If R has the same seeds as some baseline (with same hyperparameters and environment) -> do Step 1.
Else if R has different seeds but same environment as some baseline (with same hyperparameters) -> do Step 2.
If R has the same seeds but different environment as some baseline (with same hyperparameters) -> do Step 3.
If R has different seeds and different environment, then we might not have a direct baseline? Then we might have to rely on Step 2 and Step 3 separately? But note: Step 2 requires same environment, Step 3 requires same seeds. So we might not have a baseline.
Given the complexity, let's design the following:
code
We'll have a class that stores runs and can:
- Add a run
- For a given run R, find:
a) same_hyper_same_seed_same_env: list of runs (excluding R) with same hyperparameters (tolerance), same seeds, same environment.
b) same_hyper_diff_seed_same_env: list of runs with same hyperparameters, same environment, but different seeds.
c) same_hyper_same_seed_diff_env: list of runs with same hyperparameters, same seeds, but different environment.
Then, we can:
if a is not empty:
compute the mean and std of each metric at each step across a.
for each step in R, if |R[metric][step] - mean| > 3 * std (or if std is 0, then use a fixed tolerance) then flag non-determinism.
if b is not empty and R's seeds are not in the seeds of the baseline? Actually, if R's seeds are the same as in a, then we already did a. So if we are in b, then R's seeds are not the same as any in a? But note: a might be empty because we don't have runs with same seeds. Then we are in b? Actually, we are in b if R's seeds are different from the seeds in the baseline runs with same hyperparameters and environment.
Then, compute the mean and std across b (at each step). Then check if R is within 3 stds.
if c is not empty and R's seeds are the same as in c? Actually, c has same seeds but different environment. So if R's environment is the same as the baseline, then c is empty. So we do c only if R's environment is different from the baseline environment but same seeds.
Then, we can compute the difference between R and each run in c. We can also compute the mean of c and see the difference. We expect the difference to be larger than the non-determinism threshold.
But note: what if we have both a and c? That means we have runs with same seeds and same environment (a) and also runs with same seeds but different environment (c). Then for R, if R has same seeds and same environment as the baseline (so we are in a), then we do a. But we also might want to note that there is environment drift available? Actually, we are only comparing R to the same environment baseline.
Given the time, let's stick to:
code
We'll do:
non_determinism_check: compare to runs with same hyperparameters, same seeds, same environment.
seed_variance_check: compare to runs with same hyperparameters, same environment, but different seeds (only if R's seeds are not the same as the non_determinism group?).
env_drift_check: compare to runs with same hyperparameters, same seeds, but different environment.
And we'll do these checks independently.
Implementation:
code
We'll have:
def compare_run(self, run):
# Find the baseline groups
same_hyper = self.find_runs_by_hyperparameters(run.hyperparameters, tolerance=1e-6)
same_hyper_same_seed_same_env = [r for r in same_hyper if r.seeds == run.seeds and r.environment == run.environment and r.id != run.id]
same_hyper_diff_seed_same_env = [r for r in same_hyper if r.environment == run.environment and r.seeds != run.seeds]
same_hyper_same_seed_diff_env = [r for r in same_hyper if r.seeds == run.seeds and r.environment != run.environment]
# Check 1: non-determinism
if same_hyper_same_seed_same_env:
self._check_variance(run, same_hyper_same_seed_same_env, check_type='non-determinism')
# Check 2: seed variance
if same_hyper_diff_seed_same_env and not same_hyper_same_seed_same_env:
# We only do seed variance check if we don't have a non-determinism group?
# Actually, if we have non-determinism group, then we are in the same seed case, so we don't need seed variance check for this run.
# But note: what if we have both? Then we are in the same seed case, so we don't do seed variance.
# So we do seed variance only if we don't have same seed same env group?
# But what if we have same seed same env group, but we still want to know the seed variance? That's for a different run (with different seeds).
# So for the current run, if it has same seeds as the baseline, we do non-determinism. If it has different seeds, we do seed variance.
# So we can do:
# Actually, we can do seed variance check only if the run's seeds are not the same as any in the same_hyper group? But note: same_hyper_diff_seed_same_env has different seeds by definition.
# So we can do:
self._check_variance(run, same_hyper_diff_seed_same_env, check_type='seed variance')
# Check 3: environment drift
if same_hyper_same_seed_diff_env:
self._check_env_drift(run, same_hyper_same_seed_diff_env)
In _check_variance, we compute for each metric and each step:
mean = mean of baseline runs at that step
std = std of baseline runs at that step
if std == 0:
tolerance = 1e-6
else:
tolerance = 3 * std
if abs(run.metric[step] - mean) > tolerance:
flag
In _check_env_drift, we can compute the difference between R and each run in the baseline, and then compare to the non-determinism threshold? Or just report the difference.
But note: we don't have a non-determinism threshold for the environment drift? We can set a threshold for what we consider significant drift? Or just report the difference.
Alternatively, we can compute the mean and std of the baseline runs (with same seeds, different environment) and then see if R is within 3 stds? But that would be checking if R is reproducible in the new environment? Actually, we want to see if the environment caused a drift. So we can compute the difference between R and the mean of the baseline runs (with same seeds, different environment) and see if it's larger than the non-determinism threshold (from the non-determinism group) by a factor (say 10).
But we might not have a non-determinism group? Then we use a fixed threshold.
So in _check_env_drift:
We can have:
non_det_threshold = self._get_non_determinism_threshold() # maybe from the non-determinism group if available, else 1e-6
Then, for each step:
diff = abs(run.metric[step] - baseline_mean[step])
if diff > 10 * non_det_threshold:
flag
But note: the baseline runs in same_hyper_same_seed_diff_env have different environment, so we expect the difference to be larger than non_det_threshold. So we set a factor.
However, note that the non_det_threshold might be very small (1e-6) and the environment drift might be 0.01, so 10 times might be 1e-5 which is still very small. We might need a larger factor? Or we can just report the difference and let the user decide.
Given the complexity and the fact that we might not have all groups, we might just report:
code
- For non-determinism: the maximum absolute difference across steps and metrics, and whether it's above the threshold.
- For seed variance: the maximum absolute difference and whether it's within 3 stds.
- For environment drift: the maximum absolute difference and whether it's above 10 times the non-determinism threshold.
But note: the non-determinism threshold might be computed from the non-determinism group. If we don't have that group, we use a fixed threshold.
def add_run(self, run):
self.runs.append(run)
def find_runs_by_hyperparameters(self, hyperparameters, tolerance=1e-6):
result = []
for run in self.runs:
if self._hyperparameters_match(run.hyperparameters, hyperparameters, tolerance):
result.append(run)
return result
def _hyperparameters_match(self, h1, h2, tolerance):
# as above
def compare_run(self, run):
# Find runs with same hyperparameters (tolerance)
same_hyper = self.find_runs_by_hyperparameters(run.hyperparameters, tolerance=1e-6)
# Split into groups
same_hyper_same_seed_same_env = [r for r in same_hyper if r.seeds == run.seeds and r.environment == run.environment and r.run_id != run.run_id]
same_hyper_diff_seed_same_env = [r for r in same_hyper if r.environment == run.environment and r.seeds != run.seeds]
same_hyper_same_seed_diff_env = [r for r in same_hyper if r.seeds == run.seeds and r.environment != run.environment]
# Check 1: non-determinism
if same_hyper_same_seed_same_env:
self._check_variance(run, same_hyper_same_seed_same_env, check_type='non-determinism')
# Check 2: seed variance (only if we don't have same_hyper_same_seed_same_env? Actually, if we have same_hyper_same_seed_same_env, then the run's seeds are the same as the baseline, so we don't need seed variance. So we do seed variance only if same_hyper_same_seed_same_env is empty and same_hyper_diff_seed_same_env is not empty.
if not same_hyper_same_seed_same_env and same_hyper_diff_seed_same_env:
self._check_variance(run, same_hyper_diff_seed_same_env, check_type='seed variance')
# Check 3: environment drift
if same_hyper_same_seed_diff_env:
self._check_env_drift(run, same_hyper_same_seed_diff_env)
def _check_variance(self, run, baseline_runs, check_type):
# For each metric in run.metrics:
for metric_name, values in run.metrics.items():
# Extract steps and values for run
run_steps = [v['step'] for v in values]
run_values = [v['value'] for v in values]
# For each step, collect baseline values from baseline_runs that have that step
for i, step in enumerate(run_steps):
baseline_vals = []
for b in baseline_runs:
# Find the value for this metric and step in b
b_vals = b.metrics.get(metric_name, [])
for bv in b_vals:
if bv['step'] == step:
baseline_vals.append(bv['value'])
break
if not baseline_vals:
# No baseline value at this step, skip
continue
mean = np.mean(baseline_vals)
std = np.std(baseline_vals)
if std == 0:
tolerance = 1e-6
else:
tolerance = 3 * std
if abs(run_values[i] - mean) > tolerance:
print(f"Warning: {check_type} - Metric {metric_name} at step {step}: run value {run_values[i]} differs from baseline mean {mean} by {abs(run_values[i]-mean)} (tolerance {tolerance})")
def _check_env_drift(self, run, baseline_runs):
# We need a non-determinism threshold. Let's try to get it from the non-determinism group if available?
# But we don't have it here. We can compute the non-determinism threshold from runs with same hyperparameters, same seeds, same environment?
# But we don't have that in this function.
# Alternatively, we can set a fixed threshold? Or we can compute the non-determinism threshold from the baseline_runs?
# But note: the baseline_runs are same hyperparameters, same seeds, different environment. They might have high variance due to environment.
# We want to see if the difference between run and the baseline (same seeds, different environment) is larger than the non-determinism threshold.
# We can compute the non-determinism threshold from the non-determinism group if we have it. But we don't have that in this function.
# Let's change the design: we first compute the non-determinism threshold from the non-determinism group (if exists) and store it, then use it in env drift.
# Alternatively, we can do:
# For each metric and step, we have the run value and the baseline values (from same seeds, different environment). We compute the mean of the baseline values.
# Then, we compute the difference.
# We can then compare this difference to a fixed threshold (say 0.01) or to the non-determinism threshold.
# Since we don't have the non-determinism threshold in this function, let's assume we have a fixed threshold for non-determinism, say 1e-5.
non_det_threshold = 1e-5
for metric_name, values in run.metrics.items():
run_steps = [v['step'] for v in values]
run_values = [v['value'] for v in values]
for i, step in enumerate(run_steps):
baseline_vals = []
for b in baseline_runs:
b_vals = b.metrics.get(metric_name, [])
for bv in b_vals:
if bv['step'] == step:
baseline_vals.append(bv['value'])
break
if not baseline_vals:
continue
baseline_mean = np.mean(baseline_vals)
diff = abs(run_values[i] - baseline_mean)
if diff > 10 * non_det_threshold:
print(f"Warning: environment drift - Metric {metric_name} at step {step}: run value {run_values[i]} differs from baseline (same seeds, different env) mean {baseline_mean} by {diff} (non-det threshold {non_det_threshold})")
from dataclasses import dataclass, field
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime
import json
import hashlib
import os
import platform
import pkg_resources
import numpy as np
from scipy import stats
@dataclass
class SeedInfo:
"""Track all random seeds used in an experiment"""
python_seed: Optional[int] = None
numpy_seed: Optional[int] = None
torch_seed: Optional[int] = None
tensorflow_seed: Optional[int] = None
jax_seed: Optional[int] = None
cuda_deterministic: bool = False
cudnn_deterministic: bool = False
custom_seeds: Dict[str, int] = field(default_factory=dict)
def to_dict(self) -> Dict:
return {k: v for k, v in self.__dict__.items() if v is not None}
def get_all_seeds(self) -> Dict[str, int]:
return {**self.to_dict(), **self.custom_seeds}
@dataclass
class EnvironmentInfo:
"""Capture complete computational environment"""
# System info
platform: str = platform.platform()
python_version: str = platform.python_version()
cpu_info: str = platform.processor()
# Package versions (key libraries)
packages: Dict[str, str] = field(default_factory=dict)
# Hardware
gpu_count: int = 0
gpu_names: List[str] = field(default_factory=list)
cuda_version: Optional[str] = None
cudnn_version: Optional[str] = None
# Compute context
is_docker: bool = False
is_cloud: bool = False
cloud_provider: Optional[str] = None
instance_type: Optional[str] = None
def collect_current_env(self) -> 'EnvironmentInfo':
"""Auto-collect current environment information"""
env = EnvironmentInfo()
# Collect package versions for common ML libraries
packages_to_check = [
'numpy', 'torch', 'tensorflow', 'jax', 'jaxlib',
'scikit-learn', 'pandas', 'matplotlib', 'seaborn',
'hydra', 'wandb', 'mlflow', 'tensorboard',
'transformers', 'datasets', 'accelerate'
]
for pkg in packages_to_check:
try:
version = pkg_resources.get_distribution(pkg).version
env.packages[pkg] = version
except pkg_resources.DistributionNotFound:
pass
# GPU detection
try:
import torch
env.gpu_count = torch.cuda.device_count()
env.gpu_names = [torch.cuda.get_device_name(i)
for i in range(env.gpu_count)]
if env.gpu_count > 0:
env.cuda_version = torch.version.cuda
except ImportError:
pass
try:
import tensorflow as tf
gpus = tf.config.list_physical_devices('GPU')
env.gpu_count = len(gpus)
if gpus:
# TensorFlow doesn't easily provide GPU names
env.gpu_names = [f"GPU_{i}" for i in range(env.gpu_count)]
except ImportError:
pass
# Docker detection
env.is_docker = os.path.exists('/.dockerenv')
return env
def compute_hash(self) -> str:
"""Create deterministic hash of environment"""
env_dict = {
'python_version': self.python_version,
'packages': sorted(self.packages.items()),
'cuda_version': self.cuda_version,
'cudnn_version': self.cudnn_version,
'is_docker': self.is_docker
}
env_str = json.dumps(env_dict, sort_keys=True)
return hashlib.sha256(env_str.encode()).hexdigest()[:16]
def to_dict(self) -> Dict:
return {
'platform': self.platform,
'python_version': self.python_version,
'cpu_info': self.cpu_info,
'packages': self.packages,
'gpu_count': self.gpu_count,
'gpu_names': self.gpu_names,
'cuda_version': self.cuda_version,
'cudnn_version': self.cudnn_version,
'is_docker': self.is_docker,
'is_cloud': self.is_cloud,
'cloud_provider': self.cloud_provider,
'instance_type': self.instance_type,
'env_hash': self.compute_hash()
}
@dataclass
class MetricSnapshot:
"""Single point in metric history"""
step: int
value: float
timestamp: datetime = field(default_factory=datetime.now)
def to_dict(self) -> Dict:
return {
'step': self.step,
'value': self.value,
'timestamp': self.timestamp.isoformat()
}
@dataclass
class RunMetadata:
"""Complete metadata for a single training run"""
run_id: str
experiment_name: str
start_time: datetime
end_time: Optional[datetime] = None
# Seeds & Environment
seeds: SeedInfo
environment: EnvironmentInfo
# Configuration
hyperparameters: Dict[str, Any]
config_hash: str # Hash of hyperparameters + code version
# Metrics
metrics_history: Dict[str, List[MetricSnapshot]] = field(default_factory=dict)
# Code versioning
git_commit: Optional[str] = None
git_branch: Optional[str] = None
code_diff: Optional[str] = None
# System context
hostname: str = platform.node()
user: str = os.getenv('USER', 'unknown')
def finalize(self):
"""Call when run completes"""
self.end_time = datetime.now()
def get_metric_at_step(self, metric_name: str, step: int) -> Optional[float]:
"""Get metric value at specific step"""
if metric_name not in self.metrics_history:
return None
for snapshot in self.metrics_history[metric_name]:
if snapshot.step == step:
return snapshot.value
return None
def get_metric_trajectory(self, metric_name: str) -> List[Tuple[int, float]]:
"""Get full (step, value) pairs for a metric"""
if metric_name not in self.metrics_history:
return []
return [(s.step, s.value) for s in self.metrics_history[metric_name]]
def compute_config_hash(self) -> str:
"""Create hash of hyperparameters + critical config"""
config_str = json.dumps({
'hyperparameters': self.hyperparameters,
'seeds': self.seeds.get_all_seeds(),
'git_commit': self.git_commit
}, sort_keys=True, default=str)
return hashlib.sha256(config_str.encode()).hexdigest()[:16]
class ReproducibilityMonitor:
"""Main class for tracking and analyzing reproducibility"""
def __init__(self, storage_path: str = "./reproducibility_logs"):
self.storage_path = storage_path
os.makedirs(storage_path, exist_ok=True)
self.runs: Dict[str, RunMetadata] = {}
self.comparison_results: List[Dict] = []
# Variance thresholds (configurable)
self.metric_variance_thresholds = {
'accuracy': 0.001, # 0.1% variance allowed
'loss': 0.01, # Absolute difference allowed
'default': 0.005 # Default 0.5% variance
}
# Environment change impact thresholds
self.env_drift_thresholds = {
'major_version_change': 0.05, # 5% metric change
'minor_version_change': 0.02, # 2% metric change
'patch_version_change': 0.005, # 0.5% metric change
}
def register_run(self, run: RunMetadata) -> str:
"""Register a new training run"""
run.config_hash = run.compute_config_hash()
run_id = run.run_id
# Save to disk
self._save_run(run)
self.runs[run_id] = run
# Auto-analyze against existing runs
self._analyze_run_against_baselines(run)
return run_id
def _save_run(self, run: RunMetadata):
"""Save run metadata to disk"""
run_dict = {
'run_id': run.run_id,
'experiment_name': run.experiment_name,
'start_time': run.start_time.isoformat(),
'end_time': run.end_time.isoformat() if run.end_time else None,
'seeds': run.seeds.to_dict(),
'environment': run.environment.to_dict(),
'hyperparameters': run.hyperparameters,
'config_hash': run.config_hash,
'metrics_history': {
metric: [s.to_dict() for s in snapshots]
for metric, snapshots in run.metrics_history.items()
},
'git_commit': run.git_commit,
'git_branch': run.git_branch,
'hostname': run.hostname,
'user': run.user
}
filepath = os.path.join(self.storage_path, f"{run.run_id}.json")
with open(filepath, 'w') as f:
json.dump(run_dict, f, indent=2, default=str)
def load_all_runs(self):
"""Load all runs from storage"""
for filename in os.listdir(self.storage_path):
if filename.endswith('.json'):
filepath = os.path.join(self.storage_path, filename)
with open(filepath, 'r') as f:
run_dict = json.load(f)
# Reconstruct RunMetadata
seeds = SeedInfo(**run_dict['seeds'])
env = EnvironmentInfo()
env_dict = run_dict['environment']
for k, v in env_dict.items():
if hasattr(env, k):
setattr(env, k, v)
run = RunMetadata(
run_id=run_dict['run_id'],
experiment_name=run_dict['experiment_name'],
start_time=datetime.fromisoformat(run_dict['start_time']),
end_time=datetime.fromisoformat(run_dict['end_time']) if run_dict['end_time'] else None,
seeds=seeds,
environment=env,
hyperparameters=run_dict['hyperparameters'],
config_hash=run_dict['config_hash'],
git_commit=run_dict.get('git_commit'),
git_branch=run_dict.get('git_branch'),
hostname=run_dict.get('hostname', platform.node()),
user=run_dict.get('user', os.getenv('USER', 'unknown'))
)
# Reconstruct metrics
for metric, snapshots in run_dict['metrics_history'].items():
run.metrics_history[metric] = [
MetricSnapshot(
step=s['step'],
value=s['value'],
timestamp=datetime.fromisoformat(s['timestamp'])
) for s in snapshots
]
self.runs[run.run_id] = run
def _analyze_run_against_baselines(self, new_run: RunMetadata):
"""Compare new run against existing runs"""
comparisons = []
# Find candidate baseline runs
candidates = self._find_baseline_candidates(new_run)
for baseline in candidates:
comparison = self._compare_runs(new_run, baseline)
comparisons.append(comparison)
self.comparison_results.extend(comparisons)
return comparisons
def _find_baseline_candidates(self, run: RunMetadata) -> List[RunMetadata]:
"""Find runs to compare against based on config similarity"""
candidates = []
for existing_run in self.runs.values():
# Skip self-comparison
if existing_run.run_id == run.run_id:
continue
# Same experiment name?
if existing_run.experiment_name != run.experiment_name:
continue
# Similar hyperparameters (exact match for now, could add tolerance)
if existing_run.hyperparameters != run.hyperparameters:
continue
candidates.append(existing_run)
return candidates
def _compare_runs(self, run1: RunMetadata, run2: RunMetadata) -> Dict:
"""Detailed comparison between two runs"""
comparison = {
'run1_id': run1.run_id,
'run2_id': run2.run_id,
'timestamp': datetime.now().isoformat(),
'seed_comparison': self._compare_seeds(run1.seeds, run2.seeds),
'environment_comparison': self._compare_environments(run1.environment, run2.environment),
'metrics_variance': self._compute_metrics_variance(run1, run2),
'reproducible': False,
'drift_sources': []
}
# Determine reproducibility
seed_match = comparison['seed_comparison']['all_seeds_match']
env_similar = comparison['environment_comparison']['is_similar']
if seed_match and env_similar:
# Check metrics variance
max_variance = max(
v['max_abs_diff'] for v in comparison['metrics_variance'].values()
) if comparison['metrics_variance'] else 0
# Use appropriate threshold based on metric type
threshold = self.metric_variance_thresholds['default']
if 'accuracy' in comparison['metrics_variance']:
threshold = self.metric_variance_thresholds['accuracy']
elif 'loss' in comparison['metrics_variance']:
threshold = self.metric_variance_thresholds['loss']
comparison['reproducible'] = max_variance <= threshold
# Identify drift sources
if not seed_match:
comparison['drift_sources'].append('seed_mismatch')
if not env_similar:
comparison['drift_sources'].append('environment_drift')
if not comparison['reproducible'] and seed_match and env_similar:
comparison['drift_sources'].append('non_determinism')
return comparison
def _compare_seeds(self, seeds1: SeedInfo, seeds2: SeedInfo) -> Dict:
"""Compare seed configurations"""
seeds1_dict = seeds1.get_all_seeds()
seeds2_dict = seeds2.get_all_seeds()
all_keys = set(seeds1_dict.keys()) | set(seeds2_dict.keys())
matches = []
mismatches = []
for key in all_keys:
val1 = seeds1_dict.get(key)
val2 = seeds2_dict.get(key)
if val1 == val2:
matches.append(key)
else:
mismatches.append({
'seed_type': key,
'value1': val1,
'value2': val2
})
return {
'all_seeds_match': len(mismatches) == 0,
'matching_seeds': matches,
'mismatched_seeds': mismatches,
'seed_coverage': {
'run1_only': [k for k in seeds1_dict if k not in seeds2_dict],
'run2_only': [k for k in seeds2_dict if k not in seeds1_dict]
}
}
def _compare_environments(self, env1: EnvironmentInfo, env2: EnvironmentInfo) -> Dict:
"""Compare environment configurations"""
differences = {
'package_changes': [],
'hardware_changes': [],
'system_changes': []
}
# Compare package versions
all_packages = set(env1.packages.keys()) | set(env2.packages.keys())
for pkg in all_packages:
v1 = env1.packages.get(pkg)
v2 = env2.packages.get(pkg)
if v1 != v2:
diff_type = self._classify_version_change(v1, v2)
differences['package_changes'].append({
'package': pkg,
'version1': v1,
'version2': v2,
'change_type': diff_type
})
# Compare hardware
if env1.gpu_count != env2.gpu_count:
differences['hardware_changes'].append({
'change': 'gpu_count',
'value1': env1.gpu_count,
'value2': env2.gpu_count
})
# Compare CUDA versions
if env1.cuda_version != env2.cuda_version:
differences['hardware_changes'].append({
'change': 'cuda_version',
'value1': env1.cuda_version,
'value2': env2.cuda_version
})
# Check environment similarity
is_similar = (
env1.python_version == env2.python_version and
env1.is_docker == env2.is_docker and
len(differences['package_changes']) == 0
)
return {
'is_similar': is_similar,
'differences': differences,
'env_hash1': env1.compute_hash(),
'env_hash2': env2.compute_hash(),
'hashes_match': env1.compute_hash() == env2.compute_hash()
}
def _classify_version_change(self, v1: str, v2: str) -> str:
"""Classify version change as major/minor/patch"""
if v1 is None or v2 is None:
return 'unknown'
try:
parts1 = [int(p) for p in v1.split('.')]
parts2 = [int(p) for p in v2.split('.')]
if parts1[0] != parts2[0]:
return 'major'
elif len(parts1) > 1 and len(parts2) > 1 and parts1[1] != parts2[1]:
return 'minor'
else:
return 'patch'
except (ValueError, IndexError):
return 'unknown'
def _compute_metrics_variance(self, run1: RunMetadata, run2: RunMetadata) -> Dict:
"""Compute variance between two runs' metrics"""
variances = {}
# Find common metrics
common_metrics = set(run1.metrics_history.keys()) & set(run2.metrics_history.keys())
for metric in common_metrics:
traj1 = run1.get_metric_trajectory(metric)
traj2 = run2.get_metric_trajectory(metric)
# Align by step
steps1 = {step: val for step, val in traj1}
steps2 = {step: val for step, val in traj2}
common_steps = set(steps1.keys()) & set(steps2.keys())
if not common_steps:
continue
diffs = []
for step in sorted(common_steps):
diff = abs(steps1[step] - steps2[step])
diffs.append(diff)
if diffs:
variances[metric] = {
'max_abs_diff': max(diffs),
'mean_abs_diff': np.mean(diffs),
'std_diff': np.std(diffs),
'final_value_diff': abs(traj1[-1][1] - traj2[-1][1]) if traj1 and traj2 else None,
'relative_diff_end': self._relative_diff(traj1[-1][1], traj2[-1][1]) if traj1 and traj2 else None,
'num_common_steps': len(common_steps)
}
return variances
def _relative_diff(self, v1: float, v2: float) -> float:
"""Compute relative difference"""
if v1 == 0 and v2 == 0:
return 0.0
if v1 == 0 or v2 == 0:
return float('inf')
return abs(v1 - v2) / ((abs(v1) + abs(v2)) / 2)
def get_reproducibility_report(self, run_id: str) -> Dict:
"""Generate detailed reproducibility report for a run"""
if run_id not in self.runs:
return {"error": f"Run {run_id} not found"}
run = self.runs[run_id]
comparisons = [c for c in self.comparison_results
if c['run1_id'] == run_id or c['run2_id'] == run_id]
report = {
'run_id': run_id,
'experiment': run.experiment_name,
'seeds': run.seeds.to_dict(),
'environment_hash': run.environment.compute_hash(),
'config_hash': run.config_hash,
'reproducibility_score': self._compute_reproducibility_score(run, comparisons),
'comparisons': comparisons,
'alerts': self._generate_alerts(run, comparisons)
}
return report
def _compute_reproducibility_score(self, run: RunMetadata, comparisons: List[Dict]) -> float:
"""Compute 0-1 reproducibility score"""
if not comparisons:
return 1.0 # No comparisons available
reproducible_count = sum(1 for c in comparisons if c['reproducible'])
return reproducible_count / len(comparisons)
def _generate_alerts(self, run: RunMetadata, comparisons: List[Dict]) -> List[Dict]:
"""Generate alert list for potential issues"""
alerts = []
for comp in comparisons:
if not comp['reproducible']:
alert = {
'severity': 'warning' if 'non_determinism' in comp['drift_sources'] else 'critical',
'type': 'reproducibility_failure',
'comparison': comp['run1_id'] if comp['run2_id'] == run.run_id else comp['run2_id'],
'drift_sources': comp['drift_sources'],
'max_variance': max(
v['max_abs_diff'] for v in comp['metrics_variance'].values()
) if comp['metrics_variance'] else 0
}
alerts.append(alert)
# Check for seed completeness
seed_dict = run.seeds.get_all_seeds()
if not seed_dict:
alerts.append({
'severity': 'critical',
'type': 'missing_seeds',
'message': 'No seeds recorded for this run'
})
# Check for environment drift if comparing to older runs
for comp in comparisons:
if 'environment_drift' in comp['drift_sources']:
env_diff = comp['environment_comparison']['differences']
for pkg_change in env_diff['package_changes']:
if pkg_change['change_type'] == 'major':
alerts.append({
'severity': 'critical',
'type': 'major_version_change',
'package': pkg_change['package'],
'versions': f"{pkg_change['version1']} → {pkg_change['version2']}"
})
return alerts
def find_non_reproducible_runs(self, threshold: float = 0.1) -> List[Dict]:
"""Find runs with low reproducibility scores"""
problematic = []
for run_id in self.runs:
report = self.get_reproducibility_report(run_id)
if report['reproducibility_score'] < threshold:
problematic.append(report)
return sorted(problematic,
key=lambda x: x['reproducibility_score'])
def export_comparison_matrix(self) -> Dict:
"""Export pairwise comparison matrix"""
runs = list(self.runs.values())
matrix = {}
for i, run1 in enumerate(runs):
matrix[run1.run_id] = {}
for j, run2 in enumerate(runs):
if i == j:
matrix[run1.run_id][run2.run_id] = {
'reproducible': True,
'max_variance': 0.0
}
else:
# Find existing comparison or compute
comp = next((c for c in self.comparison_results
if (c['run1_id'] == run1.run_id and c['run2_id'] == run2.run_id) or
(c['run1_id'] == run2.run_id and c['run2_id'] == run1.run_id)), None)
if comp:
matrix[run1.run_id][run2.run_id] = {
'reproducible': comp['reproducible'],
'max_variance': max(
v['max_abs_diff'] for v in comp['metrics_variance'].values()
) if comp['metrics_variance'] else 0,
'drift_sources': comp['drift_sources']
}
else:
# Compute on-the-fly
comp = self._compare_runs(run1, run2)
matrix[run1.run_id][run2.run_id] = {
'reproducible': comp['reproducible'],
'max_variance': max(
v['max_abs_diff'] for v in comp['metrics_variance'].values()
) if comp['metrics_variance'] else 0,
'drift_sources': comp['drift_sources']
}
return matrix