ajax-rl 0.4.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 (150) hide show
  1. ajax/__init__.py +43 -0
  2. ajax/_compile_cache.py +148 -0
  3. ajax/agents/APG/APG.py +262 -0
  4. ajax/agents/APG/__init__.py +5 -0
  5. ajax/agents/APG/curriculum.py +91 -0
  6. ajax/agents/APG/networks.py +168 -0
  7. ajax/agents/APG/state.py +28 -0
  8. ajax/agents/APG/train_APG.py +467 -0
  9. ajax/agents/APO/APO.py +190 -0
  10. ajax/agents/APO/__init__.py +0 -0
  11. ajax/agents/APO/state.py +35 -0
  12. ajax/agents/APO/train_APO.py +437 -0
  13. ajax/agents/ASAC/ASAC.py +198 -0
  14. ajax/agents/ASAC/__init__.py +0 -0
  15. ajax/agents/ASAC/state.py +29 -0
  16. ajax/agents/ASAC/train_ASAC.py +491 -0
  17. ajax/agents/ASAC/utils.py +20 -0
  18. ajax/agents/AVG/AVG.py +152 -0
  19. ajax/agents/AVG/__init__.py +0 -0
  20. ajax/agents/AVG/state.py +39 -0
  21. ajax/agents/AVG/train_AVG.py +463 -0
  22. ajax/agents/AVG/utils.py +49 -0
  23. ajax/agents/DAgger/DAgger.py +104 -0
  24. ajax/agents/DAgger/__init__.py +0 -0
  25. ajax/agents/DAgger/state.py +22 -0
  26. ajax/agents/DAgger/train_DAgger.py +289 -0
  27. ajax/agents/DQN/DQN.py +150 -0
  28. ajax/agents/DQN/__init__.py +0 -0
  29. ajax/agents/DQN/networks.py +208 -0
  30. ajax/agents/DQN/state.py +29 -0
  31. ajax/agents/DQN/train_DQN.py +550 -0
  32. ajax/agents/DreamerV3/DreamerV3.py +383 -0
  33. ajax/agents/DreamerV3/__init__.py +21 -0
  34. ajax/agents/DreamerV3/actor_critic.py +288 -0
  35. ajax/agents/DreamerV3/distributions.py +297 -0
  36. ajax/agents/DreamerV3/learner.py +554 -0
  37. ajax/agents/DreamerV3/networks.py +503 -0
  38. ajax/agents/DreamerV3/optim.py +158 -0
  39. ajax/agents/DreamerV3/replay.py +402 -0
  40. ajax/agents/DreamerV3/state.py +382 -0
  41. ajax/agents/DreamerV3/train_DreamerV3.py +638 -0
  42. ajax/agents/DreamerV3/world_model.py +257 -0
  43. ajax/agents/IQL/IQL.py +130 -0
  44. ajax/agents/IQL/__init__.py +0 -0
  45. ajax/agents/IQL/state.py +20 -0
  46. ajax/agents/IQL/train_IQL.py +272 -0
  47. ajax/agents/PPO/PPO.py +216 -0
  48. ajax/agents/PPO/__init__.py +0 -0
  49. ajax/agents/PPO/core.py +161 -0
  50. ajax/agents/PPO/state.py +55 -0
  51. ajax/agents/PPO/train_PPO.py +919 -0
  52. ajax/agents/PPO/utils.py +121 -0
  53. ajax/agents/PQN/PQN.py +135 -0
  54. ajax/agents/PQN/__init__.py +0 -0
  55. ajax/agents/PQN/networks.py +76 -0
  56. ajax/agents/PQN/state.py +27 -0
  57. ajax/agents/PQN/train_PQN.py +246 -0
  58. ajax/agents/PQN/utils.py +51 -0
  59. ajax/agents/REDQ/REDQ.py +229 -0
  60. ajax/agents/REDQ/__init__.py +0 -0
  61. ajax/agents/REDQ/state.py +17 -0
  62. ajax/agents/REDQ/train_REDQ.py +460 -0
  63. ajax/agents/SAC/SAC.py +314 -0
  64. ajax/agents/SAC/__init__.py +0 -0
  65. ajax/agents/SAC/action_pipeline.py +361 -0
  66. ajax/agents/SAC/core.py +340 -0
  67. ajax/agents/SAC/expert.py +66 -0
  68. ajax/agents/SAC/state.py +36 -0
  69. ajax/agents/SAC/train_SAC.py +895 -0
  70. ajax/agents/TD3/TD3.py +180 -0
  71. ajax/agents/TD3/__init__.py +0 -0
  72. ajax/agents/TD3/networks.py +135 -0
  73. ajax/agents/TD3/state.py +22 -0
  74. ajax/agents/TD3/train_TD3.py +503 -0
  75. ajax/agents/TDMPC2/TDMPC2.py +448 -0
  76. ajax/agents/TDMPC2/TDMPC2MultiTask.py +543 -0
  77. ajax/agents/TDMPC2/__init__.py +18 -0
  78. ajax/agents/TDMPC2/buffer.py +624 -0
  79. ajax/agents/TDMPC2/core.py +920 -0
  80. ajax/agents/TDMPC2/dataset.py +494 -0
  81. ajax/agents/TDMPC2/multitask.py +290 -0
  82. ajax/agents/TDMPC2/networks.py +401 -0
  83. ajax/agents/TDMPC2/planner.py +567 -0
  84. ajax/agents/TDMPC2/state.py +294 -0
  85. ajax/agents/TDMPC2/train_TDMPC2.py +618 -0
  86. ajax/agents/TDMPC2/train_TDMPC2MultiTask.py +292 -0
  87. ajax/agents/UDRL/UDRL.py +100 -0
  88. ajax/agents/UDRL/__init__.py +0 -0
  89. ajax/agents/UDRL/buffer.py +233 -0
  90. ajax/agents/UDRL/state.py +62 -0
  91. ajax/agents/UDRL/train_UDRL.py +593 -0
  92. ajax/agents/UDRL/utils.py +56 -0
  93. ajax/agents/__init__.py +0 -0
  94. ajax/agents/base.py +570 -0
  95. ajax/agents/cloning.py +211 -0
  96. ajax/agents/loop.py +822 -0
  97. ajax/agents/recurrent.py +442 -0
  98. ajax/buffers/__init__.py +0 -0
  99. ajax/buffers/dataset.py +295 -0
  100. ajax/buffers/utils.py +219 -0
  101. ajax/checkpoint.py +485 -0
  102. ajax/compare.py +420 -0
  103. ajax/deprecation.py +19 -0
  104. ajax/distributional.py +265 -0
  105. ajax/environments/__init__.py +0 -0
  106. ajax/environments/create.py +474 -0
  107. ajax/environments/differentiable.py +172 -0
  108. ajax/environments/interaction.py +1236 -0
  109. ajax/environments/model_reference.py +298 -0
  110. ajax/environments/obs_norm.py +86 -0
  111. ajax/environments/pid_terms.py +188 -0
  112. ajax/environments/row_collector.py +600 -0
  113. ajax/environments/system_class.py +163 -0
  114. ajax/environments/utils.py +453 -0
  115. ajax/evaluate.py +845 -0
  116. ajax/extensions/__init__.py +15 -0
  117. ajax/extensions/adversarial.py +126 -0
  118. ajax/extensions/base.py +712 -0
  119. ajax/extensions/capabilities.py +186 -0
  120. ajax/extensions/ensemble.py +82 -0
  121. ajax/extensions/expert.py +669 -0
  122. ajax/extensions/exploration.py +452 -0
  123. ajax/extensions/instrumentation.py +541 -0
  124. ajax/extensions/offline.py +203 -0
  125. ajax/extensions/pretrain.py +1072 -0
  126. ajax/extensions/target_mods.py +527 -0
  127. ajax/log.py +360 -0
  128. ajax/logging/__init__.py +0 -0
  129. ajax/logging/wandb_logging.py +352 -0
  130. ajax/modules/__init__.py +1 -0
  131. ajax/modules/pid_actor.py +194 -0
  132. ajax/modules/pid_head.py +128 -0
  133. ajax/networks/__init__.py +0 -0
  134. ajax/networks/blocks.py +184 -0
  135. ajax/networks/distributions.py +144 -0
  136. ajax/networks/memory.py +634 -0
  137. ajax/networks/networks.py +882 -0
  138. ajax/networks/utils.py +331 -0
  139. ajax/normalizers.py +155 -0
  140. ajax/perf_utils.py +177 -0
  141. ajax/reproduction.py +37 -0
  142. ajax/schedule.py +39 -0
  143. ajax/state.py +344 -0
  144. ajax/types.py +52 -0
  145. ajax/utils.py +99 -0
  146. ajax/wrappers.py +907 -0
  147. ajax_rl-0.4.0.dist-info/METADATA +365 -0
  148. ajax_rl-0.4.0.dist-info/RECORD +150 -0
  149. ajax_rl-0.4.0.dist-info/WHEEL +4 -0
  150. ajax_rl-0.4.0.dist-info/licenses/LICENSE +21 -0
