Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
verl · 6 changed files
Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d
diff --git a/verl/trainer/runtime/README.md b/verl/trainer/runtime/README.mdnew file mode 100644index 0000000000000000000000000000000000000000..52d00b68776bcc436614f059e2a3e26f9b556032--- /dev/null+++ b/verl/trainer/runtime/README.md@@ -0,0 +1,109 @@+# Resident online PPO on Ascend++`online_ppo` runs a dense Qwen3 actor, reference, token-value critic and frozen+sequence reward classifier on two projected Ascend devices. It provides an+optional runtime entry point for a single foreground process.++The first device owns the actor and its FP32 AdamW master parameters and+moments. The rollout policy uses that same master module under BF16 autocast+with a bounded KV cache. Generation finishes before training, so each rollout+uses exactly the last committed actor version. The second device owns the+frozen reference, critic and frozen reward model. Scoring and actor/critic+backward passes can overlap across devices. Parameters and optimizer state+stay on their device.++Decode steps replay an NPU graph with fixed input, KV and BF16 linear-weight+storage. Linear weights are copied from the live masters after each optimizer+step, avoiding full-model casts on every generated token. Parameter mutation+counters check that these buffers are current before accepting a probe.+Sampling happens outside the captured graph.++The decoder uses Ascend's fused grouped-query attention, RMS normalization,+rotary embedding and SiLU kernels. Vocabulary projection only covers the+response positions during PPO scoring and training.++The runtime preserves temperature-scaled policy log probabilities, top-k then+top-p sampling, EOS termination, reference KL in token rewards, masked GAE,+and the clipped actor and value objectives from `verl.trainer.ppo.core_algos`.+Microbatches contain at most 32 trajectories. Each contributes its fraction of+the complete batch's response tokens to the loss. Gradients accumulate in FP32+before a single clipped AdamW step. Reward inputs use the reward tokenizer's+chat template, and the chosen-class score is returned without a classification activation, matching+the reward loop's `use_activation=False` contract.++## Control interface++```sh+python -m verl.trainer.runtime.online_ppo \+ --run-spec RUN_SPEC.json \+ --policy-model-path POLICY_DIRECTORY \+ --auxiliary-model-path AUXILIARY_DIRECTORY \+ --tokenizer-path TOKENIZER_DIRECTORY \+ --runtime-dir RUNTIME_DIRECTORY \+ --result-dir RESULT_DIRECTORY \+ --control-socket CONTROL_SOCKET+```++The foreground process connects to the Unix socket. After loading all roles+it sends `ready`, accepts a `start` message with the input path and sampling+seed, writes `run-result.json`, and sends `completed`. Subsequent `probe`+messages evaluate continuation log probabilities on the live FP32 master+module on the NPU, in the same precision as the portable export. PPO training+and rollout use BF16 autocast, including BF16 attention and KV storage.+`shutdown` joins the execution thread and synchronizes both devices before+exiting. The runtime creates no child processes or distributed services.++Correctness runs save FP32 master weights, both AdamW optimizers, version,+algorithm settings and random states, together with a Transformers-compatible+actor. A completion marker is written only after both artifacts are saved.+Restart restores the masters and moments before accepting new input. Frozen+roles are loaded from their original artifacts and checked for parameter+mutations and changes to bounded weight samples.++## Focused checks++```sh+python -m pytest verl/trainer/runtime/test_online_ppo.py -q+python -m pytest tests/trainer/ppo/test_core_algos_on_cpu.py -q -k 'gae or kl_penalty'+```++The decoder and device-optimizer checks require an Ascend device. They compare+padded forward outputs and backward gradients to Transformers, and verify+cached decoding against a full forward. Other checks cover FP32 accumulation+and optimizer restart, EOS/padding masks, nucleus sampling and frozen weights.+The graph check reuses a captured graph after a weight update and checks+multiple decode positions against a full forward pass.++## Supplied workload validation++Validated on two Ascend 910B1 devices using the supplied formal workload:++| Measurement | Observed result |+| --- | ---: |+| Actor / critic updates | 8 / 8 |+| Accepted trajectories | 256 |+| Consumed response tokens | 16,384 |+| Host-timed end-to-end duration | 74.263 s |+| End-to-end throughput | 220.622 response tokens/s |+| PPO duration | 19.090 s |+| Peak allocated memory, actor / auxiliary NPU | 47.8 / 27.1 GB |++Smoke and full correctness passed every gate. The update-eight portable actor+matched the live NPU probe within 0.000177 log-probability units. A fresh process+restored both optimizers and completed update nine. Frozen-role and cleanup+checks passed. These are measurements of this runtime, with startup and shutdown+included in the end-to-end interval.++Focused validation covered 10 runtime tests, seven upstream PPO GAE/KL tests,+and eight upstream Transformers candidate-generator tests. The affected decoder+and graph cases were rerun after adding the persistent BF16 weight buffers.++The public checks can be run from the supplied task environment:++```sh+export TASK_EXTERNAL_INPUT_ROOT="$TASK_DIR/workloads/formal"+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..67edb5ddb7b51edfc6dd19ee500a6b3a6ceb8bed--- /dev/null+++ b/verl/trainer/runtime/__init__.py@@ -0,0 +1,14 @@+# 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+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Small, persistent runtimes for colocated online training."""diff --git a/verl/trainer/runtime/ascend_decoder.py b/verl/trainer/runtime/ascend_decoder.pynew file mode 100644index 0000000000000000000000000000000000000000..dc6becf7a34958c90a8286e5c5b0f74acf7bbe4e--- /dev/null+++ b/verl/trainer/runtime/ascend_decoder.py@@ -0,0 +1,281 @@+# 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+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Ascend execution adapter for dense Qwen3 decoders.++The Hugging Face module remains the owner of every parameter. Training,+generation and portable export therefore use the same weights, including tied+embeddings. Only execution is specialized: masks and rotary embeddings are+prepared once per batch, attention keeps grouped KV heads, and generation uses+a bounded cache without reallocating it at every token.+"""++from dataclasses import dataclass++import torch+import torch.nn.functional as F+import torch_npu+++@dataclass+class DecoderCache:+ keys: list[torch.Tensor]+ values: list[torch.Tensor]+ length: int = 0+++class AscendDecoder:+ def __init__(self, module):+ config = module.config+ if config.model_type != "qwen3" or getattr(config, "use_sliding_window", False):+ raise ValueError("AscendDecoder requires a dense Qwen3 model with full attention")+ if config.hidden_act != "silu" or config.attention_dropout != 0:+ raise ValueError("AscendDecoder requires SiLU and zero attention dropout")+ self.module = module+ self.model = module.model+ self.config = config+ self.device = next(module.parameters()).device+ self.dtype = torch.bfloat16++ def new_cache(self, batch_size: int, capacity: int) -> DecoderCache:+ if batch_size <= 0 or capacity <= 0:+ raise ValueError("KV cache dimensions must be positive")+ shape = (batch_size, self.config.num_key_value_heads, capacity, self.config.head_dim)+ return DecoderCache(+ [torch.zeros(shape, device=self.device, dtype=self.dtype) for _ in self.model.layers],+ [torch.zeros(shape, device=self.device, dtype=self.dtype) for _ in self.model.layers],+ )++ @staticmethod+ def _norm(hidden, norm):+ return torch_npu.npu_rms_norm(+ hidden.to(norm.weight.dtype), norm.weight, epsilon=norm.variance_epsilon+ )[0]++ @staticmethod+ def linear(layer, hidden, weights=None):+ if weights is None:+ return layer(hidden)+ return F.linear(hidden, weights[layer.weight], layer.bias)++ def hidden(+ self,+ input_ids,+ attention_mask,+ position_ids=None,+ cache: DecoderCache | None = None,+ cache_position=None,+ linear_weights=None,+ ):+ batch_size, query_length = input_ids.shape+ offset = cache.length if cache is not None else 0+ key_length = offset + query_length+ if cache is not None and torch.is_grad_enabled():+ raise ValueError("KV caches are only supported for inference")+ if cache_position is not None:+ if cache is None or query_length != 1 or position_ids is None:+ raise ValueError("Indexed decoding requires a cache, one token and explicit positions")+ key_length = cache.keys[0].shape[2]+ elif cache is not None and key_length > cache.keys[0].shape[2]:+ raise ValueError("KV cache capacity exceeded")+ if position_ids is None:+ position_ids = attention_mask.long().cumsum(-1).sub(1).clamp_min(0)[:, offset:key_length]+ hidden = self.model.embed_tokens(input_ids)+ cos, sin = self.model.rotary_emb(hidden, position_ids)+ if cache_position is None:+ keys = torch.arange(key_length, device=input_ids.device)+ queries = torch.arange(offset, key_length, device=input_ids.device)+ masked = (keys[None, :] > queries[:, None])[None, None, :, :]+ masked = masked | ~attention_mask[:, None, None, :key_length].bool()+ # Left-padding queries are never consumed, but must have a finite+ # attention result so that their backward pass cannot propagate NaNs.+ masked = masked & ~((queries[:, None] == keys[None, :])[None, None, :, :])+ else:+ # Fixed-size decode uses a device-side mask and write index. Neither+ # the KV shape nor any captured host scalar changes between tokens.+ masked = ~attention_mask[:, None, None, :].bool()+ masked = masked.contiguous()+ head_dim = self.config.head_dim+ for index, layer in enumerate(self.model.layers):+ residual = hidden+ normalized = self._norm(hidden, layer.input_layernorm)+ attn = layer.self_attn+ query = self.linear(attn.q_proj, normalized, linear_weights).view(batch_size, query_length, -1, head_dim)+ key = self.linear(attn.k_proj, normalized, linear_weights).view(batch_size, query_length, -1, head_dim)+ value = self.linear(attn.v_proj, normalized, linear_weights).view(batch_size, query_length, -1, head_dim)+ query = self._norm(query, attn.q_norm).transpose(1, 2).contiguous()+ key = self._norm(key, attn.k_norm).transpose(1, 2).contiguous()+ value = value.transpose(1, 2).contiguous()+ query = torch_npu.npu_rotary_mul(query, cos[:, None], sin[:, None])+ key = torch_npu.npu_rotary_mul(key, cos[:, None], sin[:, None])+ # FP32 master modules keep the residual stream and normalization+ # in FP32. Attention, like the linear layers under autocast, uses+ # BF16 compute and BF16 KV storage.+ query, key, value = query.to(self.dtype), key.to(self.dtype), value.to(self.dtype)+ if cache is not None:+ if cache_position is None:+ cache.keys[index][:, :, offset:key_length].copy_(key)+ cache.values[index][:, :, offset:key_length].copy_(value)+ if offset:+ key = cache.keys[index][:, :, :key_length].contiguous()+ value = cache.values[index][:, :, :key_length].contiguous()+ else:+ write_index = cache_position.view(1, 1, 1, 1).expand_as(key)+ cache.keys[index].scatter_(2, write_index, key)+ cache.values[index].scatter_(2, write_index, value)+ key, value = cache.keys[index], cache.values[index]+ attention = (+ torch_npu.npu_fusion_attention_v3 if cache_position is not None else torch_npu.npu_fusion_attention+ )+ attended = attention(+ query,+ key,+ value,+ self.config.num_attention_heads,+ "BNSD",+ atten_mask=masked,+ scale=attn.scaling,+ keep_prob=1.0,+ )[0]+ attended = attended.transpose(1, 2).reshape(batch_size, query_length, -1)+ hidden = residual + self.linear(attn.o_proj, attended, linear_weights)+ residual = hidden+ normalized = self._norm(hidden, layer.post_attention_layernorm)+ gate_up = torch.cat(+ (+ self.linear(layer.mlp.gate_proj, normalized, linear_weights),+ self.linear(layer.mlp.up_proj, normalized, linear_weights),+ ),+ dim=-1,+ )+ hidden = residual + self.linear(layer.mlp.down_proj, torch_npu.npu_swiglu(gate_up, dim=-1), linear_weights)+ if cache is not None and cache_position is None:+ cache.length = key_length+ return self._norm(hidden, self.model.norm)++ def log_probs(self, input_ids, attention_mask, response_length, temperature=1.0):+ hidden = self.hidden(input_ids, attention_mask)+ selected = hidden[:, -response_length - 1 : -1]+ # Do not materialize vocabulary logits for prompt tokens.+ logits = self.module.lm_head(selected).float() / temperature+ labels = input_ids[:, -response_length:]+ return -F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none").view_as(labels)++ def values(self, input_ids, attention_mask, response_length):+ hidden = self.hidden(input_ids, attention_mask)+ return self.module.score(hidden[:, -response_length - 1 : -1]).squeeze(-1).float()++ def scores(self, input_ids, attention_mask):+ hidden = self.hidden(input_ids, attention_mask)+ # Batches are left padded, so the last token is the pooling token.+ return self.module.score(hidden[:, -1]).float()[:, -1]+++class GraphedDecode:+ """Replay a fixed-shape decode graph against the current actor weights.++ Only model computation is captured. Sampling remains outside the graph so+ normal device RNG semantics are preserved. Input buffers, KV caches and+ BF16 linear weights retain their storage addresses across online updates.+ The linear weights are refreshed from live masters at each update, avoiding+ a model-sized FP32-to-BF16 conversion on every generated token.+ """++ def __init__(self, decoder, batch_size, capacity):+ self.decoder = decoder+ self.cache = decoder.new_cache(batch_size, capacity)+ self.tokens = torch.zeros((batch_size, 1), dtype=torch.long, device=decoder.device)+ self.positions = torch.zeros_like(self.tokens)+ self.index = torch.zeros(1, dtype=torch.long, device=decoder.device)+ self.mask = torch.zeros((batch_size, capacity), dtype=torch.bool, device=decoder.device)+ self.linear_weights = {+ layer.weight: torch.empty_like(layer.weight, dtype=torch.bfloat16)+ for layer in decoder.module.modules()+ if isinstance(layer, torch.nn.Linear)+ }+ self.weight_versions = None+ self.graph = None+ self.output = None++ @property+ def weights_current(self):+ return self.weight_versions == tuple(parameter._version for parameter in self.linear_weights)++ @torch.no_grad()+ def refresh_weights(self):+ if not self.weights_current:+ for parameter, weight in self.linear_weights.items():+ weight.copy_(parameter)+ self.weight_versions = tuple(parameter._version for parameter in self.linear_weights)++ @torch.no_grad()+ def prefill(self, input_ids, attention_mask):+ self.refresh_weights()+ self.cache.length = 0+ self.prompt_length = input_ids.shape[1]+ self.prompt_lengths = attention_mask.long().sum(-1, keepdim=True)+ self.mask.zero_()+ self.mask[:, : self.prompt_length].copy_(attention_mask)+ hidden = self.decoder.hidden(input_ids, attention_mask, cache=self.cache, linear_weights=self.linear_weights)+ return self.decoder.linear(self.decoder.module.lm_head, hidden[:, -1], self.linear_weights)++ @torch.autocast("npu", dtype=torch.bfloat16, cache_enabled=False)+ def _forward(self):+ # Linear weights already use persistent BF16 storage. Keep any other+ # autocast conversions in the graph instead of retaining cached values+ # from the first capture.+ hidden = self.decoder.hidden(+ self.tokens,+ self.mask,+ self.positions,+ cache=self.cache,+ cache_position=self.index,+ linear_weights=self.linear_weights,+ )+ return self.decoder.linear(self.decoder.module.lm_head, hidden[:, -1], self.linear_weights)++ @torch.no_grad()+ def decode(self, tokens, response_index):+ position = self.prompt_length + response_index+ if position >= self.mask.shape[1]:+ raise ValueError("Decode position exceeds the KV cache capacity")+ self.tokens.copy_(tokens[:, None])+ self.positions.copy_(self.prompt_lengths + response_index)+ self.index.fill_(position)+ self.mask[:, position] = True+ if self.graph is None:+ stream = torch.npu.Stream(device=self.decoder.device)+ stream.wait_stream(torch.npu.current_stream(self.decoder.device))+ with torch.npu.stream(stream):+ for _ in range(3):+ self._forward()+ torch.npu.current_stream(self.decoder.device).wait_stream(stream)+ self.graph = torch.npu.NPUGraph()+ with torch.npu.graph(self.graph, stream=stream):+ self.output = self._forward()+ self.graph.replay()+ return self.output+++def sample_top_k_top_p(logits, *, temperature, top_k, top_p, generator=None):+ """Sample the exact top-k then nucleus distribution on the device."""+ if temperature <= 0 or not 0 < top_p <= 1 or not 0 < top_k <= logits.shape[-1]:+ raise ValueError("Invalid sampling parameters")+ values, indices = torch.topk(logits.float() / temperature, top_k, dim=-1, sorted=True)+ probabilities = values.softmax(-1)+ remove = probabilities.cumsum(-1) > top_p+ remove[:, 1:] = remove[:, :-1].clone()+ remove[:, 0] = False+ probabilities = values.masked_fill(remove, -torch.inf).softmax(-1)+ selected = torch.multinomial(probabilities, 1, generator=generator)+ return indices.gather(-1, selected).squeeze(-1)diff --git a/verl/trainer/runtime/master_optimizer.py b/verl/trainer/runtime/master_optimizer.pynew file mode 100644index 0000000000000000000000000000000000000000..4a38c0f128077b2227960f7edcfec7d71be52af7--- /dev/null+++ b/verl/trainer/runtime/master_optimizer.py@@ -0,0 +1,76 @@+# 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+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Resident FP32 AdamW state for BF16 modules or FP32 modules under autocast."""++import torch+++class MasterAdamW:+ """Accumulate microbatch gradients in FP32 and round only after an update.++ Master weights, moments and gradients live on the compute device. An FP32+ module owns its masters directly; a BF16 module uses separate masters and+ receives rounded weights after each step. Actor and rollout can share the+ same compute module in either case.+ """++ def __init__(self, module, learning_rate, *, weight_decay=0.01):+ self.parameters = [parameter for parameter in module.parameters() if parameter.requires_grad]+ self.masters = [+ parameter if parameter.dtype == torch.float32 else torch.nn.Parameter(parameter.detach().float().clone())+ for parameter in self.parameters+ ]+ self.optimizer = torch.optim.AdamW(self.masters, lr=learning_rate, weight_decay=weight_decay, foreach=True)++ @torch.no_grad()+ def accumulate(self):+ for parameter, master in zip(self.parameters, self.masters, strict=True):+ if parameter is master:+ # Autocast already accumulates this parameter's gradient in+ # FP32, including accumulation across microbatches.+ continue+ if parameter.grad is not None:+ if master.grad is None:+ master.grad = parameter.grad.float()+ else:+ master.grad.add_(parameter.grad)+ parameter.grad = None++ @torch.no_grad()+ def step(self):+ norm = torch.nn.utils.clip_grad_norm_(self.masters, 1.0, error_if_nonfinite=True, foreach=True)+ self.optimizer.step()+ for parameter, master in zip(self.parameters, self.masters, strict=True):+ if parameter is not master:+ parameter.copy_(master)+ self.optimizer.zero_grad(set_to_none=True)+ return float(norm)++ def state_dict(self):+ return {+ "masters": [parameter.detach().cpu() for parameter in self.masters],+ "optimizer": self.optimizer.state_dict(),+ }++ @torch.no_grad()+ def load_state_dict(self, state):+ if len(state["masters"]) != len(self.masters):+ raise ValueError("Checkpoint master parameter count differs")+ for parameter, master, saved in zip(self.parameters, self.masters, state["masters"], strict=True):+ if master.shape != saved.shape:+ raise ValueError("Checkpoint master parameter shape differs")+ master.copy_(saved)+ if parameter is not master:+ parameter.copy_(master)+ self.optimizer.load_state_dict(state["optimizer"])diff --git a/verl/trainer/runtime/online_ppo.py b/verl/trainer/runtime/online_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..6be73168ed7ef5b416dd8436c850e4b2652362d1--- /dev/null+++ b/verl/trainer/runtime/online_ppo.py@@ -0,0 +1,585 @@+# 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+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Persistent, two-device online PPO with resident model and optimizer state.++The foreground process owns the control connection and both device execution+threads. There are no detached services or distributed process groups. The+actor is also the rollout policy; generation finishes before the single PPO+epoch and sees the committed weights on the next iteration.++Run with ``python -m verl.trainer.runtime.online_ppo --help`` for the socket+runtime interface. Inputs and sampling seeds are supplied only after models+have loaded and the runtime has sent ``ready``.+"""++import argparse+import hashlib+import json+import random+import socket+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import numpy as np+import torch+import torch_npu # noqa: F401+from transformers import (+ AutoConfig,+ AutoModelForCausalLM,+ AutoModelForSequenceClassification,+ AutoModelForTokenClassification,+ AutoTokenizer,+)++from verl.trainer.ppo.core_algos import compute_gae_advantage_return, compute_policy_loss, compute_value_loss+from verl.trainer.runtime.ascend_decoder import AscendDecoder, GraphedDecode, sample_top_k_top_p+from verl.trainer.runtime.master_optimizer import MasterAdamW+++def read_json(path):+ with Path(path).open(encoding="utf-8") as stream:+ value = json.load(stream)+ if not isinstance(value, dict):+ raise ValueError("Expected a JSON object")+ return value+++def write_json(path, value):+ path = Path(path)+ temporary = path.with_suffix(path.suffix + ".tmp")+ temporary.write_text(json.dumps(value, allow_nan=False, indent=2) + "\n", encoding="utf-8")+ temporary.replace(path)+++def pad_left(sequences, pad_id):+ length = max(map(len, sequences))+ ids = torch.full((len(sequences), length), pad_id, dtype=torch.long)+ mask = torch.zeros_like(ids, dtype=torch.bool)+ for row, sequence in enumerate(sequences):+ ids[row, -len(sequence) :] = torch.tensor(sequence, dtype=torch.long)+ mask[row, -len(sequence) :] = True+ return ids, mask+++def training_batch(prompts, responses, pad_id):+ prompt_ids, prompt_mask = pad_left(prompts, pad_id)+ response_length = max(map(len, responses))+ response_ids = torch.full((len(responses), response_length), pad_id, dtype=torch.long)+ response_mask = torch.zeros_like(response_ids, dtype=torch.bool)+ for row, response in enumerate(responses):+ response_ids[row, : len(response)] = torch.tensor(response, dtype=torch.long)+ response_mask[row, : len(response)] = True+ return {+ "input_ids": torch.cat((prompt_ids, response_ids), dim=-1),+ "attention_mask": torch.cat((prompt_mask, response_mask), dim=-1),+ "response_mask": response_mask.float(),+ }+++class FrozenObservation:+ """Observe every parameter's mutation counter and a bounded weight sample."""++ def __init__(self, module):+ self.module = module+ self.before = self.observe()++ @torch.no_grad()+ def observe(self):+ parameters = list(self.module.parameters())+ samples = [parameter.reshape(-1)[:: max(1, parameter.numel() // 8)][:8].float() for parameter in parameters]+ sample = torch.cat(samples).cpu().numpy().tobytes()+ return {+ "parameter_count": sum(parameter.numel() for parameter in parameters),+ "mutation_versions": [parameter._version for parameter in parameters],+ "sample_sha256": hashlib.sha256(sample).hexdigest(),+ "requires_grad": any(parameter.requires_grad for parameter in parameters),+ }++ def result(self):+ after = self.observe()+ unchanged = self.before == after and not after["requires_grad"]+ if not unchanged:+ raise RuntimeError("A frozen model changed during online PPO")+ return {"unchanged": unchanged, "before": self.before, "after": after}+++class OnlinePPO:+ def __init__(self, args, spec):+ self.args = args+ self.spec = spec+ self.algorithm = spec["algorithm"]+ self.sampling = spec["sampling"]+ devices = spec["resource_ceiling"]["device_ids"]+ if len(devices) != 2 or len(set(devices)) != 2 or any(+ type(device) is not int or not 0 <= device < torch.npu.device_count() for device in devices+ ):+ raise ValueError("The resident runtime requires two distinct projected Ascend devices")+ if spec["precision"] != {"model_compute": "bfloat16", "master_parameters": "float32"}:+ raise ValueError("The resident runtime requires BF16 compute and FP32 master parameters")+ if self.algorithm["actor_epochs"] != 1 or self.algorithm["critic_epochs"] != 1:+ raise ValueError("The resident runtime implements one PPO epoch per update")+ if (+ self.algorithm["advantage_estimator"] != "gae"+ or self.algorithm["reference_kl"]["placement"] != "token_reward"+ ):+ raise ValueError("The resident runtime requires GAE and reference KL in token rewards")+ if self.sampling["responses_per_prompt"] != 1:+ raise ValueError("The resident runtime generates one response per prompt")+ self.actor_device = torch.device(f"npu:{devices[0]}")+ self.auxiliary_device = torch.device(f"npu:{devices[1]}")+ self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ppo-auxiliary")+ self.version = 0+ self.micro_batch_size = 32+ self.rollout = None+ torch.set_num_threads(4)+ torch.manual_seed(42)+ self.tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_path, local_files_only=True)+ self.reward_tokenizer = AutoTokenizer.from_pretrained(spec["reward_model_path"], local_files_only=True)+ self.pad_id = self.tokenizer.pad_token_id+ if self.pad_id is None:+ self.pad_id = self.tokenizer.eos_token_id+ options = {"local_files_only": True, "torch_dtype": torch.float32, "attn_implementation": "eager"}+ with torch.npu.device(self.actor_device):+ self.actor = AutoModelForCausalLM.from_pretrained(args.policy_model_path, **options).to(self.actor_device)+ self.actor.eval()+ self.actor_decoder = AscendDecoder(self.actor)+ self.actor_optimizer = MasterAdamW(self.actor, spec["actor_optimizer"]["learning_rate"])+ with torch.npu.device(self.auxiliary_device):+ self.reference = AutoModelForCausalLM.from_pretrained(args.policy_model_path, **options)+ self.reference.requires_grad_(False).eval().to(self.auxiliary_device)+ critic_config = AutoConfig.from_pretrained(args.auxiliary_model_path, local_files_only=True)+ critic_config.num_labels = 1+ critic_config.classifier_dropout = 0.0+ self.critic = AutoModelForTokenClassification.from_pretrained(+ args.auxiliary_model_path, config=critic_config, **options+ ).to(self.auxiliary_device)+ self.critic.eval()+ self.reward = AutoModelForSequenceClassification.from_pretrained(spec["reward_model_path"], **options)+ self.reward.requires_grad_(False).eval().to(self.auxiliary_device)+ self.reference_decoder = AscendDecoder(self.reference)+ self.critic_decoder = AscendDecoder(self.critic)+ self.reward_decoder = AscendDecoder(self.reward)+ self.critic_optimizer = MasterAdamW(self.critic, spec["critic_optimizer"]["learning_rate"])+ self.reference_observation = FrozenObservation(self.reference)+ self.reward_observation = FrozenObservation(self.reward)+ if spec.get("restart_checkpoint"):+ self.restore(Path(spec["restart_checkpoint"]))+ eos_ids = self.actor.generation_config.eos_token_id+ self.eos_ids = set(eos_ids if isinstance(eos_ids, list) else [eos_ids])+ print("Models and FP32 masters loaded", flush=True)++ @torch.no_grad()+ @torch.autocast("npu", dtype=torch.bfloat16)+ def generate(self, prompts):+ ids, mask = pad_left(prompts, self.pad_id)+ ids, mask = ids.to(self.actor_device), mask.to(self.actor_device)+ batch_size, prompt_length = ids.shape+ response_length = self.spec["measurement"]["max_response_tokens"]+ shape = (batch_size, prompt_length + response_length)+ if self.rollout is None or self.rollout.mask.shape != shape:+ self.rollout = GraphedDecode(self.actor_decoder, *shape)+ finished = torch.zeros(batch_size, device=self.actor_device, dtype=torch.bool)+ generated = []+ logits = self.rollout.prefill(ids, mask)+ for index in range(response_length):+ tokens = sample_top_k_top_p(+ logits,+ temperature=self.sampling["temperature"],+ top_k=self.sampling["top_k"],+ top_p=self.sampling["top_p"],+ )+ tokens = torch.where(finished, self.pad_id, tokens)+ generated.append(tokens)+ if not self.sampling["ignore_eos"]:+ for eos_id in self.eos_ids:+ finished |= tokens == eos_id+ if index + 1 == response_length or ((index + 1) % 8 == 0 and bool(finished.all())):+ break+ logits = self.rollout.decode(tokens, index)+ output = torch.stack(generated, dim=-1).cpu().tolist()+ if not self.sampling["ignore_eos"]:+ for row, tokens in enumerate(output):+ end = next((index + 1 for index, token in enumerate(tokens) if token in self.eos_ids), len(tokens))+ output[row] = tokens[:end]+ return output++ @torch.no_grad()+ @torch.autocast("npu", dtype=torch.bfloat16)+ def actor_log_probs(self, batch):+ with torch.npu.device(self.actor_device):+ length = batch["response_mask"].shape[-1]+ output = []+ for start in range(0, len(batch["input_ids"]), self.micro_batch_size):+ stop = start + self.micro_batch_size+ output.append(+ self.actor_decoder.log_probs(+ batch["input_ids"][start:stop].to(self.actor_device),+ batch["attention_mask"][start:stop].to(self.actor_device),+ length,+ self.sampling["temperature"],+ ).cpu()+ )+ return torch.cat(output)++ @torch.no_grad()+ @torch.autocast("npu", dtype=torch.bfloat16)+ def auxiliary_scores(self, batch, reward_inputs):+ with torch.npu.device(self.auxiliary_device):+ length = batch["response_mask"].shape[-1]+ reference, values, rewards = [], [], []+ for start in range(0, len(batch["input_ids"]), self.micro_batch_size):+ stop = start + self.micro_batch_size+ ids = batch["input_ids"][start:stop].to(self.auxiliary_device)+ mask = batch["attention_mask"][start:stop].to(self.auxiliary_device)+ reference.append(+ self.reference_decoder.log_probs(ids, mask, length, self.sampling["temperature"]).cpu()+ )+ values.append(self.critic_decoder.values(ids, mask, length).cpu())+ reward_ids, reward_mask = pad_left(reward_inputs[start:stop], self.pad_id)+ rewards.append(+ self.reward_decoder.scores(+ reward_ids.to(self.auxiliary_device), reward_mask.to(self.auxiliary_device)+ ).cpu()+ )+ return torch.cat(reference), torch.cat(values), torch.cat(rewards)++ @torch.autocast("npu", dtype=torch.bfloat16)+ def update_actor(self, batch, old_log_probs, advantages):+ with torch.npu.device(self.actor_device):+ count = batch["response_mask"].sum().to(self.actor_device)+ length = batch["response_mask"].shape[-1]+ metrics = []+ for start in range(0, len(batch["input_ids"]), self.micro_batch_size):+ stop = start + self.micro_batch_size+ log_probs = self.actor_decoder.log_probs(+ batch["input_ids"][start:stop].to(self.actor_device),+ batch["attention_mask"][start:stop].to(self.actor_device),+ length,+ self.sampling["temperature"],+ )+ mask = batch["response_mask"][start:stop].to(self.actor_device)+ # The tensor-returning API keeps microbatch metrics on device.+ loss, clip_fraction, kl, _ = compute_policy_loss(+ old_log_probs[start:stop].to(self.actor_device),+ log_probs,+ advantages[start:stop].to(self.actor_device),+ mask,+ cliprange=self.algorithm["actor_clip"],+ )+ weight = mask.sum() / count+ (loss * weight).backward()+ self.actor_optimizer.accumulate()+ metrics.append(torch.stack((loss.detach(), clip_fraction.detach(), kl.detach())) * weight)+ norm = self.actor_optimizer.step()+ if self.rollout is not None:+ self.rollout.refresh_weights()+ return norm, torch.stack(metrics).sum(0).cpu().tolist()++ @torch.autocast("npu", dtype=torch.bfloat16)+ def update_critic(self, batch, old_values, returns):+ with torch.npu.device(self.auxiliary_device):+ count = batch["response_mask"].sum().to(self.auxiliary_device)+ length = batch["response_mask"].shape[-1]+ metrics = []+ for start in range(0, len(batch["input_ids"]), self.micro_batch_size):+ stop = start + self.micro_batch_size+ values = self.critic_decoder.values(+ batch["input_ids"][start:stop].to(self.auxiliary_device),+ batch["attention_mask"][start:stop].to(self.auxiliary_device),+ length,+ )+ mask = batch["response_mask"][start:stop].to(self.auxiliary_device)+ loss, clip_fraction = compute_value_loss(+ values,+ returns[start:stop].to(self.auxiliary_device),+ old_values[start:stop].to(self.auxiliary_device),+ mask,+ self.algorithm["value_clip"],+ )+ weight = mask.sum() / count+ (loss * weight).backward()+ self.critic_optimizer.accumulate()+ metrics.append(torch.stack((loss.detach(), clip_fraction.detach())) * weight)+ norm = self.critic_optimizer.step()+ return norm, torch.stack(metrics).sum(0).cpu().tolist()++ def reward_inputs(self, messages, responses):+ output = []+ for chat, response in zip(messages, responses, strict=True):+ text = self.tokenizer.decode(response).replace(self.tokenizer.eos_token, "")+ reward_text = self.reward_tokenizer.apply_chat_template(+ [*chat, {"role": "assistant", "content": text}], tokenize=False, add_generation_prompt=False+ )+ bos = self.reward_tokenizer.bos_token+ if bos is not None and reward_text.startswith(bos):+ reward_text = reward_text[len(bos) :]+ output.append(self.reward_tokenizer.encode(reward_text, add_special_tokens=True))+ return output++ def run(self, input_path, sampling_seed):+ inputs = read_json(input_path)+ work = self.spec["resolved_work"]+ records = inputs["prompts"]+ if len(records) != work["trajectories_per_update"] or len({record["id"] for record in records}) != len(records):+ raise ValueError("Prompt coverage differs from the requested work")+ messages = [+ [+ {"role": "system", "content": inputs["system_prompt"]},+ {"role": "user", "content": record["question"]},+ ]+ for record in records+ ]+ prompts = [+ self.tokenizer.apply_chat_template(chat, tokenize=True, add_generation_prompt=True, return_dict=False)+ for chat in messages+ ]+ if any(not prompt or len(prompt) > self.spec["measurement"]["max_prompt_tokens"] for prompt in prompts):+ raise ValueError("A prompt exceeds the specified token limit")+ random.seed(sampling_seed)+ np.random.seed(sampling_seed % (2**32))+ torch.manual_seed(sampling_seed)+ torch.npu.manual_seed_all(sampling_seed)+ trajectory_records, step_metrics = [], []+ actor_grad_norms, critic_grad_norms = [], []+ started = time.monotonic()+ for _ in range(work["committed_updates"]):+ step_started = time.monotonic()+ rollout_version = self.version+ with torch.npu.device(self.actor_device):+ responses = self.generate(prompts)+ generated_at = time.monotonic()+ batch = training_batch(prompts, responses, self.pad_id)+ future = self.executor.submit(self.auxiliary_scores, batch, self.reward_inputs(messages, responses))+ old_log_probs = self.actor_log_probs(batch)+ reference_log_probs, values, scores = future.result()+ mask = batch["response_mask"]+ kl = (old_log_probs - reference_log_probs) * mask+ rewards = -self.algorithm["reference_kl"]["coefficient"] * kl+ ends = mask.sum(-1).long() - 1+ rewards[torch.arange(len(records)), ends] += scores+ advantages, returns = compute_gae_advantage_return(+ rewards, values, mask, self.algorithm["gamma"], self.algorithm["lambda"]+ )+ scored_at = time.monotonic()+ future = self.executor.submit(self.update_critic, batch, values, returns)+ actor_norm, actor_metrics = self.update_actor(batch, old_log_probs, advantages)+ critic_norm, critic_metrics = future.result()+ self.version += 1+ actor_grad_norms.append(actor_norm)+ critic_grad_norms.append(critic_norm)+ metrics = {+ "step": self.version,+ "rollout_policy_version": rollout_version,+ "actor/loss": actor_metrics[0],+ "actor/clip_fraction": actor_metrics[1],+ "actor/ppo_kl": actor_metrics[2],+ "actor/grad_norm": actor_norm,+ "critic/loss": critic_metrics[0],+ "critic/clip_fraction": critic_metrics[1],+ "critic/grad_norm": critic_norm,+ "critic/advantages/mean": float((advantages * mask).sum() / mask.sum()),+ "critic/advantages/abs_mean": float((advantages.abs() * mask).sum() / mask.sum()),+ "critic/returns/mean": float((returns * mask).sum() / mask.sum()),+ "reward/score_mean": float(scores.mean()),+ "reward/reference_kl": float(kl.sum() / mask.sum()),+ "response_tokens": int(mask.sum()),+ "timing/rollout": generated_at - step_started,+ "timing/scoring": scored_at - generated_at,+ "timing/update": time.monotonic() - scored_at,+ }+ step_metrics.append(metrics)+ trajectory_records.extend(+ {"update": self.version, "prompt_id": record["id"], "response_ids": response}+ for record, response in zip(records, responses, strict=True)+ )+ print(json.dumps(metrics, allow_nan=False), flush=True)+ ppo_seconds = time.monotonic() - started+ with torch.npu.device(self.auxiliary_device):+ reference_observation = self.reference_observation.result()+ reward_observation = self.reward_observation.result()+ result = {+ "status": "passed",+ "action": self.spec["action"],+ "committed_actor_updates": len(step_metrics),+ "committed_critic_updates": len(step_metrics),+ "accepted_trajectories": len(trajectory_records),+ "trajectory_records": trajectory_records,+ "step_metrics": step_metrics,+ "actor_grad_norms": actor_grad_norms,+ "critic_grad_norms": critic_grad_norms,+ "reference_policy_frozen": reference_observation["unchanged"],+ "reward_model_frozen": reward_observation["unchanged"],+ "frozen_model_observations": {"reference": reference_observation, "reward": reward_observation},+ "reported_ppo_seconds": ppo_seconds,+ "runtime_layout": {+ "placement": "resident_roles",+ "actor_device": str(self.actor_device),+ "rollout_device": str(self.actor_device),+ "reference_device": str(self.auxiliary_device),+ "critic_device": str(self.auxiliary_device),+ "reward_device": str(self.auxiliary_device),+ "rollout_engine": "shared_actor_with_graphed_kv_cache",+ "weight_transport": "local_bfloat16_copy_after_update",+ "rollout_weights_current": self.rollout.weights_current,+ "optimizer": "resident_fp32_master_adamw",+ "compute_precision": "bfloat16_autocast",+ "probe_precision": "float32_master_parameters",+ "micro_batch_size": self.micro_batch_size,+ "process_count": 1,+ "peak_memory_allocated_bytes": {+ str(device): torch.npu.max_memory_allocated(device)+ for device in (self.actor_device, self.auxiliary_device)+ },+ },+ }+ if self.spec["action"] == "correctness":+ checkpoint = Path(self.args.runtime_dir).parent / "checkpoints" / f"update-{self.version}"+ self.save(checkpoint)+ result["checkpoint_path"] = str(checkpoint)+ result["portable_actor_path"] = str(checkpoint / "portable-actor")+ write_json(Path(self.args.result_dir) / "run-result.json", result)++ def save(self, path):+ path.mkdir(parents=True, exist_ok=False)+ state = {+ "schema_version": 1,+ "policy_version": self.version,+ "actor": self.actor_optimizer.state_dict(),+ "critic": self.critic_optimizer.state_dict(),+ "algorithm": self.algorithm,+ "sampling": self.sampling,+ "torch_rng": torch.get_rng_state(),+ "npu_rng": torch.npu.get_rng_state_all(),+ "python_rng": random.getstate(),+ "numpy_rng": np.random.get_state(),+ }+ temporary = path / "training.pt.tmp"+ torch.save(state, temporary)+ temporary.replace(path / "training.pt")+ portable = path / "portable-actor"+ self.actor.save_pretrained(portable, safe_serialization=True)+ self.tokenizer.save_pretrained(portable)+ write_json(path / "complete.json", {"schema_version": 1, "policy_version": self.version})++ def restore(self, path):+ marker = read_json(path / "complete.json")+ state = torch.load(path / "training.pt", map_location="cpu", weights_only=False)+ if (+ state["schema_version"] != 1+ or state["policy_version"] != marker["policy_version"]+ or state["algorithm"] != self.algorithm+ or state["sampling"] != self.sampling+ ):+ raise ValueError("Restart checkpoint is incomplete or has a different PPO contract")+ with torch.npu.device(self.actor_device):+ self.actor_optimizer.load_state_dict(state["actor"])+ with torch.npu.device(self.auxiliary_device):+ self.critic_optimizer.load_state_dict(state["critic"])+ self.version = state["policy_version"]+ torch.set_rng_state(state["torch_rng"])+ torch.npu.set_rng_state_all(state["npu_rng"])+ random.setstate(state["python_rng"])+ np.random.set_state(state["numpy_rng"])+ print(f"Restored update {self.version} and both AdamW optimizers", flush=True)++ @torch.no_grad()+ def probe(self, request):+ if self.rollout is not None and not self.rollout.weights_current:+ raise RuntimeError("Rollout weights do not match the committed actor")+ prompt = self.tokenizer.encode(request["prompt"], add_special_tokens=True)+ continuation = self.tokenizer.encode(request["continuation"], add_special_tokens=False)+ if not prompt or not continuation:+ raise ValueError("Probe prompt and continuation must both tokenize to nonempty sequences")+ with torch.npu.device(self.actor_device):+ ids = torch.tensor([prompt + continuation], device=self.actor_device)+ mask = torch.ones_like(ids, dtype=torch.bool)+ # Score the live master module in its stored precision, matching+ # portable export. Training and rollout use BF16 autocast above;+ # rounding in BF16 kernels differs across CPU and NPU hardware.+ # The two roles share this module and are evaluated independently.+ outputs = []+ for _ in range(2):+ logits = self.actor(input_ids=ids, attention_mask=mask, use_cache=False).logits+ logits = logits[:, -len(continuation) - 1 : -1].float()+ selected = torch.log_softmax(logits, dim=-1).gather(-1, ids[:, -len(continuation) :, None])+ outputs.append(selected[0, :, 0].cpu().tolist())+ actor, rollout = outputs+ return {+ "type": "probe_result",+ "policy_version": self.version,+ "rollout_reported_version": self.version,+ "actor_log_probs": actor,+ "rollout_log_probs": rollout,+ }++ def close(self):+ self.executor.shutdown(wait=True, cancel_futures=True)+ for device in (self.actor_device, self.auxiliary_device):+ torch.npu.synchronize(device)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ for argument in (+ "run-spec",+ "policy-model-path",+ "auxiliary-model-path",+ "tokenizer-path",+ "runtime-dir",+ "result-dir",+ "control-socket",+ ):+ parser.add_argument(f"--{argument}", required=True)+ args = parser.parse_args()+ runtime = None+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:+ connection.connect(args.control_socket)+ stream = connection.makefile("rwb")++ def send(value):+ stream.write(json.dumps(value, allow_nan=False, separators=(",", ":")).encode() + b"\n")+ stream.flush()++ try:+ runtime = OnlinePPO(args, read_json(args.run_spec))+ send({"type": "ready"})+ started = False+ completed = False+ while True:+ line = stream.readline(1024 * 1024)+ if not line:+ raise ConnectionError("The host closed the control connection")+ if not line.endswith(b"\n"):+ raise ValueError("Control message exceeds the size limit")+ message = json.loads(line)+ if message["type"] == "start" and not started:+ started = True+ runtime.run(message["input_path"], message["sampling_seed"])+ completed = True+ send({"type": "completed"})+ elif message["type"] == "probe" and completed:+ send(runtime.probe(message["request"]))+ elif message["type"] == "shutdown":+ break+ else:+ raise ValueError("Invalid control message or lifecycle transition")+ finally:+ if runtime is not None:+ runtime.close()+ stream.close()+++if __name__ == "__main__":+ main()diff --git a/verl/trainer/runtime/test_online_ppo.py b/verl/trainer/runtime/test_online_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..3ab02809b7ecbed84c375d9f4418ce9a9145fb0f--- /dev/null+++ b/verl/trainer/runtime/test_online_ppo.py@@ -0,0 +1,215 @@+# 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+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Focused checks for the resident runtime (CPU unless marked with an NPU skip)."""++import copy+import subprocess+import sys+import textwrap++import pytest+import torch+import torch.nn.functional as F+from transformers import Qwen3Config, Qwen3ForCausalLM++from verl.trainer.runtime.ascend_decoder import AscendDecoder, GraphedDecode, sample_top_k_top_p+from verl.trainer.runtime.master_optimizer import MasterAdamW+from verl.trainer.runtime.online_ppo import FrozenObservation, training_batch+++def test_response_masks_include_eos_and_exclude_padding():+ batch = training_batch([[5, 6], [7]], [[2], [3, 2]], pad_id=2)+ assert batch["input_ids"].tolist() == [[5, 6, 2, 2], [2, 7, 3, 2]]+ assert batch["attention_mask"].tolist() == [[True, True, True, False], [False, True, True, True]]+ assert batch["response_mask"].tolist() == [[1, 0], [1, 1]]+++@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32])+def test_master_adamw_accumulation_and_restart(dtype):+ torch.manual_seed(3)+ model = torch.nn.Linear(4, 3).to(dtype)+ optimizer = MasterAdamW(model, 1e-3)+ reference = [torch.nn.Parameter(parameter.detach().float().clone()) for parameter in model.parameters()]+ expected = torch.optim.AdamW(reference, lr=1e-3, weight_decay=0.01, foreach=True)+ for _ in range(2):+ for parameter, master in zip(model.parameters(), reference, strict=True):+ gradient = torch.rand_like(parameter) / 20+ if parameter.grad is None:+ parameter.grad = gradient.clone()+ else:+ parameter.grad.add_(gradient)+ if master.grad is None:+ master.grad = gradient.float()+ else:+ master.grad.add_(gradient.float())+ optimizer.accumulate()+ torch.nn.utils.clip_grad_norm_(reference, 1.0, foreach=True)+ expected.step()+ optimizer.step()+ for actual, wanted in zip(optimizer.masters, reference, strict=True):+ torch.testing.assert_close(actual, wanted, rtol=0, atol=0)+ state = copy.deepcopy(optimizer.state_dict())+ restored_model = copy.deepcopy(model)+ restored = MasterAdamW(restored_model, 1e-3)+ restored.load_state_dict(state)+ for left, right in zip(model.parameters(), restored_model.parameters(), strict=True):+ gradient = torch.randn_like(left) / 20+ left.grad = gradient.clone()+ right.grad = gradient.clone()+ optimizer.accumulate()+ restored.accumulate()+ assert optimizer.step() == restored.step()+ for left, right in zip(optimizer.masters, restored.masters, strict=True):+ torch.testing.assert_close(left, right, rtol=0, atol=0)+ for left, right in zip(model.parameters(), restored_model.parameters(), strict=True):+ torch.testing.assert_close(left, right, rtol=0, atol=0)+++def test_nucleus_sampling_excludes_tokens_beyond_boundary():+ logits = torch.tensor([[5.0, 4.0, 3.0, 2.0, 1.0]]).expand(4096, -1)+ generator = torch.Generator().manual_seed(21)+ samples = sample_top_k_top_p(logits, temperature=1, top_k=3, top_p=0.8, generator=generator)+ assert set(samples.tolist()) == {0, 1}+ expected = torch.tensor([5.0, 4.0]).softmax(-1)[0]+ assert abs(float((samples == 0).float().mean() - expected)) < 0.03+ assert sample_top_k_top_p(logits[:1], temperature=1, top_k=1, top_p=0.1).item() == 0+++def test_frozen_observation_detects_mutation():+ model = torch.nn.Linear(4, 3).requires_grad_(False)+ observation = FrozenObservation(model)+ assert observation.result()["unchanged"]+ with torch.no_grad():+ model.weight[0, 0].add_(1)+ with pytest.raises(RuntimeError, match="frozen model changed"):+ observation.result()+++def test_generation_loads_roc_curve_only_when_used():+ program = textwrap.dedent(+ """+ import sys+ from types import SimpleNamespace+ from transformers.generation.candidate_generator import AssistedCandidateGenerator+ from transformers.utils import is_sklearn_available++ assert "sklearn.metrics" not in sys.modules+ if is_sklearn_available():+ generator = AssistedCandidateGenerator.__new__(AssistedCandidateGenerator)+ generator.assistant_generation_config = SimpleNamespace(+ num_assistant_tokens_schedule="constant", assistant_confidence_threshold=0.4+ )+ generator.matches = [0, 1, 0, 1, 0]+ generator.probs = [0.1, 0.9, 0.2, 0.8, 0.3, 0.7]+ generator.update_candidate_strategy(None, None, num_matches=1)+ assert "sklearn.metrics" in sys.modules+ assert generator.assistant_generation_config.assistant_confidence_threshold == 0.7+ """+ )+ subprocess.run([sys.executable, "-c", program], check=True, capture_output=True, text=True, timeout=120)+++@pytest.mark.skipif(not torch.npu.is_available(), reason="requires Ascend")+def test_master_adamw_on_npu():+ model = torch.nn.Linear(32, 16).to(dtype=torch.bfloat16, device="npu:0")+ optimizer = MasterAdamW(model, 1e-3)+ before = [parameter.detach().clone() for parameter in model.parameters()]+ inputs = torch.randn(8, 32, dtype=torch.bfloat16, device="npu:0")+ model(inputs).float().square().mean().backward()+ optimizer.accumulate()+ assert optimizer.step() > 0+ assert any(not torch.equal(left, right) for left, right in zip(before, model.parameters(), strict=True))+ for master in optimizer.masters:+ assert master.dtype == torch.float32 and master.device.type == "npu"+ state = optimizer.optimizer.state[master]+ assert state["exp_avg"].dtype == torch.float32 and state["exp_avg"].device.type == "npu"+ assert state["exp_avg_sq"].dtype == torch.float32 and state["exp_avg_sq"].device.type == "npu"+++@pytest.mark.skipif(not torch.npu.is_available(), reason="requires Ascend")+@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32])+def test_ascend_decoder_forward_cache_and_backward(dtype):+ torch.manual_seed(18)+ config = Qwen3Config(+ vocab_size=128,+ hidden_size=128,+ intermediate_size=256,+ num_hidden_layers=2,+ num_attention_heads=4,+ num_key_value_heads=2,+ head_dim=32,+ attention_dropout=0,+ )+ config._attn_implementation = "eager"+ model = Qwen3ForCausalLM(config).to(dtype=dtype, device="npu:0").eval()+ adapter = AscendDecoder(model)+ ids = torch.tensor([[0, 0, 5, 6, 7, 8], [11, 12, 13, 14, 15, 16]], device="npu:0")+ mask = torch.tensor([[0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]], device="npu:0").bool()+ positions = mask.long().cumsum(-1).sub(1).clamp_min(0)+ with torch.no_grad(), torch.autocast("npu", dtype=torch.bfloat16):+ expected = model.model(ids, attention_mask=mask, position_ids=positions).last_hidden_state+ actual = adapter.hidden(ids, mask)+ torch.testing.assert_close(actual[mask], expected[mask], atol=0.04, rtol=0.04)+ cache = adapter.new_cache(2, 8)+ adapter.hidden(ids[:, :4], mask[:, :4], cache=cache)+ decoded = adapter.hidden(ids[:, 4:5], mask[:, :5], cache=cache)+ torch.testing.assert_close(decoded[:, 0], actual[:, 4], atol=0.04, rtol=0.04)+ decoded = adapter.hidden(ids[:, 5:], mask, cache=cache)+ torch.testing.assert_close(decoded[:, 0], actual[:, 5], atol=0.04, rtol=0.04)+ with torch.autocast("npu", dtype=torch.bfloat16):+ loss = -adapter.log_probs(ids, mask, response_length=2).mean()+ loss.backward()+ assert all(parameter.grad is not None for parameter in model.parameters())+ assert all(torch.isfinite(parameter.grad).all() for parameter in model.parameters())+ actual_gradient = torch.cat([parameter.grad.flatten().float() for parameter in model.parameters()])+ assert actual_gradient.norm() > 0+ model.zero_grad(set_to_none=True)+ with torch.autocast("npu", dtype=torch.bfloat16):+ logits = model(ids, attention_mask=mask, position_ids=positions, use_cache=False).logits+ expected_loss = F.cross_entropy(logits[:, -3:-1].float().flatten(0, 1), ids[:, -2:].flatten())+ expected_loss.backward()+ expected_gradient = torch.cat([parameter.grad.flatten().float() for parameter in model.parameters()])+ assert (actual_gradient - expected_gradient).norm() / expected_gradient.norm() < 0.03+++@pytest.mark.skipif(not torch.npu.is_available(), reason="requires Ascend")+def test_graphed_decode_uses_positions_and_updated_weights():+ torch.manual_seed(24)+ config = Qwen3Config(+ vocab_size=128,+ hidden_size=128,+ intermediate_size=256,+ num_hidden_layers=2,+ num_attention_heads=4,+ num_key_value_heads=2,+ head_dim=32,+ attention_dropout=0,+ )+ model = Qwen3ForCausalLM(config).to(dtype=torch.float32, device="npu:0").eval()+ adapter = AscendDecoder(model)+ graph = GraphedDecode(adapter, 2, 8)+ ids = torch.tensor([[0, 0, 5, 6, 7, 8], [11, 12, 13, 14, 15, 16]], device="npu:0")+ mask = torch.tensor([[0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]], device="npu:0").bool()+ with torch.no_grad():+ for update in range(2):+ if update:+ model.lm_head.weight.mul_(0.5)+ assert not graph.weights_current+ with torch.autocast("npu", dtype=torch.bfloat16):+ expected = model.lm_head(adapter.hidden(ids, mask))+ graph.prefill(ids[:, :4], mask[:, :4])+ assert graph.weights_current+ for index in range(2):+ actual = graph.decode(ids[:, 4 + index], index)+ torch.testing.assert_close(actual, expected[:, 4 + index], atol=0.04, rtol=0.04)