Phase 06 / Data & checkpoint recovery
Track experiments and lineage with MLflow
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 70 minutes · CPU practice
Track, retrieve and compare two JAX experiments using explicit data identity, metric steps and downloaded model artifacts.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Asynchronous checkpoints and failure boundaries
Hardware: CPU
Setup help: Python, notebook, or Cloud TPU VM
Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.
Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txtpy -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txtAfter activation, run the complete worked example from that same folder:
python phases/06-recovery/06-track-experiments-and-lineage-with-mlflow/code/main.py.\.venv\Scripts\python.exe phases/06-recovery/06-track-experiments-and-lineage-with-mlflow/code/main.pyFor an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.
Download this lesson’s notebook. Open it with a Python kernel using the course environment. Run cells from the top after restarting the kernel; experiments depend on earlier definitions.
For local Jupyter, first install the course requirements using the Local Python steps, then use your environment’s Python to start Jupyter:
python -m pip install jupyterlab
python -m jupyter lab.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyter labSelect the downloaded recovery-06.ipynb file in JupyterLab. The notebook contains reference solutions; make your prediction and attempt each practice task before opening them. Restart the kernel before changing logical device setup.
The worked reference for this lesson is CPU-validated. Some references explicitly configure logical CPU devices; setting JAX_PLATFORMS does not adapt them to a TPU. Follow the execution matrix and reviewed multi-host example before attempting a target run.
For accelerator preparation, study TPU setup, observed runtime receipts, checkpointed jobs and precision and retained traces. Current receipts cover bounded v5e1 launch, resume, and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt is limited to its recorded source, environment, cases, and hardware. It does not qualify all lessons or TPU configurations. Cloud provisioning is optional for CPU learning.
Check: Validation MSE by learning rate: {0.02: 0.1199446..., 0.15: 5.04947...e-10} Verified 30 logged steps per run; selected and reloaded the better validation candidate.
Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.
What you will be able to do
- Decide what makes runs comparable
- Give data and code an identity
- Use a database and a deliberate artifact location
- Log at a useful boundary
The problem
You ran two training configurations yesterday. Today you remember which curve looked better, but not which dataset, preprocessing or checkpoint produced it. Let’s make the comparison reproducible: train two small JAX models, log them to a real local MLflow database, then retrieve the selected run and its artifact.
The idea
A tracker is useful when a plotted point leads back to the data, source, configuration and artifact that produced it. A run name or best label is not enough to identify a deployable checkpoint or reproduce its evaluation.
Make every metric point traceable
A metric record needs its run, data identity, reduction, and measurement boundary. Two validation_mse values at step 30 are comparable here because both runs use the same four validation rows and mean-squared-error definition, and the training curve records post-update values. A name and step alone would not establish that.
The example logs training history and a coefficient artifact, then retrieves the recorded metrics and artifact through MlflowClient. Selecting a run identifies a candidate run; retain the exact artifact identity too, since a run can contain more than one checkpoint or model file.
Decide what makes runs comparable
Both runs fit from zero-initialized weight and bias on the same five training points for updates. Only the learning rate changes: or . The validation set has four separate input values, and the code calculates its mean squared error after the final update.
The retrieved validation MSEs are about and , respectively. This controlled comparison supports choosing the latter on this fixture. It does not establish an optimal rate across wall-clock budgets or data distributions.
Give data and code an identity
The SHA-256 tag covers the bytes of the five training features and targets. Changing one target produces a different digest in the practice check. This makes a content change visible even when the filename, shape, and row count stay the same.
For a larger dataset, also record split IDs, schema, preprocessing, and source revision. A hash identifies the checked bytes but does not describe how examples were selected or prove the data are correct. Tie the model artifact and run to the same data and code identities.
Use a database and a deliberate artifact location
The exercise creates a temporary SQLite tracking database and local artifact directory. Run parameters and metric histories live in the database; each candidate's model.json stores its coefficients and preprocessing note. The client then retrieves metric steps and downloads the selected artifact, so the visible curve corresponds to recorded data.
This is a local MLflow 3.16.1 example. A shared tracking service adds requirements for database support, artifact access, authentication, backups, and retention that this temporary setup does not test.
Run instructions: From the course workspace, install the tested CPU dependencies
# Run from the course workspace, install the tested cpu dependencies using the course Python environment
python -m pip install -r requirements-cpu.txtExpected:
MLflow 3.16.1 and the course numerical packages are installed in the selected environment.
Log at a useful boundary
JAX dispatch can be asynchronous; converting the loss to a Python float waits for that scalar before MLflow records it. Here each of 30 points is measured after its update, and validation MSE is computed at step 30 on four rows. The independent host calculation confirms the validation denominator and target values.
Logging every update makes the curve easy to retrieve in this small run. For larger jobs, choose a reporting cadence and keep it distinct from checkpoint cadence so metric collection does not become the training schedule.
Retrieve before trusting the dashboard
The client fetches all 30 training points for each run, checks their step numbers and values against the local histories, verifies the data tag, and orders candidates by retrieved validation MSE. It then downloads and inspects the selected coefficient artifact. The plotted rate (0.15) curve falls faster and ends lower than rate (0.02), matching the retrieved values.
Training curves alone do not choose a release: in this same comparison the validation result provides the selection measure, and a final untouched test plus runtime/release checks remain separate. The plot is evidence of these two configurations, not a general recommendation.
Continue into a real registry
A registry alias such as champion is a mutable pointer to a registered model version. Resolve it to the immutable version and artifact identity when recording a release. Moving that pointer does not deploy a service, validate the artifact in a runtime, or make a validation set into a final test set.
Run instructions: Keep the local database and artifacts in a new output folder
# Run keep the local database and artifacts in a new output folder using the course Python environment
python projects/engineering-release/mlflow_lab.py --output ./engineering-runExpected:
Two training runs, two registered versions, one prompt version, one three-span trace and a model.json artifact are written. Use a fresh folder for another independent run.
A zero training error can be the wrong release
The training-lookup artifact stores all five pairs and returns zero for unseen inputs. It therefore gets training MSE (0), but all four validation x values are unseen. Its reloaded predictions are against , giving validation MSE (6). The retrieved linear candidates have much smaller held-out errors on the same split.
The exercise computes both metrics from reloaded artifacts, so the contrast is about model behavior rather than a fabricated record. A training-only selection picks the lookup; the validation-based selection rejects it. Keep the evaluation split separate from fitting and do not infer performance outside this small regression fixture.
Compare the runs that MLflow actually recorded
Predict before looking: Do the two runs improve at the same rate, and can these training curves select a release by themselves?
Read the figure
The horizontal axis is completed update through ; the vertical axis is post-update training MSE on a logarithmic scale, so equal vertical distances correspond to multiplicative ratios. Both runs start from zero and share the same training data; rate falls faster and ends near , while rate ends near .
Connect it to the computation
The retrieved MLflow history confirms each plotted training point, while the separately logged validation MSEs are about and . For this fixed fixture, both measures favor rate ; inspect the retrieved artifact and validation protocol before selection. The graph is not a universal rate ranking or a final test result.
Figure data and execution details
Open full-size figureDownload data and provenance
The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.
Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.
1 Set MLflow options and load hashing and serialization tools
Set the two MLflow environment options before importing the package, then import hashing, JSON, temporary-directory, and NumPy helpers.
import os
# Set MLFLOW_DISABLE_AGENT_HINT before importing its runtime.
os.environ['MLFLOW_DISABLE_AGENT_HINT'] = '1'
# Set MLFLOW_ENABLE_TELEMETRY before importing its runtime.
os.environ['MLFLOW_ENABLE_TELEMETRY'] = 'false'
import hashlib, json, tempfile
from pathlib import Path
import numpy as npSetting these options before MLflow loads makes the run quiet and local. The SHA-256 digest will identify the exact synthetic training arrays.
2 Define the synthetic regression data and JAX optimizer
Import JAX and MLflow, create training points on , and reserve separate validation points.
import jax
import jax.numpy as jnp
import mlflow
from mlflow import MlflowClient
x = jnp.array([-2., -1., 0., 1., 2.])
y = 2 * x + 1The training and validation inputs come from the same known line but contain different x values. The objective is mean squared error; jax.grad supplies each gradient step.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
3 Log, read back, and independently validate two learning-rate runs
Hash the data, train each rate in a temporary SQLite-backed MLflow experiment, log metrics and model values, then read the records back and select by validation MSE.
vx = jnp.array([-1.5, -.5, .5, 1.5])
vy = 2 * vx + 1
objective = lambda p: jnp.mean((p[0] * x + p[1] - y) ** 2)
update = jax.jit(lambda p, rate: p - rate * jax.grad(objective)(p))
# Transfer the device result to the host for an independent NumPy comparison.
data_hash = hashlib.sha256(np.asarray(x).tobytes() + np.asarray(y).tobytes()).hexdigest()
curves, validation, run_ids = [], [], []
candidate_artifacts = []
# Keep this run’s database and artifacts in a scratch directory removed on exit.
with tempfile.TemporaryDirectory(prefix='tracking-lesson-') as folder:
root = Path(folder)
mlflow.set_tracking_uri('sqlite:///' + str(root / 'tracking.db'))
client = MlflowClient()
experiment = client.create_experiment('two-rates', artifact_location=(root / 'artifacts').as_uri())
for rate in [.02, .15]:
p = jnp.zeros(2)
history = []
with mlflow.start_run(experiment_id=experiment) as run:
mlflow.log_params({'rate': rate, 'updates': 30})
# Check which hardware backend (`cpu`, `gpu`, or `tpu`) JAX selected for ``.
mlflow.set_tags({'data_sha256': data_hash, 'jax': jax.__version__, 'backend': jax.default_backend(), 'metric_boundary': 'after update'})
for step in range(1, 31):
p = update(p, rate)
metric = float(objective(p))
history.append(metric)
mlflow.log_metric('train_mse', metric, step=step)
held = float(jnp.mean((p[0] * vx + p[1] - vy) ** 2))
# Independent host arithmetic checks what the reported validation metric means.
oracle = sum((float(p[0]) * t + float(p[1]) - (2 * t + 1)) ** 2 for t in [-1.5, -.5, .5, 1.5]) / 4
assert abs(held - oracle) < 1e-6
mlflow.log_metric('validation_mse', held, step=30)
model_record = {'kind': 'linear', 'weight': float(p[0]), 'bias': float(p[1]), 'preprocessing': 'one unscaled scalar feature'}
candidate_artifacts.append(model_record)
mlflow.log_dict(model_record, 'model.json')
run_ids.append(run.info.run_id)
curves.append(history)
validation.append(held)
saved = client.get_metric_history(run_ids[-1], 'train_mse')
assert [m.step for m in saved] == list(range(1, 31))
np.testing.assert_allclose([m.value for m in saved], history)
assert client.get_run(run_ids[-1]).data.tags['data_sha256'] == data_hash
selected = client.search_runs([experiment], order_by=['metrics.validation_mse ASC'])[0]
assert selected.info.run_id == run_ids[int(np.argmin(validation))]
artifact = client.download_artifacts(selected.info.run_id, 'model.json')
restored = json.loads(Path(artifact).read_text())
assert abs(restored['weight'] - 2) < .001 and abs(restored['bias'] - 1) < .001The host-side validation calculation checks what the logged validation metric measures. Readback verifies step numbers, tags, and the saved model artifact; comparing validation scores selects the candidate without treating training loss as the selection criterion.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jnp.mean(x, axis=..., keepdims=...): Averages JAX array values along the selected axis.jax.jit(fn) / @jax.jit: Traces a function for its input signatures and compiles it; changed shapes, dtypes, or static arguments can trigger another compilation.jax.grad(loss_fn)(params, ...): Transforms a scalar-output function into one returning the gradient PyTree with the same structure asparams.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
import os
# Set MLFLOW_DISABLE_AGENT_HINT before importing its runtime.
os.environ['MLFLOW_DISABLE_AGENT_HINT'] = '1'
# Set MLFLOW_ENABLE_TELEMETRY before importing its runtime.
os.environ['MLFLOW_ENABLE_TELEMETRY'] = 'false'
import hashlib, json, tempfile
from pathlib import Path
import numpy as np
import jax
import jax.numpy as jnp
import mlflow
from mlflow import MlflowClient
x = jnp.array([-2., -1., 0., 1., 2.])
y = 2 * x + 1
vx = jnp.array([-1.5, -.5, .5, 1.5])
vy = 2 * vx + 1
objective = lambda p: jnp.mean((p[0] * x + p[1] - y) ** 2)
update = jax.jit(lambda p, rate: p - rate * jax.grad(objective)(p))
# Transfer the device result to the host for an independent NumPy comparison.
data_hash = hashlib.sha256(np.asarray(x).tobytes() + np.asarray(y).tobytes()).hexdigest()
curves, validation, run_ids = [], [], []
candidate_artifacts = []
# Keep this run’s database and artifacts in a scratch directory removed on exit.
with tempfile.TemporaryDirectory(prefix='tracking-lesson-') as folder:
root = Path(folder)
mlflow.set_tracking_uri('sqlite:///' + str(root / 'tracking.db'))
client = MlflowClient()
experiment = client.create_experiment('two-rates', artifact_location=(root / 'artifacts').as_uri())
for rate in [.02, .15]:
p = jnp.zeros(2)
history = []
with mlflow.start_run(experiment_id=experiment) as run:
mlflow.log_params({'rate': rate, 'updates': 30})
# Check which hardware backend (`cpu`, `gpu`, or `tpu`) JAX selected for ``.
mlflow.set_tags({'data_sha256': data_hash, 'jax': jax.__version__, 'backend': jax.default_backend(), 'metric_boundary': 'after update'})
for step in range(1, 31):
p = update(p, rate)
metric = float(objective(p))
history.append(metric)
mlflow.log_metric('train_mse', metric, step=step)
held = float(jnp.mean((p[0] * vx + p[1] - vy) ** 2))
# Independent host arithmetic checks what the reported validation metric means.
oracle = sum((float(p[0]) * t + float(p[1]) - (2 * t + 1)) ** 2 for t in [-1.5, -.5, .5, 1.5]) / 4
assert abs(held - oracle) < 1e-6
mlflow.log_metric('validation_mse', held, step=30)
model_record = {'kind': 'linear', 'weight': float(p[0]), 'bias': float(p[1]), 'preprocessing': 'one unscaled scalar feature'}
candidate_artifacts.append(model_record)
mlflow.log_dict(model_record, 'model.json')
run_ids.append(run.info.run_id)
curves.append(history)
validation.append(held)
saved = client.get_metric_history(run_ids[-1], 'train_mse')
assert [m.step for m in saved] == list(range(1, 31))
np.testing.assert_allclose([m.value for m in saved], history)
assert client.get_run(run_ids[-1]).data.tags['data_sha256'] == data_hash
selected = client.search_runs([experiment], order_by=['metrics.validation_mse ASC'])[0]
assert selected.info.run_id == run_ids[int(np.argmin(validation))]
artifact = client.download_artifacts(selected.info.run_id, 'model.json')
restored = json.loads(Path(artifact).read_text())
assert abs(restored['weight'] - 2) < .001 and abs(restored['bias'] - 1) < .001Run the example
python3 phases/06-recovery/06-track-experiments-and-lineage-with-mlflow/code/main.pyAbout this command
This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.
Inspect the complete assembled example
# Track experiments and lineage with MLflow
import os
# Set MLFLOW_DISABLE_AGENT_HINT before importing its runtime.
os.environ['MLFLOW_DISABLE_AGENT_HINT'] = '1'
# Set MLFLOW_ENABLE_TELEMETRY before importing its runtime.
os.environ['MLFLOW_ENABLE_TELEMETRY'] = 'false'
import hashlib, json, tempfile
from pathlib import Path
import numpy as np
import jax
import jax.numpy as jnp
import mlflow
from mlflow import MlflowClient
x = jnp.array([-2., -1., 0., 1., 2.])
y = 2 * x + 1
vx = jnp.array([-1.5, -.5, .5, 1.5])
vy = 2 * vx + 1
objective = lambda p: jnp.mean((p[0] * x + p[1] - y) ** 2)
update = jax.jit(lambda p, rate: p - rate * jax.grad(objective)(p))
# Transfer the device result to the host for an independent NumPy comparison.
data_hash = hashlib.sha256(np.asarray(x).tobytes() + np.asarray(y).tobytes()).hexdigest()
curves, validation, run_ids = [], [], []
candidate_artifacts = []
# Keep this run’s database and artifacts in a scratch directory removed on exit.
with tempfile.TemporaryDirectory(prefix='tracking-lesson-') as folder:
root = Path(folder)
mlflow.set_tracking_uri('sqlite:///' + str(root / 'tracking.db'))
client = MlflowClient()
experiment = client.create_experiment('two-rates', artifact_location=(root / 'artifacts').as_uri())
for rate in [.02, .15]:
p = jnp.zeros(2)
history = []
with mlflow.start_run(experiment_id=experiment) as run:
mlflow.log_params({'rate': rate, 'updates': 30})
# Record the selected backend with the experiment metadata.
mlflow.set_tags({'data_sha256': data_hash, 'jax': jax.__version__, 'backend': jax.default_backend(), 'metric_boundary': 'after update'})
for step in range(1, 31):
p = update(p, rate)
metric = float(objective(p))
history.append(metric)
mlflow.log_metric('train_mse', metric, step=step)
held = float(jnp.mean((p[0] * vx + p[1] - vy) ** 2))
# Independent host arithmetic checks what the reported validation metric means.
oracle = sum((float(p[0]) * t + float(p[1]) - (2 * t + 1)) ** 2 for t in [-1.5, -.5, .5, 1.5]) / 4
assert abs(held - oracle) < 1e-6
mlflow.log_metric('validation_mse', held, step=30)
model_record = {'kind': 'linear', 'weight': float(p[0]), 'bias': float(p[1]), 'preprocessing': 'one unscaled scalar feature'}
candidate_artifacts.append(model_record)
mlflow.log_dict(model_record, 'model.json')
run_ids.append(run.info.run_id)
curves.append(history)
validation.append(held)
saved = client.get_metric_history(run_ids[-1], 'train_mse')
assert [m.step for m in saved] == list(range(1, 31))
np.testing.assert_allclose([m.value for m in saved], history)
assert client.get_run(run_ids[-1]).data.tags['data_sha256'] == data_hash
selected = client.search_runs([experiment], order_by=['metrics.validation_mse ASC'])[0]
assert selected.info.run_id == run_ids[int(np.argmin(validation))]
artifact = client.download_artifacts(selected.info.run_id, 'model.json')
restored = json.loads(Path(artifact).read_text())
assert abs(restored['weight'] - 2) < .001 and abs(restored['bias'] - 1) < .001
print('Validation MSE by learning rate:', dict(zip([.02, .15], validation)))
print('Verified 30 logged steps per run; selected and reloaded the better validation candidate.')Expected result: Validation MSE by learning rate: {0.02: 0.1199446..., 0.15: 5.04947...e-10} Verified 30 logged steps per run; selected and reloaded the better validation candidate.
Recorded output and runtime details
Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.
Validation MSE by learning rate: {0.02: 0.11994461715221405, 0.15: 5.049471951679152e-10}
Verified 30 logged steps per run; selected and reloaded the better validation candidate.
Validation difference: 0.11994461664726686
Actual training MSE: {'linear-rate-0.02': 0.1401000006160622, 'linear-rate-0.15': 5.076259412817308e-10, 'training-lookup': 0.0}
Actual held-out MSE: {'linear-rate-0.02': 0.11994461629745246, 'linear-rate-0.15': 5.076259412817308e-10, 'training-lookup': 6.0}
Training-only selects the memorizer; held-out selection rejects it.
Changed target changes dataset identity.
PASS: recovery-06
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Check the stored comparison
# Experiment — Check the stored comparison: Both runs share initialization, data and update count.
assert validation[1] < validation[0]
print('Validation difference:',validation[0]-validation[1])Expected: The rate 0.15 run has smaller validation MSE than the rate 0.02 run.
Both runs share initialization, data and update count. This isolates a configuration comparison; it does not compare equal wall-clock budgets or establish an optimal rate.
Make it yours
Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.
Replay the two saved linear candidates in a fresh local MLflow experiment and add a third training-lookup model. The lookup stores each training x/y pair and predicts zero for an unseen x. Compute and log actual training and validation MSE for all three, save and reload every artifact, then show which model a training-only rule selects and which one the held-out rule selects.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- The two fitted linear artifact dictionaries from the example, training and untouched validation arrays.
- A third training-lookup model with zero as its unseen-input default.
Outputs
- Three local MLflow runs, each with actual training and held-out MSE and a model.json artifact.
- Reloaded-prediction checks and distinct training-only versus validation-based selections.
Invariants to check
- The third candidate has zero actual training MSE and validation MSE 6.
- All comparisons use the same split and data identity; validation is not used to fit any candidate.
- The selection uses retrieved run records and every artifact is reloaded.
Hints
- Represent lookup inference explicitly and calculate both metrics from predictions.
- Keep the exercise experiment in its own TemporaryDirectory and log all three model artifacts.
import numpy as np
def compare_three_saved_candidates(candidates, train_x, train_y, validation_x, validation_y):
# TODO: log, reload and evaluate three candidates; compare selection rules.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: a memorizer can win training loss and fail held-out selection.
def predict_artifact(record, values):
values = np.asarray(values, dtype=np.float64)
if record['kind'] == 'linear':
return record['weight'] * values + record['bias']
if record['kind'] == 'training-lookup':
mapping = dict(zip(record['training_x'], record['training_y']))
return np.array([mapping.get(float(value), record['unseen_default']) for value in values])
raise ValueError('Unknown model artifact kind')
lookup = {'kind': 'training-lookup', 'training_x': np.asarray(x).tolist(),
'training_y': np.asarray(y).tolist(), 'unseen_default': 0.0}
models = candidate_artifacts + [lookup]
names = ['linear-rate-0.02', 'linear-rate-0.15', 'training-lookup']
assert len(models) == 3
train_errors, held_errors, replay_ids = [], [], []
with tempfile.TemporaryDirectory(prefix='selection-exercise-') as folder:
selection_root = Path(folder)
mlflow.set_tracking_uri('sqlite:///' + str(selection_root / 'tracking.db'))
selection_client = MlflowClient()
selection_experiment = selection_client.create_experiment(
'three-candidate-selection', artifact_location=(selection_root / 'artifacts').as_uri())
for name, record in zip(names, models):
train_error = float(np.mean((predict_artifact(record, x) - np.asarray(y)) ** 2))
held_error = float(np.mean((predict_artifact(record, vx) - np.asarray(vy)) ** 2))
with mlflow.start_run(experiment_id=selection_experiment) as run:
mlflow.log_params({'candidate': name, 'model_kind': record['kind']})
mlflow.set_tags({'data_sha256': data_hash,
'scope': 'same synthetic data; validation never used to fit lookup or linear candidates'})
mlflow.log_metric('train_mse', train_error)
mlflow.log_metric('validation_mse', held_error)
mlflow.log_dict(record, 'model.json')
replay_ids.append(run.info.run_id)
loaded_path = selection_client.download_artifacts(replay_ids[-1], 'model.json')
loaded_record = json.loads(Path(loaded_path).read_text())
np.testing.assert_array_equal(predict_artifact(loaded_record, vx), predict_artifact(record, vx))
train_errors.append(train_error)
held_errors.append(held_error)
assert len(selection_client.search_runs([selection_experiment])) == 3
training_pick = selection_client.search_runs([selection_experiment], order_by=['metrics.train_mse ASC'])[0]
validation_pick = selection_client.search_runs([selection_experiment], order_by=['metrics.validation_mse ASC'])[0]
assert training_pick.info.run_id == replay_ids[2]
assert validation_pick.info.run_id == replay_ids[int(np.argmin(held_errors))]
assert validation_pick.info.run_id != training_pick.info.run_id
assert train_errors[2] == 0.0
np.testing.assert_allclose(held_errors[2], 6.0)
assert held_errors[2] > min(held_errors)
print('Actual training MSE:', dict(zip(names, train_errors)))
print('Actual held-out MSE:', dict(zip(names, held_errors)))
print('Training-only selects the memorizer; held-out selection rejects it.')
Change a data value
transfer
Change one training target and compute the data fingerprint again without overwriting the original record.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Change one training target and compute the data fingerprint again without overwriting the original record.
Outputs
- Original and changed fingerprints with the source record preserved.
Invariants to check
- The only dataset change is one target value, and its fingerprint is distinct.
Hints
- Hash the same input bytes plus changed target bytes.
import hashlib
import json
from pathlib import Path
import numpy as np
import mlflow
from mlflow import MlflowClient
def practice_change_a_data_value(features, labels):
"""Implement the change a data value check."""
# TODO: Copy the training targets, change one value, and recompute the content fingerprint without overwriting the original.
raise NotImplementedErrorShow a hint
Hash the same input bytes plus changed target bytes.
Reveal reference solution and reasoning
# Change a data value (transfer): Identical filenames or shapes do not imply identical data.
changed_y=np.asarray(y).copy()
changed_y[0]+=.1
# Transfer the device result to the host for an independent NumPy comparison.
changed_hash=hashlib.sha256(np.asarray(x).tobytes()+changed_y.tobytes()).hexdigest()
assert changed_hash != data_hash
print('Changed target changes dataset identity.')Identical filenames or shapes do not imply identical data. A changed target creates a different experiment contract.
Diagnose the result
If a run is missing, inspect the tracking URI and experiment ID before repeating training. If metrics disagree, compare step and reduction conventions. If recovery changes the next batch, fix checkpoint state; MLflow logging does not restore it.
Carry forward
- Decide what makes runs comparable
- Log at a useful boundary
- Continue into a real registry
Keep your evidence
Keep retrieved metric histories and data tags, all three model artifacts, actual train/validation predictions after reload, and the different training-only versus held-out selections. Explain the memorizer's zero training MSE and validation MSE of 6.
Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.
Saved in this browser. Export or back up your portfolio anytime in My learning.
Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.
Primary references
Phase 06 Integration Project
Bring this phase together: Resume optimizer and PRNG state across an interrupted training update
Checkpoint to prove: Compare resumed and uninterrupted runs under a stated determinism tolerance.
Work in projects/recovery-audit/starter/model.py. Complete stages 1 and 2 for independent calculations and changed-condition diagnosis, then retain the stage 3 evidence with --evidence-dir runs/recovery-audit. Stage 4 integrates the checks. Learner commands explicitly select the starter; --implementation solution is instructor reference execution. This bounded practice does not certify the entire phase or target hardware.