1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Run the normal RL loop with a strict pre-update train/rollout probability gate."""
16
17import argparse
18import json
19import logging
20import math
21import os
22from pathlib import Path
23from typing import Any
24
25import yaml
26
27from rl.config.loader import load_config
28from rl.trainer.build import build_trainer
29from rl.trainer.distributed import run_synchronized
30
31
32def check_metrics(metrics: dict[str, float]) -> dict[str, float]:
33 """Require nonempty, finite and exactly equal sampled-token log probabilities."""
34 keys = ("rollout_probs_diff_valid", "log_probs_valid_tokens", "rollout_log_probs_diff_max",
35 "rollout_log_probs_diff_mean", "actor_log_probs_mean", "rollout_log_probs_mean")
36 observed = {key: float(metrics[f"training/{key}"]) for key in keys}
37 if (not all(math.isfinite(value) for value in observed.values())
38 or observed["rollout_probs_diff_valid"] != 1
39 or observed["log_probs_valid_tokens"] <= 0
40 or observed["rollout_log_probs_diff_max"] != 0
41 or observed["rollout_log_probs_diff_mean"] != 0):
42 raise RuntimeError(f"Train/rollout consistency failed before optimizer update: {observed}")
43 return observed
44
45
46def check_metrics_on_all_ranks(metrics: dict[str, float]) -> dict[str, float]:
47 """Validate rank-zero global diagnostics and propagate failures to every rank."""
48 rank = int(os.environ.get("RANK", "0"))
49 return run_synchronized(
50 "train/rollout consistency",
51 lambda: check_metrics(metrics) if rank == 0 else {},
52 )
53
54
55def run(config: dict[str, Any], report_path: Path) -> None:
56 """Observe production diagnostics without changing tokens, rewards or numerical paths."""
57 if config["train"]["max_steps"] != 2 or config["logging"]["log_steps"] != 1:
58 raise ValueError("This example requires max_steps=2 and log_steps=1")
59 report_path.parent.mkdir(parents=True, exist_ok=True)
60 if int(os.environ.get("RANK", "0")) == 0 and report_path.exists():
61 report_path.unlink()
62 if int(os.environ.get("RANK", "0")) == 0:
63 report_path.with_name("config.yaml").write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")
64 trainer = build_trainer(config)
65 prepare = trainer.targets.prepare
66 checks = []
67
68 def _checked_prepare(rollout, collect_diagnostics, timings):
69 if rollout.rollout_log_probs is None:
70 raise RuntimeError("Independent rollout sampling log probabilities are required")
71 experience, metrics = prepare(rollout, collect_diagnostics, timings) # The prepare function will continue to be executed
72 observed = check_metrics_on_all_ranks(metrics)
73 checks.append({"step": trainer.state.global_step + 1, **observed})
74 if int(os.environ.get("RANK", "0")) == 0:
75 logging.info("CONSISTENCY_CHECK %s", json.dumps(checks[-1]))
76 return experience, metrics
77
78 # This example adds an observation gate at the existing pre-update boundary.
79 trainer.targets.prepare = _checked_prepare
80 trainer.train()
81 if trainer.state.global_step != 2 or [check["step"] for check in checks] != [1, 2]:
82 raise RuntimeError("The normal RL loop did not complete and verify both updates")
83 if int(os.environ.get("RANK", "0")) == 0:
84 report = {"passed": True, "completed_steps": 2, "checks": checks,
85 "training": config["train"]["accelerator"],
86 "rollout": config["rollout"]["vllm"],
87 "scope": "sampled-token log probabilities before each optimizer update"}
88 report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
89 logging.info("CONSISTENCY_PASS report=%s", report_path)
90
91
92def main() -> None:
93 """Load the explicit recipe and launch the ordinary synchronous trainer."""
94 parser = argparse.ArgumentParser(description=__doc__)
95 parser.add_argument("config")
96 parser.add_argument("--report", type=Path, default=Path("/results/run/consistency.json"))
97 args, overrides = parser.parse_known_args()
98 logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")
99 run(load_config(args.config, overrides), args.report)
100
101
102if __name__ == "__main__":
103 main()