nablapo 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. nablapo/__init__.py +7 -0
  2. nablapo/cli/__init__.py +1 -0
  3. nablapo/cli/eval.py +31 -0
  4. nablapo/cli/export.py +56 -0
  5. nablapo/cli/setup_warp.py +93 -0
  6. nablapo/cli/train.py +52 -0
  7. nablapo/config/__init__.py +5 -0
  8. nablapo/config/loader.py +341 -0
  9. nablapo/config/schema.py +159 -0
  10. nablapo/config/sections.py +17 -0
  11. nablapo/configs/MANIFEST.toml +322 -0
  12. nablapo/configs/bench/default.toml +86 -0
  13. nablapo/configs/bench/wm_imagine.toml +74 -0
  14. nablapo/configs/bench/wm_jac.toml +95 -0
  15. nablapo/configs/demos/hoi_box.toml +59 -0
  16. nablapo/configs/demos/hoi_box_wm.toml +6 -0
  17. nablapo/configs/demos/joint_joystick_lafan1.toml +134 -0
  18. nablapo/configs/demos/joystick_early.toml +125 -0
  19. nablapo/configs/demos/joystick_early_wm.toml +16 -0
  20. nablapo/configs/demos/terrain_minimal.toml +38 -0
  21. nablapo/configs/demos/tracking_lafan1.toml +11 -0
  22. nablapo/configs/eval/bench_nominal.toml +5 -0
  23. nablapo/configs/eval/hoi_box_nominal.toml +10 -0
  24. nablapo/configs/eval/joystick_grid.toml +14 -0
  25. nablapo/configs/eval/joystick_grid_dr.toml +14 -0
  26. nablapo/configs/eval/lafan1_nominal_origin.toml +9 -0
  27. nablapo/configs/eval/lafan1_nominal_v1.toml +8 -0
  28. nablapo/configs/eval/terrain_flat_steady.toml +6 -0
  29. nablapo/configs/eval/terrain_lanes.toml +5 -0
  30. nablapo/configs/eval/terrain_stand_step.toml +6 -0
  31. nablapo/configs/lafan1_tracking.toml +13 -0
  32. nablapo/configs/paper/nablamimic_arxiv_v1/ablations/h32.toml +8 -0
  33. nablapo/configs/paper/nablamimic_arxiv_v1/ablations/no_clip.toml +42 -0
  34. nablapo/configs/paper/nablamimic_arxiv_v1/ablations/no_pods.toml +43 -0
  35. nablapo/configs/paper/nablamimic_arxiv_v1/ablations/no_replay.toml +9 -0
  36. nablapo/configs/paper/nablamimic_arxiv_v1/ablations/uniform_resets.toml +8 -0
  37. nablapo/configs/paper/nablamimic_arxiv_v1/lafan1_absolute.toml +43 -0
  38. nablapo/configs/paper/nablamimic_arxiv_v1/lafan1_absolute_mjw.toml +10 -0
  39. nablapo/configs/paper/nablamimic_arxiv_v1/lafan1_residual.toml +5 -0
  40. nablapo/configs/paper/nablamimic_arxiv_v1/lafan1_residual_mjw.toml +3 -0
  41. nablapo/configs/paper/nablamimic_arxiv_v2/lafan1_residual_ema_w100.toml +43 -0
  42. nablapo/configs/paper/nablamimic_arxiv_v2/lafan1_tracking.toml +39 -0
  43. nablapo/configs/tech/actor_ema.toml +13 -0
  44. nablapo/configs/tech/anchor_to_decoder.toml +11 -0
  45. nablapo/configs/tech/applied_action_obs.toml +10 -0
  46. nablapo/configs/tech/bf16_matmuls.toml +10 -0
  47. nablapo/configs/tech/cotangent_clip.toml +11 -0
  48. nablapo/configs/tech/critic_pre_state.toml +10 -0
  49. nablapo/configs/tech/domain_randomization.toml +14 -0
  50. nablapo/configs/tech/eval_guided_resets.toml +15 -0
  51. nablapo/configs/tech/late_lr_drop.toml +11 -0
  52. nablapo/configs/tech/lr_boost.toml +11 -0
  53. nablapo/configs/tech/lr_hold_cosine.toml +17 -0
  54. nablapo/configs/tech/mask_after_done.toml +10 -0
  55. nablapo/configs/tech/muon_actor.toml +11 -0
  56. nablapo/configs/tech/mup_silu_layernorm.toml +22 -0
  57. nablapo/configs/tech/pods_targets.toml +22 -0
  58. nablapo/configs/tech/replay_starts.toml +17 -0
  59. nablapo/configs/tech/residual_actions.toml +10 -0
  60. nablapo/configs/tech/return_resets.toml +11 -0
  61. nablapo/configs/tech/termination_penalty.toml +25 -0
  62. nablapo/core/__init__.py +2 -0
  63. nablapo/core/aux.py +52 -0
  64. nablapo/core/checkpoint.py +73 -0
  65. nablapo/core/collector.py +64 -0
  66. nablapo/core/config.py +200 -0
  67. nablapo/core/critic.py +84 -0
  68. nablapo/core/ema.py +6 -0
  69. nablapo/core/optim/__init__.py +1 -0
  70. nablapo/core/optim/adam.py +12 -0
  71. nablapo/core/optim/muon.py +45 -0
  72. nablapo/core/probe.py +31 -0
  73. nablapo/core/schedules.py +58 -0
  74. nablapo/core/targets.py +116 -0
  75. nablapo/core/trainer.py +599 -0
  76. nablapo/core/tree.py +40 -0
  77. nablapo/core/windows.py +210 -0
  78. nablapo/core/wm.py +167 -0
  79. nablapo/data/__init__.py +83 -0
  80. nablapo/data/lafan1_g1.sha256 +42 -0
  81. nablapo/data/models.toml +299 -0
  82. nablapo/eval/__init__.py +3 -0
  83. nablapo/eval/config.py +17 -0
  84. nablapo/eval/runner.py +117 -0
  85. nablapo/ext/__init__.py +69 -0
  86. nablapo/nets/__init__.py +1 -0
  87. nablapo/nets/actor.py +86 -0
  88. nablapo/nets/critic.py +12 -0
  89. nablapo/nets/mlp.py +95 -0
  90. nablapo/patches/mujoco_warp/0001-adjoint-switches-clamped-kv-and-contact-normal.diff +153 -0
  91. nablapo/patches/mujoco_warp/0002-near-parallel-capsule-segment-parameters.diff +62 -0
  92. nablapo/patches/mujoco_warp/0003-soft-actuator-clamp-switch.diff +114 -0
  93. nablapo/patches/mujoco_warp/0004-ift-solve-without-cholesky-ceiling.diff +138 -0
  94. nablapo/patches/mujoco_warp/README.md +39 -0
  95. nablapo/patches/mujoco_warp/tree.sha256 +5 -0
  96. nablapo/physics/__init__.py +7 -0
  97. nablapo/physics/_smooth_gen.py +209 -0
  98. nablapo/physics/_warp_rne.py +105 -0
  99. nablapo/physics/engine.py +51 -0
  100. nablapo/physics/mjw_options.py +46 -0
  101. nablapo/physics/warp.py +283 -0
  102. nablapo/physics/warp_backend.py +18 -0
  103. nablapo/policy/__init__.py +3 -0
  104. nablapo/policy/load.py +121 -0
  105. nablapo/policy/spec.py +55 -0
  106. nablapo/samplers/__init__.py +4 -0
  107. nablapo/samplers/config.py +39 -0
  108. nablapo/samplers/probes.py +58 -0
  109. nablapo/samplers/reset.py +60 -0
  110. nablapo/tasks/__init__.py +1 -0
  111. nablapo/tasks/api.py +164 -0
  112. nablapo/tasks/bench/__init__.py +1 -0
  113. nablapo/tasks/bench/config.py +22 -0
  114. nablapo/tasks/bench/env.py +185 -0
  115. nablapo/tasks/bench/evaluate.py +42 -0
  116. nablapo/tasks/bench/task.py +48 -0
  117. nablapo/tasks/g1/__init__.py +1 -0
  118. nablapo/tasks/g1/dr.py +144 -0
  119. nablapo/tasks/g1/model.py +64 -0
  120. nablapo/tasks/g1/robot.py +109 -0
  121. nablapo/tasks/hoi/__init__.py +8 -0
  122. nablapo/tasks/hoi/blocks.py +134 -0
  123. nablapo/tasks/hoi/config.py +162 -0
  124. nablapo/tasks/hoi/env.py +742 -0
  125. nablapo/tasks/hoi/evaluate.py +111 -0
  126. nablapo/tasks/hoi/geometry.py +109 -0
  127. nablapo/tasks/hoi/motion.py +133 -0
  128. nablapo/tasks/hoi/scene.py +131 -0
  129. nablapo/tasks/hoi/starts.py +63 -0
  130. nablapo/tasks/hoi/task.py +111 -0
  131. nablapo/tasks/joint/__init__.py +2 -0
  132. nablapo/tasks/joint/config.py +84 -0
  133. nablapo/tasks/joint/env.py +244 -0
  134. nablapo/tasks/joint/task.py +105 -0
  135. nablapo/tasks/joystick/__init__.py +1 -0
  136. nablapo/tasks/joystick/config.py +128 -0
  137. nablapo/tasks/joystick/env.py +717 -0
  138. nablapo/tasks/joystick/evaluate.py +104 -0
  139. nablapo/tasks/joystick/gait.py +58 -0
  140. nablapo/tasks/joystick/task.py +104 -0
  141. nablapo/tasks/registry.py +64 -0
  142. nablapo/tasks/terrain/__init__.py +13 -0
  143. nablapo/tasks/terrain/config.py +135 -0
  144. nablapo/tasks/terrain/env.py +667 -0
  145. nablapo/tasks/terrain/evaluate.py +214 -0
  146. nablapo/tasks/terrain/generator.py +155 -0
  147. nablapo/tasks/terrain/hooks.py +386 -0
  148. nablapo/tasks/terrain/sensors.py +129 -0
  149. nablapo/tasks/terrain/source.py +182 -0
  150. nablapo/tasks/terrain/task.py +212 -0
  151. nablapo/tasks/tracking/__init__.py +1 -0
  152. nablapo/tasks/tracking/config.py +86 -0
  153. nablapo/tasks/tracking/env.py +526 -0
  154. nablapo/tasks/tracking/evaluate.py +139 -0
  155. nablapo/tasks/tracking/motion.py +157 -0
  156. nablapo/tasks/tracking/task.py +111 -0
  157. nablapo/wm/__init__.py +33 -0
  158. nablapo/wm/models.py +452 -0
  159. nablapo-0.1.0.dist-info/METADATA +194 -0
  160. nablapo-0.1.0.dist-info/RECORD +166 -0
  161. nablapo-0.1.0.dist-info/WHEEL +5 -0
  162. nablapo-0.1.0.dist-info/entry_points.txt +5 -0
  163. nablapo-0.1.0.dist-info/licenses/LICENSE +202 -0
  164. nablapo-0.1.0.dist-info/licenses/NOTICE +9 -0
  165. nablapo-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +162 -0
  166. nablapo-0.1.0.dist-info/top_level.txt +1 -0