ajax/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ from importlib.metadata import version
2
+
3
+ from ajax import _compile_cache
4
+
5
+ # Before the agent imports below, so every compile they trigger is cached.
6
+ _compile_cache.configure()
7
+
8
+ from ajax.agents.APG.APG import APG # noqa: E402
9
+ from ajax.agents.APO.APO import APO # noqa: E402
10
+ from ajax.agents.ASAC.ASAC import ASAC # noqa: E402
11
+ from ajax.agents.AVG.AVG import AVG # noqa: E402
12
+ from ajax.agents.DAgger.DAgger import DAgger # noqa: E402
13
+ from ajax.agents.DQN.DQN import DQN # noqa: E402
14
+ from ajax.agents.DreamerV3.DreamerV3 import DreamerV3 # noqa: E402
15
+ from ajax.agents.IQL.IQL import IQL # noqa: E402
16
+ from ajax.agents.PPO.PPO import PPO # noqa: E402
17
+ from ajax.agents.PQN.PQN import PQN # noqa: E402
18
+ from ajax.agents.REDQ.REDQ import REDQ # noqa: E402
19
+ from ajax.agents.SAC.SAC import SAC # noqa: E402
20
+ from ajax.agents.TD3.TD3 import TD3 # noqa: E402
21
+ from ajax.agents.TDMPC2.TDMPC2 import TDMPC2 # noqa: E402
22
+ from ajax.agents.TDMPC2.TDMPC2MultiTask import TDMPC2MultiTask # noqa: E402
23
+ from ajax.agents.UDRL.UDRL import UDRL # noqa: E402
24
+
25
+ __all__ = [
26
+ "APG",
27
+ "APO",
28
+ "ASAC",
29
+ "AVG",
30
+ "DQN",
31
+ "IQL",
32
+ "PPO",
33
+ "PQN",
34
+ "REDQ",
35
+ "SAC",
36
+ "TD3",
37
+ "TDMPC2",
38
+ "UDRL",
39
+ "DAgger",
40
+ "DreamerV3",
41
+ "TDMPC2MultiTask",
42
+ ]
43
+ __version__ = version("ajax-rl")
ajax/_compile_cache.py ADDED
@@ -0,0 +1,148 @@
1
+ """Persistent JAX compile cache, one subdirectory per host fingerprint.
2
+
3
+ HPO sweeps and any workflow that re-launches Ajax in a fresh Python
4
+ process pay the JIT compile cost once per launch. Pointing JAX at a
5
+ persistent cache directory lets later launches with identical shapes and
6
+ code load the compiled executable instead of compiling it again.
7
+
8
+ Behaviour:
9
+ * Root directory: ``~/.cache/ajax/jax_compile_cache``, overridden by
10
+ ``AJAX_JAX_COMPILE_CACHE_DIR``.
11
+ * Entries live in ``<root>/<fingerprint hash>``. The fingerprint is the
12
+ CPU model (plus the CPU feature flags on Linux), the machine
13
+ architecture, and the Python, JAX and jaxlib versions.
14
+ * ``AJAX_NO_COMPILE_CACHE=1`` disables the cache and leaves the disk
15
+ untouched.
16
+ * Nothing bounds its size on import. :func:`prune` trims a root to a
17
+ size, least recently used entries first (CI runs it once per job).
18
+
19
+ Why a fingerprint: JAX's cache key covers the HLO, the JAX/jaxlib
20
+ versions and the device kind, but on CPU not the instruction-set
21
+ features. An entry built on another CPU loads with "Target machine
22
+ feature ... could lead to SIGILL" warnings and falls back to a fresh
23
+ compile, which once looked like a multi-hour stall. Keying the
24
+ subdirectory by CPU keeps such entries apart.
25
+
26
+ Why a subdirectory rather than a wipe on mismatch: the previous design
27
+ recorded one fingerprint in the cache root and deleted the whole cache
28
+ whenever it changed. The hostname was part of it, so switching networks
29
+ wiped the cache, and every project importing Ajax from an environment
30
+ with another JAX or Python version wiped it for all the others. Keeping
31
+ one subdirectory per fingerprint, never deleted, lets each environment
32
+ keep its own warm cache.
33
+
34
+ JAX never writes programs that contain host callbacks to this cache
35
+ (``jax._src.compiler._cache_write``), so runs that log through
36
+ ``jax.debug.callback`` recompile on every launch.
37
+ """
38
+
39
+ import hashlib
40
+ import os
41
+ import platform
42
+ import subprocess
43
+ import sys
44
+
45
+ _TRUTHY = ("1", "true", "yes")
46
+
47
+
48
+ def _cpu_description() -> str:
49
+ """The CPU model, plus its feature flags where the OS reports them.
50
+
51
+ ``platform.processor()`` is not enough: it returns ``"arm"`` on every
52
+ Apple Silicon Mac and is often empty on Linux.
53
+ """
54
+ if sys.platform == "darwin":
55
+ try:
56
+ return subprocess.run(
57
+ ["sysctl", "-n", "machdep.cpu.brand_string"],
58
+ capture_output=True,
59
+ text=True,
60
+ check=True,
61
+ timeout=5,
62
+ ).stdout.strip()
63
+ except (OSError, subprocess.SubprocessError):
64
+ pass
65
+ model, flags = "", ""
66
+ try:
67
+ with open("/proc/cpuinfo") as fh:
68
+ for line in fh:
69
+ key, _, value = line.partition(":")
70
+ key = key.strip().lower()
71
+ if key == "model name" and not model:
72
+ model = value.strip()
73
+ elif key in ("flags", "features") and not flags:
74
+ flags = hashlib.sha256(value.strip().encode()).hexdigest()[:12]
75
+ if model and flags:
76
+ break
77
+ except OSError:
78
+ pass
79
+ return f"{model} flags={flags}" if model or flags else platform.processor()
80
+
81
+
82
+ def host_fingerprint() -> str:
83
+ """What must match for a cached CPU executable to be safe to load.
84
+
85
+ Deliberately excludes the hostname: it changes with the network on
86
+ macOS and says nothing about the CPU.
87
+ """
88
+ from importlib.metadata import version
89
+
90
+ py = f"{sys.version_info.major}.{sys.version_info.minor}"
91
+ return (
92
+ f"cpu={_cpu_description()}|arch={platform.machine()}|py={py}"
93
+ f"|jax={version('jax')}|jaxlib={version('jaxlib')}"
94
+ )
95
+
96
+
97
+ def cache_dir_for(root: str, fingerprint: str) -> str:
98
+ """The subdirectory of ``root`` that holds this fingerprint's entries."""
99
+ return os.path.join(root, hashlib.sha256(fingerprint.encode()).hexdigest()[:16])
100
+
101
+
102
+ def configure() -> None:
103
+ """Point JAX at this host's cache subdirectory (see the module docstring)."""
104
+ if os.environ.get("AJAX_NO_COMPILE_CACHE", "").lower() in _TRUTHY:
105
+ return
106
+
107
+ import jax
108
+
109
+ root = os.environ.get("AJAX_JAX_COMPILE_CACHE_DIR") or os.path.join(
110
+ os.path.expanduser("~"), ".cache", "ajax", "jax_compile_cache"
111
+ )
112
+ try:
113
+ cache_dir = cache_dir_for(root, host_fingerprint())
114
+ os.makedirs(cache_dir, exist_ok=True)
115
+ jax.config.update("jax_compilation_cache_dir", cache_dir)
116
+ # Cache every compile. JAX's default skips compiles under one
117
+ # second, which are cheap to store and add up over a sweep.
118
+ jax.config.update("jax_persistent_cache_min_compile_time_secs", 0.0)
119
+ jax.config.update("jax_persistent_cache_min_entry_size_bytes", 0)
120
+ except Exception:
121
+ # A read-only home or an unusual filesystem must not block
122
+ # importing Ajax; run without the cache instead.
123
+ pass
124
+
125
+
126
+ def prune(root: str, max_bytes: int) -> int:
127
+ """Delete the least recently used files under ``root`` until those left
128
+ total at most ``max_bytes``; return the bytes deleted.
129
+
130
+ JAX's own bound (``jax_compilation_cache_max_size``) lists and stats
131
+ every entry under a file lock on every write, which doubled the CI test
132
+ jobs (Ajax caches every compile); this runs once, when called. A file's
133
+ last use is its last write or, where the filesystem records it, read.
134
+ """
135
+ files = []
136
+ for directory, _, names in os.walk(root):
137
+ for name in names:
138
+ path = os.path.join(directory, name)
139
+ stat = os.stat(path)
140
+ files.append((max(stat.st_atime, stat.st_mtime), stat.st_size, path))
141
+ excess = sum(size for _, size, _ in files) - max_bytes
142
+ deleted = 0
143
+ for _, size, path in sorted(files):
144
+ if deleted >= excess:
145
+ break
146
+ os.remove(path)
147
+ deleted += size
148
+ return deleted
ajax/agents/APG/APG.py ADDED
@@ -0,0 +1,262 @@
1
+ """Analytic Policy Gradient (APG): train a deterministic controller by
2
+ back-propagating the closed-loop return through a differentiable simulator.
3
+
4
+ The general agent trains any :class:`~ajax.agents.APG.networks.Controller`
5
+ (MLP, or memory-augmented via ``memory=MemoryConfig(...)``, optionally
6
+ closed by a learnable PID layer) on a class of systems
7
+ (:mod:`ajax.environments.system_class`) by BPTT over a fixed horizon. No
8
+ critic, no replay buffer, no exploration noise: the environment must
9
+ expose transition gradients (gymnax ``with_transition_gradients``).
10
+
11
+ :meth:`APG.contextual_controller` is the configuration of Busetto,
12
+ Breschi, Forgione, Piga and Formentin, "One controller to rule them all"
13
+ (arXiv:2411.06482, 2024): a decoder-only transformer over the tracking
14
+ history with a PID output layer, trained on the model-reference matching
15
+ cost over a system class, with AdamW and a warmup-cosine schedule. Pair
16
+ it with :class:`~ajax.environments.model_reference.ModelReferenceWrapper`
17
+ for the task and :func:`~ajax.agents.APG.curriculum.train_curriculum`
18
+ for the paper's staged training.
19
+ """
20
+
21
+ from collections.abc import Sequence
22
+ from typing import Any, Callable, Optional, Union
23
+
24
+ from gymnax import EnvParams
25
+
26
+ from ajax.agents.APG.networks import PIDHeadConfig
27
+ from ajax.agents.APG.state import APGConfig
28
+ from ajax.agents.APG.train_APG import make_train
29
+ from ajax.agents.base import ActorCritic, run_config
30
+ from ajax.agents.loop import LOOP_PHASES
31
+ from ajax.environments.differentiable import with_transition_gradients
32
+ from ajax.environments.system_class import SystemClass
33
+ from ajax.environments.utils import check_env_is_gymnax
34
+ from ajax.extensions.base import Extension
35
+ from ajax.networks.memory import (
36
+ MemoryConfig,
37
+ parse_memory_config,
38
+ with_default_init,
39
+ )
40
+ from ajax.state import OptimizerConfig
41
+ from ajax.types import EnvType
42
+
43
+ # Identity at initialisation (K_P=1, K_I=K_D=0). The reference code
44
+ # initialises all three coefficients to 1.0 on an unbounded output; under
45
+ # Ajax's tanh-bounded action that init trained markedly worse (pendulum
46
+ # tracking, fresh-system M-RMSE 0.33 vs 0.25 for the identity init). These
47
+ # runs, and the deviations of contextual_controller, predate the map of
48
+ # actions onto the env's bounds: the torque was capped at +-1 of +-2.
49
+ _DEFAULT_PID = PIDHeadConfig()
50
+
51
+ # A transformer memory starts as the contextual controller's reference code
52
+ # starts its GPT: normal(0.02) kernels, the residual projections at
53
+ # 0.02/sqrt(2 n_layer), zero biases (buswayne/in-context-controller @7eb094c,
54
+ # transformer_onestep.py:162-166, :189-195). Its other kinds have no
55
+ # reference and keep flax's.
56
+ APG_MEMORY_INITS = {"transformer": "nanogpt"}
57
+
58
+
59
+ class APG(ActorCritic):
60
+ name: str = "APG"
61
+ capabilities: frozenset = frozenset("actor obs_networks".split())
62
+ supported_extension_phases: frozenset = LOOP_PHASES | {"actor_loss"}
63
+ pretrain_context: frozenset = frozenset()
64
+ # Its rollout traces the env params (a system class's samples).
65
+ supports_batched_env_params: bool = True
66
+ supports_memory: bool = True
67
+ make_train = staticmethod(make_train)
68
+
69
+ def __init__(
70
+ self,
71
+ env_id: str | EnvType,
72
+ n_envs: int = 8,
73
+ horizon: int = 100,
74
+ learning_rate: float = 5e-4,
75
+ weight_decay: float = 0.0,
76
+ beta_1: float = 0.9,
77
+ beta_2: float = 0.999,
78
+ lr_schedule: Optional[str] = None,
79
+ warmup_steps: int = 0,
80
+ lr_end_fraction: float = 0.1,
81
+ max_grad_norm: Optional[float] = 1.0,
82
+ actor_architecture: Sequence[str] = ("128", "relu", "128", "relu"),
83
+ memory: Optional[Union[MemoryConfig, dict]] = None,
84
+ pid: Optional[PIDHeadConfig] = None,
85
+ squash: bool = True,
86
+ system_class: Optional[SystemClass] = None,
87
+ env_params: Optional[EnvParams] = None,
88
+ episode_length: Optional[int] = None,
89
+ controller_factory: Optional[Callable[..., Any]] = None,
90
+ extensions: Sequence[Extension] = (),
91
+ # Simulator steps per agent step on brax / playground envs
92
+ # (ActorCritic).
93
+ action_repeat: int = 1,
94
+ ) -> None:
95
+ """
96
+ Args:
97
+ env_id: gymnax env id or prebuilt gymnax env (e.g. a
98
+ ``ModelReferenceWrapper``). Must support transition
99
+ gradients.
100
+ n_envs: systems sampled (and simulated in parallel) per update.
101
+ horizon: closed-loop rollout length differentiated through.
102
+ learning_rate: AdamW step size.
103
+ weight_decay: AdamW's decoupled weight decay, multiplied by the
104
+ (scheduled) learning rate (``OptimizerConfig.weight_decay``,
105
+ every agent's); ``0`` is plain Adam.
106
+ beta_1: AdamW first-moment decay.
107
+ beta_2: AdamW second-moment decay.
108
+ lr_schedule: ``None`` (constant) or ``"warmup_cosine"``
109
+ (linear warmup over ``warmup_steps`` updates, cosine decay
110
+ to ``learning_rate * lr_end_fraction`` at the call's last
111
+ update). When ``train`` keeps the optimizer
112
+ (``reset_optimizer_on_resume=False``), a resumed call runs
113
+ the schedule of the call that built it, the run's first or
114
+ a checkpoint's skeleton: given that flag, that call decays
115
+ to the run's last update, at its ``total_timesteps``.
116
+ max_grad_norm: global-norm gradient clipping, on by default:
117
+ BPTT over 100 steps of a nonlinear plant across a system
118
+ class diverged without it in our runs (the loss rose 1.2 ->
119
+ 1.7 M-RMSE within a stage) and was stable with it. ``None``
120
+ disables, as :meth:`contextual_controller` does by default
121
+ (the reference code does not clip).
122
+ actor_architecture: MLP encoder in front of the memory/output;
123
+ ``()`` for a linear embedding only (the paper's choice).
124
+ memory: :class:`MemoryConfig` (or dict) for a memory-augmented
125
+ controller; ``None`` for a memoryless one.
126
+ pid: :class:`PIDHeadConfig` to close the controller with a
127
+ learnable PID layer; ``None`` for a plain output.
128
+ squash: tanh-bound actions to ``[-1, 1]`` (Ajax convention).
129
+ Squashed or not, ``[-1, 1]`` is mapped onto the env's
130
+ bounds (an unsquashed action is clipped there first).
131
+ system_class: distribution over ``EnvParams`` to train across;
132
+ ``None`` trains on the env's own params only.
133
+ controller_factory: optional builder of a custom policy module,
134
+ called with ``env_args``, ``network_args``, ``action_dim``,
135
+ ``pid`` and ``squash`` keywords; must honour the
136
+ :class:`~ajax.agents.APG.networks.Controller` contract
137
+ (``stateful``, ``initialize_carry``, call convention). Lets
138
+ downstream projects plug their own architectures into the
139
+ same trainer without touching Ajax.
140
+ extensions: composable research features (see
141
+ :mod:`ajax.extensions`).
142
+ """
143
+ # Resolved before run_config, so the logged config holds what runs.
144
+ memory = with_default_init(parse_memory_config(memory), APG_MEMORY_INITS)
145
+ self.config = run_config(locals(), self.name)
146
+
147
+ # No critic; the actor's optimizer is built below.
148
+ super().__init__(
149
+ env_id=env_id,
150
+ n_envs=n_envs,
151
+ actor_architecture=tuple(actor_architecture),
152
+ env_params=env_params,
153
+ memory=memory,
154
+ episode_length=episode_length,
155
+ action_repeat=action_repeat,
156
+ extensions=extensions,
157
+ )
158
+ if not check_env_is_gymnax(self.env_args.env):
159
+ raise ValueError("APG needs a gymnax env (differentiable transitions).")
160
+ self.env_args = self.env_args.replace(
161
+ env=with_transition_gradients(self.env_args.env)
162
+ )
163
+ # Adam's eps is torch's default, 1e-8, which the reference's AdamW
164
+ # keeps (buswayne/in-context-controller at 7eb094ce17:
165
+ # transformer_onestep_CL.py:86); Ajax's shared default is 1e-5.
166
+ self.actor_optimizer_args = OptimizerConfig(
167
+ learning_rate=learning_rate,
168
+ max_grad_norm=max_grad_norm,
169
+ beta_1=beta_1,
170
+ beta_2=beta_2,
171
+ eps=1e-8,
172
+ weight_decay=weight_decay,
173
+ )
174
+ self.agent_config: APGConfig = APGConfig(horizon=horizon)
175
+ self.pid = pid
176
+ self.squash = squash
177
+ self.system_class = system_class
178
+ self.controller_factory = controller_factory
179
+ self.train_kwargs = {
180
+ "system_class": system_class,
181
+ "pid": pid,
182
+ "squash": squash,
183
+ "lr_schedule": lr_schedule,
184
+ "warmup_steps": warmup_steps,
185
+ "lr_end_fraction": lr_end_fraction,
186
+ "controller_factory": controller_factory,
187
+ }
188
+
189
+ @classmethod
190
+ def contextual_controller(
191
+ cls,
192
+ env_id: str | EnvType,
193
+ system_class: Optional[SystemClass] = None,
194
+ n_envs: int = 1,
195
+ horizon: int = 100,
196
+ n_layers: int = 8,
197
+ n_heads: int = 4,
198
+ d_model: int = 128,
199
+ context: int = 100,
200
+ final_norm: bool = True,
201
+ learning_rate: float = 5e-4,
202
+ weight_decay: float = 0.0,
203
+ warmup_steps: int = 5000,
204
+ pid: Optional[PIDHeadConfig] = _DEFAULT_PID,
205
+ beta_2: float = 0.95,
206
+ lr_schedule: Optional[str] = "warmup_cosine",
207
+ max_grad_norm: Optional[float] = None,
208
+ actor_architecture: Sequence[str] = (),
209
+ **kwargs: Any,
210
+ ) -> "APG":
211
+ """The in-context controller of Busetto et al. 2024.
212
+
213
+ Defaults follow the paper (Table 2: 8 layers, 4 heads, context 100,
214
+ width 128, ``b=1`` system per iteration, ``N=100`` horizon) and the
215
+ reference code (AdamW betas (0.9, 0.95), eps 1e-8, 5k-step warmup
216
+ then cosine decay to ``lr/10``, no gradient clipping). Deviations,
217
+ each backed by runs on the pendulum tracking test bed: actions are
218
+ tanh-bounded (Ajax convention; the reference leaves ``u``
219
+ unbounded), and the PID head starts at the identity rather than
220
+ the reference's all-ones coefficients (see ``_DEFAULT_PID``). Not
221
+ reproduced: the reference (buswayne/in-context-controller at
222
+ 7eb094ce17) sets its scheduled rate on its first parameter group
223
+ only (``train_onestep_lin_CL.py:241``), so its LayerNorm weights
224
+ keep the peak rate, and decays only tensors of two or more
225
+ dimensions (``transformer_onestep_CL.py:72-77``; moot at
226
+ ``weight_decay=0``). Not backed by runs: the LayerNorms, ``ln_f``
227
+ included, keep a bias and flax's epsilon 1e-6, where the reference's
228
+ have no bias and epsilon 1e-5 (buswayne/in-context-controller at
229
+ 7eb094ce17: ``transformer_onestep.py:33`` calls ``F.layer_norm``
230
+ with 1e-5, ``:156`` builds ``ln_f = LayerNorm(n_embd,
231
+ bias=config.bias)``, and ``train_onestep_lin_CL.py:103`` defaults
232
+ ``--bias`` to False). The transformer starts as the reference's
233
+ GPT does (``APG_MEMORY_INITS``). ``final_norm=False`` rebuilds the transformer
234
+ without its final LayerNorm, only to restore a checkpoint saved
235
+ before it (see :class:`~ajax.networks.memory.MemoryConfig`); an
236
+ expand-then-contract shim (CLAUDE.md, refactoring rule 10), it is
237
+ removed together with ``MemoryConfig.final_norm``. Extra kwargs go
238
+ to :class:`APG`.
239
+ """
240
+ return cls(
241
+ env_id,
242
+ n_envs=n_envs,
243
+ horizon=horizon,
244
+ learning_rate=learning_rate,
245
+ weight_decay=weight_decay,
246
+ beta_2=beta_2,
247
+ lr_schedule=lr_schedule,
248
+ warmup_steps=warmup_steps,
249
+ max_grad_norm=max_grad_norm,
250
+ actor_architecture=actor_architecture,
251
+ memory=MemoryConfig(
252
+ kind="transformer",
253
+ hidden_size=d_model,
254
+ num_layers=n_layers,
255
+ num_heads=n_heads,
256
+ window=context,
257
+ final_norm=final_norm,
258
+ ),
259
+ pid=pid,
260
+ system_class=system_class,
261
+ **kwargs,
262
+ )
@@ -0,0 +1,5 @@
1
+ from ajax.agents.APG.APG import APG
2
+ from ajax.agents.APG.curriculum import CurriculumStage, train_curriculum
3
+ from ajax.agents.APG.networks import Controller, PIDHeadConfig
4
+
5
+ __all__ = ["APG", "Controller", "CurriculumStage", "PIDHeadConfig", "train_curriculum"]
@@ -0,0 +1,91 @@
1
+ """Curriculum training for APG: successive stages resumed from one another.
2
+
3
+ Busetto et al. 2024 (Algorithm 2) train the contextual controller in
4
+ stages of increasing diversity: a single system with a fixed reference,
5
+ then the system class, then systems and references, then everything
6
+ including initial conditions. Each stage is an :class:`APG` agent built
7
+ on its own environment / system class; :func:`train_curriculum` chains
8
+ them through Ajax's resume path, carrying the learned parameters over
9
+ and (by default) restarting the optimizer and its schedule per stage.
10
+
11
+ The paper trains each stage to a loss tolerance; Ajax's training loop is
12
+ a fixed-length scan, so each stage gets an explicit ``n_timesteps``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Any, Optional, Sequence
19
+
20
+ import jax
21
+ import jax.numpy as jnp
22
+
23
+ from ajax.agents.APG.APG import APG
24
+ from ajax.agents.APG.state import APGState
25
+ from ajax.agents.APG.train_APG import APGAuxiliaries
26
+ from ajax.logging.wandb_logging import LoggingConfig
27
+
28
+
29
+ @dataclass
30
+ class CurriculumStage:
31
+ agent: APG
32
+ n_timesteps: int
33
+ name: str = ""
34
+
35
+
36
+ def _check_compatible(first: APG, other: APG, name: str) -> None:
37
+ if other.env_args.n_envs != first.env_args.n_envs:
38
+ raise ValueError(
39
+ f"stage {name!r}: n_envs={other.env_args.n_envs} differs from the"
40
+ f" first stage's {first.env_args.n_envs}; the resumed state is"
41
+ " batched per env"
42
+ )
43
+ if other.network_args != first.network_args:
44
+ raise ValueError(
45
+ f"stage {name!r}: network configuration differs from the first"
46
+ " stage's; parameters cannot be carried over"
47
+ )
48
+ if (other.pid, other.squash) != (first.pid, first.squash):
49
+ raise ValueError(
50
+ f"stage {name!r}: controller head (pid / squash) differs from the"
51
+ " first stage's"
52
+ )
53
+
54
+
55
+ def train_curriculum(
56
+ stages: Sequence[CurriculumStage],
57
+ seed: int | Sequence[int] = 42,
58
+ num_episode_test: int = 10,
59
+ logging_config: Optional[LoggingConfig] = None,
60
+ reset_optimizer: bool = True,
61
+ ) -> list[tuple[APGState, APGAuxiliaries]]:
62
+ """Train ``stages`` in order, each resumed from the previous one.
63
+
64
+ Returns one ``(agent_state, aux)`` pair per stage (what ``train``
65
+ returns). ``reset_optimizer`` re-initialises the optimizer and its
66
+ learning-rate schedule at every stage boundary.
67
+ """
68
+ if not stages:
69
+ raise ValueError("train_curriculum needs at least one stage")
70
+ first = stages[0].agent
71
+ for stage in stages[1:]:
72
+ _check_compatible(first, stage.agent, stage.name)
73
+ results: list[tuple[APGState, APGAuxiliaries]] = []
74
+ state: Any = None
75
+ for stage in stages:
76
+ out: Any = stage.agent.train(
77
+ seed=seed,
78
+ n_timesteps=stage.n_timesteps,
79
+ num_episode_test=num_episode_test,
80
+ logging_config=logging_config,
81
+ initial_state=state,
82
+ reset_optimizer_on_resume=reset_optimizer,
83
+ )
84
+ # The resume path donates the incoming buffers; hand the next stage
85
+ # a copy so every returned stage state stays readable.
86
+ state = jax.tree.map(jnp.copy, out[0])
87
+ results.append(out)
88
+ return results
89
+
90
+
91
+ __all__ = ["CurriculumStage", "train_curriculum"]