Skip to content

Commit 6e2dfd5

Browse files
authored
Merge pull request #1107 from utilForever/verify-training-parity
Verify C++ and Python training parity
2 parents f7a9ab1 + 38c4a5c commit 6e2dfd5

4 files changed

Lines changed: 286 additions & 3 deletions

File tree

‎Documents/RosettaRL.md‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,9 @@ cmake -S . -B build/rl-python \
9090
-DPython_EXECUTABLE="$(python -c 'import sys; print(sys.executable)')" \
9191
-DCMAKE_PREFIX_PATH="$(python -c 'import torch; print(torch.utils.cmake_prefix_path)')"
9292
cmake --build build/rl-python --config Release \
93-
--target RosettaRLTests pyRosettaRL RosettaRLWeightInterop
93+
--target RosettaRLTests pyRosettaRL RosettaRLWeightInterop RosettaRLTrainingReference
9494
ctest --test-dir build/rl-python -C Release \
95-
-R '^RosettaRL(Tests|WeightInterop|PythonTrainer)$' --output-on-failure
95+
-R '^RosettaRL(Tests|WeightInterop|PythonTrainer|TrainingParity)$' --output-on-failure
9696
```
9797

9898
Add the directory containing the built `pyRosettaRL` module to `PYTHONPATH` (`build/rl-python/lib` for a single-configuration build; append `Release` for a multi-configuration build). On Windows, use explicit paths for the interpreter and its Torch CMake prefix. The optional binding uses PyTorch's C++ module wrapper, so the model is a `torch.nn.Module` backed by the same C++ parameters and forward implementation:
@@ -109,6 +109,8 @@ logits, values = model(batch)
109109
model.save_weights("python-weights.pt")
110110
```
111111

112+
If PyTorch's bundled pybind11 headers and the installed development headers have different versions, select a matching package with `-Dpybind11_DIR=/path/to/pybind11/share/cmake/pybind11`. Mixing versions can fail in `pybind11/stl/filesystem.h`; the Windows CPU parity check uses PyTorch `2.7.0` with pybind11 `2.13.6`.
113+
112114
`cpu()`, `cuda(device)`, `eval()`, and `train()` return the same model. `float()`, `double()`, and `half()` also return the model and convert its parameters and existing gradients together.
113115

114116
`named_parameters()` yields names paired with the original C++ parameters. Use `dict(model.named_parameters())["policy.weight"]` to look up a parameter by name. `zero_grad(set_to_none=False)` zeros existing gradients in place. Passing `set_to_none=True` clears them to `None`.
@@ -132,3 +134,19 @@ policy_loss, value_loss, total_loss = train(model, batches, "weights.pt")
132134
`load_training_batch` reads the CPU batch files used by the native trainer. In-memory batches use the same three tensors in observation, policy target and outcome order. You can prepare batches inside `torch.inference_mode()` and train on them after leaving that context. To train on CUDA, use `model = model.to("cuda")` and move all three batch tensors to the device reported by `next(model.parameters()).device`.
133135

