mirror of
https://github.com/Stone-Red-Code/dvc.git
synced 2026-11-26 23:09:35 +01:00
experiments: support branching w/modified params from intermediate checkpoint (#4898)
* experiments: Allow branching from checkpoints with modified hyper params * experiments: initial checkpoints tree functionality for `exp show` * go back to flat/sortable view * add test for resume w/modified params * tests: move experiments fixtures into conftest * add show checkpoints test * test checkpoint table rendering * remove dead code * test show for checkpoint branches
This commit is contained in:
+32
-20
@@ -15,6 +15,7 @@ from dvc.command.repro import CmdRepro
|
||||
from dvc.command.repro import add_arguments as add_repro_arguments
|
||||
from dvc.exceptions import DvcException, InvalidArgumentError
|
||||
from dvc.repo.experiments import Experiments
|
||||
from dvc.scm.git import Git
|
||||
from dvc.utils.flatten import flatten
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -115,30 +116,47 @@ def _collect_rows(
|
||||
reverse = sort_order == "desc"
|
||||
experiments = _sort_exp(experiments, sort_by, sort_type, reverse)
|
||||
|
||||
last_tip = None
|
||||
new_checkpoint = True
|
||||
for i, (rev, exp) in enumerate(experiments.items()):
|
||||
row = []
|
||||
style = None
|
||||
queued = "*" if exp.get("queued", False) else ""
|
||||
|
||||
tip = exp.get("checkpoint_tip")
|
||||
parent = ""
|
||||
if rev == "baseline":
|
||||
name = exp.get("name", base_rev)
|
||||
if Git.is_sha(base_rev):
|
||||
name_rev = base_rev[:7]
|
||||
else:
|
||||
name_rev = base_rev
|
||||
name = exp.get("name", name_rev)
|
||||
row.append(f"{name}")
|
||||
style = "bold"
|
||||
else:
|
||||
if tip and tip == last_tip:
|
||||
tree = "│ ╟"
|
||||
if tip:
|
||||
parent_rev = exp.get("checkpoint_parent", "")
|
||||
parent_exp = experiments.get(parent_rev, {})
|
||||
parent_tip = parent_exp.get("checkpoint_tip")
|
||||
if tip == parent_tip:
|
||||
if new_checkpoint:
|
||||
tree = "│ ╓"
|
||||
else:
|
||||
tree = "│ ╟"
|
||||
new_checkpoint = False
|
||||
else:
|
||||
if parent_rev == base_rev:
|
||||
tree = "├─╨"
|
||||
else:
|
||||
tree = "│ ╟"
|
||||
parent = f" ({parent_rev[:7]})"
|
||||
new_checkpoint = True
|
||||
else:
|
||||
if i < len(experiments) - 1:
|
||||
if tip:
|
||||
tree = "├─╥"
|
||||
else:
|
||||
tree = "├──"
|
||||
tree = "├──"
|
||||
else:
|
||||
tree = "└──"
|
||||
row.append(f"{tree} {queued}{rev[:7]}")
|
||||
last_tip = tip
|
||||
new_checkpoint = True
|
||||
row.append(f"{tree} {queued}{rev[:7]}{parent}")
|
||||
|
||||
if not no_timestamp:
|
||||
row.append(_format_time(exp.get("timestamp")))
|
||||
@@ -152,11 +170,6 @@ def _collect_rows(
|
||||
|
||||
|
||||
def _sort_exp(experiments, sort_by, typ, reverse):
|
||||
if "baseline" in experiments:
|
||||
ret = OrderedDict({"baseline": experiments.pop("baseline")})
|
||||
else:
|
||||
ret = OrderedDict()
|
||||
|
||||
def _sort(item):
|
||||
rev, exp = item
|
||||
tip = exp.get("checkpoint_tip")
|
||||
@@ -173,6 +186,10 @@ def _sort_exp(experiments, sort_by, typ, reverse):
|
||||
return (val is None, val)
|
||||
return (True, None)
|
||||
|
||||
ret = OrderedDict()
|
||||
if "baseline" in experiments:
|
||||
ret["baseline"] = experiments.pop("baseline")
|
||||
|
||||
ret.update(sorted(experiments.items(), key=_sort, reverse=reverse))
|
||||
return ret
|
||||
|
||||
@@ -239,8 +256,6 @@ def _parse_list(param_list):
|
||||
def _show_experiments(all_experiments, console, **kwargs):
|
||||
from rich.table import Table
|
||||
|
||||
from dvc.scm.git import Git
|
||||
|
||||
include_metrics = _parse_list(kwargs.pop("include_metrics", []))
|
||||
exclude_metrics = _parse_list(kwargs.pop("exclude_metrics", []))
|
||||
include_params = _parse_list(kwargs.pop("include_params", []))
|
||||
@@ -264,9 +279,6 @@ def _show_experiments(all_experiments, console, **kwargs):
|
||||
table.add_column(name, justify="left")
|
||||
|
||||
for base_rev, experiments in all_experiments.items():
|
||||
if Git.is_sha(base_rev):
|
||||
base_rev = base_rev[:7]
|
||||
|
||||
for row, _, in _collect_rows(
|
||||
base_rev, experiments, metric_names, param_names, **kwargs,
|
||||
):
|
||||
|
||||
@@ -96,10 +96,11 @@ class Experiments:
|
||||
|
||||
EXPERIMENTS_DIR = "experiments"
|
||||
PACKED_ARGS_FILE = "repro.dat"
|
||||
STASH_MSG_PREFIX = "dvc-exp:"
|
||||
STASH_EXPERIMENT_FORMAT = "dvc-exp:{rev}:{baseline_rev}"
|
||||
STASH_EXPERIMENT_RE = re.compile(
|
||||
r"(?:On \(.*\): )"
|
||||
r"dvc-exp:(?P<baseline_rev>[0-9a-f]+)(:(?P<branch>.+))?$"
|
||||
r"dvc-exp:(?P<rev>[0-9a-f]+):(?P<baseline_rev>[0-9a-f]+)"
|
||||
r"(:(?P<branch>.+))?$"
|
||||
)
|
||||
BRANCH_RE = re.compile(
|
||||
r"^(?P<baseline_rev>[a-f0-9]{7})-(?P<exp_sha>[a-f0-9]+)"
|
||||
@@ -107,7 +108,9 @@ class Experiments:
|
||||
)
|
||||
LAST_CHECKPOINT = ":last"
|
||||
|
||||
StashEntry = namedtuple("StashEntry", ["index", "baseline_rev", "branch"])
|
||||
StashEntry = namedtuple(
|
||||
"StashEntry", ["index", "rev", "baseline_rev", "branch"]
|
||||
)
|
||||
|
||||
def __init__(self, repo):
|
||||
from dvc.lock import make_lock
|
||||
@@ -176,7 +179,10 @@ class Experiments:
|
||||
m = self.STASH_EXPERIMENT_RE.match(entry.message)
|
||||
if m:
|
||||
revs[entry.newhexsha] = self.StashEntry(
|
||||
i, m.group("baseline_rev"), m.group("branch")
|
||||
i,
|
||||
m.group("rev"),
|
||||
m.group("baseline_rev"),
|
||||
m.group("branch"),
|
||||
)
|
||||
return revs
|
||||
|
||||
@@ -239,6 +245,7 @@ class Experiments:
|
||||
self,
|
||||
*args,
|
||||
params: Optional[dict] = None,
|
||||
baseline_rev: Optional[str] = None,
|
||||
branch: Optional[str] = None,
|
||||
allow_unchanged: Optional[bool] = True,
|
||||
apply_workspace: Optional[bool] = True,
|
||||
@@ -250,6 +257,8 @@ class Experiments:
|
||||
params: Optional dictionary of parameter values to be used.
|
||||
Values take priority over any parameters specified in the
|
||||
user's workspace.
|
||||
baseline_rev: Optional baseline rev for this experiment, defaults
|
||||
to the current SCM rev.
|
||||
branch: Optional experiment branch name. If specified, the
|
||||
experiment will be added to `branch` instead of creating
|
||||
a new branch.
|
||||
@@ -264,12 +273,12 @@ class Experiments:
|
||||
rev = self.scm.get_rev()
|
||||
|
||||
if apply_workspace:
|
||||
if branch:
|
||||
raise DvcException(
|
||||
"Cannot apply workspace changes into existing experiment"
|
||||
"branch."
|
||||
)
|
||||
# patch user's workspace into experiments clone
|
||||
#
|
||||
# TODO: patching changes into an extended branch will require
|
||||
# propagating changes down the full branch, since the workspace
|
||||
# patch will be based on the original branch point, not the tip
|
||||
# of the experiment branch
|
||||
tmp = tempfile.NamedTemporaryFile(delete=False).name
|
||||
try:
|
||||
self.repo.scm.repo.git.diff(
|
||||
@@ -295,7 +304,7 @@ class Experiments:
|
||||
# save experiment as a stash commit w/message containing baseline rev
|
||||
# (stash commits are merge commits and do not contain a parent commit
|
||||
# SHA)
|
||||
msg = self._stash_msg(rev, branch)
|
||||
msg = self._stash_msg(rev, baseline_rev=baseline_rev, branch=branch)
|
||||
self.scm.repo.git.stash("push", "-m", msg)
|
||||
return self.scm.resolve_rev("stash@{0}")
|
||||
|
||||
@@ -314,10 +323,15 @@ class Experiments:
|
||||
len(dirty) - len(to_checkout) + len(untracked) - len(to_remove)
|
||||
) != 0
|
||||
|
||||
def _stash_msg(self, rev, branch=None):
|
||||
def _stash_msg(self, rev, baseline_rev=None, branch=None):
|
||||
if not baseline_rev:
|
||||
baseline_rev = rev
|
||||
msg = self.STASH_EXPERIMENT_FORMAT.format(
|
||||
rev=rev, baseline_rev=baseline_rev
|
||||
)
|
||||
if branch:
|
||||
return f"{self.STASH_MSG_PREFIX}{rev}:{branch}"
|
||||
return f"{self.STASH_MSG_PREFIX}{rev}"
|
||||
return f"{msg}:{branch}"
|
||||
return msg
|
||||
|
||||
def _pack_args(self, *args, **kwargs):
|
||||
ExperimentExecutor.pack_repro_args(self.args_file, *args, **kwargs)
|
||||
@@ -349,19 +363,22 @@ class Experiments:
|
||||
|
||||
def _commit(
|
||||
self,
|
||||
exp_hash,
|
||||
check_exists=True,
|
||||
create_branch=True,
|
||||
checkpoint=False,
|
||||
checkpoint_reset=False,
|
||||
exp_hash: str,
|
||||
baseline_rev: Optional[str] = None,
|
||||
check_exists: Optional[bool] = True,
|
||||
create_branch: Optional[bool] = True,
|
||||
checkpoint: Optional[bool] = False,
|
||||
checkpoint_reset: Optional[bool] = False,
|
||||
):
|
||||
"""Commit stages as an experiment and return the commit SHA."""
|
||||
if not self.scm.is_dirty(untracked_files=True):
|
||||
raise UnchangedExperimentError(self.scm.get_rev())
|
||||
|
||||
rev = self.scm.get_rev()
|
||||
if not baseline_rev:
|
||||
baseline_rev = rev
|
||||
checkpoint = "-checkpoint" if checkpoint else ""
|
||||
exp_name = f"{rev[:7]}-{exp_hash}{checkpoint}"
|
||||
exp_name = f"{baseline_rev[:7]}-{exp_hash}{checkpoint}"
|
||||
if create_branch:
|
||||
if (
|
||||
check_exists or checkpoint
|
||||
@@ -464,45 +481,57 @@ class Experiments:
|
||||
branch = None
|
||||
if checkpoint_resume == self.LAST_CHECKPOINT:
|
||||
# Continue from most recently committed checkpoint
|
||||
for head in sorted(
|
||||
self.scm.repo.heads,
|
||||
key=lambda h: h.commit.committed_date,
|
||||
reverse=True,
|
||||
):
|
||||
exp_branch = head.name
|
||||
m = self.BRANCH_RE.match(exp_branch)
|
||||
if m and m.group("checkpoint"):
|
||||
branch = exp_branch
|
||||
break
|
||||
if not branch:
|
||||
raise DvcException(
|
||||
"No existing checkpoint experiment to continue"
|
||||
)
|
||||
branch = self._get_last_checkpoint()
|
||||
resume_rev = self.scm.resolve_rev(branch)
|
||||
else:
|
||||
rev = self.scm.resolve_rev(checkpoint_resume)
|
||||
resume_rev = rev
|
||||
branch = self._get_branch_containing(rev)
|
||||
if not branch:
|
||||
raise DvcException(
|
||||
"Could not find checkpoint experiment "
|
||||
f"'{checkpoint_resume}'"
|
||||
)
|
||||
logger.debug(
|
||||
"Continuing checkpoint experiment '%s'", checkpoint_resume
|
||||
)
|
||||
kwargs["apply_workspace"] = False
|
||||
|
||||
rev = self.scm.resolve_rev(branch)
|
||||
logger.debug(
|
||||
"Using '%s' (tip of branch '%s') as baseline", rev, branch
|
||||
)
|
||||
baseline_rev = self._get_baseline(branch)
|
||||
if kwargs.get("params", None):
|
||||
logger.debug(
|
||||
"Branching from checkpoint '%s' with modified params",
|
||||
checkpoint_resume,
|
||||
)
|
||||
rev = resume_rev
|
||||
branch = None
|
||||
else:
|
||||
logger.debug(
|
||||
"Continuing checkpoint experiment '%s'", checkpoint_resume
|
||||
)
|
||||
rev = self.scm.resolve_rev(branch)
|
||||
logger.debug(
|
||||
"Using '%s' (tip of branch '%s') as baseline", rev, branch
|
||||
)
|
||||
self._scm_checkout(rev)
|
||||
|
||||
stash_rev = self._stash_exp(*args, branch=branch, **kwargs)
|
||||
kwargs["apply_workspace"] = False
|
||||
stash_rev = self._stash_exp(
|
||||
*args, baseline_rev=baseline_rev, branch=branch, **kwargs
|
||||
)
|
||||
logger.debug(
|
||||
"Stashed experiment '%s' for future execution.", stash_rev[:7]
|
||||
)
|
||||
return stash_rev
|
||||
|
||||
def _get_last_checkpoint(self):
|
||||
for head in sorted(
|
||||
self.scm.repo.heads,
|
||||
key=lambda h: h.commit.committed_date,
|
||||
reverse=True,
|
||||
):
|
||||
exp_branch = head.name
|
||||
m = self.BRANCH_RE.match(exp_branch)
|
||||
if m and m.group("checkpoint"):
|
||||
return exp_branch
|
||||
raise DvcException("No existing checkpoint experiment to continue")
|
||||
|
||||
@scm_locked
|
||||
def reproduce(
|
||||
self,
|
||||
@@ -521,17 +550,17 @@ class Experiments:
|
||||
stash_revs = self.stash_revs
|
||||
|
||||
# to_run contains mapping of:
|
||||
# input_rev: (stash_index, baseline_rev)
|
||||
# input_rev: (stash_index, rev, baseline_rev)
|
||||
# where input_rev contains the changes to execute (usually a stash
|
||||
# commit) and baseline_rev is the baseline to compare output against.
|
||||
# The final experiment commit will be branched from baseline_rev.
|
||||
# commit), rev is the original SCM commit to be checked out, and
|
||||
# baseline_rev is the experiment baseline.
|
||||
if revs is None:
|
||||
to_run = dict(stash_revs)
|
||||
else:
|
||||
to_run = {
|
||||
rev: stash_revs[rev]
|
||||
if rev in stash_revs
|
||||
else self.StashEntry(None, rev, None)
|
||||
else self.StashEntry(None, rev, rev, None)
|
||||
for rev in revs
|
||||
}
|
||||
|
||||
@@ -544,12 +573,13 @@ class Experiments:
|
||||
# contents of (unstashed) exp workspace to the executor tree
|
||||
executors = {}
|
||||
for rev, item in to_run.items():
|
||||
self._scm_checkout(item.baseline_rev)
|
||||
self._scm_checkout(item.rev)
|
||||
self.scm.repo.git.stash("apply", rev)
|
||||
packed_args, packed_kwargs = self._unpack_args()
|
||||
checkpoint_reset = packed_kwargs.pop("checkpoint_reset", False)
|
||||
executor = LocalExecutor(
|
||||
item.baseline_rev,
|
||||
rev=item.rev,
|
||||
baseline_rev=item.baseline_rev,
|
||||
branch=item.branch,
|
||||
repro_args=packed_args,
|
||||
repro_kwargs=packed_kwargs,
|
||||
@@ -654,7 +684,7 @@ class Experiments:
|
||||
if executor.branch:
|
||||
self._scm_checkout(executor.branch)
|
||||
else:
|
||||
self._scm_checkout(executor.baseline_rev)
|
||||
self._scm_checkout(executor.rev)
|
||||
exp_rev = self._collect_and_commit(
|
||||
rev, executor, exp_hash, checkpoint=checkpoint
|
||||
)
|
||||
@@ -678,7 +708,7 @@ class Experiments:
|
||||
if executor.branch:
|
||||
self._scm_checkout(executor.branch)
|
||||
else:
|
||||
self._scm_checkout(executor.baseline_rev)
|
||||
self._scm_checkout(executor.rev)
|
||||
|
||||
exp_hash = hash_exp(stages + unchanged)
|
||||
exp_rev = self._collect_and_commit(
|
||||
@@ -711,6 +741,7 @@ class Experiments:
|
||||
create_branch = not executor.branch
|
||||
exp_rev = self._commit(
|
||||
exp_hash,
|
||||
baseline_rev=executor.baseline_rev,
|
||||
create_branch=create_branch,
|
||||
checkpoint_reset=executor.checkpoint_reset,
|
||||
**kwargs,
|
||||
|
||||
@@ -19,18 +19,25 @@ class ExperimentExecutor:
|
||||
"""Base class for executing experiments in parallel.
|
||||
|
||||
Args:
|
||||
baseline_rev: baseline revision that this experiment is derived from.
|
||||
baseline_rev: Baseline revision that this experiment is derived from.
|
||||
|
||||
Optional keyword args:
|
||||
branch: Existing git branch for this experiment.
|
||||
rev: Git revision to be checked out for this experiment, defaults to
|
||||
branch, baseline_rev in that order.
|
||||
repro_args: Args to be passed into reproduce.
|
||||
repro_kwargs: Keyword args to be passed into reproduce.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, baseline_rev: str, branch: Optional[str] = None, **kwargs,
|
||||
self,
|
||||
baseline_rev: str,
|
||||
branch: Optional[str] = None,
|
||||
rev: Optional[str] = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.baseline_rev = baseline_rev
|
||||
self._rev = rev
|
||||
self.branch = branch
|
||||
self.repro_args = kwargs.pop("repro_args", [])
|
||||
self.repro_kwargs = kwargs.pop("repro_kwargs", {})
|
||||
@@ -84,16 +91,13 @@ class LocalExecutor(ExperimentExecutor):
|
||||
"""Local machine experiment executor."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
baseline_rev: str,
|
||||
checkpoint_reset: Optional[bool] = False,
|
||||
**kwargs,
|
||||
self, checkpoint_reset: Optional[bool] = False, **kwargs,
|
||||
):
|
||||
from dvc.repo import Repo
|
||||
|
||||
dvc_dir = kwargs.pop("dvc_dir")
|
||||
cache_dir = kwargs.pop("cache_dir")
|
||||
super().__init__(baseline_rev, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
self.tmp_dir = TemporaryDirectory()
|
||||
|
||||
# init empty DVC repo (will be overwritten when input is uploaded)
|
||||
@@ -101,7 +105,7 @@ class LocalExecutor(ExperimentExecutor):
|
||||
logger.debug(
|
||||
"Init local executor in dir '%s' with baseline '%s'.",
|
||||
self.tmp_dir,
|
||||
baseline_rev[:7],
|
||||
self.baseline_rev[:7],
|
||||
)
|
||||
self.dvc_dir = os.path.join(self.tmp_dir.name, dvc_dir)
|
||||
self._config(cache_dir)
|
||||
@@ -133,6 +137,10 @@ class LocalExecutor(ExperimentExecutor):
|
||||
def tree(self):
|
||||
return self._tree
|
||||
|
||||
@property
|
||||
def rev(self):
|
||||
return self._rev if self._rev else self.baseline_rev
|
||||
|
||||
@staticmethod
|
||||
def reproduce(dvc_dir, cwd=None, **kwargs):
|
||||
"""Run dvc repro and return the result."""
|
||||
|
||||
@@ -44,12 +44,21 @@ def _collect_experiment(repo, rev, stash=False, sha_only=True):
|
||||
return res
|
||||
|
||||
|
||||
def _collect_checkpoint_experiment(repo, branch, baseline, **kwargs):
|
||||
res = OrderedDict()
|
||||
def _collect_checkpoint_experiment(res, repo, branch, baseline, **kwargs):
|
||||
exp_rev = repo.scm.resolve_rev(branch)
|
||||
prev = None
|
||||
for rev in repo.scm.branch_revs(exp_rev, baseline):
|
||||
res[rev] = _collect_experiment(repo, rev, **kwargs)
|
||||
res[rev]["checkpoint_tip"] = exp_rev
|
||||
exp = {"checkpoint_tip": exp_rev}
|
||||
if prev:
|
||||
res[prev]["checkpoint_parent"] = rev
|
||||
if rev in res:
|
||||
res[rev].update(exp)
|
||||
res.move_to_end(rev)
|
||||
else:
|
||||
exp.update(_collect_experiment(repo, rev, **kwargs))
|
||||
res[rev] = exp
|
||||
prev = rev
|
||||
res[prev]["checkpoint_parent"] = baseline
|
||||
return res
|
||||
|
||||
|
||||
@@ -96,10 +105,9 @@ def show(
|
||||
if rev in revs:
|
||||
with repo.experiments.chdir():
|
||||
if m.group("checkpoint"):
|
||||
checkpoint_exps = _collect_checkpoint_experiment(
|
||||
repo.experiments.exp_dvc, exp_branch, rev
|
||||
_collect_checkpoint_experiment(
|
||||
res[rev], repo.experiments.exp_dvc, exp_branch, rev
|
||||
)
|
||||
res[rev].update(checkpoint_exps)
|
||||
else:
|
||||
exp_rev = repo.experiments.scm.resolve_rev(exp_branch)
|
||||
experiment = _collect_experiment(
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
from textwrap import dedent
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.func.test_repro_multistage import COPY_SCRIPT
|
||||
|
||||
CHECKPOINT_SCRIPT_FORMAT = dedent(
|
||||
"""\
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
from time import sleep
|
||||
|
||||
from dvc.api import make_checkpoint
|
||||
|
||||
checkpoint_file = {}
|
||||
checkpoint_iterations = int({})
|
||||
if os.path.exists(checkpoint_file):
|
||||
with open(checkpoint_file) as fobj:
|
||||
try:
|
||||
value = int(fobj.read())
|
||||
except ValueError:
|
||||
value = 0
|
||||
else:
|
||||
with open(checkpoint_file, "w"):
|
||||
pass
|
||||
value = 0
|
||||
|
||||
shutil.copyfile({}, {})
|
||||
|
||||
if os.getenv("DVC_CHECKPOINT"):
|
||||
for _ in range(checkpoint_iterations):
|
||||
value += 1
|
||||
with open(checkpoint_file, "w") as fobj:
|
||||
fobj.write(str(value))
|
||||
make_checkpoint()
|
||||
"""
|
||||
)
|
||||
CHECKPOINT_SCRIPT = CHECKPOINT_SCRIPT_FORMAT.format(
|
||||
"sys.argv[1]", "sys.argv[2]", "sys.argv[3]", "sys.argv[4]"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def exp_stage(tmp_dir, scm, dvc):
|
||||
tmp_dir.gen("copy.py", COPY_SCRIPT)
|
||||
tmp_dir.gen("params.yaml", "foo: 1")
|
||||
stage = dvc.run(
|
||||
cmd="python copy.py params.yaml metrics.yaml",
|
||||
metrics_no_cache=["metrics.yaml"],
|
||||
params=["foo"],
|
||||
name="copy-file",
|
||||
)
|
||||
scm.add(["dvc.yaml", "dvc.lock", "copy.py", "params.yaml", "metrics.yaml"])
|
||||
scm.commit("init")
|
||||
return stage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def checkpoint_stage(tmp_dir, scm, dvc):
|
||||
tmp_dir.gen("checkpoint.py", CHECKPOINT_SCRIPT)
|
||||
tmp_dir.gen("params.yaml", "foo: 1")
|
||||
stage = dvc.run(
|
||||
cmd="python checkpoint.py foo 5 params.yaml metrics.yaml",
|
||||
metrics_no_cache=["metrics.yaml"],
|
||||
params=["foo"],
|
||||
checkpoints=["foo"],
|
||||
no_exec=True,
|
||||
name="checkpoint-file",
|
||||
)
|
||||
scm.add(["dvc.yaml", "checkpoint.py", "params.yaml"])
|
||||
scm.commit("init")
|
||||
return stage
|
||||
@@ -1,65 +1,11 @@
|
||||
import logging
|
||||
from textwrap import dedent
|
||||
|
||||
import pytest
|
||||
from funcy import first
|
||||
|
||||
import dvc as dvc_module
|
||||
from dvc.exceptions import DvcException
|
||||
from dvc.repo.experiments import Experiments
|
||||
|
||||
CHECKPOINT_SCRIPT_FORMAT = dedent(
|
||||
"""\
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
from time import sleep
|
||||
|
||||
from dvc.api import make_checkpoint
|
||||
|
||||
checkpoint_file = {}
|
||||
checkpoint_iterations = int({})
|
||||
if os.path.exists(checkpoint_file):
|
||||
with open(checkpoint_file) as fobj:
|
||||
try:
|
||||
value = int(fobj.read())
|
||||
except ValueError:
|
||||
value = 0
|
||||
else:
|
||||
with open(checkpoint_file, "w"):
|
||||
pass
|
||||
value = 0
|
||||
|
||||
shutil.copyfile({}, {})
|
||||
|
||||
if os.getenv("DVC_CHECKPOINT"):
|
||||
for _ in range(checkpoint_iterations):
|
||||
value += 1
|
||||
with open(checkpoint_file, "w") as fobj:
|
||||
fobj.write(str(value))
|
||||
make_checkpoint()
|
||||
"""
|
||||
)
|
||||
CHECKPOINT_SCRIPT = CHECKPOINT_SCRIPT_FORMAT.format(
|
||||
"sys.argv[1]", "sys.argv[2]", "sys.argv[3]", "sys.argv[4]"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def checkpoint_stage(tmp_dir, scm, dvc):
|
||||
tmp_dir.gen("checkpoint.py", CHECKPOINT_SCRIPT)
|
||||
tmp_dir.gen("params.yaml", "foo: 1")
|
||||
stage = dvc.run(
|
||||
cmd="python checkpoint.py foo 5 params.yaml metrics.yaml",
|
||||
metrics_no_cache=["metrics.yaml"],
|
||||
params=["foo"],
|
||||
checkpoints=["foo"],
|
||||
no_exec=True,
|
||||
name="checkpoint-file",
|
||||
)
|
||||
scm.add(["dvc.yaml", "checkpoint.py", "params.yaml"])
|
||||
scm.commit("init")
|
||||
return stage
|
||||
from dvc.repo.experiments import Experiments, MultipleBranchError
|
||||
|
||||
|
||||
def test_new_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, mocker):
|
||||
@@ -79,7 +25,7 @@ def test_new_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, mocker):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("last", [True, False])
|
||||
def test_resume_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, mocker, last):
|
||||
def test_resume_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, last):
|
||||
with pytest.raises(DvcException):
|
||||
if last:
|
||||
dvc.experiments.run(
|
||||
@@ -94,6 +40,12 @@ def test_resume_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, mocker, last):
|
||||
results = dvc.experiments.run(
|
||||
checkpoint_stage.addressing, params=["foo=2"]
|
||||
)
|
||||
|
||||
with pytest.raises(DvcException):
|
||||
dvc.experiments.run(
|
||||
checkpoint_stage.addressing, checkpoint_resume="abc1234",
|
||||
)
|
||||
|
||||
if last:
|
||||
exp_rev = Experiments.LAST_CHECKPOINT
|
||||
else:
|
||||
@@ -107,7 +59,7 @@ def test_resume_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, mocker, last):
|
||||
).read_text().strip() == "foo: 2"
|
||||
|
||||
|
||||
def test_reset_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, mocker, caplog):
|
||||
def test_reset_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, caplog):
|
||||
dvc.experiments.run(checkpoint_stage.addressing)
|
||||
scm.repo.git.reset(hard=True)
|
||||
scm.repo.git.clean(force=True)
|
||||
@@ -123,3 +75,43 @@ def test_reset_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, mocker, caplog):
|
||||
assert (
|
||||
tmp_dir / ".dvc" / "experiments" / "metrics.yaml"
|
||||
).read_text().strip() == "foo: 1"
|
||||
|
||||
|
||||
def test_resume_branch(tmp_dir, scm, dvc, checkpoint_stage):
|
||||
results = dvc.experiments.run(
|
||||
checkpoint_stage.addressing, params=["foo=2"]
|
||||
)
|
||||
branch_rev = first(results)
|
||||
|
||||
results = dvc.experiments.run(
|
||||
checkpoint_stage.addressing, checkpoint_resume=branch_rev
|
||||
)
|
||||
checkpoint_a = first(results)
|
||||
|
||||
results = dvc.experiments.run(
|
||||
checkpoint_stage.addressing,
|
||||
checkpoint_resume=branch_rev,
|
||||
params=["foo=100"],
|
||||
)
|
||||
checkpoint_b = first(results)
|
||||
|
||||
dvc.experiments.checkout(checkpoint_a)
|
||||
assert (tmp_dir / "foo").read_text() == "10"
|
||||
assert (
|
||||
tmp_dir / ".dvc" / "experiments" / "metrics.yaml"
|
||||
).read_text().strip() == "foo: 2"
|
||||
|
||||
dvc.experiments.checkout(checkpoint_b)
|
||||
assert (tmp_dir / "foo").read_text() == "10"
|
||||
assert (
|
||||
tmp_dir / ".dvc" / "experiments" / "metrics.yaml"
|
||||
).read_text().strip() == "foo: 100"
|
||||
|
||||
with pytest.raises(MultipleBranchError):
|
||||
dvc.experiments._get_branch_containing(branch_rev)
|
||||
|
||||
branch_a = dvc.experiments._get_branch_containing(checkpoint_a)
|
||||
branch_b = dvc.experiments._get_branch_containing(checkpoint_b)
|
||||
assert branch_rev == dvc.experiments.scm.repo.git.merge_base(
|
||||
branch_a, branch_b, fork_point=True
|
||||
)
|
||||
|
||||
@@ -7,21 +7,6 @@ from dvc.utils.serialize import PythonFileCorruptedError
|
||||
from tests.func.test_repro_multistage import COPY_SCRIPT
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def exp_stage(tmp_dir, scm, dvc):
|
||||
tmp_dir.gen("copy.py", COPY_SCRIPT)
|
||||
tmp_dir.gen("params.yaml", "foo: 1")
|
||||
stage = dvc.run(
|
||||
cmd="python copy.py params.yaml metrics.yaml",
|
||||
metrics_no_cache=["metrics.yaml"],
|
||||
params=["foo"],
|
||||
name="copy-file",
|
||||
)
|
||||
scm.add(["dvc.yaml", "dvc.lock", "copy.py", "params.yaml", "metrics.yaml"])
|
||||
scm.commit("init")
|
||||
return stage
|
||||
|
||||
|
||||
def test_new_simple(tmp_dir, scm, dvc, exp_stage, mocker):
|
||||
tmp_dir.gen("params.yaml", "foo: 2")
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from datetime import datetime
|
||||
|
||||
from funcy import first
|
||||
|
||||
from dvc.dvcfile import PIPELINE_FILE
|
||||
from dvc.main import main
|
||||
from tests.func.test_repro_multistage import COPY_SCRIPT
|
||||
|
||||
|
||||
@@ -99,3 +102,60 @@ def test_show_queued(tmp_dir, scm, dvc):
|
||||
exp = results[exp_rev]
|
||||
assert exp["queued"]
|
||||
assert exp["params"]["params.yaml"] == {"foo": 3}
|
||||
|
||||
|
||||
def test_show_checkpoint(tmp_dir, scm, dvc, checkpoint_stage, capsys):
|
||||
baseline_rev = scm.get_rev()
|
||||
results = dvc.experiments.run(
|
||||
checkpoint_stage.addressing, params=["foo=2"]
|
||||
)
|
||||
exp_rev = first(results)
|
||||
|
||||
results = dvc.experiments.show()[baseline_rev]
|
||||
assert len(results) == 6
|
||||
|
||||
checkpoints = []
|
||||
for rev, exp in results.items():
|
||||
if rev != "baseline":
|
||||
checkpoints.append(rev)
|
||||
assert exp["checkpoint_tip"] == exp_rev
|
||||
|
||||
capsys.readouterr()
|
||||
assert main(["exp", "show", "--no-pager"]) == 0
|
||||
cap = capsys.readouterr()
|
||||
|
||||
for i, rev in enumerate(checkpoints):
|
||||
if i == 0:
|
||||
tree = "╓"
|
||||
elif i == len(checkpoints) - 1:
|
||||
tree = "╨"
|
||||
else:
|
||||
tree = "╟"
|
||||
assert f"{tree} {rev[:7]}" in cap.out
|
||||
|
||||
|
||||
def test_show_checkpoint_branch(tmp_dir, scm, dvc, checkpoint_stage, capsys):
|
||||
results = dvc.experiments.run(
|
||||
checkpoint_stage.addressing, params=["foo=2"]
|
||||
)
|
||||
branch_rev = first(results)
|
||||
|
||||
results = dvc.experiments.run(
|
||||
checkpoint_stage.addressing, checkpoint_resume=branch_rev
|
||||
)
|
||||
checkpoint_a = first(results)
|
||||
|
||||
results = dvc.experiments.run(
|
||||
checkpoint_stage.addressing,
|
||||
checkpoint_resume=branch_rev,
|
||||
params=["foo=100"],
|
||||
)
|
||||
checkpoint_b = first(results)
|
||||
|
||||
capsys.readouterr()
|
||||
assert main(["exp", "show", "--no-pager"]) == 0
|
||||
cap = capsys.readouterr()
|
||||
|
||||
for rev in (checkpoint_a, checkpoint_b):
|
||||
assert f"╓ {rev[:7]}" in cap.out
|
||||
assert f"({branch_rev[:7]})" in cap.out
|
||||
|
||||
Reference in New Issue
Block a user