parametrization: show interpolated vars in params diff (#5002)

* parametrization: show interpolated vars in params diff

* Add test for params.diff

* disable logging duration if feature is not enabled
This commit is contained in:
Saugat Pachhai
2020-12-01 15:43:37 +05:45
committed by GitHub
parent 7f0537038c
commit 1e1a0999f6
6 changed files with 160 additions and 68 deletions
+9 -12
View File
@@ -103,6 +103,8 @@ class DataResolver:
except (ContextError, VarsAlreadyLoaded) as exc:
format_and_raise(exc, "'vars'", self.relpath)
self.tracked_vars = {}
@staticmethod
def check_loaded(path, item, keys, skip_imports):
if not keys and isinstance(skip_imports[path], list):
@@ -216,20 +218,15 @@ class DataResolver:
exc, f"'stages.{name}.{key}'", self.relpath
)
# FIXME: Decide if we should track them or not (it does right now)
params = resolved.get(PARAMS_KWD, []) + self._resolve_params(
context, wdir
)
if params:
resolved[PARAMS_KWD] = params
self.tracked_vars[name] = self._get_vars(context)
return {name: resolved}
def _resolve_params(self, context: Context, wdir):
tracked = defaultdict(set)
for src, keys in context.tracked.items():
tracked[str(PathInfo(src).relative_to(wdir))].update(keys)
return [{file: list(keys)} for file, keys in tracked.items()]
def _get_vars(self, context: Context):
tracked = defaultdict(dict)
for path, vars_ in context.tracked.items():
for var in vars_:
tracked[path][var] = context.select(var, unwrap=True)
return tracked
def _resolve_wdir(
self, context: Context, name: str, wdir: str = None
+15
View File
@@ -6,6 +6,7 @@ from dvc.exceptions import DvcException
from dvc.path_info import PathInfo
from dvc.repo import locked
from dvc.repo.collect import collect
from dvc.stage import PipelineStage
from dvc.utils.serialize import LOADERS, ParseError
if TYPE_CHECKING:
@@ -49,6 +50,19 @@ def _read_params(repo, configs, rev):
return res
def _add_vars(repo, configs, params):
for stage in repo.stages:
if isinstance(stage, PipelineStage) and stage.tracked_vars:
for file, vars_ in stage.tracked_vars.items():
# `params` file are shown regardless of `tracked` or not
# to reduce noise and duplication, they are skipped
if file in configs:
continue
params[file] = params.get(file, {})
params[file].update(vars_)
@locked
def show(repo, revs=None):
res = {}
@@ -56,6 +70,7 @@ def show(repo, revs=None):
for branch in repo.brancher(revs=revs):
configs = _collect_configs(repo, branch)
params = _read_params(repo, configs, branch)
_add_vars(repo, configs, params)
if params:
res[branch] = params
+1
View File
@@ -655,6 +655,7 @@ class PipelineStage(Stage):
super().__init__(*args, **kwargs)
self.name = name
self.cmd_changed = False
self.tracked_vars = {}
def __eq__(self, other):
return super().__eq__(other) and self.name == other.name
+33 -6
View File
@@ -3,7 +3,14 @@ from collections.abc import Mapping
from copy import deepcopy
from itertools import chain
from funcy import cached_property, get_in, lcat, log_durations, project
from funcy import (
cached_property,
get_in,
lcat,
log_durations,
nullcontext,
project,
)
from dvc import dependency, output
from dvc.hash_info import HashInfo
@@ -18,6 +25,15 @@ from .utils import fill_stage_dependencies, resolve_paths
logger = logging.getLogger(__name__)
class NoopResolver:
def __init__(self, _repo, _wdir, d):
self.d = d
self.tracked_vars = {}
def resolve(self):
return self.d
class StageLoader(Mapping):
def __init__(self, dvcfile, data, lockfile_data=None):
self.dvcfile = dvcfile
@@ -29,14 +45,24 @@ class StageLoader(Mapping):
]
self.lockfile_data = lockfile_data or {}
@cached_property
def resolver(self):
resolver_cls = (
DataResolver if self._enable_parametrization else NoopResolver
)
wdir = PathInfo(self.dvcfile.path).parent
return resolver_cls(self.repo, wdir, self.data)
@cached_property
def resolved_data(self):
data = self.data
if self._enable_parametrization:
wdir = PathInfo(self.dvcfile.path).parent
with log_durations(logger.debug, "resolving values"):
resolver = DataResolver(self.repo, wdir, data)
data = resolver.resolve()
log = (
log_durations(logger.debug, "resolving values")
if self._enable_parametrization
else nullcontext()
)
with log:
data = self.resolver.resolve()
return data.get("stages", {})
@staticmethod
@@ -115,6 +141,7 @@ class StageLoader(Mapping):
self.lockfile_data.get(name, {}),
)
stage.tracked_vars = self.resolver.tracked_vars.get(name, {})
group, *keys = name.rsplit(JOIN, maxsplit=1)
if group and keys and name not in self.stages_data:
stage.raw_data.generated_from = group
+46
View File
@@ -1,3 +1,7 @@
from dvc.utils import relpath
from dvc.utils.serialize import dump_yaml
def test_diff_no_params(tmp_dir, scm, dvc):
assert dvc.params.diff() == {}
@@ -144,3 +148,45 @@ def test_no_commits(tmp_dir):
assert Git().no_commits
assert Repo.init().params.diff() == {}
def test_vars_shows_on_params_diff(tmp_dir, scm, dvc):
dvc.config["feature"]["parametrization"] = True
params_file = tmp_dir / "test_params.yaml"
param_data = {"vars": {"model1": {"epoch": 15}, "model2": {"epoch": 35}}}
dump_yaml(params_file, param_data)
d = {
"vars": ["test_params.yaml"],
"stages": {
"build": {
"foreach": "${vars}",
"do": {"cmd": "script --epoch ${item.epoch}"},
}
},
}
dump_yaml("dvc.yaml", d)
assert dvc.params.diff() == {
"test_params.yaml": {
"vars.model1.epoch": {"new": 15, "old": None},
"vars.model2.epoch": {"new": 35, "old": None},
}
}
scm.add(["dvc.yaml", "test_params.yaml"])
scm.commit("added stages")
param_data["vars"]["model1"]["epoch"] = 20
dump_yaml(params_file, param_data)
assert dvc.params.diff() == {
"test_params.yaml": {
"vars.model1.epoch": {"new": 20, "old": 15, "diff": 5},
}
}
data_dir = tmp_dir / "data"
data_dir.mkdir()
with data_dir.chdir():
assert dvc.params.diff() == {
relpath(params_file): {
"vars.model1.epoch": {"new": 20, "old": 15, "diff": 5},
}
}
+56 -50
View File
@@ -1,4 +1,3 @@
import os
from copy import deepcopy
from math import pi
@@ -34,16 +33,17 @@ RESOLVED_DVC_YAML_DATA = {
"cmd": "python script.py foo --out bar",
"outs": ["bar"],
"deps": ["foo"],
"params": [{"params.yaml": ["dict.foo", "dict.bar", "freeze"]}],
"frozen": True,
},
"stage2": {
"cmd": "echo foo bar",
"params": [{"params.yaml": ["dict.foo", "dict.bar"]}],
},
"stage2": {"cmd": "echo foo bar"},
}
}
USED_VARS = {
"stage1": {"dict.foo": "foo", "dict.bar": "bar", "freeze": True},
"stage2": {"dict.foo": "foo", "dict.bar": "bar"},
}
def recurse_not_a_node(d):
assert not isinstance(d, Node)
@@ -73,6 +73,10 @@ def test_simple(tmp_dir, dvc):
dvc, PathInfo(str(tmp_dir)), deepcopy(TEMPLATED_DVC_YAML_DATA)
)
assert_stage_equal(resolver.resolve(), deepcopy(RESOLVED_DVC_YAML_DATA))
assert resolver.tracked_vars == {
"stage1": {DEFAULT_PARAMS_FILE: USED_VARS["stage1"]},
"stage2": {DEFAULT_PARAMS_FILE: USED_VARS["stage2"]},
}
def test_vars(tmp_dir, dvc):
@@ -81,10 +85,8 @@ def test_vars(tmp_dir, dvc):
resolver = DataResolver(dvc, PathInfo(str(tmp_dir)), d)
resolved_data = deepcopy(RESOLVED_DVC_YAML_DATA)
# `vars` section is not auto-tracked
del resolved_data["stages"]["stage1"]["params"]
del resolved_data["stages"]["stage2"]["params"]
assert_stage_equal(resolver.resolve(), resolved_data)
assert not any(resolver.tracked_vars.values())
def test_no_params_yaml_and_vars(tmp_dir, dvc):
@@ -97,7 +99,7 @@ def test_no_params_yaml_and_vars(tmp_dir, dvc):
def test_vars_import(tmp_dir, dvc):
"""
Test that different file can be loaded using `use`
Test that different file can be loaded using `vars`
instead of default params.yaml.
"""
dump_yaml(tmp_dir / "params2.yaml", CONTEXT_DATA)
@@ -106,11 +108,11 @@ def test_vars_import(tmp_dir, dvc):
resolver = DataResolver(dvc, PathInfo(str(tmp_dir)), d)
resolved_data = deepcopy(RESOLVED_DVC_YAML_DATA)
for _, stage_d in resolved_data["stages"].items():
params = stage_d["params"][0]
params["params2.yaml"] = params.pop(DEFAULT_PARAMS_FILE)
assert_stage_equal(resolver.resolve(), resolved_data)
assert resolver.tracked_vars == {
"stage1": {"params2.yaml": USED_VARS["stage1"]},
"stage2": {"params2.yaml": USED_VARS["stage2"]},
}
def test_vars_and_params_import(tmp_dir, dvc):
@@ -126,13 +128,11 @@ def test_vars_and_params_import(tmp_dir, dvc):
resolver = DataResolver(dvc, PathInfo(str(tmp_dir)), d)
assert_stage_equal(
resolver.resolve(),
{
"stages": {
"stage1": {"cmd": "echo foobar bar", "params": ["dict.bar"]}
}
},
resolver.resolve(), {"stages": {"stage1": {"cmd": "echo foobar bar"}}}
)
assert resolver.tracked_vars == {
"stage1": {DEFAULT_PARAMS_FILE: {"dict.bar": "bar"}}
}
def test_with_params_section(tmp_dir, dvc):
@@ -156,14 +156,17 @@ def test_with_params_section(tmp_dir, dvc):
"stages": {
"stage1": {
"cmd": "echo foo bar foobar",
"params": [
"dict.bar",
{"params.json": ["dict.foobar", "value1"]},
],
"params": [{"params.json": ["value1"]}],
}
}
},
)
assert resolver.tracked_vars == {
"stage1": {
DEFAULT_PARAMS_FILE: {"dict.bar": "bar"},
"params.json": {"dict.foobar": "foobar"},
}
}
def test_stage_with_wdir(tmp_dir, dvc):
@@ -187,7 +190,6 @@ def test_stage_with_wdir(tmp_dir, dvc):
dump_json(data_dir / DEFAULT_PARAMS_FILE, {"dict": {"foo": "foo"}})
resolver = DataResolver(dvc, PathInfo(str(tmp_dir)), d)
root_params_file = os.path.relpath(tmp_dir / "params.yaml", data_dir)
assert_stage_equal(
resolver.resolve(),
{
@@ -195,15 +197,17 @@ def test_stage_with_wdir(tmp_dir, dvc):
"stage1": {
"cmd": "echo foo bar",
"wdir": "data",
"params": [
"dict.foo",
"value1",
{root_params_file: ["dict.bar"]},
],
"params": ["value1"],
}
}
},
)
assert resolver.tracked_vars == {
"stage1": {
str(PathInfo("data") / DEFAULT_PARAMS_FILE): {"dict.foo": "foo"},
DEFAULT_PARAMS_FILE: {"dict.bar": "bar"},
}
}
def test_with_templated_wdir(tmp_dir, dvc):
@@ -229,7 +233,6 @@ def test_with_templated_wdir(tmp_dir, dvc):
dump_json(data_dir / DEFAULT_PARAMS_FILE, {"dict": {"foo": "foo"}})
resolver = DataResolver(dvc, PathInfo(str(tmp_dir)), d)
root_params_file = os.path.relpath(tmp_dir / "params.yaml", data_dir)
assert_stage_equal(
resolver.resolve(),
{
@@ -237,15 +240,17 @@ def test_with_templated_wdir(tmp_dir, dvc):
"stage1": {
"cmd": "echo foo bar",
"wdir": "data",
"params": [
"dict.foo",
"value1",
{root_params_file: ["dict.bar", "dict.ws"]},
],
"params": ["value1"],
}
}
},
)
assert resolver.tracked_vars == {
"stage1": {
str(PathInfo("data") / DEFAULT_PARAMS_FILE): {"dict.foo": "foo"},
DEFAULT_PARAMS_FILE: {"dict.bar": "bar", "dict.ws": "data"},
}
}
def test_simple_foreach_loop(tmp_dir, dvc):
@@ -314,13 +319,14 @@ def test_foreach_loop_templatized(tmp_dir, dvc):
{
"stages": {
"build@gb": {"cmd": "python script.py --thresh 15"},
"build@us": {
"cmd": "python script.py --thresh 10",
"params": ["models.us.thresh"],
},
"build@us": {"cmd": "python script.py --thresh 10"},
}
},
)
assert resolver.tracked_vars == {
"build@gb": {},
"build@us": {DEFAULT_PARAMS_FILE: {"models.us.thresh": 10}},
}
@pytest.mark.parametrize(
@@ -419,17 +425,15 @@ def test_set_with_foreach_and_on_stage_definition(tmp_dir, dvc):
resolver.resolve(),
{
"stages": {
"build@us": {
"cmd": "command --value 10",
"params": [{"params.json": ["models.us.thresh"]}],
},
"build@gb": {
"cmd": "command --value 15",
"params": [{"params.json": ["models.gb.thresh"]}],
},
"build@us": {"cmd": "command --value 10"},
"build@gb": {"cmd": "command --value 15"},
}
},
)
assert resolver.tracked_vars == {
"build@us": {"params.json": {"models.us.thresh": 10}},
"build@gb": {"params.json": {"models.gb.thresh": 15}},
}
def test_resolve_local_tries_to_load_globally_used_files(tmp_dir, dvc):
@@ -453,11 +457,12 @@ def test_resolve_local_tries_to_load_globally_used_files(tmp_dir, dvc):
"stages": {
"build": {
"cmd": "command --value bar",
"params": [{"params.json": ["bar", "foo"]}],
"params": [{"params.json": ["foo"]}],
},
}
},
)
assert resolver.tracked_vars == {"build": {"params.json": {"bar": "bar"}}}
def test_resolve_local_tries_to_load_globally_used_params_yaml(tmp_dir, dvc):
@@ -480,11 +485,12 @@ def test_resolve_local_tries_to_load_globally_used_params_yaml(tmp_dir, dvc):
"stages": {
"build": {
"cmd": "command --value bar",
"params": [{"params.yaml": ["bar", "foo"]}],
"params": [{"params.yaml": ["foo"]}],
},
}
},
)
assert resolver.tracked_vars == {"build": {"params.yaml": {"bar": "bar"}}}
def test_vars_relpath_overwrite(tmp_dir, dvc):