134136
The returned losses describe the final batch before its update. After all batches succeed, the trainer atomically saves the updated weights in the shared format. To resume in Python, call `model.load_weights("weights.pt")` before `train`. The native trainer can resume from the same file.
137+
138+
## C++ and Python training parity
139+
140+
`RosettaRLTrainingParity` runs `RosettaRLTrainingReference` in a separate native process and compares it with `rosetta_rl_trainer.train`, using the same C++ model and loss implementation. Both construct a CPU float32 model with seed `1074` and use one intra-op thread. The native helper serializes the existing two-row `ReplayTrainingBatch`: consecutive acting-player observations from a fixed Mage replay, an End Turn target followed by a 25% End Turn / 75% Coin target, and outcomes `[+1,-1]`.
141+
142+
The test compares seeded parameters, both forward outputs, policy/value/regularized total losses, every named gradient, and every weight after one SGD step (`lr=0.01`, zero momentum and optimizer weight decay; L2 is included in the loss). All parity comparisons use `rtol=1e-5, atol=1e-6`, meaning `abs(python - native) <= 1e-6 + 1e-5 * abs(native)` elementwise. Shapes, dtypes, devices and parameter names must also match; non-finite values fail. Losses are computed in float32 and transported as float64 scalars. Comparison stops at the first mismatch and reports its stage and tensor name, such as `gradients.shared.weight`, together with numerical error details.
143+
144+
Both frontends must overfit the same batch after 64 steps. The final pre-update policy loss must be below `0.35`, value loss below `0.02`, and total loss below 15% of its initial value. The soft policy target has a minimum mean cross-entropy of about `0.2812`. After the final update, every policy probability and value must be within `0.1` absolute error of its target. The final pre-update component losses are also compared across frontends.
145+
146+
For a clean check, configure the Python-enabled build above in a new build directory, build `pyRosettaRL` and `RosettaRLTrainingReference`, then run:
147+
148+
```bash
149+
ctest --test-dir build/rl-python -C Release -R '^RosettaRLTrainingParity$' --output-on-failure
150+
```
151+
152+
The CTest supplies the module and helper paths. Ordinary pytest runs skip this cross-runtime test when the helper is not configured; a missing module or helper in the configured CTest is a failure. Use matching PyTorch/LibTorch installations. These are CPU tolerances within one build environment, not a promise of bitwise equality across platforms or GPUs, optimizer-state interchange, or frontend speed.

‎Extensions/RosettaRL/CMakeLists.txt‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,11 @@ print(";".join(definitions))
7878
add_executable(RosettaRLWeightInterop Tests/WeightArtifactInterop.cpp)
7979
target_link_libraries(RosettaRLWeightInterop PRIVATE RosettaRLModel)
8080

81-
list(APPEND rl_runtime_targets pyRosettaRL RosettaRLWeightInterop)
81+
add_executable(RosettaRLTrainingReference Tests/TrainingReference.cpp)
82+
target_link_libraries(RosettaRLTrainingReference PRIVATE RosettaRLModel)
83+
84+
list(APPEND rl_runtime_targets pyRosettaRL RosettaRLWeightInterop
85+
RosettaRLTrainingReference)
8286
endif()
8387

