Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
verl · 4 changed files
Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d
diff --git a/verl/utils/colocated_optimize.py b/verl/utils/colocated_optimize.pynew file mode 100644index 0000000000000000000000000000000000000000..4e04ef9188adae95456d5e798c95499bda234f95--- /dev/null+++ b/verl/utils/colocated_optimize.py@@ -0,0 +1,97 @@+# Copyright 2025 Bytedance Ltd. and/or its affiliates+#+# 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.+"""Heuristics for small-model colocated RL workloads.++When a single small dense model is trained and rolled out on the same NPU,+releasing the rollout cache between every GRPO update costs more wall-clock+time than the memory it returns. These helpers let the trainer and the vLLM+server derive the same decision from the public workload configuration so+their sleep/wake behaviour stays consistent.+"""++from __future__ import annotations++import torch++from verl.utils.device import is_torch_npu_available++# Rough dense-model parameter estimate (vocab embedding + attention and MLP+# weights). It is intentionally approximate; it only has to distinguish a+# sub-1B model from the much larger models for which the resident-cache+# heuristic would be unsafe.+_MAX_APPROX_PARAMETERS = 1_000_000_000+_MAX_MODEL_LEN = 2048+_MAX_NUM_SEQS = 64+_MIN_DEVICE_MEMORY_BYTES = 50 * 1024**3+++def approximate_dense_parameter_count(hf_config) -> int:+ """Return a conservative dense parameter count for a HF text config."""+ if hf_config is None:+ return 0+ explicit = getattr(hf_config, "num_parameters", None)+ if isinstance(explicit, (int, float)) and explicit > 0:+ return int(explicit)++ vocab_size = int(getattr(hf_config, "vocab_size", 0) or 0)+ hidden_size = int(getattr(hf_config, "hidden_size", 0) or 0)+ num_layers = int(getattr(hf_config, "num_hidden_layers", 0) or 0)+ intermediate_size = int(getattr(hf_config, "intermediate_size", 0) or 0)+ if min(vocab_size, hidden_size, num_layers, intermediate_size) <= 0:+ return 0++ embedding_params = vocab_size * hidden_size+ per_layer_params = 4 * hidden_size * hidden_size + 3 * hidden_size * intermediate_size+ if not getattr(hf_config, "tie_word_embeddings", False):+ embedding_params *= 2+ return embedding_params + num_layers * per_layer_params+++def should_keep_rollout_weights_resident(+ *,+ model_config,+ max_model_len: int | None,+ max_num_seqs: int | None,+ rollout_name: str | None = None,+ actor_strategy: str | None = None,+) -> bool:+ """Whether a colocated workload is small enough to keep vLLM resident.++ The rollout process and the FSDP actor share one NPU. For small dense+ models the 60+ GiB device comfortably holds both, and skipping the+ multi-second sleep/wake cycle preserves identical training and sampling+ semantics while removing fixed per-update overhead.+ """+ if not is_torch_npu_available(check_device=True):+ return False+ if rollout_name not in (None, "vllm"):+ return False+ if actor_strategy not in (None, "fsdp2"):+ return False+ if max_model_len is None or max_model_len > _MAX_MODEL_LEN:+ return False+ if max_num_seqs is None or max_num_seqs > _MAX_NUM_SEQS:+ return False++ hf_config = getattr(model_config, "hf_config", None)+ approx_parameters = approximate_dense_parameter_count(hf_config)+ if approx_parameters <= 0 or approx_parameters > _MAX_APPROX_PARAMETERS:+ return False++ try:+ device = torch.device("npu", torch.npu.current_device())+ total_memory = torch.npu.get_device_properties(device).total_memory+ except Exception:+ return False+ return int(total_memory) >= _MIN_DEVICE_MEMORY_BYTESdiff --git a/verl/workers/engine_workers.py b/verl/workers/engine_workers.pyindex bf379b49c3dc21ef702d49be1467318692a471f7..90716f56e32e9ac9dfa7b674437c2882209abd17 100644--- a/verl/workers/engine_workers.py+++ b/verl/workers/engine_workers.py@@ -500,6 +500,27 @@ class ActorRolloutRefWorker(Worker, DistProfilerExtension): def init_model(self): model_config: HFModelConfig = omega_conf_to_dataclass(self.config.model) + from verl.utils.colocated_optimize import should_keep_rollout_weights_resident++ keep_rollout_resident = (+ "actor" in self.role+ and "rollout" in self.role+ and should_keep_rollout_weights_resident(+ model_config=model_config,+ max_model_len=self.config.rollout.get("max_model_len", None),+ max_num_seqs=self.config.rollout.get("max_num_seqs", None),+ rollout_name=self.config.rollout.get("name", None),+ actor_strategy=self.config.actor.get("strategy", None),+ )+ )+ if keep_rollout_resident:+ # The actor and rollout share one NPU and the model is small enough+ # that both fit comfortably. Keeping the rollout cache resident+ # avoids a multi-second sleep/wake cycle before and after every+ # actor update. Training and sampling semantics are unchanged.+ with open_dict(self.config.rollout):+ self.config.rollout.free_cache_engine = False+ # 1. build reference model if "ref" in self.role: # TODO: align ref config with actor config@@ -553,18 +574,44 @@ class ActorRolloutRefWorker(Worker, DistProfilerExtension): optimizer_config=actor_config.optim, checkpoint_config=actor_config.checkpoint, )+ if keep_rollout_resident:+ # With only one FSDP rank there is no communication benefit+ # from resharding after each forward. Keeping the full+ # parameters materialized makes post-update observation+ # projection and the per-update rollout weight export+ # substantially cheaper; memory remains within the budget+ # identified by the colocated small-model heuristic.+ from dataclasses import replace as dataclasses_replace++ actor_training_config = dataclasses_replace(+ actor_training_config,+ engine_config=dataclasses_replace(+ actor_training_config.engine_config,+ reshard_after_forward=False,+ ),+ ) assert self.config.actor.use_dynamic_bsz == self.config.rollout.log_prob_use_dynamic_bsz # assign engine configs actor_training_config.engine_config.use_dynamic_bsz = self.config.actor.use_dynamic_bsz- actor_training_config.engine_config.infer_max_token_len_per_gpu = (- self.config.rollout.log_prob_max_token_len_per_gpu- )+ if keep_rollout_resident and self.config.actor.use_dynamic_bsz:+ # Micro-batches of 1024 tokens leave a 0.6B NPU model+ # extremely kernel-launch bound and force >10 FSDP+ # unshard/reshard cycles per update. A single-device 60GiB+ # NPU has ample headroom for much larger no-padding chunks;+ # this only changes gradient accumulation grouping, not the+ # optimization step or the loss normalization.+ actor_training_config.engine_config.infer_max_token_len_per_gpu = 8192+ actor_training_config.engine_config.max_token_len_per_gpu = 8192+ else:+ actor_training_config.engine_config.infer_max_token_len_per_gpu = (+ self.config.rollout.log_prob_max_token_len_per_gpu+ )+ actor_training_config.engine_config.max_token_len_per_gpu = self.config.actor.ppo_max_token_len_per_gpu actor_training_config.engine_config.infer_micro_batch_size_per_gpu = ( self.config.rollout.log_prob_micro_batch_size_per_gpu )- actor_training_config.engine_config.max_token_len_per_gpu = self.config.actor.ppo_max_token_len_per_gpu actor_training_config.engine_config.micro_batch_size_per_gpu = ( self.config.actor.ppo_micro_batch_size_per_gpu )diff --git a/verl/workers/rollout/vllm_rollout/utils.py b/verl/workers/rollout/vllm_rollout/utils.pyindex 248c42d3b1ebc1d190cdc8c68e069b4a9c216544..149de5705f7a5ccccc8b97ead1706ed137bf98fd 100644--- a/verl/workers/rollout/vllm_rollout/utils.py+++ b/verl/workers/rollout/vllm_rollout/utils.py@@ -37,7 +37,12 @@ VLLM_LORA_INT_ID = 123 VLLM_LORA_NAME = "123" VLLM_LORA_PATH = "simon_lora_path" -VLLM_ASCEND_REQUIRED_ENV_VARS = {"VLLM_ALL2ALL_BACKEND": "flashinfer_all2allv", "VLLM_ASCEND_ENABLE_NZ": "0"}+VLLM_ASCEND_REQUIRED_ENV_VARS = {+ "VLLM_ALL2ALL_BACKEND": "flashinfer_all2allv",+ "VLLM_ASCEND_ENABLE_NZ": "0",+ "TASK_QUEUE_ENABLE": "1",+ "HCCL_OP_EXPANSION_MODE": "AIV",+} def _resolve_vllm_weight_sync_local_rank(worker_local_rank: int, parallel_config: Any) -> int:diff --git a/verl/workers/rollout/vllm_rollout/vllm_async_server.py b/verl/workers/rollout/vllm_rollout/vllm_async_server.pyindex 962cf1fb5579f4dd7e4d857ac447544c532ec1ab..04903cb50ac94ee83c1d1dfe853ce4009ce5db95 100644--- a/verl/workers/rollout/vllm_rollout/vllm_async_server.py+++ b/verl/workers/rollout/vllm_rollout/vllm_async_server.py@@ -123,6 +123,22 @@ class vLLMHttpServer: self.config = self._init_config(config) self.model_config = self._init_model_config(model_config)++ from dataclasses import replace++ from verl.utils.colocated_optimize import should_keep_rollout_weights_resident++ if should_keep_rollout_weights_resident(+ model_config=self.model_config,+ max_model_len=self.config.max_model_len,+ max_num_seqs=self.config.max_num_seqs,+ rollout_name=self.config.name,+ ):+ # The trainer side makes the same decision before spawning this+ # server. Keeping weights and KV cache resident avoids the+ # sleep/wake cycle around each FSDP update.+ self.config = replace(self.config, free_cache_engine=False)+ self._validate_configs() self.rollout_mode = rollout_mode@@ -1021,6 +1037,12 @@ class vLLMReplica(RolloutReplica): # use VLLM_ASCEND_TASK_QUEUE_ENABLE to support different TASK_QUEUE_ENABLE mode for # train and rollout on Ascend NPU env_vars["TASK_QUEUE_ENABLE"] = os.environ["VLLM_ASCEND_TASK_QUEUE_ENABLE"]+ elif is_torch_npu_available(check_device=False):+ # Ascend guidance for ACLGraph deployments. A single pipeline+ # level and AIV HCCL op expansion reduce device-side dispatch+ # overhead; both are process-local performance knobs.+ env_vars.setdefault("TASK_QUEUE_ENABLE", "1")+ env_vars.setdefault("HCCL_OP_EXPANSION_MODE", "AIV") server = self.server_class.options( scheduling_strategy=ray.util.scheduling_strategies.NodeAffinitySchedulingStrategy(