Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions src/jaxpot/rl/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,27 +287,33 @@ def _run_all_epochs(
"""Run training loop over all epochs using a fori_loop."""
graphdef, params, non_params = self._ensure_fori_epoch_fn(model)

# ``nnx.pure`` strips Variable wrappers and yields the raw optax
# pytree that ``tx.update`` (called inside the jit body) consumes.
# This matches the canonical pattern used by ``nnx.Optimizer.update``
# internally (flax/nnx/training/optimizer.py).
# ``nnx.pure`` strips Variable wrappers from both params and
# opt_state so the jit body sees a uniform bare-array pytree.
# The two structures MUST match each other across the jit
# boundary: ``optax.MultiSteps`` (always wrapped around the base
# optimizer in production) does a ``tree.map(updates,
# state.acc_grads)`` inside its update — any wrapping asymmetry
# raises a ``Custom node type mismatch`` at trace time.
params_pure = nnx.pure(params)
opt_state = nnx.pure(self.optimizer.opt_state)

dynamic_args = self._get_dynamic_loss_args()
zero_metrics = self._create_zero_metrics()

params, opt_state, final_metrics, final_steps = self._fori_epoch_fn(
params,
new_params_pure, opt_state, final_metrics, final_steps = self._fori_epoch_fn(
params_pure,
opt_state,
batched_data,
dynamic_args,
zero_metrics,
)

# Write the bare new params back into the model's existing
# ``Param`` containers via the pure-dict path, preserving each
# Variable's metadata (sharding hints, OptVariable vs OptArray
# distinctions, etc.). Same pattern the league restore path uses.
nnx.replace_by_pure_dict(params, nnx.to_pure_dict(new_params_pure))
nnx.update(model, nnx.State.merge(params, non_params))
# ``nnx.update`` writes the new values back into the existing
# Variable containers, preserving their metadata (sharding hints,
# OptVariable vs OptArray distinctions, etc.).
nnx.update(self.optimizer.opt_state, nnx.state(opt_state))
self._metrics_accumulator.value = final_metrics
self.training_steps.value = final_steps
Expand Down
119 changes: 119 additions & 0 deletions tests/test_train_hydra_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Hydra-composed integration test for ``train_selfplay.train()``.

Closes the orchestrator-coverage gap called out in PR #19: the existing
``tests/test_train_integration.py`` exercises the underlying pieces
(``collect_selfplay``, ``PPOAgent``) directly but bypasses the Hydra
config-composition path entirely, so a typo in a config default, a
missing field in ``TrainingComponents``, or a regression in the
component-construction pipeline would slip through.

This test composes the real ``config/train_selfplay.yaml`` (with the
existing ``experiment=tic_tac_toe/colab`` profile and aggressive
tiny-scale overrides), then calls ``train_selfplay.train(...)``
end-to-end for 2 iterations. The success bar is that the training
loop completes without exception and writes a well-formed checkpoint.

Runs in <30s on CPU.
"""

from __future__ import annotations

from pathlib import Path

import pytest
from hydra import compose, initialize_config_dir
from hydra.core.global_hydra import GlobalHydra
from hydra.core.hydra_config import HydraConfig
from hydra.utils import instantiate
from omegaconf import OmegaConf

import train_selfplay
from jaxpot.utils.checkpoints import BestCheckpointManager, CheckpointManager
from jaxpot.utils.sharding import create_device_mesh


def test_train_completes_via_hydra_composed_config(tmp_path, monkeypatch):
"""train_selfplay.train() must complete on a tiny Hydra-composed config
and produce a well-formed checkpoint.
"""
repo_root = Path(__file__).parent.parent
config_dir = str(repo_root / "config")

GlobalHydra.instance().clear()
with initialize_config_dir(config_dir=config_dir, version_base=None):
cfg = compose(
config_name="train_selfplay",
overrides=[
"experiment=tic_tac_toe/colab",
"logger=none",
# Tiny scale — fits in CPU-only pytest budget.
"total_iters=2",
"selfplay_num_envs=16",
"random_num_envs=16",
"league_num_envs=0",
"archive_num_envs=0",
# Stay in random-warmup for both iters so the league path
# is skipped entirely. The league path is exercised by the
# checkpoint round-trip test instead.
"random_warmup_iters=10",
"save_every=1",
# Milestone needs ``it > 0 and it % milestone_every == 0``;
# disabling avoids writing milestone files during the run.
"milestone_every=0",
"league_add_every=0",
"use_target_selfplay=false",
"log_to_file=null",
"dump_debug_every=false",
"trainer.batch_size=16",
"trainer.num_epochs=1",
# The colab profile evaluates every 250 iters; with
# total_iters=2 no evaluator should fire, but the
# surface-level smoke is enough.
],
)

# ``train_selfplay.train()`` reads ``HydraConfig.get().runtime.output_dir``
# once at the top of its body. Compose alone doesn't populate
# HydraConfig.instance(); patch it to point at the test's tmp dir.
mock_hydra_runtime = OmegaConf.create({"runtime": {"output_dir": str(tmp_path)}})
monkeypatch.setattr(HydraConfig, "get", staticmethod(lambda: mock_hydra_runtime))

env, init, step_fn, no_auto_reset_step_fn = train_selfplay.make_env_fns(cfg)
mesh = create_device_mesh()

ckpt_path = tmp_path / "checkpoints"
ckpt_path.mkdir(exist_ok=True)
ckpt_manager = CheckpointManager(ckpt_path)
best_ckpt_manager = BestCheckpointManager(
path=tmp_path / "best_checkpoints",
keep_top_k=1,
)
checkpoint = ckpt_manager.start(cfg, env)
tracker = instantiate(cfg.logger, run_id=None)

try:
train_selfplay.train(
cfg,
env,
init,
step_fn,
no_auto_reset_step_fn,
tracker,
checkpoint,
ckpt_manager,
best_ckpt_manager,
mesh,
)
finally:
tracker.close()

# Verify the loop wrote at least one well-formed checkpoint.
checkpoints = sorted(p for p in ckpt_path.iterdir() if p.is_dir())
assert len(checkpoints) >= 1, (
f"expected at least one checkpoint in {ckpt_path}, found {checkpoints}"
)
last = checkpoints[-1]
assert (last / "metadata.json").exists(), "metadata.json missing"
assert (last / "state").is_dir(), "orbax state/ missing"
assert (last / "league.json").exists(), "league.json missing (post-#20 layout)"
assert (last / "league_states").is_dir(), "league_states/ missing"
Loading