8488
# Project options
@@ -130,4 +134,12 @@ if (BUILD_RL_PYTHON)
130134
"${Python_EXECUTABLE}" -m pytest -q
131135
"${PROJECT_SOURCE_DIR}/Tests/PythonTests/test_rl_trainer.py"
132136
)
137+
138+
add_test(NAME RosettaRLTrainingParity
139+
COMMAND ${CMAKE_COMMAND} -E env
140+
"PYTHONPATH=$<TARGET_FILE_DIR:pyRosettaRL>"
141+
"ROSETTA_RL_TRAINING_REFERENCE=$<TARGET_FILE:RosettaRLTrainingReference>"
142+
"${Python_EXECUTABLE}" -m pytest -q
143+
"${PROJECT_SOURCE_DIR}/Tests/PythonTests/test_rl_training_parity.py"
144+
)
133145
endif()
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright (c) 2026 Chris Ohk
2+
3+
#include <ATen/Parallel.h>
4+
#include <torch/serialize.h>
5+
#include <torch/utils.h>
6+
7+
#include <RosettaRL/NativeTrainer.hpp>
8+
9+
#include <cstdlib>
10+
#include <iostream>
11+
#include <string>
12+
13+
#include "ReplayTrainingBatch.hpp"
14+
15+
using namespace RosettaStone::RL;
16+
17+
namespace
18+
{
19+
c10::Dict<std::string, torch::Tensor> SnapshotWeights(
20+
const PolicyValueNetwork& model)
21+
{
22+
c10::Dict<std::string, torch::Tensor> weights;
23+
24+
for (const auto& parameter : model->named_parameters())
25+
{
26+
// Later optimizer steps must not change the reference snapshots.
27+
weights.insert(parameter.key(), parameter.value().detach().clone());
28+
}
29+
30+
return weights;
31+
}
32+
33+
torch::Tensor Losses(const TrainingStep& step)
34+
{
35+
return torch::tensor({ step.policyLoss, step.valueLoss, step.totalLoss },
36+
torch::kFloat64);
37+
}
38+
} // namespace
39+
40+
// Pytest compares these native snapshots with the actual Python trainer.
41+
int main(int argc, char** argv)
42+
{
43+
try
44+
{
45+
TORCH_CHECK(argc == 2,
46+
"Usage: RosettaRLTrainingReference reference.pt");
47+
48+
at::set_num_threads(1);
49+
at::set_num_interop_threads(1);
50+
51+
const auto [observations, policy, outcomes] =
52+
Tests::ReplayTrainingBatch();
53+
54+
torch::manual_seed(1074);
55+
56+
PolicyValueNetwork model;
57+
model->eval();
58+
59+
torch::serialize::OutputArchive reference;
60+
reference.write("observations", observations, true);
61+
reference.write("policy", policy, true);
62+
reference.write("outcomes", outcomes, true);
63+
reference.write("initial_weights", SnapshotWeights(model));
64+
65+
{
66+
torch::NoGradGuard guard;
67+
const auto [logits, values] = model->forward(observations);
68+
69+
reference.write("logits", logits, true);
70+
reference.write("values", values, true);
71+
}
72+
73+
NativeTrainer trainer(model);
74+
auto step = trainer.TrainBatch(observations, policy, outcomes);
75+
76+
reference.write("first_losses", Losses(step), true);
77+
78+
c10::Dict<std::string, torch::Tensor> gradients;
79+
80+
for (const auto& parameter : model->named_parameters())
81+
{
82+
TORCH_CHECK(parameter.value().grad().defined(),
83+
"Missing native gradient: ", parameter.key());
84+
gradients.insert(parameter.key(),
85+
parameter.value().grad().detach().clone());
86+
}
87+
88+
reference.write("gradients", gradients);
89+
reference.write("step_weights", SnapshotWeights(model));
90+
91+
for (std::size_t i = 1; i < 64; ++i)
92+
{
93+
step = trainer.TrainBatch(observations, policy, outcomes);
94+
}
95+
96+
reference.write("last_losses", Losses(step), true);
97+
98+
torch::NoGradGuard guard;
99+
const auto [logits, values] = model->forward(observations);
100+
101+
reference.write("final_logits", logits, true);
102+
reference.write("final_values", values, true);
103+
reference.save_to(argv[1]);
104+
105+
return EXIT_SUCCESS;
106+
}
107+
catch (const std::exception& error)
108+
{
109+
std::cerr << error.what() << '\n';
110+
return EXIT_FAILURE;
111+
}
112+
}
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
# Copyright (c) 2026 Chris Ohk
2+
3+
import os
4+
import subprocess
5+
from itertools import repeat
6+
7+
import pytest
8+
9+
if "ROSETTA_RL_TRAINING_REFERENCE" not in os.environ:
10+
pytest.skip(
11+
"Run the RosettaRLTrainingParity CTest for the native reference",
12+
allow_module_level=True,
13+
)
14+
15+
import torch
16+
from pyRosettaRL import PolicyValueNetwork
17+
from rosetta_rl_trainer import train
18+
19+
20+
# CPU float32 contract; see Documents/RosettaRL.md.
21+
RTOL = 1e-5
22+
ATOL = 1e-6
23+
24+
25+
def assert_close(name, actual, expected):
26+
assert actual is not None, f"{name}: missing Python tensor"
27+
assert torch.isfinite(actual).all(), f"{name}: non-finite Python tensor"
28+
assert torch.isfinite(expected).all(), f"{name}: non-finite native tensor"
29+
torch.testing.assert_close(
30+
actual,
31+
expected,
32+
rtol=RTOL,
33+
atol=ATOL,
34+
msg=lambda detail: f"{name}: {detail}",
35+
)
36+
37+
38+
def assert_named_close(stage, actual, expected):
39+
assert actual.keys() == expected.keys(), f"{stage}: parameter names differ"
40+
for name, tensor in actual.items():
41+
assert_close(f"{stage}.{name}", tensor, expected[name])
42+
43+
44+
def assert_losses_close(stage, actual, expected):
45+
for name, value, reference in zip(
46+
("policy", "value", "total"), actual, expected, strict=True
47+
):
48+
assert_close(
49+
f"{stage}.{name}", torch.tensor(value, dtype=torch.float64), reference
50+
)
51+
52+
53+
def test_native_and_python_training_parity(tmp_path):
54+
subprocess.run(
55+
[os.environ["ROSETTA_RL_TRAINING_REFERENCE"], "reference.pt"],
56+
cwd=tmp_path,
57+
check=True,
58+
)
59+
reference = torch.jit.load(str(tmp_path / "reference.pt"), map_location="cpu")
60+
batch = (reference.observations, reference.policy, reference.outcomes)
61+
observations, policy, outcomes = batch
62+
63+
original_threads = torch.get_num_threads()
64+
torch.set_num_threads(1)
65+
try:
66+
torch.manual_seed(1074)
67+
model = PolicyValueNetwork().eval()
68+
assert_named_close(
69+
"initial_weights", dict(model.named_parameters()), reference.initial_weights
70+
)
71+
72+
with torch.no_grad():
73+
logits, values = model(observations)
74+
assert_close("forward.logits", logits, reference.logits)
75+
assert_close("forward.values", values, reference.values)
76+
77+
first = train(model, [batch], tmp_path / "first.pt")
78+
assert model.training
79+
assert_losses_close("first_losses", first, reference.first_losses)
80+
assert_named_close(
81+
"gradients",
82+
{name: parameter.grad for name, parameter in model.named_parameters()},
83+
reference.gradients,
84+
)
85+
assert_named_close(
86+
"step_weights", dict(model.named_parameters()), reference.step_weights
87+
)
88+
89+
# Plain SGD has no optimizer state to preserve between these calls.
90+
last = train(model, repeat(batch, 63), tmp_path / "last.pt")
91+
assert_losses_close("last_losses", last, reference.last_losses)
92+
with torch.no_grad():
93+
logits, values = model(observations)
94+
95+
for frontend, first_losses, last_losses, final_logits, final_values in (
96+
(
97+
"native",
98+
reference.first_losses,
99+
reference.last_losses,
100+
reference.final_logits,
101+
reference.final_values,
102+
),
103+
("python", first, last, logits, values),
104+
):
105+
assert last_losses[0] < 0.35, f"{frontend}: policy loss did not overfit"
106+
assert last_losses[1] < 0.02, f"{frontend}: value loss did not overfit"
107+
assert last_losses[2] < first_losses[2] * 0.15, (
108+
f"{frontend}: total loss did not overfit"
109+
)
110+
torch.testing.assert_close(
111+
final_logits.softmax(1),
112+
policy,
113+
rtol=0,
114+
atol=0.1,
115+
msg=lambda detail: f"{frontend}.overfit.policy: {detail}",
116+
)
117+
torch.testing.assert_close(
118+
final_values,
119+
outcomes,
120+
rtol=0,
121+
atol=0.1,
122+
msg=lambda detail: f"{frontend}.overfit.values: {detail}",
123+
)
124+
finally:
125+
torch.set_num_threads(original_threads)
126+
127+
128+
def test_parity_failure_names_first_mismatched_tensor():
129+
expected = {"shared.weight": torch.zeros(2), "policy.bias": torch.zeros(2)}
130+
actual = {name: tensor + 1 for name, tensor in expected.items()}
131+
with pytest.raises(AssertionError, match=r"gradients\.shared\.weight") as error:
132+
assert_named_close("gradients", actual, expected)
133+
assert "policy.bias" not in str(error.value)
134+
assert "Greatest absolute difference" in str(error.value)
135+
136+
137+
@pytest.mark.parametrize("value", [float("nan"), float("inf")])
138+
def test_parity_rejects_non_finite_tensors(value):
139+
tensor = torch.tensor([value])
140+
with pytest.raises(AssertionError, match="forward.values: non-finite"):
141+
assert_close("forward.values", tensor, tensor)

0 commit comments

Comments
 (0)