Files
chenlin c32df70326
Checks / Layout, translation and Colab checks (push) Has been cancelled
Checks / Ruff (push) Has been cancelled
Checks / Framework tests (native backend, CPU) (push) Has been cancelled
Checks / Portable Rust controller (push) Has been cancelled
release: v0.1 generic robot training and application platform
2026-11-05 11:05:01 +08:00

91 lines
3.2 KiB
Python

"""Save earned curriculum levels alongside the policy and optimizer state."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from mjlab.tasks.velocity.rl import VelocityOnPolicyRunner
from .curriculum import CheckpointedLadder
if TYPE_CHECKING:
from mjlab.envs import ManagerBasedRlEnv
from mjlab.managers.curriculum_manager import CurriculumTermCfg
__all__ = ["CHECKPOINT_KEY", "CurriculumRunner", "curriculum_state", "ladders", "restore_curriculum"]
#: Where in a checkpoint's `infos` the ladders are kept.
CHECKPOINT_KEY = "curriculum"
def ladders(env: ManagerBasedRlEnv) -> list[tuple[str, CurriculumTermCfg]]:
"""`(term name, term cfg)` of every checkpointed ladder, in the manager's order.
The manager stores the live term instance in the config's `func` field.
"""
cm = getattr(env, "curriculum_manager", None)
names = getattr(cm, "_term_names", None) or ()
cfgs = getattr(cm, "_term_cfgs", None) or ()
return [
(name, cfg)
for name, cfg in zip(names, cfgs, strict=True)
if isinstance(cfg.func, CheckpointedLadder)
]
def curriculum_state(env: ManagerBasedRlEnv) -> dict[str, dict]:
"""Every ladder's `state_dict()`, by term name."""
return {name: cfg.func.state_dict() for name, cfg in ladders(env)}
def restore_curriculum(env: ManagerBasedRlEnv, saved: dict[str, dict] | None) -> list[str]:
"""Load `saved` into the live ladders; return one line per ladder for the log.
`saved` is None for a checkpoint written before levels were saved; every
ladder then keeps the level its constructor chose.
"""
found = ladders(env)
step = env.common_step_counter
lines = [
f"{name}: {cfg.func.load_state_dict((saved or {}).get(name), step)}"
for name, cfg in found
]
# Apply the restored level before the next sample. The wrapper has already
# reset once and applied the constructor's level.
none = torch.empty(0, dtype=torch.long, device=env.device)
for name, cfg in found:
env.curriculum_manager._curriculum_state[name] = cfg.func(env, none, **cfg.params)
return lines
class CurriculumRunner(VelocityOnPolicyRunner):
"""`VelocityOnPolicyRunner`, whose checkpoints also carry the curriculum levels.
Templates with a checkpointed curriculum select this runner.
"""
def save(self, path: str, infos: dict | None = None) -> None:
state = curriculum_state(self.env.unwrapped)
super().save(path, {**(infos or {}), CHECKPOINT_KEY: state})
def load(
self,
path: str,
load_cfg: dict | None = None,
strict: bool = True,
map_location: str | None = None,
) -> dict:
infos = super().load(path, load_cfg, strict, map_location)
env = self.env.unwrapped
if ladders(env):
saved = (infos or {}).get(CHECKPOINT_KEY)
if saved is None:
print(
f"[mjrl] {path} predates checkpointed curriculum levels; "
f"they come from MJRL_*_LEVEL, or start at 0"
)
for line in restore_curriculum(env, saved):
print(f"[mjrl] curriculum {line}")
return infos