before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
epochs=self.config.ppo_epochs, seed=self.config.data_loader_seed, dataloader_kwargs={"shuffle": self.config.shuffle}, ) def forward_backward_batch( self, data: DataProto, forward_only=False, post_process_fn=None, calculate_entropy=...
No issues found.
epochs=self.config.ppo_epochs, seed=self.config.data_loader_seed, dataloader_kwargs={"shuffle": self.config.shuffle}, ) def forward_backward_batch( self, data: DataProto, forward_only=False, post_process_fn=None, calculate_entropy=...
@@ -130,7 +130,8 @@ def __init__( else: self.prof = None self.use_fused_kernels = self.config.get("use_fused_kernels", False) - if self.use_fused_kernels: + if self.use_fused_kernels and not getattr(self.config, "overlap_moe_expert_parallel_comm", False): + # do n...
verl/workers/actor/megatron_actor.py
0
Python
1
none
16
51
51
true
[Megatron] feat: 1f1b overlap/moe_a2a_overlap
3,522
volcengine/verl
16,907
Python
ISEEKYAN
# Algorithm temperature=1.0 top_p=1.0 top_k=-1 # 0 for HF rollout, -1 for vLLM rollout val_top_p=0.7 # Performance Related Parameter use_dynamic_bsz=True actor_ppo_max_token_len=$(((max_prompt_length + max_response_length) * 2)) infer_ppo_max_token_len=$(((max_prompt_length + max_response_length) * 3)) ref_offload=T...
No issues found.
# Algorithm temperature=1.0 top_p=1.0 top_k=-1 # 0 for HF rollout, -1 for vLLM rollout val_top_p=0.7 # Performance Related Parameter use_dynamic_bsz=True actor_ppo_max_token_len=$(((max_prompt_length + max_response_length) * 2)) infer_ppo_max_token_len=$(((max_prompt_length + max_response_length) * 3)) ref_offload=T...
@@ -0,0 +1,140 @@ +#!/usr/bin/env bash +set -xeuo pipefail + +project_name='DAPO' +exp_name='DAPO-Qwen2.5-7b-MATH-0527a1-fsdp2-sglang-one-step-off-4-12' + +adv_estimator=grpo + +use_kl_in_reward=False +kl_coef=0.0 +use_kl_loss=False +kl_loss_coef=0.0 + +clip_ratio_low=0.2 +clip_ratio_high=0.28 + +max_prompt_length=$((1...
recipe/one_step_off_policy/dapo_7b_math_fsdp2_sglang_4_12.sh
0
Shell
1
none
16
51
51
true
[sglang, recipe] feat: add SGLang as rollout engine for one-step-off-policy
3,531
volcengine/verl
16,907
Python
KAMiPan
AssertionError: If equal_size is True and len(seqlen_list) is not divisible by k_partitions. AssertionError: If any resulting partition is empty. """ assert len(seqlen_list) >= k_partitions, f"number of items:[{len(seqlen_list)}] < k_partitions:[{k_partitions}]" def _check_and_sort_partitio...
No issues found.
AssertionError: If equal_size is True and len(seqlen_list) is not divisible by k_partitions. AssertionError: If any resulting partition is empty. """ assert len(seqlen_list) >= k_partitions, f"number of items:[{len(seqlen_list)}] < k_partitions:[{k_partitions}]" def _check_and_sort_partitio...
@@ -24,6 +24,16 @@ from verl.utils.device import get_device_name +def calculate_workload(seqlen_list: list[int]): + """ + Calculate the workload for a dense transformer block based on sequence length. + FLOPs = 12 * hidden_size^2 * seqlen + 2 * hidden_size * seqlen^2 + Hardcodes the constants by a 7B m...
verl/utils/seqlen_balancing.py
0
Python
1
none
16
51
51
true
[perf, data] feat: DP workload balance
3,605
volcengine/verl
16,907
Python
conver334
if not os.path.exists(file_path): raise FileNotFoundError(f"Reward function file '{file_path}' not found.") spec = importlib.util.spec_from_file_location("custom_module", file_path) assert spec is not None module = importlib.util.module_from_spec(spec) try: ...
No issues found.
if not os.path.exists(file_path): raise FileNotFoundError(f"Reward function file '{file_path}' not found.") spec = importlib.util.spec_from_file_location("custom_module", file_path) assert spec is not None module = importlib.util.module_from_spec(spec) try: ...
@@ -109,6 +109,11 @@ def load_reward_manager( An instance of the specified reward manager class. """ + # Try to get a custom reward function based on the configuration + # user defined reward manager can be registered in custom_reward_fn + compute_score = get_custom_reward_fn(config) + final...
verl/trainer/ppo/reward.py
0
Python
1
none
16
51
51
true
[recipe] fix: move all collabllm files into recipe directory
3,706
volcengine/verl
16,907
Python
chenhaiq
critic_lr=2e-6 gae_gamma=1.0 gae_lam=1.0 critic_warmup=20 train_batch_size=512 ppo_mini_batch_size=512 n_resp_per_prompt_val=30 # ================= perfomance ================= infer_tp=4 # vllm train_sp=4 # train offload=True actor_max_token_len_per_gpu=$(( (max_prompt_length + max_response_length) * 2 )) critic_...
No issues found.
critic_lr=2e-6 gae_gamma=1.0 gae_lam=1.0 critic_warmup=20 train_batch_size=512 ppo_mini_batch_size=512 n_resp_per_prompt_val=30 # ================= perfomance ================= infer_tp=4 # vllm train_sp=4 # train offload=True actor_max_token_len_per_gpu=$(( (max_prompt_length + max_response_length) * 2 )) critic_...
@@ -0,0 +1,125 @@ +set -x + +# ================= data/model/tool ================= +HDFS_ROOT=${HDFS_ROOT:-$PWD} +DATA_ROOT=${DATA_ROOT:-$PWD} + +dapo_math_17k=$DATA_ROOT/dataset/BytedTsinghua-SIA/DAPO-Math-17k +aime_2024=$DATA_ROOT/dataset/Maxwell-Jia/AIME_2024 +aime_2025=$DATA_ROOT/dataset/yentinglin/aime_2025 +actor...
recipe/retool/run_gpt_oss_ppo.sh
0
Shell
1
none
16
51
51
true
[recipe, rollout] feat: enable gpt-oss training for tool agent add gpt-oss for retool recipe
3,837
volcengine/verl
16,907
Python
HJSang
# clear kv cache get_torch_device().empty_cache() return output @register(dispatch_mode=make_nd_compute_dataproto_dispatch_fn(mesh_name="actor")) @DistProfiler.annotate(color="blue", role="actor_compute_log_prob") def compute_log_prob(self, data: DataProto): # when is_lora i...
No issues found.
# clear kv cache get_torch_device().empty_cache() return output @register(dispatch_mode=make_nd_compute_dataproto_dispatch_fn(mesh_name="actor")) @DistProfiler.annotate(color="blue", role="actor_compute_log_prob") def compute_log_prob(self, data: DataProto): # when is_lora i...
@@ -15,7 +15,6 @@ The main entry point to run the PPO algorithm """ -import asyncio import datetime import json import logging @@ -85,6 +84,7 @@ from verl.utils.profiler import DistProfiler, DistProfilerExtension, ProfilerConfig, log_gpu_memory_usage, simple_timer from verl.utils.profiler.performance import re...
verl/workers/fsdp_workers.py
0
Python
1
none
16
51
51
true
[worker] fix: create a new event loop if none exists
3,839
volcengine/verl
16,907
Python
baymax591
train_path=$HOME/data/geo3k/train.parquet test_path=$HOME/data/geo3k/test.parquet python3 -m verl.trainer.main_ppo --config-path=config \ --config-name='ppo_megatron_trainer.yaml'\ algorithm.adv_estimator=grpo \ data.train_files="$train_path" \ data.val_files="$test_path" \ data.train_batch_size=51...
No issues found.
train_path=$HOME/data/geo3k/train.parquet test_path=$HOME/data/geo3k/test.parquet python3 -m verl.trainer.main_ppo --config-path=config \ --config-name='ppo_megatron_trainer.yaml'\ algorithm.adv_estimator=grpo \ data.train_files="$train_path" \ data.val_files="$test_path" \ data.train_batch_size=51...
@@ -2,15 +2,6 @@ set -x ENGINE=${1:-vllm} export CUDA_DEVICE_MAX_CONNECTIONS=1 # For megatron communication/computation overlapping - -# dependency: vllm>=0.11.0, megatron-lm>=0.13, mbridge with qwen3vl_cp branch -# environment option1: use a stable container later than docker://verlai/verl:vllm011.dev6 - # and...
examples/grpo_trainer/run_qwen3_vl-30b-megatron.sh
0
Shell
1
none
16
51
51
true
[env] feat: update docker file building schema, from VLLM base images
3,937
volcengine/verl
16,907
Python
ISEEKYAN
output_lst = [] ctx = torch.no_grad() if forward_only else nullcontext() for micro_batch in micro_batches: with ctx: loss, meta_info = self.forward_step(micro_batch, loss_function=loss_function, forward_only=forward_only) if not forward_only: ...
No issues found.
output_lst = [] ctx = torch.no_grad() if forward_only else nullcontext() for micro_batch in micro_batches: with ctx: loss, meta_info = self.forward_step(micro_batch, loss_function=loss_function, forward_only=forward_only) if not forward_only: ...
@@ -476,6 +476,14 @@ def forward_backward_batch(self, data: TensorDict, loss_function: Callable, forw # note that the global_batch_size should include data on all the dp tu.assign_non_tensor(data, sp_size=self.ulysses_sequence_parallel_size) + # compute num_tokens in global batch for loss nor...
verl/workers/engine/fsdp/transformer_impl.py
0
Python
1
none
16
51
51
true
[trainer] fix: normalize sft loss by num_tokens in global batch
3,994
volcengine/verl
16,907
Python
wuxibin89
2. Try current working directory 3. Try relative to verl package installation (project root) Args: config_path: Configuration file path (relative or absolute) Returns: Absolute path to the configuration file Raises: FileNotFoundError: If the configuration file cannot be fo...
No issues found.
2. Try current working directory 3. Try relative to verl package installation (project root) Args: config_path: Configuration file path (relative or absolute) Returns: Absolute path to the configuration file Raises: FileNotFoundError: If the configuration file cannot be fo...
@@ -12,6 +12,65 @@ # See the License for the specific language governing permissions and # limitations under the License. +import os + + +def resolve_config_path(config_path: str) -> str: + """Resolve agent loop configuration file path. + + In multi-node Ray training, relative paths may not resolve correctly ...
verl/experimental/agent_loop/utils.py
0
Python
1
none
16
51
51
true
[rollout] fix: resolve agent loop config path in multi-node Ray training
4,029
volcengine/verl
16,907
Python
CzsGit
@GPUMemoryLogger(role="dp actor", logger=logger) def update_policy(self, data: DataProto): # make sure we are in training mode self.actor_module.train() temperature = data.meta_info["temperature"] # temperature must be in the data.meta_info to avoid silent error select_keys = ...
No issues found.
@GPUMemoryLogger(role="dp actor", logger=logger) def update_policy(self, data: DataProto): # make sure we are in training mode self.actor_module.train() temperature = data.meta_info["temperature"] # temperature must be in the data.meta_info to avoid silent error select_keys = ...
@@ -295,13 +295,13 @@ def update_policy(self, data: DataProto): ] if self.config.use_kl_loss: select_keys.append("ref_log_prob") - # if self.config.tis_imp_ratio_cap > 0: - # assert "rollout_log_probs" in data.batch.keys(), ( - # "Truncated Importance Samp...
recipe/flowrl/flowrl_actor.py
0
Python
1
none
16
51
51
true
[worker, trainer, recipe] feat: add FP16 training and inference support
4,036
volcengine/verl
16,907
Python
Xuekai-Zhu
TRAIN_FILE=${TRAIN_FILE:-"${RAY_DATA_HOME}/data/dapo-math-17k.parquet"} TEST_FILE=${TEST_FILE:-"${RAY_DATA_HOME}/data/aime-2024.parquet"} # Algorithm temperature=1.0 top_p=1.0 top_k=-1 # 0 for HF rollout, -1 for vLLM rollout val_top_p=0.7 # Performance Related Parameter use_dynamic_bsz=True actor_ppo_max_token_len=$(...
No issues found.
TRAIN_FILE=${TRAIN_FILE:-"${RAY_DATA_HOME}/data/dapo-math-17k.parquet"} TEST_FILE=${TEST_FILE:-"${RAY_DATA_HOME}/data/aime-2024.parquet"} # Algorithm temperature=1.0 top_p=1.0 top_k=-1 # 0 for HF rollout, -1 for vLLM rollout val_top_p=0.7 # Performance Related Parameter use_dynamic_bsz=True actor_ppo_max_token_len=$(...
@@ -0,0 +1,142 @@ +#!/usr/bin/env bash +set -xeuo pipefail + + +rollout_mode="async" +rollout_name="vllm" # sglang or vllm +if [ "$rollout_mode" = "async" ]; then + export VLLM_USE_V1=1 + return_raw_chat="True" +fi +dtype="float16" # ["bfloat16", "float16"] + +project_name='DAPO-fp16' +exp_name='fp16' + +adv_esti...
recipe/dapo/test_dapo_8b_megatron_fp16.sh
0
Shell
1
none
16
51
51
true
[megatron] feat: fp16 training (dense and MoE supported)
4,086
volcengine/verl
16,907
Python
ISEEKYAN
Update Prometheus configuration file with server addresses and reload on first node. server_addresses: vllm or sglang server addresses """ if not server_addresses: logger.warning("No server addresses available to update Prometheus config") return try: # Get Prometheus conf...
No issues found.
Update Prometheus configuration file with server addresses and reload on first node. server_addresses: vllm or sglang server addresses """ if not server_addresses: logger.warning("No server addresses available to update Prometheus config") return try: # Get Prometheus conf...
@@ -0,0 +1,107 @@ +# Copyright 2025 Meituan 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 re...
verl/experimental/agent_loop/prometheus_utils.py
0
Python
1
none
16
51
51
true
[sglang,vllm] feat: use prometheus and grafana to show rollout message
4,088
volcengine/verl
16,907
Python
ArronHZG
@ray.remote(num_cpus=1) # please make sure main_task is not scheduled on head class TaskRunner: def run(self, config): # print initial config from pprint import pprint from omegaconf import OmegaConf from verl.utils.fs import copy_to_local print(f"TaskRunner hostname: {so...
No issues found.
@ray.remote(num_cpus=1) # please make sure main_task is not scheduled on head class TaskRunner: def run(self, config): # print initial config from pprint import pprint from omegaconf import OmegaConf from verl.utils.fs import copy_to_local print(f"TaskRunner hostname: {so...
@@ -97,13 +97,13 @@ def run(self, config): if config.actor_rollout_ref.actor.strategy in {"fsdp", "fsdp2"}: assert config.critic.strategy in {"fsdp", "fsdp2"} - from verl.workers.fsdp_workers import ActorRolloutRefWorker, CriticWorker + from verl.workers.fsdp_workers import...
recipe/dapo/main_dapo.py
0
Python
1
none
16
51
51
true
[BREAKING][rollout] feat: change rollout to server mode by default
4,106
volcengine/verl
16,907
Python
wuxibin89
raise NotImplementedError(f"{sequence_length=} is larger than {max_length=}") else: raise NotImplementedError(f"Unknown truncation method {truncation}") return input_ids, attention_mask def tokenize_and_postprocess_data( prompt: str, tokenizer: PreTrainedTokenizer, max_length:...
No issues found.
raise NotImplementedError(f"{sequence_length=} is larger than {max_length=}") else: raise NotImplementedError(f"Unknown truncation method {truncation}") return input_ids, attention_mask def tokenize_and_postprocess_data( prompt: str, tokenizer: PreTrainedTokenizer, max_length:...
@@ -775,3 +775,27 @@ def distributed_masked_mean(local_tensor, local_mask): global_mean = local_sum / local_num return global_mean + + +@contextmanager +def use_original_torch_compile(): + """torch.compile might be replaced by mindspeed on NPU, this contextmanager + can revert torch.compile temporaril...
verl/utils/torch_functional.py
0
Python
1
none
16
51
51
true
[vllm] fix: Fix issues that occur during the ACLGraph initialization process in the NPU.
4,209
volcengine/verl
16,907
Python
chengminhua
def _initialize_llm_servers(self): rollout_world_size = self.config.rollout.tensor_model_parallel_size world_size = ( self.resource_pool.world_size if self.resource_pool # colocate mode else self.config.n_gpus_per_node * self.config.nnodes # standalone mode ...
No issues found.
def _initialize_llm_servers(self): rollout_world_size = self.config.rollout.tensor_model_parallel_size world_size = ( self.resource_pool.world_size if self.resource_pool # colocate mode else self.config.n_gpus_per_node * self.config.nnodes # standalone mode ...
@@ -75,7 +75,14 @@ def _initialize_llm_servers(self): for replica_rank in range(num_replicas) ] if self.resource_pool: - self._run_all([server.init_colocated(self.resource_pool) for server in self.rollout_replicas]) + split_resource_pool = self.resource_pool.split(sp...
verl/experimental/reward/reward_model.py
0
Python
1
none
16
51
51
true
[single_controller] feat: support resource pool split method
4,251
volcengine/verl
16,907
Python
yyDing1
load_megatron_optimizer(self.actor_optimizer) log_gpu_memory_usage("After load actor optimizer during update_actor", logger=logger) micro_batch_size = self.config.actor.ppo_micro_batch_size_per_gpu data.meta_info["micro_batch_size"] = micro_batch_size dataloader = self.a...
No issues found.
load_megatron_optimizer(self.actor_optimizer) log_gpu_memory_usage("After load actor optimizer during update_actor", logger=logger) micro_batch_size = self.config.actor.ppo_micro_batch_size_per_gpu data.meta_info["micro_batch_size"] = micro_batch_size dataloader = self.a...
@@ -806,6 +806,12 @@ def save_checkpoint(self, checkpoint_path, hdfs_path=None, global_step=0, max_ck if self._is_offload_param: offload_megatron_model_to_cpu(self.actor_module) + @register(dispatch_mode=Dispatch.ONE_TO_ALL) + def async_calls_finalize_fn_exec(self, blocking=False): + ...
verl/workers/megatron_workers.py
0
Python
1
none
16
51
51
true
[megatron] fix: megatron async save ckpt fix
4,253
volcengine/verl
16,907
Python
Leem-Li
assert unpadd_data["info"] == "test_info" padded_data, pad_size = tu.pad_to_divisor(data, size_divisor=7) assert pad_size == 4 expected_obs = torch.tensor([[1, 2], [3, 4], [5, 6], [1, 2], [3, 4], [5, 6], [1, 2]]) expected_labels = ["a", "b", "c", "a", "b", "c", "a"] assert torch.all(torch.eq(p...
No issues found.
assert unpadd_data["info"] == "test_info" padded_data, pad_size = tu.pad_to_divisor(data, size_divisor=7) assert pad_size == 4 expected_obs = torch.tensor([[1, 2], [3, 4], [5, 6], [1, 2], [3, 4], [5, 6], [1, 2]]) expected_labels = ["a", "b", "c", "a", "b", "c", "a"] assert torch.all(torch.eq(p...
@@ -22,6 +22,7 @@ import numpy as np import pytest import torch +from tensordict.tensorclass import NonTensorData, NonTensorStack from verl.utils import tensordict_utils as tu @@ -45,10 +46,10 @@ def test_union_tensor_dict(): # conflict in tensor values tu.union_tensor_dict(data1, data_with_co...
tests/test_protocol_v2_on_cpu.py
0
Python
1
none
16
51
51
true
[misc] fix: fix list conversion in get_tensordict
4,304
volcengine/verl
16,907
Python
PeterSH6
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) if pixel_values_videos is not None: pixel_values_videos = pixel_values_videos.type(model.visual.dtype) video_embeds, deepstack_video_embeds = model.visual(pixel_values_videos, grid_thw=video_grid_thw) n_video_tok...
No issues found.
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) if pixel_values_videos is not None: pixel_values_videos = pixel_values_videos.type(model.visual.dtype) video_embeds, deepstack_video_embeds = model.visual(pixel_values_videos, grid_thw=video_grid_thw) n_video_tok...
@@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import functools import logging import os from dataclasses import dataclass @@ -334,3 +335,41 @@ def forward_with_triton_backend( entropy=entropy, hidden_states=outputs.hidd...
verl/models/transformers/qwen3_vl.py
0
Python
1
none
16
51
51
true
[fsdp] fix: qwen3vlmoe with Monkey patch to fix a bug in transformers 4.57.x
4,402
volcengine/verl
16,907
Python
pengyanai
2. Worker groups for each role (actor, critic, etc.) """ self.resource_pool_manager.create_resource_pool() self.resource_pool_to_cls = {pool: {} for pool in self.resource_pool_manager.resource_pool_dict.values()} # create actor and rollout if self.hybrid_engine: ...
No issues found.
2. Worker groups for each role (actor, critic, etc.) """ self.resource_pool_manager.create_resource_pool() self.resource_pool_to_cls = {pool: {} for pool in self.resource_pool_manager.resource_pool_dict.values()} # create actor and rollout if self.hybrid_engine: ...
@@ -1315,15 +1315,10 @@ def fit(self): batch_dict, repeat_times=self.config.actor_rollout_ref.rollout.n, interleave=True ) batch: TensorDict = self.dict_to_tensordict(repeated_batch_dict) - asyncio.run(self.tq_client.async_put(data=batch, partition_i...
recipe/transfer_queue/ray_trainer.py
0
Python
1
none
16
51
51
true
[data] feat: TransferQueue - Add zero-copy serialization support & usage improvement
4,429
volcengine/verl
16,907
Python
0oshowero0
return dx, dw, None, None def qwen3_moe_sparse_moe_block_forward_npu(self, hidden_states: torch.Tensor) -> torch.Tensor: """NPU optimized implementation for `forward` in Qwen3MoeSparseMoeBlock.""" # hidden_states: (batch_size, sequence_length, hidden_size) hidden_dim = hidden_states.shape[...
No issues found.
return dx, dw, None, None def qwen3_moe_sparse_moe_block_forward_npu(self, hidden_states: torch.Tensor) -> torch.Tensor: """NPU optimized implementation for `forward` in Qwen3MoeSparseMoeBlock.""" # hidden_states: (batch_size, sequence_length, hidden_size) hidden_dim = hidden_states.shape[...
@@ -239,6 +239,7 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # Patches for Qwen3 Model modeling_qwen3.Qwen3RMSNorm.forward = rms_norm_forward_npu modeling_qwen3.Qwen3MLP.forward = silu_forward_npu +modeling_qwen3.apply_rotary_pos_emb = apply_rotary_pos_emb_npu # Patches for Qwen3 MoE M...
verl/models/transformers/npu_patch.py
0
Python
1
none
16
51
51
true
[model] feat: add qwen3-4b grpo script on ASCEND NPU A3
4,432
volcengine/verl
16,907
Python
5082459
rollout_config = config.actor_rollout_ref.rollout model_config = config.actor_rollout_ref.model rollout_server_class = get_rollout_replica_class(ROLLOUT_NAME) server = rollout_server_class( replica_rank=0, config=rollout_config, model_config=model_co...
No issues found.
rollout_config = config.actor_rollout_ref.rollout model_config = config.actor_rollout_ref.model rollout_server_class = get_rollout_replica_class(ROLLOUT_NAME) server = rollout_server_class( replica_rank=0, config=rollout_config, model_config=model_co...
@@ -0,0 +1,217 @@ +# Copyright 2024 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 ...
tests/workers/rollout/rollout_vllm/test_vllm_abort.py
0
Python
1
none
16
51
51
true
[vllm] feat: support abort generating requests in vllm server
4,453
volcengine/verl
16,907
Python
PeterSH6
wg.init_model() batch_size = 8 seqlen = 32 response_length = seqlen // 2 torch.manual_seed(1) np.random.seed(1) input_ids = torch.randint(0, model_config.hf_config.vocab_size, (batch_size, seqlen)) attention_mask = create_random_mask( input_ids=input_ids, max_ratio_of_valid_t...
No issues found.
wg.init_model() batch_size = 8 seqlen = 32 response_length = seqlen // 2 torch.manual_seed(1) np.random.seed(1) input_ids = torch.randint(0, model_config.hf_config.vocab_size, (batch_size, seqlen)) attention_mask = create_random_mask( input_ids=input_ids, max_ratio_of_valid_t...
@@ -36,6 +36,7 @@ from verl import DataProto from verl.single_controller.ray import RayClassWithInitArgs, RayResourcePool, RayWorkerGroup from verl.trainer.config import CheckpointConfig +from verl.utils import tensordict_utils as tu from verl.utils.model import compute_position_id_with_mask, create_random_mask fr...
tests/models/test_engine.py
0
Python
1
none
16
51
51
true
[model] feat: enhances TrainingWorker
4,461
volcengine/verl
16,907
Python
vermouth1992
LEVEL="level0" CONTENTS=['npu','cpu'] ANALYSIS=True python3 -m verl.trainer.main_ppo \ algorithm.adv_estimator=grpo \ data.train_files=$HOME/data/gsm8k/train.parquet \ data.val_files=$HOME/data/gsm8k/test.parquet \ data.train_batch_size=32 \ data.max_prompt_length=1024 \ data.max_response_lengt...
No issues found.
LEVEL="level0" CONTENTS=['npu','cpu'] ANALYSIS=True python3 -m verl.trainer.main_ppo \ algorithm.adv_estimator=grpo \ data.train_files=$HOME/data/gsm8k/train.parquet \ data.val_files=$HOME/data/gsm8k/test.parquet \ data.train_batch_size=32 \ data.max_prompt_length=1024 \ data.max_response_lengt...
@@ -8,7 +8,7 @@ PROFILE_RANKS="[1,2]" # profiling NPU options SAVE_PATH="$HOME/profile_data" -LEVEL="level1" +LEVEL="level0" CONTENTS=['npu','cpu'] ANALYSIS=True
examples/grpo_trainer/run_qwen2_5_7b_grpo_discrete_prof_npu.sh
0
Shell
1
none
16
51
51
true
[perf] fix: modify the NPU profiler default configuration
4,475
volcengine/verl
16,907
Python
tardis-key
is_npu_available = is_torch_npu_available() def get_visible_devices_keyword() -> str: """Function that gets visible devices keyword name. Returns: 'CUDA_VISIBLE_DEVICES' or `ASCEND_RT_VISIBLE_DEVICES` """ return "CUDA_VISIBLE_DEVICES" if is_cuda_available else "ASCEND_RT_VISIBLE_DEVICES" def...
No issues found.
is_npu_available = is_torch_npu_available() def get_visible_devices_keyword() -> str: """Function that gets visible devices keyword name. Returns: 'CUDA_VISIBLE_DEVICES' or `ASCEND_RT_VISIBLE_DEVICES` """ return "CUDA_VISIBLE_DEVICES" if is_cuda_available else "ASCEND_RT_VISIBLE_DEVICES" def...
@@ -92,3 +92,15 @@ def set_expandable_segments(enable: bool) -> None: """ if is_cuda_available: torch.cuda.memory._set_allocator_settings(f"expandable_segments:{enable}") + + +def auto_set_ascend_device_name(config): + if config and config.trainer and config.trainer.device: + if is_torch_np...
verl/utils/device.py
0
Python
1
none
16
51
51
true
[hardware] feat: Auto set device_name to npu for Ascend NPU
4,489
volcengine/verl
16,907
Python
FightingZhen
train_prompt_mini_bsz=32 total_rollout_steps=$(((train_bsz * 400))) test_freq=25 staleness_threshold=0.6 # 0 0.3 1 require_batches=1 total_train_gpus=$((n_gpus_training * n_nodes_train)) total_rollout_gpus=$((n_gpus_rollout * n_nodes_rollout)) trigger_parameter_sync_step=$((train_bsz / ( train_prompt_mini_bsz * require...
No issues found.
train_prompt_mini_bsz=32 total_rollout_steps=$(((train_bsz * 400))) test_freq=25 staleness_threshold=0.6 # 0 0.3 1 require_batches=1 total_train_gpus=$((n_gpus_training * n_nodes_train)) total_rollout_gpus=$((n_gpus_rollout * n_nodes_rollout)) trigger_parameter_sync_step=$((train_bsz / ( train_prompt_mini_bsz * require...
@@ -0,0 +1,191 @@ +#!/usr/bin/env bash +set -xeuo pipefail + +project_name='DAPO-Qwen3-30B-A3B-Base-Async' +exp_name='Fsdp2-tp4sp4' + +# Ray +RAY_ADDRESS=${RAY_ADDRESS:-"http://localhost:8265"} +WORKING_DIR=${WORKING_DIR:-"${PWD}"} +RUNTIME_ENV=${RUNTIME_ENV:-"${WORKING_DIR}/verl/trainer/runtime_env.yaml"} +# Paths +DA...
recipe/fully_async_policy/shell/dapo_30b_a3b_base_math_fsdp.sh
0
Shell
1
none
16
51
51
true
[rollout,vllm] feat: disable sleep mode in fully-async mode
4,521
volcengine/verl
16,907
Python
chenjiaoAngel
""" Context manager entry for switching the engine and model into evaluation mode. Usage: with engine.eval_mode(): # runs in evaluation mode """ return EngineEvalModeCtx(self, **kwargs) def optimizer_zero_grad(self): """ Zero out ...
No issues found.
""" Context manager entry for switching the engine and model into evaluation mode. Usage: with engine.eval_mode(): # runs in evaluation mode """ return EngineEvalModeCtx(self, **kwargs) def optimizer_zero_grad(self): """ Zero out ...
@@ -41,13 +41,11 @@ load_megatron_optimizer, offload_megatron_model_to_cpu, offload_megatron_optimizer, - per_tensor_generator, register_megatron_training_hooks, ) from verl.utils.model import ( extract_multi_modal_inputs_tensordict, load_mcore_dist_weights, - load_megatron_gptmode...
verl/workers/engine/megatron/transformer_impl.py
0
Python
1
none
16
51
51
true
[megatron] chore: clean legacy code path part 1, make engine use mbridge by default
4,528
volcengine/verl
16,907
Python
ISEEKYAN
- "pkg://verl.utils.dataset.rl_dataset" - "pkg://verl/utils/dataset/rl_dataset" - or `file_path` (absolute or relative), e.g., - "file://verl/utils/dataset/rl_dataset.py" - "/path/to/verl/utils/dataset/rl_dataset.py" ...
No issues found.
- "pkg://verl.utils.dataset.rl_dataset" - "pkg://verl/utils/dataset/rl_dataset" - or `file_path` (absolute or relative), e.g., - "file://verl/utils/dataset/rl_dataset.py" - "/path/to/verl/utils/dataset/rl_dataset.py" ...
@@ -197,6 +197,39 @@ def load_extern_object(module_path: str, object_name: str) -> object: return getattr(module, object_name) +def load_class_from_fqn(fqn: str, description: str = "class") -> type: + """Load a class from its fully qualified name. + + Args: + fqn: Fully qualified class name (e.g.,...
verl/utils/import_utils.py
0
Python
1
none
16
51
51
true
[rollout, trainer] feat: extend agent loop for custom implementations
4,548
volcengine/verl
16,907
Python
JoyboyBrian
# 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. from abc import ABC, abstractmethod from typing import Any, Callable imp...
No issues found.
# 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. from abc import ABC, abstractmethod from typing import Any, Callable imp...
@@ -43,3 +43,30 @@ def __call__( return_dict: bool = False, ) -> torch.Tensor | dict[str, Any]: pass + + def _extract_reward_from_rm_scores( + self, data: DataProto, return_dict: bool = False + ) -> torch.Tensor | dict[str, Any] | None: + """ + Extract reward from alrea...
verl/workers/reward_manager/abstract.py
0
Python
1
none
16
51
51
true
[reward] feat: Optimize reward computation when use_reward_loop=True
4,581
volcengine/verl
16,907
Python
none0663
@dataclass class ProfileConfig(BaseConfig): """Configuration for profiling. The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config. Args: profile_ranks (Optional[list[int]]): List of ranks to profile. None means all ranks. step_start (int): Sta...
No issues found.
@dataclass class ProfileConfig(BaseConfig): """Configuration for profiling. The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config. Args: profile_ranks (Optional[list[int]]): List of ranks to profile. None means all ranks. step_start (int): Sta...
@@ -36,6 +36,7 @@ class CheckpointConfig(BaseConfig): save_contents: list[str] = field(default_factory=lambda: ["model", "optimizer", "extra"]) load_contents: list[str] = field(default_factory=lambda: ["model", "optimizer", "extra"]) async_save: bool = False + mbridge_config: dict[str, Any] = field(de...
verl/trainer/config/config.py
0
Python
1
none
16
51
51
true
[megatron] feat: use yaml to manage mbridge args
4,584
volcengine/verl
16,907
Python
Kite0011
A dictionary mapping mesh names to whether they are used for collect. """ assert mesh_name not in self.__dispatch_dp_rank, ( f"{mesh_name} is already registered, {self.__dispatch_dp_rank.keys()}" ) assert mesh_name not in self.__collect_dp_rank, ( ...
No issues found.
A dictionary mapping mesh names to whether they are used for collect. """ assert mesh_name not in self.__dispatch_dp_rank, ( f"{mesh_name} is already registered, {self.__dispatch_dp_rank.keys()}" ) assert mesh_name not in self.__collect_dp_rank, ( ...
@@ -117,6 +117,9 @@ def _query_dispatch_info(self, mesh_name: str): @register(dispatch_mode=Dispatch.ONE_TO_ALL) def _query_collect_info(self, mesh_name: str): + return self.query_collect_info(mesh_name) + + def query_collect_info(self, mesh_name: str): """Query the collect info for a giv...
verl/single_controller/base/worker.py
0
Python
1
none
16
51
51
true
[data] feat: TransferQueue - remove redundant data collect for both TQ and DataProto
4,618
volcengine/verl
16,907
Python
0oshowero0
assert actor_worker_2.world_size == 4 data = DataProto.from_dict({"a": torch.zeros(8)}) actor_output_1 = actor_worker_1.add(data) actor_output_2 = actor_worker_2.add(data) assert actor_output_1.batch["a"].tolist() == [0, 0, 1, 1, 2, 2, 3, 3] assert actor_output_2.batch["a"].tolist() == [100, 10...
No issues found.
assert actor_worker_2.world_size == 4 data = DataProto.from_dict({"a": torch.zeros(8)}) actor_output_1 = actor_worker_1.add(data) actor_output_2 = actor_worker_2.add(data) assert actor_output_1.batch["a"].tolist() == [0, 0, 1, 1, 2, 2, 3, 3] assert actor_output_2.batch["a"].tolist() == [100, 10...
@@ -26,19 +26,20 @@ RayWorkerGroup, split_resource_pool, ) +from verl.utils.device import get_device_name, get_nccl_backend @ray.remote class Actor(Worker): def __init__(self, worker_id) -> None: super().__init__() self.worker_id = worker_id - self.temp_tensor = torch.rand...
tests/single_controller/test_split_resource_pool.py
0
Python
1
none
16
51
51
true
[ci] feat: add npu unit test
4,626
volcengine/verl
16,907
Python
yyyy2000
# for training, we only care about loss and metrics delta_time = timer.last update_lr_scheduler = tu.get(data, key="update_lr_scheduler", default=False) # update lr scheduler if update_lr_scheduler: lr = self.engine.lr_scheduler_step() else: l...
No issues found.
# for training, we only care about loss and metrics delta_time = timer.last update_lr_scheduler = tu.get(data, key="update_lr_scheduler", default=False) # update lr scheduler if update_lr_scheduler: lr = self.engine.lr_scheduler_step() else: l...
@@ -27,11 +27,7 @@ from verl.single_controller.base.decorator import Dispatch, make_nd_compute_dataproto_dispatch_fn, register from verl.utils import tensordict_utils as tu from verl.utils.config import omega_conf_to_dataclass -from verl.utils.device import ( - get_device_name, - get_torch_device, - set_exp...
verl/workers/engine_workers.py
0
Python
1
none
16
51
51
true
[megatron] feat: LoRA adapter only refit (TensorLoRARequest)
4,632
volcengine/verl
16,907
Python
HollowMan6
log_gpu_memory_usage("After rollout offload", logger=logger) for model in self.actor.actor_module: model.train() # add empty cache after each compute aggressive_empty_cache(force_sync=True) # FIXME(@wuxibin): megatron+sglang failed with `expandable_segments:True...
No issues found.
log_gpu_memory_usage("After rollout offload", logger=logger) for model in self.actor.actor_module: model.train() # add empty cache after each compute aggressive_empty_cache(force_sync=True) # FIXME(@wuxibin): megatron+sglang failed with `expandable_segments:True...
@@ -906,12 +906,16 @@ def load_pretrained_model(self, checkpoint_path, del_local_after_load=True): def save_checkpoint(self, checkpoint_path, hdfs_path=None, global_step=0, max_ckpt_to_keep=None): if self._is_offload_param: load_megatron_model_to_gpu(self.actor_module) + if self.checkp...
verl/workers/megatron_workers.py
0
Python
1
none
16
51
51
true
[megatron] fix: megatron async save ckpt fix
4,638
volcengine/verl
16,907
Python
Leem-Li
install_requires = [ "accelerate", "codetiming", "datasets", "dill", "hydra-core", "numpy<2.0.0", "pandas", "peft", "pyarrow>=19.0.0", "pybind11", "pylatexenc", "ray[default]>=2.41.0", "torchdata", "tensordict>=0.8.0,<=0.10.0,!=0.9.0", "transformers", "wa...
No issues found.
install_requires = [ "accelerate", "codetiming", "datasets", "dill", "hydra-core", "numpy<2.0.0", "pandas", "peft", "pyarrow>=19.0.0", "pybind11", "pylatexenc", "ray[default]>=2.41.0", "torchdata", "tensordict>=0.8.0,<=0.10.0,!=0.9.0", "transformers", "wa...
@@ -57,7 +57,7 @@ ] TRL_REQUIRES = ["trl<=0.9.6"] MCORE_REQUIRES = ["mbridge"] -TRANSFERQUEUE_REQUIRES = ["TransferQueue==0.1.4.dev1"] +TRANSFERQUEUE_REQUIRES = ["TransferQueue==0.1.5.dev3"] extras_require = { "test": TEST_REQUIRES,
setup.py
0
Python
1
none
16
51
51
true
[data] feat: TransferQueue - Support sync TransferQueue client & optimize clear interface and validation procedure
4,660
volcengine/verl
16,907
Python
0oshowero0
critic_cls = RayClassWithInitArgs(cls=self.role_worker_mapping[Role.Critic], config=critic_cfg) self.resource_pool_to_cls[resource_pool]["critic"] = critic_cls # create reference policy if needed if self.use_reference_policy: resource_pool = self.resource_pool_manage...
No issues found.
critic_cls = RayClassWithInitArgs(cls=self.role_worker_mapping[Role.Critic], config=critic_cfg) self.resource_pool_to_cls[resource_pool]["critic"] = critic_cls # create reference policy if needed if self.use_reference_policy: resource_pool = self.resource_pool_manage...
@@ -48,11 +48,7 @@ from verl import DataProto from verl.experimental.dataset.sampler import AbstractCurriculumSampler -from verl.single_controller.ray import ( - RayClassWithInitArgs, - RayResourcePool, - RayWorkerGroup, -) +from verl.single_controller.ray import RayClassWithInitArgs, RayResourcePool, RayW...
verl/experimental/transfer_queue/ray_trainer.py
0
Python
1
none
16
51
51
true
[megatron] feat: Share actor and ref in LoRA
4,673
volcengine/verl
16,907
Python
HollowMan6
Detects the available accelerator and returns the corresponding PyTorch device type string. Currently supports CUDA, Ascend NPU, and CPU. Returns: str: Device type string ('cuda', 'npu', or 'cpu'). """ if is_cuda_available: device = "cuda" elif is_npu_available: device =...
No issues found.
Detects the available accelerator and returns the corresponding PyTorch device type string. Currently supports CUDA, Ascend NPU, and CPU. Returns: str: Device type string ('cuda', 'npu', or 'cpu'). """ if is_cuda_available: device = "cuda" elif is_npu_available: device =...
@@ -15,19 +15,26 @@ logger = logging.getLogger(__name__) -def is_torch_npu_available() -> bool: +def is_torch_npu_available(check_device=True) -> bool: """Check if Ascend NPU is available for PyTorch operations. Attempts to detect NPU availability by checking for the torch.npu module and its is_av...
verl/utils/device.py
0
Python
1
none
16
51
51
true
[sglang] fix: sglang TP+DP support / port bug
4,715
volcengine/verl
16,907
Python
hustmf
"num_attention_heads": 16, "num_key_value_heads": 8, "head_dim": 256, "sliding_window": 1024, "layer_types": None, # Will be auto-generated based on sliding_window_pattern "sliding_window_pattern": 6, # Every 6th layer is fu...
No issues found.
"num_attention_heads": 16, "num_key_value_heads": 8, "head_dim": 256, "sliding_window": 1024, "layer_types": None, # Will be auto-generated based on sliding_window_pattern "sliding_window_pattern": 6, # Every 6th layer is fu...
@@ -16,14 +16,16 @@ import pytest -from verl.utils.flops_counter import _DEVICE_FLOPS, FlopsCounter, get_device_flops +from verl.utils.flops_counter import FlopsCounter VALID_CONFIG_TYPE = {"llama", "qwen2", "qwen3", "qwen3_moe", "deepseek_v3", "mistral", "gemma3_text", "apertus"} class Config: def __...
tests/utils/test_flops_counter.py
0
Python
1
none
16
51
51
true
[perf] feat: Add MFU for Qwen3-VL dense
4,753
volcengine/verl
16,907
Python
zhihaofang1017
COMMAND="torchrun --standalone --nnodes=${NNODES:-1} --nproc-per-node=${NUM_GPUS:-1} ${ENTRYPOINT}" else ENTRYPOINT=${ENTRYPOINT:-"-m verl.trainer.sft_trainer_ray"} COMMAND="python ${ENTRYPOINT} trainer.nnodes=${NNODES:-1} trainer.n_gpus_per_node=${NUM_GPUS:-1}" fi RESUME_MODE=disable ckpts_home=${ckpts_home:-~...
No issues found.
COMMAND="torchrun --standalone --nnodes=${NNODES:-1} --nproc-per-node=${NUM_GPUS:-1} ${ENTRYPOINT}" else ENTRYPOINT=${ENTRYPOINT:-"-m verl.trainer.sft_trainer_ray"} COMMAND="python ${ENTRYPOINT} trainer.nnodes=${NNODES:-1} trainer.n_gpus_per_node=${NUM_GPUS:-1}" fi RESUME_MODE=disable ckpts_home=${ckpts_home:-~...
@@ -1,5 +1,17 @@ set -x +NUM_GPUS=${NUM_GPUS:-4} + +mode=${mode:-spmd} + +if [ "$mode" = "spmd" ]; then + ENTRYPOINT=${ENTRYPOINT:-"-m verl.trainer.sft_trainer"} + COMMAND="torchrun --standalone --nnodes=${NNODES:-1} --nproc-per-node=${NUM_GPUS:-1} ${ENTRYPOINT}" +else + ENTRYPOINT=${ENTRYPOINT:-"-m verl.trainer....
tests/special_npu/run_qwen2_5_05b_sft_peft_sp2.sh
0
Shell
1
none
16
51
51
true
[trainer] feat: enable ray-based sft trainer on ascend npu
4,764
volcengine/verl
16,907
Python
ji-huazhong
"""Test reduce_metrics correctly handles Metric objects.""" metric = Metric(aggregation="mean") metric.extend([1.0, 2.0, 3.0]) metrics = { "custom_metric": metric, "list_metric": [4.0, 5.0, 6.0], } result = reduce_metrics(metrics) self.as...
No issues found.
"""Test reduce_metrics correctly handles Metric objects.""" metric = Metric(aggregation="mean") metric.extend([1.0, 2.0, 3.0]) metrics = { "custom_metric": metric, "list_metric": [4.0, 5.0, 6.0], } result = reduce_metrics(metrics) self.as...
@@ -32,6 +32,10 @@ from verl.utils.metric import ( reduce_metrics, ) +from verl.utils.metric.utils import ( + AggregationType, + Metric, +) class TestReduceMetrics(unittest.TestCase): @@ -67,6 +71,167 @@ def test_reduce_metrics_single_value(self): self.assertEqual(result["single"], 5.0) +...
tests/trainer/ppo/test_metric_utils_on_cpu.py
0
Python
1
none
16
51
51
true
[worker, training_utils] fix: Engine Metric Aggregation
4,778
volcengine/verl
16,907
Python
JacobHelwig
rank, world_size, get_torch_device().current_device(), ) @register(dispatch_mode=Dispatch.ONE_TO_ALL, blocking=False) def sync_rollout_weights(self): assert (self._is_actor or self._is_rollout) and not self.config.hybrid_engine assert hasattr(self, "_...
No issues found.
rank, world_size, get_torch_device().current_device(), ) @register(dispatch_mode=Dispatch.ONE_TO_ALL, blocking=False) def sync_rollout_weights(self): assert (self._is_actor or self._is_rollout) and not self.config.hybrid_engine assert hasattr(self, "_...
@@ -22,7 +22,7 @@ from ray.util.collective import collective from torch.distributed.fsdp import FullyShardedDataParallel as FSDP -from recipe.one_step_off_policy.distributed_util import vllm_stateless_init_process_group +from recipe.one_step_off_policy.distributed_utils import vllm_stateless_init_process_group fro...
recipe/one_step_off_policy/fsdp_workers.py
0
Python
1
none
16
51
51
true
[recipe] fix: workaround for making the one-step off-policy recipe compatible with IPv6 environments on Ascend NPU
4,782
volcengine/verl
16,907
Python
ji-huazhong
set -x MODEL_ID=${MODEL_ID:-Qwen/Qwen2.5-0.5B-Instruct} MODEL_PATH=${MODEL_PATH:-${HOME}/.cache/models/${MODEL_ID}} python3 -m verl.trainer.main_ppo \ algorithm.adv_estimator=grpo \ data.train_files=$HOME/data/gsm8k/train.parquet \ data.val_files=$HOME/data/gsm8k/test.parquet \ data.train_batch_size=1...
No issues found.
set -x MODEL_ID=${MODEL_ID:-Qwen/Qwen2.5-0.5B-Instruct} MODEL_PATH=${MODEL_PATH:-${HOME}/.cache/models/${MODEL_ID}} python3 -m verl.trainer.main_ppo \ algorithm.adv_estimator=grpo \ data.train_files=$HOME/data/gsm8k/train.parquet \ data.val_files=$HOME/data/gsm8k/test.parquet \ data.train_batch_size=1...
@@ -1,5 +1,4 @@ set -x -export VLLM_ASCEND_ENABLE_NZ=0 MODEL_ID=${MODEL_ID:-Qwen/Qwen2.5-0.5B-Instruct} MODEL_PATH=${MODEL_PATH:-${HOME}/.cache/models/${MODEL_ID}}
tests/special_npu/run_qwen2_5_05b_grpo.sh
0
Shell
1
none
16
47
47
true
[rollout, vllm] fix: accuracy issue in verl serve mode + vllm-ascend + dp + ep + tp scenarios
4,783
volcengine/verl
16,907
Python
leo-pony
#!/usr/bin/env bash set -xeuo pipefail rm -rf ~/verl/test/log mkdir -p ~/verl/test/log export VERL_FILE_LOGGER_ROOT=~/verl/test/log VPP_SIZE=${VPP_SIZE:-2} # test with single gpu as golden echo "run with single gpu as golden" BACKEND=fsdp SP_SIZE=1 FSDP_SIZE=1 NUM_GPUS=1 FSDP_STRATEGY=fsdp VERL_FILE_LOGGER_PATH=~/ve...
No issues found.
#!/usr/bin/env bash set -xeuo pipefail rm -rf ~/verl/test/log mkdir -p ~/verl/test/log export VERL_FILE_LOGGER_ROOT=~/verl/test/log VPP_SIZE=${VPP_SIZE:-2} # test with single gpu as golden echo "run with single gpu as golden" BACKEND=fsdp SP_SIZE=1 FSDP_SIZE=1 NUM_GPUS=1 FSDP_STRATEGY=fsdp VERL_FILE_LOGGER_PATH=~/ve...
@@ -25,9 +25,8 @@ echo "run with sp2 fsdp_size2 num_gpus8 fsdp_strategy fsdp2" BACKEND=fsdp SP_SIZE=2 FSDP_SIZE=2 NUM_GPUS=8 FSDP_STRATEGY=fsdp2 bash tests/special_e2e/sft/run_sft_engine.sh # test with veomni -# FIXME(ji-huazhong): set SP=1 cause qwen_vl do not support SP right now -echo "run with sp1 fsdp_size4 nu...
tests/special_e2e/sft/test_sft_engine_all.sh
0
Shell
1
none
16
43
43
true
[trainer] feat: VeOmniEngine supports qwen3_vl ulysses
4,806
volcengine/verl
16,907
Python
A1waysBeenHere
def test_torch_save_data_proto(): obs = torch.tensor([[1, 2], [3, 4], [5, 6]]) labels = ["a", "b", "c"] data = tu.get_tensordict({"obs": obs, "labels": labels}, non_tensor_dict={"info": "test_info"}) filename = "test_data.pt" torch.save(data, filename) loaded_data = torch.load(filename, weight...
No issues found.
def test_torch_save_data_proto(): obs = torch.tensor([[1, 2], [3, 4], [5, 6]]) labels = ["a", "b", "c"] data = tu.get_tensordict({"obs": obs, "labels": labels}, non_tensor_dict={"info": "test_info"}) filename = "test_data.pt" torch.save(data, filename) loaded_data = torch.load(filename, weight...
@@ -988,3 +988,34 @@ def test_get_tensordict_agent_loop_scenario(): # Verify metadata assert td["global_steps"] == 42 + + +def test_contiguous(): + # create a tensordict that contains normal tensor, nested tensor, + # nontensorstack with numpy, nontensorstack with tensor, NonTensorData with numpy and ...
tests/test_protocol_v2_on_cpu.py
0
Python
1
none
16
51
51
true
[misc] feat: consolidate tensordict before dispatch
4,830
volcengine/verl
16,907
Python
vermouth1992
# runs in evaluation mode """ return EngineEvalModeCtx(self, **kwargs) def optimizer_zero_grad(self): """ Zero out gradients of all parameters before starting a new backward pass. """ self.optimizer.zero_grad() # use use_contiguous_buffers_in_...
No issues found.
# runs in evaluation mode """ return EngineEvalModeCtx(self, **kwargs) def optimizer_zero_grad(self): """ Zero out gradients of all parameters before starting a new backward pass. """ self.optimizer.zero_grad() # use use_contiguous_buffers_in_...
@@ -536,9 +536,12 @@ def forward_backward_batch(self, data: TensorDict, loss_function: Callable, forw else: return {} - def get_per_tensor_param(self): + def get_per_tensor_param(self, **kwargs): load_megatron_model_to_gpu(self.module, load_grad=False) - per_tensor_param = ...
verl/workers/engine/megatron/transformer_impl.py
0
Python
1
none
16
51
51
true
[fsdp, megatron] fix: Engine Rollout Worker LoRA Parameter Update
4,836
volcengine/verl
16,907
Python
JacobHelwig
max_response_length=512 ppo_mini_batch_size=3 actor_ppo_max_token_len=$(((max_prompt_length + max_response_length) * 2)) infer_ppo_max_token_len=$(((max_prompt_length + max_response_length) * 2)) exper_name=Node${NODES}_bs${bs}_${PP}${TP}${EP}${ETP}_${SGLANG_INFER_TP}_minbs${ppo_mini_batch_size}_micro_bs${micro_bs} ...
No issues found.
max_response_length=512 ppo_mini_batch_size=3 actor_ppo_max_token_len=$(((max_prompt_length + max_response_length) * 2)) infer_ppo_max_token_len=$(((max_prompt_length + max_response_length) * 2)) exper_name=Node${NODES}_bs${bs}_${PP}${TP}${EP}${ETP}_${SGLANG_INFER_TP}_minbs${ppo_mini_batch_size}_micro_bs${micro_bs} ...
@@ -0,0 +1,110 @@ + +set -x + +NODES=6 + +# R2: enable routing replay +# R3: enable rollout routing replay +# If enabling R3, please set actor_rollout_ref.rollout.enable_rollout_routing_replay=True +# R3 example is based on SGLang related commit https://github.com/sgl-project/sglang/commit/bed301a5acaa9577c9aa706468bdf...
examples/router_replay/run_qwen30_a3b_megatron_sglang.sh
0
Shell
1
none
16
51
51
true
[algo, rollout, sglang] feat: Support router replay with sglang
4,840
volcengine/verl
16,907
Python
moehanabi
with engine.eval_mode(): # runs in evaluation mode """ return EngineEvalModeCtx(self, **kwargs) def optimizer_zero_grad(self): """ Zero out gradients of all parameters before starting a new backward pass. """ self.optimizer.zero_grad() ...
No issues found.
with engine.eval_mode(): # runs in evaluation mode """ return EngineEvalModeCtx(self, **kwargs) def optimizer_zero_grad(self): """ Zero out gradients of all parameters before starting a new backward pass. """ self.optimizer.zero_grad() ...
@@ -38,6 +38,7 @@ vocab_parallel_log_probs_from_logits, ) from verl.utils.megatron_utils import ( + get_megatron_module_device, load_megatron_model_to_gpu, load_megatron_optimizer, offload_megatron_model_to_cpu, @@ -437,7 +438,8 @@ def save_checkpoint( global_step: Integer training...
verl/workers/engine/megatron/transformer_impl.py
0
Python
1
none
16
51
51
true
[ckpt] fix: Megatron save ckpt after validation
4,841
volcengine/verl
16,907
Python
wdl339
dp_rank = 0 dp_size = 1 self.train_sampler = DistributedSampler( self.train_dataset, shuffle=True, num_replicas=dp_size, rank=dp_rank, drop_last=True ) self.global_batch_size = config.data.train_batch_size self.train_batch_size_per_dp = self.global_batch_si...
No issues found.
dp_rank = 0 dp_size = 1 self.train_sampler = DistributedSampler( self.train_dataset, shuffle=True, num_replicas=dp_size, rank=dp_rank, drop_last=True ) self.global_batch_size = config.data.train_batch_size self.train_batch_size_per_dp = self.global_batch_si...
@@ -291,11 +291,11 @@ def fit(self): global_step += 1 # construct tensordict data = tu.get_tensordict(tensor_dict=data, non_tensor_dict=meta_info) - batch_seqlens = self._get_batch_seqlens(data=data) + batch_seqlens = self._get_batch_seqle...
verl/trainer/sft_trainer_ray.py
0
Python
1
none
16
51
51
true
fix(sft_trainer): Fix global_tokens and total_tokens metrics always showing 0.0
4,854
volcengine/verl
16,907
Python
khazic
""" # see comments from train_batch maybe_fix_3d_position_ids(data) with torch.no_grad(): outputs = self.forward_backward_batch(data, loss_function, forward_only=True) return outputs def get_per_tensor_param(self) -> tuple[Generator[tuple[str, torch.Tensor], Non...
No issues found.
""" # see comments from train_batch maybe_fix_3d_position_ids(data) with torch.no_grad(): outputs = self.forward_backward_batch(data, loss_function, forward_only=True) return outputs def get_per_tensor_param(self) -> tuple[Generator[tuple[str, torch.Tensor], Non...
@@ -22,14 +22,7 @@ from tensordict import TensorDict from verl.utils.device import get_device_name - - -def _maybe_fix_3d_position_ids(data: TensorDict): - # note for tensordict with pickle/unpickle. nested tensor in tensordict after consolidate and pickle/unpickle - # will incur indexing error for ragged ten...
verl/workers/engine/base.py
0
Python
1
none
16
51
51
true
[misc] fix: fix 3d position_ids for train_mini_batch
4,860
volcengine/verl
16,907
Python
wdl339
print("[FullyAsyncTrainer] async_rollout_manager sleep") await self.async_rollout_manager.sleep() else: print("[FullyAsyncTrainer] Skip async rollout manager (use_trainer_do_validate=False)") async def fit(self): """ The training loop of PPO. The ...
No issues found.
print("[FullyAsyncTrainer] async_rollout_manager sleep") await self.async_rollout_manager.sleep() else: print("[FullyAsyncTrainer] Skip async rollout manager (use_trainer_do_validate=False)") async def fit(self): """ The training loop of PPO. The ...
@@ -269,12 +269,12 @@ async def init_workers(self): async def _init_async_rollout_manager(self): # use async rollout do validate + print(f"[FullyAsyncTrainer] use_trainer_do_validate: {self.config.async_training.use_trainer_do_validate}") if self.config.async_training.use_trainer_do_vali...
verl/experimental/fully_async_policy/fully_async_trainer.py
0
Python
1
none
16
51
51
true
[rollout] feat: use rollout and validate parallel process
4,863
volcengine/verl
16,907
Python
chenjiaoAngel
self.resource_pool_to_cls[resource_pool][str(Role.Critic)] = critic_cls # create reference policy if needed if self.use_reference_policy and Role.RefPolicy in self.role_worker_mapping: resource_pool = self.resource_pool_manager.get_resource_pool(Role.RefPolicy) ref_p...
No issues found.
self.resource_pool_to_cls[resource_pool][str(Role.Critic)] = critic_cls # create reference policy if needed if self.use_reference_policy and Role.RefPolicy in self.role_worker_mapping: resource_pool = self.resource_pool_manager.get_resource_pool(Role.RefPolicy) ref_p...
@@ -339,7 +339,7 @@ def __init__( self.role_worker_mapping = role_worker_mapping self.resource_pool_manager = resource_pool_manager - self.use_reference_policy = need_reference_policy(self.role_worker_mapping) + self.use_reference_policy = need_reference_policy(self.config) # ...
verl/trainer/ppo/ray_trainer.py
0
Python
1
none
16
51
51
true
[worker] feat: New engine share actor and ref for LoRA
4,867
volcengine/verl
16,907
Python
HollowMan6
# See the License for the specific language governing permissions and # limitations under the License. import os import re # Get PR title from environment pr_title = os.environ.get("PR_TITLE", "").strip() # Define rules allowed_modules = ["fsdp", "megatron", "veomni", "sglang", "vllm", "rollout", "trainer"] allowed_...
No issues found.
# See the License for the specific language governing permissions and # limitations under the License. import os import re # Get PR title from environment pr_title = os.environ.get("PR_TITLE", "").strip() # Define rules allowed_modules = ["fsdp", "megatron", "veomni", "sglang", "vllm", "rollout", "trainer"] allowed_...
@@ -19,7 +19,7 @@ pr_title = os.environ.get("PR_TITLE", "").strip() # Define rules -allowed_modules = ["fsdp", "megatron", "sglang", "vllm", "rollout", "trainer"] +allowed_modules = ["fsdp", "megatron", "veomni", "sglang", "vllm", "rollout", "trainer"] allowed_modules += ["tests", "training_utils", "recipe", "hard...
tests/special_sanity/check_pr_title.py
0
Python
1
none
16
51
51
true
[veomni] refactor: minor refactoring to ensure veomni engine compatibility with forward_only mode
4,889
volcengine/verl
16,907
Python
ji-huazhong
import torch from safetensors.torch import safe_open from tqdm import tqdm from transformers import AutoConfig from veomni.models import build_tokenizer, save_model_weights @dataclass class StateDictIterator: filepath: str def __iter__(self) -> Generator[tuple[str, "torch.Tensor"], None, None]: if s...
No issues found.
import torch from safetensors.torch import safe_open from tqdm import tqdm from transformers import AutoConfig from veomni.models import build_tokenizer, save_model_weights @dataclass class StateDictIterator: filepath: str def __iter__(self) -> Generator[tuple[str, "torch.Tensor"], None, None]: if s...
@@ -0,0 +1,121 @@ +# 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 r...
scripts/veomni/moe_merge.py
0
Python
1
none
16
51
51
true
[veomni] feat: support offloading/loading the veomni model/optimizer
4,916
volcengine/verl
16,907
Python
ji-huazhong
add_bias_linear=False, add_qkv_bias=qkv_bias, qk_layernorm=qk_layernorm, ) # override_transformer_config_kwargs as kwargs shall never be none args.update(override_transformer_config_kwargs) return check_and_construct_configs(args, TransformerConfig) def hf_to_mcore_config_qwen2...
No issues found.
add_bias_linear=False, add_qkv_bias=qkv_bias, qk_layernorm=qk_layernorm, ) # override_transformer_config_kwargs as kwargs shall never be none args.update(override_transformer_config_kwargs) return check_and_construct_configs(args, TransformerConfig) def hf_to_mcore_config_qwen2...
@@ -290,7 +290,7 @@ def hf_to_mcore_config_dpskv3( set_experimental_flag(True) - from .patch_v012 import apply_patch + from .patch import apply_patch apply_patch()
verl/models/mcore/config_converter.py
0
Python
1
none
16
51
51
true
[megatron] fix: patch mcore for MLA support with flash_attn
4,931
volcengine/verl
16,907
Python
HollowMan6
def forward( self, input_, weight=None, runtime_gather_output=None, ): """ Forward pass for the linear layer. This method computes the linear transformation and handles sequence parallelism if enabled, gathering outputs from different sequence pa...
No issues found.
def forward( self, input_, weight=None, runtime_gather_output=None, ): """ Forward pass for the linear layer. This method computes the linear transformation and handles sequence parallelism if enabled, gathering outputs from different sequence pa...
@@ -153,9 +153,15 @@ def freeze_moe_router(model): if hasattr(layer.mlp.router, "bias"): layer.mlp.router.bias.requires_grad = False if hasattr(layer.mlp, "shared_experts"): - if hasattr(layer.mlp.shared_experts, "gate_weight"): + ...
verl/models/mcore/bridge.py
0
Python
1
none
16
51
51
true
[rollout,mbridge] feat: add metrics for rollout num preempted and fix mbrideg freeze moe
4,956
volcengine/verl
16,907
Python
RobotGF
# Note the default MultiturnSFT Dataset requires all the sys/user/assistant in 'data.message_key' DATASET_DIR=${DATASET_DIR:-~/dataset/rl/gsm8k} TRAIN_FILES=${DATASET_DIR}/train.parquet VAL_FILES=${DATASET_DIR}/eval.parquet project_name=verl_sft_test RESUME_MODE=disable MODEL_PATH="XiaomiMiMo/MiMo-7B-RL" ckpts_home...
No issues found.
# Note the default MultiturnSFT Dataset requires all the sys/user/assistant in 'data.message_key' DATASET_DIR=${DATASET_DIR:-~/dataset/rl/gsm8k} TRAIN_FILES=${DATASET_DIR}/train.parquet VAL_FILES=${DATASET_DIR}/eval.parquet project_name=verl_sft_test RESUME_MODE=disable MODEL_PATH="XiaomiMiMo/MiMo-7B-RL" ckpts_home...
@@ -0,0 +1,102 @@ +#!/usr/bin/env bash +set -xeuo pipefail + +NUM_GPUS=${NUM_GPUS:-8} +SP_SIZE=${SP_SIZE:-1} +TP_SIZE=${TP_SIZE:-1} +PP_SIZE=${PP_SIZE:-1} +VPP_SIZE=${VPP_SIZE:-null} +CP_SIZE=${CP_SIZE:-1} +PAD_MODE=${PAD_MODE:-no_padding} +USE_REMOVE_PADDING=${USE_REMOVE_PADDING:-False} +LR="1e-5" +MINLR="1e-6" + +exp...
examples/sft/gsm8k/run_mimo_megatron_mtp.sh
0
Shell
1
none
16
51
51
true
[megatron] feat: Support MTP training in SFT
4,981
volcengine/verl
16,907
Python
arvyanh
) self.resource_pool_to_cls[resource_pool][str(Role.RefPolicy)] = ref_policy_cls # create a reward model if reward_fn is None # for legacy discriminative reward model, we create a reward model worker here # for reward loop discriminative reward model, we create a reward ...
No issues found.
) self.resource_pool_to_cls[resource_pool][str(Role.RefPolicy)] = ref_policy_cls # create a reward model if reward_fn is None # for legacy discriminative reward model, we create a reward model worker here # for reward loop discriminative reward model, we create a reward ...
@@ -1438,7 +1438,7 @@ def fit(self): gen_batch_output = self.actor_rollout_wg.generate_sequences(gen_batch_output) else: if curr_step_profile: - self.async_rollout_manager.start_profile() + ...
verl/trainer/ppo/ray_trainer.py
0
Python
1
none
16
51
51
true
[rollout, perf, cfg] fix: Add global step info and support more profile control params for rollout profiling (sglang backend)
5,025
volcengine/verl
16,907
Python
bithighrr
probs, top_indices = _compute_topk(scores, topk, num_groups=num_groups, group_topk=group_topk) if router_replay is not None: router_replay.record_indices(top_indices) return probs, top_indices elif routing_action == RouterReplayAction.REPLAY_FORWARD: ...
No issues found.
probs, top_indices = _compute_topk(scores, topk, num_groups=num_groups, group_topk=group_topk) if router_replay is not None: router_replay.record_indices(top_indices) return probs, top_indices elif routing_action == RouterReplayAction.REPLAY_FORWARD: ...
@@ -84,6 +84,7 @@ def __init__(self): self.recorded_topk_idx = None # For recording self.router_replay_action = None # Router replay action for this layer self.replay_backward_list = [] # List of tensors for backward pass replay + self.layer_number = None # Global layer index if av...
verl/utils/megatron/router_replay_patch.py
0
Python
1
none
16
51
51
true
[megatron, training_utils] fix: router replay R3 align router replay data with global layer indices
5,037
volcengine/verl
16,907
Python
HollowMan6
async def _run_agent_loop( self, sampling_params: dict[str, Any], trajectory: dict[str, Any], *, agent_name: str, trace: bool = True, **kwargs, ) -> _InternalAgentLoopOutput: with rollout_trace_attr( step=trajectory["step"], ...
No issues found.
async def _run_agent_loop( self, sampling_params: dict[str, Any], trajectory: dict[str, Any], *, agent_name: str, trace: bool = True, **kwargs, ) -> _InternalAgentLoopOutput: with rollout_trace_attr( step=trajectory["step"], ...
@@ -33,7 +33,6 @@ from verl.experimental.agent_loop.prometheus_utils import update_prometheus_config from verl.experimental.agent_loop.utils import resolve_config_path -from verl.experimental.reward_loop import RewardLoopWorker from verl.protocol import DataProto from verl.single_controller.ray.base import RayRes...
verl/experimental/agent_loop/agent_loop.py
0
Python
1
none
16
51
51
true
[reward] feat: split reward loop manager and agent loop manager
5,134
volcengine/verl
16,907
Python
yyDing1
for key, val in default_keys.items(): if key not in data.keys(): tu.assign_non_tensor(data, **{key: val}) with ( self.engine.train_mode(disable_auto_offload=disable_auto_offload), Timer(name="train_batch", logger=None) as timer, ): ...
No issues found.
for key, val in default_keys.items(): if key not in data.keys(): tu.assign_non_tensor(data, **{key: val}) with ( self.engine.train_mode(disable_auto_offload=disable_auto_offload), Timer(name="train_batch", logger=None) as timer, ): ...
@@ -615,7 +615,9 @@ async def update_weights(self): # main memory can trade sync time to avoid OOM self.rollout.sleep_level = 1 - do_lora_base_sync = not self.base_sync_done or self.rollout.sleep_level != 1 + do_lora_base_sync = (not self.base_sync_done) or ( + ...
verl/workers/engine_workers.py
0
Python
1
none
16
51
51
true
[worker] feat: Avoid redundant base weight sync when engine doesn't sleep
5,147
volcengine/verl
16,907
Python
JohnConnor123
# use use_contiguous_buffers_in_local_ddp and no overlap_dp_param_comm for chunk in self.module: # if use distributed optimizer, zero grad buffer will be handled by optimizer chunk.zero_grad_buffer() def optimizer_step(self): """ Perform an optimization step ...
No issues found.
# use use_contiguous_buffers_in_local_ddp and no overlap_dp_param_comm for chunk in self.module: # if use distributed optimizer, zero grad buffer will be handled by optimizer chunk.zero_grad_buffer() def optimizer_step(self): """ Perform an optimization step ...
@@ -286,7 +286,18 @@ def initialize(self): self.optimizer = self._build_optimizer() self.lr_scheduler = self._build_lr_scheduler() - tmp_config = OmegaConf.create({"model": {"path": self.model_config.local_path}}) + full_reshardable = self.engine_config.dist_ckpt_optim_fully_reshardabl...
verl/workers/engine/megatron/transformer_impl.py
0
Python
1
none
16
51
51
true
[megatron] fix: checkpoints uses `fully_reshardable` by default when supported
5,154
volcengine/verl
16,907
Python
HollowMan6
images = multi_modal_data.get("images") videos = multi_modal_data.get("videos") param_version = kwargs.get("param_version", 0) metrics = {} request_id = uuid4().hex param_version_start = param_version param_version_end = param_version if not output: ...
No issues found.
images = multi_modal_data.get("images") videos = multi_modal_data.get("videos") param_version = kwargs.get("param_version", 0) metrics = {} request_id = uuid4().hex param_version_start = param_version param_version_end = param_version if not output: ...
@@ -37,11 +37,14 @@ def __init__(self, *args, **kwargs): async def run(self, sampling_params: dict[str, Any], **kwargs) -> AgentLoopOutput: output: Optional[AgentLoopOutput] = kwargs.get("output", None) messages = list(kwargs["raw_prompt"]) + multi_modal_data = await self.process_vision_in...
verl/experimental/fully_async_policy/agent_loop/partial_single_turn_agent_loop.py
0
Python
1
none
16
51
51
true
[vllm] fix: handle multimodal inputs correctly in full async mode
5,160
volcengine/verl
16,907
Python
Silas-11
if update_successful: # allgather already execute in optimizer.step in new megatron pass else: raise NotImplementedError("Megatron optimizer step failed. This should not happen") return grad_norm def lr_scheduler_step(self): """ Advance t...
No issues found.
if update_successful: # allgather already execute in optimizer.step in new megatron pass else: raise NotImplementedError("Megatron optimizer step failed. This should not happen") return grad_norm def lr_scheduler_step(self): """ Advance t...
@@ -11,7 +11,6 @@ # 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. - import logging import os from functools import partial @@ -33,6 +32,11 @@ from verl.utils.debug import log_gpu_memo...
verl/workers/engine/megatron/transformer_impl.py
0
Python
1
none
16
51
51
true
[algo] feat: support rollout router replay in MegatronEngine
5,185
volcengine/verl
16,907
Python
xhx1022
# TODO Here you can use the new registration method to support dynamic registration of roles if config.reward_model.enable_resource_pool: if config.reward_model.n_gpus_per_node <= 0: raise ValueError("config.reward_model.n_gpus_per_node must be greater than 0") if...
No issues found.
# TODO Here you can use the new registration method to support dynamic registration of roles if config.reward_model.enable_resource_pool: if config.reward_model.n_gpus_per_node <= 0: raise ValueError("config.reward_model.n_gpus_per_node must be greater than 0") if...
@@ -314,13 +314,24 @@ def run(self, config): # Used for multimodal LLM, could be None processor = hf_processor(local_path, trust_remote_code=trust_remote_code, use_fast=True) - # Load the reward manager for training and validation. - reward_fn = load_reward_manager( - config...
verl/trainer/main_ppo.py
0
Python
1
none
16
51
51
true
[reward] refactor: migrate all reward managers to the new asynchronous reward manager
5,189
volcengine/verl
16,907
Python
yyDing1
post_process=post_process, ) else: output = output_orig return output return fused_forward_model def fused_forward_no_padding_gen(vision_model: bool = False): def fused_forward_no_padding( model, input_ids: Tensor, labels: Tensor...
No issues found.
post_process=post_process, ) else: output = output_orig return output return fused_forward_model def fused_forward_no_padding_gen(vision_model: bool = False): def fused_forward_no_padding( model, input_ids: Tensor, labels: Tensor...
@@ -29,12 +29,12 @@ from packaging import version from torch import Tensor -from verl.models.mcore.util import preprocess_packed_seqs +from verl.models.mcore.util import preprocess_packed_seqs, preprocess_thd_no_padding from verl.utils.kernel.linear_cross_entropy import linear_cross_entropy from verl.utils.megatr...
verl/models/mcore/model_forward_fused.py
0
Python
1
none
16
51
51
true
[megatron] feat: fused kernel suppport for new model engine
5,191
volcengine/verl
16,907
Python
HollowMan6
get_torch_device().set_rng_state(self.gen_random_states) if fsdp_version(self.actor_module_fsdp) == 1: fsdp_unshard_exit_stack = contextlib.ExitStack() optional_state = _get_module_fsdp_state(self.actor_module_fsdp) if optional_state is None: self.fsd...
No issues found.
get_torch_device().set_rng_state(self.gen_random_states) if fsdp_version(self.actor_module_fsdp) == 1: fsdp_unshard_exit_stack = contextlib.ExitStack() optional_state = _get_module_fsdp_state(self.actor_module_fsdp) if optional_state is None: self.fsd...
@@ -305,6 +305,7 @@ def init_model(self): lr_scheduler=self.actor_lr_scheduler, processing_class=self.processor if self.processor is not None else self.tokenizer, checkpoint_config=self.config.actor.checkpoint, + trust_remote_code=self.config.model.trust...
verl/experimental/vla/fsdp_workers.py
0
Python
1
none
16
51
51
true
[fsdp] fix: Support trust_remote_code during FSDP HugginFace checkpoint save
5,200
volcengine/verl
16,907
Python
thvasilo
detached, worker_env=None, ): """Initialize the worker group by creating new workers from a resource pool. Args: resource_pool: Resource pool for worker allocation ray_cls_with_init: Class with initialization arguments for workers bin_pack: Whethe...
No issues found.
detached, worker_env=None, ): """Initialize the worker group by creating new workers from a resource pool. Args: resource_pool: Resource pool for worker allocation ray_cls_with_init: Class with initialization arguments for workers bin_pack: Whethe...
@@ -87,11 +87,25 @@ def sort_placement_group_by_node_ip(pgs: list[PlacementGroup]) -> list[Placement @ray.remote -def get_master_addr_port() -> tuple[str, str]: +def get_master_addr_port(master_port_range: Optional[list[int]] = None) -> tuple[str, str]: addr = ray.util.get_node_ip_address().strip("[]") - w...
verl/single_controller/ray/base.py
0
Python
1
none
16
51
51
true
[ray,trainer] feat: add master port range configuration for port range
5,201
volcengine/verl
16,907
Python
RobotGF
# fsdp actor_rollout_ref.actor.fsdp_config.use_orig_params=True actor_rollout_ref.actor.fsdp_config.model_dtype=bfloat16 actor_rollout_ref.actor.fsdp_config.param_offload=${offload} actor_rollout_ref.actor.fsdp_config.optimizer_offload=${offload} actor_rollout_ref.actor.fsdp_config.forward_prefe...
No issues found.
# fsdp actor_rollout_ref.actor.fsdp_config.use_orig_params=True actor_rollout_ref.actor.fsdp_config.model_dtype=bfloat16 actor_rollout_ref.actor.fsdp_config.param_offload=${offload} actor_rollout_ref.actor.fsdp_config.optimizer_offload=${offload} actor_rollout_ref.actor.fsdp_config.forward_prefe...
@@ -0,0 +1,175 @@ +#!/usr/bin/env bash +set -xeuo pipefail + +project_name="verl_grpo_qwen3-next-80b" +experiment_name="Qwen3_Next_80B_Instruct" + +# Paths +WORK_DIR=${WORK_DIR:-"${HOME}/verl"} +MODEL_PATH=${WORK_DIR}/Qwen3-Next-80B-A3B-Instruct +TRAIN_FILE=${WORK_DIR}/datasets/dapo-math-17k/dapo-math-17k.parquet +TEST...
examples/grpo_trainer/run_qwen3next_80b_fsdp_npu.sh
0
Shell
1
none
16
51
51
true
[fsdp] feat: add script for qwen3next training on npu platform
5,236
volcengine/verl
16,907
Python
zjchenn
last_exception = None for attempt in range(max_retries): try: # It's safer to have a timeout instead of None, which can hang indefinitely. timeout = aiohttp.ClientTimeout(total=None) async with aiohttp.ClientSession(timeout=timeout) as session:...
No issues found.
last_exception = None for attempt in range(max_retries): try: # It's safer to have a timeout instead of None, which can hang indefinitely. timeout = aiohttp.ClientTimeout(total=None) async with aiohttp.ClientSession(timeout=timeout) as session:...
@@ -20,7 +20,7 @@ import numpy as np import ray import torch -from omegaconf import DictConfig +from omegaconf import DictConfig, open_dict from tensordict import TensorDict from verl.protocol import DataProto @@ -35,6 +35,51 @@ logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) +def migrate_legacy_re...
verl/experimental/reward_loop/reward_loop.py
0
Python
1
none
16
51
51
true
[reward] fix: backward compatibility with old reward config
5,287
volcengine/verl
16,907
Python
yyDing1
method="monkey_patch_model", kwargs={"vocab_size": len(self.model_config.tokenizer)} ) build_app_sig = inspect.signature(build_app) supported_tasks: tuple[Any, ...] = () if "supported_tasks" in build_app_sig.parameters: supported_tasks = await engine_client.get_s...
No issues found.
method="monkey_patch_model", kwargs={"vocab_size": len(self.model_config.tokenizer)} ) build_app_sig = inspect.signature(build_app) supported_tasks: tuple[Any, ...] = () if "supported_tasks" in build_app_sig.parameters: supported_tasks = await engine_client.get_s...
@@ -153,10 +153,10 @@ def __init__( if self.node_rank == 0: self._master_address = self._server_address # used for torch.distributed.init_process_group - self._master_port, self._master_sock = get_free_port(self._server_address) + self._master_port, self._master_...
verl/workers/rollout/vllm_rollout/vllm_async_server.py
0
Python
1
none
16
51
51
true
[ci] fix: occasional CI failures caused by sglang server port conflicts
5,310
volcengine/verl
16,907
Python
pengwu22
else: index = np.arange(len(batch)) trajectory_info = await get_trajectory_info( batch.meta_info.get("global_steps", -1), index, batch.meta_info.get("validate", False) ) if not partial_output_list: partial_output_list = [None] * len(batch) tr...
No issues found.
else: index = np.arange(len(batch)) trajectory_info = await get_trajectory_info( batch.meta_info.get("global_steps", -1), index, batch.meta_info.get("validate", False) ) if not partial_output_list: partial_output_list = [None] * len(batch) tr...
@@ -28,11 +28,11 @@ AsyncLLMServerManager, DictConfigWrap, _agent_loop_registry, + _get_rollout_and_model_config, get_trajectory_info, ) -from verl.experimental.agent_loop.prometheus_utils import update_prometheus_config from verl.protocol import DataProto -from verl.single_controller.ray impor...
verl/experimental/fully_async_policy/agent_loop/agent_loop.py
0
Python
1
none
16
51
51
true
[BREAKING][rollout,cfg] refactor: get rid of actor_rollout_ref config from rollout
5,418
volcengine/verl
16,907
Python
wuxibin89
adapter = AsyncTRTLLMHttpAdapter(host="localhost", port=8000) post_response = AsyncMock() post_response.status = 200 post_response.headers = {"Content-Type": "application/json"} post_response.raise_for_status = Mock() post_response.json = AsyncMock(return_value={"status"...
No issues found.
adapter = AsyncTRTLLMHttpAdapter(host="localhost", port=8000) post_response = AsyncMock() post_response.status = 200 post_response.headers = {"Content-Type": "application/json"} post_response.raise_for_status = Mock() post_response.json = AsyncMock(return_value={"status"...
@@ -175,9 +175,9 @@ def test_init_without_device_mesh(self): worker0 = replica.workers[0] worker1 = replica.workers[1] - replica_rank = ray.get(worker0._get_attribute.remote("replica_rank")) - is_leader_rank_0 = ray.get(worker0._get_attribute.remote("is_leader_rank")) -...
tests/workers/rollout/rollout_trtllm/test_adapter.py
0
Python
1
none
16
51
51
true
[ci] fix: failed trtllm_unit_tests with attribute error
5,446
volcengine/verl
16,907
Python
HollowMan6
deindent() push(`})`) } // JavaScript function genCallExpression( node: CallExpression, context: CodegenContext, multilines = node.arguments.length > 2 ) { context.push(node.callee + `(`, node, true) multilines && context.indent() genNodeList(node.arguments, context, multilines) multilines && context...
This cleans up object property mappings/location. 🙈 Looks little dirty.
deindent() push(`})`) } // JavaScript function genCallExpression( node: CallExpression, context: CodegenContext, multilines = node.arguments.length > 2 ) { context.push(node.callee + `(`, node, true) multilines && context.indent() genNodeList(node.arguments, context, multilines) multilines && context...
@@ -518,7 +518,8 @@ function genObjectExpression(node: ObjectExpression, context: CodegenContext) { push(multilines ? `{` : `{ `) multilines && indent() for (let i = 0; i < properties.length; i++) { - const { key, value } = properties[i] + const { key, value, loc } = properties[i] + push('', { loc } a...
packages/compiler-core/src/codegen.ts
26
TypeScript
0.214
suggestion
71
44
45
false
fix(compiler): generate correct mappings for v-for and object properties
69
vuejs/vue-next
25,296
TypeScript
znck
znck
if (node) { let name if ( node.type === NodeTypes.EXPRESSION && !node.children && !node.isStatic ) { const content = node.content.replace(/^_ctx\./, '') if (content !== node.content && isSimpleIdentifier(content)) { ...
I have added this for L522. Otherwise, I guess it would always be non-empty.
if (node) { let name if ( node.type === NodeTypes.EXPRESSION && !node.children && !node.isStatic ) { const content = node.content.replace(/^_ctx\./, '') if (content !== node.content && isSimpleIdentifier(content)) { ...
@@ -130,7 +130,7 @@ function createCodegenContext( } }) } - advancePositionWithMutation(context, code) + if (code) advancePositionWithMutation(context, code)
packages/compiler-core/src/codegen.ts
26
TypeScript
0.214
suggestion
76
51
51
false
fix(compiler): generate correct mappings for v-for and object properties
69
vuejs/vue-next
25,296
TypeScript
znck
znck
} } type PropsExpression = ObjectExpression | CallExpression | ExpressionNode function buildProps( { loc: elementLoc, props }: ElementNode, context: TransformContext ): { props: PropsExpression directives: DirectiveNode[] } { let isStatic = true let properties: ObjectExpression['properties'] = [] cons...
This gives the correct location for an object property name.
// node.tagType can also be TEMPLATE, in which case nothing needs to be done } } type PropsExpression = ObjectExpression | CallExpression | ExpressionNode function buildProps( { loc: elementLoc, props }: ElementNode, context: TransformContext ): { props: PropsExpression directives: DirectiveNode[] } { ...
@@ -121,7 +122,7 @@ function buildProps( const { loc, name, value } = prop properties.push( createObjectProperty( - createExpression(name, true, loc), + createExpression(name, true, getInnerRange(loc, 0, name.length)),
packages/compiler-core/src/transforms/transformElement.ts
26
TypeScript
0.214
suggestion
60
51
51
false
fix(compiler): generate correct mappings for v-for and object properties
69
vuejs/vue-next
25,296
TypeScript
znck
znck
TransformContext } from '../transform' import { NodeTypes, ExpressionNode, createExpression, SourceLocation } from '../ast' import { createCompilerError, ErrorCodes } from '../errors' import { getInnerRange } from '../utils' import { RENDER_LIST } from '../runtimeConstants' import { processExpression } from '...
This gives a more accurate location for `v-for` and even allows setting breakpoint separately for v-for and the element it's applied to.
TransformContext } from '../transform' import { NodeTypes, ExpressionNode, createExpression, SourceLocation } from '../ast' import { createCompilerError, ErrorCodes } from '../errors' import { getInnerRange } from '../utils' import { RENDER_LIST } from '../runtimeConstants' import { processExpression } from '...
@@ -25,7 +25,7 @@ export const transformFor = createStructuralDirectiveTransform( context.replaceNode({ type: NodeTypes.FOR, - loc: node.loc, + loc: dir.loc,
packages/compiler-core/src/transforms/vFor.ts
26
TypeScript
0.5
suggestion
136
51
51
false
fix(compiler): generate correct mappings for v-for and object properties
69
vuejs/vue-next
25,296
TypeScript
znck
znck
[['x', {}], 'foo x'], [undefined, 'foo'] ]) }) test('class merge between parent and child', () => { const root = document.createElement('div') type ClassItem = { value: string | object | string[] } const childClass: ClassItem = { value: 'd' } const child = () => h('div', ...
The only difference between the 2 cases is that `child2` has an empty `props` declaration, therefore it successfully triggered class merging while the other one didn't. I didn't see anything about this behavior in the `inheritAttrs` RFS. Seems a bug in the current implementation? @yyx990803
[['x', { y: true, z: true }], 'foo x y z'], [['x', { y: true, z: false }], 'foo x y'], [['f', { z: true }], 'foo f z'], [['l', 'f', { n: true, z: true }], 'foo l f n z'], [['x', {}], 'foo x'], [undefined, 'foo'] ]) }) test('class merge between parent and child', () => { ...
@@ -0,0 +1,235 @@ +// https://github.com/vuejs/vue/blob/dev/test/unit/features/directives/class.spec.js + +import { h, render, ComponentOptions } from '../../src' + +function assertClass(assertions: Array<Array<any>>) { + const root = document.createElement('div') + const dynamic = { value: '' } + const wrapper = ()...
packages/runtime-dom/__tests__/modules/class.spec.ts
26
TypeScript
0.714
bug
295
51
51
false
test: add test for runtime-dom/modules/class
75
vuejs/vue-next
25,296
TypeScript
haoqunjiang
haoqunjiang
return target.update case '$nextTick': return nextTick case '$watch': return instanceWatch.bind(target) } } return target.user[key] } } }, // this trap is only called in browser-compiled render func...
```suggestion `Attempting to mutate public property "${key}". ` + `Properties starting with $ are reserved and readonly.`, ```
case '$forceUpdate': return target.update case '$nextTick': return nextTick case '$watch': return instanceWatch.bind(target) } } return target.user[key] } } }, // this trap is only cal...
@@ -90,10 +91,15 @@ export const PublicInstanceProxyHandlers = { } else if (hasOwn(renderContext, key)) { renderContext[key] = value } else if (key[0] === '$' && key.slice(1) in target) { - // TODO warn attempt of mutating public property + __DEV__ && + warn( + `Attempting to ...
packages/runtime-core/src/componentProxy.ts
26
TypeScript
0.714
suggestion
149
40
42
false
fix: add warnings
82
vuejs/vue-next
25,296
TypeScript
yyx990803
TimvdEijnden
return target.user[key] } } }, // this trap is only called in browser-compiled render functions that use // `with (this) {}` has(_: any, key: string): boolean { return key[0] !== '_' && !globalsWhitelist.has(key) }, set(target: ComponentInternalInstance, key: string, value: any): boo...
```suggestion warn( `Attempting to mutate prop "${key}". Props are readonly.`, target ) ```
} return target.user[key] } } }, // this trap is only called in browser-compiled render functions that use // `with (this) {}` has(_: any, key: string): boolean { return key[0] !== '_' && !globalsWhitelist.has(key) }, set(target: ComponentInternalInstance, key: string, valu...
@@ -90,10 +91,16 @@ export const PublicInstanceProxyHandlers = { } else if (hasOwn(renderContext, key)) { renderContext[key] = value } else if (key[0] === '$' && key.slice(1) in target) { - // TODO warn attempt of mutating public property + __DEV__ && + warn( + `Attempting to ...
packages/runtime-core/src/componentProxy.ts
26
TypeScript
0.714
suggestion
132
34
35
false
fix: add warnings
82
vuejs/vue-next
25,296
TypeScript
yyx990803
TimvdEijnden
}) } } if (methods) { for (const key in methods) { renderContext[key] = (methods as MethodOptions)[key].bind(ctx) } } if (watchOptions) { for (const key in watchOptions) { const raw = watchOptions[key] const getter = () => ctx[key] if (isString(raw)) { c...
```suggestion warn(`Invalid watch option: "${key}"`) ```
}) } } if (methods) { for (const key in methods) { renderContext[key] = (methods as MethodOptions)[key].bind(ctx) } } if (watchOptions) { for (const key in watchOptions) { const raw = watchOptions[key] const getter = () => ctx[key] if (isString(raw)) { c...
@@ -267,15 +267,15 @@ export function applyOptions( if (isFunction(handler)) { watch(getter, handler as any) } else if (__DEV__) { - // TODO warn invalid watch handler path + warn(`Expected a function as watch handler "${raw}"`) } } else if (isFunction(raw)...
packages/runtime-core/src/apiOptions.ts
26
TypeScript
0.571
suggestion
66
51
51
false
fix: add warnings
82
vuejs/vue-next
25,296
TypeScript
yyx990803
TimvdEijnden
if (computedOptions) { for (const key in computedOptions) { const opt = (computedOptions as ComputedOptions)[key] renderContext[key] = isFunction(opt) ? computed(opt.bind(ctx)) : computed({ get: opt.get.bind(ctx), set: opt.set.bind(ctx) }) } } ...
```suggestion warn(`Invalid watch handler specified by key "${raw}": `, handler) ```
if (computedOptions) { for (const key in computedOptions) { const opt = (computedOptions as ComputedOptions)[key] renderContext[key] = isFunction(opt) ? computed(opt.bind(ctx)) : computed({ get: opt.get.bind(ctx), set: opt.set.bind(ctx) }) } } ...
@@ -267,15 +267,15 @@ export function applyOptions( if (isFunction(handler)) { watch(getter, handler as any) } else if (__DEV__) { - // TODO warn invalid watch handler path + warn(`Expected a function as watch handler "${raw}"`)
packages/runtime-core/src/apiOptions.ts
26
TypeScript
0.714
suggestion
96
51
51
false
fix: add warnings
82
vuejs/vue-next
25,296
TypeScript
yyx990803
TimvdEijnden
import { mockWarn } from '@vue/runtime-test' describe('component proxy', () => { /** * These tests should tests the warnings for PublicInstanceProxyHandlers in componentProxy * {@link @vue/runtime-core/src/componentProxy} * * The function setupStatefulComponent is the location where PublicInstanceProxyHa...
The `PublicInstanceProxy` is simply `this` inside any Vue 2.x options :)
import { createApp, nodeOps, mockWarn } from '@vue/runtime-test' const createTestInstance = (props?: any) => { const component = { render() {} } const root = nodeOps.createElement('div') return createApp().mount(component, root, props) } describe('component proxy', () => { describe('warnings', () => { ...
@@ -0,0 +1,36 @@ +import { mockWarn } from '@vue/runtime-test' + +describe('component proxy', () => { + /** + * These tests should tests the warnings for PublicInstanceProxyHandlers in componentProxy + * {@link @vue/runtime-core/src/componentProxy} + * + * The function setupStatefulComponent is the location wh...
packages/runtime-core/__tests__/componentProxy.spec.ts
11
TypeScript
0.357
suggestion
72
36
36
false
fix: add warnings
82
vuejs/vue-next
25,296
TypeScript
yyx990803
TimvdEijnden
import { createApp, nodeOps, mockWarn } from '@vue/runtime-test' describe('component proxy', () => { /** * These tests should tests the warnings for PublicInstanceProxyHandlers in componentProxy * {@link @vue/runtime-core/src/componentProxy} * * The function setupStatefulComponent is the location where P...
Can we remove outdated comments here?
import { createApp, nodeOps, mockWarn } from '@vue/runtime-test' const createTestInstance = (props?: any) => { const component = { render() {} } const root = nodeOps.createElement('div') return createApp().mount(component, root, props) } describe('component proxy', () => { describe('warnings', () => { ...
@@ -0,0 +1,49 @@ +import { createApp, nodeOps, mockWarn } from '@vue/runtime-test' + +describe('component proxy', () => { + /** + * These tests should tests the warnings for PublicInstanceProxyHandlers in componentProxy + * {@link @vue/runtime-core/src/componentProxy} + * + * The function setupStatefulComponen...
packages/runtime-core/__tests__/componentProxy.spec.ts
11
TypeScript
0.143
question
37
36
36
false
fix: add warnings
82
vuejs/vue-next
25,296
TypeScript
yyx990803
TimvdEijnden
describe('warnings', () => { mockWarn() let app: any, appProps: any beforeEach(() => { const component = { render() {} } const root = nodeOps.createElement('div') app = createApp().mount(component, root, appProps) }) test('Attempting to mutate public property', ()...
Out of scope assignment here makes the tests a bit harder to read in isolation. I'd refactor it into something like a `createTestInstance()` function to be called in each spec.
mockWarn() test('Attempting to mutate public property', () => { const app = createTestInstance() try { app.$props = { foo: 'bar' } } catch { expect( 'Attempting to mutate public property "$props". ' + 'Properties starting with $ are reserved and readonly...
@@ -0,0 +1,49 @@ +import { createApp, nodeOps, mockWarn } from '@vue/runtime-test' + +describe('component proxy', () => { + /** + * These tests should tests the warnings for PublicInstanceProxyHandlers in componentProxy + * {@link @vue/runtime-core/src/componentProxy} + * + * The function setupStatefulComponen...
packages/runtime-core/__tests__/componentProxy.spec.ts
26
TypeScript
0.571
refactor
176
38
29
false
fix: add warnings
82
vuejs/vue-next
25,296
TypeScript
yyx990803
TimvdEijnden
export type MaybeRef<T = any> = T | Ref<T> export type MaybeRefOrGetter<T = any> = MaybeRef<T> | (() => T) /** * Returns the inner value if the argument is a ref, otherwise return the * argument itself. This is a sugar function for * `val = isRef(val) ? val.value : val`. * * @example * ```js * function useFoo(...
```suggestion * Normalizes values / refs / getters to values. ```
* `val = isRef(val) ? val.value : val`. * * @example * ```js * function useFoo(x: number | Ref<number>) { * const unwrapped = unref(x) * // unwrapped is guaranteed to be number now * } * ``` * * @param ref - Ref or plain value to be converted into the plain value. * @see {@link https://vuejs.org/api/rea...
@@ -207,10 +215,30 @@ export function triggerRef(ref: Ref) { * @param ref - Ref or plain value to be converted into the plain value. * @see {@link https://vuejs.org/api/reactivity-utilities.html#unref} */ -export function unref<T>(ref: T | Ref<T>): T { +export function unref<T>(ref: MaybeRef<T>): T { return is...
packages/reactivity/src/ref.ts
26
TypeScript
0.571
suggestion
68
51
51
false
feat(reactivity): improve support of getter usage in reactivity APIs
7,997
vuejs/vue-next
25,296
TypeScript
skirtles-code
yyx990803
describe('reactive in shallow ref', () => { const x = shallowRef({ a: reactive({ b: ref(0) }) }) expectType<number>(x.value.a.b) }) describe('toRef <-> toValue', () => { function foo( a: MaybeRef<string>, b: () => string, c: MaybeRefOrGetter<string>, d: ComputedRef<string> ) {...
```suggestion // @ts-expect-error ref created from getter should be readonly ```
describe('reactive in shallow ref', () => { const x = shallowRef({ a: reactive({ b: ref(0) }) }) expectType<number>(x.value.a.b) }) describe('toRef <-> toValue', () => { function foo( a: MaybeRef<string>, b: () => string, c: MaybeRefOrGetter<string>, d: ComputedRef<string> ) {...
@@ -319,3 +333,58 @@ describe('reactive in shallow ref', () => { expectType<number>(x.value.a.b) }) + +describe('toRef <-> toValue', () => { + function foo( + a: MaybeRef<string>, + b: () => string, + c: MaybeRefOrGetter<string>, + d: ComputedRef<string> + ) { + const r = toRef(a) + expectType...
packages/dts-test/ref.test-d.ts
26
TypeScript
0.786
suggestion
86
51
51
false
feat(reactivity): improve support of getter usage in reactivity APIs
7,997
vuejs/vue-next
25,296
TypeScript
skirtles-code
yyx990803
private readonly _object: T, private readonly _key: K, private readonly _defaultValue?: T[K] ) {} get value() { const val = this._object[this._key] return val === undefined ? (this._defaultValue as T[K]) : val } set value(newVal) { this._object[this._key] = newVal } get dep(): Dep...
Should this also have `__v_isReadonly` set to `true`? ```js isReadonly(toRef(() => {})) // should be true? ```
return val === undefined ? (this._defaultValue as T[K]) : val } set value(newVal) { this._object[this._key] = newVal } get dep(): Dep | undefined { return getDepFromReactive(toRaw(this._object), this._key) } } class GetterRefImpl<T> { public readonly __v_isRef = true public readonly __v_isR...
@@ -333,12 +361,35 @@ class ObjectRefImpl<T extends object, K extends keyof T> { } } +class GetterRefImpl<T> { + public readonly __v_isRef = true + constructor(private readonly _getter: () => T) {} + get value() { + return this._getter() + } +}
packages/reactivity/src/ref.ts
26
TypeScript
0.786
suggestion
115
51
51
false
feat(reactivity): improve support of getter usage in reactivity APIs
7,997
vuejs/vue-next
25,296
TypeScript
skirtles-code
yyx990803
} } class GetterRefImpl<T> { public readonly __v_isRef = true constructor(private readonly _getter: () => T) {} get value() { return this._getter() } } export type ToRef<T> = IfAny<T, Ref<T>, [T] extends [Ref] ? T : Ref<T>> /** * Used to normalize values / refs / getters into refs. * * @example * `...
```suggestion * // equivalent to ref(1) ```
get value() { return this._getter() } } export type ToRef<T> = IfAny<T, Ref<T>, [T] extends [Ref] ? T : Ref<T>> /** * Used to normalize values / refs / getters into refs. * * @example * ```js * // returns existing refs as-is * toRef(existingRef) * * // creates a ref that calls the getter on .value acc...
@@ -333,12 +361,35 @@ class ObjectRefImpl<T extends object, K extends keyof T> { } } +class GetterRefImpl<T> { + public readonly __v_isRef = true + constructor(private readonly _getter: () => T) {} + get value() { + return this._getter() + } +} + export type ToRef<T> = IfAny<T, Ref<T>, [T] extends [Ref] ?...
packages/reactivity/src/ref.ts
26
TypeScript
0.429
suggestion
46
51
51
false
feat(reactivity): improve support of getter usage in reactivity APIs
7,997
vuejs/vue-next
25,296
TypeScript
skirtles-code
yyx990803
export function toRef<T>( value: T ): T extends () => infer R ? Readonly<Ref<R>> : T extends Ref ? T : Ref<UnwrapRef<T>> export function toRef<T extends object, K extends keyof T>( object: T, key: K ): ToRef<T[K]> export function toRef<T extends object, K extends keyof T>( object: T, key: K, default...
I think this will potentially cause a breaking change for arrays: ```js const arr = reactive(['a', 'b']) const c = toRef(arr, 1) ``` Previously this would have worked, but now `c` will be the whole array. `Symbol` keys for objects too.
: Ref<UnwrapRef<T>> export function toRef<T extends object, K extends keyof T>( object: T, key: K ): ToRef<T[K]> export function toRef<T extends object, K extends keyof T>( object: T, key: K, defaultValue: T[K] ): ToRef<Exclude<T[K], undefined>> export function toRef( source: Record<string, any> | MaybeRe...
@@ -371,15 +430,31 @@ export function toRef<T extends object, K extends keyof T>( key: K, defaultValue: T[K] ): ToRef<Exclude<T[K], undefined>> -export function toRef<T extends object, K extends keyof T>( - object: T, - key: K, - defaultValue?: T[K] -): ToRef<T[K]> { - const val = object[key] +export functio...
packages/reactivity/src/ref.ts
26
TypeScript
0.857
suggestion
247
51
51
false
feat(reactivity): improve support of getter usage in reactivity APIs
7,997
vuejs/vue-next
25,296
TypeScript
skirtles-code
yyx990803
type: Constructor<P>, props?: (RawProps & P) | ({} extends P ? null : never), children?: RawChildren | RawSlots, ): VNode // fake constructor type returned by `defineComponent` export function h(type: DefineComponent, children?: RawChildren): VNode export function h<P>( type: DefineComponent<P>, props?: (Raw...
Just stumbled upon this as I was reading the changelog. Is there a reason why every call to `h` will now (afaik) create an inline version of `doCreateVNode`? Can't this be created outside of the scope of calling `h()`?
export function h<P>( type: Constructor<P>, props?: (RawProps & P) | ({} extends P ? null : never), children?: RawChildren | RawSlots, ): VNode // fake constructor type returned by `defineComponent` export function h(type: DefineComponent, children?: RawChildren): VNode export function h<P>( type: DefineCompon...
@@ -201,25 +202,35 @@ export function h<P>( // Actual implementation export function h(type: any, propsOrChildren?: any, children?: any): VNode { + // #6913 disable tracking block in h function + const doCreateVNode = (type: any, props?: any, children?: any) => {
packages/runtime-core/src/h.ts
26
TypeScript
0.643
question
218
46
51
false
fix(runtime-core): disable tracking block in h function
8,213
vuejs/vue-next
25,296
TypeScript
spaceemotion
edison1105
) { removedWhitespace = true nodes[i] = null as any } else { // Otherwise, the whitespace is condensed into a single space node.content = ' ' } } else if (shouldCondense) { // in condense mode, consecutive whitespaces in tex...
Do we still need this section of the change? Doesn't the code in `hydration.ts` cover it? I think this part may cause other problems, e.g.: ```html <script setup> import { ref } from 'vue' const msg = ref('\r') </script> <template> <h1>{{ msg.startsWith('\r') }}</h1> </template> ``` This will ren...
// - the whitespace is the first or last node, or: // - (condense mode) the whitespace is between two comments, or: // - (condense mode) the whitespace is between comment and element, or: // - (condense mode) the whitespace is between two elements AND contains newline i...
@@ -865,6 +865,13 @@ function condenseWhitespace( node.content = node.content.replace(windowsNewlineRE, '\n') } } + // #9229 innerHTML normalize \r\n or \r into a single \n in the DOM + else if ( + node.type === NodeTypes.INTERPOLATION && + node.content.type === NodeTypes.SIMPLE_EXP...
packages/compiler-core/src/parser.ts
26
TypeScript
0.857
bug
396
51
51
false
fix(hydration): avoid mismatch during hydrate text with newlines in interpolation
9,232
vuejs/vue-next
25,296
TypeScript
skirtles-code
edison1105
// Instead of being a DirectiveTransform, v-slot processing is called during // transformElement to build the slots object for a component. export function buildSlots( node: ElementNode, context: TransformContext, buildSlotFn: SlotFnBuilder = buildClientSlotFn ): { slots: SlotsExpression hasDynamicSlots: boo...
I think this also needs to account for identifiers being used within the `v-slot` value itself, e.g.: ```html <MyChild v-for="i in items" v-slot="{ value = i.value }"> ``` - [Playground - This PR](https://deploy-preview-9427--vue-sfc-playground.netlify.app/#__DEV__eNqFUk1P4zAQ/SsjX8pKNBHb3UsVVgsVB5D4EHCrOYRk2ho...
export function buildSlots( node: ElementNode, context: TransformContext, buildSlotFn: SlotFnBuilder = buildClientSlotFn, ): { slots: SlotsExpression hasDynamicSlots: boolean } { context.helper(WITH_CTX) const { children, loc } = node const slotsProperties: Property[] = [] const dynamicSlots: (Condit...
@@ -134,9 +134,11 @@ export function buildSlots( // since it likely uses a scope variable. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0 // with `prefixIdentifiers: true`, this can be further optimized to make - // it dynamic only when the slot actually uses the scope variables. + ...
packages/compiler-core/src/transforms/vSlot.ts
26
TypeScript
0.857
suggestion
1,619
51
51
false
fix(compiler-core/v-slot): force dynamic slots when slot referencing scope vars
9,427
vuejs/vue-next
25,296
TypeScript
skirtles-code
edison1105
if ( targetAnchor && targetAnchor.nodeType === 8 && (targetAnchor as Comment).data === 'teleport anchor' ) { vnode.targetAnchor = targetAnchor ;(target as TeleportTargetElement)._lpa = vnode.targetAnchor && nextSibling(vnode.t...
```suggestion else if (isTeleportDisabled(vnode.props)) { if (vnode.shapeFlag & ShapeFlags.ARRAY_CHILDREN) { vnode.anchor = hydrateChildren( nextSibling(node), vnode, parentNode(node)!, parentComponent, parentSuspense, slotScopeIds, optimized...
interface TeleportTargetElement extends Element { // last teleport target _lpa?: Node | null } function hydrateTeleport( node: Node, vnode: TeleportVNode, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, slotScopeIds: string[] | null, optimized: boolean, { ...
@@ -406,6 +406,21 @@ function hydrateTeleport( } updateCssVars(vnode) } + if (!target && isTeleportDisabled(vnode.props)) {
packages/runtime-core/src/components/Teleport.ts
26
TypeScript
0.786
performance
425
51
51
false
fix(Teleport): hydrate disabled Teleport with undefined target
11,235
vuejs/vue-next
25,296
TypeScript
edison1105
linzhe141
if (!root) return if (styles) { styles.forEach(css => { const s = document.createElement('style') s.textContent = css root.appendChild(s) // record for HMR if (__DEV__) { ;(this._styles || (this._styles = [])).push(s) } }) } } /** ...
@yyx990803 Can we do the append? As my global styles are in the last tag and override child styles. In case of append we would have child styles come after the global. Maybe an option to specify this?
if (parent instanceof VueElement) { instance.parent = parent._instance instance.provides = parent._instance!.provides break } } } } return vnode } private _applyStyles( styles: string[] | undefined, owner?: ConcreteComponent, )...
@@ -486,19 +499,36 @@ export class VueElement extends BaseClass { return vnode } - private _applyStyles(styles: string[] | undefined) { - const root = this.shadowRoot - if (!root) return - if (styles) { - styles.forEach(css => { - const s = document.createElement('style') - s.text...
packages/runtime-dom/src/apiCustomElement.ts
26
TypeScript
0.429
question
202
51
51
false
feat(custom-element): inject child components styles to custom element shadow root
11,517
vuejs/vue-next
25,296
TypeScript
boga001
yyx990803
warn(`useCssVars is called without current active component instance.`) return } const updateTeleports = (instance.ut = (vars = getter(instance.proxy)) => { Array.from( document.querySelectorAll(`[data-v-owner="${instance.uid}"]`), ).forEach(node => setVarsOnNode(node, vars)) }) if (__...
Should just call `setVars` and not create another watcher on each update.
warn(`useCssVars is called without current active component instance.`) return } /* v8 ignore stop */ const updateTeleports = (instance.ut = (vars = getter(instance.proxy)) => { Array.from( document.querySelectorAll(`[data-v-owner="${instance.uid}"]`), ).forEach(node => setVarsOnNode(node...
@@ -47,6 +48,10 @@ export function useCssVars(getter: (ctx: any) => Record<string, string>) { watchPostEffect(setVars) }) + onBeforeUpdate(() => { + watchPostEffect(setVars)
packages/runtime-dom/src/helpers/useCssVars.ts
26
TypeScript
0.429
suggestion
73
51
51
false
fix(runtime-dom): before update should also set css vars
11,561
vuejs/vue-next
25,296
TypeScript
yyx990803
linzhe141
instance.isMounted = true if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { devtoolsComponentAdded(instance) } // #2458: deference mount-only object parameters to prevent memleaks initialVNode = container = anchor = null as any } else { let { next, bu, u, pare...
```suggestion update() ```
queuePostRenderEffect( () => instance.emit('hook:mounted'), parentSuspense, ) } // activated hook for keep-alive roots. // #1742 activated hook must be accessed after first render // since the hook may be injected by a child keep-alive ...
@@ -1438,7 +1438,7 @@ function baseCreateRenderer( nonHydratedAsyncRoot.asyncDep!.then(() => { // the instance may be destroyed during the time period if (!instance.isUnmounted) { - componentUpdateFn() + instance.update()
packages/runtime-core/src/renderer.ts
26
TypeScript
0.429
suggestion
44
51
51
false
fix(runtime-core): properly handle async component update before resolve
11,619
vuejs/vue-next
25,296
TypeScript
edison1105
linzhe141
instance.isMounted = true if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { devtoolsComponentAdded(instance) } // #2458: deference mount-only object parameters to prevent memleaks initialVNode = container = anchor = null as any } else { let { next, bu, u, pare...
There is another problem here. The `update()` is executed 2 times. This behavior is not related to this PR. But it needs to be fixed. The flow is as follows: 1. When `locateNonHydratedAsyncRoot` is called, `subComponent.asyncResolved` is `false`, `nonHydratedAsyncRoot` has a value, and a `then` callback is registe...
queuePostRenderEffect( () => instance.emit('hook:mounted'), parentSuspense, ) } // activated hook for keep-alive roots. // #1742 activated hook must be accessed after first render // since the hook may be injected by a child keep-alive ...
@@ -1438,7 +1438,7 @@ function baseCreateRenderer( nonHydratedAsyncRoot.asyncDep!.then(() => { // the instance may be destroyed during the time period if (!instance.isUnmounted) { - componentUpdateFn() + update()
packages/runtime-core/src/renderer.ts
26
TypeScript
1
suggestion
1,250
51
51
false
fix(runtime-core): properly handle async component update before resolve
11,619
vuejs/vue-next
25,296
TypeScript
edison1105
linzhe141
this.$emit('one', 1) }, render, } const app = createApp({ render() { return [h(CompA), ', ', h(CompB)] }, }) app.mixin({ emits: { one: (arg: number) => arg === 0, two: null, }, }) const root = nodeOps.createElement('div') app.mount(root) expect(`event v...
These tests are outside the `describe` block. All the other tests in this file are inside the `describe`. Is there a reason to have these outside?
created(this) { this.$emit('one', 1) }, render, }) const app = createApp({ render() { return [h(CompA), h(CompB)] }, }) app.mixin({ emits: { one: validateByGlobalMixin, two: null, }, }) const root = nodeOps.createElemen...
@@ -599,3 +600,76 @@ describe('component: emit', () => { expect(renderFn).toHaveBeenCalledTimes(1) }) }) + +test('merging emits for a component that is also used as a mixin', () => {
packages/runtime-core/__tests__/componentEmits.spec.ts
26
TypeScript
0.5
question
146
51
26
false
fix(runtime-core): use separate emits caches for components and mixins
11,661
vuejs/vue-next
25,296
TypeScript
skirtles-code
gcaaa31928
// Note: emits and listener fallthrough is tested in // ./rendererAttrsFallthrough.spec.ts. import { type ComponentPublicInstance, createApp, defineComponent, h, nextTick, nodeOps, render, toHandlers, } from '@vue/runtime-test' import { isEmitListener } from '../src/componentEmits' describe('component...
```suggestion test('merging emits from global mixins and extends', () => { ```
// Note: emits and listener fallthrough is tested in // ./rendererAttrsFallthrough.spec.ts. import { type ComponentPublicInstance, createApp, defineComponent, h, nextTick, nodeOps, render, toHandlers, } from '@vue/runtime-test' import { isEmitListener } from '../src/componentEmits' describe('component...
@@ -599,3 +600,76 @@ describe('component: emit', () => { expect(renderFn).toHaveBeenCalledTimes(1) }) }) + +test('merging emits for a component that is also used as a mixin', () => { + const render = () => h('div') + const CompA = { + render, + } + + const mixin = { + emits: { + one: (arg: numbe...
packages/runtime-core/__tests__/componentEmits.spec.ts
26
TypeScript
0.571
suggestion
80
676
644
false
fix(runtime-core): use separate emits caches for components and mixins
11,661
vuejs/vue-next
25,296
TypeScript
skirtles-code
gcaaa31928
two: null, }, }) const root = nodeOps.createElement('div') app.mount(root) expect(`event validation failed for event "one"`).not.toHaveBeenWarned() }) test('merging props from global mixins and extends', () => { let renderProxy: any let extendedRenderProxy: any const render = () => h('div') ...
Couldn't this use `defineComponent`, rather than explicitly typing the `this` value? That seems to be how the other tests in this file are handling it. There's some similar code in the other new test where the typings could just be removed.
// Note: emits and listener fallthrough is tested in // ./rendererAttrsFallthrough.spec.ts. import { type ComponentPublicInstance, createApp, defineComponent, h, nextTick, nodeOps, render, toHandlers, } from '@vue/runtime-test' import { isEmitListener } from '../src/componentEmits' describe('component...
@@ -599,3 +600,76 @@ describe('component: emit', () => { expect(renderFn).toHaveBeenCalledTimes(1) }) }) + +test('merging emits for a component that is also used as a mixin', () => { + const render = () => h('div') + const CompA = { + render, + } + + const mixin = { + emits: { + one: (arg: numbe...
packages/runtime-core/__tests__/componentEmits.spec.ts
26
TypeScript
0.643
suggestion
243
44
644
false
fix(runtime-core): use separate emits caches for components and mixins
11,661
vuejs/vue-next
25,296
TypeScript
skirtles-code
gcaaa31928
// Note: emits and listener fallthrough is tested in // ./rendererAttrsFallthrough.spec.ts. import { type ComponentPublicInstance, createApp, defineComponent, h, nextTick, nodeOps, render, toHandlers, } from '@vue/runtime-test' import { isEmitListener } from '../src/componentEmits' describe('component...
Is there a reason to grab things from internal properties here? Can't this be tested via the public API, like in the other test?
// Note: emits and listener fallthrough is tested in // ./rendererAttrsFallthrough.spec.ts. import { type ComponentPublicInstance, createApp, defineComponent, h, nextTick, nodeOps, render, toHandlers, } from '@vue/runtime-test' import { isEmitListener } from '../src/componentEmits' describe('component...
@@ -599,3 +600,76 @@ describe('component: emit', () => { expect(renderFn).toHaveBeenCalledTimes(1) }) }) + +test('merging emits for a component that is also used as a mixin', () => { + const render = () => h('div') + const CompA = { + render, + } + + const mixin = { + emits: { + one: (arg: numbe...
packages/runtime-core/__tests__/componentEmits.spec.ts
26
TypeScript
0.357
question
128
676
644
false
fix(runtime-core): use separate emits caches for components and mixins
11,661
vuejs/vue-next
25,296
TypeScript
skirtles-code
gcaaa31928