nablapo/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """NablaPO: first-order policy optimization that backpropagates the return through an exact differentiable simulator.
2
+
3
+ Importing the package loads nothing heavy (no JAX, no simulator, no extension). The public API is documented in
4
+ docs/api.md.
5
+ """
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1 @@
1
+ """Command-line entry points: nablapo-train, nablapo-eval, nablapo-export-policy, nablapo-setup-warp."""
nablapo/cli/eval.py ADDED
@@ -0,0 +1,31 @@
1
+ """nablapo-eval: evaluate a run's light checkpoints with an evaluation protocol.
2
+
3
+ nablapo-eval RUN [--protocol NAME_OR_PATH] [--updates U ...] [--out FILE]
4
+
5
+ Default protocol: the run's [eval] protocol; default checkpoints: every light checkpoint of the first hour of
6
+ training, every 1000 updates, and the last one. Results are merged into FILE (default RUN/eval_<protocol>.json).
7
+ """
8
+
9
+ import argparse
10
+ import sys
11
+ from pathlib import Path
12
+
13
+
14
+ def main(argv=None):
15
+ ap = argparse.ArgumentParser(prog="nablapo-eval", description="Evaluate a run's checkpoints.")
16
+ ap.add_argument("run")
17
+ ap.add_argument("--protocol", default=None)
18
+ ap.add_argument("--updates", type=int, nargs="+", default=None)
19
+ ap.add_argument("--out", default=None)
20
+ args = ap.parse_args(argv)
21
+ from ..config import resolve
22
+ from ..eval.runner import evaluate_run
23
+ proto = args.protocol or resolve(Path(args.run) / "config.resolved.toml").config.eval.protocol
24
+ if not proto:
25
+ ap.error("no protocol: the run has no [eval] protocol; pass --protocol")
26
+ evaluate_run(args.run, proto, args.updates, args.out, log=lambda s: print(s, flush=True))
27
+ return 0
28
+
29
+
30
+ if __name__ == "__main__":
31
+ sys.exit(main())
nablapo/cli/export.py ADDED
@@ -0,0 +1,56 @@
1
+ """nablapo-export-policy: write a release directory (actor.npz + policy_spec.json) from a run's light checkpoint.
2
+
3
+ nablapo-export-policy RUN --out DIR [--update U] # default: the newest light checkpoint
4
+ """
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import sys
10
+ from pathlib import Path
11
+
12
+
13
+ def export(run, out, update=None):
14
+ import jax
15
+ import numpy as np
16
+
17
+ from ..config import resolve
18
+ from ..core import checkpoint
19
+ from ..core.trainer import actor_spec_for
20
+ from ..eval.runner import light_checkpoints
21
+ from ..nets import actor as actor_net
22
+ from ..policy.spec import build_spec, flat_params
23
+ from ..tasks import registry
24
+ run, out = Path(run), Path(out)
25
+ cks = dict(light_checkpoints(run))
26
+ if not cks:
27
+ raise FileNotFoundError(f"no light checkpoints in {run / 'ckpt'}")
28
+ u = update if update is not None else max(cks)
29
+ cfg = resolve(run / "config.resolved.toml").config
30
+ task = registry.get(cfg.task.family)(cfg.task)
31
+ env = task.make_env(eval_mode=True)
32
+ spec = actor_spec_for(env, cfg)
33
+ arrays, meta = checkpoint.read(cks[u])
34
+ actor = checkpoint.restore(arrays, "actor", actor_net.init(jax.random.PRNGKey(0), spec))
35
+ out.mkdir(parents=True, exist_ok=True)
36
+ with open(out / "actor.npz", "wb") as f:
37
+ np.savez(f, **flat_params(actor))
38
+ digest = hashlib.sha256((out / "actor.npz").read_bytes()).hexdigest()
39
+ pspec = build_spec(task, env, spec, {"weights_sha256": digest, "update": int(meta["update"]),
40
+ "actor": meta.get("actor", "live")})
41
+ (out / "policy_spec.json").write_text(json.dumps(pspec, indent=1) + "\n")
42
+ return out
43
+
44
+
45
+ def main(argv=None):
46
+ ap = argparse.ArgumentParser(prog="nablapo-export-policy", description="Export a policy release directory.")
47
+ ap.add_argument("run")
48
+ ap.add_argument("--out", required=True)
49
+ ap.add_argument("--update", type=int, default=None)
50
+ a = ap.parse_args(argv)
51
+ print(export(a.run, a.out, a.update))
52
+ return 0
53
+
54
+
55
+ if __name__ == "__main__":
56
+ sys.exit(main())
@@ -0,0 +1,93 @@
1
+ """nablapo-setup-warp: build the patched MuJoCo Warp tree (patches/mujoco_warp/README.md) and install it.
2
+
3
+ nablapo-setup-warp [DEST] [--no-install] # DEST default <data dir>/mujoco_warp ($NABLAPO_DATA)
4
+
5
+ etaoxing/mujoco_warp at the head of its pull request #1 (4af093f, on top of 357a75d), then the patches 0001-0004
6
+ shipped with nablapo (git apply), the source-tree check against tree.sha256, and an editable install (pip, no
7
+ dependencies) into the running Python environment. An existing DEST that already holds the patched tree is only
8
+ checked and installed. scripts/setup_mujoco_warp.sh runs this module. Needs git and network access.
9
+ """
10
+
11
+ import argparse
12
+ import hashlib
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ URL = "https://github.com/etaoxing/mujoco_warp.git"
19
+ BASE = "357a75d60a56d67d476942a1b6e54b3045ee8e87"
20
+ HEAD = "4af093f02a3f48f0009ca7c916674b928136f310"
21
+ _PKG = Path(__file__).resolve().parents[1]
22
+ REPO_PATCHES = _PKG.parents[1] / "patches" / "mujoco_warp" # patches/mujoco_warp of a source checkout
23
+ PACKAGED_PATCHES = _PKG / "patches" / "mujoco_warp" # nablapo/patches/mujoco_warp of the wheel (setup.py)
24
+
25
+
26
+ def patches_dir():
27
+ """The MuJoCo Warp patches of this nablapo: the repository's in a source checkout, else the wheel's copy."""
28
+ return REPO_PATCHES if (REPO_PATCHES / "tree.sha256").is_file() else PACKAGED_PATCHES
29
+
30
+
31
+ def expected_hash(pdir=None):
32
+ lines = [s.strip() for s in ((pdir or patches_dir()) / "tree.sha256").read_text().splitlines()]
33
+ return next(s for s in lines if s and not s.startswith("#"))
34
+
35
+
36
+ def tree_hash(dest):
37
+ """`find mujoco_warp -type f -name '*.py' | LC_ALL=C sort | xargs sha256sum | sha256sum` in dest."""
38
+ dest = Path(dest)
39
+ files = sorted((p.relative_to(dest).as_posix() for p in (dest / "mujoco_warp").rglob("*.py")
40
+ if p.is_file() and not p.is_symlink()), key=lambda s: s.encode())
41
+ listing = "".join(f"{hashlib.sha256((dest / f).read_bytes()).hexdigest()} {f}\n" for f in files)
42
+ return hashlib.sha256(listing.encode()).hexdigest()
43
+
44
+
45
+ def git(dest, *args, check=True):
46
+ return subprocess.run(["git", "-C", str(dest), *args], check=check, capture_output=True, text=True)
47
+
48
+
49
+ def build(dest, log=print):
50
+ """Clone, check out and patch the tree in dest unless it already is the patched tree; returns dest."""
51
+ dest = Path(dest)
52
+ pdir = patches_dir()
53
+ want = expected_hash(pdir)
54
+ if not (dest / ".git").is_dir():
55
+ dest.parent.mkdir(parents=True, exist_ok=True)
56
+ subprocess.run(["git", "clone", "-q", URL, str(dest)], check=True)
57
+ if tree_hash(dest) != want:
58
+ if git(dest, "cat-file", "-e", f"{HEAD}^{{commit}}", check=False).returncode:
59
+ git(dest, "fetch", "-q", "origin", "pull/1/head")
60
+ git(dest, "cat-file", "-e", f"{HEAD}^{{commit}}")
61
+ if git(dest, "status", "--porcelain", "--untracked-files=no").stdout.strip():
62
+ raise SystemExit(f"{dest} has local changes; use a fresh directory")
63
+ git(dest, "-c", "advice.detachedHead=false", "checkout", "-q", "--detach", HEAD)
64
+ git(dest, "merge-base", "--is-ancestor", BASE, "HEAD")
65
+ for p in sorted(pdir.glob("000[1-4]-*.diff")):
66
+ git(dest, "apply", str(p))
67
+ log(f"applied {p.name}")
68
+ got = tree_hash(dest)
69
+ if got != want:
70
+ raise SystemExit(f"patched MuJoCo Warp tree hash {got} != {want} ({pdir / 'tree.sha256'})")
71
+ log(f"MuJoCo Warp tree OK: {dest}")
72
+ return dest
73
+
74
+
75
+ def main(argv=None):
76
+ ap = argparse.ArgumentParser(prog="nablapo-setup-warp", description="Build and install the patched MuJoCo Warp.")
77
+ ap.add_argument("dest", nargs="?", default=None, help="tree directory (default <data dir>/mujoco_warp)")
78
+ ap.add_argument("--no-install", action="store_true", help="build and check the tree only")
79
+ args = ap.parse_args(argv)
80
+ if args.dest:
81
+ dest = Path(args.dest)
82
+ else:
83
+ from ..data import data_dir
84
+ dest = data_dir() / "mujoco_warp"
85
+ build(dest.resolve(), log=lambda s: print(s, flush=True))
86
+ if not args.no_install:
87
+ subprocess.run([sys.executable, "-m", "pip", "install", "--no-deps", "-e", str(dest.resolve())], check=True,
88
+ env={**os.environ, "PIP_DISABLE_PIP_VERSION_CHECK": "1"})
89
+ return 0
90
+
91
+
92
+ if __name__ == "__main__":
93
+ sys.exit(main())
nablapo/cli/train.py ADDED
@@ -0,0 +1,52 @@
1
+ """nablapo-train: train from a TOML config.
2
+
3
+ nablapo-train CONFIG --out DIR [--set section.key=value ...]
4
+ nablapo-train --out DIR --resume latest [--set run.updates=N run.hours=H]
5
+
6
+ At the first start the resolved config is written to DIR (config.resolved.toml, config.json); a resumed run reads
7
+ DIR/config.resolved.toml and takes no other config; its overrides may only extend the budget (run.updates,
8
+ run.hours), which is recorded in DIR/run.jsonl.
9
+ """
10
+
11
+ import argparse
12
+ import sys
13
+ from pathlib import Path
14
+
15
+
16
+ def main(argv=None):
17
+ ap = argparse.ArgumentParser(prog="nablapo-train", description="Train a policy from a TOML config.")
18
+ ap.add_argument("config", nargs="?", help="TOML config (not with --resume)")
19
+ ap.add_argument("--out", required=True, help="output directory")
20
+ ap.add_argument("--set", nargs="+", default=[], metavar="KEY=VALUE", help="overrides, e.g. run.seed=1")
21
+ ap.add_argument("--resume", default=None, help="'latest' (the newest full checkpoint in OUT/ckpt) or a path")
22
+ ap.add_argument("--no-extensions", action="store_true", help="resolve the config without extension blocks")
23
+ args = ap.parse_args(argv)
24
+ from ..config import resolve, write_record
25
+ from ..core import checkpoint
26
+ from ..core.trainer import Trainer
27
+ out = Path(args.out)
28
+ if args.resume:
29
+ budget = ("run.updates=", "run.hours=")
30
+ if args.config or any(not s.startswith(budget) for s in args.set):
31
+ ap.error("--resume takes the run's own config.resolved.toml: no CONFIG, and --set only for run.updates / "
32
+ "run.hours")
33
+ res = resolve(out / "config.resolved.toml", [f"run.out={str(out)!r}".replace("'", '"'), *args.set])
34
+ resume = checkpoint.latest(out / "ckpt") if args.resume == "latest" else Path(args.resume)
35
+ if resume is None:
36
+ print(f"no full checkpoint in {out / 'ckpt'}; starting from scratch", flush=True)
37
+ else:
38
+ if not args.config:
39
+ ap.error("CONFIG is required")
40
+ if (out / "config.json").exists():
41
+ ap.error(f"{out} already holds a run; use --resume latest or another --out")
42
+ res = resolve(args.config, list(args.set), extensions=not args.no_extensions)
43
+ write_record(res, out)
44
+ resume = None
45
+ from ..tasks import registry
46
+ task = registry.get(res.config.task.family)(res.config.task)
47
+ Trainer(res.config, task, out, resume, log=lambda s: print(s, flush=True)).run()
48
+ return 0
49
+
50
+
51
+ if __name__ == "__main__":
52
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ """TOML configs: typed sections, technique blocks, the merge order, --set overrides and the resolved record."""
2
+
3
+ from .loader import Config, Resolved, config_path, dump_toml, load_config, resolve # noqa: F401
4
+ from .loader import shipped_configs, write_record # noqa: F401
5
+ from .schema import REQUIRED, ConfigError # noqa: F401
@@ -0,0 +1,341 @@
1
+ """TOML config loading: base chains, technique blocks, the merge order, --set overrides, validation and the resolved
2
+ record.
3
+
4
+ Merge order (each step overrides the previous ones):
5
+ 1. code defaults of the config dataclasses;
6
+ 2. the task family's defaults (its Config dataclass and Task.defaults for core keys);
7
+ 3. technique blocks in the order of the resolved `techniques` list: each block's parameters are its [params], then
8
+ its [defaults.<family>], then the [tech.<name>] overrides of the config chain (base first); a key set by two
9
+ blocks is an error unless the later block lists the earlier one in `overrides`;
10
+ 4. the base configs' direct keys, deepest base first;
11
+ 5. the config's own direct keys;
12
+ 6. command-line overrides `section.key=value` (values parsed as TOML).
13
+ """
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import tomllib
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ from .schema import REQUIRED, ConfigError, build, coerce, flatten, schema
23
+
24
+ SECTIONS = ("task", "learner", "wm", "sampler", "eval", "run")
25
+ TOP_KEYS = {"base", "techniques", "tech", *SECTIONS}
26
+ BLOCK_KEYS = {"name", "help", "requires", "conflicts", "overrides", "params", "defaults", "sets"}
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Config:
31
+ """The resolved, validated config: one dataclass per section."""
32
+ task: object
33
+ learner: object
34
+ wm: object
35
+ sampler: object
36
+ eval: object
37
+ run: object
38
+ techniques: tuple = ()
39
+
40
+
41
+ @dataclass
42
+ class Resolved:
43
+ config: Config
44
+ values: dict # {dotted key: value}
45
+ layers: dict # {dotted key: layer that set it}
46
+ techniques: list # [{name, source, sha256, params}]
47
+ files: list = field(default_factory=list)
48
+
49
+
50
+ def section_classes(family):
51
+ from ..core.config import LearnerConfig
52
+ from ..eval.config import EvalConfig
53
+ from ..samplers.config import SamplerConfig
54
+ from ..tasks import registry
55
+ from ..wm import WMConfig
56
+ from .sections import RunConfig
57
+ task_cls = registry.get(family)
58
+ return task_cls, {"task": task_cls.Config, "learner": LearnerConfig, "wm": WMConfig, "sampler": SamplerConfig,
59
+ "eval": EvalConfig, "run": RunConfig}
60
+
61
+
62
+ def full_schema(classes):
63
+ out = {}
64
+ for sec, cls in classes.items():
65
+ out.update(schema(cls, sec + "."))
66
+ return out
67
+
68
+
69
+ def _flatten_table(t, prefix):
70
+ out = {}
71
+ for k, v in t.items():
72
+ if isinstance(v, dict):
73
+ out.update(_flatten_table(v, f"{prefix}{k}."))
74
+ else:
75
+ out[f"{prefix}{k}"] = v
76
+ return out
77
+
78
+
79
+ def read_chain(path, seen=()):
80
+ """[(path, data)] from the deepest base to `path` (a path or a `nablapo:` reference); a relative `base` is
81
+ relative to the file that names it."""
82
+ path = config_path(path).resolve()
83
+ if path in seen:
84
+ raise ConfigError(f"base cycle at {path}")
85
+ data = tomllib.loads(path.read_text())
86
+ unknown = set(data) - TOP_KEYS
87
+ if unknown:
88
+ raise ConfigError(f"{path}: unknown top-level keys {sorted(unknown)}")
89
+ chain = []
90
+ if "base" in data:
91
+ base = data["base"]
92
+ chain = read_chain(base if base.startswith(SHIPPED) else path.parent / base, seen + (path,))
93
+ return chain + [(path, data)]
94
+
95
+
96
+ def parse_override(s):
97
+ """'section.key=value' -> (key, value); the value is parsed as TOML, else taken as a string."""
98
+ if "=" not in s:
99
+ raise ConfigError(f"override {s!r}: expected section.key=value")
100
+ k, v = s.split("=", 1)
101
+ k = k.strip()
102
+ try:
103
+ val = tomllib.loads(f"v = {v}")["v"]
104
+ except tomllib.TOMLDecodeError:
105
+ val = v
106
+ return k, val
107
+
108
+
109
+ SHIPPED = "nablapo:" # prefix of a reference to a config file that ships with the library
110
+ REPO_CONFIGS = Path(__file__).resolve().parents[3] / "configs" # configs/ of a source checkout
111
+ PACKAGED_CONFIGS = Path(__file__).resolve().parents[1] / "configs" # nablapo/configs of the wheel (setup.py)
112
+
113
+
114
+ def shipped_configs():
115
+ """The configs that ship with this nablapo: the repository's configs/ in a source checkout, else the copy that
116
+ the wheel carries as package data (nablapo/configs)."""
117
+ return REPO_CONFIGS if (REPO_CONFIGS / "MANIFEST.toml").is_file() else PACKAGED_CONFIGS
118
+
119
+
120
+ def config_path(ref):
121
+ """The file of a config reference: `nablapo:<path>` is <path> under shipped_configs() (for example
122
+ `nablapo:paper/nablamimic_arxiv_v2/lafan1_tracking.toml`), anything else a file path."""
123
+ s = str(ref)
124
+ if not s.startswith(SHIPPED):
125
+ return Path(ref)
126
+ p = shipped_configs() / s[len(SHIPPED):]
127
+ if not p.is_file():
128
+ raise ConfigError(f"{s}: no such shipped config ({p})")
129
+ return p
130
+
131
+
132
+ def configs_root(start=None):
133
+ """The configs directory of technique blocks and evaluation protocols: the nearest ancestor of `start` with a
134
+ MANIFEST.toml, else $NABLAPO_CONFIGS, else shipped_configs()."""
135
+ if start is not None:
136
+ for p in [Path(start).resolve(), *Path(start).resolve().parents]:
137
+ if (p / "MANIFEST.toml").exists():
138
+ return p
139
+ if os.environ.get("NABLAPO_CONFIGS"):
140
+ return Path(os.environ["NABLAPO_CONFIGS"])
141
+ return shipped_configs()
142
+
143
+
144
+ def load_block(name, root, extensions=True):
145
+ """(block dict, source record) of a technique block: public blocks from <configs>/tech/<name>.toml, extension
146
+ blocks `<ext>.<block>` from the extension's technique_blocks() mapping or its configs/tech/ directory."""
147
+ if "." in name:
148
+ if not extensions:
149
+ raise ConfigError(f"technique {name!r} is an extension block; extensions are disabled")
150
+ ext_name, block = name.split(".", 1)
151
+ from .. import ext
152
+ try:
153
+ mod = ext.load(ext_name)
154
+ except KeyError as e:
155
+ raise ConfigError(str(e)) from None
156
+ if hasattr(mod, "technique_blocks"):
157
+ text = mod.technique_blocks()[block]
158
+ else:
159
+ text = (Path(mod.__file__).parent / "configs" / "tech" / f"{block}.toml").read_text()
160
+ source = {"source": ext_name, "version": getattr(mod, "__version__", None)}
161
+ else:
162
+ p = root / "tech" / f"{name}.toml"
163
+ if not p.exists():
164
+ raise ConfigError(f"unknown technique block {name!r} (no {p})")
165
+ text = p.read_text()
166
+ source = {"source": "public", "path": f"tech/{name}.toml"}
167
+ blk = tomllib.loads(text)
168
+ unknown = set(blk) - BLOCK_KEYS
169
+ if unknown:
170
+ raise ConfigError(f"technique {name}: unknown keys {sorted(unknown)}")
171
+ if blk.get("name", name.split(".")[-1]) != name.split(".")[-1]:
172
+ raise ConfigError(f"technique {name}: file declares name {blk.get('name')!r}")
173
+ source["sha256"] = hashlib.sha256(text.encode()).hexdigest()
174
+ return blk, source
175
+
176
+
177
+ def _subst(v, params, name):
178
+ if isinstance(v, str) and v.startswith("{") and v.endswith("}") and v[1:-1] in params:
179
+ return params[v[1:-1]]
180
+ if isinstance(v, str) and "{" in v:
181
+ raise ConfigError(f"technique {name}: cannot substitute {v!r}")
182
+ return v
183
+
184
+
185
+ def resolve(path=None, overrides=(), extensions=True, data=None):
186
+ """Resolve a config file (or an already parsed dict `data`) with overrides; returns Resolved."""
187
+ if data is not None:
188
+ chain = [(Path("<data>"), data)]
189
+ root = configs_root(None)
190
+ else:
191
+ chain = read_chain(path)
192
+ root = configs_root(chain[-1][0].parent)
193
+ ovr = [parse_override(o) if isinstance(o, str) else tuple(o) for o in overrides]
194
+
195
+ family = None
196
+ for _, d in chain:
197
+ family = d.get("task", {}).get("family", family)
198
+ for k, v in ovr:
199
+ if k == "task.family":
200
+ family = v
201
+ if family is None:
202
+ raise ConfigError("no task family: set [task] family")
203
+ task_cls, classes = section_classes(family)
204
+ sch = full_schema(classes)
205
+ values, layers = {}, {}
206
+
207
+ def put(key, value, layer):
208
+ if key not in sch:
209
+ raise ConfigError(f"{layer}: unknown key {key!r}")
210
+ values[key] = coerce(sch[key], value)
211
+ layers[key] = layer
212
+
213
+ for k, info in sch.items(): # 1 + 2 (task.* defaults are the family's Config defaults)
214
+ values[k] = info.default
215
+ layers[k] = f"family:{family}" if k.startswith("task.") else "default"
216
+ for k, v in getattr(task_cls, "defaults", {}).items():
217
+ put(k, v, f"family:{family}")
218
+
219
+ names = [] # 3
220
+ for p, d in chain:
221
+ for n in d.get("techniques", []):
222
+ if n in names:
223
+ raise ConfigError(f"{p}: technique {n!r} listed twice")
224
+ names.append(n)
225
+ blocks = {n: load_block(n, root, extensions) for n in names}
226
+ for n, (blk, _) in blocks.items():
227
+ for r in blk.get("requires", []):
228
+ if r not in names:
229
+ raise ConfigError(f"technique {n} requires {r}")
230
+ for c in blk.get("conflicts", []):
231
+ if c in names:
232
+ raise ConfigError(f"technique {n} conflicts with {c}")
233
+ tech_ovr = {}
234
+ for p, d in chain:
235
+ for n, t in d.get("tech", {}).items():
236
+ if n not in names:
237
+ raise ConfigError(f"{p}: [tech.{n}] for a technique that is not listed")
238
+ tech_ovr.setdefault(n, {}).update(t)
239
+ set_by, tech_records = {}, []
240
+ for n in names:
241
+ blk, source = blocks[n]
242
+ params = dict(blk.get("params", {}))
243
+ for k, v in blk.get("defaults", {}).get(family, {}).items():
244
+ if k not in params:
245
+ raise ConfigError(f"technique {n}: [defaults.{family}] sets unknown parameter {k!r}")
246
+ params[k] = v
247
+ for k, v in tech_ovr.get(n, {}).items():
248
+ if k not in params:
249
+ raise ConfigError(f"[tech.{n}]: unknown parameter {k!r} (parameters: {sorted(params)})")
250
+ params[k] = v
251
+ for key, v in blk.get("sets", {}).items():
252
+ prev = set_by.get(key)
253
+ if prev is not None and prev not in blk.get("overrides", []):
254
+ raise ConfigError(f"techniques {prev} and {n} both set {key}")
255
+ put(key, _subst(v, params, n), f"tech:{n}")
256
+ set_by[key] = n
257
+ tech_records.append({"name": n, **source, "params": params})
258
+
259
+ for i, (p, d) in enumerate(chain): # 4 + 5
260
+ layer = "config" if i == len(chain) - 1 else f"base:{p.name}"
261
+ for sec in SECTIONS:
262
+ for k, v in _flatten_table(d.get(sec, {}), sec + ".").items():
263
+ put(k, v, layer)
264
+ for k, v in ovr: # 6
265
+ put(k, v, "override")
266
+ if values["task.family"] != family:
267
+ raise ConfigError("task.family changed after the family defaults were applied")
268
+ unset = [k for k, v in values.items() if v is REQUIRED]
269
+ if unset:
270
+ raise ConfigError(f"options without a code default are not set: {', '.join(unset)} (set them in the config)")
271
+
272
+ secs = {sec: build(cls, {k[len(sec) + 1:]: v for k, v in values.items() if k.startswith(sec + ".")})
273
+ for sec, cls in classes.items()}
274
+ validate(secs)
275
+ cfg = Config(**secs, techniques=tuple(names))
276
+ return Resolved(cfg, values, layers, tech_records, [str(p) for p, _ in chain])
277
+
278
+
279
+ def validate(secs):
280
+ """Cross-field rules."""
281
+ lr = secs["learner"]
282
+ if lr.window.hoist_encoder and not getattr(secs["task"], "anchor_to_decoder", True):
283
+ raise ConfigError("learner.window.hoist_encoder needs a goal encoder whose input is the static goal "
284
+ "(task.anchor_to_decoder = true for tracking)")
285
+
286
+
287
+ def load_config(path, overrides=(), extensions=True):
288
+ """The validated Config of a TOML file."""
289
+ return resolve(path, overrides, extensions).config
290
+
291
+
292
+ def _toml_value(v):
293
+ if isinstance(v, bool):
294
+ return "true" if v else "false"
295
+ if isinstance(v, (int, float)):
296
+ return repr(v)
297
+ if isinstance(v, str):
298
+ return json.dumps(v)
299
+ if isinstance(v, (list, tuple)):
300
+ return "[" + ", ".join(_toml_value(x) for x in v) + "]"
301
+ raise TypeError(type(v))
302
+
303
+
304
+ def dump_toml(values, header=""):
305
+ """A TOML document of {dotted key: value} (a resolved config: loadable with no techniques)."""
306
+ tables = {}
307
+ for k, v in values.items():
308
+ t, leaf = k.rsplit(".", 1)
309
+ tables.setdefault(t, {})[leaf] = v
310
+ lines = [f"# {line}" for line in header.splitlines()] + ["techniques = []", ""]
311
+ for t in sorted(tables, key=lambda s: (s.split(".")[0] not in SECTIONS, SECTIONS.index(s.split(".")[0])
312
+ if s.split(".")[0] in SECTIONS else 99, s)):
313
+ lines.append(f"[{t}]")
314
+ lines += [f"{leaf} = {_toml_value(v)}" for leaf, v in tables[t].items()]
315
+ lines.append("")
316
+ return "\n".join(lines)
317
+
318
+
319
+ def write_record(res, out_dir):
320
+ """config.resolved.toml (loadable as a config) and config.json (values, techniques, the layer of each key)."""
321
+ out_dir = Path(out_dir)
322
+ out_dir.mkdir(parents=True, exist_ok=True)
323
+ from .. import __version__
324
+ vals = {k: v for k, v in res.values.items() if k != "run.out"}
325
+ (out_dir / "config.resolved.toml").write_text(dump_toml(vals, f"resolved config, nablapo {__version__}"))
326
+ rec = {"nablapo": __version__, "values": {k: list(v) if isinstance(v, tuple) else v for k, v in res.values.items()},
327
+ "techniques": res.techniques, "layers": res.layers,
328
+ "files": [os.path.basename(f) for f in res.files]}
329
+ (out_dir / "config.json").write_text(json.dumps(rec, indent=1))
330
+ return rec
331
+
332
+
333
+ def as_flat(cfg):
334
+ out = {}
335
+ for sec in SECTIONS:
336
+ out.update(flatten(getattr(cfg, sec), sec + "."))
337
+ return out
338
+
339
+
340
+ __all__ = ["Config", "Resolved", "resolve", "load_config", "write_record", "dump_toml", "ConfigError", "as_flat",
341
+ "config_path", "shipped_configs"]