Files
prime-rl/tests/utils.py
T
d8698f4e53
Release / Push CUDA image to Docker (push) Canceled after 0s
test(ci): add reverse-text smoke tests for RL OPD + SFT training modes (#2563)
* test(ci): add reverse-text smoke tests for RL OPD + SFT training modes

Covers the rl-entrypoint training_mode = "opd" / "sft" paths on the
existing `vm` integration runner. The student inference deployment is
launched by the rl entrypoint; the teacher is started as a dedicated
`uv run inference` process by the test fixture (low gpu_memory_utilization
on GPU 0 so the student still fits), with orchestrator.teacher.client
pointing at it.

Both tests pass locally on 2× Blackwell GPUs in ~1m40s each.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(ci): match reverse_text training config + symmetric 0.4 gpu util

Aligns max_steps / seq_len / batch_size / rollouts_per_example / max_completion_tokens
with the existing reverse_text smoke test, and switches the student+teacher
overlap from asymmetric (0.85 + 0.1) to symmetric 0.4 + 0.4 — both fit on one
Blackwell GPU with the small Qwen3-0.6B models. Both tests still pass locally
(~2m10s each).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(ci): drop to 5 steps and remove [ckpt] for the OPD/SFT smoke tests

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(ci): drop [deployment] and enforce_eager from OPD/SFT configs

Matches the rest of `configs/ci/integration/` — the default
SingleNodeDeploymentConfig (1 train + 1 infer GPU, gpus_per_node=8)
works on the 2-GPU vm runner, and no other CI config sets
enforce_eager. OPD test still passes locally (2m18s).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(ci): assert eval reward goes up instead of loss goes down

Loss going down is a weak signal for distillation training modes — both OPD
(KL-style) and SFT (teacher-token CE) loss curves are noisy across the 5
smoke steps. Switch to checking that the per-step eval reward on the same
reverse-text env actually improves end-to-end.

- Add [orchestrator.eval] (interval=1, num_examples=16) to both configs.
- New `check_eval_avg_goes_up` helper greps the orchestrator log for
  "Evaluated <env> ... Avg@K=X.XXXX" and asserts last > first.

Both tests pass locally (OPD 1m52s, SFT 1m42s).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 15:30:44 -07:00

223 lines
8.8 KiB
Python

import re
from pathlib import Path
from tests.conftest import ProcessResult
def strip_escape_codes(text: str) -> str:
"""Helper to strip escape codes from text"""
return re.sub(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", text)
def check_no_error(process: ProcessResult, output_dir: Path) -> None:
"""Helper to assert that a process did not error"""
if process.returncode != 0:
print("=== Inference Outputs ===")
with open(output_dir / "logs" / "inference.log", "r") as f:
print(*f.readlines()[-100:], sep="")
print("=== Orchestrator Outputs ===")
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
print(*f.readlines()[-1000:], sep="")
assert process.returncode == 0, f"Process has non-zero return code ({process})"
def check_number_goes_up_or_down(
lines: list[str],
start_step: int = 0,
end_step: int = -1,
pattern: str = r"Reward:\s*(\d+\.\d{4})",
go_up: bool = True,
):
"""Helper to assert that a number in lines goes up from a specified start to end step"""
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
assert len(step_lines) > 0, f"No step lines found in output ({lines})"
try:
start_step_line = step_lines[start_step]
except IndexError:
start_step_line = ""
try:
end_step_line = step_lines[end_step]
except IndexError:
end_step_line = ""
assert start_step_line, f"Could not find start step {start_step} in output ({lines})"
assert end_step_line, f"Could not find end step {end_step} in output ({lines})"
start_step_match = re.search(pattern, start_step_line)
end_step_match = re.search(pattern, end_step_line)
assert start_step_match is not None, (
f"Could not find number for start step {start_step} in line {start_step_line} ({lines})"
)
assert end_step_match is not None, (
f"Could not find number for end step {end_step} in line {end_step_line} ({lines})"
)
start_step_number = float(start_step_match.group(1))
end_step_number = float(end_step_match.group(1))
if go_up:
assert start_step_number < end_step_number, (
f"Number did not go up. Found start_number={start_step_number} <= end_number={end_step_number} "
f"(start line: {start_step_line}, end line: {end_step_line}) ({lines})"
)
else:
assert start_step_number > end_step_number, (
f"Number did not go down. Found start_number={start_step_number} >= end_number={end_step_number} "
f"(start line: {start_step_line}, end line: {end_step_line}) ({lines})"
)
def check_metric_in_range(
lines: list[str],
metric_name: str,
pattern: str,
step: int = -1,
min_threshold: float | None = None,
max_threshold: float | None = None,
):
"""Helper to assert that a metric in step logs is within a threshold"""
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
assert len(step_lines) > 0, f"No step lines found in output ({lines})"
# Search for the specific step number in the lines
if step == -1:
step_line = step_lines[-1]
else:
step_pattern = rf"Step {step}\b"
matching_lines = [line for line in step_lines if re.search(step_pattern, line)]
assert len(matching_lines) > 0, f"Could not find step {step} in output ({step_lines})"
step_line = matching_lines[0]
metric_match = re.search(pattern, step_line)
assert metric_match is not None, f"Could not find {metric_name} for step {step}. Line: {step_line} ({lines})"
metric_value = float(metric_match.group(1))
if min_threshold is not None:
assert metric_value >= min_threshold, (
f"{metric_name} did not reach minimum threshold. Found {metric_name}={metric_value} < {min_threshold} "
f"(line: {step_line}) ({lines})"
)
if max_threshold is not None:
assert metric_value <= max_threshold, (
f"{metric_name} exceeded maximum threshold. Found {metric_name}={metric_value} > {max_threshold} "
f"(line: {step_line}) ({lines})"
)
def check_reward_goes_up(lines: list[str]):
return check_number_goes_up_or_down(lines, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
def check_loss_goes_down(lines: list[str]):
return check_number_goes_up_or_down(lines, go_up=False, pattern=r"Loss:\s*(\d+\.\d{4})")
def check_eval_avg_goes_up(lines: list[str], env_name: str):
"""Assert that the last `Evaluated {env_name} ... Avg@K=X.XXXX` line reports a
higher score than the first one. Use for smoke tests with `interval = 1`
evals."""
pattern = rf"Evaluated {re.escape(env_name)} .*Avg@\d+=(\d+\.\d{{4}})"
eval_lines = [line for line in lines if "SUCCESS" in line and re.search(pattern, line)]
assert len(eval_lines) >= 2, f"Need at least 2 eval lines for {env_name!r}, found {len(eval_lines)}"
start = float(re.search(pattern, eval_lines[0]).group(1))
end = float(re.search(pattern, eval_lines[-1]).group(1))
assert end > start, (
f"Eval avg for {env_name!r} did not go up: first={start} last={end}\n"
f"first line: {eval_lines[0]}\nlast line: {eval_lines[-1]}"
)
def check_reward_in_range(
lines: list[str],
step: int = -1,
min_threshold: float | None = 0.0,
max_threshold: float | None = None,
):
"""Helper to assert that reward in step logs is within a threshold"""
check_metric_in_range(
lines,
metric_name="Reward",
pattern=r"Reward:\s*(\d+\.\d{4})",
step=step,
min_threshold=min_threshold,
max_threshold=max_threshold,
)
def check_avg_reward_in_range(
lines: list[str],
last_n_steps: int,
min_threshold: float | None = None,
max_threshold: float | None = None,
):
"""Helper to assert that the average reward over the last N steps is within a threshold"""
pattern = r"Reward:\s*(\d+\.\d{4})"
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
assert len(step_lines) >= last_n_steps, (
f"Not enough step lines found. Expected at least {last_n_steps}, got {len(step_lines)}"
)
recent_lines = step_lines[-last_n_steps:]
rewards = []
for line in recent_lines:
match = re.search(pattern, line)
assert match is not None, f"Could not find Reward in line: {line}"
rewards.append(float(match.group(1)))
avg_reward = sum(rewards) / len(rewards)
if min_threshold is not None:
assert avg_reward >= min_threshold, (
f"Average reward over last {last_n_steps} steps did not reach minimum threshold. "
f"Found avg_reward={avg_reward:.4f} < {min_threshold} (rewards={rewards})"
)
if max_threshold is not None:
assert avg_reward <= max_threshold, (
f"Average reward over last {last_n_steps} steps exceeded maximum threshold. "
f"Found avg_reward={avg_reward:.4f} > {max_threshold} (rewards={rewards})"
)
def check_avg_mismatch_kl_in_range(
lines: list[str],
last_n_steps: int,
min_threshold: float | None = None,
max_threshold: float | None = None,
):
"""Helper to assert that the average mismatch KL over the last N steps is within a threshold"""
pattern = r"Mismatch KL:\s*(\d+\.\d{4})"
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
assert len(step_lines) >= last_n_steps, (
f"Not enough step lines found. Expected at least {last_n_steps}, got {len(step_lines)}"
)
recent_lines = step_lines[-last_n_steps:]
kl_values = []
for line in recent_lines:
match = re.search(pattern, line)
assert match is not None, f"Could not find Mismatch KL in line: {line}"
kl_values.append(float(match.group(1)))
avg_kl = sum(kl_values) / len(kl_values)
if min_threshold is not None:
assert avg_kl >= min_threshold, (
f"Average mismatch KL over last {last_n_steps} steps did not reach minimum threshold. "
f"Found avg_kl={avg_kl:.4f} < {min_threshold} (kl_values={kl_values})"
)
if max_threshold is not None:
assert avg_kl <= max_threshold, (
f"Average mismatch KL over last {last_n_steps} steps exceeded maximum threshold. "
f"Found avg_kl={avg_kl:.4f} > {max_threshold} (kl_values={kl_values})"
)
def check_mismatch_kl_in_range(
lines: list[str],
step: int = -1,
min_threshold: float | None = None,
max_threshold: float | None = None,
):
"""Helper to assert that mismatch KL in step logs is within a threshold"""
check_metric_in_range(
lines,
metric_name="Mismatch KL",
pattern=r"Mismatch KL:\s*(\d+\.\d{4})",
step=step,
min_threshold=min_threshold,
max_threshold=max_threshold,
)