Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
verl · 9 changed files
Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d
diff --git a/verl/trainer/runtime/README.md b/verl/trainer/runtime/README.mdnew file mode 100644index 0000000000000000000000000000000000000000..9eea0db525dede37bcf74304149a93b98fcbe797--- /dev/null+++ b/verl/trainer/runtime/README.md@@ -0,0 +1,111 @@+# Resident online GRPO on two Ascend devices++`python -m verl.trainer.runtime.online_grpo` implements the line-delimited JSON+control protocol for an online policy run. Its required arguments are+`--run-spec`, `--model-path`, `--tokenizer-path`, `--runtime-dir`, `--result-dir`,+and `--control-socket`.++## Execution++The foreground process owns an actor on projected device zero and an in-process+vLLM engine on projected device one. Both models remain resident. The runtime+loads the supplied model and warms its kernels before sending `ready`. Prompts+and the scoring endpoint arrive in the subsequent `start` message.++The runtime overlaps actor optimization with the next rollout batch. At most+one batch is prefetched, so policy lag is zero on the first update and one on+subsequent updates. Both operations finish before the full weight refresh. A+run spec that disallows policy lag uses serial generation instead.++For each update, the runtime:++1. Generates four independently seeded responses for each prompt group using+ the supplied sampling parameters.+2. Sends every response exactly once to the host scoring endpoint and computes+ group-normalized advantages with the sample standard deviation.+3. Packs trajectories in their original order into bounded microbatches. Causal+ attention receives explicit sequence boundaries. Only response predictors+ reach the vocabulary projection.+4. Accumulates the clipped loss with a denominator equal to the response-token+ count of the entire update. BF16 parameter casts participate in autograd, so+ gradients accumulate into FP32 master parameters. Gradient clipping and+ AdamW run once per update.+ Microbatches with zero advantages are evaluated without backward, while the+ optimizer still receives zero gradients and advances any existing momentum.+5. Casts every actor parameter into persistent BF16 transfer buckets and copies+ them to vLLM through its native weight loaders. It verifies that every+ rollout parameter was loaded, synchronizes the copy, invalidates cached+ prefixes, and publishes the new rollout policy version.++The dense Qwen3 decoder uses differentiable Ascend RMSNorm, rotary, SiLU, and+variable-length attention kernels. It retains the original Transformers model+as the owner of all parameters and checkpoints. The runtime preserves actual+embedding/output-head sharing, including checkpoints whose config declares+sharing but contains two independent weight tensors.++Training log probabilities use the supplied actor temperature. Freshness probes+compare live actor and rollout probabilities in vLLM Ascend's raw-logit+convention. Pre-update probabilities used for loss auditing come directly from+the training forward pass.++## Restart and lifecycle++Correctness runs save FP32 model and AdamW state, RNG state, and the committed+policy version under `checkpoints/update-8`. They also export a standard BF16+Transformers actor in `portable-actor`. A fresh restart process restores the+training checkpoint and refreshes vLLM before accepting update nine.++The runtime stays alive for the host's final unseen freshness probe, then shuts+down vLLM on `shutdown`. Initialization and execution failures close the control+connection. The host remains responsible for the outer process-group timeout+and cleanup.++## Focused checks++```bash+python -m pytest -q verl/trainer/runtime/tests+python -m pytest -q tests/trainer/ppo/test_core_algos_on_cpu.py -k grpo+```++The decoder comparison requires an Ascend device. It compares packed forward+values and gradients with independent Transformers sequences. The CPU checks+cover sequence boundaries, response predictors, group normalization, and+microbatch loss and gradient scaling. Additional tests cover complete repeated+weight transfer, checkpoint and momentum restoration, and the zero-lag and+one-update-lag schedules, including seed provenance and reward accounting.++## Validation results++Development workload, REDACTED_DATE, using the supplied task commands on two+projected Ascend 910B devices:++| Check | Result |+| --- | --- |+| Final measurement | Passed: 939.14 response tokens/s; 18,642 tokens in 19.850 s |+| Work accounting | Eight committed updates and 256 accepted trajectories |+| Correctness | Passed all host gates, including the final live freshness probe |+| Portable actor | Passed: BF16 export, 311 tensors, 2,031,739,904 parameters |+| Fresh process restart | Passed: restored update eight and committed update nine |+| Cleanup | Passed: processes stopped, port released, checkpoint removed |+| Focused runtime tests | 11 passed |+| Upstream GRPO CPU tests | Four passed |++The measurement uses the host's elapsed time, including its final unseen probe.+All trajectory tokens, seeds, rewards, advantages, and old/new log probabilities+matched the preceding measurement of the retained configuration. All rollout+parameters were checked after every complete policy refresh.++The supplied smoke run completed its one update with zero loss and zero+gradient. Its worker's only failed gate was `parameters_changed`; the original+reference smoke also fails that gate. With a zero first gradient, the supplied+AdamW settings leave the FP32 parameters unchanged. The full eight-update run+contains nonzero gradients and passes parameter-change validation.++The public lifecycle checks can be repeated with:++```bash+bash "$TASK_DIR/run/smoke.sh"+bash "$TASK_DIR/run/correctness.sh"+bash "$TASK_DIR/run/benchmark_once.sh"+bash "$TASK_DIR/run/cleanup.sh"+```diff --git a/verl/trainer/runtime/__init__.py b/verl/trainer/runtime/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..692a46616a72adb37458edb42145c3c7db96cfca--- /dev/null+++ b/verl/trainer/runtime/__init__.py@@ -0,0 +1,5 @@+# Copyright 2026 The verl contributors+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0+"""Small, resident execution plans for online policy optimization."""diff --git a/verl/trainer/runtime/online_grpo.py b/verl/trainer/runtime/online_grpo.pynew file mode 100644index 0000000000000000000000000000000000000000..0b648c1efa83e6eb8f2c8e6308bc5a1470d43827--- /dev/null+++ b/verl/trainer/runtime/online_grpo.py@@ -0,0 +1,474 @@+# Copyright 2026 The verl contributors+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0+"""Foreground, two-device online GRPO execution plan.++The control connection supplies prompts and a scoring endpoint only after both+models are ready. No prompt or reward information is read during initialization.+The actor and rollout engine occupy separate devices for their entire lifetime.+There are no Ray workers, parameter offloads, or disk transfers in the update+loop. The host owns timing and the final, previously unseen freshness request.+"""++import argparse+import json+import math+import os+import signal+import socket+import time+from collections.abc import Mapping+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from urllib.request import Request, urlopen+++def send_message(connection, message):+ connection.sendall(json.dumps(message, allow_nan=False, separators=(",", ":")).encode() + b"\n")+++def receive_message(stream):+ line = stream.readline()+ if not line:+ raise RuntimeError("The host closed the control connection")+ message = json.loads(line)+ if not isinstance(message, dict):+ raise ValueError("Control messages must be JSON objects")+ return message+++def score_responses(endpoint, rows):+ request = Request(+ endpoint["url"].rstrip("/") + "/score_batch",+ data=json.dumps(+ {"items": [{"prompt_id": row["prompt_id"], "response_text": row["response_text"]} for row in rows]},+ allow_nan=False,+ ).encode(),+ headers={"Authorization": "Bearer " + endpoint["token"], "Content-Type": "application/json"},+ method="POST",+ )+ with urlopen(request, timeout=300) as response:+ rewards = json.load(response)["rewards"]+ if len(rewards) != len(rows) or any(type(reward) not in (int, float) or reward not in (0, 1) for reward in rewards):+ raise ValueError("The scoring endpoint returned an invalid reward vector")+ for row, reward in zip(rows, rewards, strict=True):+ row["reward"] = float(reward)+++def group_advantages(rows, responses_per_prompt, epsilon):+ if len(rows) % responses_per_prompt:+ raise ValueError("Incomplete prompt group")+ for offset in range(0, len(rows), responses_per_prompt):+ group = rows[offset : offset + responses_per_prompt]+ if len({row["prompt_id"] for row in group}) != 1:+ raise ValueError("Trajectories are not grouped by prompt")+ rewards = [row["reward"] for row in group]+ mean = math.fsum(rewards) / len(rewards)+ std = math.sqrt(math.fsum((reward - mean) ** 2 for reward in rewards) / (len(rewards) - 1))+ for row in group:+ row["advantage"] = (row["reward"] - mean) / (std + epsilon) if std else 0.0+++def trajectory_observation(rows, version, responses_per_prompt):+ groups = [rows[offset : offset + responses_per_prompt] for offset in range(0, len(rows), responses_per_prompt)]+ return {+ "policy_version": version,+ "prompt_ids": [group[0]["prompt_id"] for group in groups],+ "rewards": [[row["reward"] for row in group] for group in groups],+ "advantages": [[row["advantage"] for row in group] for group in groups],+ "response_lengths": [len(row["response_ids"]) for row in rows],+ "response_texts": [[row["response_text"] for row in group] for group in groups],+ "consumed_response_tokens": sum(len(row["response_ids"]) for row in rows),+ "nonzero_advantage_groups": sum(any(row["advantage"] != 0 for row in group) for group in groups),+ "trajectories": [{key: value for key, value in row.items() if key != "prompt_ids"} for row in rows],+ }+++def validate_spec(spec):+ """Reject unsupported numerical semantics rather than silently ignoring them."""+ if spec.get("action") not in {"smoke", "correctness", "measurement", "restart"}:+ raise ValueError("Unsupported online GRPO action")+ if spec.get("precision") != {"model_compute": "bfloat16", "master_parameters": "float32"}:+ raise ValueError("The resident actor requires BF16 compute and FP32 master parameters")+ algorithm = spec["workload"]["algorithm"]+ required = {+ "advantage_estimator": "grpo",+ "ppo_epochs": 1,+ "shuffle": False,+ "loss_aggregation": "token-mean",+ "entropy_coefficient": 0.0,+ "use_reference_kl": False,+ }+ if any(algorithm.get(name) != value for name, value in required.items()):+ raise ValueError("Unsupported actor loss or update schedule")+ sampling = spec["workload"]["sampling"]+ if sampling["responses_per_prompt"] < 2 or not sampling["logprobs"]:+ raise ValueError("GRPO requires multiple responses per group and rollout log probabilities")+ if spec["workload"]["pipeline"]["sync_every_committed_updates"] != 1:+ raise ValueError("The resident runtime refreshes the rollout after every update")+++class OnlineGRPO:+ def __init__(self, args, spec):+ validate_spec(spec)+ # These existing backend switches select in-process execution and keep+ # reloadable weights in their standard layout. Set them before vLLM is+ # imported or either model is initialized.+ os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"+ os.environ["VLLM_ASCEND_ENABLE_NZ"] = "0"+ os.environ.setdefault("PYTORCH_NPU_ALLOC_CONF", "expandable_segments:True")+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")+ import torch+ import torch_npu # noqa: F401+ from transformers import AutoTokenizer+ from vllm.platforms import current_platform++ from .resident_actor import ResidentActor+ from .resident_rollout import ResidentRollout++ # CANN discovers custom kernel binaries at its first initialization.+ # An in-process actor must not initialize CANN before vLLM registers+ # the packaged operator path.+ current_platform.import_kernels()++ if torch.npu.device_count() < 2 or len(spec["resource_ceiling"]["device_ids"]) != 2:+ raise ValueError("This resident execution plan requires two projected Ascend devices")+ torch.set_num_threads(8)+ self.args, self.spec = args, spec+ self.workload = spec["workload"]+ self.action = spec["action"]+ self.tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_path, local_files_only=True)+ self.actor = ResidentActor(+ args.model_path, "npu:0", self.workload["algorithm"], self.workload["sampling"]["temperature"]+ )+ self.version = 0+ if self.action == "restart":+ self.version = self.actor.load(spec["restart_checkpoint"])+ if self.version != 8:+ raise ValueError("Restart requires a checkpoint at update eight")+ self.initial_projection = self.actor.projection()+ self.rollout = ResidentRollout(+ args.model_path,+ args.tokenizer_path,+ "npu:1",+ self.workload["sampling"],+ len(self.tokenizer),+ self.actor.model.config.tie_word_embeddings,+ )+ self.rollout.refresh(self.actor, self.version)+ self.actor_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="grpo-actor")+ # Exercise the actor's forward/backward kernels before ready, without+ # committing an update or using any workload inputs.+ warmup = [{"prompt_ids": [1, 2], "response_ids": [3, 4]}]++ def warm_actor():+ with torch.npu.device(self.actor.device):+ self.actor._forward(warmup, self.actor.temperature).sum().backward()+ self.actor.optimizer.zero_grad(set_to_none=True)+ torch.npu.synchronize(self.actor.device)++ self.actor_executor.submit(warm_actor).result()+ self.actor.restore_rng_state()++ def encode(self, question):+ ids = self.tokenizer.apply_chat_template(+ [{"role": "system", "content": self.system_prompt}, {"role": "user", "content": question}],+ tokenize=True,+ add_generation_prompt=True,+ enable_thinking=self.workload["sampling"]["enable_thinking"],+ )+ if isinstance(ids, Mapping):+ ids = ids["input_ids"]+ if not ids or len(ids) > 256 or any(type(token) is not int for token in ids):+ raise ValueError("Prompt length is outside the supported range")+ return list(ids)++ def probe(self, prompt_ids, seed, max_tokens=32):+ generated = self.rollout.generate([{"prompt_ids": prompt_ids, "seed": seed}], max_tokens=max_tokens)[0]+ row = {"prompt_ids": prompt_ids, **generated}+ # vLLM Ascend returns raw model log probabilities. Compare the live+ # actor in the same convention, independently of the training loss's+ # temperature scaling.+ actor_values = self.actor.log_probs([row], temperature=1.0)[0]+ return {+ "policy_version": self.version,+ "rollout_reported_version": generated["policy_version"],+ "actor_log_probs": actor_values,+ "rollout_log_probs": generated["old_log_probs"],+ }++ def run(self, start):+ asset = json.loads(Path(start["prompt_path"]).read_text())+ self.system_prompt = asset["system_prompt"]+ base_seed = int(asset.get("seed", self.workload["development_seed"]))+ prompts = asset["prompts"]+ if self.action == "smoke":+ batches = [prompts[: self.workload["smoke"]["prompt_groups"]]]+ elif self.action == "restart":+ batches = [prompts[-8:]]+ else:+ groups = self.workload["measurement"]["prompt_groups_per_update"]+ updates = self.workload["measurement"]["committed_updates"]+ if len(prompts) != groups * updates:+ raise ValueError("Prompt count does not match the complete online run")+ batches = [prompts[offset : offset + groups] for offset in range(0, len(prompts), groups)]+ encoded = {prompt["id"]: self.encode(prompt["question"]) for batch in batches for prompt in batch}+ responses = self.workload["sampling"]["responses_per_prompt"]+ observations = {"initial": {"parameter_projection": self.initial_projection}}+ step_metrics, policy_versions, trajectories, freshness = [], [], [], []++ def generate_batch(update, version):+ requests = [+ {+ "prompt_id": prompt["id"],+ "prompt_ids": encoded[prompt["id"]],+ "response_ordinal": response,+ "seed": base_seed + update * 100000 + version * 10000 + ordinal * responses + response,+ }+ for ordinal, prompt in enumerate(batches[update - 1])+ for response in range(responses)+ ]+ phase = time.monotonic()+ generated = self.rollout.generate(requests)+ rollout_seconds = time.monotonic() - phase+ rows = [{**request, **output} for request, output in zip(requests, generated, strict=True)]+ if any(row["policy_version"] != version for row in rows):+ raise RuntimeError("A rollout used an unexpected policy version")+ return rows, rollout_seconds++ def update_actor(rows):+ phase = time.monotonic()+ metrics = self.actor.update(rows)+ return metrics, time.monotonic() - phase++ started = time.monotonic()+ pending_rollout = generate_batch(1, self.version)+ max_lag = self.workload["pipeline"]["max_accepted_policy_lag"]+ for update, batch in enumerate(batches, 1):+ before = self.version+ rows, rollout_seconds = pending_rollout+ trajectory_version = rows[0]["policy_version"]+ lag = before - trajectory_version+ if not 0 <= lag <= max_lag:+ raise RuntimeError("Trajectory policy lag exceeds the run contract")+ phase = time.monotonic()+ for row in rows:+ row["response_text"] = self.tokenizer.decode(row["response_ids"], skip_special_tokens=True)+ score_responses(start["reward_endpoint"], rows)+ group_advantages(rows, responses, self.workload["algorithm"]["group_normalization_epsilon"])+ scoring_seconds = time.monotonic() - phase+ actor_update = self.actor_executor.submit(update_actor, rows)+ # Generate at most one batch ahead. Both operations finish before+ # publishing the actor update and refreshing the rollout weights.+ # Thus a prefetched trajectory is exactly one update old when used.+ if update < len(batches) and max_lag >= 1:+ pending_rollout = generate_batch(update + 1, before)+ metrics, actor_seconds = actor_update.result()+ self.version += 1+ phase = time.monotonic()+ self.rollout.refresh(self.actor, self.version)+ sync_seconds = time.monotonic() - phase+ observation = trajectory_observation(rows, trajectory_version, responses)+ trajectories.extend({"update": update, **row} for row in observation["trajectories"])+ if update in {1, len(batches)}:+ phase = time.monotonic()+ probe = self.probe(encoded[batches[0][0]["id"]], base_seed + 81983 + self.version)+ positions = sorted({0, len(probe["actor_log_probs"]) // 2, len(probe["actor_log_probs"]) - 1})+ selected = [+ {+ "position": index,+ "actor_log_prob": probe["actor_log_probs"][index],+ "rollout_log_prob": probe["rollout_log_probs"][index],+ }+ for index in positions+ ]+ freshness.append(+ {+ "policy_version": self.version,+ "rollout_reported_version": probe["rollout_reported_version"],+ "selected_log_probs": selected,+ "max_abs_logprob_difference": max(+ abs(item["actor_log_prob"] - item["rollout_log_prob"]) for item in selected+ ),+ "seconds": time.monotonic() - phase,+ }+ )+ if update in {1, 4, len(batches)}:+ values = self.actor.log_probs(rows[:4])+ observations[str(update)] = {+ "trajectory": observation,+ "actor_metrics": metrics,+ "parameter_projection": self.actor.projection(),+ "selected_log_probs": [+ [row[index] for index in sorted({0, len(row) // 2, len(row) - 1})] for row in values+ ],+ }+ step_metrics.append(+ {+ "update": update,+ "trajectory_policy_version": trajectory_version,+ "actor_version_before_update": before,+ "actor_version_after_update": self.version,+ "policy_lag": lag,+ "consumed_response_tokens": observation["consumed_response_tokens"],+ "accepted_trajectories": len(rows),+ "scoring_seconds": scoring_seconds,+ "rollout_generation_seconds": rollout_seconds,+ "rollout_sleep_seconds": 0.0,+ "actor_update_seconds": actor_seconds,+ "weight_sync_seconds": sync_seconds,+ "actor_metrics": metrics,+ "nonzero_advantage_groups": observation["nonzero_advantage_groups"],+ }+ )+ policy_versions.append(+ {+ "update": update,+ "trajectory": trajectory_version,+ "actor_before": before,+ "actor_after": self.version,+ "rollout_after_sync": self.rollout.version,+ "lag": lag,+ }+ )+ print(+ json.dumps(+ {+ "update": self.version,+ "rollout_seconds": rollout_seconds,+ "actor_seconds": actor_seconds,+ "sync_seconds": sync_seconds,+ **metrics,+ }+ ),+ flush=True,+ )+ if update < len(batches) and max_lag < 1:+ pending_rollout = generate_batch(update + 1, self.version)+ elapsed = time.monotonic() - started+ dtypes = self.actor.state_dtypes()+ gates = {+ "actor_initialized": True,+ "rollout_initialized": True,+ "rollouts_complete": len(trajectories) == sum(len(batch) * responses for batch in batches),+ "reward_advantage_valid": all(math.isfinite(row["advantage"]) for row in trajectories),+ "updates_complete": len(step_metrics) == len(batches),+ "weights_synced": self.rollout.version == self.version,+ "policy_lag_valid": all(0 <= item["lag"] <= max_lag for item in policy_versions),+ "freshness_valid": all(item["max_abs_logprob_difference"] <= 0.5 for item in freshness),+ "parameters_changed": self.actor.projection()["value"] != self.initial_projection["value"],+ "metrics_finite": (+ all(math.isfinite(value) for step in step_metrics for value in step["actor_metrics"].values())+ and set(dtypes["parameters"]) == {"float32"}+ and set(dtypes["optimizer"]) == {"float32"}+ ),+ "observations_complete": {"1", str(len(batches))}.issubset(observations),+ }+ checkpoint, portable = None, None+ if self.action == "correctness":+ checkpoint = str(Path(self.args.runtime_dir).parent / "checkpoints/update-8")+ portable = self.actor.save(checkpoint, self.version)+ visible = os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "")+ result = {+ "schema_version": 1,+ "kind": "online_grpo_worker",+ "action": self.action,+ "status": "passed" if all(gates.values()) else "failed",+ "gates": gates,+ "committed_updates": len(batches),+ "accepted_trajectories": len(trajectories),+ "consumed_response_tokens": sum(len(row["response_ids"]) for row in trajectories),+ "trajectory_records": trajectories,+ "end_to_end_seconds": elapsed,+ "policy_versions": policy_versions,+ "step_metrics": step_metrics,+ "observations": observations,+ "freshness_probes": freshness,+ "device_observations": {+ "actor": [{"role": "actor", "current_device": self.actor.device.index, "visible_devices": visible}],+ "rollout": [+ {"role": "rollout", "current_device": self.rollout.device.index, "visible_devices": visible}+ ],+ },+ "logical_parameter_count": self.initial_projection["logical_parameter_count"],+ "parameter_tensor_count": self.initial_projection["parameter_tensor_count"],+ "state_dtypes": dtypes,+ "checkpoint_path": checkpoint,+ "portable_actor_path": portable,+ "checkpoint_reloaded": self.action == "restart",+ "runtime_layout": {+ "actor_world_size": 1,+ "rollout_tensor_parallel_size": 1,+ "separate_devices": True,+ "overlap_rollout_and_actor": max_lag >= 1,+ "activation_checkpointing": False,+ "remove_padding": True,+ "max_tokens_per_microbatch": self.actor.max_tokens,+ "parameter_offload": False,+ "optimizer_offload": False,+ "weight_sync": "full_policy_direct_device_copy",+ },+ }+ print(+ json.dumps(+ {+ "status": result["status"],+ "gates": gates,+ "committed_updates": len(batches),+ "consumed_response_tokens": result["consumed_response_tokens"],+ "run_seconds": elapsed,+ }+ ),+ flush=True,+ )+ Path(self.args.result_dir, "run-result.json").write_text(json.dumps(result, allow_nan=False) + "\n")++ def close(self):+ self.actor_executor.shutdown(wait=True, cancel_futures=True)+ self.rollout.close()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ for name in ("run-spec", "model-path", "tokenizer-path", "runtime-dir", "result-dir", "control-socket"):+ parser.add_argument("--" + name, required=True)+ args = parser.parse_args()+ spec = json.loads(Path(args.run_spec).read_text())+ runtime = None+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ # Connect before initialization so an initialization failure also promptly+ # closes the host's read rather than leaving it blocked in accept().+ connection.connect(args.control_socket)++ def terminate(signum, frame):+ raise SystemExit(128 + signum)++ signal.signal(signal.SIGTERM, terminate)+ try:+ with connection.makefile("rb") as stream:+ runtime = OnlineGRPO(args, spec)+ send_message(connection, {"type": "ready"})+ start = receive_message(stream)+ if start.get("type") != "start":+ raise ValueError("Expected a start message")+ runtime.run(start)+ send_message(connection, {"type": "completed"})+ probe = receive_message(stream)+ if probe.get("type") != "probe" or probe.get("kind") != "freshness":+ raise ValueError("Expected a freshness probe")+ request = probe["request"]+ result = runtime.probe(+ runtime.encode(request["question"]), int(request["seed"]), int(request["max_tokens"])+ )+ send_message(connection, {"type": "probe_result", **result})+ if receive_message(stream).get("type") != "shutdown":+ raise ValueError("Expected a shutdown message")+ finally:+ if runtime is not None:+ runtime.close()+ connection.close()+++if __name__ == "__main__":+ main()diff --git a/verl/trainer/runtime/policy_transfer.py b/verl/trainer/runtime/policy_transfer.pynew file mode 100644index 0000000000000000000000000000000000000000..f7b8b3ce380b0f411cd01a24f41f0370b9900dfe--- /dev/null+++ b/verl/trainer/runtime/policy_transfer.py@@ -0,0 +1,73 @@+# Copyright 2026 The verl contributors+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0+"""Coalesced, full-parameter transfer between resident Ascend models."""++import torch+++DEFAULT_BUCKET_BYTES = 256 * 1024 * 1024+++def parameter_buckets(named_parameters, bucket_bytes=DEFAULT_BUCKET_BYTES):+ """Group whole tensors, keeping an oversized tensor in its own bucket."""+ if bucket_bytes <= 0:+ raise ValueError("A transfer bucket must have a positive size")+ bucket, size = [], 0+ for name, parameter in named_parameters:+ parameter_bytes = parameter.numel() * torch.bfloat16.itemsize+ if bucket and size + parameter_bytes > bucket_bytes:+ yield bucket+ bucket, size = [], 0+ bucket.append((name, parameter))+ size += parameter_bytes+ if bucket:+ yield bucket+++class ResidentPolicyTransfer:+ """Persistent BF16 staging buffers with one copy per bucket.++ Cast on the actor device before the peer transfer. The destination views+ have the original Transformers names and shapes, ready for vLLM's weight+ loaders to place them in fused inference parameters. Call only between+ actor updates and after all outstanding generation has completed.+ """++ def __init__(self, named_parameters, destination, bucket_bytes=DEFAULT_BUCKET_BYTES):+ parameters = list(named_parameters)+ if not parameters:+ raise ValueError("Cannot transfer an empty policy")+ self.source = parameters[0][1].device+ self.destination = torch.device(destination)+ if any(parameter.device != self.source for _, parameter in parameters):+ raise ValueError("The resident transfer requires an unsharded actor")+ self.buckets = []+ self.weights = []+ for parameters in parameter_buckets(parameters, bucket_bytes):+ count = sum(parameter.numel() for _, parameter in parameters)+ source = torch.empty(count, device=self.source, dtype=torch.bfloat16)+ destination = torch.empty(count, device=self.destination, dtype=torch.bfloat16)+ source_views = []+ offset = 0+ for name, parameter in parameters:+ count = parameter.numel()+ source_views.append((parameter, source.narrow(0, offset, count).view(parameter.shape)))+ self.weights.append((name, destination.narrow(0, offset, count).view(parameter.shape)))+ offset += count+ self.buckets.append((source, destination, source_views))++ @torch.no_grad()+ def stage(self):+ with torch.npu.device(self.source):+ for _, _, views in self.buckets:+ for parameter, view in views:+ view.copy_(parameter, non_blocking=True)+ # A single producer barrier covers every cast. The consumer stream+ # then orders the peer copies before the inference weight loaders.+ torch.npu.synchronize(self.source)+ with torch.npu.device(self.destination):+ for source, destination, _ in self.buckets:+ destination.copy_(source, non_blocking=True)+ return self.weightsdiff --git a/verl/trainer/runtime/resident_actor.py b/verl/trainer/runtime/resident_actor.pynew file mode 100644index 0000000000000000000000000000000000000000..24b14567935bcf0fc29d18a91691226efc2543b9--- /dev/null+++ b/verl/trainer/runtime/resident_actor.py@@ -0,0 +1,298 @@+# Copyright 2026 The verl contributors+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0+"""An unsharded BF16 actor with FP32 parameters and optimizer state.++Packing is performed on the host, where sequence lengths are already known.+The attention kernel receives those lengths directly, avoiding a device to host+length transfer in every decoder layer. Only response positions reach the large+vocabulary projection. Parameter casts remain in autograd, so microbatch+gradients accumulate into FP32 master parameters.+"""++import math+from collections import Counter+from copy import deepcopy+from pathlib import Path++import torch+import torch_npu+from torch import nn+from transformers import AutoModelForCausalLM+++def packed_inputs(rows, device):+ """Pack independent causal sequences and identify response predictors."""+ ids, positions, predictors, labels, ends = [], [], [], [], []+ for row in rows:+ prompt, response = row["prompt_ids"], row["response_ids"]+ if not prompt or not response:+ raise ValueError("Both prompt and response must contain tokens")+ offset = len(ids)+ sequence = prompt + response+ ids.extend(sequence)+ positions.extend(range(len(sequence)))+ predictors.extend(range(offset + len(prompt) - 1, offset + len(sequence) - 1))+ labels.extend(response)+ ends.append(len(ids))+ return (+ torch.tensor(ids, dtype=torch.long, device=device),+ torch.tensor(positions, dtype=torch.long, device=device),+ torch.tensor(predictors, dtype=torch.long, device=device),+ torch.tensor(labels, dtype=torch.long, device=device),+ tuple(ends),+ )+++def microbatches(rows, max_tokens):+ """Keep trajectory order and cap the number of packed input tokens."""+ batch, tokens = [], 0+ for row in rows:+ length = len(row["prompt_ids"]) + len(row["response_ids"])+ if batch and tokens + length > max_tokens:+ yield batch+ batch, tokens = [], 0+ batch.append(row)+ tokens += length+ if batch:+ yield batch+++def clipped_loss(log_probs, old_log_probs, advantages, token_count, clip_low=0.2, clip_high=0.2):+ """Contribution of a microbatch to the global token-mean PPO loss."""+ ratio = (log_probs.float() - old_log_probs.float()).exp()+ terms = -torch.minimum(ratio * advantages, ratio.clamp(1 - clip_low, 1 + clip_high) * advantages)+ return terms.sum() / token_count+++class PackedQwen3(nn.Module):+ """Qwen3's dense decoder using the differentiable Ascend fused kernels.++ The original Transformers module owns every parameter, including the tied+ embedding. This wrapper has no alternative model state or training rule.+ """++ def __init__(self, model):+ super().__init__()+ if model.config.model_type != "qwen3" or model.config.hidden_act != "silu":+ raise ValueError("The packed resident decoder currently supports dense Qwen3 with SiLU")+ if getattr(model.config, "sliding_window", None) or model.config.attention_dropout:+ raise ValueError("The resident decoder requires full causal attention without dropout")+ self.model = model+ self.register_buffer(+ "causal_mask", torch.ones(2048, 2048, device=model.device, dtype=torch.bool).triu_(1), persistent=False+ )++ @staticmethod+ def norm(x, module):+ return torch_npu.npu_rms_norm(x, module.weight, epsilon=module.variance_epsilon)[0]++ def forward(self, ids, positions, predictors, labels, sequence_ends, temperature):+ decoder = self.model.model+ hidden = decoder.embed_tokens(ids)+ cos, sin = decoder.rotary_emb(hidden.unsqueeze(0), positions.unsqueeze(0))+ cos, sin = cos.squeeze(0).unsqueeze(1), sin.squeeze(0).unsqueeze(1)+ for layer in decoder.layers:+ residual = hidden+ hidden = self.norm(hidden, layer.input_layernorm)+ attention = layer.self_attn+ shape = (hidden.shape[0], -1, attention.head_dim)+ query = self.norm(attention.q_proj(hidden).view(shape), attention.q_norm)+ key = self.norm(attention.k_proj(hidden).view(shape), attention.k_norm)+ value = attention.v_proj(hidden).view(shape)+ query = torch_npu.npu_rotary_mul(query, cos, sin)+ key = torch_npu.npu_rotary_mul(key, cos, sin)+ attended = torch_npu.npu_fusion_attention(+ query,+ key,+ value,+ query.shape[1],+ "TND",+ scale=attention.scaling,+ keep_prob=1.0,+ atten_mask=self.causal_mask,+ sparse_mode=3,+ actual_seq_qlen=sequence_ends,+ actual_seq_kvlen=sequence_ends,+ )[0]+ hidden = residual + attention.o_proj(attended.reshape(hidden.shape[0], -1))+ residual = hidden+ hidden = self.norm(hidden, layer.post_attention_layernorm)+ gate_up = torch.cat((layer.mlp.gate_proj(hidden), layer.mlp.up_proj(hidden)), dim=-1)+ hidden = residual + layer.mlp.down_proj(torch_npu.npu_swiglu(gate_up, dim=-1))+ hidden = self.norm(hidden, decoder.norm).index_select(0, predictors)+ # The reference actor divides its BF16 logits by a BF16 temperature.+ # Keep that rounding behavior before the FP32 cross entropy reduction.+ scale = torch.tensor(temperature, dtype=hidden.dtype, device=hidden.device)+ logits = (self.model.lm_head(hidden) / scale).float()+ return -torch_npu.npu_cross_entropy_loss(logits, labels, reduction="none")[0]+++class ResidentActor:+ def __init__(self, model_path, device, algorithm, temperature=0.7, max_tokens=2048):+ self.device = torch.device(device)+ self.algorithm = algorithm+ self.temperature = temperature+ self.max_tokens = max_tokens+ self._restored_rng = None+ with torch.npu.device(self.device):+ self.model = AutoModelForCausalLM.from_pretrained(+ model_path, dtype=torch.float32, attn_implementation="eager", local_files_only=True+ ).to(self.device)+ self.model.config.use_cache = False+ # Transformers may keep both checkpoint tensors independent even+ # when an older config declares tied embeddings. Preserve the+ # actual loaded model in rollout and in portable checkpoints.+ self.model.config.tie_word_embeddings = self.model.model.embed_tokens.weight is self.model.lm_head.weight+ self.forward_model = PackedQwen3(self.model)+ self.optimizer = torch.optim.AdamW(+ self.model.parameters(),+ lr=algorithm["learning_rate"],+ betas=tuple(algorithm["betas"]),+ weight_decay=algorithm["weight_decay"],+ foreach=True,+ )++ def _forward(self, rows, temperature):+ # Casting once per microbatch gives BF16 compute and FP32 accumulation;+ # tied parameters are preserved by functional_call's tie_weights=True.+ weights = {name: value.to(torch.bfloat16) for name, value in self.forward_model.named_parameters()}+ return torch.func.functional_call(+ self.forward_model, weights, (*packed_inputs(rows, self.device), temperature)+ )++ @torch.no_grad()+ def log_probs(self, rows, temperature=None):+ result = []+ with torch.npu.device(self.device):+ for batch in microbatches(rows, self.max_tokens):+ values = self._forward(batch, self.temperature if temperature is None else temperature).float().cpu()+ result.extend(part.tolist() for part in values.split([len(row["response_ids"]) for row in batch]))+ return result++ def update(self, rows):+ token_count = sum(len(row["response_ids"]) for row in rows)+ if token_count == 0:+ raise ValueError("Cannot update an actor without response tokens")+ with torch.npu.device(self.device):+ self.optimizer.zero_grad(set_to_none=True)+ losses, new_values = [], []+ has_gradient = False+ for batch in microbatches(rows, self.max_tokens):+ active = any(row["advantage"] != 0.0 for row in batch)+ # Zero-advantage tokens have an identically zero derivative.+ # Still evaluate their actual probabilities for loss auditing.+ with torch.set_grad_enabled(active):+ log_probs = self._forward(batch, self.temperature)+ old = torch.tensor(+ [value for row in batch for value in row["old_log_probs"]], device=self.device, dtype=torch.float32+ )+ advantages = torch.tensor(+ [row["advantage"] for row in batch for _ in row["response_ids"]],+ device=self.device,+ dtype=torch.float32,+ )+ loss = clipped_loss(+ log_probs,+ old,+ advantages,+ token_count,+ self.algorithm["clip_ratio_low"],+ self.algorithm["clip_ratio_high"],+ )+ if active:+ loss.backward()+ has_gradient = True+ losses.append(loss.detach())+ new_values.append(log_probs.detach())+ if not has_gradient:+ # A zero gradient is different from an absent gradient: AdamW+ # must still advance its moments and apply existing momentum.+ for parameter in self.model.parameters():+ parameter.grad = torch.zeros_like(parameter)+ grad_norm = torch.nn.utils.clip_grad_norm_(+ self.model.parameters(), self.algorithm["clip_grad"], error_if_nonfinite=True, foreach=True+ )+ self.optimizer.step()+ values = torch.cat(new_values).float().cpu()+ for row, part in zip(rows, values.split([len(row["response_ids"]) for row in rows]), strict=True):+ row["new_log_probs"] = part.tolist()+ loss_value, norm_value = torch.stack((torch.stack(losses).sum(), grad_norm)).float().cpu().tolist()+ self.optimizer.zero_grad(set_to_none=True)+ torch.npu.synchronize(self.device)+ return {+ "actor/pg_loss": loss_value,+ "loss": loss_value,+ "grad_norm": norm_value,+ "lr": self.optimizer.param_groups[0]["lr"],+ }++ @torch.no_grad()+ def projection(self):+ samples, factors = [], []+ parameters = list(self.model.parameters())+ with torch.npu.device(self.device):+ for ordinal, parameter in enumerate(parameters):+ flat = parameter.flatten()+ for position in sorted({0, flat.numel() // 2, flat.numel() - 1}):+ samples.append(flat[position])+ factors.append(((ordinal + position) % 31 + 1) / 31)+ values = torch.stack(samples).float().cpu().tolist()+ return {+ "value": math.fsum(value * factor for value, factor in zip(values, factors, strict=True)),+ "logical_parameter_count": sum(parameter.numel() for parameter in parameters),+ "parameter_tensor_count": len(parameters),+ }++ def state_dtypes(self):+ parameters, optimizer = Counter(), Counter()+ for parameter in self.model.parameters():+ parameters[str(parameter.dtype).removeprefix("torch.")] += parameter.numel()+ for state in self.optimizer.state.values():+ for value in state.values():+ if isinstance(value, torch.Tensor):+ optimizer[str(value.dtype).removeprefix("torch.")] += value.numel()+ return {"parameters": dict(parameters), "optimizer": dict(optimizer)}++ def save(self, path, version):+ path = Path(path)+ path.mkdir(parents=True, exist_ok=False)+ with torch.npu.device(self.device):+ optimizer = self.optimizer.state_dict()+ optimizer["state"] = {+ key: {name: value.cpu() if isinstance(value, torch.Tensor) else value for name, value in state.items()}+ for key, state in optimizer["state"].items()+ }+ torch.save(+ {+ "model": {name: value.cpu() for name, value in self.model.state_dict().items()},+ "optimizer": optimizer,+ "policy_version": version,+ "torch_rng": torch.get_rng_state(),+ "npu_rng": torch.npu.get_rng_state(self.device),+ },+ path / "training.pt.tmp",+ )+ (path / "training.pt.tmp").replace(path / "training.pt")+ portable = path / "portable-actor"+ state = {name: value.to(device="cpu", dtype=torch.bfloat16) for name, value in self.model.state_dict().items()}+ self.model.save_pretrained(portable, state_dict=state, safe_serialization=True)+ portable_config = deepcopy(self.model.config)+ portable_config.dtype = torch.bfloat16+ portable_config.save_pretrained(portable)+ return str(portable)++ def load(self, path):+ checkpoint = torch.load(Path(path) / "training.pt", map_location="cpu", weights_only=True)+ self.model.load_state_dict(checkpoint["model"])+ self.optimizer.load_state_dict(checkpoint["optimizer"])+ self._restored_rng = (checkpoint["torch_rng"], checkpoint["npu_rng"])+ return int(checkpoint["policy_version"])++ def restore_rng_state(self):+ """Restore after rollout initialization, which seeds PyTorch globally."""+ if self._restored_rng is not None:+ torch.set_rng_state(self._restored_rng[0])+ torch.npu.set_rng_state(self._restored_rng[1], self.device)+ self._restored_rng = Nonediff --git a/verl/trainer/runtime/resident_rollout.py b/verl/trainer/runtime/resident_rollout.pynew file mode 100644index 0000000000000000000000000000000000000000..0ce1e18fd094fc60f8a514df57d89d92b5e527f7--- /dev/null+++ b/verl/trainer/runtime/resident_rollout.py@@ -0,0 +1,125 @@+# Copyright 2026 The verl contributors+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0+"""Resident vLLM rollout on a dedicated device, with direct full weight refresh."""++import torch+from vllm import LLM, SamplingParams+from vllm.v1.executor.uniproc_executor import UniProcExecutor++from .policy_transfer import ResidentPolicyTransfer+++class CurrentDeviceExecutor(UniProcExecutor):+ """Use the caller's projected device instead of implicitly selecting zero."""++ def _distributed_args(self):+ initialization, rank, _ = super()._distributed_args()+ return initialization, rank, torch.npu.current_device()+++class ResidentRollout:+ def __init__(self, model_path, tokenizer_path, device, sampling, vocab_size, tie_word_embeddings):+ self.device = torch.device(device)+ self.sampling = sampling+ self.version = 0+ self.transfer = None+ with torch.npu.device(self.device):+ self.llm = LLM(+ model=str(model_path),+ tokenizer=str(tokenizer_path),+ dtype="bfloat16",+ tensor_parallel_size=1,+ distributed_executor_backend=CurrentDeviceExecutor,+ max_model_len=512,+ max_num_seqs=32,+ max_num_batched_tokens=4096,+ gpu_memory_utilization=0.60,+ enable_chunked_prefill=True,+ enable_prefix_caching=True,+ enable_sleep_mode=False,+ logprobs_mode="raw_logprobs",+ generation_config="auto",+ hf_overrides={"tie_word_embeddings": tie_word_embeddings},+ disable_log_stats=True,+ additional_config={"enable_async_exponential": True},+ compilation_config={+ "mode": 3,+ "cudagraph_mode": "FULL_DECODE_ONLY",+ "cudagraph_capture_sizes": [1, 2, 4, 8, 16, 32],+ },+ )+ # This execution plan explicitly disables engine multiprocessing;+ # apply_model returns the resident object without serialization.+ self.model = self.llm.apply_model(lambda model: model)[0]+ if next(self.model.parameters()).device != self.device:+ raise RuntimeError("Rollout model was initialized on an unexpected device")+ self.parameter_names = {name for name, _ in self.model.named_parameters()}+ self.vocab_size = vocab_size+ if vocab_size < self.model.config.vocab_size:+ from types import MethodType++ original = self.model.compute_logits++ def compute_logits(model, *args, **kwargs):+ logits = original(*args, **kwargs)+ logits[..., vocab_size:] = -float("inf")+ return logits++ self.model.compute_logits = MethodType(compute_logits, self.model)++ @torch.no_grad()+ def refresh(self, actor, version):+ # All generation has completed before this method. Loading every named+ # tensor also refreshes norms and the embedding/output head, and vLLM's+ # loaders handle its fused QKV and gate/up layouts.+ with torch.npu.device(self.device):+ if self.transfer is None:+ self.transfer = ResidentPolicyTransfer(actor.model.named_parameters(), self.device)+ loaded = self.model.load_weights(self.transfer.stage())+ if missing := self.parameter_names - loaded:+ raise RuntimeError(f"Policy refresh omitted rollout parameters: {sorted(missing)}")+ torch.npu.synchronize(self.device)+ if not self.llm.reset_prefix_cache():+ raise RuntimeError("Cannot refresh a rollout policy with active cached requests")+ self.version = version++ def generate(self, requests, max_tokens=None):+ with torch.npu.device(self.device):+ outputs = self.llm.generate(+ [{"prompt_token_ids": item["prompt_ids"]} for item in requests],+ [+ SamplingParams(+ n=1,+ temperature=self.sampling["temperature"],+ top_p=self.sampling["top_p"],+ top_k=self.sampling["top_k"],+ max_tokens=max_tokens or self.sampling["max_response_tokens"],+ logprobs=0,+ seed=item["seed"],+ )+ for item in requests+ ],+ use_tqdm=False,+ )+ result = []+ for output in outputs:+ response = output.outputs[0]+ if not output.finished or not response.token_ids or response.logprobs is None:+ raise RuntimeError("Rollout did not return a complete response with log probabilities")+ result.append(+ {+ "response_ids": list(response.token_ids),+ "old_log_probs": [+ float(probs[token].logprob)+ for token, probs in zip(response.token_ids, response.logprobs, strict=True)+ ],+ "policy_version": self.version,+ }+ )+ return result++ def close(self):+ with torch.npu.device(self.device):+ self.llm.llm_engine.engine_core.shutdown()diff --git a/verl/trainer/runtime/tests/test_online_grpo.py b/verl/trainer/runtime/tests/test_online_grpo.pynew file mode 100644index 0000000000000000000000000000000000000000..3eb3e147295f2bbe0aca5ab493657c3a9508fd86--- /dev/null+++ b/verl/trainer/runtime/tests/test_online_grpo.py@@ -0,0 +1,97 @@+# Copyright 2026 The verl contributors+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0+"""Exercise the execution schedule without allocating a model or a device."""++import json+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespace++import pytest+import torch++from verl.trainer.runtime import online_grpo+++@pytest.mark.parametrize("max_lag", [0, 1])+def test_schedule_refreshes_every_update_and_preserves_seed_provenance(tmp_path, monkeypatch, max_lag):+ class Actor:+ device = torch.device("npu:0")+ max_tokens = 2048++ def __init__(self):+ self.updates = 0++ def update(self, rows):+ self.updates += 1+ for row in rows:+ row["new_log_probs"] = list(row["old_log_probs"])+ return {"loss": 0.0, "actor/pg_loss": 0.0}++ def projection(self):+ return {"value": self.updates, "logical_parameter_count": 1, "parameter_tensor_count": 1}++ def log_probs(self, rows, temperature=None):+ return [list(row["old_log_probs"]) for row in rows]++ def state_dtypes(self):+ return {"parameters": {"float32": 1}, "optimizer": {"float32": 2}}++ class Rollout:+ device = torch.device("npu:1")++ def __init__(self):+ self.version = 0+ self.refreshes = []++ def generate(self, requests, max_tokens=None):+ return [+ {"response_ids": [3, 4], "old_log_probs": [-0.5, -0.2], "policy_version": self.version}+ for _ in requests+ ]++ def refresh(self, actor, version):+ assert actor.updates == version+ self.version = version+ self.refreshes.append(version)++ runtime = online_grpo.OnlineGRPO.__new__(online_grpo.OnlineGRPO)+ runtime.actor, runtime.rollout = Actor(), Rollout()+ runtime.version = 0+ runtime.initial_projection = runtime.actor.projection()+ runtime.action = "measurement"+ runtime.args = SimpleNamespace(result_dir=tmp_path, runtime_dir=tmp_path / "runtime")+ runtime.workload = {+ "development_seed": 17,+ "measurement": {"prompt_groups_per_update": 8, "committed_updates": 8},+ "sampling": {"responses_per_prompt": 4},+ "algorithm": {"group_normalization_epsilon": 1e-6},+ "pipeline": {"max_accepted_policy_lag": max_lag},+ }+ runtime.encode = lambda question: [1, 2]+ runtime.tokenizer = SimpleNamespace(decode=lambda ids, **kwargs: "answer")+ prompts = [{"id": str(index), "question": "A question"} for index in range(64)]+ path = tmp_path / "prompts.json"+ path.write_text(json.dumps({"prompts": prompts, "seed": 17, "system_prompt": "Solve"}))+ scored = []++ def score(endpoint, rows):+ scored.extend((row["prompt_id"], row["response_ordinal"]) for row in rows)+ for index, row in enumerate(rows):+ row["reward"] = float(index % 2)++ monkeypatch.setattr(online_grpo, "score_responses", score)+ with ThreadPoolExecutor(max_workers=1) as runtime.actor_executor:+ runtime.run({"prompt_path": str(path), "reward_endpoint": {}})+ result = json.loads((tmp_path / "run-result.json").read_text())+ assert result["status"] == "passed"+ assert runtime.rollout.refreshes == list(range(1, 9))+ assert len(scored) == len(set(scored)) == 256+ assert [item["lag"] for item in result["policy_versions"]] == [0] + [max_lag] * 7+ for row in result["trajectory_records"]:+ prompt_ordinal = int(row["prompt_id"]) % 8+ assert row["seed"] == (+ 17 + row["update"] * 100000 + row["policy_version"] * 10000+ + prompt_ordinal * 4 + row["response_ordinal"]+ )diff --git a/verl/trainer/runtime/tests/test_policy_transfer.py b/verl/trainer/runtime/tests/test_policy_transfer.pynew file mode 100644index 0000000000000000000000000000000000000000..53ff20f6b1e56727e66d6892cf1e387f552a9bba--- /dev/null+++ b/verl/trainer/runtime/tests/test_policy_transfer.py@@ -0,0 +1,36 @@+# Copyright 2026 The verl contributors+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0++import pytest+import torch++from verl.trainer.runtime.policy_transfer import ResidentPolicyTransfer, parameter_buckets+++def test_buckets_preserve_names_and_oversized_tensors():+ parameters = [(str(index), torch.empty(size)) for index, size in enumerate([3, 2, 9, 1, 2])]+ buckets = list(parameter_buckets(parameters, bucket_bytes=10))+ assert [[name for name, _ in bucket] for bucket in buckets] == [["0", "1"], ["2"], ["3", "4"]]+ with pytest.raises(ValueError, match="positive"):+ list(parameter_buckets(parameters, bucket_bytes=0))+++@pytest.mark.skipif(torch.npu.device_count() < 2, reason="Requires two projected Ascend devices")+def test_npu_full_transfer_refreshes_every_tensor():+ parameters = [+ ("embedding", torch.arange(21, dtype=torch.float32, device="npu:0").reshape(7, 3) / 17),+ ("norm", torch.ones(3, dtype=torch.float32, device="npu:0")),+ ("head", torch.arange(12, dtype=torch.float32, device="npu:0").reshape(3, 4) / 13),+ ]+ transfer = ResidentPolicyTransfer(parameters, "npu:1", bucket_bytes=32)+ for _ in range(2):+ weights = transfer.stage()+ torch.npu.synchronize(1)+ assert [name for name, _ in weights] == [name for name, _ in parameters]+ for (_, source), (_, received) in zip(parameters, weights, strict=True):+ assert received.device == torch.device("npu:1")+ assert received.dtype == torch.bfloat16+ torch.testing.assert_close(received.cpu(), source.bfloat16().cpu(), rtol=0, atol=0)+ source.add_(0.125)diff --git a/verl/trainer/runtime/tests/test_resident_actor.py b/verl/trainer/runtime/tests/test_resident_actor.pynew file mode 100644index 0000000000000000000000000000000000000000..aec73520460ecca5a7b8e6407581a29ed9f7d0d4--- /dev/null+++ b/verl/trainer/runtime/tests/test_resident_actor.py@@ -0,0 +1,160 @@+# Copyright 2026 The verl contributors+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0+"""Numerical and packing checks for the resident execution plan."""++import copy+import math+from collections import UserDict++import pytest+import torch++from verl.trainer.runtime.online_grpo import OnlineGRPO, group_advantages+from verl.trainer.runtime.resident_actor import PackedQwen3, ResidentActor, clipped_loss, microbatches, packed_inputs+++def test_response_predictors_and_sequence_boundaries():+ rows = [+ {"prompt_ids": [10, 11], "response_ids": [12, 13, 14]},+ {"prompt_ids": [20, 21, 22], "response_ids": [23]},+ ]+ ids, positions, predictors, labels, ends = packed_inputs(rows, "cpu")+ assert ids.tolist() == [10, 11, 12, 13, 14, 20, 21, 22, 23]+ assert positions.tolist() == [0, 1, 2, 3, 4, 0, 1, 2, 3]+ assert predictors.tolist() == [1, 2, 3, 7]+ assert labels.tolist() == [12, 13, 14, 23]+ assert ends == (5, 9)+ assert list(microbatches(rows, 8)) == [[rows[0]], [rows[1]]]+ assert list(microbatches(rows, 9)) == [rows]+ with pytest.raises(ValueError, match="contain tokens"):+ packed_inputs([{"prompt_ids": [], "response_ids": [1]}], "cpu")+++def test_group_normalization_and_zero_variance():+ rows = [{"prompt_id": "a", "reward": value} for value in [0.0, 0.0, 1.0, 1.0]]+ rows += [{"prompt_id": "b", "reward": 1.0} for _ in range(4)]+ group_advantages(rows, 4, 1e-6)+ expected = 0.5 / (math.sqrt(1 / 3) + 1e-6)+ assert [row["advantage"] for row in rows] == pytest.approx([-expected, -expected, expected, expected, 0, 0, 0, 0])+ with pytest.raises(ValueError, match="Incomplete"):+ group_advantages(rows[:3], 4, 1e-6)+++@pytest.mark.parametrize("encoding", [[1, 2, 3], UserDict({"input_ids": [1, 2, 3], "attention_mask": [1, 1, 1]})])+def test_chat_encoding_accepts_tokenizer_mappings(encoding):+ class Tokenizer:+ def apply_chat_template(self, *args, **kwargs):+ return encoding++ runtime = OnlineGRPO.__new__(OnlineGRPO)+ runtime.tokenizer = Tokenizer()+ runtime.system_prompt = "Solve the question."+ runtime.workload = {"sampling": {"enable_thinking": False}}+ assert runtime.encode("What is one plus two?") == [1, 2, 3]+++def test_microbatch_loss_and_gradients_use_global_token_denominator():+ old = torch.tensor([-0.2, -1.0, -0.3, -0.7, -0.4])+ new = (old + torch.tensor([0.0, -0.6, 0.5, -0.4, 0.7])).requires_grad_()+ advantages = torch.tensor([1.0, -1.0, -1.0, 1.0, 0.0])+ expected_terms = []+ for before, after, advantage in zip(old.tolist(), new.tolist(), advantages.tolist(), strict=True):+ ratio = math.exp(after - before)+ expected_terms.append(-min(ratio * advantage, min(max(ratio, 0.8), 1.2) * advantage))+ full = clipped_loss(new, old, advantages, 5)+ assert full.item() == pytest.approx(sum(expected_terms) / 5)+ full.backward()+ gradient = new.grad.clone()+ new.grad = None+ (clipped_loss(new[:2], old[:2], advantages[:2], 5) + clipped_loss(new[2:], old[2:], advantages[2:], 5)).backward()+ torch.testing.assert_close(new.grad, gradient)+ # The token with zero advantage must contribute neither a loss nor a gradient.+ assert new.grad[-1] == 0+++@pytest.mark.skipif(not torch.npu.is_available(), reason="Requires an Ascend device")+def test_npu_packed_decoder_matches_independent_transformers_sequences():+ from transformers import Qwen3Config, Qwen3ForCausalLM++ torch.manual_seed(17)+ config = Qwen3Config(+ vocab_size=128, hidden_size=128, intermediate_size=256, num_hidden_layers=2,+ num_attention_heads=2, num_key_value_heads=1, head_dim=64,+ max_position_embeddings=64, tie_word_embeddings=False,+ )+ config._attn_implementation = "eager"+ device = torch.device("npu:0")+ with torch.npu.device(device):+ reference = Qwen3ForCausalLM(config).to(device=device, dtype=torch.bfloat16)+ model = copy.deepcopy(reference).float()+ wrapper = PackedQwen3(model)+ rows = [+ {"prompt_ids": [1, 2, 3], "response_ids": [4, 5, 6]},+ {"prompt_ids": [7], "response_ids": [8, 9]},+ ]+ parameters = {name: value.bfloat16() for name, value in wrapper.named_parameters()}+ packed = torch.func.functional_call(wrapper, parameters, (*packed_inputs(rows, device), 1.0))+ independent = []+ for row in rows:+ ids = torch.tensor([row["prompt_ids"] + row["response_ids"]], device=device)+ logits = reference(ids, use_cache=False).logits[0, len(row["prompt_ids"]) - 1 : -1].float()+ targets = torch.tensor(row["response_ids"], device=device)+ independent.append(logits.log_softmax(-1).gather(-1, targets[:, None]).squeeze(-1))+ independent = torch.cat(independent)+ torch.testing.assert_close(packed.float(), independent.float(), atol=0.015, rtol=0.005)+ packed.sum().backward()+ independent.sum().backward()+ packed_grads = torch.cat([parameter.grad.flatten() for parameter in model.parameters()])+ reference_grads = torch.cat([parameter.grad.float().flatten() for parameter in reference.parameters()])+ assert (packed_grads - reference_grads).norm() / reference_grads.norm() < 0.05+ assert all(parameter.dtype == parameter.grad.dtype == torch.float32 for parameter in model.parameters())+++@pytest.mark.skipif(not torch.npu.is_available(), reason="Requires an Ascend device")+def test_npu_checkpoint_and_zero_advantage_preserve_adam_momentum(tmp_path):+ from transformers import AutoConfig, Qwen3Config, Qwen3ForCausalLM++ config = Qwen3Config(+ vocab_size=128, hidden_size=128, intermediate_size=256, num_hidden_layers=1,+ num_attention_heads=2, num_key_value_heads=1, head_dim=64,+ max_position_embeddings=64, tie_word_embeddings=False,+ )+ initial = tmp_path / "initial"+ torch.manual_seed(12)+ Qwen3ForCausalLM(config).bfloat16().save_pretrained(initial)+ algorithm = {+ "learning_rate": 1e-6, "betas": [0.9, 0.999], "weight_decay": 0.01,+ "clip_grad": 1.0, "clip_ratio_low": 0.2, "clip_ratio_high": 0.2,+ }+ actor = ResidentActor(initial, "npu:0", algorithm, max_tokens=8)+ rows = [+ {"prompt_ids": [1, 2, 3], "response_ids": [4, 5, 6], "advantage": 1.0},+ {"prompt_ids": [7, 8, 9], "response_ids": [10, 11, 12], "advantage": -1.0},+ ]+ for row, values in zip(rows, actor.log_probs(rows), strict=True):+ row["old_log_probs"] = values+ assert actor.update(rows)["grad_norm"] > 0+ checkpoint = tmp_path / "checkpoint"+ portable = actor.save(checkpoint, 1)+ assert AutoConfig.from_pretrained(portable).dtype == torch.bfloat16+ restored = ResidentActor(initial, "npu:0", algorithm, max_tokens=8)+ assert restored.load(checkpoint) == 1+ restored.restore_rng_state()+ assert restored.projection() == actor.projection()+ # Even with zero advantages, AdamW must advance its moments and apply the+ # momentum from the preceding update. Compare to an explicit zero gradient.+ for row in rows:+ row["advantage"] = 0.0+ assert actor.update(rows)["grad_norm"] == 0+ with torch.npu.device(restored.device):+ for parameter in restored.model.parameters():+ parameter.grad = torch.zeros_like(parameter)+ restored.optimizer.step()+ for actual, expected in zip(actor.model.parameters(), restored.model.parameters(), strict=True):+ torch.testing.assert_close(actual, expected, rtol=0, atol=0)+ actual_state = actor.optimizer.state[actual]+ expected_state = restored.optimizer.state[expected]+ for name in actual_state:+ torch.testing.assert_close(actual_state[name], expected_state[name], rtol=0, atol=0)