text
stringlengths
1.03k
82.6k
file_name
stringlengths
8
85
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from concurrent.futures import ThreadPoolExecutor from pathlib import Path import numpy as np import torch from torch.distributed._tensor import Placement, Shard try: # for torch 2.5+ from torch.distributed.tensor import DTensor except ImportError: from torch.distributed._tensor import DTensor from tqdm import tqdm from .base_model_merger import BaseModelMerger class FSDPModelMerger(BaseModelMerger): """ Model merger for FSDP (Fully Sharded Data Parallel) checkpoints. This class handles the conversion of FSDP distributed checkpoints into HuggingFace format. FSDP shards model parameters across multiple processes, and this merger reconstructs the full model by loading and concatenating the sharded parameters from all ranks. The merger supports various FSDP configurations including: - Pure FSDP (single dimension sharding) - FSDP + DDP (data parallel + fully sharded data parallel) - DTensor-based sharding with custom device meshes Key features: - Automatic detection of world size from checkpoint filenames - Support for DTensor and non-DTensor checkpoints - Parallel loading of checkpoint shards for efficiency - Validation against reference HuggingFace models Example: To merge FSDP checkpoints: ```python config = ModelMergerConfig( operation="merge", backend="fsdp", local_dir="path/to/fsdp/checkpoints", target_dir="path/to/output" ) merger = FSDPModelMerger(config) merger.merge_and_save() ``` """ def _get_world_size(self) -> int: """_summary_ From FSDP json config file, extract the world size. Returns: int: world size """ config_path = Path(self.config.local_dir) / "fsdp_config.json" if not config_path.exists(): raise FileNotFoundError(f"Config file {config_path} does not exist.") with open(config_path) as f: config = json.load(f) # Extract world size from the config world_size = config.get("world_size", None) if world_size is None: raise ValueError("World size not found in the config file.") return world_size def _load_rank_zero_state_dict(self, world_size: int) -> dict: return torch.load( Path(self.config.local_dir) / f"model_world_size_{world_size}_rank_0.pt", map_location="cpu", weights_only=False, ) def _extract_device_mesh_info(self, state_dict: dict, world_size: int) -> tuple[np.ndarray, tuple[str, ...]]: """ Retrieves sharding information (device_mesh, mesh_dim_names) from a DTensor in the state_dict. If no DTensor is found, infers a simple FSDP mesh based on world_size. """ pivot_key = sorted(list(state_dict.keys()))[0] weight = state_dict[pivot_key] if isinstance(weight, DTensor): # get sharding info device_mesh = weight.device_mesh mesh = device_mesh.mesh mesh_dim_names = device_mesh.mesh_dim_names else: # for non-DTensor mesh = np.array([world_size], dtype=np.int64) mesh_dim_names = ("fsdp",) return mesh, mesh_dim_names def _calculate_shard_configuration( self, mesh: np.ndarray, mesh_dim_names: tuple[str, ...] ) -> tuple[int, tuple[int, ...]]: """Calculates the total number of shards and the shape of the device mesh.""" assert mesh_dim_names in (("fsdp",), ("ddp", "fsdp")), f"Unsupported mesh_dim_names {mesh_dim_names}" if "tp" in mesh_dim_names: # TODO: "tp" is not supported yet due to the above assert total_shards = mesh.shape[-1] * mesh.shape[-2] mesh_shape = (mesh.shape[-2], mesh.shape[-1]) else: total_shards = mesh.shape[-1] mesh_shape = (mesh.shape[-1],) return total_shards, mesh_shape def _merge_by_placement(self, tensors: list[torch.Tensor], placement: Placement) -> torch.Tensor: """Merges a list of tensors based on their DTensor placement""" if placement.is_replicate(): return tensors[0] elif placement.is_partial(): raise NotImplementedError("Partial placement is not supported yet") elif placement.is_shard(): return torch.cat(tensors, dim=placement.dim).contiguous() raise NotImplementedError(f"Unsupported placement: {placement}") def _load_and_merge_state_dicts( self, world_size: int, total_shards: int, mesh_shape: tuple[int, ...], mesh_dim_names: tuple[str, ...] ) -> dict[str, torch.Tensor]: model_state_dict_lst = [None] * total_shards def process_one_shard(rank: int, model_state_dict_lst: list): model_path = Path(self.config.local_dir) / f"model_world_size_{world_size}_rank_{rank}.pt" state_dict = torch.load(model_path, map_location="cpu", weights_only=False) model_state_dict_lst[rank] = state_dict return state_dict with ThreadPoolExecutor(max_workers=min(32, os.cpu_count())) as executor: futures = [executor.submit(process_one_shard, rank, model_state_dict_lst) for rank in range(total_shards)] for future in tqdm(futures, desc=f"Loading {total_shards} FSDP shards", total=total_shards): future.result() # Merge state dicts from all shards state_dict = {} param_placements: dict[str, list] = {} for key in set(model_state_dict_lst[0].keys()): state_dict[key] = [] for model_state_shard in model_state_dict_lst: # add tensor shard in order of rank to state_dict[key] tensor = model_state_shard.pop(key) if isinstance(tensor, DTensor): state_dict[key].append(tensor._local_tensor.bfloat16()) placements = tuple(tensor.placements) # replicated placement at dp dimension can be discarded if mesh_dim_names[0] in ("dp", "ddp"): placements = placements[1:] if key not in param_placements: param_placements[key] = placements else: assert param_placements[key] == placements else: state_dict[key].append(tensor.bfloat16()) del model_state_dict_lst # Merge tensors for key in sorted(state_dict): if not isinstance(state_dict[key], list): print(f"No need to merge key {key}") continue if key in param_placements: # merge shards placements: tuple[Shard] = param_placements[key] if len(mesh_shape) == 1: # 1-D list, FSDP without TP assert len(placements) == 1 shards = state_dict[key] state_dict[key] = self._merge_by_placement(shards, placements[0]) else: # 2-D list, FSDP + TP raise NotImplementedError("FSDP + TP is not supported yet") else: state_dict[key] = torch.cat(state_dict[key], dim=0) return state_dict def merge_and_save(self): world_size = self._get_world_size() rank_zero_state_dict = self._load_rank_zero_state_dict(world_size) mesh, mesh_dim_names = self._extract_device_mesh_info(rank_zero_state_dict, world_size) print(f"Got device mesh {mesh}, mesh_dim_names {mesh_dim_names}") total_shards, mesh_shape = self._calculate_shard_configuration(mesh, mesh_dim_names) print(f"Processing model shards with {total_shards} {mesh_shape} in total") merged_state_dict = self._load_and_merge_state_dicts(world_size, total_shards, mesh_shape, mesh_dim_names) if self.config.operation == "test": if not self.config.test_hf_dir: raise ValueError("test_hf_dir must be provided for test operation") self._validate_state_dict(merged_state_dict) elif self.config.operation == "merge": self.save_hf_model_and_tokenizer(merged_state_dict) if self.config.hf_upload: self.upload_to_huggingface() else: raise ValueError(f"Unknown operation: {self.config.operation}") def _validate_state_dict(self, state_dict: dict[str, torch.Tensor]): auto_model_class = self.get_transformers_auto_model_class() hf_model = auto_model_class.from_pretrained(self.config.test_hf_dir, torch_dtype=torch.bfloat16) hf_state_dict = hf_model.state_dict() del hf_model hf_model_keys = set(hf_state_dict.keys()) collected_keys = set(state_dict.keys()) missing_keys = hf_model_keys - collected_keys assert len(missing_keys) == 0, f"Missing keys in collected state dict: {list(sorted(missing_keys))}" extra_keys = collected_keys - hf_model_keys assert len(extra_keys) == 0, f"Extra keys in collected state dict: {list(sorted(extra_keys))}" for key in hf_model_keys: hf_shape = hf_state_dict[key].shape collected_shape = state_dict[key].shape assert hf_shape == collected_shape, ( f"Shape mismatch for key '{key}': original {hf_shape} vs collected {collected_shape}" ) hf_dtype = hf_state_dict[key].dtype collected_dtype = state_dict[key].dtype assert hf_dtype == collected_dtype, ( f"Dtype mismatch for key '{key}': original {hf_dtype} vs collected {collected_dtype}" ) torch.testing.assert_close(hf_state_dict[key], state_dict[key], atol=1e-6, rtol=1e-6) print("FSDP checks passed: The merged state_dict matches the hf model saved by FSDPCheckpointManager.") def cleanup(self): """Cleanup temporary files if needed.""" # FSDP merger does not create temporary files, so no cleanup is needed. pass
verl__model_merger__fsdp_model_merger.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, ContextManager import numpy as np import torch import torch.distributed as dist try: # NPU patch import mindspeed.megatron_adaptor # noqa: F401 except ImportError: pass from accelerate import init_empty_weights from megatron.core import mpu from megatron.core.models.gpt.gpt_model import ModelType from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed from safetensors.torch import load_file from transformers import ( AutoConfig, PretrainedConfig, ) from verl.models.mcore import hf_to_mcore_config from verl.utils.device import get_device_name, get_nccl_backend, get_torch_device from verl.utils.distributed import set_numa_affinity from verl.utils.megatron.dist_checkpointing import load_dist_checkpointing from verl.utils.megatron_utils import get_model from verl.utils.tokenizer import hf_processor, hf_tokenizer from .base_model_merger import BaseModelMerger, ModelMergerConfig @contextmanager def noop_context() -> Any: yield def get_dynamic_pipeline_shards(layer_num: int, pp_size: int) -> list[int]: """Calculate the pipeline sharding configuration for Megatron-LM. Args: layer_num: Total number of layers in the model. pp_size: Number of pipeline parallel ranks. Returns: layer number of each pp rank. Make the sharding of the pipeline as uniform as possible. """ if layer_num < pp_size: raise ValueError(f"layer_num {layer_num} must be greater than pp_size {pp_size}.") if pp_size < 1: raise ValueError(f"pp_size must be at least 1, got {pp_size}.") if pp_size == 1: return [layer_num] if pp_size == 2: return [ layer_num // 2, layer_num - layer_num // 2, ] middle_size = pp_size - 2 shards_strategy = [] for middle_layer_num in range(layer_num): first_last_layer_num = layer_num - middle_layer_num * middle_size first_layer_num = first_last_layer_num // 2 last_layer_num = first_last_layer_num - first_last_layer_num // 2 if 0 < first_layer_num <= middle_layer_num and 0 < last_layer_num <= middle_layer_num: shards_strategy.append( ( [first_layer_num] + [middle_layer_num] * middle_size + [last_layer_num], abs(first_layer_num - middle_layer_num), ) ) # sort by diff of layer_num, to make it as uniform as possible res = sorted(shards_strategy, key=lambda x: x[1])[0][0] assert sum(res) == layer_num, f"sum(res)={sum(res)} != layer_num={layer_num}, pp_size={pp_size}" return res class MegatronModelMerger(BaseModelMerger): """ Model merger for Megatron-LM distributed checkpoints. This class handles the conversion of Megatron-LM distributed checkpoints into HuggingFace format. Megatron-LM uses tensor parallelism, pipeline parallelism, and data parallelism to distribute large language models across multiple GPUs. This merger reconstructs the full model by loading distributed checkpoints and applying the necessary transformations. Key features: - Support for tensor parallel, pipeline parallel, and data parallel configurations - Automatic parameter name mapping from Megatron to HuggingFace conventions - Handling of QKV and gate-up tensor splitting/merging - Support for tied word embeddings and value models - Integration with Megatron's distributed checkpointing system The merger handles various model architectures and configurations: - Standard transformer models (GPT-style) - Models with tied word embeddings - Value models for reinforcement learning - Multi-layer attention (MLA) architectures - Mixture of Experts (MoE) models Args: config (ModelMergerConfig): Configuration object with Megatron-specific settings including tie_word_embedding and is_value_model flags. Example: To merge Megatron checkpoints: ```python config = ModelMergerConfig( operation="merge", backend="megatron", local_dir="path/to/megatron/checkpoints", target_dir="path/to/output", tie_word_embedding=True ) merger = MegatronModelMerger(config) merger.merge_and_save() ``` """ def __init__(self, config: ModelMergerConfig): super().__init__(config) # Currently we use only 1 rank to merge the dist_ckpt, we will move to multi-process save shortly afterwards if "WORLD_SIZE" not in os.environ: os.environ["RANK"] = "0" os.environ["LOCAL_RANK"] = "0" os.environ["WORLD_SIZE"] = "1" os.environ["MASTER_ADDR"] = "localhost" os.environ["MASTER_PORT"] = "12355" set_numa_affinity() torch.distributed.init_process_group(get_nccl_backend()) self.rank = torch.distributed.get_rank() self.world_size = torch.distributed.get_world_size() local_rank = os.environ.get("LOCAL_RANK", 0) get_torch_device().set_device(f"{get_device_name()}:{local_rank}") mpu.initialize_model_parallel( tensor_model_parallel_size=1, pipeline_model_parallel_size=self.world_size, virtual_pipeline_model_parallel_size=None, context_parallel_size=1, expert_model_parallel_size=1, ) model_parallel_cuda_manual_seed(0) self.hf_config = AutoConfig.from_pretrained( self.config.hf_model_config_path, trust_remote_code=self.config.trust_remote_code ) print(self.hf_config, flush=True) self.params_mapping = { # megatron core gpt model name, huggingface model name # NOTICE: It's a little bit tricky, when 2 keys have the same prefix, we need to make sure the # longer key within the containing relationship is processed first. "embedding.word_embeddings": "model.embed_tokens", # input layer norm for dpskv3 "input_layernorm.weight": "input_layernorm.weight", "input_layernorm.bias": "input_layernorm.bias", # attn "self_attention.linear_qkv.layer_norm_weight": "input_layernorm.weight", "self_attention.linear_qkv.layer_norm_bias": "input_layernorm.bias", "self_attention.linear_qkv": "self_attn.qkv_proj", "self_attention.q_layernorm": "self_attn.q_norm", "self_attention.k_layernorm": "self_attn.k_norm", "self_attention.linear_proj": "self_attn.o_proj", # mla "self_attention.linear_q_proj": "self_attn.q_proj", "self_attention.linear_q_down_proj": "self_attn.q_a_proj", "self_attention.linear_q_up_proj.layer_norm_weight": "self_attn.q_a_layernorm.weight", "self_attention.linear_q_up_proj": "self_attn.q_b_proj", "self_attention.linear_kv_down_proj": "self_attn.kv_a_proj_with_mqa", "self_attention.linear_kv_up_proj.layer_norm_weight": "self_attn.kv_a_layernorm.weight", "self_attention.linear_kv_up_proj": "self_attn.kv_b_proj", # mlp "pre_mlp_layernorm": "post_attention_layernorm", "mlp.linear_fc1.layer_norm_weight": "post_attention_layernorm.weight", "mlp.linear_fc1.layer_norm_bias": "post_attention_layernorm.bias", "mlp.linear_fc1": "mlp.gate_up_proj", "mlp.linear_fc2": "mlp.down_proj", # moe "mlp.router.expert_bias": "mlp.gate.e_score_correction_bias", "mlp.router": "mlp.gate", "mlp.shared_experts.linear_fc1": "mlp.shared_experts.gate_up_proj", "mlp.shared_experts.linear_fc2": "mlp.shared_experts.down_proj", "linear_fc1": "gate_up_proj", "linear_fc2": "down_proj", # output "final_layernorm": "norm", "output_layer": "lm_head", } if "Qwen2MoeForCausalLM" in self.hf_config.architectures: self.params_mapping["mlp.shared_experts.linear_fc1"] = "mlp.shared_expert.gate_up_proj" self.params_mapping["mlp.shared_experts.linear_fc2"] = "mlp.shared_expert.down_proj" self.params_mapping["mlp.shared_experts.gate_weight"] = "mlp.shared_expert_gate.weight" def _load_state_dicts(self, model_ckpt_path: str) -> dict[str, Any]: """_summary_ Use Megatron dist_checkpointing to load the model state dicts from the checkpoint directory. Args: model_ckpt_path (str): Path to the model checkpoint directory. Returns: State dict containing the model parameters. """ # init hf config self.pipeline_shards = get_dynamic_pipeline_shards(self.hf_config.num_hidden_layers, self.world_size) print(f"Pipeline shards: {self.pipeline_shards}, total layers: {sum(self.pipeline_shards)}") tf_config = hf_to_mcore_config( self.hf_config, torch.bfloat16, num_layers_in_first_pipeline_stage=self.pipeline_shards[0] if len(self.pipeline_shards) > 1 else None, num_layers_in_last_pipeline_stage=self.pipeline_shards[-1] if len(self.pipeline_shards) > 2 else None, ) tf_config.use_cpu_initialization = self.config.use_cpu_initialization tie_word_embeddings = getattr(self.hf_config, "tie_word_embeddings", False) # init megatron model def megatron_model_provider(pre_process, post_process): from verl.models.mcore import init_mcore_model parallel_model = init_mcore_model( tf_config, self.hf_config, pre_process, post_process, share_embeddings_and_output_weights=tie_word_embeddings, value=False, ) return parallel_model context: Callable[..., ContextManager] = ( init_empty_weights if self.config.use_cpu_initialization else noop_context ) with context(): whole_model = get_model( model_provider_func=megatron_model_provider, model_type=ModelType.encoder_or_decoder, wrap_with_ddp=False, transformer_config=tf_config, ) if self.config.use_cpu_initialization: # convert meta device to empty tensor so it can use `copy_` function whole_model[0].module = whole_model[0].module.to_empty(device="cpu") # load state dicts sharded_state_dict = {} for vpp_rank, model in enumerate(whole_model): key = f"model{vpp_rank}" if len(whole_model) > 1 else "model" mpu.set_virtual_pipeline_model_parallel_rank(vpp_rank) sharded_state_dict[key] = model.sharded_state_dict() model_state_dict = load_dist_checkpointing(sharded_state_dict, model_ckpt_path) model_state_dict_list = [] for vpp_rank, model in enumerate(whole_model): key = f"model{vpp_rank}" if len(whole_model) > 1 else "model" mpu.set_virtual_pipeline_model_parallel_rank(vpp_rank) model_state_dict_list.append(model_state_dict[key]) return model_state_dict_list def _check_megatron_state_key(self, key: str) -> bool: """ Checks if the key is a valid Megatron state key. Now the model merger only supports keys that start with "decoder/embedding/output_layer" in TransformerLayer. Shall not use key starts with "model." """ if key.startswith("model."): raise ValueError( f"Invalid key {key} in Megatron state_dict. Expected keys to start with " f"'decoder/embedding/output_layer' in TransformerLayer." ) skip_checking_keys = ["embedding.word_embeddings", "output_layer"] for skip_key in skip_checking_keys: if skip_key in key: print(f"skip checking key {key}") return # Exclude extra state keys if not key.startswith("decoder"): raise ValueError( f"Invalid key {key} in Megatron state_dict. Expected keys to start with 'decoder' in TransformerLayer." ) def _split_tensors( self, key: str, tensor: torch.Tensor, config: PretrainedConfig, is_value_model: bool = False ) -> list[torch.Tensor]: """ Splits a tensor into multiple tensors based on the name. This is used to handle qkv and gate_up tensors. """ if "linear_fc1.weight" in key: # if the tensor is gate and proj gate_lst = [] up_lst = [] gate, up = tensor.chunk(2) gate_lst.append(gate) up_lst.append(up) gate = torch.cat(gate_lst, dim=0) up = torch.cat(up_lst, dim=0) return [gate, up] elif "self_attention.linear_qkv." in key and "layer_norm" not in key: # if the tensor is qkv, for each param on tp, split into q, k, v # concat q, k, v separately. q_lst, k_lst, v_lst = [], [], [] assert config.num_attention_heads % config.num_key_value_heads == 0 num_q_per_kv = config.num_attention_heads // config.num_key_value_heads assert tensor.shape[0] % (num_q_per_kv + 2) == 0, ( f"Tensor shape {tensor.shape} is not divisible by {num_q_per_kv + 2}" ) kv_size = tensor.shape[0] // (num_q_per_kv + 2) split_size = [kv_size * num_q_per_kv, kv_size, kv_size] num_query_groups_per_partition = config.num_key_value_heads for chunk in tensor.chunk(num_query_groups_per_partition): split_size = [ kv_size * num_q_per_kv // num_query_groups_per_partition, kv_size // num_query_groups_per_partition, kv_size // num_query_groups_per_partition, ] q, k, v = chunk.split(split_size) q_lst.append(q) k_lst.append(k) v_lst.append(v) return [torch.cat(q_lst, dim=0), torch.cat(k_lst, dim=0), torch.cat(v_lst, dim=0)] else: return [tensor] def _merge_state_dicts(self, model_state_dict_list: list[dict[str, Any]]) -> dict[str, torch.Tensor]: state_dict = {} layers_cum = 0 if self.world_size > 1: pipeline_cumsum = np.cumsum(self.pipeline_shards) layers_cum = 0 if self.rank == 0 else pipeline_cumsum[self.rank - 1] print(f"{layers_cum=}") for model_state_dict in model_state_dict_list: layers_handled = 0 keys = model_state_dict.keys() for key in keys: if "extra_state" in key: continue if self.config.tie_word_embedding and ("output_layer" in key): print("skip lm_head and reward_head loading because of tie_word_embeddings") continue self._check_megatron_state_key(key) hf_name = self._replace_name(key, self.params_mapping) assert hf_name is not None, f"Failed to convert layer name [{key}] from megatron to huggingface." if "model.layers." in hf_name: local_layer_no = int(hf_name.split(".")[2]) layers_handled = max(local_layer_no, layers_handled) global_layer_no = local_layer_no + layers_cum new_key_list = hf_name.split(".") new_key_list[2] = str(global_layer_no) hf_name = ".".join(new_key_list) else: warnings.warn(f"hf_name {hf_name} will not be fixed with layer number", stacklevel=2) if "mlp.experts." in hf_name and ".weight" in hf_name: name_prefix, expert_id = hf_name.split(".weight") for proj in ["gate_up", "down"]: if f"{proj}_proj" in hf_name: hf_name = hf_name.replace( f"mlp.experts.{proj}_proj.weight{expert_id}", f"mlp.experts.{expert_id}.{proj}_proj.weight", ) tensor = model_state_dict[key] split_tensor = self._split_tensors( key, tensor, self.hf_config, is_value_model=self.config.is_value_model ) if len(split_tensor) == 1: state_dict[hf_name] = split_tensor[0] elif len(split_tensor) == 3: # split qkv for n, d in zip(["q", "k", "v"], split_tensor, strict=True): state_dict[hf_name.replace("qkv", n)] = d elif len(split_tensor) == 2: # split gate up state_dict[hf_name.replace("gate_up", "gate")] = split_tensor[0] state_dict[hf_name.replace("gate_up", "up")] = split_tensor[1] shape_info = ( split_tensor.shape if isinstance(split_tensor, torch.Tensor) else [t.shape for t in split_tensor] ) print(f"converted {key} to {hf_name} with shape {shape_info}") layers_cum += layers_handled + 1 # zero based return state_dict def save_hf_model_and_tokenizer(self, merged_state_dict): if self.world_size == 1: return super().save_hf_model_and_tokenizer(merged_state_dict) from safetensors.torch import save_file layer_num = self.hf_config.num_hidden_layers # FIXME: make configurable saves_per_layer = 1 if layer_num < 30 else 2 saves_total = saves_per_layer * layer_num saves_indexes = {} # calculate the layer start index and key chunks layer_this_rank = self.pipeline_shards[self.rank] pipeline_cumsum = np.cumsum(self.pipeline_shards) layer_start = 0 if self.rank == 0 else pipeline_cumsum[self.rank - 1] keys = list(merged_state_dict.keys()) keys_chunk = np.array_split(np.array(keys), layer_this_rank * saves_per_layer) numel = 0 assert len(keys_chunk) == layer_this_rank * saves_per_layer, ( f"Expected {len(keys_chunk)} chunks, but got {layer_this_rank * saves_per_layer} for rank {self.rank}." ) # save to model shards manually target_dir = Path(self.config.target_dir) for i, keys in enumerate(keys_chunk): sd_to_save = {k: merged_state_dict[k] for k in keys} numel += sum([sd_to_save[i].numel() for i in sd_to_save]) save_idx = layer_start * saves_per_layer + i save_path = target_dir / f"model-{save_idx + 1:05d}-of-{saves_total:05d}.safetensors" save_file(sd_to_save, save_path) for k in keys: saves_indexes[k] = str(save_path.name) tensor = torch.tensor([numel]).to(get_device_name()) dist.all_reduce(tensor, op=dist.ReduceOp.SUM) numel = tensor.cpu().item() all_save_indexes = [{} for _ in range(self.world_size)] dist.all_gather_object(all_save_indexes, saves_indexes) saves_indexes = {k: v for i in all_save_indexes for k, v in i.items()} if self.rank == 0: with open(target_dir / "model.safetensors.index.json", "w") as f: json.dump( { "metadata": { "total_size": numel, }, "weight_map": saves_indexes, }, f, indent=4, ) print(f"model saved to {target_dir} with {numel=}") self.model_config.save_pretrained(self.config.target_dir) processor = hf_processor(self.hf_model_config_path, trust_remote_code=self.config.trust_remote_code) tokenizer = hf_tokenizer(self.hf_model_config_path, trust_remote_code=self.config.trust_remote_code) if processor is not None: print(f"Saving processor to {self.config.target_dir}") processor.save_pretrained(self.config.target_dir) if tokenizer is not None: print(f"Saving tokenizer to {self.config.target_dir}") tokenizer.save_pretrained(self.config.target_dir) def merge_and_save(self): from verl.utils.megatron_utils import get_dist_checkpoint_path model_ckpt_path = get_dist_checkpoint_path(self.config.local_dir) model_state_dict = self._load_state_dicts(model_ckpt_path) merged_state_dict = self._merge_state_dicts(model_state_dict) del model_state_dict if self.config.operation == "test": if not self.config.test_hf_dir: raise ValueError("test_hf_dir must be provided for test operation") self._validate_state_dict(merged_state_dict) elif self.config.operation == "merge": self.save_hf_model_and_tokenizer(merged_state_dict) if self.config.hf_upload: self.upload_to_huggingface() else: raise ValueError(f"Unknown operation: {self.config.operation}") def _validate_state_dict(self, state_dict: dict[str, torch.Tensor]): """ Compares the merged Megatron state_dict against a reference safetensors model. Applies necessary name mappings from Megatron to Hugging Face conventions using _replace_name. """ ref_state_dict = load_file(Path(self.config.test_hf_dir) / "model.safetensors") for name, loaded_weight in state_dict.items(): # name = self._replace_name(original_name, self.params_mapping) if not name or name.endswith(".bias") and name not in ref_state_dict: continue if "rotary_emb.inv_freq" in name: continue if "lm_head.weight" in name: if self.config.is_value_model or self.config.tie_word_embedding: continue if name not in ref_state_dict: raise RuntimeError(f"key: {name} not exist in state_dict") param = ref_state_dict[name] assert loaded_weight.dtype == param.dtype torch.testing.assert_close(loaded_weight.to("cpu"), param, atol=1e-2, rtol=5e-2) def _replace_name(self, megatron_name: str, name_mapping: dict[str, str]) -> str: for m_name, v_name in name_mapping.items(): if m_name not in megatron_name: continue megatron_name = megatron_name.replace("decoder", "model") param_name = megatron_name.replace(m_name, v_name) return param_name return None # Return None if no mapping found def cleanup(self): torch.distributed.destroy_process_group()
verl__model_merger__megatron_model_merger.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import torch import torch.distributed as dist from verl.utils.device import get_device_id, get_torch_device def _megatron_calc_layer_map(config): """Calculate the mapping of global layer_idx to local layer_idx Returns: layer_map (Dict: int -> tuple(int, int, int)): mapping from the global layer index to a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model) """ from megatron.core import mpu print(f"get megatron data parallel size: {mpu.get_data_parallel_world_size()}") pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 layer_map = dict() num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers for pp_rank_idx in range(pp_size): for virtual_pp_rank_idx in range(virtual_pp_size): layer_offset = ( virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model ) for layer_idx in range(num_layers_per_model): layer_map[layer_offset + layer_idx] = ( pp_rank_idx, virtual_pp_rank_idx, layer_idx, ) return layer_map def load_state_dict_to_megatron_llama( state_dict, wrapped_models, config, params_dtype, is_value_model=False, tie_word_embeddings=False ): """Load merged state_dict to sharded Megatron module in training.""" from megatron.core import DistributedDataParallel as LocalDDP from megatron.core import mpu from megatron.core.transformer.module import Float16Module from torch.nn.parallel import DistributedDataParallel as torchDDP from verl.utils.logger import print_rank_0 from verl.utils.megatron_utils import unwrap_model start_time = time.time() def _get_gpt_model(model): return model def fetch_params(module): for param in module.parameters(): torch.distributed.fetch( param.data, src=mpu.get_data_parallel_src_rank(), group=mpu.get_data_parallel_group() ) dp_rank = mpu.get_data_parallel_rank() pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 mp_group = mpu.get_model_parallel_group() if torch.distributed.get_rank() == 0: assert mp_group.rank() == 0, f"mp_rank:[{mp_group.rank}] != 0 on rank #0" assert pp_rank == 0, f"pp_rank:[{pp_rank}] != 0 on rank #0" assert dp_rank == 0, f"dp_rank:[{dp_rank}] != 0 on rank #0" if not isinstance(wrapped_models, list | tuple): wrapped_models = list(wrapped_models) assert len(wrapped_models) == virtual_pp_size num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers, ( f"num_layers_per_model: {num_layers_per_model} * pp_size: {pp_size} * virtual_pp_size " f"{virtual_pp_size} != config.num_hidden_layers: {config.num_hidden_layers}" ) models = [None] * len(wrapped_models) for i, wrapped_model in enumerate(wrapped_models): models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module)) gpt_model_module = _get_gpt_model(models[i]) assert len(gpt_model_module.model.layers) == num_layers_per_model def _fetch_tensor(tensor, name) -> torch.Tensor: """fetch tensor""" nonlocal state_dict if tensor is not None: tensor.data.copy_(state_dict[name]) def _fetch_tp_shard_tensor_vocab(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """fetch tensor in tp shards""" nonlocal state_dict tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) if tensor is not None: tensor.data.copy_(tensor_chunk[tp_rank]) else: print(f"tp_shard tensor:[{name}] not in state_dict, skip loading") def _fetch_tp_shard_tensor(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """fetch tensor in tp shards""" nonlocal state_dict tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) if tensor is not None: tensor.data.copy_(tensor_chunk[tp_rank]) else: print(f"tp_shard tensor:[{name}] not in state_dict, skip loading") def _fetch_tp_shard_tensor_gate_up(tensor, gate_name, up_name) -> torch.Tensor: """fetch gate_up tensor in tp shards""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if gate_name in state_dict and up_name in state_dict: gate_weight = state_dict[gate_name] up_weight = state_dict[up_name] new_gate_up_weight = torch.empty( config.intermediate_size * 2, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): intermediate_size_tp = config.intermediate_size // tp_size gate_weight_tp = gate_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] up_weight_tp = up_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] new_gate_up_weight[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)].copy_( torch.cat([gate_weight_tp, up_weight_tp], dim=0) ) tensor_chunk = torch.chunk(new_gate_up_weight, tp_size, dim=0) if tensor is not None: tensor.data.copy_(tensor_chunk[tp_rank]) else: print(f"tp_shard tensor:[{gate_name}, {up_name}] not in state_dict, skip loading") def _fetch_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name) -> torch.Tensor: """fetch tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() assert q_name in state_dict and k_name in state_dict and v_name in state_dict full_weight_q = state_dict[q_name] full_weight_k = state_dict[k_name] full_weight_v = state_dict[v_name] hidden_size_per_head = config.hidden_size // config.num_attention_heads if config.num_key_value_heads >= tp_size: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size total_size = q_size_tp + 2 * kv_size_tp new_weight_qkv = torch.empty( total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] k_part = full_weight_k[i * kv_size_tp : (i + 1) * kv_size_tp] v_part = full_weight_v[i * kv_size_tp : (i + 1) * kv_size_tp] new_weight_qkv[i * total_size : (i + 1) * total_size].copy_(torch.cat([q_part, k_part, v_part], dim=0)) else: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head total_size = q_size_tp + 2 * kv_size_tp new_weight_qkv = torch.empty( total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] start_idx = i * config.num_key_value_heads // tp_size * hidden_size_per_head end_idx = (i * config.num_key_value_heads // tp_size + 1) * hidden_size_per_head k_part = full_weight_k[start_idx:end_idx] v_part = full_weight_v[start_idx:end_idx] new_weight_qkv[i * total_size : (i + 1) * total_size].copy_(torch.cat([q_part, k_part, v_part], dim=0)) tensor_chunk = torch.chunk(new_weight_qkv, tp_size, dim=0) if tensor is not None: tensor.data.copy_(tensor_chunk[tp_rank]) # Embeddings # ------------------- print_rank_0("loading embeddings...") gpt_model_module = _get_gpt_model(models[0]) embed_tokens_weight = None if pp_rank == 0: embed_tokens_weight = gpt_model_module.model.embed_tokens.weight _fetch_tp_shard_tensor_vocab(embed_tokens_weight, "model.embed_tokens.weight") # Transformer layers # ------------------- layer_map = _megatron_calc_layer_map(config) pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() num_layer_per_pp = config.num_hidden_layers // pp_size vpp_size = mpu.get_virtual_pipeline_model_parallel_world_size() layer_list = [] if vpp_size is not None: for vpp_rank in range(vpp_size): num_layer_vpp_chunk = num_layer_per_pp // vpp_size num_layer_this_model = num_layer_vpp_chunk offset = vpp_rank * (config.num_hidden_layers // mpu.get_virtual_pipeline_model_parallel_world_size()) + ( mpu.get_pipeline_model_parallel_rank() * num_layer_vpp_chunk ) layer_list.extend(list(range(offset, offset + num_layer_this_model))) else: num_layer_this_model = num_layer_per_pp offset = pp_rank * num_layer_per_pp layer_list.extend(list(range(offset, offset + num_layer_this_model))) for layer in layer_list: print_rank_0(f"loading layer #{layer}...") layer_name = f"model.layers.{layer}" dst_pp_rank, dst_virtual_pp_rank, dst_layer_idx = layer_map[layer] gpt_model_module = _get_gpt_model(models[dst_virtual_pp_rank]) sync_layer = gpt_model_module.model.layers[dst_layer_idx] _fetch_tensor( sync_layer.input_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.input_layernorm.weight", ) _fetch_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_proj.weight", f"{layer_name}.self_attn.k_proj.weight", f"{layer_name}.self_attn.v_proj.weight", ) _fetch_tp_shard_tensor( sync_layer.self_attn.o_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.o_proj.weight", chunk_dim=1, ) _fetch_tensor( sync_layer.post_attention_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.post_attention_layernorm.weight", ) _fetch_tp_shard_tensor_gate_up( sync_layer.mlp.gate_up_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.gate_proj.weight", f"{layer_name}.mlp.up_proj.weight", ) _fetch_tp_shard_tensor( sync_layer.mlp.down_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.down_proj.weight", chunk_dim=1, ) # Final Layernorm # ------------------- print_rank_0("loading final layernorm...") gpt_model_module = _get_gpt_model(models[-1]) _fetch_tensor( getattr(gpt_model_module.model.norm, "weight", None), "model.norm.weight", ) print_rank_0("loading lm_head...") if pp_rank + 1 == pp_size: lm_head_weight = gpt_model_module.lm_head.weight if is_value_model: if "lm_head.weight" in state_dict and state_dict["lm_head.weight"].shape[0] == 1: _fetch_tensor(lm_head_weight, "lm_head.weight") print_rank_0("load lm_head weight") elif "reward_head.weight" in state_dict and state_dict["reward_head.weight"].shape[0] == 1: _fetch_tensor(lm_head_weight, "reward_head.weight") print_rank_0("load lm_head from value_head weight") else: _fetch_tensor(None, "lm_head.weight") print_rank_0("fail to match lm_head in value_model") else: _fetch_tp_shard_tensor(lm_head_weight, "lm_head.weight") dist.barrier() get_torch_device().empty_cache() print_rank_0(f"loading megatron ckpt done, time elapsed {time.time() - start_time}s")
verl__models__llama__megatron__checkpoint_utils__llama_loader.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import torch import torch.distributed as dist from verl.utils.device import get_device_id, get_torch_device def _megatron_calc_layer_map(config): """Calculate the mapping of global layer_idx to local layer_idx Returns: layer_map (Dict: int -> tuple(int, int, int)): mapping from the global layer index to a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model) """ from megatron.core import mpu print(f"get megatron data parallel size: {mpu.get_data_parallel_world_size()}") pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 layer_map = dict() num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers for pp_rank_idx in range(pp_size): for virtual_pp_rank_idx in range(virtual_pp_size): layer_offset = ( virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model ) for layer_idx in range(num_layers_per_model): layer_map[layer_offset + layer_idx] = ( pp_rank_idx, virtual_pp_rank_idx, layer_idx, ) return layer_map def load_state_dict_to_megatron_llama( state_dict, wrapped_models, config, params_dtype, is_value_model=False, tie_word_embeddings=False ): """Load merged state_dict to sharded Megatron module in training.""" from megatron.core import DistributedDataParallel as LocalDDP from megatron.core import mpu from megatron.core.transformer.module import Float16Module from torch.nn.parallel import DistributedDataParallel as torchDDP from verl.utils.logger import print_rank_0 from verl.utils.megatron_utils import unwrap_model start_time = time.time() def _get_gpt_model(model): return model def broadcast_params(module): for param in module.parameters(): torch.distributed.broadcast( param.data, src=mpu.get_data_parallel_src_rank(), group=mpu.get_data_parallel_group() ) dp_rank = mpu.get_data_parallel_rank() pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 mp_group = mpu.get_model_parallel_group() if torch.distributed.get_rank() == 0: assert mp_group.rank() == 0, f"mp_rank:[{mp_group.rank}] != 0 on rank #0" assert pp_rank == 0, f"pp_rank:[{pp_rank}] != 0 on rank #0" assert dp_rank == 0, f"dp_rank:[{dp_rank}] != 0 on rank #0" if not isinstance(wrapped_models, list | tuple): wrapped_models = list(wrapped_models) assert len(wrapped_models) == virtual_pp_size num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers, ( f"num_layers_per_model: {num_layers_per_model} * pp_size: {pp_size} * virtual_pp_size " f"{virtual_pp_size} != config.num_hidden_layers: {config.num_hidden_layers}" ) models = [None] * len(wrapped_models) for i, wrapped_model in enumerate(wrapped_models): models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module)) gpt_model_module = _get_gpt_model(models[i]) assert len(gpt_model_module.model.layers) == num_layers_per_model def _broadcast_tensor(tensor, name) -> torch.Tensor: """broadcast tensor from rank0 across mp_group""" nonlocal state_dict nonlocal mp_group if torch.distributed.get_rank() == 0: if name in state_dict: weight = state_dict[name] tensor_shape = weight.shape else: tensor_shape = None else: weight = None tensor_shape = None obj_list = [tensor_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) tensor_shape = obj_list[0] if tensor_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tensor:[{name}] not in state_dict, skip load") return if tensor is None: tensor = torch.empty( tensor_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) if torch.distributed.get_rank() == 0: tensor.data.copy_(weight) dist.broadcast(tensor, src=0, group=mp_group) def _broadcast_tp_shard_tensor_vocab(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == 0: if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == 0: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=0, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == 0: if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == 0: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=0, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == 0: gate_weight = state_dict[gate_name] up_weight = state_dict[up_name] new_gate_up_weight = torch.empty( config.intermediate_size * 2, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): intermediate_size_tp = config.intermediate_size // tp_size gate_weight_tp = gate_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] up_weight_tp = up_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] new_gate_up_weight[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)].copy_( torch.cat([gate_weight_tp, up_weight_tp], dim=0) ) tensor_chunk = torch.chunk(new_gate_up_weight, tp_size, dim=0) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{gate_name, up_name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank() == 0:} tensor {gate_name, up_name} shape " f"{tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == 0: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=0, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == 0: assert q_name in state_dict and k_name in state_dict and v_name in state_dict full_weight_q = state_dict[q_name] full_weight_k = state_dict[k_name] full_weight_v = state_dict[v_name] hidden_size_per_head = config.hidden_size // config.num_attention_heads if config.num_key_value_heads >= tp_size: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size total_size = q_size_tp + 2 * kv_size_tp new_weight_qkv = torch.empty( total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] k_part = full_weight_k[i * kv_size_tp : (i + 1) * kv_size_tp] v_part = full_weight_v[i * kv_size_tp : (i + 1) * kv_size_tp] new_weight_qkv[i * total_size : (i + 1) * total_size].copy_( torch.cat([q_part, k_part, v_part], dim=0) ) else: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head total_size = q_size_tp + 2 * kv_size_tp new_weight_qkv = torch.empty( total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] start_idx = i * config.num_key_value_heads // tp_size * hidden_size_per_head end_idx = (i * config.num_key_value_heads // tp_size + 1) * hidden_size_per_head k_part = full_weight_k[start_idx:end_idx] v_part = full_weight_v[start_idx:end_idx] new_weight_qkv[i * total_size : (i + 1) * total_size].copy_( torch.cat([q_part, k_part, v_part], dim=0) ) tensor_chunk = torch.chunk(new_weight_qkv, tp_size, dim=0) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{q_name, k_name, v_name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {q_name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == 0: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=0, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) if dp_rank == 0: # Embeddings # ------------------- print_rank_0("loading embeddings...") gpt_model_module = _get_gpt_model(models[0]) embed_tokens_weight = None if pp_rank == 0: embed_tokens_weight = gpt_model_module.model.embed_tokens.weight _broadcast_tp_shard_tensor_vocab(embed_tokens_weight, "model.embed_tokens.weight") # Transformer layers # ------------------- layer_map = _megatron_calc_layer_map(config) for layer in range(config.num_hidden_layers): print_rank_0(f"loading layer #{layer}...") layer_name = f"model.layers.{layer}" dst_pp_rank, dst_virtual_pp_rank, dst_layer_idx = layer_map[layer] gpt_model_module = _get_gpt_model(models[dst_virtual_pp_rank]) sync_layer = gpt_model_module.model.layers[dst_layer_idx] _broadcast_tensor( sync_layer.input_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.input_layernorm.weight", ) _broadcast_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_proj.weight", f"{layer_name}.self_attn.k_proj.weight", f"{layer_name}.self_attn.v_proj.weight", ) _broadcast_tp_shard_tensor( sync_layer.self_attn.o_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.o_proj.weight", chunk_dim=1, ) _broadcast_tensor( sync_layer.post_attention_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.post_attention_layernorm.weight", ) _broadcast_tp_shard_tensor_gate_up( sync_layer.mlp.gate_up_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.gate_proj.weight", f"{layer_name}.mlp.up_proj.weight", ) _broadcast_tp_shard_tensor( sync_layer.mlp.down_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.down_proj.weight", chunk_dim=1, ) # Final Layernorm # ------------------- print_rank_0("loading final layernorm...") gpt_model_module = _get_gpt_model(models[-1]) _broadcast_tensor( getattr(gpt_model_module.model.norm, "weight", None), "model.norm.weight", ) print_rank_0("loading lm_head...") lm_head_weight = None if pp_rank + 1 == pp_size: lm_head_weight = gpt_model_module.lm_head.weight if is_value_model: if "lm_head.weight" in state_dict and state_dict["lm_head.weight"].shape[0] == 1: _broadcast_tensor(lm_head_weight, "lm_head.weight") print_rank_0("load lm_head weight") elif "reward_head.weight" in state_dict and state_dict["reward_head.weight"].shape[0] == 1: _broadcast_tensor(lm_head_weight, "reward_head.weight") print_rank_0("load lm_head from value_head weight") else: _broadcast_tensor(None, "lm_head.weight") print_rank_0("fail to match lm_head in value_model") else: _broadcast_tp_shard_tensor(lm_head_weight, "lm_head.weight") dist.barrier() # Broadcast weights inside data parallel groups for wrapped_model in wrapped_models: broadcast_params(wrapped_model) get_torch_device().empty_cache() print_rank_0(f"loading megatron ckpt done, time elapsed {time.time() - start_time}s")
verl__models__llama__megatron__checkpoint_utils__llama_loader_depracated.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import torch import torch.distributed as dist from megatron.core import mpu from megatron.core.distributed import DistributedDataParallel as LocalDDP from megatron.core.transformer.module import Float16Module from torch.nn.parallel import DistributedDataParallel as torchDDP from verl.utils.device import get_device_id, get_torch_device from verl.utils.logger import print_rank_0 from verl.utils.megatron_utils import unwrap_model def _megatron_calc_global_rank(tp_rank: int = 0, dp_rank: int = 0, pp_rank: int = 0): """given TP,DP,PP rank to get the global rank.""" tp_size = mpu.get_tensor_model_parallel_world_size() dp_size = mpu.get_data_parallel_world_size() pp_size = mpu.get_pipeline_model_parallel_world_size() assert tp_size * dp_size * pp_size == torch.distributed.get_world_size(), ( f"{tp_size} x {dp_size} x {pp_size} != {torch.distributed.get_world_size()}" ) # We only support TP-DP-PP grouping, for correctness when resharding return (pp_rank * dp_size + dp_rank) * tp_size + tp_rank def _megatron_calc_layer_map(config): """Calculate the mapping of global layer_idx to local layer_idx Returns: layer_map (Dict: int -> tuple(int, int, int)): mapping from the global layer index to a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model) """ from megatron.core import mpu pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 layer_map = dict() num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers for pp_rank_idx in range(pp_size): for virtual_pp_rank_idx in range(virtual_pp_size): layer_offset = ( virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model ) for layer_idx in range(num_layers_per_model): layer_map[layer_offset + layer_idx] = ( pp_rank_idx, virtual_pp_rank_idx, layer_idx, ) return layer_map def merge_megatron_ckpt_llama(wrapped_models, config, dtype, is_value_model=False, tie_word_embeddings=False): """Merge sharded parameters of a Megatron module into a merged checkpoint. Args: wrapped_models (list of megatron.core.distributed.DistributedDataParallel): The local DDP wrapped megatron modules. config (str or None): HF config for model dtype: model params type is_value_model: if model is value model tie_word_embeddings: tie_word_embeddings, not used in llama, only to keep same interface with qwen2 Returns: state_dict (dict): The merged state_dict in rank 0, and an empty dictionary in other ranks. """ start_time = time.time() def _get_gpt_model(model): return model dp_rank = mpu.get_data_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() pp_rank = mpu.get_pipeline_model_parallel_rank() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 mp_group = mpu.get_model_parallel_group() if dist.get_rank() == 0: assert mp_group.rank() == 0, f"mp_rank:[{mp_group.rank}] != 0 on rank #0" assert pp_rank == 0, f"pp_rank:[{pp_rank}] != 0 on rank #0" assert dp_rank == 0, f"dp_rank:[{dp_rank}] != 0 on rank #0" if not isinstance(wrapped_models, list | tuple): wrapped_models = list(wrapped_models) assert len(wrapped_models) == virtual_pp_size num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers models = [None] * len(wrapped_models) for i, wrapped_model in enumerate(wrapped_models): models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module)) assert len(models[i].model.layers) == num_layers_per_model, ( "len model layers {} not equal to num_layers_per_model {}".format( len(models[i].model.layers), num_layers_per_model ) ) state_dict = dict() def _get_cpu_tensor(tensor: torch.Tensor): if tensor is None: return None if tensor.device == torch.device("cpu"): return tensor.detach().clone() return tensor.detach().cpu() def _broadcast_tensor(tensor, name, src_pp_rank) -> torch.Tensor: """broadcast tensor across mp_group""" nonlocal state_dict nonlocal mp_group src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank) if torch.distributed.get_rank() == src_rank: if tensor is None: weight = None tensor_shape = None else: weight = tensor tensor_shape = weight.shape else: weight = None tensor_shape = None obj_list = [tensor_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) tensor_shape = obj_list[0] if tensor_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tensor:[{name}] not exist, skip collect") return if weight is None: weight = torch.empty( tensor_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) dist.broadcast(weight, src=src_rank, group=mp_group) if torch.distributed.get_rank() == 0: state_dict[name] = _get_cpu_tensor(weight) def _broadcast_tp_shard_tensor(tensor, name, src_pp_rank, concat_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=concat_dim) if mutate_func is not None: full_tensor = mutate_func(full_tensor) state_dict[name] = full_tensor def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name, src_pp_rank) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{gate_name, up_name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=0) intermediate_size_tp = config.intermediate_size // tp_size gate_weight_list = [] up_weight_list = [] for i in range(tp_size): gate_up_weight_tp = full_tensor[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)] gate_weight_tp = gate_up_weight_tp[:intermediate_size_tp] up_weight_tp = gate_up_weight_tp[intermediate_size_tp:] gate_weight_list.append(gate_weight_tp) up_weight_list.append(up_weight_tp) state_dict[gate_name] = torch.cat(gate_weight_list, dim=0) state_dict[up_name] = torch.cat(up_weight_list, dim=0) def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, src_pp_rank): """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{q_name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=0) q_weight_list = [] k_weight_list = [] v_weight_list = [] hidden_size_per_head = config.hidden_size // config.num_attention_heads if config.num_key_value_heads >= tp_size: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size total_size = q_size_tp + 2 * kv_size_tp for i in range(tp_size): qkv_part = full_tensor[i * total_size : (i + 1) * total_size] q_part = qkv_part[:q_size_tp] k_part = qkv_part[q_size_tp : q_size_tp + kv_size_tp] v_part = qkv_part[q_size_tp + kv_size_tp : total_size] q_weight_list.append(q_part) k_weight_list.append(k_part) v_weight_list.append(v_part) else: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head total_size = q_size_tp + 2 * kv_size_tp for i in range(tp_size): qkv_part = full_tensor[i * total_size : (i + 1) * total_size] q_part = qkv_part[:q_size_tp] k_part = qkv_part[q_size_tp : q_size_tp + kv_size_tp] v_part = qkv_part[q_size_tp + kv_size_tp : total_size] q_weight_list.append(q_part) if i * config.num_key_value_heads % tp_size == 0: k_weight_list.append(k_part) v_weight_list.append(v_part) state_dict[q_name] = torch.cat(q_weight_list, dim=0) state_dict[k_name] = torch.cat(k_weight_list, dim=0) state_dict[v_name] = torch.cat(v_weight_list, dim=0) # empty cache before collecting weights get_torch_device().empty_cache() # Embeddings # ------------------- if dp_rank == 0: # Embeddings # ------------------- print_rank_0("collecting embeddings...") gpt_model_module = _get_gpt_model(models[0]) _broadcast_tp_shard_tensor( gpt_model_module.model.embed_tokens.weight if pp_rank == 0 else None, "model.embed_tokens.weight", src_pp_rank=0, ) # Transformer layers # ------------------- layer_map = _megatron_calc_layer_map(config) for layer in range(config.num_hidden_layers): print_rank_0(f"collecting layer #{layer}...") layer_name = f"model.layers.{layer}" src_pp_rank, src_virtual_pp_rank, src_layer_idx = layer_map[layer] gpt_model_module = _get_gpt_model(models[src_virtual_pp_rank]) sync_layer = gpt_model_module.model.layers[src_layer_idx] _broadcast_tensor( sync_layer.input_layernorm.weight, f"{layer_name}.input_layernorm.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.weight, f"{layer_name}.self_attn.q_proj.weight", f"{layer_name}.self_attn.k_proj.weight", f"{layer_name}.self_attn.v_proj.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor( sync_layer.self_attn.o_proj.weight, f"{layer_name}.self_attn.o_proj.weight", concat_dim=1, src_pp_rank=src_pp_rank, ) _broadcast_tensor( sync_layer.post_attention_layernorm.weight, f"{layer_name}.post_attention_layernorm.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor_gate_up( sync_layer.mlp.gate_up_proj.weight, f"{layer_name}.mlp.gate_proj.weight", f"{layer_name}.mlp.up_proj.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor( sync_layer.mlp.down_proj.weight, f"{layer_name}.mlp.down_proj.weight", concat_dim=1, src_pp_rank=src_pp_rank, ) # Final Layernorm # ------------------- print_rank_0("collecting final layernorm...") gpt_model_module = _get_gpt_model(models[-1]) _broadcast_tensor( getattr(gpt_model_module.model.norm, "weight", None), "model.norm.weight", src_pp_rank=pp_size - 1, ) print_rank_0("collecting lm_head...") if is_value_model: if pp_rank == pp_size - 1: print(f"gpt_model_module.lm_head.weight: {gpt_model_module.lm_head.weight.shape}") _broadcast_tensor( gpt_model_module.lm_head.weight if pp_rank == pp_size - 1 else None, "lm_head.weight", src_pp_rank=pp_size - 1, ) _broadcast_tensor( gpt_model_module.reward_head.weight if pp_rank == pp_size - 1 and getattr(gpt_model_module, "reward_weight", None) is not None else None, "reward_head.weight", src_pp_rank=pp_size - 1, ) else: _broadcast_tp_shard_tensor( getattr(gpt_model_module.lm_head, "weight", None) if pp_rank == pp_size - 1 else None, "lm_head.weight", src_pp_rank=pp_size - 1, ) dist.barrier() get_torch_device().empty_cache() if torch.distributed.get_rank() == 0: if dtype not in [torch.float16, torch.bfloat16, torch.float32]: print(f'Unknown/unsupported dtype to save: {dtype}"') exit(1) for k, v in state_dict.items(): if dtype != v.dtype: state_dict[k] = v.to(dtype) print_rank_0(f"merge megatron ckpt done, time elapsed {time.time() - start_time}s") return state_dict
verl__models__llama__megatron__checkpoint_utils__llama_saver.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from typing import Optional import torch import torch.nn.functional as F from einops import rearrange from flash_attn.layers.rotary import apply_rotary_emb from megatron.core import ModelParallelConfig, tensor_parallel from megatron.core import parallel_state as mpu from torch import nn from transformers import LlamaConfig from transformers.utils import is_flash_attn_2_available from verl.models.llama.megatron.layers.parallel_linear import QKVParallelLinear from verl.utils.megatron import tensor_parallel as tp_utils class LlamaRotaryEmbedding(nn.Module): def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): super().__init__() self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) # Build here to make `torch.jit.trace` work. self._set_cos_sin_cache( seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() ) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) freqs = torch.einsum("i,j->ij", t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) def forward(self, x, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] if seq_len > self.max_seq_len_cached: self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) return ( self.cos_cached[:seq_len].to(dtype=x.dtype), self.sin_cached[:seq_len].to(dtype=x.dtype), ) class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding): """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) t = t / self.scaling_factor freqs = torch.einsum("i,j->ij", t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding): """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len if seq_len > self.max_position_embeddings: base = self.base * ( (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) ) ** (self.dim / (self.dim - 2)) inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) freqs = torch.einsum("i,j->ij", t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) class LlamaLlama3ScalingRotaryEmbedding(LlamaRotaryEmbedding): def __init__(self, dim, config, max_position_embeddings=2048, base=10000, device=None): super().__init__(dim, max_position_embeddings, base, device) self.factor = config.rope_scaling["factor"] # `8` in the original implementation self.high_freq_factor = config.rope_scaling["high_freq_factor"] # `1` in the original implementation self.low_freq_factor = config.rope_scaling["low_freq_factor"] # `4` in the original implementation self.old_context_len = config.rope_scaling[ "original_max_position_embeddings" ] # `8192` in the original implementation low_freq_wavelen = self.old_context_len / self.low_freq_factor high_freq_wavelen = self.old_context_len / self.high_freq_factor wavelen = 2 * math.pi / self.inv_freq # wavelen < high_freq_wavelen: do nothing; wavelen > low_freq_wavelen: divide by factor inv_freq_llama = torch.where(wavelen > low_freq_wavelen, self.inv_freq / self.factor, self.inv_freq) # otherwise: interpolate between the two, using a smooth factor smooth_factor = (self.old_context_len / wavelen - self.low_freq_factor) / ( self.high_freq_factor - self.low_freq_factor ) smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / self.factor + smooth_factor * inv_freq_llama is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen) inv_freq = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama) self.register_buffer("inv_freq", inv_freq, persistent=False) # Build here to make `torch.jit.trace` work. self._set_cos_sin_cache( seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() ) def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb(q, k, cos, sin, position_ids): cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) class ParallelLlamaAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig): super().__init__() self.config = config self.megatron_config = megatron_config self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.hidden_size // self.num_heads self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.max_position_embeddings = config.max_position_embeddings self.rope_theta = config.rope_theta # assign values after tp tp_size = mpu.get_tensor_model_parallel_world_size() assert self.num_heads % tp_size == 0, ( f"num_head must be divisible by tp_size. Got num_head={self.num_heads}, tp_size={tp_size}" ) assert self.num_key_value_heads % tp_size == 0, ( f"num_key_value_heads must be divisible by tp_size. Got num_key_value_heads=" f"{self.num_key_value_heads}, tp_size={tp_size}" ) self.num_heads_per_tp = self.num_heads // tp_size self.num_key_value_heads_per_tp = self.num_key_value_heads // tp_size self.hidden_size_per_tp = self.hidden_size // tp_size if (self.head_dim * self.num_heads) != self.hidden_size: raise ValueError( f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and " f"`num_heads`: {self.num_heads})." ) column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear() if megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" assert row_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, megatron_config) tp_utils.update_kwargs_with_config(row_kwargs, megatron_config) # [self.q_size, self.k_size, self.v_size] self.qkv_proj = QKVParallelLinear( input_size=self.hidden_size, num_heads=self.num_heads, num_key_value_heads=self.num_key_value_heads, head_dim=self.head_dim, bias=config.attention_bias, gather_output=False, skip_bias_add=False, **column_kwargs, ) self.q_size = self.num_heads_per_tp * self.head_dim self.k_size = self.num_key_value_heads_per_tp * self.head_dim self.v_size = self.num_key_value_heads_per_tp * self.head_dim self.o_proj = tensor_parallel.RowParallelLinear( input_size=self.num_heads * self.head_dim, output_size=self.hidden_size, bias=config.attention_bias, input_is_parallel=True, skip_bias_add=False, **row_kwargs, ) self._init_rope() def _init_rope(self): if self.config.rope_scaling is None: self.rotary_emb = LlamaRotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta, ) else: rope_type_key = "type" if "type" in self.config.rope_scaling else "rope_type" scaling_type = self.config.rope_scaling[rope_type_key] scaling_factor = self.config.rope_scaling["factor"] if scaling_type == "linear": self.rotary_emb = LlamaLinearScalingRotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "dynamic": self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "llama3": self.rotary_emb = LlamaLlama3ScalingRotaryEmbedding( self.head_dim, self.config, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta, ) else: raise ValueError(f"Unknown RoPE scaling type {scaling_type}") def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: bsz, q_len, _ = hidden_states.size() qkv = self.qkv_proj(hidden_states)[0] query_states, key_states, value_states = qkv.split([self.q_size, self.k_size, self.v_size], dim=-1) query_states = query_states.view(bsz, q_len, self.num_heads_per_tp, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads_per_tp, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads_per_tp, self.head_dim).transpose(1, 2) kv_seq_len = key_states.shape[-2] cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) if attn_weights.size() != (bsz, self.num_heads_per_tp, q_len, kv_seq_len): raise ValueError( f"Attention weights should be of size {(bsz, self.num_heads_per_tp, q_len, kv_seq_len)}, " f"but is {attn_weights.size()}" ) if attention_mask is not None: if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): raise ValueError( f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" ) attn_weights = attn_weights + attention_mask # upcast attention to fp32 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) attn_output = torch.matmul(attn_weights, value_states) if attn_output.size() != (bsz, self.num_heads_per_tp, q_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads_per_tp, q_len, self.head_dim)}, " f"but is {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, self.hidden_size_per_tp) attn_output = self.o_proj(attn_output)[0] return attn_output """ Remove padding Attention - Using Flash-attn 2 - Compatible with sequence parallel """ if is_flash_attn_2_available(): from flash_attn import flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa: F401 def apply_rotary_pos_emb_rmpad(q, k, cos, sin, position_ids, indices, sequence_length): batch_size = position_ids.shape[0] q = pad_input(q, indices, batch_size, sequence_length) # (batch_size, seqlen, num_head, head_dim) k = pad_input(k, indices, batch_size, sequence_length) cos = cos[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim] sin = sin[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim] q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) q_embed = index_first_axis(rearrange(q_embed, "b s ... -> (b s) ..."), indices) k_embed = index_first_axis(rearrange(k_embed, "b s ... -> (b s) ..."), indices) return q_embed, k_embed # use flash-attn rotary embeddings with rmpad # cos/sin shoudl be: (seq_length, rotary_dim / 2) def apply_rotary_pos_emb_rmpad_flash(q, k, cos, sin, cu_seqlens, max_seqlen): q_embed = apply_rotary_emb( q, cos, sin, interleaved=False, inplace=False, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen ) k_embed = apply_rotary_emb( k, cos, sin, interleaved=False, inplace=False, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen ) return q_embed, k_embed class ParallelLlamaAttentionRmPad(ParallelLlamaAttention): def forward( self, hidden_states: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, sequence_length: int = None, indices: torch.Tensor = None, cu_seqlens: torch.Tensor = None, max_seqlen_in_batch: int = None, ): total_nnz, _, _ = hidden_states.size() # This is the total_nnz padded after sequence parallel if self.megatron_config.sequence_parallel: total_nnz = total_nnz * mpu.get_tensor_model_parallel_world_size() qkv = self.qkv_proj(hidden_states)[0] query_states, key_states, value_states = qkv.split( [self.q_size, self.k_size, self.v_size], dim=-1 ) # (total_nnz, 1, hidden_size) if self.megatron_config.sequence_parallel: sequence_parallel_pad = total_nnz - cu_seqlens[-1] total_nnz = cu_seqlens[-1] # total_nnz before sp padding query_states = query_states[:total_nnz] key_states = key_states[:total_nnz] value_states = value_states[:total_nnz] # Flash attention requires the input to have the shape # batch_size x seq_length x head_dime x hidden_dim # therefore we just need to keep the original shape query_states = query_states.view(total_nnz, self.num_heads_per_tp, self.head_dim) key_states = key_states.view(total_nnz, self.num_key_value_heads_per_tp, self.head_dim) value_states = value_states.view(total_nnz, self.num_key_value_heads_per_tp, self.head_dim) cos, sin = self.rotary_emb(value_states, seq_len=sequence_length) cos, sin = cos[:, : cos.shape[1] // 2], sin[:, : sin.shape[1] // 2] # flash attn only needs half query_states, key_states = apply_rotary_pos_emb_rmpad_flash( query_states, key_states, cos, sin, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen_in_batch ) # query_states, key_states = apply_rotary_pos_emb_rmpad(query_states, key_states, cos, sin, # position_ids, indices, # TODO: llama does not have dropout in the config?? # It is recommended to use dropout with FA according to the docs # when training. dropout_rate = 0.0 # if not self.training else self.attn_dropout # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in float16 just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (LlamaRMSNorm handles it correctly) input_dtype = query_states.dtype if input_dtype == torch.float32: query_states = query_states.to(torch.float16) key_states = key_states.to(torch.float16) value_states = value_states.to(torch.float16) attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, max_seqlen_q=max_seqlen_in_batch, max_seqlen_k=max_seqlen_in_batch, dropout_p=dropout_rate, softmax_scale=None, causal=True, ) attn_output_unpad = attn_output_unpad.to(input_dtype) attn_output_unpad = attn_output_unpad.reshape(total_nnz, 1, self.hidden_size_per_tp).contiguous() # sequence parallel reduce_scatter is performed inside RowColumnParallel if enabled # Here we need to repad if self.megatron_config.sequence_parallel: attn_output_unpad = F.pad(attn_output_unpad, pad=(0, 0, 0, 0, 0, sequence_parallel_pad)) attn_output_unpad = self.o_proj(attn_output_unpad)[0] return attn_output_unpad
verl__models__llama__megatron__layers__parallel_attention.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional import torch from megatron.core import ModelParallelConfig from torch import nn from transformers import LlamaConfig from verl.utils.megatron_utils import TransformerConfig, convert_config from .parallel_attention import ParallelLlamaAttention, ParallelLlamaAttentionRmPad from .parallel_mlp import ParallelLlamaMLP from .parallel_rmsnorm import ParallelLlamaRMSNorm class ParallelLlamaDecoderLayer(nn.Module): def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig, layer_idx: int): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.layer_idx = layer_idx self.hidden_size = config.hidden_size self.self_attn = ParallelLlamaAttention(config=config, megatron_config=megatron_config) self.mlp = ParallelLlamaMLP(config, megatron_config=megatron_config) self.input_layernorm = ParallelLlamaRMSNorm(config, megatron_config) self.post_attention_layernorm = ParallelLlamaRMSNorm(config, megatron_config) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states """ residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Note: sequence parallel is hidden inside ColumnParallelLinear # reduce scatter is hidden inside RowParallelLinear # Self Attention hidden_states = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, ) # TODO: add sequence parallel operator reduce_scatter here hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) # TODO: add sequence parallel operator all_gather here hidden_states = self.mlp(hidden_states) # TODO: add sequence parallel operator reduce_scatter here hidden_states = residual + hidden_states outputs = hidden_states return outputs class ParallelLlamaDecoderLayerRmPad(nn.Module): def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig, layer_idx: int): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.layer_idx = layer_idx self.hidden_size = config.hidden_size self.self_attn = ParallelLlamaAttentionRmPad(config=config, megatron_config=megatron_config) self.mlp = ParallelLlamaMLP(config, megatron_config=megatron_config) self.input_layernorm = ParallelLlamaRMSNorm(config, megatron_config) self.post_attention_layernorm = ParallelLlamaRMSNorm(config, megatron_config) def forward( self, hidden_states: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, sequence_length: int = None, indices: torch.Tensor = None, cu_seqlens: int = None, max_seqlen_in_batch: int = None, ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]: residual = hidden_states # (total_nnz // sp, 1, hidden_size) hidden_states = self.input_layernorm(hidden_states) # Self Attention # (total_nnz // sp, 1, hidden_size) -> all-gather (total_nnz, 1, hidden_size) # -> col + row -> reduce-scatter -> (total_nnz // sp, 1, hidden_size) hidden_states = self.self_attn( hidden_states=hidden_states, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) hidden_states = residual + hidden_states # Fully Connected # shape changes same as attn residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = hidden_states return outputs
verl__models__llama__megatron__layers__parallel_decoder.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/linear.py import torch from megatron.core import tensor_parallel class QKVParallelLinear(tensor_parallel.ColumnParallelLinear): def __init__( self, input_size, num_heads, num_key_value_heads, head_dim, *, bias=True, gather_output=True, skip_bias_add=False, **kwargs, ): # Keep input parameters, and already restrict the head numbers self.input_size = input_size self.q_output_size = num_heads * head_dim self.kv_output_size = num_key_value_heads * head_dim self.head_dim = head_dim self.gather_output = gather_output self.skip_bias_add = skip_bias_add input_size = self.input_size output_size = (num_heads + 2 * num_key_value_heads) * self.head_dim super().__init__( input_size=input_size, output_size=output_size, bias=bias, gather_output=gather_output, skip_bias_add=skip_bias_add, **kwargs, ) class MergedColumnParallelLinear(tensor_parallel.ColumnParallelLinear): def __init__( self, input_size, gate_ouput_size, up_output_size, *, bias=True, gather_output=True, skip_bias_add=False, **kwargs, ): # Keep input parameters, and already restrict the head numbers self.input_size = input_size self.output_size = gate_ouput_size + up_output_size self.gather_output = gather_output self.skip_bias_add = skip_bias_add super().__init__( input_size=self.input_size, output_size=self.output_size, bias=bias, gather_output=gather_output, skip_bias_add=skip_bias_add, **kwargs, ) class LinearForLastLayer(torch.nn.Linear): def __init__( self, input_size, output_size, *, config, bias=True, ): super().__init__(in_features=input_size, out_features=output_size, bias=bias) self.sequence_parallel = config.sequence_parallel if self.sequence_parallel: self.weight.sequence_parallel = True def forward( self, input_, weight=None, runtime_gather_output=None, ): logits = super().forward(input_) logits = logits.float() if self.sequence_parallel: logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False) return logits, None
verl__models__llama__megatron__layers__parallel_linear.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from megatron.core import ModelParallelConfig, tensor_parallel from megatron.core import parallel_state as mpu from torch import nn from transformers.activations import ACT2FN from verl.models.llama.megatron.layers.parallel_linear import MergedColumnParallelLinear from verl.utils.megatron import tensor_parallel as tp_utils class ParallelLlamaMLP(nn.Module): def __init__(self, config, megatron_config: ModelParallelConfig = None) -> None: super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size # The weight is only [hidden_size, intermediate_size // model_parallel_world_size] column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear() if megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" assert row_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(row_kwargs, megatron_config) tp_utils.update_kwargs_with_config(column_kwargs, megatron_config) tp_size = mpu.get_tensor_model_parallel_world_size() self.gate_up_proj = MergedColumnParallelLinear( input_size=self.hidden_size, gate_ouput_size=self.intermediate_size, up_output_size=self.intermediate_size, bias=False, gather_output=False, skip_bias_add=False, **column_kwargs, ) self.gate_size = self.intermediate_size // tp_size self.down_proj = tensor_parallel.RowParallelLinear( input_size=self.intermediate_size, output_size=self.hidden_size, bias=False, input_is_parallel=True, skip_bias_add=False, **row_kwargs, ) self.act_fn = ACT2FN[config.hidden_act] def forward(self, x): gate_up = self.gate_up_proj(x)[0] gate, up = gate_up.split(self.gate_size, dim=-1) return self.down_proj(self.act_fn(gate) * up)[0]
verl__models__llama__megatron__layers__parallel_mlp.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numbers import torch from megatron.core import ModelParallelConfig from torch import nn from transformers import LlamaConfig from verl.utils.megatron import sequence_parallel as sp_utils class ParallelLlamaRMSNorm(nn.Module): def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig): """ LlamaRMSNorm is equivalent to T5LayerNorm """ super().__init__() if isinstance(config.hidden_size, numbers.Integral): normalized_shape = (config.hidden_size,) self.normalized_shape = torch.Size(normalized_shape) self.weight = nn.Parameter(torch.ones(self.normalized_shape)) self.variance_epsilon = config.rms_norm_eps if megatron_config.sequence_parallel: sp_utils.mark_parameter_as_sequence_parallel(self.weight) def forward(self, hidden_states): from apex.normalization.fused_layer_norm import fused_rms_norm_affine return fused_rms_norm_affine( input=hidden_states, weight=self.weight, normalized_shape=self.normalized_shape, eps=self.variance_epsilon, memory_efficient=True, )
verl__models__llama__megatron__layers__parallel_rmsnorm.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PyTorch LLaMA model with Megatron-style acceleration.""" from typing import Optional import torch import torch.utils.checkpoint from megatron.core import ModelParallelConfig, mpu, tensor_parallel from torch import nn from transformers.modeling_outputs import BaseModelOutputWithPast from transformers.models.llama.configuration_llama import LlamaConfig from transformers.models.llama.modeling_llama import CausalLMOutputWithPast from verl.utils.megatron import sequence_parallel as sp_utils from verl.utils.megatron import tensor_parallel as tp_utils from verl.utils.megatron_utils import TransformerConfig, convert_config from .layers import ParallelLlamaDecoderLayer, ParallelLlamaDecoderLayerRmPad, ParallelLlamaRMSNorm """ TODO: 1. Add weight initialization. Here we need to be careful on TP weight init. 2. Add sequence parallel 3. Load checkpoint from meta LLama pretrained checkpoint """ # Copied from transformers.models.bart.modeling_bart._make_causal_mask def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len) # Copied from transformers.models.bart.modeling_bart._expand_mask def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) class ParallelLlamaModel(nn.Module): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] Args: config: LlamaConfig """ def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding() if megatron_config is not None: assert embedding_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config) self.embed_tokens = tensor_parallel.VocabParallelEmbedding( num_embeddings=config.vocab_size, embedding_dim=config.hidden_size, **embedding_kwargs ) self.layers = nn.ModuleList( [ParallelLlamaDecoderLayer(config, megatron_config) for _ in range(config.num_hidden_layers)] ) self.norm = ParallelLlamaRMSNorm(config, megatron_config) # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds): # create causal mask # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] combined_attention_mask = None if input_shape[-1] > 1: combined_attention_mask = _make_causal_mask( input_shape, inputs_embeds.dtype, device=inputs_embeds.device, ) if attention_mask is not None: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( inputs_embeds.device ) combined_attention_mask = ( expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask ) return combined_attention_mask def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | BaseModelOutputWithPast: """ Args: input_ids: input ids. shape (batch_size, seq_length) attention_mask: attention_mask. shape (batch_size, seq_length) position_ids: position ids. shape (batch_size, seq_length) Returns: """ batch_size, seq_length = input_ids.shape inputs_embeds = self.embed_tokens(input_ids) # embed positions attention_mask = self._prepare_decoder_attention_mask(attention_mask, (batch_size, seq_length), inputs_embeds) hidden_states = inputs_embeds for idx, decoder_layer in enumerate(self.layers): layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, ) hidden_states = layer_outputs hidden_states = self.norm(hidden_states) return hidden_states class ParallelLlamaForCausalLM(nn.Module): def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.model = ParallelLlamaModel(config, megatron_config=megatron_config) self.vocab_size = config.vocab_size column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = tensor_parallel.ColumnParallelLinear( input_size=config.hidden_size, output_size=config.vocab_size, bias=False, gather_output=False, skip_bias_add=False, **column_kwargs, ) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: ```""" # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, ) hidden_states = outputs logits = self.lm_head(hidden_states)[0] logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits) logits = logits.float() return CausalLMOutputWithPast( loss=None, logits=logits, past_key_values=None, hidden_states=None, attentions=None, ) from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa: F401, E402 class ParallelLlamaModelRmPad(nn.Module): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] Args: config: LlamaConfig """ def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding() self.megatron_config = megatron_config if megatron_config is not None: assert embedding_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config) self.embed_tokens = tensor_parallel.VocabParallelEmbedding( num_embeddings=config.vocab_size, embedding_dim=config.hidden_size, **embedding_kwargs ) self.layers = nn.ModuleList( [ParallelLlamaDecoderLayerRmPad(config, megatron_config) for _ in range(config.num_hidden_layers)] ) self.norm = ParallelLlamaRMSNorm(config, megatron_config) def forward( self, input_ids: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, sequence_length: int = None, indices: torch.Tensor = None, cu_seqlens: int = None, max_seqlen_in_batch: int = None, ) -> tuple | BaseModelOutputWithPast: """ Args: input_ids: input ids. shape (1, totol_nnz) position_ids: position ids. shape (batch_size, seq_length) Returns: """ inputs_embeds = self.embed_tokens(input_ids) # (1, total_nnz) -> (1, total_nnz, hidden_size) # (1, total_nnz, hidden_size) -> (total_nnz, 1, hidden_size) -> (total_nnz // sp, 1, hidden_size) inputs_embeds = inputs_embeds.transpose(0, 1) if self.megatron_config.sequence_parallel: inputs_embeds = tensor_parallel.scatter_to_sequence_parallel_region(inputs_embeds) hidden_states = inputs_embeds for idx, decoder_layer in enumerate(self.layers): layer_outputs = decoder_layer( hidden_states, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) hidden_states = layer_outputs hidden_states = self.norm(hidden_states) return hidden_states class ParallelLlamaForCausalLMRmPad(nn.Module): def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.megatron_config = megatron_config self.model = ParallelLlamaModelRmPad(config, megatron_config=megatron_config) self.vocab_size = config.vocab_size self._init_head(config) def _init_head(self, config): column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if self.megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = tensor_parallel.ColumnParallelLinear( input_size=config.hidden_size, output_size=config.vocab_size, bias=False, gather_output=False, skip_bias_add=False, **column_kwargs, ) def _forward_head(self, hidden_states): # all_gather from sequence parallel region is performed inside lm_head logits = self.lm_head(hidden_states)[0] logits = logits.float() # (total_nnz_padded, 1, vocab_size // tp) logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits) # (total_nnz_padded, 1, vocab_size) return logits def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: ```""" batch_size, sequence_length = input_ids.shape # remove padding here input_ids, indices, cu_seqlens, max_seqlen_in_batch, *_ = unpad_input( input_ids.unsqueeze(dim=-1), attention_mask ) # (total_nnz, 1) # pad input_ids to multiple of tp for all tp ranks # TODO: for better performance, the sp padding should be removed at each layer. Not sure the performance gap if self.megatron_config.sequence_parallel: input_ids = sp_utils.pad_to_sequence_parallel(input_ids) input_ids = input_ids.transpose(0, 1) # (1, total_nnz+pad) outputs = self.model( input_ids=input_ids, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) hidden_states = outputs logits = self._forward_head(hidden_states) # remove padding from sequence parallel if self.megatron_config.sequence_parallel: totol_nnz = cu_seqlens[-1] logits = logits[:totol_nnz] # (total_nnz_padded) logits = torch.squeeze(logits, dim=1) # remove the artificial batch dimension # add removed padding back logits = pad_input( logits, indices, batch_size, seqlen=sequence_length ) # (batch_size, sequence_length, vocab_size) return CausalLMOutputWithPast( loss=None, logits=logits, past_key_values=None, hidden_states=None, attentions=None, ) class ParallelLlamaForValueRmPad(ParallelLlamaForCausalLMRmPad): def _init_head(self, config): column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if self.megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = nn.Linear(in_features=config.hidden_size, out_features=1, bias=False) # lm_head is effectively the same as sequence parallel sp_utils.mark_parameter_as_sequence_parallel(self.lm_head.weight) def _forward_head(self, hidden_states): logits = self.lm_head(hidden_states) # (total_nnz_padded // tp, 1, 1) logits = logits.float() if self.megatron_config.sequence_parallel: logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False) return logits def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: output = super().forward(input_ids, attention_mask, position_ids) output.logits = torch.squeeze(output.logits, dim=-1) return output """ Support pipeline parallelism """ class ParallelLlamaModelRmPadPP(nn.Module): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] This model definition supports pipeline parallelism. To support pp and vpp, - This model only contains layer in this pp stage and vpp chunk - When calling get_model in Megatron, this rank will instantiate all the vpp chunks in this pp. Args: config: LlamaConfig """ def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig, pre_process, post_process): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.pre_process = pre_process self.post_process = post_process self.megatron_config = megatron_config embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding() if megatron_config is not None: assert embedding_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config) if pre_process: self.embed_tokens = tensor_parallel.VocabParallelEmbedding( num_embeddings=config.vocab_size, embedding_dim=config.hidden_size, **embedding_kwargs ) else: self.embed_tokens = None pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = megatron_config.pipeline_model_parallel_size self.num_layer_per_pp = config.num_hidden_layers // pp_size vpp_size = megatron_config.virtual_pipeline_model_parallel_size vpp_rank = mpu.get_virtual_pipeline_model_parallel_rank() if vpp_size is not None: self.layers = nn.ModuleList() self.num_layer_vpp_chunk = self.num_layer_per_pp // vpp_size self.num_layer_this_model = self.num_layer_vpp_chunk offset = vpp_rank * (config.num_hidden_layers // vpp_size) + (pp_rank * self.num_layer_vpp_chunk) else: self.num_layer_this_model = self.num_layer_per_pp offset = pp_rank * self.num_layer_per_pp self.layers = nn.ModuleList() for i in range(self.num_layer_this_model): layer = ParallelLlamaDecoderLayerRmPad(config, megatron_config, layer_idx=offset + i) self.layers.add_module(f"{i}", layer) if post_process: self.norm = ParallelLlamaRMSNorm(config, megatron_config) else: self.norm = None def set_input_tensor(self, input_tensor): """Set input tensor to be used instead of forward()'s input. When doing pipeline parallelism the input from the previous stage comes from communication, not from the input, so the model's forward_step_func won't have it. This function is thus used by internal code to bypass the input provided by the forward_step_func""" self.input_tensor = input_tensor def forward( self, input_ids: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, sequence_length: int = None, indices: torch.Tensor = None, cu_seqlens: int = None, max_seqlen_in_batch: int = None, ) -> tuple | BaseModelOutputWithPast: """ Args: input_ids: input ids. shape (1, totol_nnz) position_ids: position ids. shape (batch_size, seq_length) Returns: """ if self.pre_process: inputs_embeds = self.embed_tokens(input_ids) # (1, total_nnz) -> (1, total_nnz, hidden_size) # vocab parallel embedding will not do sequence parallel reduce-scatter in open source megatron # so need to deal with it by handle here: # (1, total_nnz, hidden_size) -> (total_nnz, 1, hidden_size) -> (total_nnz // sp, 1, hidden_size) inputs_embeds = inputs_embeds.transpose(0, 1) if self.megatron_config.sequence_parallel: inputs_embeds = tensor_parallel.scatter_to_sequence_parallel_region(inputs_embeds) hidden_states = inputs_embeds else: # self.hidden_states should be passed by Megatron hidden_states = self.input_tensor for idx, decoder_layer in enumerate(self.layers): layer_outputs = decoder_layer( hidden_states, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) hidden_states = layer_outputs if self.post_process: hidden_states = self.norm(hidden_states) return hidden_states class ParallelLlamaForCausalLMRmPadPP(nn.Module): def __init__( self, config: LlamaConfig, megatron_config: ModelParallelConfig, pre_process, post_process, share_embeddings_and_output_weights=False, ): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.megatron_config = megatron_config self.model = ParallelLlamaModelRmPadPP( config, megatron_config=megatron_config, pre_process=pre_process, post_process=post_process ) assert share_embeddings_and_output_weights is False, ( "Llama Model not supports sharing embedding and output weights" ) self.share_embeddings_and_output_weights = share_embeddings_and_output_weights self.vocab_size = config.vocab_size self.pre_process = pre_process self.post_process = post_process if post_process: self._init_head(config) def set_input_tensor(self, input_tensor): """Set input tensor to be used instead of forward()'s input. When doing pipeline parallelism the input from the previous stage comes from communication, not from the input, so the model's forward_step_func won't have it. This function is thus used by internal code to bypass the input provided by the forward_step_func""" assert len(input_tensor) == 1 self.model.set_input_tensor(input_tensor[0]) def _init_head(self, config): column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if self.megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = tensor_parallel.ColumnParallelLinear( input_size=config.hidden_size, output_size=config.vocab_size, bias=False, gather_output=False, skip_bias_add=False, **column_kwargs, ) def _forward_head(self, hidden_states): # all_gather from sequence parallel region is performed inside lm_head # logits shape before forward_head hidden_states.shape: [4, 32, 4096] logits = self.lm_head(hidden_states)[0] # logits shape after forward_head logits.shape: [8, 32, 8] logits = logits.float() # (total_nnz_padded, 1, vocab_size // tp) return logits def forward( self, # original input *, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: ```""" # Note that input_ids, attention_mask and position_ids should be passed to every pp layer. # In the first pp, input_ids will be used, in other pp layers hidden_states will be used inside self.model batch_size, sequence_length = input_ids.shape # remove padding here input_ids_rmpad, indices, cu_seqlens, max_seqlen_in_batch, *_ = unpad_input( input_ids.unsqueeze(dim=-1), attention_mask ) # (total_nnz, 1) # pad input_ids to multiple of tp for all tp ranks # TODO: for better performance, the sp padding should be removed at each layer. Not sure the performance gap if self.megatron_config.sequence_parallel: input_ids_rmpad = sp_utils.pad_to_sequence_parallel(input_ids_rmpad) input_ids_rmpad = input_ids_rmpad.transpose(0, 1) # (1, total_nnz+pad) outputs = self.model( input_ids=input_ids_rmpad, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) if self.post_process: hidden_states = outputs # print(f'hidden_states.shape = {hidden_states.shape}') # torch.Size([4, 32, 4096]) logits = self._forward_head(hidden_states) logits = torch.squeeze(logits, dim=1) # remove the artificial batch dimension # torch.Size([8, 32, 16]) # remove padding from sequence parallel if self.megatron_config.sequence_parallel: totol_nnz = cu_seqlens[-1] logits = logits[:totol_nnz] # (total_nnz_padded) # add removed padding back. If input is already rmpad, we let the caller pad_input logits = pad_input( logits, indices, batch_size, seqlen=sequence_length ) # (batch_size, sequence_length, vocab_size) return CausalLMOutputWithPast( loss=None, logits=logits, past_key_values=None, hidden_states=None, attentions=None, ) else: return outputs class ParallelLlamaForValueRmPadPP(ParallelLlamaForCausalLMRmPadPP): def _init_head(self, config): column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if self.megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = nn.Linear(in_features=config.hidden_size, out_features=1, bias=False) # lm_head is effectively the same as sequence parallel sp_utils.mark_parameter_as_sequence_parallel(self.lm_head.weight) def _forward_head(self, hidden_states): logits = self.lm_head(hidden_states) # (total_nnz_padded // tp, 1, 1) logits = logits.float() if self.megatron_config.sequence_parallel: logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False) return logits def forward( self, *, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: output = super().forward(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids) if self.post_process: output.logits = torch.squeeze(output.logits, dim=-1) return output else: return output
verl__models__llama__megatron__modeling_llama_megatron.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from megatron.bridge import AutoBridge from megatron.bridge.models.conversion.param_mapping import AutoMapping from megatron.bridge.peft.canonical_lora import CanonicalLoRA from megatron.bridge.peft.dora import DoRA from megatron.bridge.peft.lora import LoRA, VLMLoRA except ImportError: # `pip install verl[mcore]` or print("Megatron-Bridge package not found. Please install Megatron-Bridge with `pip install megatron-bridge`") raise import torch from megatron.core import tensor_parallel def _ensure_model_list(model): return model if isinstance(model, list) else [model] class LinearForLastLayer(torch.nn.Linear): """ A custom linear layer implementation for the last layer of a model. This layer extends PyTorch's Linear module with functionality specifically designed for handling the final layer in transformer models with sequence parallelism. Attributes: sequence_parallel: Boolean indicating whether sequence parallelism is enabled """ def __init__( self, input_size, output_size, *, sequence_parallel: bool, ): """ Initializes the LinearForLastLayer. Args: input_size: The size of the input features output_size: The size of the output features sequence_parallel (bool): Whether sequence parallelism is enabled """ super().__init__(in_features=input_size, out_features=output_size, bias=False) self.sequence_parallel = sequence_parallel if self.sequence_parallel: self.weight.sequence_parallel = True 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 parallel regions. Args: input_: Input tensor weight: Placeholder for compatibility runtime_gather_output: Placeholder for compatibility Returns: tuple: (logits, None) where logits is the output of the linear transformation """ logits = super().forward(input_) logits = logits.float() if self.sequence_parallel: logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False) return logits, None # Make Megatron-Bridge AutoMapping treats the custom last layer as replicated. AutoMapping.register_module_type("LinearForLastLayer", "replicated") def make_value_model(hidden_size, sequence_parallel): """Creates a pre-wrap hook that replace the output layer with a value head. Args: hidden_size (int): The hidden size of the model's transformer layers. sequence_parallel (bool): Whether sequence parallelism is enabled. Returns: A hook function that can be used as a `pre_wrap_hook` in Megatron-Bridge. The hook itself takes the model as input and prepares it for value head activation. """ from megatron.core import parallel_state def hook(model): model_post_process = [] if ( parallel_state.get_pipeline_model_parallel_world_size() > 1 and parallel_state.get_virtual_pipeline_model_parallel_world_size() is not None ): for i in range(parallel_state.get_virtual_pipeline_model_parallel_world_size()): model_post_process.append(parallel_state.is_pipeline_last_stage(ignore_virtual=False, vp_stage=i)) else: model_post_process.append(parallel_state.is_pipeline_last_stage()) model_list = _ensure_model_list(model) assert len(model_post_process) == len(model_list), "Model list length and post process list length must match." for index, model_chunk in enumerate(model_list): if not model_post_process[index]: continue model_chunk.output_layer = LinearForLastLayer( input_size=hidden_size, output_size=1, sequence_parallel=sequence_parallel, ) return hook def freeze_moe_router(model): """Pre-wrap hook to freeze MoE router parameters. Args: model: List of MegatronModule instances or single module Returns: The model with frozen router parameters """ for model_chunk in _ensure_model_list(model): if hasattr(model_chunk, "decoder") and hasattr(model_chunk.decoder, "layers"): for layer in model_chunk.decoder.layers: if hasattr(layer.mlp, "router"): if hasattr(layer.mlp.router, "weight"): layer.mlp.router.weight.requires_grad = False 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") and layer.mlp.shared_experts.gate_weight is not None ): layer.mlp.shared_experts.gate_weight.requires_grad = False if ( hasattr(layer.mlp.shared_experts, "gate_bias") and layer.mlp.shared_experts.gate_bias is not None ): layer.mlp.shared_experts.gate_bias.requires_grad = False return model __all__ = [ "AutoBridge", "make_value_model", "freeze_moe_router", "LoRA", "VLMLoRA", "DoRA", "CanonicalLoRA", ]
verl__models__mcore__bridge.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # convert huggingface config to mcore transformer config import warnings from typing import TypeVar import torch import torch.nn.functional as F from megatron.core import parallel_state as mpu from megatron.core.transformer import MLATransformerConfig, TransformerConfig from transformers import PretrainedConfig T = TypeVar("T", bound=TransformerConfig) def _get_base_transformer_config( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> dict: """ Create a base TransformerConfig with common parameters across different model architectures. TODO: (ycl) use dataclass or converter config? Args: hf_config: HuggingFace model configuration dtype: Data type for the model override_transformer_config_kwargs: Additional parameters to override defaults Returns: TransformerConfig with common parameters """ # Common parallel state parameters overlap_p2p_comm = ( mpu.get_virtual_pipeline_model_parallel_world_size() is not None and mpu.get_virtual_pipeline_model_parallel_world_size() > 1 ) batch_p2p_comm = False # Base configuration with common parameters base_config = { # Model architecture parameters "num_layers": hf_config.num_hidden_layers, "hidden_size": hf_config.hidden_size, "num_attention_heads": hf_config.num_attention_heads, "num_query_groups": hf_config.num_key_value_heads, "ffn_hidden_size": hf_config.intermediate_size, "attention_dropout": hf_config.attention_dropout, "hidden_dropout": getattr(hf_config, "hidden_dropout", 0.0), "kv_channels": getattr(hf_config, "head_dim", None), "layernorm_epsilon": hf_config.rms_norm_eps, "add_bias_linear": True, # Activation and normalization "activation_func": F.silu, "normalization": "RMSNorm", "gated_linear_unit": True, # Data types "pipeline_dtype": dtype, "params_dtype": dtype, "bf16": dtype is torch.bfloat16, # Parallel configuration "tensor_model_parallel_size": mpu.get_tensor_model_parallel_world_size(), "pipeline_model_parallel_size": mpu.get_pipeline_model_parallel_world_size(), "expert_model_parallel_size": mpu.get_expert_model_parallel_world_size(), "expert_tensor_parallel_size": mpu.get_expert_tensor_parallel_world_size(), "virtual_pipeline_model_parallel_size": mpu.get_virtual_pipeline_model_parallel_world_size(), "context_parallel_size": mpu.get_context_parallel_world_size(), "overlap_p2p_comm": overlap_p2p_comm, "batch_p2p_comm": batch_p2p_comm, "sequence_parallel": mpu.get_tensor_model_parallel_world_size() > 1, # Common settings "variable_seq_lengths": True, "masked_softmax_fusion": True, "moe_token_dispatcher_type": "alltoall", } # Update with any provided overrides # override_transformer_config_kwargs as kwargs shall never be none base_config.update(override_transformer_config_kwargs) return base_config def _get_mla_transformer_config( hf_config: PretrainedConfig, mla_rope_config: dict, dtype: torch.dtype, **override_transformer_config_kwargs ) -> dict: """ Create a MLATransformerConfig with common parameters across different model architectures. This is specifically for MLA models like DeepseekV3. Args: hf_config: HuggingFace model configuration mla_rope_config: MLA specific RoPE configuration dtype: Data type for the model override_transformer_config_kwargs: Additional parameters to override defaults Returns: MLATransformerConfig with common parameters """ base_config = _get_base_transformer_config(hf_config=hf_config, dtype=dtype, **override_transformer_config_kwargs) mla_config = { # MLA specific parameters "q_lora_rank": hf_config.q_lora_rank, "kv_lora_rank": hf_config.kv_lora_rank, "qk_head_dim": hf_config.qk_nope_head_dim, "qk_pos_emb_head_dim": hf_config.qk_rope_head_dim, "v_head_dim": hf_config.v_head_dim, "rotary_base": hf_config.rope_theta, "rotary_scaling_factor": mla_rope_config["factor"], "rope_type": mla_rope_config["type"], "max_position_embeddings": mla_rope_config["original_max_position_embeddings"], "beta_fast": mla_rope_config["beta_fast"], "beta_slow": mla_rope_config["beta_slow"], "mscale": mla_rope_config["mscale"], "mscale_all_dim": mla_rope_config["mscale_all_dim"], } base_config.update(mla_config) return base_config def check_and_construct_configs(original_config: dict, cls: type[T]) -> T: """ Check and disable incompatible configurations for older Megatron version. Args: original_config (dict): The original model configuration. Returns: dict: The updated model configuration with incompatible settings disabled. """ removed_keys = [] for key in original_config.keys(): if not hasattr(cls, key): removed_keys.append(key) if removed_keys: warnings.warn( f"The following keys are not supported in the current Megatron version and will be removed: {removed_keys}", stacklevel=2, ) for key in removed_keys: original_config.pop(key) original_config = mapping_string_to_attn_backend(original_config) if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0: print(f"Overridden {cls.__name__} init config: {original_config}") return cls(**original_config) def hf_to_mcore_config_dense( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> TransformerConfig: # for LlamaForCausalLM or Qwen2ForCausalLM qkv_bias = True if "Qwen2" in hf_config.architectures[0] else getattr(hf_config, "attention_bias", False) qk_layernorm = True if "Qwen3" in hf_config.architectures[0] else False args: dict = _get_base_transformer_config( hf_config=hf_config, dtype=dtype, use_cpu_initialization=False, 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_qwen2moe( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> TransformerConfig: args: dict = _get_base_transformer_config( hf_config=hf_config, dtype=dtype, use_cpu_initialization=False, add_bias_linear=False, layernorm_epsilon=hf_config.rms_norm_eps, # MoE specific moe_ffn_hidden_size=hf_config.moe_intermediate_size, moe_router_bias_update_rate=0.001, moe_router_topk=hf_config.num_experts_per_tok, num_moe_experts=hf_config.num_experts, moe_shared_expert_intermediate_size=hf_config.shared_expert_intermediate_size, moe_aux_loss_coeff=hf_config.router_aux_loss_coef, # moe_aux_loss_coeff=0.0, moe_router_load_balancing_type="none", # turn off aux_loss as it hurts perf in RL moe_shared_expert_overlap=True, moe_grouped_gemm=True, moe_router_score_function="softmax", # Other optimizations persist_layer_norm=True, bias_activation_fusion=True, bias_dropout_fusion=True, # Qwen specific moe_router_pre_softmax=True, add_qkv_bias=True, ) # 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_mixtral( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> TransformerConfig: args: dict = _get_base_transformer_config( hf_config=hf_config, dtype=dtype, use_cpu_initialization=False, add_bias_linear=False, layernorm_epsilon=hf_config.rms_norm_eps, # MoE specific num_moe_experts=hf_config.num_local_experts, moe_aux_loss_coeff=hf_config.router_aux_loss_coef, moe_router_topk=hf_config.num_experts_per_tok, moe_router_pre_softmax=True, moe_router_load_balancing_type="none", # turn off aux_loss as it hurts perf in RL moe_router_score_function="softmax", moe_shared_expert_intermediate_size=None, # mixtral has no shared expert moe_shared_expert_overlap=False, # mixtral has no shared expert moe_ffn_hidden_size=hf_config.intermediate_size, moe_router_bias_update_rate=0.001, # moe_permute_fusion=True, # need TE 2.1+ moe_grouped_gemm=True, # Other optimizations persist_layer_norm=True, apply_rope_fusion=True, bias_activation_fusion=True, bias_dropout_fusion=True, ) # 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_qwen3moe( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> TransformerConfig: args: dict = _get_base_transformer_config( hf_config=hf_config, dtype=dtype, use_cpu_initialization=False, add_bias_linear=False, layernorm_epsilon=hf_config.rms_norm_eps, # MoE specific moe_ffn_hidden_size=hf_config.moe_intermediate_size, moe_router_bias_update_rate=0.001, moe_router_topk=hf_config.num_experts_per_tok, num_moe_experts=hf_config.num_experts, moe_aux_loss_coeff=hf_config.router_aux_loss_coef, # moe_aux_loss_coeff=0.0, moe_router_load_balancing_type="none", # turn off aux_loss as it hurts perf in RL moe_grouped_gemm=True, moe_router_score_function="softmax", # Other optimizations persist_layer_norm=True, bias_activation_fusion=True, bias_dropout_fusion=True, # Qwen specific moe_router_pre_softmax=False, qk_layernorm=True, ) # 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_dpskv3( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> MLATransformerConfig: # DeepseekV3ForCausalLM from megatron.core.config import set_experimental_flag from megatron.core.transformer.enums import AttnBackend set_experimental_flag(True) from .patch import apply_patch apply_patch() mla_rope_config = { "beta_fast": 32, "beta_slow": 1, "factor": 1, "mscale": 1.0, "mscale_all_dim": 1.0, "original_max_position_embeddings": 4096, "type": "rope", } if "rope_scaling" in hf_config and hf_config.rope_scaling is not None: mla_rope_config.update(hf_config.rope_scaling) moe_layer_freq = [1] * hf_config.num_hidden_layers for i in range(min(hf_config.first_k_dense_replace, hf_config.num_hidden_layers)): moe_layer_freq[i] = 0 # disable MTP and quantization for now if "num_nextn_predict_layers" in hf_config: assert hf_config.num_nextn_predict_layers == 0, ( "MTP is not supported for now, please modify the config.json to set num_nextn_predict_layers to 0" ) assert "quantization_config" not in hf_config or not hf_config.quantization_config, ( "quantization is not supported for now, please modify the config.json to remove quantization_config" ) args: dict = _get_mla_transformer_config( hf_config=hf_config, mla_rope_config=mla_rope_config, dtype=dtype, # Additional parameters use_cpu_initialization=False, add_bias_linear=False, attention_backend=AttnBackend.fused, qk_layernorm=True, # Standard MoE parameters moe_ffn_hidden_size=hf_config.moe_intermediate_size, moe_token_dispatcher_type="alltoall", moe_router_bias_update_rate=0.001, moe_router_enable_expert_bias=True, moe_router_topk=hf_config.num_experts_per_tok, num_moe_experts=hf_config.n_routed_experts, moe_shared_expert_intermediate_size=hf_config.moe_intermediate_size * hf_config.n_shared_experts, moe_aux_loss_coeff=getattr(hf_config, "aux_loss_alpha", 0.001), moe_router_load_balancing_type="seq_aux_loss", moe_shared_expert_overlap=True, # moe_permute_fusion=True, # need TE 2.1+ moe_grouped_gemm=True, moe_router_score_function="sigmoid", moe_router_pre_softmax=True, moe_router_topk_scaling_factor=hf_config.routed_scaling_factor, moe_layer_freq=moe_layer_freq, # mcore 0.12 moe moe_router_dtype="fp64", disable_bf16_reduced_precision_matmul=True, # Other optimizations # deallocate_pipeline_outputs=True, # gradient_accumulation_fusion=True, persist_layer_norm=True, bias_activation_fusion=True, bias_dropout_fusion=True, ) # override_transformer_config_kwargs as kwargs shall never be none args.update(override_transformer_config_kwargs) transformer_config = check_and_construct_configs(args, MLATransformerConfig) # MTP if "num_nextn_predict_layers" in hf_config: transformer_config.mtp_num_layers = hf_config.num_nextn_predict_layers transformer_config.mtp_loss_scaling_factor = 0.1 return transformer_config def hf_to_mcore_config_qwen2_5_vl( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> TransformerConfig: # Qwen2_5_VLForConditionalGeneration args = _get_base_transformer_config( hf_config=hf_config, dtype=dtype, add_bias_linear=False, # qwen specific add_qkv_bias=True, mrope_section=hf_config.rope_scaling["mrope_section"], ) # override_transformer_config_kwargs as kwargs shall never be none args.update(override_transformer_config_kwargs) args = mapping_string_to_attn_backend(args) return TransformerConfig(**args) def hf_to_mcore_config_llama4( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> TransformerConfig: # Llama4ForConditionalGeneration raise NotImplementedError("Llama4ForConditionalGeneration is not supported yet") def mapping_string_to_attn_backend(args: dict) -> dict: if "attention_backend" in args and isinstance(args["attention_backend"], str): from megatron.core.transformer.enums import AttnBackend args["attention_backend"] = AttnBackend[args["attention_backend"]] return args
verl__models__mcore__config_converter.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import torch import torch.distributed as dist from verl.utils.device import get_device_id, get_torch_device from .saver import _megatron_calc_global_rank def _megatron_calc_layer_map(config): """Calculate the mapping of global layer_idx to local layer_idx Returns: layer_map (Dict: int -> tuple(int, int, int)): mapping from the global layer index to a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model) """ from megatron.core import mpu pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 layer_map = dict() num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers for pp_rank_idx in range(pp_size): for virtual_pp_rank_idx in range(virtual_pp_size): layer_offset = ( virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model ) for layer_idx in range(num_layers_per_model): layer_map[layer_offset + layer_idx] = ( pp_rank_idx, virtual_pp_rank_idx, layer_idx, ) return layer_map def load_state_dict_to_megatron_gptmodel(state_dict, wrapped_models, config, params_dtype, is_value_model=False): """Load merged state_dict to sharded Megatron module in training.""" from megatron.core import DistributedDataParallel as LocalDDP from megatron.core import mpu from megatron.core.transformer.module import Float16Module from torch.nn.parallel import DistributedDataParallel as torchDDP from verl.utils.logger import print_rank_0 from verl.utils.megatron_utils import unwrap_model start_time = time.time() def _get_gpt_model(model): return model def broadcast_params(module): for param in module.parameters(): torch.distributed.broadcast( param.data, src=mpu.get_data_parallel_src_rank(), group=mpu.get_data_parallel_group() ) dp_rank = mpu.get_data_parallel_rank() pp_rank = mpu.get_pipeline_model_parallel_rank() cp_rank = mpu.get_context_parallel_rank() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=0, cp_rank=cp_rank) pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 mp_group = mpu.get_model_parallel_group() if torch.distributed.get_rank() == src_rank: assert mp_group.rank() == 0, f"mp_rank:[{mp_group.rank}] != 0 on rank #0" assert pp_rank == 0, f"pp_rank:[{pp_rank}] != 0 on rank #0" assert dp_rank == 0, f"dp_rank:[{dp_rank}] != 0 on rank #0" if not isinstance(wrapped_models, list | tuple): wrapped_models = list(wrapped_models) assert len(wrapped_models) == virtual_pp_size num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers models = [None] * len(wrapped_models) for i, wrapped_model in enumerate(wrapped_models): models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module)) gpt_model_module = _get_gpt_model(models[i]) assert len(gpt_model_module.decoder.layers) == num_layers_per_model def _broadcast_tensor(tensor, name) -> torch.Tensor: """broadcast tensor from rank0 across mp_group""" nonlocal state_dict nonlocal mp_group if torch.distributed.get_rank() == src_rank: if name in state_dict: weight = state_dict[name] tensor_shape = weight.shape else: tensor_shape = None else: weight = None tensor_shape = None obj_list = [tensor_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) tensor_shape = obj_list[0] if tensor_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tensor:[{name}] not in state_dict, skip load") return if tensor is None: tensor = torch.empty( tensor_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) if torch.distributed.get_rank() == src_rank: tensor.data.copy_(weight) dist.broadcast(tensor, src=src_rank, group=mp_group) def _broadcast_tp_shard_tensor_vocab(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == src_rank: if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == src_rank: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=src_rank, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == src_rank: if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == src_rank: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=src_rank, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == src_rank: gate_weight = state_dict[gate_name] up_weight = state_dict[up_name] new_gate_up_weight = torch.empty( config.intermediate_size * 2, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): intermediate_size_tp = config.intermediate_size // tp_size gate_weight_tp = gate_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] up_weight_tp = up_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] new_gate_up_weight[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)].copy_( torch.cat([gate_weight_tp, up_weight_tp], dim=0) ) tensor_chunk = torch.chunk(new_gate_up_weight, tp_size, dim=0) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{gate_name, up_name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank() == src_rank:} tensor {gate_name, up_name} shape " f"{tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == src_rank: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=src_rank, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, bias=False) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == src_rank: assert q_name in state_dict and k_name in state_dict and v_name in state_dict full_weight_q = state_dict[q_name] full_weight_k = state_dict[k_name] full_weight_v = state_dict[v_name] hidden_size_per_head = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) if config.num_key_value_heads >= tp_size: q_size_tp = hidden_size_per_head * config.num_attention_heads // tp_size kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size total_size = q_size_tp + 2 * kv_size_tp sizes = [total_size * tp_size] if not bias: sizes.append(config.hidden_size) new_weight_qkv = torch.empty(*sizes, dtype=params_dtype, device=get_device_id()) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] k_part = full_weight_k[i * kv_size_tp : (i + 1) * kv_size_tp] v_part = full_weight_v[i * kv_size_tp : (i + 1) * kv_size_tp] num_query_groups_per_partition = models[0].config.num_query_groups // tp_size new_weight_qkv_this_tp = new_weight_qkv[i * total_size : (i + 1) * total_size] q_part_per_head = torch.chunk(q_part, num_query_groups_per_partition, dim=0) k_part_per_head = torch.chunk(k_part, num_query_groups_per_partition, dim=0) v_part_per_head = torch.chunk(v_part, num_query_groups_per_partition, dim=0) total_size_per_head = total_size // num_query_groups_per_partition for j in range(num_query_groups_per_partition): new_weight_qkv_this_tp[j * total_size_per_head : (j + 1) * total_size_per_head].copy_( torch.cat([q_part_per_head[j], k_part_per_head[j], v_part_per_head[j]], dim=0) ) else: q_size_tp = hidden_size_per_head * config.num_attention_heads // tp_size kv_size_tp = hidden_size_per_head total_size = q_size_tp + 2 * kv_size_tp sizes = [total_size * tp_size] if not bias: sizes.append(config.hidden_size) new_weight_qkv = torch.empty(*sizes, dtype=params_dtype, device=get_device_id()) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] start_idx = i * config.num_key_value_heads // tp_size * hidden_size_per_head end_idx = (i * config.num_key_value_heads // tp_size + 1) * hidden_size_per_head k_part = full_weight_k[start_idx:end_idx] v_part = full_weight_v[start_idx:end_idx] new_weight_qkv_this_tp = new_weight_qkv[i * total_size : (i + 1) * total_size] q_part_per_head = torch.chunk(q_part, config.num_attention_heads, dim=0) k_part_per_head = torch.chunk(k_part, config.num_attention_heads, dim=0) v_part_per_head = torch.chunk(v_part, config.num_attention_heads, dim=0) total_size_per_head = total_size // config.num_attention_heads for j in range(config.num_attention_heads): new_weight_qkv_this_tp[j * total_size_per_head : (j + 1) * total_size_per_head].copy_( torch.cat([q_part_per_head[j], k_part_per_head[j], v_part_per_head[j]], dim=0) ) tensor_chunk = torch.chunk(new_weight_qkv, tp_size, dim=0) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{q_name, k_name, v_name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {q_name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == src_rank: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=src_rank, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) if dp_rank == 0: # Embeddings # ------------------- print_rank_0("loading embeddings...") gpt_model_module = _get_gpt_model(models[0]) embed_tokens_weight = None if pp_rank == 0: embed_tokens_weight = gpt_model_module.embedding.word_embeddings.weight _broadcast_tp_shard_tensor_vocab(embed_tokens_weight, "model.embed_tokens.weight") # Transformer layers # ------------------- layer_map = _megatron_calc_layer_map(config) for layer in range(config.num_hidden_layers): layer_name = f"model.layers.{layer}" print_rank_0(f"loading layer #{layer}, with layer_name model.layers.{layer}...") dst_pp_rank, dst_virtual_pp_rank, dst_layer_idx = layer_map[layer] gpt_model_module = _get_gpt_model(models[dst_virtual_pp_rank]) sync_layer = gpt_model_module.decoder.layers[dst_layer_idx] _broadcast_tensor( sync_layer.self_attention.linear_qkv.layer_norm_weight if dst_pp_rank == pp_rank else None, f"{layer_name}.input_layernorm.weight", ) if f"{layer_name}.self_attn.q_norm.weight" in state_dict: _broadcast_tensor( sync_layer.self_attention.q_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_norm.weight", ) _broadcast_tensor( sync_layer.self_attention.k_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.k_norm.weight", ) _broadcast_tp_shard_tensor_qkv( sync_layer.self_attention.linear_qkv.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_proj.weight", f"{layer_name}.self_attn.k_proj.weight", f"{layer_name}.self_attn.v_proj.weight", ) if f"{layer_name}.self_attn.q_proj.bias" in state_dict: _broadcast_tp_shard_tensor_qkv( sync_layer.self_attention.linear_qkv.bias if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_proj.bias", f"{layer_name}.self_attn.k_proj.bias", f"{layer_name}.self_attn.v_proj.bias", bias=True, ) _broadcast_tp_shard_tensor( sync_layer.self_attention.linear_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.o_proj.weight", chunk_dim=1, ) _broadcast_tensor( sync_layer.mlp.linear_fc1.layer_norm_weight if dst_pp_rank == pp_rank else None, f"{layer_name}.post_attention_layernorm.weight", ) _broadcast_tp_shard_tensor_gate_up( sync_layer.mlp.linear_fc1.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.gate_proj.weight", f"{layer_name}.mlp.up_proj.weight", ) _broadcast_tp_shard_tensor( sync_layer.mlp.linear_fc2.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.down_proj.weight", chunk_dim=1, ) # Final Layernorm # ------------------- print_rank_0("loading final layernorm...") gpt_model_module = _get_gpt_model(models[-1]) _broadcast_tensor( getattr(gpt_model_module.decoder.final_layernorm, "weight", None), "model.norm.weight", ) print_rank_0("loading lm_head...") lm_head_weight = None if pp_rank + 1 == pp_size: lm_head_weight = gpt_model_module.output_layer.weight if is_value_model: # if torch.distributed.get_rank() == src_rank: if "lm_head.weight" in state_dict and state_dict["lm_head.weight"].shape[0] == 1: _broadcast_tensor(lm_head_weight, "lm_head.weight") elif "reward_head.weight" in state_dict and state_dict["reward_head.weight"].shape[0] == 1: _broadcast_tensor(lm_head_weight, "reward_head.weight") print_rank_0("load lm_head from value_head weight") elif "score.weight" in state_dict and state_dict["score.weight"].shape[0] == 1: _broadcast_tensor(lm_head_weight, "score.weight") print_rank_0("load lm_head from score weight") else: _broadcast_tensor(None, "lm_head.weight") print_rank_0("fail to match lm_head in value_model") # else: # _broadcast_tensor(lm_head_weight, "lm_head.weight") else: _broadcast_tp_shard_tensor(lm_head_weight, "lm_head.weight") dist.barrier() # Broadcast weights inside data parallel groups for wrapped_model in wrapped_models: broadcast_params(wrapped_model) pass get_torch_device().empty_cache() print_rank_0(f"loading megatron ckpt done, time elapsed {time.time() - start_time}s")
verl__models__mcore__loader.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from verl.utils.megatron_utils import unwrap_model from verl.workers.config import MtpConfig from .util import ( postprocess_bshd, postprocess_bshd_no_padding, postprocess_packed_seqs, postprocess_thd_no_padding, preprocess_bshd, preprocess_bshd_no_padding, preprocess_packed_seqs, preprocess_thd_no_padding, ) def model_forward_gen(vision_model: bool = False): def model_forward( model, input_ids, attention_mask, position_ids, multi_modal_inputs: dict, logits_processor=None, logits_processor_args: dict = None, value_model=False, data_format: str = "thd", mtp_config: MtpConfig = None, ): """Forward pass for models with sequence packing.""" assert data_format in ["thd", "bshd"], "data_format must be 'thd' or 'bshd'" pre_process = ( unwrap_model(model).pre_process if not vision_model else False ) # vision model does not need pre_process, because we pack the input_ids to thd in the forward function post_process = unwrap_model(model).post_process sp = unwrap_model(model).config.sequence_parallel fp8 = unwrap_model(model).config.fp8 use_fp8_padding = fp8 in ["e4m3", "hybrid"] model_kwargs = {} if "pixel_values" in multi_modal_inputs: model_kwargs["pixel_values"] = multi_modal_inputs["pixel_values"].to(input_ids.device) if "image_grid_thw" in multi_modal_inputs: model_kwargs["image_grid_thw"] = multi_modal_inputs["image_grid_thw"].to(input_ids.device) if "pixel_values_videos" in multi_modal_inputs: model_kwargs["pixel_values_videos"] = multi_modal_inputs["pixel_values_videos"].to(input_ids.device) if "video_grid_thw" in multi_modal_inputs: model_kwargs["video_grid_thw"] = multi_modal_inputs["video_grid_thw"].to(input_ids.device) batch_size, seq_len = attention_mask.shape[:2] if data_format == "thd": input_ids_rmpad, packed_seq_params = preprocess_packed_seqs( input_ids, attention_mask, pre_process=pre_process or post_process, use_fp8_padding=use_fp8_padding ) input_ids_rmpad = input_ids_rmpad.contiguous() # when pp > 1 and processor is not None, we need to pass the labels and loss_mask to the model if mtp_config and mtp_config.enable_train and post_process: args = { k: preprocess_packed_seqs(v, attention_mask, pre_process=True, use_fp8_padding=use_fp8_padding)[0] for k, v in logits_processor_args.items() } model_kwargs["labels"] = args["label"].contiguous() model_kwargs["loss_mask"] = args["label_mask"].contiguous() input_args = dict( input_ids=input_ids_rmpad, attention_mask=None, position_ids=position_ids if not vision_model else None, # vision models will calculate position_ids packed_seq_params=packed_seq_params, **model_kwargs, ) if vision_model: # workaround for supporting sequence packing with context parallelism # cp split with sequence packing will make model lose vision token information, so we need to keep # the original input_ids and pack them after vision embedding is calculated, # cooporate with mbridge input_args["input_ids"] = input_ids input_args["attention_mask"] = attention_mask output_orig = model(**input_args) if post_process and logits_processor is not None: args = { k: preprocess_packed_seqs(v, attention_mask, pre_process=True, use_fp8_padding=use_fp8_padding)[0] for k, v in logits_processor_args.items() } output_dict = logits_processor(output_orig, **args) output = { k: postprocess_packed_seqs( v, packed_seq_params, attention_mask, batch_size, seq_len, post_process=post_process ) for k, v in output_dict.items() } else: output = postprocess_packed_seqs( output_orig, packed_seq_params, attention_mask, batch_size, seq_len, post_process=post_process ) elif data_format == "bshd": """ data_format: "thd" or "bshd", default is "thd", why we need this? for some new models, GPT-OSS, the thd format is not supported, so we need to use the bshd format. When using the bshd format, we have to add paddings to the input_ids to meet the longest sequence length, so it is recommended to disable dynamic batch size and set batch size to 1 """ assert not vision_model, "vision model does not support bshd format" assert fp8 is None, "fp8 is not supported for bshd format yet" batch_size, sequence_length = attention_mask.shape[:2] new_input_ids, new_attention_mask, new_position_ids = preprocess_bshd( input_ids, attention_mask, position_ids, sequence_parallel=sp, pre_process=pre_process ) output_orig = model( input_ids=new_input_ids, position_ids=new_position_ids, attention_mask=new_attention_mask, **model_kwargs, ) if post_process and logits_processor is not None: args = { k: preprocess_bshd(v, attention_mask, position_ids, sequence_parallel=sp, pre_process=True)[0] for k, v in logits_processor_args.items() } output_dict = logits_processor(output_orig, **args) output = { k: postprocess_bshd( v, new_attention_mask, attention_mask, sequence_length, post_process=post_process ) for k, v in output_dict.items() } else: output = postprocess_bshd( output_orig, new_attention_mask, attention_mask, sequence_length, post_process=post_process ) if value_model and post_process: output = output[..., 0] return output return model_forward def gptmodel_forward_no_padding( model, input_ids, multi_modal_inputs: dict, logits_processor=None, logits_processor_args: dict = None, value_model=False, vision_model=False, pad_token_id=None, data_format: str = "thd", enable_mtp: bool = False, ): """Default forward pass for GPT models with optional sequence packing.""" assert data_format in ["thd", "bshd"], "data_format must be 'thd' or 'bshd'" pre_process = unwrap_model(model).pre_process post_process = unwrap_model(model).post_process model_kwargs = {} if "pixel_values" in multi_modal_inputs: model_kwargs["pixel_values"] = multi_modal_inputs["pixel_values"].to(input_ids.device) if "image_grid_thw" in multi_modal_inputs: model_kwargs["image_grid_thw"] = multi_modal_inputs["image_grid_thw"].to(input_ids.device) if "pixel_values_videos" in multi_modal_inputs: model_kwargs["pixel_values_videos"] = multi_modal_inputs["pixel_values_videos"].to(input_ids.device) if "video_grid_thw" in multi_modal_inputs: model_kwargs["video_grid_thw"] = multi_modal_inputs["video_grid_thw"].to(input_ids.device) batch_size = input_ids.shape[0] if data_format == "thd": input_ids_rmpad, packed_seq_params = preprocess_thd_no_padding(input_ids, pre_process=pre_process) input_ids_rmpad = input_ids_rmpad.contiguous() if enable_mtp and post_process: args = { k: preprocess_thd_no_padding(v, pre_process=True, need_roll=(k == "label" or k == "loss_mask"))[0] for k, v in logits_processor_args.items() } model_kwargs["labels"] = args["label"].contiguous() model_kwargs["loss_mask"] = args["loss_mask"].contiguous() if logits_processor_args and "loss_mask" in logits_processor_args: logits_processor_args.pop("loss_mask") # For VLM model, need to pass bshd format `input_ids` and `attention_mask`. attention_mask = None if vision_model: input_ids_rmpad = input_ids.to_padded_tensor(pad_token_id) seqlens_in_batch = input_ids.offsets().diff() attention_mask = torch.zeros_like(input_ids_rmpad, dtype=torch.bool) for i, seqlen in enumerate(seqlens_in_batch): attention_mask[i, :seqlen] = True output_orig = model( input_ids=input_ids_rmpad, attention_mask=attention_mask, position_ids=None, packed_seq_params=packed_seq_params, **model_kwargs, ) if post_process and logits_processor is not None: args = { k: preprocess_thd_no_padding(v, pre_process=True, need_roll=(k == "label"))[0] for k, v in logits_processor_args.items() } output_dict = logits_processor(output_orig, **args) output = { k: postprocess_thd_no_padding(v, packed_seq_params, input_ids, batch_size, post_process=post_process) for k, v in output_dict.items() } else: output = postprocess_thd_no_padding( output_orig, packed_seq_params, input_ids, batch_size, post_process=post_process ) else: """ data_format: "thd" or "bshd", default is "thd", why we need this? for some new models, GPT-OSS, the thd format is not supported, so we need to use the bshd format. When using the bshd format, we have to add paddings to the input_ids to meet the longest sequence length, so it is recommended to disable dynamic batch size and set batch size to 1 """ input_ids_bshd, attention_mask_bshd, position_ids_bshd = preprocess_bshd_no_padding( input_ids, pre_process=pre_process ) if enable_mtp and post_process: args = { k: preprocess_bshd_no_padding(v, pre_process=True, need_roll=(k == "label" or k == "loss_mask"))[0] for k, v in logits_processor_args.items() } model_kwargs["labels"] = args["label"].contiguous() model_kwargs["loss_mask"] = args["loss_mask"].contiguous() if logits_processor_args and "loss_mask" in logits_processor_args: logits_processor_args.pop("loss_mask") output_orig = model( input_ids=input_ids_bshd, attention_mask=attention_mask_bshd, position_ids=position_ids_bshd, **model_kwargs, ) if post_process and logits_processor is not None: args = { k: preprocess_bshd_no_padding(v, pre_process=True, need_roll=(k == "label"))[0] for k, v in logits_processor_args.items() } output_dict = logits_processor(output_orig, **args) output = { k: postprocess_bshd_no_padding(v, attention_mask_bshd, post_process=post_process) for k, v in output_dict.items() } else: output = postprocess_bshd_no_padding(output_orig, attention_mask_bshd, post_process=post_process) if value_model and post_process: # output = output[..., 0] # while using nested tensor, the advanced indexing operation above will result in an error at backward, i.e. # ValueError: NestedTensor _nested_select_backward_default(grad_output: t, self: jt_all, dim: any, index: any) # so we use `squeeze` to remove the last dimension output = output.squeeze(-1) return output
verl__models__mcore__model_forward.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Callable, Optional import torch from megatron.core.models.common.model_chunk_schedule_plan import TransformerModelChunkSchedulePlan from megatron.core.models.gpt.gpt_model import GPTModel from megatron.core.utils import make_viewless_tensor from torch import Tensor from verl.models.mcore.util import preprocess_packed_seqs from verl.utils.kernel.linear_cross_entropy import linear_cross_entropy from verl.utils.megatron_utils import unwrap_model from verl.utils.model import CausalLMOutputForPPO from .util import postprocess_packed_seqs, postprocess_packed_seqs_for_dict_output def gptmodel_forward_1f1b_overlap( model: GPTModel, input_ids: Tensor, position_ids: Tensor, attention_mask: Tensor, labels: Tensor = None, labels_mask: Tensor = None, multi_modal_inputs: Optional[dict] = None, logits_processor: Optional[Callable] = None, logits_processor_args: Optional[dict] = None, temperature: float = 1.0, ) -> TransformerModelChunkSchedulePlan: pre_process: bool = unwrap_model(model).pre_process post_process: bool = unwrap_model(model).post_process assert logits_processor is None, "only support fused kernel" batch_size, seq_len = attention_mask.shape[:2] input_ids_rmpad, packed_seq_params = preprocess_packed_seqs(input_ids, attention_mask, pre_process=pre_process) input_ids_rmpad = input_ids_rmpad.contiguous() schedule_plan = model.build_schedule_plan( input_ids=input_ids_rmpad, attention_mask=attention_mask, labels=labels, position_ids=position_ids, packed_seq_params=packed_seq_params, ) if post_process: attention_mask_out = attention_mask def _postprocess( self, hidden_states, input_ids, position_ids, labels, rotary_pos_emb, rotary_pos_cos, rotary_pos_sin, mtp_in_postprocess=None, loss_mask=None, decoder_input=None, attention_mask=None, inference_params=None, packed_seq_params=None, sequence_len_offset=None, runtime_gather_output=None, extra_block_kwargs=None, inference_context=None, ): """patched from https://github.com/NVIDIA/Megatron-LM/blob/core_r0.14.0/megatron/core/models/gpt/gpt_model.py#L412""" """Postprocesses decoder hidden states to generate logits or compute loss. Applies Multi-Token Prediction if enabled, generates output logits through the output layer, and computes language model loss when labels are provided. """ from megatron.core import parallel_state from megatron.core.tensor_parallel import gather_from_sequence_parallel_region in_inference_mode = inference_context is not None and not self.training if in_inference_mode: assert runtime_gather_output, "Inference must always gather TP logits" # logits and loss output_weight = None if self.share_embeddings_and_output_weights: output_weight = self.shared_embedding_or_output_weight() if mtp_in_postprocess: hidden_states = self.mtp( input_ids=input_ids, position_ids=position_ids, hidden_states=hidden_states, attention_mask=attention_mask, inference_params=inference_params, rotary_pos_emb=rotary_pos_emb, rotary_pos_cos=rotary_pos_cos, rotary_pos_sin=rotary_pos_sin, packed_seq_params=packed_seq_params, sequence_len_offset=sequence_len_offset, embedding=self.embedding, **(extra_block_kwargs or {}), ) if not self.post_process: return hidden_states if self.mtp_process: from megatron.core.transformer.multi_token_prediction import ( MTPLossAutoScaler, MTPLossLoggingHelper, roll_tensor, ) mtp_labels = labels.clone() hidden_states_list = torch.chunk(hidden_states, 1 + self.config.mtp_num_layers, dim=0) hidden_states = hidden_states_list[0] if loss_mask is None: # if loss_mask is not provided, use all ones as loss_mask loss_mask = torch.ones_like(mtp_labels) for mtp_layer_number in range(self.config.mtp_num_layers): # output mtp_logits, _ = self.output_layer( hidden_states_list[mtp_layer_number + 1], weight=output_weight, runtime_gather_output=runtime_gather_output, ) # Calc loss for the current Multi-Token Prediction (MTP) layers. mtp_labels, _ = roll_tensor(mtp_labels, shifts=-1, dims=-1, cp_group=self.cp_group) loss_mask, num_tokens = roll_tensor(loss_mask, shifts=-1, dims=-1, cp_group=self.cp_group) mtp_loss = self.compute_language_model_loss(mtp_labels, mtp_logits) mtp_loss = loss_mask * mtp_loss if self.training: # TODO(shifangx): remove the use of parallel_state here # after moving loss logging to loss_func in pretrain_gpt.py MTPLossLoggingHelper.save_loss_to_tracker( torch.sum(mtp_loss) / num_tokens, mtp_layer_number, self.config.mtp_num_layers, avg_group=parallel_state.get_data_parallel_group(with_context_parallel=True), ) mtp_loss_scale = self.config.mtp_loss_scaling_factor / self.config.mtp_num_layers if self.config.calculate_per_token_loss: hidden_states = MTPLossAutoScaler.apply(hidden_states, mtp_loss_scale * mtp_loss) else: hidden_states = MTPLossAutoScaler.apply(hidden_states, mtp_loss_scale * mtp_loss / num_tokens) if logits_processor is not None: logits, _ = self.output_layer( hidden_states, weight=output_weight, runtime_gather_output=runtime_gather_output ) output_orig = logits.transpose(0, 1).contiguous() args = { k: preprocess_packed_seqs(v, attention_mask_out, pre_process=True)[0] for k, v in logits_processor_args.items() } output_dict = logits_processor(output_orig, **args) output = { k: postprocess_packed_seqs( v, packed_seq_params, attention_mask_out, batch_size, seq_len, post_process=post_process ) for k, v in output_dict.items() } else: # fused kernel labels_rmpad, _ = preprocess_packed_seqs(labels, attention_mask, pre_process=True) labels_mask_rmpad, _ = preprocess_packed_seqs(labels_mask, attention_mask, pre_process=True) labels_rmpad = labels_rmpad.contiguous() labels_mask_rmpad = labels_mask_rmpad.contiguous() output = CausalLMOutputForPPO( loss=None, logits=None, past_key_values=None, hidden_states=hidden_states, attentions=None, ) if self.config.sequence_parallel: hidden_states = gather_from_sequence_parallel_region(hidden_states) logprobs, entropy = linear_cross_entropy( hidden_states, self.output_layer.weight, labels_rmpad, temperature, "none", parallel_state.get_tensor_model_parallel_group(), ) output.entropy = entropy output.log_probs = logprobs output = postprocess_packed_seqs_for_dict_output( labels_mask_rmpad, output, packed_seq_params, attention_mask, batch_size, seq_len, post_process=post_process, ) output_ = [output["log_probs"]] # TODO NOW 1f1b overlap only support one tensor output # if "entropy" in output: # output_.append(output["entropy"]) output_ = tuple(output_) return output_ def _custom_post_process_node_forward_impl(self, hidden_states): if self.gpt_model.decoder.final_layernorm and not self.gpt_model.mtp_process: hidden_states = self.gpt_model.decoder.final_layernorm(hidden_states) # TENorm produces a "viewed" tensor. This will result in schedule.py's # deallocate_output_tensor() throwing an error, so a viewless tensor is # created to prevent this. hidden_states = make_viewless_tensor(inp=hidden_states, requires_grad=True, keep_graph=True) # Run GPTModel._postprocess output = self.gpt_model._postprocess( hidden_states=hidden_states, input_ids=self.chunk_state.input_ids, position_ids=self.chunk_state.position_ids, labels=self.chunk_state.labels, decoder_input=self.chunk_state.decoder_input, rotary_pos_emb=self.chunk_state.rotary_pos_emb, rotary_pos_cos=self.chunk_state.rotary_pos_cos, rotary_pos_sin=self.chunk_state.rotary_pos_sin, mtp_in_postprocess=False, loss_mask=self.chunk_state.loss_mask, attention_mask=self.chunk_state.attention_mask, packed_seq_params=self.chunk_state.packed_seq_params, sequence_len_offset=self.chunk_state.sequence_len_offset, runtime_gather_output=self.chunk_state.runtime_gather_output, extra_block_kwargs=self.chunk_state.extra_block_kwargs, ) return output schedule_plan.post_process.forward_impl = _custom_post_process_node_forward_impl.__get__( schedule_plan.post_process, schedule_plan.post_process.__class__ ) unwrap_model(model)._postprocess = _postprocess.__get__(unwrap_model(model), unwrap_model(model).__class__) return schedule_plan
verl__models__mcore__model_forward_1f1b_overlap.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import OrderedDict from typing import Optional import megatron.core as mcore import torch from megatron.core import parallel_state from megatron.core.config_logger import has_config_logger_enabled, log_config_to_disk from megatron.core.inference.contexts import BaseInferenceContext from megatron.core.models.gpt.gpt_model import GPTModel from megatron.core.packed_seq_params import PackedSeqParams from megatron.core.tensor_parallel.mappings import gather_from_sequence_parallel_region from megatron.core.utils import deprecate_inference_params from packaging import version from torch import Tensor 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.megatron_utils import unwrap_model from verl.utils.model import CausalLMOutputForPPO from .util import postprocess_packed_seqs_for_dict_output, postprocess_thd_no_padding def _get_patching_model(model: torch.nn.Module): model = unwrap_model(model) if isinstance(model, GPTModel): return model if not (hasattr(model, "language_model") and isinstance(model.language_model, GPTModel)): print(f"Model {model.__class__.__name__} is not a supported for fused forward") return None return model.language_model def patch_fused_forward(model: torch.nn.Module): assert version.parse(mcore.__version__) >= version.parse("0.13.0"), ( "Fused forward patching requires mecore >= 0.13.0" ) model = _get_patching_model(model) if model is not None: model.forward_backup = model.forward model.forward = _fused_GPTModel_forward.__get__(model, model.__class__) def unpatch_fused_forward(model: torch.nn.Module): model = _get_patching_model(model) if model is not None: model.forward = model.forward_backup def fused_forward_model_gen(vision_model: bool = False): def fused_forward_model( model, input_ids: Tensor, position_ids: Tensor, attention_mask: Tensor, labels: Tensor, labels_mask: Tensor, temperature: float, multi_modal_inputs: dict, ): pre_process: bool = ( unwrap_model(model).pre_process if not vision_model else False ) # vision model does not need pre_process, because we pack the input_ids to thd in the forward function post_process: bool = unwrap_model(model).post_process model_kwargs = {} if "pixel_values" in multi_modal_inputs: model_kwargs["pixel_values"] = multi_modal_inputs["pixel_values"].to(input_ids.device) if "image_grid_thw" in multi_modal_inputs: model_kwargs["image_grid_thw"] = multi_modal_inputs["image_grid_thw"].to(input_ids.device) if "pixel_values_videos" in multi_modal_inputs: model_kwargs["pixel_values_videos"] = multi_modal_inputs["pixel_values_videos"].to(input_ids.device) if "video_grid_thw" in multi_modal_inputs: model_kwargs["video_grid_thw"] = multi_modal_inputs["video_grid_thw"].to(input_ids.device) batch_size, seq_len = attention_mask.shape[:2] input_ids_rmpad, packed_seq_params = preprocess_packed_seqs(input_ids, attention_mask, pre_process=pre_process) input_ids_rmpad = input_ids_rmpad.contiguous() labels_rmpad, _ = preprocess_packed_seqs(labels, attention_mask, pre_process=True) labels_mask_rmpad, _ = preprocess_packed_seqs(labels_mask, attention_mask, pre_process=True) labels_rmpad = labels_rmpad.contiguous() labels_mask_rmpad = labels_mask_rmpad.contiguous() input_args = dict( input_ids=input_ids_rmpad, attention_mask=None, position_ids=position_ids if not vision_model else None, # vision models will calculate position_ids packed_seq_params=packed_seq_params, labels=labels_rmpad, temperature=temperature, **model_kwargs, ) if vision_model: # workaround for supporting sequence packing with context parallelism # cp split with sequence packing will make model lose vision token information, so we need to keep # the original input_ids and pack them after vision embedding is calculated, # cooporate with mbridge input_args["input_ids"] = input_ids input_args["attention_mask"] = attention_mask output_orig: CausalLMOutputForPPO = model(**input_args) if post_process: # output_orig is in type of CausalLMOutputForPPO output = postprocess_packed_seqs_for_dict_output( labels_mask_rmpad, output_orig, packed_seq_params, attention_mask, batch_size, seq_len, 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, multi_modal_inputs: dict, temperature: float, calculate_entropy: bool, pad_token_id: int, ): pre_process = unwrap_model(model).pre_process post_process = unwrap_model(model).post_process input_ids_rmpad, packed_seq_params = preprocess_thd_no_padding(input_ids, pre_process=pre_process) input_ids_rmpad = input_ids_rmpad.contiguous() model_kwargs = {} if "pixel_values" in multi_modal_inputs: model_kwargs["pixel_values"] = multi_modal_inputs["pixel_values"].to(input_ids.device) if "image_grid_thw" in multi_modal_inputs: model_kwargs["image_grid_thw"] = multi_modal_inputs["image_grid_thw"].to(input_ids.device) if "pixel_values_videos" in multi_modal_inputs: model_kwargs["pixel_values_videos"] = multi_modal_inputs["pixel_values_videos"].to(input_ids.device) if "video_grid_thw" in multi_modal_inputs: model_kwargs["video_grid_thw"] = multi_modal_inputs["video_grid_thw"].to(input_ids.device) attention_mask = None if vision_model: input_ids_rmpad = input_ids.to_padded_tensor(pad_token_id) seqlens_in_batch = input_ids.offsets().diff().to(input_ids.device) max_seq_len = input_ids_rmpad.shape[1] attention_mask = torch.arange(max_seq_len, device=input_ids.device).unsqueeze( 0 ) < seqlens_in_batch.unsqueeze(1) labels_rmpad, _ = preprocess_thd_no_padding(labels, pre_process=True, need_roll=True) labels_rmpad = labels_rmpad.contiguous() output_orig: CausalLMOutputForPPO = model( input_ids=input_ids_rmpad, attention_mask=attention_mask, position_ids=None, packed_seq_params=packed_seq_params, labels=labels_rmpad, temperature=temperature, **model_kwargs, ) if not post_process: return output_orig log_probs = output_orig.log_probs if log_probs.dim() == 1: log_probs = log_probs.unsqueeze(0) log_probs = postprocess_thd_no_padding( log_probs, packed_seq_params, input_ids, input_ids.shape[0], post_process=post_process ) output = {"log_probs": log_probs} if calculate_entropy: entropy = output_orig.entropy if entropy.dim() == 1: entropy = entropy.unsqueeze(0) entropy = postprocess_thd_no_padding( entropy, packed_seq_params, input_ids, input_ids.shape[0], post_process=post_process ) output["entropy"] = entropy return output return fused_forward_no_padding def _fused_GPTModel_forward( model, input_ids: Tensor, position_ids: Tensor, attention_mask: Tensor, decoder_input: Tensor = None, labels: Tensor = None, inference_context: BaseInferenceContext = None, packed_seq_params: PackedSeqParams = None, extra_block_kwargs: dict = None, runtime_gather_output: Optional[bool] = None, *, inference_params: Optional[BaseInferenceContext] = None, loss_mask: Optional[Tensor] = None, temperature: float = 1.0, **kwargs, ) -> CausalLMOutputForPPO: """ Patch self._postprocess in forward for GPT models to enable fused kernel support. https://github.com/NVIDIA/Megatron-LM/blob/core_v0.13.0/megatron/core/models/gpt/gpt_model.py TODO: Currently we still need to patch `forward` because we need to pass `temperature` explicitly to `self._postprocess` when calling, maybe there can be a better way to handle this? """ inference_context = deprecate_inference_params(inference_context, inference_params) preproc_output = model._preprocess( input_ids=input_ids, position_ids=position_ids, decoder_input=decoder_input, inference_context=inference_context, packed_seq_params=packed_seq_params, ) (decoder_input, rotary_pos_emb, rotary_pos_cos, rotary_pos_sin, sequence_len_offset) = preproc_output[:5] # Run decoder. hidden_states = model.decoder( hidden_states=decoder_input, attention_mask=attention_mask, inference_context=inference_context, rotary_pos_emb=rotary_pos_emb, rotary_pos_cos=rotary_pos_cos, rotary_pos_sin=rotary_pos_sin, packed_seq_params=packed_seq_params, sequence_len_offset=sequence_len_offset, **(extra_block_kwargs or {}), **kwargs, ) if not model.post_process: return hidden_states output = CausalLMOutputForPPO( loss=None, logits=None, past_key_values=None, hidden_states=hidden_states, attentions=None, ) if model.config.sequence_parallel: hidden_states = gather_from_sequence_parallel_region(hidden_states) # Get the output weight - use embedding weight if output_layer is None or weight is shared if hasattr(model, "output_layer") and model.output_layer is not None and model.output_layer.weight is not None: output_weight = model.output_layer.weight else: # When embeddings are tied, use the embedding weight output_weight = model.embedding.word_embeddings.weight logprobs, entropy = linear_cross_entropy( hidden_states, output_weight, labels, temperature, "none", parallel_state.get_tensor_model_parallel_group(), ) if has_config_logger_enabled(model.config): payload = OrderedDict( { "input_ids": input_ids, "position_ids": position_ids, "attention_mask": attention_mask, "decoder_input": decoder_input, "logprobs": logprobs, "entropy": entropy, } ) log_config_to_disk(model.config, payload, prefix="input_and_logits") output.entropy = entropy output.log_probs = logprobs return output
verl__models__mcore__model_forward_fused.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # use mcore transformer config to initialize the model import inspect from abc import ABC, abstractmethod from megatron.core.models.gpt.gpt_layer_specs import get_gpt_decoder_block_spec, get_gpt_mtp_block_spec from megatron.core.models.gpt.gpt_model import GPTModel from .config_converter import PretrainedConfig, TransformerConfig class BaseModelInitializer(ABC): """Base class for model initializers.""" def __init__(self, tfconfig: TransformerConfig, hf_config: PretrainedConfig): self.tfconfig = tfconfig self.hf_config = hf_config self.has_vp_stage = inspect.signature(get_gpt_decoder_block_spec).parameters.get("vp_stage", None) is not None @abstractmethod def get_transformer_layer_spec(self, vp_stage=None): """Get the transformer layer specification. https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/models/gpt/gpt_layer_specs.py""" pass def get_rope_scaling_args(self) -> dict: """Get rope scaling args.""" rope_scaling_args = {} if "rope_scaling" in self.hf_config: if self.hf_config.rope_scaling is not None: # assert self.hf_config.rope_scaling["type"] == "linear", "only linear scaling is supported for now" rope_scaling_args["seq_len_interpolation_factor"] = self.hf_config.rope_scaling["factor"] return rope_scaling_args def initialize( self, pre_process: bool = True, post_process: bool = True, share_embeddings_and_output_weights: bool = False, value: bool = False, **extra_kwargs, ) -> GPTModel: """Initialize a GPT model with the given configuration. https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/models/gpt/gpt_model.py Args: pre_process (bool): include embedding layer. post_process (bool): including an output layer. share_embeddings_and_output_weights (bool): input embeddings and output logit weights are shared. value (bool): add an extra linear layer for classification or regression. Returns: GPTModel: An initialized GPT model instance """ vp_stage = extra_kwargs.get("vp_stage", None) transformer_layer_spec = self.get_transformer_layer_spec(vp_stage=vp_stage) rope_scaling_args = self.get_rope_scaling_args() mtp_block_spec = extra_kwargs.get("mtp_block_spec", None) model = GPTModel( config=self.tfconfig, transformer_layer_spec=transformer_layer_spec, vocab_size=self.hf_config.vocab_size, max_sequence_length=self.hf_config.max_position_embeddings, pre_process=pre_process, post_process=post_process, share_embeddings_and_output_weights=share_embeddings_and_output_weights, position_embedding_type="rope", rotary_base=self.hf_config.rope_theta, **rope_scaling_args, mtp_block_spec=mtp_block_spec, **({} if not self.has_vp_stage else {"vp_stage": vp_stage}), ) if post_process and value: from verl.models.llama.megatron.layers.parallel_linear import LinearForLastLayer model.output_layer = LinearForLastLayer( input_size=self.tfconfig.hidden_size, output_size=1, config=self.tfconfig ) return model class DenseModel(BaseModelInitializer): """Initializer for dense models like Llama and Qwen2.""" def get_transformer_layer_spec(self, vp_stage=None): assert self.tfconfig.normalization == "RMSNorm", "only RMSNorm is supported for now" extra_kwargs = {} if not self.has_vp_stage else {"vp_stage": vp_stage} return get_gpt_decoder_block_spec(self.tfconfig, use_transformer_engine=True, **extra_kwargs) class Qwen2MoEModel(BaseModelInitializer): """Initializer for Qwen2 MoE models.""" def get_transformer_layer_spec(self, vp_stage=None): assert self.tfconfig.normalization == "RMSNorm", "only RMSNorm is supported for now" extra_kwargs = {} if not self.has_vp_stage else {"vp_stage": vp_stage} transformer_layer_spec = get_gpt_decoder_block_spec(self.tfconfig, use_transformer_engine=True, **extra_kwargs) # Patch layer spec for shared experts for i in range(len(transformer_layer_spec.layer_specs)): transformer_layer_spec.layer_specs[i].submodules.mlp.submodules.shared_experts.params["gate"] = True return transformer_layer_spec def initialize(self, **kwargs): # Qwen default freeze_moe_router: true model = super().initialize(**kwargs) freeze_moe_router = kwargs.get("freeze_moe_router", True) if freeze_moe_router: for layer in model.decoder.layers: layer.mlp.router.weight.requires_grad = False return model class MixtralModel(BaseModelInitializer): """Initializer for Mixtral models.""" def get_transformer_layer_spec(self, vp_stage=None): assert self.tfconfig.normalization == "RMSNorm", "only RMSNorm is supported for now" extra_kwargs = {} if not self.has_vp_stage else {"vp_stage": vp_stage} transformer_layer_spec = get_gpt_decoder_block_spec(self.tfconfig, use_transformer_engine=True, **extra_kwargs) return transformer_layer_spec def initialize(self, **kwargs): model = super().initialize(**kwargs) freeze_moe_router = kwargs.get("freeze_moe_router", False) if freeze_moe_router: for layer in model.decoder.layers: layer.mlp.router.weight.requires_grad = False return model class Qwen3MoEModel(BaseModelInitializer): """Initializer for Qwen3 MoE models.""" def get_transformer_layer_spec(self, vp_stage=None): assert self.tfconfig.normalization == "RMSNorm", "only RMSNorm is supported for now" extra_kwargs = {} if not self.has_vp_stage else {"vp_stage": vp_stage} transformer_layer_spec = get_gpt_decoder_block_spec(self.tfconfig, use_transformer_engine=True, **extra_kwargs) return transformer_layer_spec def initialize(self, **kwargs): # Qwen default freeze_moe_router: true model = super().initialize(**kwargs) freeze_moe_router = kwargs.get("freeze_moe_router", True) if freeze_moe_router: for layer in model.decoder.layers: layer.mlp.router.weight.requires_grad = False return model class DeepseekV3Model(BaseModelInitializer): """Initializer for DeepseekV3 models.""" def get_transformer_layer_spec(self, vp_stage=None): extra_kwargs = {} if not self.has_vp_stage else {"vp_stage": vp_stage} transformer_layer_spec = get_gpt_decoder_block_spec(self.tfconfig, use_transformer_engine=True, **extra_kwargs) return transformer_layer_spec def get_rope_scaling_args(self) -> dict: """Get rope scaling args.""" rope_scaling_args = {} return rope_scaling_args def initialize( self, **kwargs, ): vp_stage = kwargs.get("vp_stage", None) freeze_moe_router = kwargs.get("freeze_moe_router", True) if freeze_moe_router: self.tfconfig.moe_router_load_balancing_type = "none" # MTP if self.tfconfig.mtp_num_layers is not None and self.tfconfig.mtp_num_layers > 0: transformer_layer_spec = self.get_transformer_layer_spec(vp_stage=vp_stage) mtp_block_spec = get_gpt_mtp_block_spec( self.tfconfig, transformer_layer_spec, use_transformer_engine=True, vp_stage=vp_stage ) kwargs["mtp_block_spec"] = mtp_block_spec model = super().initialize(**kwargs) if freeze_moe_router: for layer in model.decoder.layers: if hasattr(layer.mlp, "router"): layer.mlp.router.weight.requires_grad = False return model class Qwen25VLModel(BaseModelInitializer): """Initializer for Qwen2.5 VL models.""" def get_transformer_layer_spec(self, vp_stage=None): extra_kwargs = {} if not self.has_vp_stage else {"vp_stage": vp_stage} transformer_layer_spec = get_gpt_decoder_block_spec(self.tfconfig, use_transformer_engine=True, **extra_kwargs) return transformer_layer_spec def initialize( self, pre_process=None, post_process=None, share_embeddings_and_output_weights=False, value=False, **extra_kwargs, ): tfconfig = self.tfconfig hf_config = self.hf_config # Qwen2_5_VLForConditionalGeneration from copy import deepcopy transformer_layer_spec = self.get_transformer_layer_spec() from megatron.core.extensions.transformer_engine import TEColumnParallelLinear, TERowParallelLinear from megatron.core.models.gpt.moe_module_specs import MLPSubmodules from megatron.core.models.vision.vit_layer_specs import get_vit_layer_with_transformer_engine_spec from .qwen2_5_vl import Qwen2_5VLModel, get_vision_model_config, get_vision_projection_config vision_transformer_config = get_vision_model_config(deepcopy(tfconfig)) vision_transformer_config.pipeline_model_parallel_size = 1 vision_transformer_config.first_pipeline_num_layers = None vision_projection_config = get_vision_projection_config( deepcopy(tfconfig), vision_transformer_config.hidden_size, spatial_merge_size=hf_config.vision_config.spatial_merge_size, ) vision_projection_layer_spec = MLPSubmodules( linear_fc1=TEColumnParallelLinear, linear_fc2=TERowParallelLinear, ) vision_transformer_layer_spec = get_vit_layer_with_transformer_engine_spec() qwen25_vl_model = Qwen2_5VLModel( language_transformer_config=tfconfig, language_transformer_layer_spec=transformer_layer_spec, language_vocab_size=hf_config.vocab_size, language_max_sequence_length=hf_config.max_position_embeddings, vision_transformer_config=vision_transformer_config, vision_transformer_layer_spec=vision_transformer_layer_spec, vision_projection_config=vision_projection_config, vision_projection_layer_spec=vision_projection_layer_spec, vision_projection_type="mlp", language_rotary_base=hf_config.rope_theta, pre_process=pre_process, post_process=post_process, add_decoder=True, add_encoder=True, parallel_output=True, language_share_embeddings_and_output_weights=share_embeddings_and_output_weights, ) if post_process and value: from verl.models.llama.megatron.layers.parallel_linear import LinearForLastLayer qwen25_vl_model.language_model.output_layer = LinearForLastLayer( input_size=tfconfig.hidden_size, output_size=1, config=tfconfig ) return qwen25_vl_model
verl__models__mcore__model_initializer.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Callable import torch from megatron.core import parallel_state from megatron.core.models.gpt.gpt_model import GPTModel from megatron.core.transformer.multi_token_prediction import ( MTPLossAutoScaler, MTPLossLoggingHelper, roll_tensor, ) try: from megatron.core.utils import unwrap_model except ImportError: from verl.utils.megatron_utils import unwrap_model def _get_patching_model(model: torch.nn.Module): model = unwrap_model(model) if isinstance(model, GPTModel): return model if not (hasattr(model, "language_model") and isinstance(model.language_model, GPTModel)): print(f"Model {model.__class__.__name__} is not a supported for fused forward") return None return model.language_model def patch_postprocess(model: torch.nn.Module): model = _get_patching_model(model) if model is not None: model._postprocess_backup = model._postprocess model._postprocess = _megatron_gptmodel_postprocess.__get__(model, model.__class__) def unpatch_postprocess(model: torch.nn.Module): model = _get_patching_model(model) if model is not None: model._postprocess = model._postprocess_backup # copy from https://github.com/NVIDIA/Megatron-LM/blob/23e092f41ec8bc659020e401ddac9576c1cfed7e/megatron/core/models/gpt/gpt_model.py # patch the postprocess method of GPTModel to support advanced features like MTP, 1f1b overlap, etc. def _megatron_gptmodel_postprocess( self, hidden_states, input_ids, position_ids, labels, rotary_pos_emb, rotary_pos_cos, rotary_pos_sin, mtp_in_postprocess=None, loss_mask=None, decoder_input=None, attention_mask=None, inference_params=None, packed_seq_params=None, sequence_len_offset=None, runtime_gather_output=None, extra_block_kwargs=None, inference_context=None, ): """Postprocesses decoder hidden states to generate logits or compute loss. Applies Multi-Token Prediction if enabled, generates output logits through the output layer, and computes language model loss when labels are provided. """ # logits and loss output_weight = None if self.share_embeddings_and_output_weights: output_weight = self.shared_embedding_or_output_weight() if mtp_in_postprocess and labels is not None: hidden_states = self.mtp( input_ids=input_ids, position_ids=position_ids, hidden_states=hidden_states, attention_mask=attention_mask, inference_params=inference_params, rotary_pos_emb=rotary_pos_emb, rotary_pos_cos=rotary_pos_cos, rotary_pos_sin=rotary_pos_sin, packed_seq_params=packed_seq_params, sequence_len_offset=sequence_len_offset, embedding=self.embedding, **(extra_block_kwargs or {}), ) if not self.post_process: return hidden_states # Skip when mtp_num_layers is None or 0 if self.config.mtp_num_layers and labels is not None: mtp_labels = labels.clone() hidden_states_list = torch.chunk(hidden_states, 1 + self.config.mtp_num_layers, dim=0) hidden_states = hidden_states_list[0] if loss_mask is None: # if loss_mask is not provided, use all ones as loss_mask loss_mask = torch.ones_like(mtp_labels) for mtp_layer_number in range(self.config.mtp_num_layers): # Calc loss for the current Multi-Token Prediction (MTP) layers. mtp_labels, _ = roll_tensor( mtp_labels, shifts=-1, dims=-1, cp_group=self.cp_group, packed_seq_params=packed_seq_params, ) loss_mask, num_tokens = roll_tensor( loss_mask, shifts=-1, dims=-1, cp_group=self.cp_group, packed_seq_params=packed_seq_params, ) # Compute mtp loss without storing logits to save memory. mtp_loss = self.compute_output_layer_and_language_model_loss( hidden_states_list[mtp_layer_number + 1], labels=mtp_labels, weight=self.shared_embedding_or_output_weight(), sequence_parallel_enabled=self.output_layer.sequence_parallel, column_parallel_linear=self.output_layer, col_linear_kwargs={ "weight": output_weight, "runtime_gather_output": runtime_gather_output, }, ) mtp_loss = loss_mask * mtp_loss if self.training: # TODO(shifangx): remove the use of parallel_state here # after moving loss logging to loss_func in pretrain_gpt.py MTPLossLoggingHelper.save_loss_to_tracker( torch.sum(mtp_loss) / num_tokens, mtp_layer_number, self.config.mtp_num_layers, avg_group=parallel_state.get_data_parallel_group(with_context_parallel=True), ) mtp_loss_scale = self.config.mtp_loss_scaling_factor / self.config.mtp_num_layers if self.config.calculate_per_token_loss: hidden_states = MTPLossAutoScaler.apply(hidden_states, mtp_loss_scale * mtp_loss) else: hidden_states = MTPLossAutoScaler.apply(hidden_states, mtp_loss_scale * mtp_loss / num_tokens) logits, _ = self.output_layer(hidden_states, weight=output_weight, runtime_gather_output=runtime_gather_output) # [s b h] => [b s h] return logits.transpose(0, 1).contiguous() def patch_mtp_layer_get_embeddings(model: torch.nn.Module): """Patch the _get_embeddings method of MultiTokenPredictionLayer""" from megatron.core.models.gpt.gpt_model import GPTModel from megatron.core.transformer.multi_token_prediction import MultiTokenPredictionLayer # Unwrap each model in the actor_module to get the actual GPTModel model = _get_patching_model(model) # Collect all MultiTokenPredictionLayer instances target_layers = [] if isinstance(model, GPTModel): # Check if GPTModel has MTP and find the layers if hasattr(model, "mtp") and hasattr(model.mtp, "layers"): for layer in model.mtp.layers: if isinstance(layer, MultiTokenPredictionLayer): target_layers.append(layer) elif hasattr(model, "layers"): # Check if any layer in the model is MultiTokenPredictionLayer for layer in model.layers: if isinstance(layer, MultiTokenPredictionLayer): target_layers.append(layer) if target_layers: for layer in target_layers: layer._get_embeddings_backup = layer._get_embeddings layer._get_embeddings = _patched_get_embeddings_for_detach.__get__(layer, layer.__class__) print(f"Found and patched {len(target_layers)} MTP layer(s) in any of the actor modules") return True else: print("No MTP layers found to patch in any of the actor modules") return False def unpatch_mtp_layer_get_embeddings(model: torch.nn.Module): """Unpatch the _get_embeddings method of MultiTokenPredictionLayer""" from megatron.core.models.gpt.gpt_model import GPTModel from megatron.core.transformer.multi_token_prediction import MultiTokenPredictionLayer # Unwrap each model in the actor_module to get the actual GPTModel model = _get_patching_model(model) # Collect all MultiTokenPredictionLayer instances target_layers = [] if isinstance(model, GPTModel): # Check if GPTModel has MTP and find the layers if hasattr(model, "mtp") and hasattr(model.mtp, "layers"): for layer in model.mtp.layers: if isinstance(layer, MultiTokenPredictionLayer): target_layers.append(layer) elif hasattr(model, "layers"): # Check if any layer in the model is MultiTokenPredictionLayer for layer in model.layers: if isinstance(layer, MultiTokenPredictionLayer): target_layers.append(layer) unpatched_count = 0 for layer in target_layers: if hasattr(layer, "_get_embeddings_backup"): layer._get_embeddings = layer._get_embeddings_backup delattr(layer, "_get_embeddings_backup") unpatched_count += 1 if unpatched_count > 0: print(f"Unpatched {unpatched_count} MTP layer(s)") return True return False def _patched_get_embeddings_for_detach( self, input_ids: torch.Tensor, position_ids: torch.Tensor, embedding: Callable, hidden_states: torch.Tensor, packed_seq_params=None, ): """ Patched version of _get_embeddings method for MultiTokenPredictionLayer. This is a modified version that you can customize according to your needs. The original implementation is preserved below with modifications. """ # You can modify the logic here as needed # For example, you could: # - Change the shift amount in roll_tensor # - Apply custom transformations to input_ids or position_ids # - Add debugging information # - Modify the embedding computation # Original logic with custom modifications from megatron.core.transformer.multi_token_prediction import roll_tensor from megatron.core.utils import make_viewless_tensor # Calc logits for the current Multi-Token Prediction (MTP) layers. input_ids, _ = roll_tensor( input_ids, shifts=-1, # You can modify this shift value dims=-1, cp_group=self.cp_group, packed_seq_params=packed_seq_params, ) position_ids, _ = roll_tensor( position_ids, shifts=-1, # You can modify this shift value dims=-1, cp_group=self.cp_group, packed_seq_params=packed_seq_params, ) # embedding computation - you can modify this part decoder_input = embedding(input_ids=input_ids, position_ids=position_ids) # Apply custom transformations if needed # For example: decoder_input = some_custom_function(decoder_input) hidden_states = make_viewless_tensor(inp=hidden_states, requires_grad=True, keep_graph=True) # detach decoder_input and hidden_states decoder_input = decoder_input.detach() hidden_states = hidden_states.detach() return input_ids, position_ids, decoder_input, hidden_states
verl__models__mcore__mtp_patch.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # there is some bug in mcore 0.12, so we need to patch it # 1. `get_query_key_value_tensors` in `multi_latent_attention.py` works wrong when packed_seq_params is not None def apply_patch(): import megatron.core import torch import torch.nn.functional as F from megatron.core import parallel_state, tensor_parallel from megatron.core.transformer.multi_latent_attention import ( MLASelfAttention, MultiLatentAttention, apply_rotary_pos_emb, deprecate_inference_params, gather_from_sequence_parallel_region, gather_from_tensor_model_parallel_region, scatter_to_sequence_parallel_region, ) from packaging import version mcore_ge_013 = version.parse(megatron.core.__version__) >= version.parse("0.13.0") def patch_get_query_key_value_tensors( self, hidden_states, key_value_states=None, position_ids=None, packed_seq_params=None, inference_context=None, *, inference_params=None, ): """ Derives `query`, `key` and `value` tensors from `hidden_states`. """ # s = sequence length, b = batch size, h = hidden size, n = num attention heads # Attention heads [s, b, n*h] assert hidden_states.ndim == 3, f"hidden_states should be 3D, [s, b, n*h], got {hidden_states.ndim}D" inference_context = deprecate_inference_params(inference_context, inference_params) # ========================================= # Prepare RoPE and seqlen related params # ========================================= rotary_seq_len = self.rotary_pos_emb.get_rotary_seq_len( inference_context, None, hidden_states, self.config, packed_seq_params ) # rotary_pos_emb:[s, b, 1, 64] mscale = 1.0 if self.config.rope_type == "rope": packed_seq = packed_seq_params is not None and packed_seq_params.qkv_format == "thd" try: # In case of TypeError: RotaryEmbedding.forward() got an unexpected keyword argument 'packed_seq' rotary_pos_emb = self.rotary_pos_emb(rotary_seq_len, packed_seq=packed_seq) except TypeError: rotary_pos_emb = self.rotary_pos_emb(rotary_seq_len) else: rotary_pos_emb, mscale = self.rotary_pos_emb(rotary_seq_len) # ========================================= # QKV down projection and layernorm # ========================================= if self.config.q_lora_rank is not None: # if linear_q_down_proj is ColumnParallelLinear: # q_compressed: [s, b, q_lora_rank / TP] # elif linear_q_down_proj is Linear: # q_compressed: [s / TP, b, q_lora_rank] q_compressed, _ = self.linear_q_down_proj(hidden_states) # When output is sharded (ColumnParallelLinear), two things are needed to be # identical to a normal Linear. # 1. Manually gather output to restore output dim q_lora_rank; # 2. Scatter sequence back to s / TP if sequence-parallel since it was # gathered by ColumnParallelLinear. if q_compressed.size(-1) != self.config.q_lora_rank: q_compressed = gather_from_tensor_model_parallel_region(q_compressed) if self.config.sequence_parallel: q_compressed = scatter_to_sequence_parallel_region(q_compressed) q_compressed = self.q_layernorm(q_compressed) else: q_compressed = hidden_states # if linear_kv_down_proj is ColumnParallelLinear: # kv_combined: [s, b, (kv_lora_rank + qk_pos_emb_head_dim) / TP] # elif linear_kv_down_proj is Linear: # kv_combined: [s / TP, b, (kv_lora_rank + qk_pos_emb_head_dim)] kv_combined, _ = self.linear_kv_down_proj(hidden_states) if kv_combined.size(-1) != self.config.kv_lora_rank + self.config.qk_pos_emb_head_dim: # kv_combined: [s, b, (kv_lora_rank + qk_pos_emb_head_dim)] kv_combined = gather_from_tensor_model_parallel_region(kv_combined) # kv_compressed:[s, b, kv_lora_rank], k_pos_emb: [s, b, qk_pos_emb_head_dim] kv_compressed, k_pos_emb = torch.split( kv_combined, [self.config.kv_lora_rank, self.config.qk_pos_emb_head_dim], dim=-1 ) if self.config.sequence_parallel: # kv_compressed:[s / TP, b, kv_lora_rank] kv_compressed = scatter_to_sequence_parallel_region(kv_compressed) else: # kv_compressed:[s / TP, b, kv_lora_rank], k_pos_emb: [s / TP, b, qk_pos_emb_head_dim] kv_compressed, k_pos_emb = torch.split( kv_combined, [self.config.kv_lora_rank, self.config.qk_pos_emb_head_dim], dim=-1 ) if parallel_state.get_tensor_model_parallel_world_size() > 1: # k_pos_emb: [s, b, qk_pos_emb_head_dim] k_pos_emb = gather_from_sequence_parallel_region(k_pos_emb) kv_compressed = self.kv_layernorm(kv_compressed) # ========================================= # QKV up projection and RoPE apply # ========================================= def qkv_up_proj_and_rope_apply(q_compressed, kv_compressed, k_pos_emb, rotary_pos_emb): if self.config.q_lora_rank is not None: q, _ = self.linear_q_up_proj(q_compressed) else: # hidden_states:[s, b, 2048], q: [s, b, n * 192] q, _ = self.linear_q_proj(q_compressed) q_len, bsz, _ = q.size() # q: [s, b, n, 192] q = q.view(q_len, bsz, self.num_attention_heads_per_partition, self.q_head_dim) # kv: [s, b, 2048] kv, _ = self.linear_kv_up_proj(kv_compressed) # kv: [s, b, n, 256] kv = kv.view( q_len, bsz, self.num_attention_heads_per_partition, self.config.qk_head_dim + self.config.v_head_dim, ) cp_size = parallel_state.get_context_parallel_world_size() if inference_context is not None: # add offset to the sequence start for inference sequence_start = inference_context.sequence_len_offset sequence_end = sequence_start + q_len rotary_pos_emb = rotary_pos_emb[sequence_start:sequence_end] elif packed_seq_params is None or cp_size == 1: # Shorten rotary_pos_emb to the sequence length when inference_params # is not provided. This makes sure we can run forward directly with # any sequence length. During training, the sequence length is always # the full rotary_pos_emb length, except for sequence packing + CP. # When sequence packing and context parallel are both enabled, the # position embedding will not split rotary_pos_emb, so it may exceed # the sequence length on this CP rank, but we need the full rotary_pos_emb # to cover the full sequence, so we do not shorten it here. rotary_pos_emb = rotary_pos_emb[0:q_len] # [s, b, 64] -> [s, b, 1, 64] k_pos_emb = torch.unsqueeze(k_pos_emb, 2) # q: [s, b, n, 128], q_pos_emb: [s, b, n, 64] q_no_pe, q_pos_emb = torch.split(q, [self.config.qk_head_dim, self.config.qk_pos_emb_head_dim], dim=-1) # k_no_pe: [s, b, n, 128], value: [s, b, n, 128] k_no_pe, value = torch.split(kv, [self.config.qk_head_dim, self.config.v_head_dim], dim=-1) if packed_seq_params is not None: cu_seqlens_q = packed_seq_params.cu_seqlens_q cu_seqlens_kv = packed_seq_params.cu_seqlens_kv q_pos_emb = q_pos_emb.squeeze(1) k_pos_emb = k_pos_emb.squeeze(1) q_no_pe = q_no_pe.squeeze(1) k_no_pe = k_no_pe.squeeze(1) value = value.squeeze(1) else: cu_seqlens_q = cu_seqlens_kv = None # q_pos_emb: [s, b, n, 64], k_pos_emb:[s, b, 1, 64] q_pos_emb = apply_rotary_pos_emb( q_pos_emb, rotary_pos_emb, config=self.config, cu_seqlens=cu_seqlens_q, mscale=mscale, ) k_pos_emb = apply_rotary_pos_emb( k_pos_emb, rotary_pos_emb, config=self.config, cu_seqlens=cu_seqlens_kv, mscale=mscale, ) # query: [s, b, n, 192] query = torch.cat([q_no_pe, q_pos_emb], dim=-1) if packed_seq_params is not None: k_pos_emb = k_pos_emb.expand(-1, self.num_attention_heads_per_partition, -1) key = torch.cat([k_no_pe, k_pos_emb], dim=-1) else: # key: [s, b, n, 192] k_pos_emb = k_pos_emb.expand(-1, -1, self.num_attention_heads_per_partition, -1) key = torch.cat([k_no_pe, k_pos_emb], dim=-1) query = query.contiguous() key = key.contiguous() value = value.contiguous() return query, key, value if self.recompute_up_proj: self.qkv_up_checkpoint = tensor_parallel.CheckpointWithoutOutput() query, key, value = self.qkv_up_checkpoint.checkpoint( qkv_up_proj_and_rope_apply, q_compressed, kv_compressed, k_pos_emb, rotary_pos_emb ) else: query, key, value = qkv_up_proj_and_rope_apply(q_compressed, kv_compressed, k_pos_emb, rotary_pos_emb) return query, key, value def patch_forward( self, hidden_states, attention_mask, key_value_states=None, inference_context=None, rotary_pos_emb=None, rotary_pos_cos=None, rotary_pos_sin=None, attention_bias=None, packed_seq_params=None, position_ids=None, sequence_len_offset=None, *, inference_params=None, **kwargs, ): """Forward pass for multi-latent attention""" assert attention_bias is None, "Attention bias should not be passed into MLA." assert rotary_pos_cos is None and rotary_pos_sin is None, "MLA does not support Flash Decoding" # hidden_states: [sq, b, h] inference_context = deprecate_inference_params(inference_context, inference_params) # ===================== # Query, Key, and Value # ===================== # Get the query, key and value tensors based on the type of attention - # self or cross attn. # query: [96, 1, 16, 128], key:[96, 1, 16, 128], value:[96, 1, 16, 128] query, key, value = self.get_query_key_value_tensors( hidden_states, key_value_states, position_ids, packed_seq_params, inference_context=inference_context, ) # =================================================== # Adjust key, value for inference # =================================================== # rotary_pos_emb = None if mcore_ge_013: query, key, value, _, attn_mask_type, _ = self._adjust_key_value_for_inference( inference_context, query, key, value, rotary_pos_emb=None ) else: query, key, value, _, attn_mask_type = self._adjust_key_value_for_inference( inference_context, query, key, value, rotary_pos_emb=None ) # TODO: Currently, TE can only accept contiguous tensors for MLA query = query.contiguous() key = key.contiguous() value = value.contiguous() # ================================== # core attention computation # ================================== # Need corresponding TE change thd_qkv_format = packed_seq_params and packed_seq_params.qkv_format == "thd" v_dim = value.shape[-1] if thd_qkv_format and query.shape[-1] != v_dim: value = F.pad(value, [0, query.shape[-1] - v_dim]) self.core_attention.hidden_size_per_attention_head_v = value.shape[-1] if self.checkpoint_core_attention and self.training: core_attn_out = self._checkpointed_attention_forward( query, key, value, attention_mask, packed_seq_params=packed_seq_params ) else: core_attn_out = self.core_attention( query, key, value, attention_mask, packed_seq_params=packed_seq_params, attn_mask_type=attn_mask_type, ) if thd_qkv_format: if core_attn_out.ndim == 2: core_attn_out = core_attn_out.reshape(*core_attn_out.shape[:-1], -1, value.shape[-1]) if query.shape[-1] != v_dim: core_attn_out = core_attn_out[..., :v_dim] # reshape to same output shape as unpacked case # (t, np, hn) -> (t, b=1, h=np*hn) # t is the pack size = sum (sq_i) # note that batch is a dummy dimension in the packed case core_attn_out = core_attn_out.reshape(core_attn_out.size(0), 1, -1) if self.recompute_up_proj: assert self.qkv_up_checkpoint is not None self.qkv_up_checkpoint.discard_output_and_register_recompute(core_attn_out) self.qkv_up_checkpoint = None # ================= # Output. [sq, b, h] # ================= output, bias = self.linear_proj(core_attn_out) return output, bias MLASelfAttention.get_query_key_value_tensors = patch_get_query_key_value_tensors MultiLatentAttention.forward = patch_forward def apply_patch_mbridge(): try: from megatron.core.utils import get_tensor_model_parallel_group_if_none except ImportError: import warnings import megatron.core.utils import torch from megatron.core import parallel_state def get_tensor_model_parallel_group_if_none(tp_group, is_expert=False, check_initialized=True): """Issue a deprecation warning if tp_group is None and return the default tp group.""" if not torch.distributed.is_initialized(): return None if tp_group is None: if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0: warnings.warn( "Warning: tp_group is None, using default tp group. Passing tp_group will be mandatory soon", DeprecationWarning, stacklevel=2, ) if is_expert: tp_group = parallel_state.get_expert_tensor_parallel_group(check_initialized=check_initialized) else: tp_group = parallel_state.get_tensor_model_parallel_group(check_initialized=check_initialized) return tp_group megatron.core.utils.get_tensor_model_parallel_group_if_none = get_tensor_model_parallel_group_if_none
verl__models__mcore__patch.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2024 Alibaba PAI Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from megatron.core.transformer.attention import * from .rope_utils import apply_rotary_pos_emb_absolute class Qwen2_5VLSelfAttention(SelfAttention): """ Overrides the SelfAttention class, the difference is that qwen2_5_vl uses apply_rotary_pos_emb_absolute instead of apply_rotary_pos_emb """ def forward( self, hidden_states: Tensor, attention_mask: Tensor, key_value_states: Optional[Tensor] = None, inference_context: Optional[BaseInferenceContext] = None, rotary_pos_emb: Optional[Union[Tensor, Tuple[Tensor, Tensor]]] = None, rotary_pos_cos: Optional[Tensor] = None, rotary_pos_sin: Optional[Tensor] = None, attention_bias: Optional[Tensor] = None, packed_seq_params: Optional[PackedSeqParams] = None, sequence_len_offset: Optional[int] = None, *, inference_params: Optional[BaseInferenceContext] = None, rotary_pos_cos_sin: Optional[Tensor] = None, ) -> Tuple[Tensor, Tensor]: """ Perform a forward pass through the attention module. Args: hidden_states (Tensor): Hidden states. attention_mask (Tensor): Attention mask. key_value_states (Optional[Tensor]): Key/value states (for cross attention). inference_context (Optional[BaseInferenceContext]): Inference context that manages KV cache. rotary_pos_emb (Optional[Union[Tensor, Tuple[Tensor, Tensor]]]): Rotary embedding tensor(s). rotary_pos_cos (Optional[Tensor]): Rotary embedding cosine. rotary_pos_sin (Optional[Tensor]): Rotary embedding sine. attention_bias (Optional[Tensor]): Attention bias. packed_seq_params (Optional[PackedSeqparams]): Parameters used for THD format. sequence_len_offset (Optional[int]): Sequence length offset used for inference CUDA graphs. Return: (Tuple[Tensor, Tensor]) Attention output and bias. """ inference_context = deprecate_inference_params(inference_context, inference_params) if inference_context and inference_context.is_dynamic_batching(): assert flash_decode_and_prefill_kernel is not None, ( "Internal use only: install package `nvidia_chunked_flash_attn`." ) # hidden_states: [sq, b, h] if self.config.flash_decode and not self.training and inference_context is not None: rotary_pos_emb = None else: assert rotary_pos_cos is None and rotary_pos_sin is None # For self attention we just duplicate the rotary_pos_emb if it isn't already if rotary_pos_emb is not None and not isinstance(rotary_pos_emb, tuple): rotary_pos_emb = (rotary_pos_emb,) * 2 # ===================== # Query, Key, and Value # ===================== # Get the query, key and value tensors based on the type of attention - # self or cross attn. query, key, value = self.get_query_key_value_tensors(hidden_states, key_value_states) # =================================================== # Adjust key, value, and rotary_pos_emb for inference # =================================================== # This branch only runs in the decode phase of flash decoding and returns after the linear # projection. This conditional is not used in the prefill phase or non-flash-decoding cases. if ( self.config.flash_decode and inference_context is not None and inference_context.is_decode_only() and not self.training and rotary_pos_cos is not None ): assert self.layer_number in inference_context.key_value_memory_dict assert inference_context.sequence_len_offset is not None inference_key_memory, inference_value_memory = inference_context.key_value_memory_dict[self.layer_number] output = self.flash_decode( sequence_len_offset=sequence_len_offset, query_layer=query, key_layer=key, value_layer=value, inference_key_memory=inference_key_memory, inference_value_memory=inference_value_memory, rotary_cos=rotary_pos_cos, rotary_sin=rotary_pos_sin, ) out = output.transpose(0, 1).contiguous() context_layer = out.view(out.size(0), out.size(1), -1) output, bias = self.linear_proj(context_layer) return output, bias # Use latest mcore 0.13 API and forward-compatible with previous versions. outputs = self._adjust_key_value_for_inference( inference_context, query, key, value, rotary_pos_emb, rotary_pos_cos, rotary_pos_sin, sequence_len_offset, ) query, key, value, rotary_pos_emb, attn_mask_type = outputs[:5] if packed_seq_params is not None: query = query.squeeze(1) key = key.squeeze(1) value = value.squeeze(1) # ================================================ # relative positional embedding (rotary embedding) # ================================================ if rotary_pos_emb is not None and not self.config.flash_decode: q_pos_emb, k_pos_emb = rotary_pos_emb if packed_seq_params is not None: if packed_seq_params.cu_seqlens_q_padded is not None: cu_seqlens_q = packed_seq_params.cu_seqlens_q_padded else: cu_seqlens_q = packed_seq_params.cu_seqlens_q if packed_seq_params.cu_seqlens_kv_padded is not None: cu_seqlens_kv = packed_seq_params.cu_seqlens_kv_padded else: cu_seqlens_kv = packed_seq_params.cu_seqlens_kv else: cu_seqlens_q = cu_seqlens_kv = None if q_pos_emb is not None: # TODO VIJAY: simplify if inference_context is None or inference_context.is_static_batching(): query = apply_rotary_pos_emb_absolute(query, q_pos_emb, config=self.config, cu_seqlens=cu_seqlens_q) else: query = inference_context.apply_rotary_emb_query(query, q_pos_emb, self.config, cu_seqlens_q) if k_pos_emb is not None: key = apply_rotary_pos_emb_absolute(key, k_pos_emb, config=self.config, cu_seqlens=cu_seqlens_kv) # TODO, can apply positional embedding to value_layer so it has # absolute positional embedding. # otherwise, only relative positional embedding takes effect # value_layer = apply_rotary_pos_emb(value_layer, k_pos_emb) # ================================== # core attention computation # ================================== if self.checkpoint_core_attention and self.training: core_attn_out = self._checkpointed_attention_forward( query, key, value, attention_mask, attn_mask_type=attn_mask_type, attention_bias=attention_bias, packed_seq_params=packed_seq_params, ) else: if inference_context is None or inference_context.is_static_batching(): # Static batching attention kernel. core_attn_out = self.core_attention( query, key, value, attention_mask, attn_mask_type=attn_mask_type, attention_bias=attention_bias, packed_seq_params=packed_seq_params, ) else: # Dynamic batching attention kernel. q, k, v = (query, key, value) cu_query_lengths, max_seqlen_q = inference_context.cu_query_lengths() cu_kv_lengths, max_seqlen_k = inference_context.cu_kv_lengths() core_attn_out = self.flash_decode_and_prefill( q, k, v, max_seqlen_q, max_seqlen_k, cu_query_lengths, cu_kv_lengths ) core_attn_out = core_attn_out.squeeze(0).unsqueeze(1) core_attn_out = rearrange(core_attn_out, "s b h d -> s b (h d)") if packed_seq_params is not None and packed_seq_params.qkv_format == "thd": # reshape to same output shape as unpacked case # (t, np, hn) -> (t, b=1, h=np*hn) # t is the pack size = sum (sq_i) # note that batch is a dummy dimension in the packed case core_attn_out = core_attn_out.reshape(core_attn_out.size(0), 1, -1) # ================= # Output. [sq, b, h] # ================= output, bias = self.linear_proj(core_attn_out) return output, bias
verl__models__mcore__qwen2_5_vl__attention.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2024 Alibaba PAI Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import torch from megatron.core import InferenceParams, mpu, tensor_parallel from megatron.core.models.gpt.gpt_model import GPTModel # from .transformer_config import Qwen2VLTransformerConfig from megatron.core.packed_seq_params import PackedSeqParams from megatron.core.transformer import MegatronModule from megatron.core.transformer.spec_utils import ModuleSpec from megatron.core.transformer.transformer_config import TransformerConfig from verl.models.mcore.util import preprocess_packed_seqs from .attention import Qwen2_5VLSelfAttention from .vision_model import Qwen2_5VisionModel # Note: This is under development and may be missing features. class Qwen2_5VLModel(MegatronModule): """Qwen2.5VL multi-modal model. Args: language_transformer_config (TransformerConfig): Transformer config for the language model. language_transformer_layer_spec (ModuleSpec): Specifies module to use for transformer layers of the language model. language_vocab_size (int): Language model vocabulary size. language_max_sequence_length (int): Language model maximum sequence length. This is used for positional embedding. vision_transformer_config (TransformerConfig): Transformer config for the vision model. vision_transformer_layer_spec (ModuleSpec): Specifies module to use for transformer layers of the vision model. vision_projection_config (TransformerConfig): Config for the projection from vision model outputs to language model inputs. vision_projection_layer_spec (ModuleSpec): Specifies the module to use for the vision projection. vision_projection_type (str): Type of the vision projection to use. Default is a 2-layer MLP. parallel_output (bool): Do not gather the outputs, keep them split across tensor parallel ranks. This is typically True for training and False for inference. language_rotary_percent (float): Percent of rotary dimension to use for rotary position embeddings in the language model. Defaults to 1.0. pre_process (bool): Include the embedding layer in the gpt decoder (used with pipeline parallelism). Defaults to True. post_process (bool): Include an output layer and a layernorm in the gpt decoder (used with pipeline parallelism). Defaults to True. add_encoder (bool): Construct the encoder module (used with pipeline parallelism). Defaults to True. When we use pipelining, the encoder will live on only a subset of the pipeline stages (specifically, only the first stage). add_decoder (bool): Construct the decoder module (used with pipeline parallelism). Defaults to True. When we use pipelining, the decoder will live on only a subset of the pipeline stages (specifically, every stage after the first one). img_h (int): The height of each image that the ViT will see. img_w (int): The width of each image that the ViT will see. patch_dim (int): The size of each patch side. img_embedding_idx (int): Index in the language_embeddings tensor where image_embeddings should be inserted. Defaults to 0. """ def __init__( self, language_transformer_config: TransformerConfig, language_transformer_layer_spec: ModuleSpec, language_vocab_size: int, language_max_sequence_length: int, vision_transformer_config: TransformerConfig, vision_transformer_layer_spec: ModuleSpec, vision_projection_config: TransformerConfig, vision_projection_layer_spec: ModuleSpec, vision_projection_type: str = "mlp", parallel_output: bool = True, language_rotary_percent: float = 1.0, pre_process: bool = True, post_process: bool = True, add_encoder: bool = True, add_decoder: bool = True, language_rotary_base: int = 10000, fp16_lm_cross_entropy: bool = False, language_share_embeddings_and_output_weights: bool = False, image_token_id: int = 151655, video_token_id: int = 151656, ) -> None: super().__init__(config=language_transformer_config) # patch self_attention to use qwen2_5_vl attention vision_transformer_layer_spec.submodules.self_attention.module = Qwen2_5VLSelfAttention for layer_spec in language_transformer_layer_spec.layer_specs: layer_spec.submodules.self_attention.module = Qwen2_5VLSelfAttention logging.getLogger(__name__).warning("Qwen2VL model is under development and may be missing features.") self.pre_process = pre_process self.post_process = post_process self.add_encoder = add_encoder self.add_decoder = add_decoder self.encoder_hidden_state = None self.vision_model = None self.vision_projection = None self.language_model = None self.image_token_id = image_token_id self.video_token_id = video_token_id self.square_merge_size = vision_projection_config.ffn_hidden_size // vision_transformer_config.hidden_size # This attribute is needed to check if an all-reduce is required # on the word embeddings inside `finalize_model_grads._allreduce_word_embedding_grads`. self.share_embeddings_and_output_weights = False if self.pre_process: self.vision_model = Qwen2_5VisionModel( vision_transformer_config, vision_transformer_layer_spec, vision_projection_config, vision_projection_layer_spec, projection_type=vision_projection_type, pre_process=True, post_process=True, ) self.language_model = GPTModel( config=language_transformer_config, transformer_layer_spec=language_transformer_layer_spec, vocab_size=language_vocab_size, max_sequence_length=language_max_sequence_length, parallel_output=parallel_output, position_embedding_type="mrope", rotary_percent=language_rotary_percent, pre_process=self.pre_process, post_process=self.post_process, rotary_base=language_rotary_base, fp16_lm_cross_entropy=fp16_lm_cross_entropy, share_embeddings_and_output_weights=language_share_embeddings_and_output_weights, scatter_embedding_sequence_parallel=False, ) assert mpu.get_context_parallel_world_size() <= 1, "please use mbridge for qwen2_5_vl with context parallelism" self.share_embeddings_and_output_weights = self.language_model.share_embeddings_and_output_weights def shared_embedding_or_output_weight(self): """This is a convenience method to surface the language model's word embeddings, which is necessary for `finalize_model_grads._allreduce_word_embedding_grads`.""" if self.add_decoder: return self.language_model.shared_embedding_or_output_weight() return None def set_input_tensor(self, input_tensor) -> None: # This is usually handled in schedules.py but some inference code still # gives us non-lists or None if not isinstance(input_tensor, list): input_tensor = [input_tensor] assert len(input_tensor) == 1, "input_tensor should only be length 1 for Qwen2VL" if self.pre_process: self.encoder_hidden_state = input_tensor[0] else: self.language_model.set_input_tensor(input_tensor[0]) def freeze(self, freeze_language_model: bool, freeze_vision_model: bool, freeze_vision_projection: bool): """Freeze model modules. Make specific modules non-trainable by setting requires_grad to False for the module's parameters. Args: freeze_language_model (bool): Freeze the language model module. freeze_vision_model (bool): Freeze the vision model module. freeze_vision_projection (bool): Freeze the vision projection module. """ modules = [] if freeze_language_model and self.language_model is not None: modules.append(self.language_model) if freeze_vision_model and self.vision_model is not None: modules.append(self.vision_model) if freeze_vision_projection and self.vision_projection is not None: modules.append(self.vision_projection) for module in modules: for param in module.parameters(): param.requires_grad = False def forward( self, input_ids: torch.Tensor, position_ids: torch.Tensor, attention_mask: torch.Tensor = None, labels: torch.Tensor = None, inference_params: InferenceParams = None, packed_seq_params: PackedSeqParams = None, extra_block_kwargs: dict = None, pixel_values: torch.Tensor = None, pixel_values_videos: torch.Tensor = None, image_grid_thw: torch.Tensor = None, video_grid_thw: torch.Tensor = None, **kwargs, ) -> torch.Tensor: """Forward function of the Qwen2VL model. ### there is a workaround for supporting sequence packing with context parallelism # cp split with sequence packing will make model lose vision token information, so we need to keep # the original input_ids and pack them after vision embedding is calculated, # cooporate with verl's models/mcore/model_forward.py # pack the combined_embeddings to thd here, we check if packed_seq_params is None to determine if # we need to pack the combined_embeddings to thd # this function needs the position_ids and attention_mask in BSHD format, no matter use packed_seq or not Args: image_data (torch.Tensor): input image of shape [total_thw_size, n_features]. input_ids (torch.Tensor): input text ids [batch, text_seq_len]. position_ids (torch.Tensor): input text position ids [batch, text_seq_len]. attention_mask (torch.Tensor): attention mask for the language model [batch, 1, combined_seq_len, combined_seq_len]. labels (torch.Tensor): Optional target text labels [batch, combined_seq_len]. inference_params (InferenceParams): Inference-time parameters including KV cache. video_start_index: 0 -- all video len(video_seq) -- all image others -- mixture *_input_mask: should not be None in the first PP stage Returns: output (torch.Tensor): Loss of shape [b, s] if labels are provided, otherwise logits of shape [b, s, vocab_size]. """ video_start_index = 0 vision_grid_thw = None vision_data = None if image_grid_thw is not None: image_mask = input_ids == self.image_token_id vision_grid_thw = image_grid_thw vision_data = pixel_values video_start_index = image_mask.sum().item() if video_grid_thw is not None: video_mask = input_ids == self.video_token_id if vision_grid_thw is not None: vision_grid_thw = torch.cat([vision_grid_thw, video_grid_thw], dim=0) vision_data = torch.cat([vision_data, pixel_values_videos], dim=0) else: vision_grid_thw = video_grid_thw vision_data = pixel_values_videos use_inference_kv_cache = ( inference_params is not None and "image_tokens_count" in inference_params.key_value_memory_dict ) if use_inference_kv_cache: raise NotImplementedError() if self.pre_process: vision_embeds = None if vision_grid_thw is not None and vision_grid_thw.shape[0] > 0: vision_embeds = self.vision_model( vision_data=vision_data, # If None, vision model should use intermediate outputs (EPP > 1) grid_thw=vision_grid_thw, # should provided in each EPP stage ) # If running inference, the language model KV cache will be updated for image token positions. # Here we store the image tokens sequence length, which can be used as an offset to the KV cache later. if inference_params is not None: raise NotImplementedError() # inference_params.key_value_memory_dict["image_tokens_count"] = ( # vision_embeddings.shape[0] # ) # If running inference, we can skip image token computation if they were computed already earlier # for this sample. if use_inference_kv_cache: language_embeddings: torch.Tensor = self.language_model.embedding( input_ids=input_ids, position_ids=None, # NOTE: disable ) # [text_seq_len, b, h_language] # NOTE: why not cat here? is it the combined embeddings useless? combined_embeddings = language_embeddings elif vision_embeds is not None: if video_start_index == 0: image_embeds = None video_embeds = vision_embeds elif video_start_index == vision_embeds.shape[0]: image_embeds = vision_embeds video_embeds = None elif 0 < video_start_index < vision_embeds.shape[0]: image_embeds = vision_embeds[:video_start_index] video_embeds = vision_embeds[video_start_index:] else: raise ValueError( f"Expect video token start index in range [0, {vision_embeds.shape[0]}], but got " f"{video_start_index}" ) combined_embeddings = self.language_model.embedding( input_ids=input_ids, position_ids=None, # NOTE: disable ) # [text_seq_len, b, h_language] if image_embeds is not None or video_embeds is not None: combined_embeddings = combined_embeddings.transpose(0, 1).contiguous() if image_embeds is not None: image_mask = (input_ids == self.image_token_id).contiguous() if image_mask.sum() > 0: combined_embeddings = combined_embeddings.clone() combined_embeddings[image_mask] = image_embeds.to( dtype=combined_embeddings.dtype, device=combined_embeddings.device ) if video_embeds is not None: video_mask = (input_ids == self.video_token_id).contiguous() if video_mask.sum() > 0: combined_embeddings = combined_embeddings.clone() combined_embeddings[video_mask] = video_embeds.to( dtype=combined_embeddings.dtype, device=combined_embeddings.device ) combined_embeddings = combined_embeddings.transpose(0, 1).contiguous() else: combined_embeddings = self.language_model.embedding( input_ids=input_ids, position_ids=None, # NOTE: disable ) # [text_seq_len, b, h_language] if packed_seq_params is not None: combined_embeddings = ( preprocess_packed_seqs( combined_embeddings.transpose(0, 1).contiguous(), attention_mask, pre_process=True )[0] .transpose(0, 1) .contiguous() ) if self.config.sequence_parallel: combined_embeddings = tensor_parallel.scatter_to_sequence_parallel_region(combined_embeddings) combined_embeddings = combined_embeddings.contiguous() else: combined_embeddings = None from .rope_utils import get_rope_index # BSHD position_ids, _ = get_rope_index( input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, attention_mask=attention_mask, ) # THD if packed_seq_params is not None: position_ids = ( preprocess_packed_seqs(position_ids.permute(1, 2, 0), attention_mask, pre_process=True)[0] .permute(2, 0, 1) .contiguous() ) attention_mask = None output = self.language_model( input_ids=None, position_ids=position_ids, # None in encoder attention_mask=attention_mask, # None in encoder decoder_input=combined_embeddings, # only not None in the first decoder PP stage labels=labels, # only not None in the last decoder PP stage # inference_params=inference_params, # currently always None packed_seq_params=packed_seq_params, # currently always None **(extra_block_kwargs or {}), **kwargs, ) return output
verl__models__mcore__qwen2_5_vl__model.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2024 Alibaba PAI Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import logging from typing import Optional import torch from megatron.core.models.common.embeddings.rope_utils import * from megatron.core.models.common.embeddings.rope_utils import _apply_rotary_pos_emb_bshd from torch import Tensor logger = logging.getLogger(__name__) # Slightly modified from Qwen2VLForConditionalGeneration.get_rope_index def get_rope_index( input_ids: Optional[torch.LongTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, second_per_grid_ts: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, ): """ Calculate the 3D rope index based on image and video's temporal, height and width in LLM. Explanation: Each embedding sequence contains vision embedding and text embedding or just contains text embedding. For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs. Examples: input_ids: [T T T T T], here T is for text. temporal position_ids: [0, 1, 2, 3, 4] height position_ids: [0, 1, 2, 3, 4] width position_ids: [0, 1, 2, 3, 4] For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part and 1D rotary position embedding for text part. Examples: Temporal (Time): 3 patches, representing different segments of the video in time. Height: 2 patches, dividing each frame vertically. Width: 2 patches, dividing each frame horizontally. We also have some important parameters: fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second. tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity. temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames. interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100] vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] text temporal position_ids: [101, 102, 103, 104, 105] text height position_ids: [101, 102, 103, 104, 105] text width position_ids: [101, 102, 103, 104, 105] Here we calculate the text start position_ids as the max vision position_ids plus 1. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*): The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. Returns: position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`) mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`) """ spatial_merge_size = 2 tokens_per_second = 2 image_token_id = 151655 video_token_id = 151656 vision_start_token_id = 151652 mrope_position_deltas = [] if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): total_input_ids = input_ids if attention_mask is None: attention_mask = torch.ones_like(total_input_ids) position_ids = torch.ones( 3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device, ) image_index, video_index = 0, 0 attention_mask = attention_mask.to(total_input_ids.device) for i, input_ids in enumerate(total_input_ids): input_ids = input_ids[attention_mask[i] == 1] image_nums, video_nums = 0, 0 vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1) vision_tokens = input_ids[vision_start_indices + 1] image_nums = (vision_tokens == image_token_id).sum() video_nums = (vision_tokens == video_token_id).sum() input_tokens = input_ids.tolist() llm_pos_ids_list: list = [] st = 0 remain_images, remain_videos = image_nums, video_nums for _ in range(image_nums + video_nums): if image_token_id in input_tokens and remain_images > 0: ed_image = input_tokens.index(image_token_id, st) else: ed_image = len(input_tokens) + 1 if video_token_id in input_tokens and remain_videos > 0: ed_video = input_tokens.index(video_token_id, st) else: ed_video = len(input_tokens) + 1 if ed_image < ed_video: t, h, w = ( image_grid_thw[image_index][0], image_grid_thw[image_index][1], image_grid_thw[image_index][2], ) second_per_grid_t = 0 image_index += 1 remain_images -= 1 ed = ed_image else: t, h, w = ( video_grid_thw[video_index][0], video_grid_thw[video_index][1], video_grid_thw[video_index][2], ) if second_per_grid_ts is not None: second_per_grid_t = second_per_grid_ts[video_index] else: second_per_grid_t = 1.0 video_index += 1 remain_videos -= 1 ed = ed_video llm_grid_t, llm_grid_h, llm_grid_w = ( t.item(), h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) text_len = ed - st st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) range_tensor = torch.arange(llm_grid_t).view(-1, 1) expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w) time_tensor = expanded_range * second_per_grid_t * tokens_per_second time_tensor_long = time_tensor.long() t_index = time_tensor_long.flatten() h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) st = ed + llm_grid_t * llm_grid_h * llm_grid_w if st < len(input_tokens): st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 text_len = len(input_tokens) - st llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device) mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i])) mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1) return position_ids, mrope_position_deltas else: if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device) max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0] mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1] else: position_ids = ( torch.arange(input_ids.shape[1], device=input_ids.device) .view(1, 1, -1) .expand(3, input_ids.shape[0], -1) ) mrope_position_deltas = torch.zeros( [input_ids.shape[0], 1], device=input_ids.device, dtype=input_ids.dtype, ) return position_ids, mrope_position_deltas def apply_rotary_pos_emb_thd_absolute( t: Tensor, cu_seqlens: Tensor, freqs: Tensor, rotary_interleaved: bool = False ) -> Tensor: """A baseline implementation of applying RoPE for `thd` format. Args: t (Tensor): Input tensor T is of shape [t, h, d] cu_seqlens(Tensor): Cumulative sum of sequence lengths in a batch for `t`, with shape [b + 1] and dtype torch.int32. freqs (Tensor): Rotary Positional embedding tensor freq is of shape [max_s, 1, 1, d] Returns: Tensor: Shape [t, h, d]. The input tensor after applying RoPE. """ return _apply_rotary_pos_emb_bshd(t[:, None], freqs, rotary_interleaved=rotary_interleaved).squeeze(1) def apply_rotary_pos_emb_absolute( t: Tensor, freqs: Tensor, config: TransformerConfig, cu_seqlens: Optional[Tensor] = None, ): """ Reroute to the appropriate apply_rotary_pos_emb function depending on bshd (conventional) / thd (packed seq) format In Qwen2-VL, the shape of freqs is (seq_length, bs, 1, 2 * dim) instead of [max_seqlen, 1, 1, 2 * dim] """ if config.apply_rope_fusion: if cu_seqlens is None: # NOTE: TE backends do not support mRoPE in bshd format when bs > 1 if freqs.shape[1] > 1: return _apply_rotary_pos_emb_bshd(t, freqs, rotary_interleaved=config.rotary_interleaved) else: return fused_apply_rotary_pos_emb(t, freqs) else: # NOTE: as expected, thd format can use bshd return fused_apply_rotary_pos_emb(t[:, None], freqs).squeeze(1) else: if cu_seqlens is None: return _apply_rotary_pos_emb_bshd(t, freqs, rotary_interleaved=config.rotary_interleaved) else: return apply_rotary_pos_emb_thd_absolute(t, cu_seqlens, freqs, rotary_interleaved=config.rotary_interleaved)
verl__models__mcore__qwen2_5_vl__rope_utils.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2024 Alibaba PAI Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from megatron.core import parallel_state from megatron.core.transformer import TransformerConfig def get_vision_model_config(config: TransformerConfig) -> TransformerConfig: # Given a Transformer Config from decoder, build vision encoder config # diff: out_hidden_size & intermediate_size # mlp: hidden_size -> intermediate_size -> embed_dim, silu # NOTE: here we provide a workaround to solve the wrong layer amount when VPP of decoder is on if config.num_layers in [28, 36]: config.ffn_hidden_size = 3420 else: config.ffn_hidden_size = 3456 if parallel_state.get_virtual_pipeline_model_parallel_world_size() is not None: config.num_layers = 32 * parallel_state.get_virtual_pipeline_model_parallel_world_size() # depth else: config.num_layers = 32 # depth config.num_attention_heads = 16 # num_heads config.add_bias_linear = True # all nn.Linear has bias (MLP, attn) config.add_qkv_bias = True # qkv_proj in attn has bias config.hidden_size = 1280 # hidden_size config.hidden_dropout = 0.0 config.attention_dropout = 0.0 # config.gated_linear_unit = False # no gated # config.activation_func = quick_gelu # hidden_act config.kv_channels = config.hidden_size // config.num_attention_heads config.num_query_groups = config.num_attention_heads # no GQA config.layernorm_zero_centered_gamma = False # False config.apply_query_key_layer_scaling = False # factor=math.sqrt(head_dim) config.bias_activation_fusion = False # no swiglu, set false config.bias_dropout_fusion = False # no dropout, set false config.attention_softmax_in_fp32 = True # use True # config.normalization = 'LayerNorm' # use RMSNorm config.seq_length = 1 config.tp_comm_overlap = False config.sequence_parallel = False config.temporal_patch_size = 2 config.patch_size = 14 config.in_channels = 3 config.spatial_merge_size = 2 config.fullatt_block_indexes = [7, 15, 23, 31] config._qwen2_5_vl_window_size = 112 return config def get_vision_projection_config( config: TransformerConfig, embed_dim: int, spatial_merge_size: int ) -> TransformerConfig: # merger: # context_dim = hidden_size * merge_size**2 # out_hidden_size = hidden_size # context_dim -> context_dim -> out_hidden_size # MLP: # input_size -> ffn_hidden_size -> hidden_size # spec: LN -> Linear(bias=True) -> GELU -> Linear(bias=True) config.gated_linear_unit = False config.bias_activation_fusion = False config.add_bias_linear = True config.ffn_hidden_size = embed_dim * (spatial_merge_size**2) config.activation_func = torch.nn.functional.gelu config.tp_comm_overlap = False config.sequence_parallel = False return config
verl__models__mcore__qwen2_5_vl__vision_config.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2024 Alibaba PAI Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional import torch from megatron.core import InferenceParams from megatron.core.models.common.vision_module.vision_module import VisionModule from megatron.core.models.vision.multimodal_projector import MultimodalProjector from megatron.core.packed_seq_params import PackedSeqParams from megatron.core.transformer.enums import ModelType from megatron.core.transformer.spec_utils import ModuleSpec from megatron.core.transformer.transformer_config import TransformerConfig from torch import nn from torch.nn import functional as F from .vision_transformer_block import Qwen2_5VisionTransformerBlock as TransformerBlock # copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py class PatchEmbed(nn.Module): def __init__( self, patch_size: int = 14, temporal_patch_size: int = 2, in_channels: int = 3, embed_dim: int = 1152, ) -> None: super().__init__() self.patch_size = patch_size self.temporal_patch_size = temporal_patch_size self.in_channels = in_channels self.embed_dim = embed_dim kernel_size = [temporal_patch_size, patch_size, patch_size] self.proj = nn.Conv3d(in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: target_dtype = self.proj.weight.dtype hidden_states = hidden_states.view( -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size ) hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim) return hidden_states # copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py class VisionRotaryEmbedding(nn.Module): def __init__(self, dim: int, theta: float = 10000.0) -> None: super().__init__() inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) def forward(self, seqlen: int) -> torch.Tensor: seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype) freqs = torch.outer(seq, self.inv_freq) return freqs.float() class Qwen2_5VisionModel(VisionModule): """Qwen2.5 ViT vision model. Args: transformer_config (TransformerConfig): Transformer config. transformer_layer_spec (ModuleSpec): Specifies module to use for transformer layers. ln_pre_impl (ModuleSpec or type): Specifies the layer norm type to use for ln_pre. add_class_token (bool, optional): Include a class token. Defaults to True. class_token_len (int): Class token length. Defaults to 1 but 8 may be faster. patch_dim (int): Image patch size. img_h (int): Input image height. img_w (int): Input image width. """ def __init__( self, transformer_config: TransformerConfig, transformer_layer_spec: ModuleSpec, projection_config: TransformerConfig, projection_layer_spec: ModuleSpec, projection_type: str = "mlp", pre_process: bool = True, post_process: bool = False, ) -> None: super().__init__(config=transformer_config) self.spatial_merge_size = transformer_config.spatial_merge_size embed_dim = transformer_config.hidden_size num_heads = transformer_config.num_attention_heads temporal_patch_size = transformer_config.temporal_patch_size patch_size = transformer_config.patch_size in_channels = transformer_config.in_channels self.patch_size = transformer_config.patch_size self.fullatt_block_indexes = transformer_config.fullatt_block_indexes self.window_size = transformer_config._qwen2_5_vl_window_size self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size self.max_sequence_length = transformer_config.seq_length self.patch_embed = PatchEmbed( patch_size=patch_size, temporal_patch_size=temporal_patch_size, in_channels=in_channels, embed_dim=embed_dim, ) head_dim = embed_dim // num_heads self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2) self.model_type = ModelType.encoder_or_decoder self.pre_process = pre_process self.post_process = post_process # Transformer layers. # TODO: Follow-up changes will make pre and post_process configurable. They are needed for supporting # pipeline parallelism. # NOTE: a final layer norm and/or linear layer present in some implementations are omitted here. self.decoder = TransformerBlock( config=transformer_config, spec=transformer_layer_spec, pre_process=self.pre_process, post_process=self.post_process, post_layer_norm=True, ) self.merge_hidden_size = projection_config.ffn_hidden_size self.square_merge_size = self.merge_hidden_size // embed_dim if self.post_process: self.projection = MultimodalProjector( projection_config, projection_layer_spec, projection_type, projection_config.ffn_hidden_size ) else: self.projection = None self.input_tensor = None def set_input_tensor(self, input_tensor: torch.Tensor) -> None: """Sets input tensor to the model. Args: input_tensor (Tensor): Sets the input tensor for the model. """ if self.pre_process: # always True self.input_tensor = input_tensor else: raise NotImplementedError() def rot_pos_emb(self, grid_thw): pos_ids = [] for t, h, w in grid_thw: hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) hpos_ids = hpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) hpos_ids = hpos_ids.permute(0, 2, 1, 3) hpos_ids = hpos_ids.flatten() wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1) wpos_ids = wpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) wpos_ids = wpos_ids.permute(0, 2, 1, 3) wpos_ids = wpos_ids.flatten() pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)) pos_ids = torch.cat(pos_ids, dim=0).to(grid_thw.device) max_grid_size = grid_thw[:, 1:].max() rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size).to(grid_thw.device) rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1) return rotary_pos_emb def get_window_index(self, grid_thw): window_index: list = [] cu_window_seqlens: list = [0] window_index_id = 0 vit_merger_window_size = self.window_size // self.spatial_merge_size // self.patch_size for grid_t, grid_h, grid_w in grid_thw: llm_grid_h, llm_grid_w = ( grid_h // self.spatial_merge_size, grid_w // self.spatial_merge_size, ) index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape(grid_t, llm_grid_h, llm_grid_w) pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100) index_padded = index_padded.reshape( grid_t, num_windows_h, vit_merger_window_size, num_windows_w, vit_merger_window_size, ) index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape( grid_t, num_windows_h * num_windows_w, vit_merger_window_size, vit_merger_window_size, ) seqlens = (index_padded != -100).sum([2, 3]).reshape(-1) index_padded = index_padded.reshape(-1) index_new = index_padded[index_padded != -100] window_index.append(index_new + window_index_id) cu_seqlens_tmp = seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1] cu_window_seqlens.extend(cu_seqlens_tmp.tolist()) window_index_id += (grid_t * llm_grid_h * llm_grid_w).item() window_index = torch.cat(window_index, dim=0) return window_index, cu_window_seqlens def forward( self, vision_data: Optional[torch.Tensor], grid_thw: torch.Tensor, inference_params: Optional[InferenceParams] = None, extra_block_kwargs: dict = None, ) -> torch.Tensor: """Forward function of the Qwen2 Vision Model. This function passes the input tensors through the embedding layer and then the transformer. Args: x (torch.Tensor): input image/video data of shape [n_tokens, n_dims] grid_thw (torch.Tensor): the size tensor indicates grid size of each image/frame packed_seq_params (PackedSeqParams): parameters to build attention mask in the backend Returns: x (torch.Tensor): output after final transformer block of shape [b, s, h]. """ assert grid_thw is not None assert self.input_tensor is None assert inference_params is None # Rotary positional embeddings (embedding is None for PP intermediate devices) vision_data = self.patch_embed(vision_data) window_index, cu_window_seqlens = self.get_window_index(grid_thw) cu_window_seqlens = torch.tensor( cu_window_seqlens, device=vision_data.device, dtype=torch.int32, ) cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens) seq_len, _ = vision_data.size() vision_data = vision_data.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) vision_data = vision_data[window_index, :, :] vision_data = vision_data.reshape(seq_len, 1, -1) rotary_pos_emb = self.rot_pos_emb(grid_thw) rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) rotary_pos_emb = rotary_pos_emb[window_index, :, :] rotary_pos_emb = rotary_pos_emb.reshape(seq_len, 1, 1, -1).repeat(1, 1, 1, 2) hidden_states = self.decoder( hidden_states=vision_data, attention_mask=None, inference_params=inference_params, rotary_pos_emb=rotary_pos_emb, packed_seq_params=self.build_packed_seq_params(None, cu_window_seqlens), packed_seq_params_full=self.build_packed_seq_params(grid_thw), fullatt_block_indexes=self.fullatt_block_indexes, **(extra_block_kwargs or {}), ) hidden_states = self.projection(hidden_states.view(-1, self.merge_hidden_size)) reverse_indices = torch.argsort(window_index) return hidden_states[reverse_indices, :] def build_packed_seq_params( self, grid_thw: Optional[torch.Tensor], cu_seqlens: Optional[torch.Tensor] = None, ) -> PackedSeqParams: # NOTE: each frame is a sequence (rather than each grid) if grid_thw is not None: seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]) cu_seqlens = seqlens.cumsum(dim=0) cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0).int() else: seqlens = cu_seqlens[1:] - cu_seqlens[:-1] max_seqlen_q = seqlens.max() return PackedSeqParams( cu_seqlens_q=cu_seqlens, cu_seqlens_kv=cu_seqlens, qkv_format="thd", max_seqlen_q=max_seqlen_q, max_seqlen_kv=max_seqlen_q, )
verl__models__mcore__qwen2_5_vl__vision_model.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2024 Alibaba PAI Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from megatron.core.transformer.transformer_block import * class Qwen2_5VisionTransformerBlock(TransformerBlock): def _checkpointed_forward( self, hidden_states: Tensor, attention_mask: Tensor, context: Tensor, context_mask: Tensor, rotary_pos_emb: Tensor, attention_bias: Tensor, packed_seq_params: PackedSeqParams, packed_seq_params_full: PackedSeqParams, fullatt_block_indexes, ): """Forward method with activation checkpointing.""" def custom(start: int, end: int): def custom_forward(hidden_states, attention_mask, context, context_mask, rotary_pos_emb): for index in range(start, end): if index in fullatt_block_indexes: packed_seq_params_now = packed_seq_params_full else: packed_seq_params_now = packed_seq_params layer = self._get_layer(index) hidden_states, context = layer( hidden_states=hidden_states, attention_mask=attention_mask, context=context, context_mask=context_mask, rotary_pos_emb=rotary_pos_emb, attention_bias=attention_bias, inference_context=None, packed_seq_params=packed_seq_params_now, ) return hidden_states, context return custom_forward def checkpoint_handler(forward_func): """Determines whether to use the `te_checkpoint` or `tensor_parallel.checkpoint`""" if self.config.fp8: return te_checkpoint( forward_func, self.config.distribute_saved_activations, tensor_parallel.random.get_cuda_rng_tracker, parallel_state.get_tensor_model_parallel_group(), hidden_states, attention_mask, context, context_mask, rotary_pos_emb, ) else: return tensor_parallel.checkpoint( forward_func, self.config.distribute_saved_activations, hidden_states, attention_mask, context, context_mask, rotary_pos_emb, ) if self.config.recompute_method == "uniform": # Uniformly divide the total number of Transformer layers and checkpoint # the input activation of each divided chunk. # A method to further reduce memory usage reducing checkpoints. layer_idx = 0 while layer_idx < self.num_layers_per_pipeline_rank: hidden_states, context = checkpoint_handler( custom(layer_idx, layer_idx + self.config.recompute_num_layers) ) layer_idx += self.config.recompute_num_layers elif self.config.recompute_method == "block": # Checkpoint the input activation of only a set number of individual # Transformer layers and skip the rest. # A method fully use the device memory removing redundant re-computation. recompute_skip_num_layers = 0 for layer_idx in range(self.num_layers_per_pipeline_rank): # Skip recomputation when input grad computation is not needed. # Need to have at least one input tensor with gradient computation # for re-enterant autograd engine. if self.config.fp8 and not hidden_states.requires_grad: recompute_skip_num_layers += 1 if ( layer_idx >= recompute_skip_num_layers and layer_idx < self.config.recompute_num_layers + recompute_skip_num_layers ): hidden_states, context = checkpoint_handler(custom(layer_idx, layer_idx + 1)) else: hidden_states, context = custom(layer_idx, layer_idx + 1)( hidden_states, attention_mask, context, context_mask, rotary_pos_emb ) else: raise ValueError("Invalid activation recompute method.") return hidden_states def forward( self, hidden_states: Union[Tensor, WrappedTensor], attention_mask: Optional[Tensor], context: Optional[Tensor] = None, context_mask: Optional[Tensor] = None, rotary_pos_emb: Optional[Tensor] = None, rotary_pos_cos: Optional[Tensor] = None, rotary_pos_sin: Optional[Tensor] = None, attention_bias: Optional[Tensor] = None, inference_context: Optional[BaseInferenceContext] = None, packed_seq_params: Optional[PackedSeqParams] = None, sequence_len_offset: Optional[Tensor] = None, packed_seq_params_full: PackedSeqParams = None, fullatt_block_indexes=None, *, inference_params: Optional[BaseInferenceContext] = None, ): """ Perform the forward pass through the transformer block. This method handles the core computation of the transformer, including self-attention, optional cross-attention, and feed-forward operations. Args: hidden_states (Union[Tensor, WrappedTensor]): Input tensor of shape [s, b, h] where s is the sequence length, b is the batch size, and h is the hidden size. Can be passed as a WrappedTensor during inference to avoid an obsolete reference in the calling function. attention_mask (Tensor): Boolean tensor of shape [1, 1, s, s] for masking self-attention. context (Tensor, optional): Context tensor for cross-attention. context_mask (Tensor, optional): Mask for cross-attention context rotary_pos_emb (Tensor, optional): Rotary positional embeddings. attention_bias (Tensor): Bias tensor for Q * K.T of shape in shape broadcastable to [b, num_head, sq, skv], e.g. [1, 1, sq, skv]. Used as an alternative to apply attention mask for TE cuDNN attention. inference_context (BaseInferenceContext, optional): Parameters for inference-time optimizations. packed_seq_params (PackedSeqParams, optional): Parameters for packed sequence processing. Returns: Union[Tensor, Tuple[Tensor, Tensor]]: The output hidden states tensor of shape [s, b, h], and optionally the updated context tensor if cross-attention is used. """ inference_context = deprecate_inference_params(inference_context, inference_params) # Delete the obsolete reference to the initial input tensor if necessary if isinstance(hidden_states, WrappedTensor): hidden_states = hidden_states.unwrap() if not self.pre_process: # See set_input_tensor() hidden_states = self.input_tensor # Update the inference parameters with the current batch size in case it is variable if inference_context and not self.training: inference_context.current_batch_size = hidden_states.size(1) # Viewless tensor. # - We only need to create a viewless tensor in the case of micro batch # size (mbs) == 1, since in this case, 'hidden_states.transpose()' # above creates a view tensor, and '.contiguous()' is a pass-through. # For mbs >= 2, '.contiguous()' creates a new tensor, eliminating # the need to make it viewless. # # However, we don't explicitly check mbs == 1 here because # make_viewless_tensor() has negligible overhead when its input # is already viewless. # # - For the 'else' case above, calling make_viewless_tensor() here is # likely redundant, since p2p_communication.py (likely originator) # already creates viewless tensors. That said, make_viewless_tensor() # is called here to be future-proof and corner-case-proof. hidden_states = make_viewless_tensor(inp=hidden_states, requires_grad=True, keep_graph=True) if self.config.sequence_parallel: rng_context = tensor_parallel.get_cuda_rng_tracker().fork() else: rng_context = nullcontext() # If fp8_recipe is delayed, wrap the entire pass with get_fp8_context(), # otherwise do nothing extra at the outer level # if we are using other fp8 recipes, then the context manager enter&exit are free # we can wrap fp8_context within the for loop over layers, so that we can fine-grained # control which layer will be fp8 or bf16 use_outer_fp8_context = self.config.fp8 and self.config.fp8_recipe == Fp8Recipe.delayed use_inner_fp8_context = self.config.fp8 and self.config.fp8_recipe != Fp8Recipe.delayed outer_fp8_context = get_fp8_context(self.config) if use_outer_fp8_context else nullcontext() with rng_context, outer_fp8_context: # Forward pass. if self.config.recompute_granularity == "full" and self.training: hidden_states = self._checkpointed_forward( hidden_states=hidden_states, attention_mask=attention_mask, context=context, context_mask=context_mask, rotary_pos_emb=rotary_pos_emb, attention_bias=attention_bias, packed_seq_params=packed_seq_params, packed_seq_params_full=packed_seq_params_full, fullatt_block_indexes=fullatt_block_indexes, ) else: for l_no, layer in enumerate(self.layers): inner_fp8_context = ( get_fp8_context(self.config, layer.layer_number - 1) if use_inner_fp8_context else nullcontext() ) if l_no in fullatt_block_indexes: packed_seq_params_now = packed_seq_params_full else: packed_seq_params_now = packed_seq_params with self.offload_context, inner_fp8_context: hidden_states, context = layer( hidden_states=hidden_states, attention_mask=attention_mask, context=context, context_mask=context_mask, rotary_pos_emb=rotary_pos_emb, rotary_pos_cos=rotary_pos_cos, rotary_pos_sin=rotary_pos_sin, attention_bias=attention_bias, inference_context=inference_context, packed_seq_params=packed_seq_params_now, sequence_len_offset=sequence_len_offset, ) if ( torch.is_grad_enabled() and self.config.cpu_offloading and self.group_prefetch_offload_commit_async is not None ): hidden_states = self.group_prefetch_offload_commit_async(hidden_states) # Final layer norm. if self.final_layernorm is not None: hidden_states = self.final_layernorm(hidden_states) # TENorm produces a "viewed" tensor. This will result in schedule.py's # deallocate_output_tensor() throwing an error, so a viewless tensor is # created to prevent this. hidden_states = make_viewless_tensor(inp=hidden_states, requires_grad=True, keep_graph=True) return hidden_states
verl__models__mcore__qwen2_5_vl__vision_transformer_block.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Registry module for model architecture components. """ from enum import Enum from typing import Callable import torch import torch.nn as nn from .model_forward import gptmodel_forward_no_padding, model_forward_gen from .model_forward_fused import fused_forward_model_gen, fused_forward_no_padding_gen class SupportedVLM(Enum): QWEN2_5_VL = "Qwen2_5_VLForConditionalGeneration" QWEN3_MOE_VL = "Qwen3VLMoeForConditionalGeneration" QWEN3_VL = "Qwen3VLForConditionalGeneration" supported_vlm = [member.value for member in SupportedVLM] def get_mcore_forward_fn(hf_config) -> Callable: """ Get the forward function for given model architecture. """ assert len(hf_config.architectures) == 1, "Only one architecture is supported for now" if hf_config.architectures[0] in supported_vlm: return model_forward_gen(True) else: # default to language model return model_forward_gen(False) def get_mcore_forward_no_padding_fn(hf_config) -> Callable: """ Get the forward function for given model architecture. """ assert len(hf_config.architectures) == 1, "Only one architecture is supported for now" return gptmodel_forward_no_padding def get_mcore_forward_fused_fn(hf_config) -> Callable: """ Get the forward function for given model architecture. """ assert len(hf_config.architectures) == 1, "Only one architecture is supported for now" if hf_config.architectures[0] in supported_vlm: return fused_forward_model_gen(True) else: # default to language model return fused_forward_model_gen(False) def get_mcore_forward_fused_no_padding_fn(hf_config) -> Callable: """ Get the fused forward function for no-padding inputs. """ assert len(hf_config.architectures) == 1, "Only one architecture is supported for now" if hf_config.architectures[0] in supported_vlm: return fused_forward_no_padding_gen(True) else: # default to language model return fused_forward_no_padding_gen(False) # ruff: noqa ######################################################## # below is the deprecated code ######################################################## from .config_converter import ( PretrainedConfig, TransformerConfig, hf_to_mcore_config_dense, hf_to_mcore_config_dpskv3, hf_to_mcore_config_llama4, hf_to_mcore_config_mixtral, hf_to_mcore_config_qwen2_5_vl, hf_to_mcore_config_qwen2moe, hf_to_mcore_config_qwen3moe, ) from .model_initializer import ( BaseModelInitializer, DeepseekV3Model, DenseModel, MixtralModel, Qwen2MoEModel, Qwen3MoEModel, Qwen25VLModel, ) from .weight_converter import ( McoreToHFWeightConverterDense, McoreToHFWeightConverterDpskv3, McoreToHFWeightConverterMixtral, McoreToHFWeightConverterQwen2_5_VL, McoreToHFWeightConverterQwen2Moe, McoreToHFWeightConverterQwen3Moe, ) class SupportedModel(Enum): LLAMA = "LlamaForCausalLM" # tested QWEN2 = "Qwen2ForCausalLM" # tested QWEN2_MOE = "Qwen2MoeForCausalLM" # pending DEEPSEEK_V3 = "DeepseekV3ForCausalLM" # not tested MIXTRAL = "MixtralForCausalLM" # tested QWEN2_5_VL = "Qwen2_5_VLForConditionalGeneration" # not supported LLAMA4 = "Llama4ForConditionalGeneration" # not tested QWEN3 = "Qwen3ForCausalLM" # tested QWEN3_MOE = "Qwen3MoeForCausalLM" # tested GLM4_MOE = "Glm4MoeForCausalLM" QWEN3_TOKEN_CLASSIFICATION = "Qwen3ForTokenClassification" LLAMA_TOKEN_CLASSIFICATION = "LlamaForTokenClassification" QWEN3_MOE_VL = "Qwen3VLMoeForConditionalGeneration" QWEN3_VL = "Qwen3VLForConditionalGeneration" GPT_OSS = "GptOssForCausalLM" MiMO = "MiMoForCausalLM" # Registry for model configuration converters MODEL_CONFIG_CONVERTER_REGISTRY: dict[SupportedModel, Callable[[PretrainedConfig, torch.dtype], TransformerConfig]] = { SupportedModel.LLAMA: hf_to_mcore_config_dense, SupportedModel.QWEN2: hf_to_mcore_config_dense, SupportedModel.QWEN2_MOE: hf_to_mcore_config_qwen2moe, SupportedModel.DEEPSEEK_V3: hf_to_mcore_config_dpskv3, SupportedModel.MIXTRAL: hf_to_mcore_config_mixtral, SupportedModel.QWEN2_5_VL: hf_to_mcore_config_qwen2_5_vl, SupportedModel.LLAMA4: hf_to_mcore_config_llama4, SupportedModel.QWEN3: hf_to_mcore_config_dense, SupportedModel.QWEN3_MOE: hf_to_mcore_config_qwen3moe, SupportedModel.QWEN3_TOKEN_CLASSIFICATION: hf_to_mcore_config_dense, SupportedModel.LLAMA_TOKEN_CLASSIFICATION: hf_to_mcore_config_dense, } # Registry for model initializers MODEL_INITIALIZER_REGISTRY: dict[SupportedModel, type[BaseModelInitializer]] = { SupportedModel.LLAMA: DenseModel, SupportedModel.QWEN2: DenseModel, SupportedModel.QWEN2_MOE: Qwen2MoEModel, SupportedModel.MIXTRAL: MixtralModel, SupportedModel.DEEPSEEK_V3: DeepseekV3Model, SupportedModel.QWEN2_5_VL: Qwen25VLModel, SupportedModel.LLAMA4: DenseModel, SupportedModel.QWEN3: DenseModel, SupportedModel.QWEN3_MOE: Qwen3MoEModel, SupportedModel.QWEN3_TOKEN_CLASSIFICATION: DenseModel, SupportedModel.LLAMA_TOKEN_CLASSIFICATION: DenseModel, } # Registry for model forward functions MODEL_FORWARD_REGISTRY: dict[SupportedModel, Callable] = { SupportedModel.LLAMA: model_forward_gen(), SupportedModel.QWEN2: model_forward_gen(), SupportedModel.QWEN2_MOE: model_forward_gen(), SupportedModel.MIXTRAL: model_forward_gen(), SupportedModel.DEEPSEEK_V3: model_forward_gen(), SupportedModel.LLAMA4: model_forward_gen(), SupportedModel.QWEN3: model_forward_gen(), SupportedModel.QWEN3_MOE: model_forward_gen(), SupportedModel.QWEN2_5_VL: model_forward_gen(True), SupportedModel.QWEN3_MOE_VL: model_forward_gen(True), SupportedModel.QWEN3_VL: model_forward_gen(True), SupportedModel.GLM4_MOE: model_forward_gen(), SupportedModel.QWEN3_TOKEN_CLASSIFICATION: model_forward_gen(), SupportedModel.LLAMA_TOKEN_CLASSIFICATION: model_forward_gen(), SupportedModel.GPT_OSS: model_forward_gen(), SupportedModel.MiMO: model_forward_gen(), } # Registry for model forward functions MODEL_FORWARD_NOPAD_REGISTRY: dict[SupportedModel, Callable] = { SupportedModel.LLAMA: gptmodel_forward_no_padding, SupportedModel.QWEN2: gptmodel_forward_no_padding, SupportedModel.QWEN2_MOE: gptmodel_forward_no_padding, SupportedModel.MIXTRAL: gptmodel_forward_no_padding, SupportedModel.DEEPSEEK_V3: gptmodel_forward_no_padding, SupportedModel.QWEN2_5_VL: gptmodel_forward_no_padding, SupportedModel.QWEN3_MOE_VL: gptmodel_forward_no_padding, SupportedModel.QWEN3_VL: gptmodel_forward_no_padding, SupportedModel.LLAMA4: gptmodel_forward_no_padding, SupportedModel.QWEN3: gptmodel_forward_no_padding, SupportedModel.QWEN3_MOE: gptmodel_forward_no_padding, SupportedModel.GLM4_MOE: gptmodel_forward_no_padding, SupportedModel.QWEN3_TOKEN_CLASSIFICATION: gptmodel_forward_no_padding, SupportedModel.LLAMA_TOKEN_CLASSIFICATION: gptmodel_forward_no_padding, SupportedModel.GPT_OSS: gptmodel_forward_no_padding, SupportedModel.MiMO: gptmodel_forward_no_padding, } # Registry for model forward functions MODEL_FORWARD_FUSED_REGISTRY: dict[SupportedModel, Callable] = { SupportedModel.LLAMA: fused_forward_model_gen(), SupportedModel.QWEN2: fused_forward_model_gen(), SupportedModel.QWEN2_MOE: fused_forward_model_gen(), SupportedModel.MIXTRAL: fused_forward_model_gen(), SupportedModel.QWEN2_5_VL: fused_forward_model_gen(True), SupportedModel.QWEN3_MOE_VL: fused_forward_model_gen(True), SupportedModel.QWEN3_VL: fused_forward_model_gen(True), SupportedModel.LLAMA4: fused_forward_model_gen(), SupportedModel.QWEN3: fused_forward_model_gen(), SupportedModel.QWEN3_MOE: fused_forward_model_gen(), SupportedModel.DEEPSEEK_V3: fused_forward_model_gen(), SupportedModel.GLM4_MOE: fused_forward_model_gen(), SupportedModel.GPT_OSS: fused_forward_model_gen(), SupportedModel.MiMO: fused_forward_model_gen(), } # Registry for model weight converters MODEL_WEIGHT_CONVERTER_REGISTRY: dict[SupportedModel, type] = { SupportedModel.LLAMA: McoreToHFWeightConverterDense, SupportedModel.QWEN2: McoreToHFWeightConverterDense, SupportedModel.QWEN2_MOE: McoreToHFWeightConverterQwen2Moe, SupportedModel.MIXTRAL: McoreToHFWeightConverterMixtral, SupportedModel.DEEPSEEK_V3: McoreToHFWeightConverterDpskv3, SupportedModel.QWEN3: McoreToHFWeightConverterDense, SupportedModel.QWEN3_MOE: McoreToHFWeightConverterQwen3Moe, SupportedModel.QWEN2_5_VL: McoreToHFWeightConverterQwen2_5_VL, SupportedModel.QWEN3_TOKEN_CLASSIFICATION: McoreToHFWeightConverterDense, SupportedModel.LLAMA_TOKEN_CLASSIFICATION: McoreToHFWeightConverterDense, } def get_supported_model(model_type: str) -> SupportedModel: try: return SupportedModel(model_type) except ValueError as err: supported_models = [e.value for e in SupportedModel] raise NotImplementedError( f"Model Type: {model_type} not supported. Supported models: {supported_models}" ) from err def hf_to_mcore_config( hf_config: PretrainedConfig, dtype: torch.dtype, **override_transformer_config_kwargs ) -> TransformerConfig: """Convert huggingface PretrainedConfig to mcore TransformerConfig. Args: hf_config: The huggingface PretrainedConfig. dtype: The dtype of the model. **override_transformer_config_kwargs: The kwargs to override the transformer config. Returns: The mcore TransformerConfig. """ assert len(hf_config.architectures) == 1, "Only one architecture is supported for now" model = get_supported_model(hf_config.architectures[0]) return MODEL_CONFIG_CONVERTER_REGISTRY[model](hf_config, dtype, **override_transformer_config_kwargs) def init_mcore_model( tfconfig: TransformerConfig, hf_config: PretrainedConfig, pre_process: bool = True, post_process: bool = None, *, share_embeddings_and_output_weights: bool = False, value: bool = False, **extra_kwargs, # may be used for vlm and moe ) -> nn.Module: """ Initialize a Mcore model. Args: tfconfig: The transformer config. hf_config: The HuggingFace config. pre_process: Optional pre-processing function. post_process: Optional post-processing function. share_embeddings_and_output_weights: Whether to share embeddings and output weights. value: Whether to use value. **extra_kwargs: Additional keyword arguments. Returns: The initialized model. """ assert len(hf_config.architectures) == 1, "Only one architecture is supported for now" model = get_supported_model(hf_config.architectures[0]) initializer_cls = MODEL_INITIALIZER_REGISTRY[model] initializer = initializer_cls(tfconfig, hf_config) return initializer.initialize( pre_process=pre_process, post_process=post_process, share_embeddings_and_output_weights=share_embeddings_and_output_weights, value=value, **extra_kwargs, ) def get_mcore_weight_converter(hf_config: PretrainedConfig, dtype: torch.dtype) -> Callable: """ Get the weight converter for given model architecture. """ assert len(hf_config.architectures) == 1, "Only one architecture is supported for now" model = get_supported_model(hf_config.architectures[0]) tfconfig = hf_to_mcore_config(hf_config, dtype) return MODEL_WEIGHT_CONVERTER_REGISTRY[model](hf_config, tfconfig)
verl__models__mcore__registry.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import torch import torch.distributed as dist from megatron.core import mpu from megatron.core.distributed import DistributedDataParallel as LocalDDP from megatron.core.transformer.module import Float16Module from torch.nn.parallel import DistributedDataParallel as torchDDP from verl.utils.device import get_device_id, get_torch_device from verl.utils.logger import print_rank_0 from verl.utils.megatron_utils import unwrap_model def _megatron_calc_global_rank( tp_rank: int = 0, dp_rank: int = 0, pp_rank: int = 0, cp_rank: int = 0, ep_rank: int = 0 ): """Calculate global rank with support for CP/EP parallelism""" # Get parallel sizes for each dimension tp_size = mpu.get_tensor_model_parallel_world_size() dp_size = mpu.get_data_parallel_world_size() pp_size = mpu.get_pipeline_model_parallel_world_size() cp_size = mpu.get_context_parallel_world_size() # ep_size = mpu.get_expert_model_parallel_world_size() # Verify total GPU count matches (must be consistent with parallel_state.py) total_size = tp_size * dp_size * pp_size * cp_size assert total_size == torch.distributed.get_world_size(), ( f"{tp_size}x{dp_size}x{pp_size}x{cp_size} != {torch.distributed.get_world_size()}" ) # Core calculation logic (corresponds to RankGenerator order parameter) # Assumes default order is "tp-cp-ep-dp-pp" return ((pp_rank * dp_size + dp_rank) * cp_size + cp_rank) * tp_size + tp_rank def _megatron_calc_layer_map(config): """Calculate the mapping of global layer_idx to local layer_idx Returns: layer_map (Dict: int -> tuple(int, int, int)): mapping from the global layer index to a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model) """ from megatron.core import mpu pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 layer_map = dict() num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers for pp_rank_idx in range(pp_size): for virtual_pp_rank_idx in range(virtual_pp_size): layer_offset = ( virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model ) for layer_idx in range(num_layers_per_model): layer_map[layer_offset + layer_idx] = ( pp_rank_idx, virtual_pp_rank_idx, layer_idx, ) return layer_map def merge_megatron_ckpt_gptmodel(wrapped_models, config, dtype, is_value_model=False, tie_word_embeddings=False): """Merge sharded parameters of a Megatron module into a merged checkpoint. Args: wrapped_models (list of megatron.core.distributed.DistributedDataParallel): The local DDP wrapped megatron modules. config (str or None): HF config for model dtype: model params type is_value_model: if model is value model tie_word_embeddings: tie_word_embeddings Returns: state_dict (dict): The merged state_dict in rank 0, and an empty dictionary in other ranks. """ start_time = time.time() def _get_gpt_model(model): return model dp_rank = mpu.get_data_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() pp_rank = mpu.get_pipeline_model_parallel_rank() cp_rank = mpu.get_context_parallel_rank() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 mp_group = mpu.get_model_parallel_group() if dist.get_rank() == 0: assert mp_group.rank() == 0, f"mp_rank:[{mp_group.rank}] != 0 on rank #0" assert pp_rank == 0, f"pp_rank:[{pp_rank}] != 0 on rank #0" assert dp_rank == 0, f"dp_rank:[{dp_rank}] != 0 on rank #0" if not isinstance(wrapped_models, list | tuple): wrapped_models = list(wrapped_models) assert len(wrapped_models) == virtual_pp_size num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers models = [None] * len(wrapped_models) for i, wrapped_model in enumerate(wrapped_models): models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module)) assert len(models[i].decoder.layers) == num_layers_per_model, ( "len model layers {} not equal to num_layers_per_model {}".format( len(models[i].decoder.layers), num_layers_per_model ) ) state_dict = dict() def _get_cpu_tensor(tensor: torch.Tensor): if tensor is None: return None if tensor.device == torch.device("cpu"): return tensor.detach().clone() return tensor.detach().cpu() def _broadcast_tensor(tensor, name, src_pp_rank) -> torch.Tensor: """broadcast tensor across mp_group""" nonlocal state_dict nonlocal mp_group src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank, cp_rank=cp_rank) if torch.distributed.get_rank() == src_rank: if tensor is None: weight = None tensor_shape = None else: weight = tensor tensor_shape = weight.shape else: weight = None tensor_shape = None obj_list = [tensor_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) tensor_shape = obj_list[0] if tensor_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tensor:[{name}] not exist, skip collect") return if weight is None: weight = torch.empty( tensor_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) dist.broadcast(weight, src=src_rank, group=mp_group) if torch.distributed.get_rank() == 0: state_dict[name] = _get_cpu_tensor(weight) def _broadcast_tp_shard_tensor(tensor, name, src_pp_rank, concat_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group # tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank, cp_rank=cp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank, cp_rank=cp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=concat_dim) if mutate_func is not None: full_tensor = mutate_func(full_tensor) state_dict[name] = full_tensor def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name, src_pp_rank) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group # tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank, cp_rank=cp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{gate_name, up_name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank, cp_rank=cp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=0) intermediate_size_tp = config.intermediate_size // tp_size gate_weight_list = [] up_weight_list = [] for i in range(tp_size): gate_up_weight_tp = full_tensor[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)] gate_weight_tp = gate_up_weight_tp[:intermediate_size_tp] up_weight_tp = gate_up_weight_tp[intermediate_size_tp:] gate_weight_list.append(gate_weight_tp) up_weight_list.append(up_weight_tp) state_dict[gate_name] = torch.cat(gate_weight_list, dim=0) state_dict[up_name] = torch.cat(up_weight_list, dim=0) def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, src_pp_rank): """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group # tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank, cp_rank=cp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{q_name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank, cp_rank=cp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=0) q_weight_list = [] k_weight_list = [] v_weight_list = [] hidden_size_per_head = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) if config.num_key_value_heads >= tp_size: q_size_tp = hidden_size_per_head * config.num_attention_heads // tp_size kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size total_size = q_size_tp + 2 * kv_size_tp for i in range(tp_size): num_query_groups_per_partition = wrapped_models[0].config.num_query_groups // tp_size qkv_part = full_tensor[i * total_size : (i + 1) * total_size] q_size_chunk = q_size_tp // num_query_groups_per_partition kv_size_chunk = kv_size_tp // num_query_groups_per_partition for qkv_part_chunk in qkv_part.chunk(num_query_groups_per_partition): q_part = qkv_part_chunk[:q_size_chunk] k_part = qkv_part_chunk[q_size_chunk : q_size_chunk + kv_size_chunk] v_part = qkv_part_chunk[q_size_chunk + kv_size_chunk :] q_weight_list.append(q_part) k_weight_list.append(k_part) v_weight_list.append(v_part) else: q_size_tp = hidden_size_per_head * config.num_attention_heads // tp_size kv_size_tp = hidden_size_per_head total_size = q_size_tp + 2 * kv_size_tp for i in range(tp_size): num_query_groups_per_partition = wrapped_models[0].config.num_query_groups // tp_size qkv_part = full_tensor[i * total_size : (i + 1) * total_size] q_size_chunk = q_size_tp // num_query_groups_per_partition kv_size_chunk = kv_size_tp // num_query_groups_per_partition for qkv_part_chunk in qkv_part.chunk(num_query_groups_per_partition): q_part = qkv_part_chunk[:q_size_chunk] k_part = qkv_part_chunk[q_size_chunk : q_size_chunk + kv_size_chunk] v_part = qkv_part_chunk[q_size_chunk + kv_size_chunk :] q_weight_list.append(q_part) if i * config.num_key_value_heads % tp_size == 0: k_weight_list.append(k_part) v_weight_list.append(v_part) state_dict[q_name] = torch.cat(q_weight_list, dim=0) state_dict[k_name] = torch.cat(k_weight_list, dim=0) state_dict[v_name] = torch.cat(v_weight_list, dim=0) # empty cache before collecting weights get_torch_device().empty_cache() # Embeddings # ------------------- if dp_rank == 0 and cp_rank == 0: # models are identical across cp ranks # Embeddings # ------------------- print_rank_0("collecting embeddings...") gpt_model_module = _get_gpt_model(models[0]) _broadcast_tp_shard_tensor( gpt_model_module.embedding.word_embeddings.weight if pp_rank == 0 else None, "model.embed_tokens.weight", src_pp_rank=0, ) # Transformer layers # ------------------- layer_map = _megatron_calc_layer_map(config) for layer in range(config.num_hidden_layers): print_rank_0(f"collecting layer #{layer}...") layer_name = f"model.layers.{layer}" src_pp_rank, src_virtual_pp_rank, src_layer_idx = layer_map[layer] gpt_model_module = _get_gpt_model(models[src_virtual_pp_rank]) sync_layer = gpt_model_module.decoder.layers[src_layer_idx] _broadcast_tensor( sync_layer.self_attention.linear_qkv.layer_norm_weight, f"{layer_name}.input_layernorm.weight", src_pp_rank=src_pp_rank, ) if gpt_model_module.config.qk_layernorm: _broadcast_tensor( sync_layer.self_attention.q_layernorm.weight, f"{layer_name}.self_attn.q_norm.weight", src_pp_rank=src_pp_rank, ) _broadcast_tensor( sync_layer.self_attention.k_layernorm.weight, f"{layer_name}.self_attn.k_norm.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor_qkv( sync_layer.self_attention.linear_qkv.weight, f"{layer_name}.self_attn.q_proj.weight", f"{layer_name}.self_attn.k_proj.weight", f"{layer_name}.self_attn.v_proj.weight", src_pp_rank=src_pp_rank, ) if gpt_model_module.config.add_qkv_bias: _broadcast_tp_shard_tensor_qkv( sync_layer.self_attention.linear_qkv.bias, f"{layer_name}.self_attn.q_proj.bias", f"{layer_name}.self_attn.k_proj.bias", f"{layer_name}.self_attn.v_proj.bias", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor( sync_layer.self_attention.linear_proj.weight, f"{layer_name}.self_attn.o_proj.weight", concat_dim=1, src_pp_rank=src_pp_rank, ) _broadcast_tensor( sync_layer.mlp.linear_fc1.layer_norm_weight, f"{layer_name}.post_attention_layernorm.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor_gate_up( sync_layer.mlp.linear_fc1.weight, f"{layer_name}.mlp.gate_proj.weight", f"{layer_name}.mlp.up_proj.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor( sync_layer.mlp.linear_fc2.weight, f"{layer_name}.mlp.down_proj.weight", concat_dim=1, src_pp_rank=src_pp_rank, ) # Final Layernorm # ------------------- print_rank_0("collecting final layernorm...") gpt_model_module = _get_gpt_model(models[-1]) _broadcast_tensor( getattr(gpt_model_module.decoder.final_layernorm, "weight", None), "model.norm.weight", src_pp_rank=pp_size - 1, ) if tie_word_embeddings: print_rank_0("tie word embedding skip load lm_head...") else: print_rank_0("collecting lm_head...") if is_value_model: lm_head_weight = None if pp_rank == pp_size - 1: lm_head_weight = getattr(gpt_model_module.output_layer, "weight", None) _broadcast_tensor(lm_head_weight, "lm_head.weight", src_pp_rank=pp_size - 1) else: _broadcast_tp_shard_tensor( getattr(gpt_model_module.output_layer, "weight", None) if pp_rank == pp_size - 1 else None, "lm_head.weight", src_pp_rank=pp_size - 1, ) dist.barrier() get_torch_device().empty_cache() if torch.distributed.get_rank() == 0: for k, v in state_dict.items(): if dtype != v.dtype: state_dict[k] = v.to(dtype) print_rank_0(f"merge megatron ckpt done, time elapsed {time.time() - start_time}s") return state_dict def merge_megatron_ckpt_gptmodel_qwen_moe( wrapped_models, config, dtype, is_value_model=False, tie_word_embeddings=False ): raise NotImplementedError("merge_megatron_ckpt_gptmodel_qwen_moe is not implemented") def merge_megatron_ckpt_gptmodel_qwen2_5_vl( wrapped_models, config, dtype, is_value_model=False, tie_word_embeddings=False ): raise NotImplementedError("merge_megatron_ckpt_gptmodel_qwen2_5_vl is not implemented") def merge_megatron_ckpt_gptmodel_dpskv3(wrapped_models, config, dtype, is_value_model=False, tie_word_embeddings=False): raise NotImplementedError("merge_megatron_ckpt_gptmodel_dpskv3 is not implemented") def merge_megatron_ckpt_gptmodel_mixtral( wrapped_models, config, dtype, is_value_model=False, tie_word_embeddings=False ): raise NotImplementedError("merge_megatron_ckpt_gptmodel_mixtral is not implemented")
verl__models__mcore__saver.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math import torch from megatron.core import parallel_state as mpu from megatron.core.packed_seq_params import PackedSeqParams from verl.utils.model import CausalLMOutputForPPO def preprocess_packed_seqs( input_ids: torch.Tensor, attention_mask: torch.Tensor, pre_process: bool = True, use_fp8_padding=False ) -> tuple[torch.Tensor, PackedSeqParams]: """ Preprocess packed sequences CP splits sequence into CP*2 chunks, and each GPU gets 2 chunks (GPU0 gets first and last chunks, GPU1 gets second and second last chunks, and so on), this is for load balancing with causal masking. See https://github.com/NVIDIA/TransformerEngine/issues/1368 """ batch_size = input_ids.shape[0] seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) tp_size = mpu.get_tensor_model_parallel_world_size() cp_size = mpu.get_context_parallel_world_size() cp_rank = mpu.get_context_parallel_rank() align_size = tp_size * cp_size * 2 if cp_size > 1 else tp_size if use_fp8_padding: # if fp8 is enabled, ensure the sequence is padded to multiples of 16 for better performance original_align_size = align_size align_size = math.lcm(16, align_size) pad_size = (align_size - seqlens_in_batch % align_size) % align_size seqlens_in_batch_padded = seqlens_in_batch + pad_size cu_seqlens = torch.zeros(batch_size + 1, dtype=torch.int32, device=input_ids.device) cu_seqlens[1:] = torch.cumsum(seqlens_in_batch, dim=0) cu_seqlens_padded = torch.zeros(batch_size + 1, dtype=torch.int32, device=input_ids.device) cu_seqlens_padded[1:] = torch.cumsum(seqlens_in_batch_padded, dim=0) if use_fp8_padding: # make sure all the sequences are padded to multiples of 128 for TE compatibility align_size_last = original_align_size * 128 pad_size_last = (align_size_last - cu_seqlens_padded[-1] % align_size_last) % align_size_last cu_seqlens_padded[-1] += pad_size_last seqlens_in_batch_padded[-1] += pad_size_last # ---------------------------------------------------------------------------- # Move the index information needed in the subsequent loop to the CPU at once, # to avoid frequent .item() calls in the loop that cause D2H synchronization # ---------------------------------------------------------------------------- seqlens_in_batch_cpu: list[int] = seqlens_in_batch.tolist() # original valid lengths seqlens_in_batch_padded_cpu: list[int] = seqlens_in_batch_padded.tolist() # lengths after padding cu_seqlens_padded_cpu: list[int] = cu_seqlens_padded.tolist() # start positions (after padding) # Pure Python int calculation to avoid further synchronization max_seqlen_in_batch = max(seqlens_in_batch_padded_cpu) shape = list(input_ids.shape[1:]) shape[0] = sum(seqlens_in_batch_padded_cpu) // cp_size if pre_process: input_ids_rmpad = torch.zeros(shape, dtype=input_ids.dtype, device=input_ids.device) for i in range(batch_size): # Use Python int, so no GPU→CPU sync in the loop if cp_size <= 1: seqlen = seqlens_in_batch_cpu[i] start_idx = cu_seqlens_padded_cpu[i] input_ids_rmpad[start_idx : start_idx + seqlen] = input_ids[i, attention_mask[i]] continue seqlen_padded_i = seqlens_in_batch_padded_cpu[i] seqlen = seqlen_padded_i // cp_size half_seqlen = seqlen // 2 start_idx = cu_seqlens_padded_cpu[i] // cp_size # split to 2 chunks d = input_ids[i, attention_mask[i]] input_ids_rmpad[start_idx : start_idx + half_seqlen] = d[ half_seqlen * cp_rank : half_seqlen * (cp_rank + 1) ] remain_start = seqlen_padded_i - half_seqlen * (cp_rank + 1) remain_end = seqlen_padded_i - half_seqlen * cp_rank remain_end = min(remain_end, d.shape[0]) remain_len = remain_end - remain_start if remain_len > 0: input_ids_rmpad[start_idx + half_seqlen : start_idx + half_seqlen + remain_len] = d[ remain_start:remain_end ] packed_seq_params = PackedSeqParams( qkv_format="thd", cu_seqlens_q=cu_seqlens_padded, max_seqlen_q=max_seqlen_in_batch, cu_seqlens_kv=cu_seqlens_padded, max_seqlen_kv=max_seqlen_in_batch, cu_seqlens_q_padded=cu_seqlens_padded, cu_seqlens_kv_padded=cu_seqlens_padded, ) if pre_process: return input_ids_rmpad.unsqueeze(0), packed_seq_params else: return input_ids, packed_seq_params def postprocess_packed_seqs( output: torch.Tensor, packed_seq_params: PackedSeqParams, attention_mask: torch.Tensor, batch_size: int, seq_len: int, post_process: bool = True, ) -> torch.Tensor: """ Postprocess packed sequences """ if not post_process: return output # ------------------------------------------------------------------------- # Move the lengths and offsets needed for subsequent Python-level indexing to the CPU in advance, # to avoid a large number of .item() calls in the loop # ------------------------------------------------------------------------- cu_padded_cpu: list[int] = packed_seq_params.cu_seqlens_q_padded.tolist() seq_lens_cpu: list[int] = attention_mask.sum(dim=1, dtype=torch.int32).cpu().tolist() shape = [batch_size, seq_len] + list(output.shape[2:]) # 1,packed, dim -> batch_size, seq_len, dim output_new = torch.zeros(shape, dtype=output.dtype, device=output.device) cp_size = mpu.get_context_parallel_world_size() # all gather output across context parallel group if cp_size > 1: # output shape: [1, packed_len, hidden_dim] # need to gather across cp group and concatenate in sequence dimension output_list = [torch.empty_like(output, dtype=output.dtype) for _ in range(cp_size)] torch.distributed.all_gather(output_list, output.detach(), group=mpu.get_context_parallel_group()) output_list[mpu.get_context_parallel_rank()] = output else: output_list = [output] for i in range(batch_size): if cp_size <= 1: s = seq_lens_cpu[i] start_idx = cu_padded_cpu[i] output_new[i, attention_mask[i]] = output[0][start_idx : start_idx + s] continue s_len_padded_chunk = (cu_padded_cpu[i + 1] - cu_padded_cpu[i]) // cp_size half_seqlen = s_len_padded_chunk // 2 s_len = seq_lens_cpu[i] s_len_padded = s_len_padded_chunk * cp_size tmp = torch.empty(s_len_padded, *output.shape[2:], device=output.device, dtype=output.dtype) for j in range(cp_size): o = output_list[j][0] # split to 2 chunks packed_start_idx = cu_padded_cpu[i] // cp_size o0, o1 = ( o[packed_start_idx : packed_start_idx + half_seqlen], o[packed_start_idx + half_seqlen : packed_start_idx + s_len_padded_chunk], ) tmp[j * half_seqlen : (j + 1) * half_seqlen] = o0 tmp[s_len_padded - (j + 1) * half_seqlen : s_len_padded - j * half_seqlen] = o1 output_new[i, attention_mask[i]] = tmp[:s_len] return output_new def preprocess_bshd( input_ids: torch.Tensor, attention_mask: torch.Tensor, position_ids: torch.Tensor, sequence_parallel: bool = False, pre_process: bool = True, ): """ Remove left padding from input_ids, attention_mask and position_ids return new_input_ids, new_attention_mask, new_position_ids """ assert attention_mask.ndim == 2 assert position_ids.ndim == 2 cp_size = mpu.get_context_parallel_world_size() assert cp_size == 1, "Context parallel size without seq_pack is not supported" batch_size = input_ids.shape[0] shape = list(input_ids.shape) # batch_size, seq_len,... seq_lens = attention_mask.sum(dim=1) seq_len = seq_lens.max().item() if sequence_parallel: sp_world_size = mpu.get_tensor_model_parallel_world_size() pad_size = (sp_world_size - seq_len % sp_world_size) % sp_world_size seq_len = seq_len + pad_size shape[1] = seq_len if pre_process: new_input_ids = torch.zeros(dtype=input_ids.dtype, device=input_ids.device, size=shape) new_attention_mask = torch.zeros( dtype=attention_mask.dtype, device=attention_mask.device, size=(batch_size, seq_len) ) new_position_ids = torch.zeros(dtype=position_ids.dtype, device=position_ids.device, size=(batch_size, seq_len)) for i in range(batch_size): if pre_process: new_input_ids[i, : seq_lens[i]] = input_ids[i, attention_mask[i]] new_attention_mask[i, : seq_lens[i]] = attention_mask[i, attention_mask[i]] new_position_ids[i, : seq_lens[i]] = position_ids[i, attention_mask[i]] if pre_process: return new_input_ids, new_attention_mask, new_position_ids else: return input_ids, new_attention_mask, new_position_ids def postprocess_bshd( result, attention_mask: torch.Tensor, original_attention_mask: torch.Tensor, origin_seqlen: int, post_process: bool = True, ): """ Recover left padding from result return result """ if not post_process: return result shape = list(result.shape) batch_size = shape[0] shape[1] = origin_seqlen new_result = torch.zeros(dtype=result.dtype, device=result.device, size=shape) for i in range(batch_size): new_result[i, original_attention_mask[i]] = result[i, attention_mask[i]] return new_result def postprocess_packed_seqs_for_dict_output( labels_mask: torch.Tensor, output: CausalLMOutputForPPO, packed_seq_params: PackedSeqParams, attention_mask: torch.Tensor, batch_size: int, seq_len: int, post_process: bool = True, ) -> dict[str, torch.Tensor]: """_summary_ For fused kernels, the output is a dictionary with keys like 'log_probs', 'entropy', etc. This function post-processes each tensor in the output dictionary. Args: output (CausalLMOutputForPPO): _description_ packed_seq_params (PackedSeqParams): _description_ attention_mask (torch.Tensor): _description_ batch_size (int): _description_ seq_len (int): _description_ post_process (bool, optional): _description_. Defaults to True. Returns: CausalLMOutputForPPO: _description_ """ ret = {} output.entropy = output.entropy.view(1, -1) output.log_probs = output.log_probs.view(1, -1) output.log_probs = output.log_probs.masked_fill(~labels_mask, 0.0) ret["entropy"] = postprocess_packed_seqs( output.entropy, packed_seq_params, attention_mask, batch_size, seq_len, post_process=post_process ) ret["log_probs"] = postprocess_packed_seqs( output.log_probs, packed_seq_params, attention_mask, batch_size, seq_len, post_process=post_process ) return ret ### No padding versions for model engine ### inputs are nested tensors def preprocess_thd_no_padding( input_ids: torch.Tensor, pre_process: bool = True, need_roll: bool = False ) -> tuple[torch.Tensor, PackedSeqParams]: """ Preprocess packed sequences CP splits sequence into CP*2 chunks, and each GPU gets 2 chunks (GPU0 gets first and last chunks, GPU1 gets second and second last chunks, and so on), this is for load balancing with causal masking. See https://github.com/NVIDIA/TransformerEngine/issues/1368 """ batch_size = input_ids.shape[0] tp_size = mpu.get_tensor_model_parallel_world_size() cp_size = mpu.get_context_parallel_world_size() cp_rank = mpu.get_context_parallel_rank() align_size = tp_size * cp_size * 2 if cp_size > 1 else tp_size seqlens_in_batch = input_ids.offsets().diff() pad_size = (align_size - seqlens_in_batch % align_size) % align_size seqlens_in_batch_padded = seqlens_in_batch + pad_size cu_seqlens = torch.zeros(batch_size + 1, dtype=torch.int32, device=input_ids.device) cu_seqlens[1:] = torch.cumsum(seqlens_in_batch, dim=0) cu_seqlens_padded = torch.zeros(batch_size + 1, dtype=torch.int32, device=input_ids.device) cu_seqlens_padded[1:] = torch.cumsum(seqlens_in_batch_padded, dim=0) # ---------------------------------------------------------------------------- # Move the index information needed in the subsequent loop to the CPU at once, # to avoid frequent .item() calls in the loop that cause D2H synchronization # ---------------------------------------------------------------------------- seqlens_in_batch_cpu: list[int] = seqlens_in_batch.tolist() # original valid lengths seqlens_in_batch_padded_cpu: list[int] = seqlens_in_batch_padded.tolist() # lengths after padding cu_seqlens_padded_cpu: list[int] = cu_seqlens_padded.tolist() # start positions (after padding) # Pure Python int calculation to avoid further synchronization max_seqlen_in_batch = max(seqlens_in_batch_padded_cpu) shape = list(input_ids.shape[1:]) shape[0] = sum(seqlens_in_batch_padded_cpu) // cp_size if pre_process: input_ids_rmpad = torch.zeros(shape, dtype=input_ids.dtype, device=input_ids.device) if need_roll: saved_roll_dict = {} for i in range(batch_size): # Use Python int, so no GPU→CPU sync in the loop if cp_size <= 1: seqlen = seqlens_in_batch_cpu[i] start_idx = cu_seqlens_padded_cpu[i] input_ids_rmpad[start_idx : start_idx + seqlen] = input_ids[i] continue seqlen_padded_i = seqlens_in_batch_padded_cpu[i] seqlen = seqlen_padded_i // cp_size half_seqlen = seqlen // 2 start_idx = cu_seqlens_padded_cpu[i] // cp_size # split to 2 chunks d = input_ids[i] input_ids_rmpad[start_idx : start_idx + half_seqlen] = d[ half_seqlen * cp_rank : half_seqlen * (cp_rank + 1) ] remain_start = seqlen_padded_i - half_seqlen * (cp_rank + 1) remain_end = seqlen_padded_i - half_seqlen * cp_rank remain_end = min(remain_end, d.shape[0]) remain_len = remain_end - remain_start if remain_len > 0: input_ids_rmpad[start_idx + half_seqlen : start_idx + half_seqlen + remain_len] = d[ remain_start:remain_end ] if need_roll: # Handle roll for cp_size > 1 case saved_roll_dict[start_idx + half_seqlen - 1] = d[(cp_rank + 1) * half_seqlen] if remain_len > 0: if remain_end == d.shape[0]: saved_roll_dict[start_idx + half_seqlen + remain_len - 1] = d[0] else: saved_roll_dict[start_idx + half_seqlen + remain_len - 1] = d[remain_end] if need_roll: input_ids_rmpad = torch.roll(input_ids_rmpad, shifts=-1, dims=0) if len(saved_roll_dict) > 0: for k, v in saved_roll_dict.items(): input_ids_rmpad[k] = v packed_seq_params = PackedSeqParams( qkv_format="thd", cu_seqlens_q=cu_seqlens_padded, max_seqlen_q=max_seqlen_in_batch, cu_seqlens_kv=cu_seqlens_padded, max_seqlen_kv=max_seqlen_in_batch, cu_seqlens_q_padded=cu_seqlens_padded, cu_seqlens_kv_padded=cu_seqlens_padded, ) if pre_process: return input_ids_rmpad.unsqueeze(0), packed_seq_params else: return input_ids, packed_seq_params def postprocess_thd_no_padding( output: torch.Tensor, packed_seq_params: PackedSeqParams, input_ids: torch.Tensor, batch_size: int, post_process: bool = True, ) -> torch.Tensor: """ Postprocess packed sequences """ if not post_process: return output # ------------------------------------------------------------------------- # Move the lengths and offsets needed for subsequent Python-level indexing to the CPU in advance, # to avoid a large number of .item() calls in the loop # ------------------------------------------------------------------------- cu_padded_cpu: list[int] = packed_seq_params.cu_seqlens_q_padded.tolist() # The reason why we use input_ids.offsets() instead of packed_seq_params.cu_seqlens_q.diff() # is that the latter one is the padded length, while the former one is the original length. cu_seqlens = input_ids.offsets() seq_lens_cpu: list[int] = cu_seqlens.diff().tolist() output_new = [] cp_size = mpu.get_context_parallel_world_size() # all gather output across context parallel group if cp_size > 1: # output shape: [1, packed_len, hidden_dim] # need to gather across cp group and concatenate in sequence dimension output_list = [torch.empty_like(output) for _ in range(cp_size)] torch.distributed.all_gather(output_list, output.detach(), group=mpu.get_context_parallel_group()) output_list[mpu.get_context_parallel_rank()] = output else: output_list = [output] for i in range(batch_size): if cp_size <= 1: s = seq_lens_cpu[i] start_idx = cu_padded_cpu[i] output_new.append(output[0][start_idx : start_idx + s]) continue s_len_padded_chunk = (cu_padded_cpu[i + 1] - cu_padded_cpu[i]) // cp_size half_seqlen = s_len_padded_chunk // 2 s_len = seq_lens_cpu[i] s_len_padded = s_len_padded_chunk * cp_size tmp = torch.empty(s_len_padded, *output.shape[2:], device=output.device) for j in range(cp_size): o = output_list[j][0] # split to 2 chunks packed_start_idx = cu_padded_cpu[i] // cp_size o0, o1 = ( o[packed_start_idx : packed_start_idx + half_seqlen], o[packed_start_idx + half_seqlen : packed_start_idx + s_len_padded_chunk], ) tmp[j * half_seqlen : (j + 1) * half_seqlen] = o0 tmp[s_len_padded - (j + 1) * half_seqlen : s_len_padded - j * half_seqlen] = o1 output_new.append(tmp[:s_len]) output_new_tensor = torch.nested.as_nested_tensor(output_new, layout=torch.jagged) return output_new_tensor def preprocess_bshd_no_padding(input_ids: torch.Tensor, pre_process: bool = True, need_roll: bool = False): """ Preprocess bshd sequences return "input_ids, attention_mask, position_ids" """ cp_size = mpu.get_context_parallel_world_size() # TODO: support context parallel size > 1 assert cp_size == 1, "Context parallel size without bshd is not supported yet" batch_size = input_ids.shape[0] seqlens_in_batch = input_ids.offsets().diff() max_seqlen = seqlens_in_batch.max().item() if mpu.get_tensor_model_parallel_world_size() > 1: sp_world_size = mpu.get_tensor_model_parallel_world_size() pad_size = (sp_world_size - max_seqlen % sp_world_size) % sp_world_size max_seqlen = max_seqlen + pad_size attention_mask = torch.zeros(batch_size, max_seqlen, dtype=torch.bool, device=input_ids.device) input_ids_bshd = torch.zeros(batch_size, max_seqlen, dtype=input_ids.dtype, device=input_ids.device) for i in range(batch_size): attention_mask[i, : seqlens_in_batch[i]] = True input_ids_bshd[i, : seqlens_in_batch[i]] = input_ids[i] position_ids = torch.arange(max_seqlen, dtype=torch.long, device=input_ids.device) position_ids = position_ids.unsqueeze(0).expand_as(input_ids_bshd) if need_roll: input_ids_bshd = torch.roll(input_ids_bshd, shifts=-1, dims=1) return input_ids_bshd, attention_mask, position_ids def postprocess_bshd_no_padding( output: torch.Tensor, attention_mask: torch.Tensor, post_process: bool = True, ) -> torch.Tensor: """ Postprocess bshd sequences """ if not post_process: return output batch_size = output.shape[0] output_new = [] for i in range(batch_size): mask = attention_mask[i].bool() output_new.append(output[i][mask]) output_new_tensor = torch.nested.as_nested_tensor(output_new, layout=torch.jagged) return output_new_tensor
verl__models__mcore__util.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # online convert mcore weight to pure huggingface weight, no any fusion # including format conversion and name mapping # not including resharding import torch from megatron.core.transformer import TransformerConfig from transformers import PretrainedConfig class McoreToHFWeightConverterBase: def __init__(self, hf_config: PretrainedConfig, mcore_config: TransformerConfig): self.hf_config = hf_config self.mcore_config = mcore_config def convert_param(self, name: str, params_one_group: list[torch.Tensor]) -> torch.Tensor: raise NotImplementedError class McoreToHFWeightConverterDense(McoreToHFWeightConverterBase): def _convert_attention_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: # 'decoder.layers.0.self_attention.linear_proj.weight' # 'decoder.layers.0.self_attention.linear_qkv.layer_norm_weight' # 'decoder.layers.0.self_attention.linear_qkv.weight' # 'decoder.layers.0.self_attention.linear_qkv.bias' layer_number = name.split(".")[2] convert_names = [] if "self_attention.linear_qkv.bias" in name or "self_attention.linear_qkv.weight" in name: param_type = name.split(".")[-1] assert param_type == "bias" or param_type == "weight" convert_names.append(f"model.layers.{layer_number}.self_attn.q_proj.{param_type}") convert_names.append(f"model.layers.{layer_number}.self_attn.k_proj.{param_type}") convert_names.append(f"model.layers.{layer_number}.self_attn.v_proj.{param_type}") assert len(params) == 3 elif "self_attention.linear_proj.weight" in name: convert_names.append(f"model.layers.{layer_number}.self_attn.o_proj.weight") assert len(params) == 1 elif "self_attention.linear_qkv.layer_norm_weight" in name: convert_names.append(f"model.layers.{layer_number}.input_layernorm.weight") assert len(params) == 1 elif "self_attention.q_layernorm.weight" in name: convert_names.append(f"model.layers.{layer_number}.self_attn.q_norm.weight") assert len(params) == 1 elif "self_attention.k_layernorm.weight" in name: convert_names.append(f"model.layers.{layer_number}.self_attn.k_norm.weight") assert len(params) == 1 else: raise NotImplementedError(f"Unsupported parameter name: {name}") return convert_names, params def _convert_mlp_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: # 'decoder.layers.0.mlp.linear_fc1.layer_norm_weight' # 'decoder.layers.0.mlp.linear_fc1.weight' # 'decoder.layers.0.mlp.linear_fc2.weight' layer_number = name.split(".")[2] convert_names = [] if "mlp.linear_fc1.weight" in name: # split gate_proj and up_proj convert_names.append(f"model.layers.{layer_number}.mlp.gate_proj.weight") convert_names.append(f"model.layers.{layer_number}.mlp.up_proj.weight") assert len(params) == 2 elif "mlp.linear_fc1.layer_norm_weight" in name: convert_names.append(f"model.layers.{layer_number}.post_attention_layernorm.weight") assert len(params) == 1 elif "mlp.linear_fc2.weight" in name: convert_names.append(f"model.layers.{layer_number}.mlp.down_proj.weight") assert len(params) == 1 else: raise NotImplementedError(f"Unsupported parameter name: {name}") return convert_names, params def convert_param(self, name: str, params_one_group: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: direct_name_mapping = { "embedding.word_embeddings.weight": "model.embed_tokens.weight", "decoder.final_layernorm.weight": "model.norm.weight", "output_layer.weight": "lm_head.weight", } if name in direct_name_mapping: return [direct_name_mapping[name]], [params_one_group[0]] if "self_attention" in name: return self._convert_attention_param(name, params_one_group) elif "mlp" in name: return self._convert_mlp_param(name, params_one_group) else: raise NotImplementedError(f"Unsupported parameter name: {name}") class McoreToHFWeightConverterQwen2Moe(McoreToHFWeightConverterDense): def _convert_mlp_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: # 'decoder.layers.0.pre_mlp_layernorm.weight', # 'decoder.layers.0.mlp.router.weight', # 'decoder.layers.0.mlp.shared_experts.gate_weight', # 'decoder.layers.0.mlp.shared_experts.linear_fc1.weight', # 'decoder.layers.0.mlp.shared_experts.linear_fc2.weight' # moe1 # 'decoder.layers.0.mlp.experts.linear_fc1.weight0', # 'decoder.layers.0.mlp.experts.linear_fc1.weight1', # 'decoder.layers.0.mlp.experts.linear_fc1.weight2', # 'decoder.layers.0.mlp.experts.linear_fc1.weight3', # moe2 # 'decoder.layers.0.mlp.experts.linear_fc2.weight0', # 'decoder.layers.0.mlp.experts.linear_fc2.weight1', layer_number = name.split(".")[2] convert_names = [] if "pre_mlp_layernorm" in name: convert_names.append(f"model.layers.{layer_number}.post_attention_layernorm.weight") assert len(params) == 1 elif "mlp.router.weight" in name: convert_names.append(f"model.layers.{layer_number}.mlp.gate.weight") assert len(params) == 1 elif "shared_experts.gate_weight" in name: convert_names.append(f"model.layers.{layer_number}.mlp.shared_expert_gate.weight") assert len(params) == 1 elif "shared_experts.linear_fc1.weight" in name: # split gate_proj and up_proj convert_names.append(f"model.layers.{layer_number}.mlp.shared_expert.gate_proj.weight") convert_names.append(f"model.layers.{layer_number}.mlp.shared_expert.up_proj.weight") assert len(params) == 2 elif "shared_experts.linear_fc2.weight" in name: convert_names.append(f"model.layers.{layer_number}.mlp.shared_expert.down_proj.weight") assert len(params) == 1 elif "mlp.experts.linear_fc1" in name: # split gate_proj and up_proj expert_id = name.split("weight")[-1] convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.gate_proj.weight") convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.up_proj.weight") assert len(params) == 2 elif "mlp.experts.linear_fc2" in name: expert_id = name.split("weight")[-1] convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.down_proj.weight") assert len(params) == 1 else: raise NotImplementedError(f"Unsupported parameter name: {name}") return convert_names, params class McoreToHFWeightConverterQwen2_5_VL(McoreToHFWeightConverterDense): def convert_param(self, name: str, params_one_group: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: direct_name_mapping = { "language_model.embedding.word_embeddings.weight": "model.embed_tokens.weight", "language_model.decoder.final_layernorm.weight": "model.norm.weight", "language_model.output_layer.weight": "lm_head.weight", "vision_model.patch_embed.proj.weight": "visual.patch_embed.proj.weight", "vision_model.decoder.final_layernorm.weight": "visual.merger.ln_q.weight", "vision_model.projection.encoder.linear_fc1.weight": "visual.merger.mlp.0.weight", "vision_model.projection.encoder.linear_fc1.bias": "visual.merger.mlp.0.bias", "vision_model.projection.encoder.linear_fc2.weight": "visual.merger.mlp.2.weight", "vision_model.projection.encoder.linear_fc2.bias": "visual.merger.mlp.2.bias", } if name in direct_name_mapping: return [direct_name_mapping[name]], [params_one_group[0]] if "self_attention" in name: return self._convert_attention_param(name, params_one_group) elif "mlp" in name: return self._convert_mlp_param(name, params_one_group) else: raise NotImplementedError(f"Unsupported parameter name: {name}") def _convert_attention_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: model_type, _, _, layer_number = name.split(".")[:4] convert_names = [] if model_type == "language_model": name_map_after_layer = { "self_attention.linear_qkv.bias": [ "self_attn.q_proj.bias", "self_attn.k_proj.bias", "self_attn.v_proj.bias", ], "self_attention.linear_qkv.weight": [ "self_attn.q_proj.weight", "self_attn.k_proj.weight", "self_attn.v_proj.weight", ], "self_attention.linear_proj.weight": "self_attn.o_proj.weight", "self_attention.linear_qkv.layer_norm_weight": "input_layernorm.weight", } name_after_layer = ".".join(name.split(".")[-3:]) mapped_name = name_map_after_layer.get(name_after_layer) if isinstance(mapped_name, list): assert len(params) == len(mapped_name) for one in mapped_name: convert_names.append(f"model.layers.{layer_number}.{one}") else: assert len(params) == 1 convert_names.append(f"model.layers.{layer_number}.{mapped_name}") elif model_type == "vision_model": name_map_after_layer = { "self_attention.linear_proj.weight": "attn.proj.weight", "self_attention.linear_proj.bias": "attn.proj.bias", "self_attention.linear_qkv.layer_norm_weight": "norm1.weight", } name_after_layer = ".".join(name.split(".")[-3:]) mapped_name = name_map_after_layer.get(name_after_layer, None) if mapped_name is None: assert "linear_qkv" in name_after_layer assert len(params) == 3 new_param = torch.cat(params, dim=0) params = [new_param] if "bias" in name_after_layer: convert_names.append(f"visual.blocks.{layer_number}.attn.qkv.bias") else: convert_names.append(f"visual.blocks.{layer_number}.attn.qkv.weight") else: assert len(params) == 1 convert_names.append(f"visual.blocks.{layer_number}.{mapped_name}") else: raise NotImplementedError(f"Unsupported model type: {model_type}") return convert_names, params def _convert_mlp_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: model_type, _, _, layer_number = name.split(".")[:4] convert_names = [] if model_type == "language_model": name_map_after_layer = { "mlp.linear_fc1.weight": ["mlp.gate_proj.weight", "mlp.up_proj.weight"], "mlp.linear_fc1.bias": ["mlp.gate_proj.bias", "mlp.up_proj.bias"], "mlp.linear_fc2.weight": "mlp.down_proj.weight", "mlp.linear_fc2.bias": "mlp.down_proj.bias", "mlp.linear_fc1.layer_norm_weight": "post_attention_layernorm.weight", } name_after_layer = ".".join(name.split(".")[-3:]) mapped_name = name_map_after_layer.get(name_after_layer) if isinstance(mapped_name, list): assert len(params) == len(mapped_name) for one in mapped_name: convert_names.append(f"model.layers.{layer_number}.{one}") else: assert len(params) == 1 convert_names.append(f"model.layers.{layer_number}.{mapped_name}") elif model_type == "vision_model": name_map_after_layer = { "mlp.linear_fc1.weight": ["mlp.gate_proj.weight", "mlp.up_proj.weight"], "mlp.linear_fc1.bias": ["mlp.gate_proj.bias", "mlp.up_proj.bias"], "mlp.linear_fc2.weight": "mlp.down_proj.weight", "mlp.linear_fc2.bias": "mlp.down_proj.bias", "mlp.linear_fc1.layer_norm_weight": "norm2.weight", } name_after_layer = ".".join(name.split(".")[-3:]) mapped_name = name_map_after_layer.get(name_after_layer) if isinstance(mapped_name, list): assert len(params) == len(mapped_name) for one in mapped_name: convert_names.append(f"visual.blocks.{layer_number}.{one}") else: assert len(params) == 1 convert_names.append(f"visual.blocks.{layer_number}.{mapped_name}") else: raise NotImplementedError(f"Unsupported model type: {model_type}") return convert_names, params class McoreToHFWeightConverterDpskv3(McoreToHFWeightConverterBase): def _convert_attention_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: # mcore # 'decoder.layers.0.input_layernorm.weight' # 'decoder.layers.0.self_attention.linear_proj.weight' # 'decoder.layers.0.self_attention.linear_q_proj.weight' # 'decoder.layers.0.self_attention.linear_kv_down_proj.weight' # 'decoder.layers.0.self_attention.linear_kv_up_proj.layer_norm_weight' # 'decoder.layers.0.self_attention.linear_kv_up_proj.weight' # 'decoder.layers.0.self_attention.linear_q_down_proj.weight' # 'decoder.layers.0.self_attention.linear_q_up_proj.weight' # 'decoder.layers.0.self_attention.linear_q_up_proj.layer_norm_weight' # hf # 'model.layers.0.input_layernorm.weight' # 'model.layers.0.self_attn.o_proj.weight' # 'model.layers.0.self_attn.q_proj.weight' # 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight' # 'model.layers.0.self_attn.kv_a_layernorm.weight' # 'model.layers.0.self_attn.kv_b_proj.weight' # 'model.layers.0.self_attn.q_a_proj.weight' # 'model.layers.0.self_attn.q_b_proj.weight' # 'model.layers.0.self_attn.q_a_layernorm.weight' name_map_after_layer = { "input_layernorm.weight": "input_layernorm.weight", "self_attention.linear_proj.weight": "self_attn.o_proj.weight", "self_attention.linear_q_proj.weight": "self_attn.q_proj.weight", "self_attention.linear_kv_down_proj.weight": "self_attn.kv_a_proj_with_mqa.weight", "self_attention.linear_kv_up_proj.layer_norm_weight": "self_attn.kv_a_layernorm.weight", "self_attention.linear_kv_up_proj.weight": "self_attn.kv_b_proj.weight", "self_attention.linear_q_down_proj.weight": "self_attn.q_a_proj.weight", "self_attention.linear_q_up_proj.weight": "self_attn.q_b_proj.weight", "self_attention.linear_q_up_proj.layer_norm_weight": "self_attn.q_a_layernorm.weight", } assert len(params) == 1 convert_names = [] layer_number = name.split(".")[2] name_after_layer = name.split(f".{layer_number}.")[1] convert_names.append(f"model.layers.{layer_number}.{name_map_after_layer[name_after_layer]}") return convert_names, params def _convert_mlp_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: # mcore dense # 'decoder.layers.0.mlp.linear_fc1.layer_norm_weight' # 'decoder.layers.0.mlp.linear_fc2.weight' # 'decoder.layers.0.mlp.linear_fc1.weight' # --- # 'decoder.layers.1.mlp.shared_experts.linear_fc1.weight' # --- # 'decoder.layers.1.mlp.shared_experts.linear_fc2.weight' # hf dense # 'model.layers.0.post_attention_layernorm.weight' # 'model.layers.0.mlp.down_proj.weight' # 'model.layers.0.mlp.gate_proj.weight' # 'model.layers.0.mlp.up_proj.weight' # 'model.layers.1.mlp.shared_experts.gate_proj.weight' # 'model.layers.1.mlp.shared_experts.up_proj.weight' # 'model.layers.1.mlp.shared_experts.down_proj.weight' # mcore moe # 'decoder.layers.1.pre_mlp_layernorm.weight' # 'decoder.layers.1.mlp.router.weight' # 'decoder.layers.1.mlp.router.expert_bias' # 'decoder.layers.1.mlp.experts.linear_fc1.weight0' # --- # 'decoder.layers.1.mlp.experts.linear_fc2.weight0' # hf moe # 'model.layers.1.post_attention_layernorm.weight' # 'model.layers.1.mlp.gate.weight' # 'model.layers.1.mlp.gate.e_score_correction_bias' # 'model.layers.1.mlp.experts.0.gate_proj.weight' # 'model.layers.1.mlp.experts.0.up_proj.weight' # 'model.layers.1.mlp.experts.0.down_proj.weight' name_map_after_layer = { "mlp.linear_fc1.layer_norm_weight": "post_attention_layernorm.weight", "mlp.linear_fc2.weight": "mlp.down_proj.weight", "mlp.shared_experts.linear_fc2.weight": "mlp.shared_experts.down_proj.weight", "mlp.linear_fc1.weight": ["mlp.gate_proj.weight", "mlp.up_proj.weight"], "mlp.shared_experts.linear_fc1.weight": [ "mlp.shared_experts.gate_proj.weight", "mlp.shared_experts.up_proj.weight", ], "pre_mlp_layernorm.weight": "post_attention_layernorm.weight", "mlp.router.weight": "mlp.gate.weight", "mlp.router.expert_bias": "mlp.gate.e_score_correction_bias", } convert_names = [] layer_number = name.split(".")[2] name_after_layer = name.split(f".{layer_number}.")[1] if name_after_layer in name_map_after_layer: mapped_name = name_map_after_layer[name_after_layer] if isinstance(mapped_name, list): assert len(params) == len(mapped_name) for one in mapped_name: convert_names.append(f"model.layers.{layer_number}.{one}") else: assert len(params) == 1 convert_names.append(f"model.layers.{layer_number}.{mapped_name}") else: if "mlp.experts.linear_fc1.weight" in name: expert_id = name.split("weight")[-1] convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.gate_proj.weight") convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.up_proj.weight") assert len(params) == 2 elif "mlp.experts.linear_fc2.weight" in name: expert_id = name.split("weight")[-1] convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.down_proj.weight") assert len(params) == 1 else: raise NotImplementedError(f"Unsupported parameter name: {name}") return convert_names, params def _convert_mtp_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: assert self.mcore_config.mtp_num_layers == 1, "only support one mtp layer for now" assert self.mcore_config.num_layers == 61, "only support 61 layers for now" direct_name_mapping = { "mtp.layers.0.enorm.weight": "model.layers.61.enorm.weight", "mtp.layers.0.hnorm.weight": "model.layers.61.hnorm.weight", "mtp.layers.0.eh_proj.weight": "model.layers.61.eh_proj.weight", "mtp.layers.0.final_layernorm.weight": "model.layers.61.shared_head.norm.weight", } if name in direct_name_mapping: return [direct_name_mapping[name]], [params[0]] assert "mtp.layers.0.transformer_layer" in name, "only support transformer layer for now" # use proxy name to convert proxy_name = name.replace("mtp.layers.0.transformer_layer", "decoder.layers.61") if "self_attention" in proxy_name or "input_layernorm.weight" in proxy_name: convert_names, params = self._convert_attention_param(proxy_name, params) elif "mlp" in proxy_name: convert_names, params = self._convert_mlp_param(proxy_name, params) else: raise NotImplementedError(f"Unsupported parameter name: {name}") return convert_names, params def convert_param(self, name: str, params_one_group: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: direct_name_mapping = { "embedding.word_embeddings.weight": "model.embed_tokens.weight", "decoder.final_layernorm.weight": "model.norm.weight", "output_layer.weight": "lm_head.weight", } if name in direct_name_mapping: return [direct_name_mapping[name]], [params_one_group[0]] if "mtp" in name: return self._convert_mtp_param(name, params_one_group) elif "self_attention" in name or "input_layernorm.weight" in name: return self._convert_attention_param(name, params_one_group) elif "mlp" in name: return self._convert_mlp_param(name, params_one_group) else: raise NotImplementedError(f"Unsupported parameter name: {name}") class McoreToHFWeightConverterMixtral(McoreToHFWeightConverterDense): def _convert_mlp_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: # decoder.layers.0.mlp.router.weight # decoder.layers.0.mlp.experts.linear_fc1.weight0 - weight7 # decoder.layers.0.mlp.experts.linear_fc2.weight0 - weight7 layer_number = name.split(".")[2] convert_names = [] if "pre_mlp_layernorm" in name: convert_names.append(f"model.layers.{layer_number}.post_attention_layernorm.weight") elif "mlp.router.weight" in name: convert_names.append(f"model.layers.{layer_number}.block_sparse_moe.gate.weight") elif "mlp.experts.linear_fc1.weight" in name: expert_id = name.split("weight")[-1] convert_names.append(f"model.layers.{layer_number}.block_sparse_moe.experts.{expert_id}.w1.weight") convert_names.append(f"model.layers.{layer_number}.block_sparse_moe.experts.{expert_id}.w3.weight") elif "mlp.experts.linear_fc2.weight" in name: expert_id = name.split("weight")[-1] convert_names.append(f"model.layers.{layer_number}.block_sparse_moe.experts.{expert_id}.w2.weight") else: raise NotImplementedError(f"Unsupported parameter name: {name}") return convert_names, params class McoreToHFWeightConverterQwen3Moe(McoreToHFWeightConverterDense): def _convert_mlp_param(self, name: str, params: list[torch.Tensor]) -> tuple[list[str], list[torch.Tensor]]: # qwen3 moe no share expert # 'decoder.layers.0.pre_mlp_layernorm.weight', # 'decoder.layers.0.mlp.router.weight', # moe1 # 'decoder.layers.0.mlp.experts.linear_fc1.weight0', # 'decoder.layers.0.mlp.experts.linear_fc1.weight1', # 'decoder.layers.0.mlp.experts.linear_fc1.weight2', # 'decoder.layers.0.mlp.experts.linear_fc1.weight3', # moe2 # 'decoder.layers.0.mlp.experts.linear_fc2.weight0', # 'decoder.layers.0.mlp.experts.linear_fc2.weight1', layer_number = name.split(".")[2] convert_names = [] if "pre_mlp_layernorm" in name: convert_names.append(f"model.layers.{layer_number}.post_attention_layernorm.weight") assert len(params) == 1 elif "mlp.router.weight" in name: convert_names.append(f"model.layers.{layer_number}.mlp.gate.weight") assert len(params) == 1 elif "mlp.experts.linear_fc1" in name: # split gate_proj and up_proj expert_id = name.split("weight")[-1] convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.gate_proj.weight") convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.up_proj.weight") assert len(params) == 2 elif "mlp.experts.linear_fc2" in name: expert_id = name.split("weight")[-1] convert_names.append(f"model.layers.{layer_number}.mlp.experts.{expert_id}.down_proj.weight") assert len(params) == 1 else: raise NotImplementedError(f"Unsupported parameter name: {name}") return convert_names, params
verl__models__mcore__weight_converter.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import torch import torch.distributed as dist from verl.utils.device import get_device_id, get_torch_device def _megatron_calc_layer_map(config): """Calculate the mapping of global layer_idx to local layer_idx Returns: layer_map (Dict: int -> tuple(int, int, int)): mapping from the global layer index to a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model) """ from megatron.core import mpu pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 layer_map = dict() num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers for pp_rank_idx in range(pp_size): for virtual_pp_rank_idx in range(virtual_pp_size): layer_offset = ( virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model ) for layer_idx in range(num_layers_per_model): layer_map[layer_offset + layer_idx] = ( pp_rank_idx, virtual_pp_rank_idx, layer_idx, ) return layer_map def load_state_dict_to_megatron_qwen2( state_dict, wrapped_models, config, params_dtype, is_value_model=False, tie_word_embeddings=False ): """Load merged state_dict to sharded Megatron module in training.""" from megatron.core import DistributedDataParallel as LocalDDP from megatron.core import mpu from megatron.core.transformer.module import Float16Module from torch.nn.parallel import DistributedDataParallel as torchDDP from verl.utils.logger import print_rank_0 from verl.utils.megatron_utils import unwrap_model start_time = time.time() def _get_gpt_model(model): return model def fetch_params(module): for param in module.parameters(): torch.distributed.fetch( param.data, src=mpu.get_data_parallel_src_rank(), group=mpu.get_data_parallel_group() ) dp_rank = mpu.get_data_parallel_rank() pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 mp_group = mpu.get_model_parallel_group() if torch.distributed.get_rank() == 0: assert mp_group.rank() == 0, f"mp_rank:[{mp_group.rank}] != 0 on rank #0" assert pp_rank == 0, f"pp_rank:[{pp_rank}] != 0 on rank #0" assert dp_rank == 0, f"dp_rank:[{dp_rank}] != 0 on rank #0" if not isinstance(wrapped_models, list | tuple): wrapped_models = list(wrapped_models) assert len(wrapped_models) == virtual_pp_size num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers, ( f"num_layers_per_model: {num_layers_per_model} * pp_size: {pp_size} * virtual_pp_size: " f"{virtual_pp_size} != config.num_hidden_layers: {config.num_hidden_layers}" ) models = [None] * len(wrapped_models) for i, wrapped_model in enumerate(wrapped_models): models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module)) gpt_model_module = _get_gpt_model(models[i]) assert len(gpt_model_module.model.layers) == num_layers_per_model def _fetch_tensor(tensor, name) -> torch.Tensor: """fetch tensor""" nonlocal state_dict if tensor is not None: tensor = tensor.data.copy_(state_dict[name], non_blocking=True) def _fetch_tp_shard_tensor_vocab(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """fetch tensor in tp shards""" nonlocal state_dict tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) if tensor is not None: tensor = tensor.data.copy_(tensor_chunk[tp_rank], non_blocking=True) else: print(f"tp_shard tensor:[{name}] not in state_dict, skip loading") def _fetch_tp_shard_tensor(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """fetch tensor in tp shards""" nonlocal state_dict tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) if tensor is not None: tensor = tensor.data.copy_(tensor_chunk[tp_rank], non_blocking=True) else: print(f"tp_shard tensor:[{name}] not in state_dict, skip loading") def _fetch_tp_shard_tensor_gate_up(tensor, gate_name, up_name) -> torch.Tensor: """fetch gate_up tensor in tp shards""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if gate_name in state_dict and up_name in state_dict: gate_weight = state_dict[gate_name] up_weight = state_dict[up_name] new_gate_up_weight = torch.empty( config.intermediate_size * 2, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): intermediate_size_tp = config.intermediate_size // tp_size gate_weight_tp = gate_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] up_weight_tp = up_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] new_gate_up_weight[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)].copy_( torch.cat([gate_weight_tp, up_weight_tp], dim=0) ) tensor_chunk = torch.chunk(new_gate_up_weight, tp_size, dim=0) if tensor is not None: tensor = tensor.data.copy_(tensor_chunk[tp_rank], non_blocking=True) else: print(f"tp_shard tensor:[{gate_name}, {up_name}] not in state_dict, skip loading") def _fetch_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, bias=False) -> torch.Tensor: """fetch tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() assert q_name in state_dict and k_name in state_dict and v_name in state_dict full_weight_q = state_dict[q_name] full_weight_k = state_dict[k_name] full_weight_v = state_dict[v_name] hidden_size_per_head = config.hidden_size // config.num_attention_heads if config.num_key_value_heads >= tp_size: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size total_size = q_size_tp + 2 * kv_size_tp if not bias: new_weight_qkv = torch.empty( total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id() ) else: new_weight_qkv = torch.empty(total_size * tp_size, dtype=params_dtype, device=get_device_id()) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] k_part = full_weight_k[i * kv_size_tp : (i + 1) * kv_size_tp] v_part = full_weight_v[i * kv_size_tp : (i + 1) * kv_size_tp] new_weight_qkv[i * total_size : (i + 1) * total_size].copy_(torch.cat([q_part, k_part, v_part], dim=0)) else: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head total_size = q_size_tp + 2 * kv_size_tp if not bias: new_weight_qkv = torch.empty( total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id() ) else: new_weight_qkv = torch.empty(total_size * tp_size, dtype=params_dtype, device=get_device_id()) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] start_idx = i * config.num_key_value_heads // tp_size * hidden_size_per_head end_idx = (i * config.num_key_value_heads // tp_size + 1) * hidden_size_per_head k_part = full_weight_k[start_idx:end_idx] v_part = full_weight_v[start_idx:end_idx] new_weight_qkv[i * total_size : (i + 1) * total_size].copy_(torch.cat([q_part, k_part, v_part], dim=0)) tensor_chunk = torch.chunk(new_weight_qkv, tp_size, dim=0) if tensor is not None: tensor = tensor.data.copy_(tensor_chunk[tp_rank], non_blocking=True) # Embeddings # ------------------- print_rank_0("loading embeddings...") gpt_model_module = _get_gpt_model(models[0]) if pp_rank == 0: embed_tokens_weight = gpt_model_module.model.embed_tokens.weight _fetch_tp_shard_tensor_vocab(embed_tokens_weight, "model.embed_tokens.weight") # Transformer layers # ------------------- layer_map = _megatron_calc_layer_map(config) pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() num_layer_per_pp = config.num_hidden_layers // pp_size vpp_size = mpu.get_virtual_pipeline_model_parallel_world_size() layer_list = [] if vpp_size is not None: for vpp_rank in range(vpp_size): num_layer_vpp_chunk = num_layer_per_pp // vpp_size num_layer_this_model = num_layer_vpp_chunk offset = vpp_rank * (config.num_hidden_layers // mpu.get_virtual_pipeline_model_parallel_world_size()) + ( mpu.get_pipeline_model_parallel_rank() * num_layer_vpp_chunk ) layer_list.extend(list(range(offset, offset + num_layer_this_model))) else: num_layer_this_model = num_layer_per_pp offset = pp_rank * num_layer_per_pp layer_list.extend(list(range(offset, offset + num_layer_this_model))) for layer in layer_list: print(f"{torch.distributed.get_rank()} loading layer #{layer}...") layer_name = f"model.layers.{layer}" dst_pp_rank, dst_virtual_pp_rank, dst_layer_idx = layer_map[layer] print( f"{torch.distributed.get_rank()} offset: {offset}, num_layer_this_model: {num_layer_this_model}, " f"layer_name: {layer_name}, layer_map[layer]: {layer_map[layer]}" ) gpt_model_module = _get_gpt_model(models[dst_virtual_pp_rank]) sync_layer = gpt_model_module.model.layers[dst_layer_idx] _fetch_tensor( sync_layer.input_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.input_layernorm.weight", ) _fetch_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_proj.weight", f"{layer_name}.self_attn.k_proj.weight", f"{layer_name}.self_attn.v_proj.weight", ) _fetch_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.bias if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_proj.bias", f"{layer_name}.self_attn.k_proj.bias", f"{layer_name}.self_attn.v_proj.bias", bias=True, ) _fetch_tp_shard_tensor( sync_layer.self_attn.o_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.o_proj.weight", chunk_dim=1, ) _fetch_tensor( sync_layer.post_attention_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.post_attention_layernorm.weight", ) _fetch_tp_shard_tensor_gate_up( sync_layer.mlp.gate_up_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.gate_proj.weight", f"{layer_name}.mlp.up_proj.weight", ) _fetch_tp_shard_tensor( sync_layer.mlp.down_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.down_proj.weight", chunk_dim=1, ) # Final Layernorm # ------------------- print_rank_0("loading final layernorm...") gpt_model_module = _get_gpt_model(models[-1]) _fetch_tensor( getattr(gpt_model_module.model.norm, "weight", None), "model.norm.weight", ) if tie_word_embeddings: print_rank_0("tie_word_embeddings skip load lm_head") else: print_rank_0("loading lm_head...") if pp_rank + 1 == pp_size: lm_head_weight = gpt_model_module.lm_head.weight if is_value_model: if "lm_head.weight" in state_dict and state_dict["lm_head.weight"].shape[0] == 1: _fetch_tensor(lm_head_weight, "lm_head.weight") print_rank_0("load lm_head from value_head weight") elif "reward_head.weight" in state_dict and state_dict["reward_head.weight"].shape[0] == 1: _fetch_tensor(lm_head_weight, "reward_head.weight") print_rank_0("load lm_head from value_head weight") else: _fetch_tensor(None, "lm_head.weight") print_rank_0("fail to match lm_head in value_model") else: _fetch_tp_shard_tensor(lm_head_weight, "lm_head.weight") dist.barrier() get_torch_device().empty_cache() print_rank_0(f"loading megatron ckpt done, time elapsed {time.time() - start_time}s")
verl__models__qwen2__megatron__checkpoint_utils__qwen2_loader.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import torch import torch.distributed as dist from verl.utils.device import get_device_id, get_torch_device def _megatron_calc_layer_map(config): """Calculate the mapping of global layer_idx to local layer_idx Returns: layer_map (Dict: int -> tuple(int, int, int)): mapping from the global layer index to a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model) """ from megatron.core import mpu pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 layer_map = dict() num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers for pp_rank_idx in range(pp_size): for virtual_pp_rank_idx in range(virtual_pp_size): layer_offset = ( virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model ) for layer_idx in range(num_layers_per_model): layer_map[layer_offset + layer_idx] = ( pp_rank_idx, virtual_pp_rank_idx, layer_idx, ) return layer_map def load_state_dict_to_megatron_qwen2( state_dict, wrapped_models, config, params_dtype, is_value_model=False, tie_word_embeddings=False ): """Load merged state_dict to sharded Megatron module in training.""" from megatron.core import DistributedDataParallel as LocalDDP from megatron.core import mpu from megatron.core.transformer.module import Float16Module from torch.nn.parallel import DistributedDataParallel as torchDDP from verl.utils.logger import print_rank_0 from verl.utils.megatron_utils import unwrap_model start_time = time.time() def _get_gpt_model(model): return model def broadcast_params(module): for param in module.parameters(): torch.distributed.broadcast( param.data, src=mpu.get_data_parallel_src_rank(), group=mpu.get_data_parallel_group() ) dp_rank = mpu.get_data_parallel_rank() pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 mp_group = mpu.get_model_parallel_group() if torch.distributed.get_rank() == 0: assert mp_group.rank() == 0, f"mp_rank:[{mp_group.rank}] != 0 on rank #0" assert pp_rank == 0, f"pp_rank:[{pp_rank}] != 0 on rank #0" assert dp_rank == 0, f"dp_rank:[{dp_rank}] != 0 on rank #0" if not isinstance(wrapped_models, list | tuple): wrapped_models = list(wrapped_models) assert len(wrapped_models) == virtual_pp_size num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers, ( f"num_layers_per_model: {num_layers_per_model} * pp_size: {pp_size} * virtual_pp_size: " f"{virtual_pp_size} != config.num_hidden_layers: {config.num_hidden_layers}" ) models = [None] * len(wrapped_models) for i, wrapped_model in enumerate(wrapped_models): models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module)) gpt_model_module = _get_gpt_model(models[i]) assert len(gpt_model_module.model.layers) == num_layers_per_model def _broadcast_tensor(tensor, name) -> torch.Tensor: """broadcast tensor from rank0 across mp_group""" nonlocal state_dict nonlocal mp_group if torch.distributed.get_rank() == 0: if name in state_dict: weight = state_dict[name] tensor_shape = weight.shape else: tensor_shape = None else: weight = None tensor_shape = None obj_list = [tensor_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) tensor_shape = obj_list[0] if tensor_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tensor:[{name}] not in state_dict, skip load") return if tensor is None: tensor = torch.empty( tensor_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) if torch.distributed.get_rank() == 0: tensor.data.copy_(weight) dist.broadcast(tensor, src=0, group=mp_group) def _broadcast_tp_shard_tensor_vocab(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == 0: if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == 0: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=0, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == 0: if name in state_dict: full_weight = state_dict[name] if mutate_func is not None: full_weight = mutate_func(full_weight) tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == 0: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=0, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == 0: gate_weight = state_dict[gate_name] up_weight = state_dict[up_name] new_gate_up_weight = torch.empty( config.intermediate_size * 2, config.hidden_size, dtype=params_dtype, device=get_device_id() ) for i in range(tp_size): intermediate_size_tp = config.intermediate_size // tp_size gate_weight_tp = gate_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] up_weight_tp = up_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp] new_gate_up_weight[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)].copy_( torch.cat([gate_weight_tp, up_weight_tp], dim=0) ) tensor_chunk = torch.chunk(new_gate_up_weight, tp_size, dim=0) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{gate_name, up_name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank() == 0:} tensor {gate_name, up_name} shape " f"{tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == 0: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=0, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, bias=False) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() if torch.distributed.get_rank() == 0: assert q_name in state_dict and k_name in state_dict and v_name in state_dict full_weight_q = state_dict[q_name] full_weight_k = state_dict[k_name] full_weight_v = state_dict[v_name] hidden_size_per_head = config.hidden_size // config.num_attention_heads if config.num_key_value_heads >= tp_size: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size total_size = q_size_tp + 2 * kv_size_tp if not bias: new_weight_qkv = torch.empty( total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id() ) else: new_weight_qkv = torch.empty(total_size * tp_size, dtype=params_dtype, device=get_device_id()) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] k_part = full_weight_k[i * kv_size_tp : (i + 1) * kv_size_tp] v_part = full_weight_v[i * kv_size_tp : (i + 1) * kv_size_tp] new_weight_qkv[i * total_size : (i + 1) * total_size].copy_( torch.cat([q_part, k_part, v_part], dim=0) ) else: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head total_size = q_size_tp + 2 * kv_size_tp if not bias: new_weight_qkv = torch.empty( total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id() ) else: new_weight_qkv = torch.empty(total_size * tp_size, dtype=params_dtype, device=get_device_id()) for i in range(tp_size): q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp] start_idx = i * config.num_key_value_heads // tp_size * hidden_size_per_head end_idx = (i * config.num_key_value_heads // tp_size + 1) * hidden_size_per_head k_part = full_weight_k[start_idx:end_idx] v_part = full_weight_v[start_idx:end_idx] new_weight_qkv[i * total_size : (i + 1) * total_size].copy_( torch.cat([q_part, k_part, v_part], dim=0) ) tensor_chunk = torch.chunk(new_weight_qkv, tp_size, dim=0) chunk_shape = tensor_chunk[0].shape else: chunk_shape = None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=0, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{q_name, k_name, v_name}] not in state_dict, skip loading") return if tensor is None: sync_tensor = torch.empty( chunk_shape, dtype=params_dtype, device=get_device_id(), requires_grad=False, ) else: assert tensor.shape == chunk_shape, ( f"rank #{torch.distributed.get_rank()} tensor {q_name} shape {tensor.shape} != {chunk_shape}" ) sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False) for i in range(tp_size): if torch.distributed.get_rank() == 0: sync_tensor.data.copy_(tensor_chunk[i]) dist.broadcast(sync_tensor, src=0, group=mp_group) if (i == tp_rank) and (tensor is not None): tensor.data.copy_(sync_tensor) if dp_rank == 0: # Embeddings # ------------------- print_rank_0("loading embeddings...") gpt_model_module = _get_gpt_model(models[0]) embed_tokens_weight = None if pp_rank == 0: embed_tokens_weight = gpt_model_module.model.embed_tokens.weight _broadcast_tp_shard_tensor_vocab(embed_tokens_weight, "model.embed_tokens.weight") # Transformer layers # ------------------- layer_map = _megatron_calc_layer_map(config) for layer in range(config.num_hidden_layers): print_rank_0(f"loading layer #{layer}...") layer_name = f"model.layers.{layer}" dst_pp_rank, dst_virtual_pp_rank, dst_layer_idx = layer_map[layer] gpt_model_module = _get_gpt_model(models[dst_virtual_pp_rank]) sync_layer = gpt_model_module.model.layers[dst_layer_idx] _broadcast_tensor( sync_layer.input_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.input_layernorm.weight", ) _broadcast_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_proj.weight", f"{layer_name}.self_attn.k_proj.weight", f"{layer_name}.self_attn.v_proj.weight", ) _broadcast_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.bias if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.q_proj.bias", f"{layer_name}.self_attn.k_proj.bias", f"{layer_name}.self_attn.v_proj.bias", bias=True, ) _broadcast_tp_shard_tensor( sync_layer.self_attn.o_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.self_attn.o_proj.weight", chunk_dim=1, ) _broadcast_tensor( sync_layer.post_attention_layernorm.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.post_attention_layernorm.weight", ) _broadcast_tp_shard_tensor_gate_up( sync_layer.mlp.gate_up_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.gate_proj.weight", f"{layer_name}.mlp.up_proj.weight", ) _broadcast_tp_shard_tensor( sync_layer.mlp.down_proj.weight if dst_pp_rank == pp_rank else None, f"{layer_name}.mlp.down_proj.weight", chunk_dim=1, ) # Final Layernorm # ------------------- print_rank_0("loading final layernorm...") gpt_model_module = _get_gpt_model(models[-1]) _broadcast_tensor( getattr(gpt_model_module.model.norm, "weight", None), "model.norm.weight", ) if tie_word_embeddings: print_rank_0("tie_word_embeddings skip load lm_head") else: print_rank_0("loading lm_head...") lm_head_weight = None if pp_rank + 1 == pp_size: lm_head_weight = gpt_model_module.lm_head.weight if is_value_model: if "lm_head.weight" in state_dict and state_dict["lm_head.weight"].shape[0] == 1: _broadcast_tensor(lm_head_weight, "lm_head.weight") print_rank_0("load lm_head from value_head weight") elif "reward_head.weight" in state_dict and state_dict["reward_head.weight"].shape[0] == 1: _broadcast_tensor(lm_head_weight, "reward_head.weight") print_rank_0("load lm_head from value_head weight") else: _broadcast_tensor(None, "lm_head.weight") print_rank_0("fail to match lm_head in value_model") else: _broadcast_tp_shard_tensor(lm_head_weight, "lm_head.weight") dist.barrier() # Broadcast weights inside data parallel groups for wrapped_model in wrapped_models: broadcast_params(wrapped_model) get_torch_device().empty_cache() print_rank_0(f"loading megatron ckpt done, time elapsed {time.time() - start_time}s")
verl__models__qwen2__megatron__checkpoint_utils__qwen2_loader_depracated.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import torch import torch.distributed as dist from megatron.core import mpu from megatron.core.distributed import DistributedDataParallel as LocalDDP from megatron.core.transformer.module import Float16Module from torch.nn.parallel import DistributedDataParallel as torchDDP from verl.utils.device import get_device_id, get_torch_device from verl.utils.logger import print_rank_0 from verl.utils.megatron_utils import unwrap_model def _megatron_calc_global_rank(tp_rank: int = 0, dp_rank: int = 0, pp_rank: int = 0): """given TP,DP,PP rank to get the global rank.""" tp_size = mpu.get_tensor_model_parallel_world_size() dp_size = mpu.get_data_parallel_world_size() pp_size = mpu.get_pipeline_model_parallel_world_size() assert tp_size * dp_size * pp_size == torch.distributed.get_world_size(), ( f"{tp_size} x {dp_size} x {pp_size} != {torch.distributed.get_world_size()}" ) # We only support TP-DP-PP grouping, for correctness when resharding return (pp_rank * dp_size + dp_rank) * tp_size + tp_rank def _megatron_calc_layer_map(config): """Calculate the mapping of global layer_idx to local layer_idx Returns: layer_map (Dict: int -> tuple(int, int, int)): mapping from the global layer index to a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model) """ from megatron.core import mpu pp_size = mpu.get_pipeline_model_parallel_world_size() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 layer_map = dict() num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers for pp_rank_idx in range(pp_size): for virtual_pp_rank_idx in range(virtual_pp_size): layer_offset = ( virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model ) for layer_idx in range(num_layers_per_model): layer_map[layer_offset + layer_idx] = ( pp_rank_idx, virtual_pp_rank_idx, layer_idx, ) return layer_map def merge_megatron_ckpt_qwen2(wrapped_models, config, dtype, is_value_model=False, tie_word_embeddings=False): """Merge sharded parameters of a Megatron module into a merged checkpoint. Args: wrapped_models (list of megatron.core.distributed.DistributedDataParallel): The local DDP wrapped megatron modules. config (str or None): HF config for model dtype: model params type is_value_model: if model is value model tie_word_embeddings: tie_word_embeddings Returns: state_dict (dict): The merged state_dict in rank 0, and an empty dictionary in other ranks. """ start_time = time.time() def _get_gpt_model(model): return model dp_rank = mpu.get_data_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() pp_rank = mpu.get_pipeline_model_parallel_rank() virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1 mp_group = mpu.get_model_parallel_group() if dist.get_rank() == 0: assert mp_group.rank() == 0, f"mp_rank:[{mp_group.rank}] != 0 on rank #0" assert pp_rank == 0, f"pp_rank:[{pp_rank}] != 0 on rank #0" assert dp_rank == 0, f"dp_rank:[{dp_rank}] != 0 on rank #0" if not isinstance(wrapped_models, list | tuple): wrapped_models = list(wrapped_models) assert len(wrapped_models) == virtual_pp_size num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers models = [None] * len(wrapped_models) for i, wrapped_model in enumerate(wrapped_models): models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module)) assert len(models[i].model.layers) == num_layers_per_model, ( "len model layers {} not equal to num_layers_per_model {}".format( len(models[i].model.layers), num_layers_per_model ) ) state_dict = dict() def _get_cpu_tensor(tensor: torch.Tensor): if tensor is None: return None if tensor.device == torch.device("cpu"): return tensor.detach().clone() return tensor.detach().cpu() def _broadcast_tensor(tensor, name, src_pp_rank) -> torch.Tensor: """broadcast tensor across mp_group""" nonlocal state_dict nonlocal mp_group src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank) if torch.distributed.get_rank() == src_rank: if tensor is None: weight = None tensor_shape = None else: weight = tensor tensor_shape = weight.shape else: weight = None tensor_shape = None obj_list = [tensor_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) tensor_shape = obj_list[0] if tensor_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tensor:[{name}] not exist, skip collect") return if weight is None: weight = torch.empty( tensor_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) dist.broadcast(weight, src=src_rank, group=mp_group) if torch.distributed.get_rank() == 0: state_dict[name] = _get_cpu_tensor(weight) def _broadcast_tp_shard_tensor(tensor, name, src_pp_rank, concat_dim=0, mutate_func=None) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=concat_dim) if mutate_func is not None: full_tensor = mutate_func(full_tensor) state_dict[name] = full_tensor def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name, src_pp_rank) -> torch.Tensor: """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{gate_name, up_name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=0) intermediate_size_tp = config.intermediate_size // tp_size gate_weight_list = [] up_weight_list = [] for i in range(tp_size): gate_up_weight_tp = full_tensor[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)] gate_weight_tp = gate_up_weight_tp[:intermediate_size_tp] up_weight_tp = gate_up_weight_tp[intermediate_size_tp:] gate_weight_list.append(gate_weight_tp) up_weight_list.append(up_weight_tp) state_dict[gate_name] = torch.cat(gate_weight_list, dim=0) state_dict[up_name] = torch.cat(up_weight_list, dim=0) def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, src_pp_rank): """broadcast tensor in tp shards across mp_group""" nonlocal state_dict nonlocal mp_group tp_size = mpu.get_tensor_model_parallel_world_size() src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank) chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None obj_list = [chunk_shape] dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group) chunk_shape = obj_list[0] if chunk_shape is None: # all or none ranks in the mp_group should reach here print_rank_0(f"tp_shard tensor:[{q_name}] not exist, skip collecting") return buffer_tensor = torch.empty( chunk_shape, dtype=dtype, device=get_device_id(), requires_grad=False, ) chunk_tensors = [None] * tp_size for i in range(tp_size): cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank) sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group) if torch.distributed.get_rank() == 0: chunk_tensors[i] = _get_cpu_tensor(sync_tensor) if torch.distributed.get_rank() == 0: full_tensor = torch.concat(chunk_tensors, dim=0) q_weight_list = [] k_weight_list = [] v_weight_list = [] hidden_size_per_head = config.hidden_size // config.num_attention_heads if config.num_key_value_heads >= tp_size: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size total_size = q_size_tp + 2 * kv_size_tp for i in range(tp_size): qkv_part = full_tensor[i * total_size : (i + 1) * total_size] q_part = qkv_part[:q_size_tp] k_part = qkv_part[q_size_tp : q_size_tp + kv_size_tp] v_part = qkv_part[q_size_tp + kv_size_tp : total_size] q_weight_list.append(q_part) k_weight_list.append(k_part) v_weight_list.append(v_part) else: q_size_tp = config.hidden_size // tp_size kv_size_tp = hidden_size_per_head total_size = q_size_tp + 2 * kv_size_tp for i in range(tp_size): qkv_part = full_tensor[i * total_size : (i + 1) * total_size] q_part = qkv_part[:q_size_tp] k_part = qkv_part[q_size_tp : q_size_tp + kv_size_tp] v_part = qkv_part[q_size_tp + kv_size_tp : total_size] q_weight_list.append(q_part) if i * config.num_key_value_heads % tp_size == 0: k_weight_list.append(k_part) v_weight_list.append(v_part) state_dict[q_name] = torch.cat(q_weight_list, dim=0) state_dict[k_name] = torch.cat(k_weight_list, dim=0) state_dict[v_name] = torch.cat(v_weight_list, dim=0) # empty cache before collecting weights get_torch_device().empty_cache() # Embeddings # ------------------- if dp_rank == 0: # Embeddings # ------------------- print_rank_0("collecting embeddings...") gpt_model_module = _get_gpt_model(models[0]) _broadcast_tp_shard_tensor( gpt_model_module.model.embed_tokens.weight if pp_rank == 0 else None, "model.embed_tokens.weight", src_pp_rank=0, ) # Transformer layers # ------------------- layer_map = _megatron_calc_layer_map(config) for layer in range(config.num_hidden_layers): print_rank_0(f"collecting layer #{layer}...") layer_name = f"model.layers.{layer}" src_pp_rank, src_virtual_pp_rank, src_layer_idx = layer_map[layer] gpt_model_module = _get_gpt_model(models[src_virtual_pp_rank]) sync_layer = gpt_model_module.model.layers[src_layer_idx] _broadcast_tensor( sync_layer.input_layernorm.weight, f"{layer_name}.input_layernorm.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.weight, f"{layer_name}.self_attn.q_proj.weight", f"{layer_name}.self_attn.k_proj.weight", f"{layer_name}.self_attn.v_proj.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor_qkv( sync_layer.self_attn.qkv_proj.bias, f"{layer_name}.self_attn.q_proj.bias", f"{layer_name}.self_attn.k_proj.bias", f"{layer_name}.self_attn.v_proj.bias", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor( sync_layer.self_attn.o_proj.weight, f"{layer_name}.self_attn.o_proj.weight", concat_dim=1, src_pp_rank=src_pp_rank, ) _broadcast_tensor( sync_layer.post_attention_layernorm.weight, f"{layer_name}.post_attention_layernorm.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor_gate_up( sync_layer.mlp.gate_up_proj.weight, f"{layer_name}.mlp.gate_proj.weight", f"{layer_name}.mlp.up_proj.weight", src_pp_rank=src_pp_rank, ) _broadcast_tp_shard_tensor( sync_layer.mlp.down_proj.weight, f"{layer_name}.mlp.down_proj.weight", concat_dim=1, src_pp_rank=src_pp_rank, ) # Final Layernorm # ------------------- print_rank_0("collecting final layernorm...") gpt_model_module = _get_gpt_model(models[-1]) _broadcast_tensor( getattr(gpt_model_module.model.norm, "weight", None), "model.norm.weight", src_pp_rank=pp_size - 1, ) if tie_word_embeddings: print_rank_0("tie word embedding skip load lm_head...") else: print_rank_0("collecting lm_head...") if is_value_model: _broadcast_tensor( gpt_model_module.lm_head.weight if pp_rank == pp_size - 1 else None, "lm_head.weight", src_pp_rank=pp_size - 1, ) _broadcast_tensor( gpt_model_module.reward_head.weight if pp_rank == pp_size - 1 and getattr(gpt_model_module, "reward_weight", None) is not None else None, "reward_head.weight", src_pp_rank=pp_size - 1, ) else: _broadcast_tp_shard_tensor( getattr(gpt_model_module.lm_head, "weight", None) if pp_rank == pp_size - 1 else None, "lm_head.weight", src_pp_rank=pp_size - 1, ) dist.barrier() get_torch_device().empty_cache() if torch.distributed.get_rank() == 0: for k, v in state_dict.items(): if dtype != v.dtype: state_dict[k] = v.to(dtype) print_rank_0(f"merge megatron ckpt done, time elapsed {time.time() - start_time}s") return state_dict
verl__models__qwen2__megatron__checkpoint_utils__qwen2_saver.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from typing import Optional import torch.nn.functional as F from einops import rearrange from transformers.utils import is_flash_attn_2_available if is_flash_attn_2_available(): from flash_attn import flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa: F401 import torch from flash_attn.layers.rotary import apply_rotary_emb from megatron.core import ModelParallelConfig, tensor_parallel from megatron.core import parallel_state as mpu from torch import nn from transformers import Qwen2Config from verl.models.qwen2.megatron.layers.parallel_linear import QKVParallelLinear from verl.utils.megatron import tensor_parallel as tp_utils class Qwen2RotaryEmbedding(nn.Module): def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): super().__init__() self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) # Build here to make `torch.jit.trace` work. self._set_cos_sin_cache( seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() ) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) freqs = torch.einsum("i,j->ij", t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) def forward(self, x, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] if seq_len > self.max_seq_len_cached: self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) return ( self.cos_cached[:seq_len].to(dtype=x.dtype), self.sin_cached[:seq_len].to(dtype=x.dtype), ) class Qwen2LinearScalingRotaryEmbedding(Qwen2RotaryEmbedding): """Qwen2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) t = t / self.scaling_factor freqs = torch.einsum("i,j->ij", t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) class Qwen2DynamicNTKScalingRotaryEmbedding(Qwen2RotaryEmbedding): """Qwen2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len if seq_len > self.max_position_embeddings: base = self.base * ( (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) ) ** (self.dim / (self.dim - 2)) inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) freqs = torch.einsum("i,j->ij", t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb(q, k, cos, sin, position_ids): cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) class ParallelQwen2Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig): super().__init__() self.config = config self.megatron_config = megatron_config self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.hidden_size // self.num_heads self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.max_position_embeddings = config.max_position_embeddings self.rope_theta = config.rope_theta # assign values after tp tp_size = mpu.get_tensor_model_parallel_world_size() assert self.num_heads % tp_size == 0, ( f"num_head must be divisible by tp_size. Got num_head={self.num_heads}, tp_size={tp_size}" ) assert self.num_key_value_heads % tp_size == 0, ( f"num_key_value_heads must be divisible by tp_size. Got num_key_value_heads=" f"{self.num_key_value_heads}, tp_size={tp_size}" ) self.num_heads_per_tp = self.num_heads // tp_size self.num_key_value_heads_per_tp = self.num_key_value_heads // tp_size self.hidden_size_per_tp = self.hidden_size // tp_size if (self.head_dim * self.num_heads) != self.hidden_size: raise ValueError( f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and " f"`num_heads`: {self.num_heads})." ) column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear() if megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" assert row_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, megatron_config) tp_utils.update_kwargs_with_config(row_kwargs, megatron_config) # [self.q_size, self.k_size, self.v_size] self.qkv_proj = QKVParallelLinear( input_size=self.hidden_size, num_heads=self.num_heads, num_key_value_heads=self.num_key_value_heads, head_dim=self.head_dim, # bias=config.attention_bias, bias=True, gather_output=False, skip_bias_add=False, **column_kwargs, ) self.q_size = self.num_heads_per_tp * self.head_dim self.k_size = self.num_key_value_heads_per_tp * self.head_dim self.v_size = self.num_key_value_heads_per_tp * self.head_dim self.o_proj = tensor_parallel.RowParallelLinear( input_size=self.num_heads * self.head_dim, output_size=self.hidden_size, # bias=config.attention_bias, bias=False, input_is_parallel=True, skip_bias_add=False, **row_kwargs, ) self._init_rope() def _init_rope(self): self.rotary_emb = Qwen2RotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta, ) def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: bsz, q_len, _ = hidden_states.size() qkv = self.qkv_proj(hidden_states)[0] query_states, key_states, value_states = qkv.split([self.q_size, self.k_size, self.v_size], dim=-1) query_states = query_states.view(bsz, q_len, self.num_heads_per_tp, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads_per_tp, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads_per_tp, self.head_dim).transpose(1, 2) kv_seq_len = key_states.shape[-2] cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) if attn_weights.size() != (bsz, self.num_heads_per_tp, q_len, kv_seq_len): raise ValueError( f"Attention weights should be of size {(bsz, self.num_heads_per_tp, q_len, kv_seq_len)}, " f"but is {attn_weights.size()}" ) if attention_mask is not None: if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): raise ValueError( f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" ) attn_weights = attn_weights + attention_mask # upcast attention to fp32 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) attn_output = torch.matmul(attn_weights, value_states) if attn_output.size() != (bsz, self.num_heads_per_tp, q_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads_per_tp, q_len, self.head_dim)}, " f"but is {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, self.hidden_size_per_tp) attn_output = self.o_proj(attn_output)[0] return attn_output """ Remove padding Attention - Using Flash-attn 2 - Compatible with sequence parallel """ def apply_rotary_pos_emb_rmpad(q, k, cos, sin, position_ids, indices, sequence_length): batch_size = position_ids.shape[0] q = pad_input(q, indices, batch_size, sequence_length) # (batch_size, seqlen, num_head, head_dim) k = pad_input(k, indices, batch_size, sequence_length) cos = cos[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim] sin = sin[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim] q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) q_embed = index_first_axis(rearrange(q_embed, "b s ... -> (b s) ..."), indices) k_embed = index_first_axis(rearrange(k_embed, "b s ... -> (b s) ..."), indices) return q_embed, k_embed # use flash-attn rotary embeddings with rmpad # cos/sin shoudl be: (seq_length, rotary_dim / 2) def apply_rotary_pos_emb_rmpad_flash(q, k, cos, sin, cu_seqlens, max_seqlen): q_embed = apply_rotary_emb( q, cos, sin, interleaved=False, inplace=False, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen ) k_embed = apply_rotary_emb( k, cos, sin, interleaved=False, inplace=False, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen ) return q_embed, k_embed class ParallelQwen2AttentionRmPad(ParallelQwen2Attention): def forward( self, hidden_states: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, sequence_length: int = None, indices: torch.Tensor = None, cu_seqlens: torch.Tensor = None, max_seqlen_in_batch: int = None, ): total_nnz, _, _ = hidden_states.size() # This is the total_nnz padded after sequence parallel if self.megatron_config.sequence_parallel: total_nnz = total_nnz * mpu.get_tensor_model_parallel_world_size() qkv = self.qkv_proj(hidden_states)[0] query_states, key_states, value_states = qkv.split( [self.q_size, self.k_size, self.v_size], dim=-1 ) # (total_nnz, 1, hidden_size) if self.megatron_config.sequence_parallel: sequence_parallel_pad = total_nnz - cu_seqlens[-1] total_nnz = cu_seqlens[-1] # total_nnz before sp padding query_states = query_states[:total_nnz] key_states = key_states[:total_nnz] value_states = value_states[:total_nnz] # Flash attention requires the input to have the shape # batch_size x seq_length x head_dime x hidden_dim # therefore we just need to keep the original shape query_states = query_states.view(total_nnz, self.num_heads_per_tp, self.head_dim) key_states = key_states.view(total_nnz, self.num_key_value_heads_per_tp, self.head_dim) value_states = value_states.view(total_nnz, self.num_key_value_heads_per_tp, self.head_dim) cos, sin = self.rotary_emb(value_states, seq_len=sequence_length) cos, sin = cos[:, : cos.shape[1] // 2], sin[:, : sin.shape[1] // 2] # flash attn only needs half query_states, key_states = apply_rotary_pos_emb_rmpad_flash( query_states, key_states, cos, sin, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen_in_batch ) # query_states, key_states = apply_rotary_pos_emb_rmpad(query_states, key_states, cos, sin, # position_ids, indices, # It is recommended to use dropout with FA according to the docs # when training. dropout_rate = 0.0 # if not self.training else self.attn_dropout # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in float16 just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (Qwen2RMSNorm handles it correctly) input_dtype = query_states.dtype if input_dtype == torch.float32: query_states = query_states.to(torch.float16) key_states = key_states.to(torch.float16) value_states = value_states.to(torch.float16) attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, max_seqlen_q=max_seqlen_in_batch, max_seqlen_k=max_seqlen_in_batch, dropout_p=dropout_rate, softmax_scale=None, causal=True, ) attn_output_unpad = attn_output_unpad.to(input_dtype) attn_output_unpad = attn_output_unpad.reshape(total_nnz, 1, self.hidden_size_per_tp).contiguous() # sequence parallel reduce_scatter is performed inside RowColumnParallel if enabled # Here we need to repad if self.megatron_config.sequence_parallel: attn_output_unpad = F.pad(attn_output_unpad, pad=(0, 0, 0, 0, 0, sequence_parallel_pad)) attn_output_unpad = self.o_proj(attn_output_unpad)[0] return attn_output_unpad
verl__models__qwen2__megatron__layers__parallel_attention.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional import torch from megatron.core import ModelParallelConfig from torch import nn from transformers import Qwen2Config from verl.utils.megatron_utils import TransformerConfig, convert_config from .parallel_attention import ParallelQwen2Attention, ParallelQwen2AttentionRmPad from .parallel_mlp import ParallelQwen2MLP from .parallel_rmsnorm import ParallelQwen2RMSNorm class ParallelQwen2DecoderLayer(nn.Module): def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig, layer_idx: int): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.layer_idx = layer_idx self.hidden_size = config.hidden_size self.self_attn = ParallelQwen2Attention(config=config, megatron_config=megatron_config) self.mlp = ParallelQwen2MLP(config, megatron_config=megatron_config) self.input_layernorm = ParallelQwen2RMSNorm(config, megatron_config) self.post_attention_layernorm = ParallelQwen2RMSNorm(config, megatron_config) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states """ residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Note: sequence parallel is hidden inside ColumnParallelLinear # reduce scatter is hidden inside RowParallelLinear # Self Attention hidden_states = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, ) # TODO: add sequence parallel operator reduce_scatter here hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) # TODO: add sequence parallel operator all_gather here hidden_states = self.mlp(hidden_states) # TODO: add sequence parallel operator reduce_scatter here hidden_states = residual + hidden_states outputs = hidden_states return outputs class ParallelQwen2DecoderLayerRmPad(nn.Module): def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig, layer_idx: int): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.hidden_size = config.hidden_size self.layer_idx = layer_idx self.self_attn = ParallelQwen2AttentionRmPad(config=config, megatron_config=megatron_config) self.mlp = ParallelQwen2MLP(config, megatron_config=megatron_config) self.input_layernorm = ParallelQwen2RMSNorm(config, megatron_config) self.post_attention_layernorm = ParallelQwen2RMSNorm(config, megatron_config) def forward( self, hidden_states: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, sequence_length: int = None, indices: torch.Tensor = None, cu_seqlens: int = None, max_seqlen_in_batch: int = None, ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]: residual = hidden_states # (total_nnz // sp, 1, hidden_size) hidden_states = self.input_layernorm(hidden_states) # Self Attention # (total_nnz // sp, 1, hidden_size) -> all-gather (total_nnz, 1, hidden_size) # -> col + row -> reduce-scatter -> (total_nnz // sp, 1, hidden_size) hidden_states = self.self_attn( hidden_states=hidden_states, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) hidden_states = residual + hidden_states # Fully Connected # shape changes same as attn residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = hidden_states return outputs
verl__models__qwen2__megatron__layers__parallel_decoder.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023 The vLLM team. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/linear.py from megatron.core import tensor_parallel class QKVParallelLinear(tensor_parallel.ColumnParallelLinear): def __init__( self, input_size, num_heads, num_key_value_heads, head_dim, *, bias=True, gather_output=True, skip_bias_add=False, **kwargs, ): # Keep input parameters, and already restrict the head numbers self.input_size = input_size self.q_output_size = num_heads * head_dim self.kv_output_size = num_key_value_heads * head_dim self.head_dim = head_dim self.gather_output = gather_output self.skip_bias_add = skip_bias_add input_size = self.input_size output_size = (num_heads + 2 * num_key_value_heads) * self.head_dim super().__init__( input_size=input_size, output_size=output_size, bias=bias, gather_output=gather_output, skip_bias_add=skip_bias_add, **kwargs, ) class MergedColumnParallelLinear(tensor_parallel.ColumnParallelLinear): def __init__( self, input_size, gate_ouput_size, up_output_size, *, bias=True, gather_output=True, skip_bias_add=False, **kwargs, ): # Keep input parameters, and already restrict the head numbers self.input_size = input_size self.output_size = gate_ouput_size + up_output_size self.gather_output = gather_output self.skip_bias_add = skip_bias_add super().__init__( input_size=self.input_size, output_size=self.output_size, bias=bias, gather_output=gather_output, skip_bias_add=skip_bias_add, **kwargs, )
verl__models__qwen2__megatron__layers__parallel_linear.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from megatron.core import ModelParallelConfig, tensor_parallel from megatron.core import parallel_state as mpu from torch import nn from transformers.activations import ACT2FN from verl.models.qwen2.megatron.layers.parallel_linear import MergedColumnParallelLinear from verl.utils.megatron import tensor_parallel as tp_utils class ParallelQwen2MLP(nn.Module): def __init__(self, config, megatron_config: ModelParallelConfig = None) -> None: super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size # The weight is only [hidden_size, intermediate_size // model_parallel_world_size] column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear() if megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" assert row_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(row_kwargs, megatron_config) tp_utils.update_kwargs_with_config(column_kwargs, megatron_config) tp_size = mpu.get_tensor_model_parallel_world_size() self.gate_up_proj = MergedColumnParallelLinear( input_size=self.hidden_size, gate_ouput_size=self.intermediate_size, up_output_size=self.intermediate_size, bias=False, gather_output=False, skip_bias_add=False, **column_kwargs, ) self.gate_size = self.intermediate_size // tp_size self.down_proj = tensor_parallel.RowParallelLinear( input_size=self.intermediate_size, output_size=self.hidden_size, bias=False, input_is_parallel=True, skip_bias_add=False, **row_kwargs, ) self.act_fn = ACT2FN[config.hidden_act] def forward(self, x): gate_up = self.gate_up_proj(x)[0] gate, up = gate_up.split(self.gate_size, dim=-1) return self.down_proj(self.act_fn(gate) * up)[0]
verl__models__qwen2__megatron__layers__parallel_mlp.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numbers import torch from apex.normalization.fused_layer_norm import fused_rms_norm_affine from megatron.core import ModelParallelConfig from torch import nn from transformers import Qwen2Config from verl.utils.megatron import sequence_parallel as sp_utils class ParallelQwen2RMSNorm(nn.Module): def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig): """ Qwen2RMSNorm is equivalent to T5LayerNorm """ super().__init__() if isinstance(config.hidden_size, numbers.Integral): normalized_shape = (config.hidden_size,) self.normalized_shape = torch.Size(normalized_shape) self.weight = nn.Parameter(torch.ones(self.normalized_shape)) self.variance_epsilon = config.rms_norm_eps if megatron_config.sequence_parallel: sp_utils.mark_parameter_as_sequence_parallel(self.weight) def forward(self, hidden_states): return fused_rms_norm_affine( input=hidden_states, weight=self.weight, normalized_shape=self.normalized_shape, eps=self.variance_epsilon, memory_efficient=True, )
verl__models__qwen2__megatron__layers__parallel_rmsnorm.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PyTorch Qwen2 model.""" from typing import Optional import torch import torch.utils.checkpoint from megatron.core import ModelParallelConfig, mpu, parallel_state, tensor_parallel from torch import nn from transformers.modeling_outputs import BaseModelOutputWithPast from transformers.models.qwen2.configuration_qwen2 import Qwen2Config from transformers.models.qwen2.modeling_qwen2 import CausalLMOutputWithPast from verl.utils.device import get_device_name from verl.utils.megatron import sequence_parallel as sp_utils from verl.utils.megatron import tensor_parallel as tp_utils from verl.utils.megatron_utils import TransformerConfig, convert_config from .layers import ParallelQwen2DecoderLayer, ParallelQwen2DecoderLayerRmPad, ParallelQwen2RMSNorm """ TODO: 1. Add weight initialization. Here we need to be careful on TP weight init. 2. Add sequence parallel 3. Load checkpoint from Qwen2 pretrained checkpoint """ # Copied from transformers.models.bart.modeling_bart._make_causal_mask def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len) # Copied from transformers.models.bart.modeling_bart._expand_mask def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) class ParallelQwen2Model(nn.Module): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`] Args: config: Qwen2Config """ def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding() if megatron_config is not None: assert embedding_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(embedding_kwargs, megatron_config) self.embed_tokens = tensor_parallel.VocabParallelEmbedding( num_embeddings=config.vocab_size, embedding_dim=config.hidden_size, **embedding_kwargs ) self.layers = nn.ModuleList( [ParallelQwen2DecoderLayer(config, megatron_config) for _ in range(config.num_hidden_layers)] ) self.norm = ParallelQwen2RMSNorm(config, megatron_config) # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds): # create causal mask # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] combined_attention_mask = None if input_shape[-1] > 1: combined_attention_mask = _make_causal_mask( input_shape, inputs_embeds.dtype, device=inputs_embeds.device, ) if attention_mask is not None: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( inputs_embeds.device ) combined_attention_mask = ( expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask ) return combined_attention_mask def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | BaseModelOutputWithPast: """ Args: input_ids: input ids. shape (batch_size, seq_length) attention_mask: attention_mask. shape (batch_size, seq_length) position_ids: position ids. shape (batch_size, seq_length) Returns: """ batch_size, seq_length = input_ids.shape inputs_embeds = self.embed_tokens(input_ids) # embed positions attention_mask = self._prepare_decoder_attention_mask(attention_mask, (batch_size, seq_length), inputs_embeds) hidden_states = inputs_embeds for idx, decoder_layer in enumerate(self.layers): layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, ) hidden_states = layer_outputs hidden_states = self.norm(hidden_states) return hidden_states class ParallelQwen2ForCausalLM(nn.Module): def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.model = ParallelQwen2Model(config, megatron_config=megatron_config) self.vocab_size = config.vocab_size column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = tensor_parallel.ColumnParallelLinear( input_size=config.hidden_size, output_size=config.vocab_size, bias=False, gather_output=False, skip_bias_add=False, **column_kwargs, ) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: ```""" # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, ) hidden_states = outputs logits = self.lm_head(hidden_states)[0] logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits) logits = logits.float() return CausalLMOutputWithPast( loss=None, logits=logits, past_key_values=None, hidden_states=None, attentions=None, ) from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa: F401, E402 class ParallelQwen2ModelRmPad(nn.Module): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`] Args: config: Qwen2Config """ def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding() self.megatron_config = megatron_config if megatron_config is not None: assert embedding_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config) self.embed_tokens = tensor_parallel.VocabParallelEmbedding( num_embeddings=config.vocab_size, embedding_dim=config.hidden_size, **embedding_kwargs ) self.layers = nn.ModuleList( [ParallelQwen2DecoderLayerRmPad(config, megatron_config) for _ in range(config.num_hidden_layers)] ) self.norm = ParallelQwen2RMSNorm(config, megatron_config) def forward( self, input_ids: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, sequence_length: int = None, indices: torch.Tensor = None, cu_seqlens: int = None, max_seqlen_in_batch: int = None, ) -> tuple | BaseModelOutputWithPast: """ Args: input_ids: input ids. shape (1, totol_nnz) position_ids: position ids. shape (batch_size, seq_length) Returns: """ inputs_embeds = self.embed_tokens(input_ids) # (1, total_nnz) -> (1, total_nnz, hidden_size) # (1, total_nnz, hidden_size) -> (total_nnz, 1, hidden_size) -> (total_nnz // sp, 1, hidden_size) inputs_embeds = inputs_embeds.transpose(0, 1) if self.megatron_config.sequence_parallel: inputs_embeds = tensor_parallel.scatter_to_sequence_parallel_region(inputs_embeds) hidden_states = inputs_embeds for idx, decoder_layer in enumerate(self.layers): layer_outputs = decoder_layer( hidden_states, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) hidden_states = layer_outputs hidden_states = self.norm(hidden_states) return hidden_states class ParallelQwen2ForCausalLMRmPad(nn.Module): def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.megatron_config = megatron_config self.model = ParallelQwen2ModelRmPad(config, megatron_config=megatron_config) self.vocab_size = config.vocab_size self._init_head(config) def _init_head(self, config: Qwen2Config): column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if self.megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = tensor_parallel.ColumnParallelLinear( input_size=config.hidden_size, output_size=config.vocab_size, bias=False, gather_output=False, skip_bias_add=False, **column_kwargs, ) def _forward_head(self, hidden_states): # all_gather from sequence parallel region is performed inside lm_head logits = self.lm_head(hidden_states)[0] logits = logits.float() # (total_nnz_padded, 1, vocab_size // tp) logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits) # (total_nnz_padded, 1, vocab_size) return logits def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: ```""" batch_size, sequence_length = input_ids.shape # remove padding here input_ids, indices, cu_seqlens, max_seqlen_in_batch, *_ = unpad_input( input_ids.unsqueeze(dim=-1), attention_mask ) # (total_nnz, 1) # pad input_ids to multiple of tp for all tp ranks # TODO: for better performance, the sp padding should be removed at each layer. Not sure the performance gap if self.megatron_config.sequence_parallel: input_ids = sp_utils.pad_to_sequence_parallel(input_ids) input_ids = input_ids.transpose(0, 1) # (1, total_nnz+pad) outputs = self.model( input_ids=input_ids, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) hidden_states = outputs logits = self._forward_head(hidden_states) # remove padding from sequence parallel if self.megatron_config.sequence_parallel: totol_nnz = cu_seqlens[-1] logits = logits[:totol_nnz] # (total_nnz_padded) logits = torch.squeeze(logits, dim=1) # remove the artificial batch dimension # add removed padding back logits = pad_input( logits, indices, batch_size, seqlen=sequence_length ) # (batch_size, sequence_length, vocab_size) return CausalLMOutputWithPast( loss=None, logits=logits, past_key_values=None, hidden_states=None, attentions=None, ) class ParallelQwen2ForValueRmPad(ParallelQwen2ForCausalLMRmPad): def _init_head(self, config): column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if self.megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = nn.Linear(in_features=config.hidden_size, out_features=1, bias=False) # lm_head is effectively the same as sequence parallel sp_utils.mark_parameter_as_sequence_parallel(self.lm_head.weight) def _forward_head(self, hidden_states): logits = self.lm_head(hidden_states) # (total_nnz_padded // tp, 1, 1) logits = logits.float() if self.megatron_config.sequence_parallel: logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False) return logits def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: output = super().forward(input_ids, attention_mask, position_ids) output.logits = torch.squeeze(output.logits, dim=-1) return output """ Support pipeline parallelism """ class ParallelQwen2ModelRmPadPP(nn.Module): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`] This model definition supports pipeline parallelism. To support pp and vpp, - This model only contains layer in this pp stage and vpp chunk - When calling get_model in Megatron, this rank will instantiate all the vpp chunks in this pp. Args: config: Qwen2Config """ def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig, pre_process, post_process): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.pre_process = pre_process self.post_process = post_process self.megatron_config = megatron_config embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding() if megatron_config is not None: assert embedding_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config) if pre_process: self.embed_tokens = tensor_parallel.VocabParallelEmbedding( num_embeddings=config.vocab_size, embedding_dim=config.hidden_size, **embedding_kwargs ) else: self.embed_tokens = None pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = megatron_config.pipeline_model_parallel_size self.num_layer_per_pp = config.num_hidden_layers // pp_size vpp_size = megatron_config.virtual_pipeline_model_parallel_size vpp_rank = mpu.get_virtual_pipeline_model_parallel_rank() if vpp_size is not None: self.num_layer_vpp_chunk = self.num_layer_per_pp // vpp_size self.num_layer_this_model = self.num_layer_vpp_chunk offset = vpp_rank * (config.num_hidden_layers // vpp_size) + (pp_rank * self.num_layer_vpp_chunk) else: self.num_layer_this_model = self.num_layer_per_pp offset = pp_rank * self.num_layer_per_pp self.layers = nn.ModuleList() for i in range(self.num_layer_this_model): layer = ParallelQwen2DecoderLayerRmPad(config, megatron_config, layer_idx=i + offset) self.layers.add_module(f"{i}", layer) if post_process: self.norm = ParallelQwen2RMSNorm(config, megatron_config) else: self.norm = None def set_input_tensor(self, input_tensor): """Set input tensor to be used instead of forward()'s input. When doing pipeline parallelism the input from the previous stage comes from communication, not from the input, so the model's forward_step_func won't have it. This function is thus used by internal code to bypass the input provided by the forward_step_func""" self.input_tensor = input_tensor def forward( self, input_ids: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, sequence_length: int = None, indices: torch.Tensor = None, cu_seqlens: int = None, max_seqlen_in_batch: int = None, ) -> tuple | BaseModelOutputWithPast: """ Args: input_ids: input ids. shape (1, totol_nnz) position_ids: position ids. shape (batch_size, seq_length) Returns: """ if self.pre_process: inputs_embeds = self.embed_tokens(input_ids) # (1, total_nnz) -> (1, total_nnz, hidden_size) # vocab parallel embedding will not do sequence parallel reduce-scatter in open source megatron # so need to deal with it by handle here: # (1, total_nnz, hidden_size) -> (total_nnz, 1, hidden_size) -> (total_nnz // sp, 1, hidden_size) inputs_embeds = inputs_embeds.transpose(0, 1) if self.megatron_config.sequence_parallel: inputs_embeds = tensor_parallel.scatter_to_sequence_parallel_region(inputs_embeds) hidden_states = inputs_embeds else: # self.hidden_states should be passed by Megatron hidden_states = self.input_tensor for idx, decoder_layer in enumerate(self.layers): layer_outputs = decoder_layer( hidden_states, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) hidden_states = layer_outputs if self.post_process: hidden_states = self.norm(hidden_states) return hidden_states class ParallelQwen2ForCausalLMRmPadPP(nn.Module): def __init__( self, config: Qwen2Config, megatron_config: ModelParallelConfig, pre_process, post_process, share_embeddings_and_output_weights, ): super().__init__() self.config: TransformerConfig = convert_config(config, megatron_config) self.megatron_config = megatron_config self.model = ParallelQwen2ModelRmPadPP( config, megatron_config=megatron_config, pre_process=pre_process, post_process=post_process ) self.share_embeddings_and_output_weights = share_embeddings_and_output_weights self.vocab_size = config.vocab_size self.pre_process = pre_process self.post_process = post_process if post_process: self._init_head(config) if pre_process or post_process: self.setup_embeddings_and_output_layer() def set_input_tensor(self, input_tensor): """Set input tensor to be used instead of forward()'s input. When doing pipeline parallelism the input from the previous stage comes from communication, not from the input, so the model's forward_step_func won't have it. This function is thus used by internal code to bypass the input provided by the forward_step_func""" assert len(input_tensor) == 1 self.model.set_input_tensor(input_tensor[0]) def _init_head(self, config): column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if self.megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = tensor_parallel.ColumnParallelLinear( input_size=config.hidden_size, output_size=config.vocab_size, bias=False, gather_output=False, skip_bias_add=False, skip_weight_param_allocation=self.pre_process and self.share_embeddings_and_output_weights, **column_kwargs, ) def setup_embeddings_and_output_layer(self) -> None: """Sets up embedding layer in first stage and output layer in last stage. This function initializes word embeddings in the final stage when we are using pipeline parallelism and sharing word embeddings, and sets up param attributes on the embedding and output layers. """ # Set `is_embedding_or_output_parameter` attribute. if self.pre_process: self.model.embed_tokens.weight.is_embedding_or_output_parameter = True if self.post_process and self.lm_head.weight is not None: self.lm_head.weight.is_embedding_or_output_parameter = True if not self.share_embeddings_and_output_weights: return if parallel_state.get_pipeline_model_parallel_world_size() == 1: # Zero out wgrad if sharing embeddings between two layers on same # pipeline stage to make sure grad accumulation into main_grad is # correct and does not include garbage values (e.g., from torch.empty). self.shared_embedding_or_output_weight().zero_out_wgrad = True return if parallel_state.is_pipeline_first_stage() and self.pre_process and not self.post_process: self.shared_embedding_or_output_weight().shared_embedding = True if self.post_process and not self.pre_process: assert not parallel_state.is_pipeline_first_stage() # set word_embeddings weights to 0 here, then copy first # stage's weights using all_reduce below. self.lm_head.weight.data.fill_(0) self.lm_head.weight.shared = True self.lm_head.weight.shared_embedding = True if torch.distributed.is_initialized() and parallel_state.is_rank_in_embedding_group(): weight = self.shared_embedding_or_output_weight() weight.data = weight.data.to(get_device_name()) torch.distributed.all_reduce(weight.data, group=parallel_state.get_embedding_group()) def shared_embedding_or_output_weight(self) -> torch.Tensor: if self.pre_process: return self.model.embed_tokens.weight elif self.post_process: return self.lm_head.weight return None def _forward_head(self, hidden_states): # all_gather from sequence parallel region is performed inside lm_head # print(f'logits shape before forward_head: {hidden_states.shape}, vocab_size = ' # f'{self.config.vocab_size}') # [4, 32, 4096] output_weight = None if self.share_embeddings_and_output_weights: output_weight = self.shared_embedding_or_output_weight() logits = self.lm_head(hidden_states, weight=output_weight)[0] # print(f'logits shape after forward_head: {logits.shape}') # [8, 32, 8] logits = logits.float() # (total_nnz_padded, 1, vocab_size // tp) return logits def forward( self, # original input *, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: ```""" # Note that input_ids, attention_mask and position_ids should be passed to every pp layer. # In the first pp, input_ids will be used, in other pp layers hidden_states will be used inside self.model batch_size, sequence_length = input_ids.shape # remove padding here input_ids_rmpad, indices, cu_seqlens, max_seqlen_in_batch, *_ = unpad_input( input_ids.unsqueeze(dim=-1), attention_mask ) # (total_nnz, 1) # pad input_ids to multiple of tp for all tp ranks # TODO: for better performance, the sp padding should be removed at each layer. Not sure the performance gap if self.megatron_config.sequence_parallel: input_ids_rmpad = sp_utils.pad_to_sequence_parallel(input_ids_rmpad) input_ids_rmpad = input_ids_rmpad.transpose(0, 1) # (1, total_nnz+pad) outputs = self.model( input_ids=input_ids_rmpad, position_ids=position_ids, sequence_length=sequence_length, indices=indices, cu_seqlens=cu_seqlens, max_seqlen_in_batch=max_seqlen_in_batch, ) if self.post_process: hidden_states = outputs logits = self._forward_head(hidden_states) logits = torch.squeeze(logits, dim=1) # remove the artificial batch dimension # torch.Size([8, 32, 16]) # remove padding from sequence parallel if self.megatron_config.sequence_parallel: totol_nnz = cu_seqlens[-1] logits = logits[:totol_nnz] # (total_nnz_padded) # add removed padding back. If input is already rmpad, we let the caller pad_input logits = pad_input( logits, indices, batch_size, seqlen=sequence_length ) # (batch_size, sequence_length, vocab_size) return CausalLMOutputWithPast( loss=None, logits=logits, past_key_values=None, hidden_states=None, attentions=None, ) else: return outputs class ParallelQwen2ForValueRmPadPP(ParallelQwen2ForCausalLMRmPadPP): def _init_head(self, config): column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear() if self.megatron_config is not None: assert column_kwargs.get("config", False), "must have ModelParallelConfig" tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config) self.lm_head = nn.Linear(in_features=config.hidden_size, out_features=1, bias=False) # lm_head is effectively the same as sequence parallel sp_utils.mark_parameter_as_sequence_parallel(self.lm_head.weight) def _forward_head(self, hidden_states): logits = self.lm_head(hidden_states) # (total_nnz_padded // tp, 1, 1) logits = logits.float() if self.megatron_config.sequence_parallel: logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False) return logits def forward( self, *, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, ) -> tuple | CausalLMOutputWithPast: output = super().forward(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids) if self.post_process: output.logits = torch.squeeze(output.logits, dim=-1) return output else: return output
verl__models__qwen2__megatron__modeling_qwen2_megatron.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import importlib from typing import Optional import torch.nn as nn # Supported models in Megatron-LM # Architecture -> (module, class). _MODELS = { "LlamaForCausalLM": ( "llama", ("ParallelLlamaForCausalLMRmPadPP", "ParallelLlamaForValueRmPadPP", "ParallelLlamaForCausalLMRmPad"), ), "Qwen2ForCausalLM": ( "qwen2", ("ParallelQwen2ForCausalLMRmPadPP", "ParallelQwen2ForValueRmPadPP", "ParallelQwen2ForCausalLMRmPad"), ), "MistralForCausalLM": ( "mistral", ("ParallelMistralForCausalLMRmPadPP", "ParallelMistralForValueRmPadPP", "ParallelMistralForCausalLMRmPad"), ), "ApertusForCausalLM": ( "apertus", ("ParallelApertusForCausalLMRmPadPP", "ParallelApertusForValueRmPadPP", "ParallelApertusForCausalLMRmPad"), ), } # return model class class ModelRegistry: @staticmethod def load_model_cls(model_arch: str, value=False) -> Optional[type[nn.Module]]: if model_arch not in _MODELS: return None megatron = "megatron" module_name, model_cls_name = _MODELS[model_arch] if not value: # actor/ref model_cls_name = model_cls_name[0] elif value: # critic/rm model_cls_name = model_cls_name[1] module = importlib.import_module(f"verl.models.{module_name}.{megatron}.modeling_{module_name}_megatron") return getattr(module, model_cls_name, None) @staticmethod def get_supported_archs() -> list[str]: return list(_MODELS.keys())
verl__models__registry.py
# Copyright 2025 The SwissAI Initiative # 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from typing import Callable, Optional import torch if sys.version_info >= (3, 11): pass else: pass from transformers.cache_utils import Cache from transformers.models.apertus.modeling_apertus import apply_rotary_pos_emb from transformers.utils import logging # Import compatibility wrapper for flash_attn_supports_top_left_mask from verl.utils.ulysses import ( gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_world_size, validate_ulysses_config, ) logger = logging.get_logger(__name__) def apertus_attn_forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: """ Adapted from transformers 4.49.0 to support Ulysses sequence parallelism for transformers >= 4.48.0. Key differences from Llama attention: - QK normalization applied after Q/K projections NOTE: This function has been tested only on transformers versions between 4.48.0 and 4.50.0. """ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS from transformers.models.apertus.modeling_apertus import eager_attention_forward bsz, q_len, _ = hidden_states.shape query_states = self.q_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2) key_states = self.k_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2) value_states = self.v_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2) query_states = self.q_norm(query_states) key_states = self.k_norm(key_states) ########## AlltoAll for Ulysses ########## ulysses_sp_size = get_ulysses_sequence_parallel_world_size() if ulysses_sp_size > 1: validate_ulysses_config(self.config.num_attention_heads, ulysses_sp_size) query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1) key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1) value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1) full_q_len = query_states.size(2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_value is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False): logger.warning_once( "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. " "Falling back to eager attention. This warning can be removed using the argument " '`attn_implementation="eager"` when loading the model.' ) else: attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous() ########## AlltoAll for Ulysses ########## if ulysses_sp_size > 1: attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2) attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
verl__models__transformers__apertus.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass from typing import Optional, Union import torch from transformers.cache_utils import Cache from transformers.modeling_outputs import CausalLMOutputWithPast @dataclass class CausalLMOutputForPPO(CausalLMOutputWithPast): log_probs: Optional[torch.FloatTensor] = None entropy: Optional[torch.FloatTensor] = None def forward_base_model( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, ) -> CausalLMOutputWithPast: r""" Copy paste LLaMa's forward https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/transformers/model/llama.py This function should be generic enough for all pure text models. ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) return outputs def forward_with_torch_backend( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Union["Cache", list[torch.FloatTensor]]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: int | torch.Tensor = 0, temperature: float = 1.0, **loss_kwargs, ) -> tuple | CausalLMOutputForPPO: from verl.utils.experimental.torch_functional import FusedLinearForPPO outputs = forward_base_model( self, input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, ) hidden_states = outputs[0] if not return_dict: raise NotImplementedError("forward_with_torch_backend has to return_dict") # Loss calculations if labels is not None: rolled_labels = torch.roll(labels, shifts=-1, dims=-1) elif input_ids is not None: rolled_labels = torch.roll(input_ids, shifts=-1, dims=-1) else: raise RuntimeError("To use forward_with_torch_backend, either labels or input_ids must be provided.") fused_linear_for_ppo = FusedLinearForPPO() log_probs, entropy = fused_linear_for_ppo.forward( hidden_states=hidden_states, vocab_weights=self.lm_head.weight, input_ids=rolled_labels, temperature=temperature, ) return CausalLMOutputForPPO( log_probs=log_probs, entropy=entropy, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def forward_with_triton_backend( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Union["Cache", list[torch.FloatTensor]]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: int | torch.Tensor = 0, temperature: float = 1.0, **loss_kwargs, ) -> tuple | CausalLMOutputForPPO: from verl.utils.kernel.linear_cross_entropy import linear_cross_entropy outputs = forward_base_model( self, input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) hidden_states = outputs[0] if not return_dict: raise NotImplementedError("forward_with_triton_backend has to return_dict") # Loss calculations if labels is not None: rolled_labels = torch.roll(labels, shifts=-1, dims=-1) elif input_ids is not None: rolled_labels = torch.roll(input_ids, shifts=-1, dims=-1) else: raise RuntimeError("To use forward_with_triton_backend, either labels or input_ids must be provided.") log_probs, entropy = linear_cross_entropy( hidden_states, self.lm_head.weight, rolled_labels, temperature, "none", ) return CausalLMOutputForPPO( log_probs=log_probs, entropy=entropy, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
verl__models__transformers__dense_common.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import itertools import logging import os from dataclasses import dataclass from typing import Optional import torch import torch.distributed as dist from transformers.modeling_flash_attention_utils import _flash_attention_forward, fa_peft_integration_check from transformers.models.glm4v.modeling_glm4v import ( Glm4vCausalLMOutputWithPast, Glm4vForConditionalGeneration, Glm4vTextAttention, ) from transformers.utils import is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10 from verl.utils.device import is_npu_available from verl.utils.ulysses import ( gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_group, get_ulysses_sequence_parallel_world_size, validate_ulysses_config, ) logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func _flash_supports_window_size = "window_size" in inspect.signature(flash_attn_func).parameters _flash_supports_deterministic = "deterministic" in inspect.signature(flash_attn_func).parameters _flash_use_top_left_mask = not is_flash_attn_greater_or_equal_2_10() if is_npu_available: from transformers.integrations.npu_flash_attention import npu_flash_attn_func as flash_attn_func from transformers.integrations.npu_flash_attention import npu_flash_attn_varlen_func as flash_attn_varlen_func from transformers.modeling_flash_attention_utils import flash_attn_supports_top_left_mask _flash_supports_window_size = "window_size" in inspect.signature(flash_attn_func).parameters _flash_supports_deterministic = "deterministic" in inspect.signature(flash_attn_func).parameters _flash_use_top_left_mask = flash_attn_supports_top_left_mask() _flash_deterministic_enabled = os.getenv("FLASH_ATTENTION_DETERMINISTIC", "0") == "1" def get_rope_index( processor, input_ids: torch.Tensor, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, ) -> torch.Tensor: """ Gets the position ids for GLM4V in padding-free format. The batch dim has been removed and the input_ids should be a 1D tensor representing a single example. """ spatial_merge_size = processor.image_processor.merge_size image_token_id = processor.tokenizer.convert_tokens_to_ids("<|image|>") video_start_token_id = processor.tokenizer.convert_tokens_to_ids("<|begin_of_video|>") video_end_token_id = processor.tokenizer.convert_tokens_to_ids("<|end_of_video|>") if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): if attention_mask is None: attention_mask = torch.ones_like(input_ids) position_ids = torch.ones(3, input_ids.size(0), dtype=input_ids.dtype, device=input_ids.device) # (3, seqlen) image_index, video_index = 0, 0 video_group_index = 0 input_ids_filtered = input_ids[attention_mask == 1] input_tokens = input_ids_filtered.tolist() input_token_type = [] video_check_flg = False for token in input_tokens: if token == video_start_token_id: video_check_flg = True elif token == video_end_token_id: video_check_flg = False if token == image_token_id and not video_check_flg: input_token_type.append("image") elif token == image_token_id and video_check_flg: input_token_type.append("video") else: input_token_type.append("text") input_type_group = [] for key, group in itertools.groupby(enumerate(input_token_type), lambda x: x[1]): group = list(group) start_index = group[0][0] end_index = group[-1][0] + 1 input_type_group.append((key, start_index, end_index)) llm_pos_ids_list = [] video_frame_num = 1 for modality_type, start_idx, end_idx in input_type_group: st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 if modality_type == "image": t, h, w = ( image_grid_thw[image_index][0], image_grid_thw[image_index][1], image_grid_thw[image_index][2], ) llm_grid_t, llm_grid_h, llm_grid_w = ( t.item(), h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten() h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx) image_index += 1 video_frame_num = 1 elif modality_type == "video": t, h, w = ( video_frame_num, video_grid_thw[video_index][1], video_grid_thw[video_index][2], ) llm_grid_t, llm_grid_h, llm_grid_w = ( t, h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) for t_idx in range(llm_grid_t): t_index = torch.tensor(t_idx).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten() h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(1, -1, llm_grid_w).flatten() w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(1, llm_grid_h, -1).flatten() llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx) video_group_index += 1 if video_group_index >= video_grid_thw[video_index][0]: video_index += 1 video_group_index = 0 video_frame_num += 1 else: text_len = end_idx - start_idx llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) video_frame_num = 1 llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device) else: if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = position_ids.unsqueeze(0).expand(3, -1).to(input_ids.device) else: position_ids = torch.arange(input_ids.shape[0], device=input_ids.device).view(1, -1).expand(3, -1) return position_ids def prepare_fa2_from_position_ids( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, position_ids: torch.Tensor ): assert position_ids.ndim == 2 # (batch_size, seq_length) query = query.contiguous().view(-1, query.size(-2), query.size(-1)) key = key.contiguous().view(-1, key.size(-2), key.size(-1)) value = value.contiguous().view(-1, value.size(-2), value.size(-1)) position_ids = position_ids.view(-1) cu_seqlens = torch.cat( ( (position_ids == 0).nonzero().view(-1).to(torch.int32), torch.tensor(position_ids.size(), device=position_ids.device, dtype=torch.int32), ) ) max_length = cu_seqlens.diff().max() # use cu_seqlens to infer max_length for qwen2vl mrope return (query, key, value, (cu_seqlens, cu_seqlens), (max_length, max_length)) def _custom_flash_attention_forward( query_states: torch.Tensor, key_states: torch.Tensor, value_states: torch.Tensor, attention_mask: Optional[torch.Tensor], query_length: int, is_causal: bool = True, position_ids: Optional[torch.Tensor] = None, use_top_left_mask: bool = False, deterministic: Optional[bool] = None, **kwargs, ): """ Patches flash attention forward to handle 3D position ids in mrope. (3, batch_size, seq_length) """ # Assuming 4D tensors, key_states.shape[1] is the key/value sequence length (source length). flash_kwargs = {} if _flash_supports_deterministic: flash_kwargs["deterministic"] = deterministic if deterministic is not None else _flash_deterministic_enabled if kwargs.get("softcap") is not None: flash_kwargs["softcap"] = kwargs.pop("softcap") query_states, key_states, value_states = fa_peft_integration_check( query_states, key_states, value_states, target_dtype=torch.bfloat16 ) if position_ids is not None: assert position_ids.ndim == 2 # (batch_size, seq_length / sp_size) sp_size = get_ulysses_sequence_parallel_world_size() if sp_size > 1: # qkv: (batch_size, seq_length / sp_size, num_head, head_size) validate_ulysses_config(query_states.size(2), sp_size) query_states = gather_seq_scatter_heads(query_states, seq_dim=1, head_dim=2) key_states = gather_seq_scatter_heads(key_states, seq_dim=1, head_dim=2) value_states = gather_seq_scatter_heads(value_states, seq_dim=1, head_dim=2) position_ids_lst = [torch.empty_like(position_ids) for _ in range(sp_size)] position_ids = dist.all_gather(position_ids_lst, position_ids, group=get_ulysses_sequence_parallel_group()) position_ids = torch.cat(position_ids_lst, dim=-1) # (batch_size, seq_length) if position_ids is not None and query_length != 1 and not (torch.diff(position_ids, dim=-1) >= 0).all(): batch_size = query_states.size(0) q, k, v, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_q, max_seqlen_k) = prepare_fa2_from_position_ids( query_states, key_states, value_states, position_ids ) attn_output = flash_attn_varlen_func( q=q, k=k, v=v, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_k, dropout_p=kwargs.pop("dropout", 0.0), softmax_scale=kwargs.pop("softmax_scale", None), causal=is_causal, **flash_kwargs, ) attn_output = attn_output.view(batch_size, -1, attn_output.size(-2), attn_output.size(-1)) else: attn_output = _flash_attention_forward( query_states, key_states, value_states, attention_mask, query_length, is_causal=is_causal, use_top_left_mask=use_top_left_mask, deterministic=deterministic, **kwargs, ) # do not pass position_ids to old flash_attention_forward if sp_size > 1: # (batch_size, seq_length, num_head, head_size) attn_output = gather_heads_scatter_seq(attn_output, head_dim=2, seq_dim=1) return attn_output def glm4v_attn_forward( self: "Glm4vTextAttention", hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46 **kwargs, ) -> tuple[torch.Tensor, None, None]: from transformers.models.glm4v.modeling_glm4v import apply_multimodal_rotary_pos_emb, repeat_kv bsz, q_len, _ = hidden_states.size() # q_len = seq_length / sp_size query_states = self.q_proj(hidden_states) # (batch_size, seq_length / sp_size, num_heads * head_size) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) # Because the input can be padded, the absolute sequence length depends on the max position id. cos, sin = position_embeddings query_states, key_states = apply_multimodal_rotary_pos_emb( query_states, key_states, cos, sin, self.rope_scaling["mrope_section"] ) key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) dropout_rate = 0.0 if not self.training else self.attention_dropout # This is before the transpose q_len = query_states.shape[2] # FA2 uses non-transposed inputs query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) attn_output = _custom_flash_attention_forward( query_states, key_states, value_states, attention_mask, query_length=q_len, is_causal=getattr(self, "is_causal", True), dropout=dropout_rate, use_top_left_mask=_flash_use_top_left_mask, position_ids=position_ids, # important: pass position ids ) # (batch_size, seq_length / sp_size, num_head, head_size) attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() attn_output = self.o_proj(attn_output) return attn_output, None def _get_input_embeds( model: "Glm4vForConditionalGeneration", input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, ): inputs_embeds = model.get_input_embeddings()(input_ids) if pixel_values is not None: pixel_values = pixel_values.type(model.visual.dtype) image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) n_image_tokens = (input_ids == model.config.image_token_id).sum().item() n_image_features = image_embeds.shape[0] if n_image_tokens != n_image_features: raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" ) mask = input_ids == model.config.image_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) image_mask = mask_expanded.to(inputs_embeds.device) image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) 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 = model.visual(pixel_values_videos, grid_thw=video_grid_thw) n_video_tokens = (input_ids == model.config.video_token_id).sum().item() n_video_features = video_embeds.shape[0] if n_video_tokens != n_video_features: raise ValueError( f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" ) mask = input_ids == model.config.video_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) video_mask = mask_expanded.to(inputs_embeds.device) video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) if pixel_values is None and pixel_values_videos is None: # handle mixed text-image data pixel_values = torch.zeros((16, 1176), dtype=inputs_embeds.dtype, device=inputs_embeds.device) image_grid_thw = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device) image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) inputs_embeds += 0.0 * image_embeds.mean() if attention_mask is not None: attention_mask = attention_mask.to(inputs_embeds.device) return inputs_embeds, attention_mask def process_position_ids(position_ids: torch.Tensor) -> torch.Tensor: if position_ids.ndim != 3 or position_ids.size(0) != 4: # we concat the text position ids with the 3D vision position ids by default # see https://github.com/huggingface/transformers/pull/39447 raise ValueError("position_ids should be a 3D tensor of shape (4, batch_size, seq_length).") return position_ids @dataclass class Glm4vCausalLMOutputForPPO(Glm4vCausalLMOutputWithPast): log_probs: Optional[torch.FloatTensor] = None entropy: Optional[torch.FloatTensor] = None def glm4v_base_forward( self: "Glm4vForConditionalGeneration", input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, **kwargs, ): kwargs["inputs_embeds"], kwargs["attention_mask"] = _get_input_embeds( self, input_ids, attention_mask, pixel_values, pixel_values_videos, image_grid_thw, video_grid_thw ) # avoid lora module having multiple keyword arguments return self.language_model( input_ids=None, **kwargs, ) def glm4v_forward( self: "Glm4vForConditionalGeneration", input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, **kwargs, ): return self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=process_position_ids(position_ids), pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, **kwargs, ) def forward_with_normal_backend( self: Glm4vForConditionalGeneration, input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> "Glm4vCausalLMOutputWithPast": outputs = glm4v_forward(self, input_ids, **kwargs) hidden_states = outputs[0] logits = self.lm_head(hidden_states) return Glm4vCausalLMOutputWithPast( logits=logits, hidden_states=outputs.hidden_states, ) def forward_with_torch_backend( self: Glm4vForConditionalGeneration, input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> tuple | Glm4vCausalLMOutputForPPO: from verl.utils.experimental.torch_functional import FusedLinearForPPO outputs = glm4v_forward(self, input_ids, **kwargs) hidden_states = outputs[0] # Loss calculations if labels is not None: rolled_labels = torch.roll(labels, shifts=-1, dims=-1) elif input_ids is not None: rolled_labels = torch.roll(input_ids, shifts=-1, dims=-1) else: raise RuntimeError("To use forward_with_torch_backend, either labels or input_ids must be provided.") fused_linear_for_ppo = FusedLinearForPPO() log_probs, entropy = fused_linear_for_ppo.forward( hidden_states=hidden_states, vocab_weights=self.lm_head.weight, input_ids=rolled_labels, temperature=temperature, ) return Glm4vCausalLMOutputForPPO( log_probs=log_probs, entropy=entropy, hidden_states=outputs.hidden_states, ) def forward_with_triton_backend( self: Glm4vForConditionalGeneration, input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> tuple | Glm4vCausalLMOutputForPPO: from verl.utils.kernel.linear_cross_entropy import linear_cross_entropy outputs = glm4v_forward(self, input_ids, **kwargs) hidden_states = outputs[0] # Loss calculations if labels is not None: rolled_labels = torch.roll(labels, shifts=-1, dims=-1) elif input_ids is not None: rolled_labels = torch.roll(input_ids, shifts=-1, dims=-1) else: raise RuntimeError("To use forward_with_triton_backend, either labels or input_ids must be provided.") log_probs, entropy = linear_cross_entropy( hidden_states, self.lm_head.weight, rolled_labels, temperature, "none", ) return Glm4vCausalLMOutputForPPO( log_probs=log_probs, entropy=entropy, hidden_states=outputs.hidden_states, )
verl__models__transformers__glm4v.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional import torch import torch.nn.functional as F from transformers.cache_utils import Cache from transformers.modeling_flash_attention_utils import _flash_attention_forward from verl.models.transformers.monkey_patch import is_transformers_version_in_range # Import compatibility wrapper for flash_attn_supports_top_left_mask from verl.utils.transformers_compat import flash_attn_supports_top_left_mask from verl.utils.ulysses import ( gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_world_size, validate_ulysses_config, ) # Copied from transformers.models.llama.modeling_llama.rotate_half def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos[position_ids].unsqueeze(unsqueeze_dim) sin = sin[position_ids].unsqueeze(unsqueeze_dim) b, h, s, d = q.shape q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d) b, h, s, d = k.shape k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed # Copied from transformers.models.llama.modeling_llama.repeat_kv def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) def _ulysses_flash_attn_forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: bsz, q_len, _ = hidden_states.size() if self.q_lora_rank is None: q = self.q_proj(hidden_states) else: q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))) q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2) # Flash attention requires the input to have the shape # batch_size x seq_length x head_dim x hidden_dim # therefore we just need to keep the original shape compressed_kv = self.kv_a_proj_with_mqa(hidden_states) compressed_kv, k_pe = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1) k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2) kv = ( self.kv_b_proj(self.kv_a_layernorm(compressed_kv)) .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim) .transpose(1, 2) ) k_nope, value_states = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1) # patch ulysses_sp_size = get_ulysses_sequence_parallel_world_size() if ulysses_sp_size > 1: validate_ulysses_config(self.num_heads, ulysses_sp_size) num_key_value_groups = self.config.num_attention_heads // self.config.num_key_value_heads k_pe = repeat_kv(k_pe, ulysses_sp_size) # to keep heads=1 after a2a k_nope = repeat_kv(k_nope, num_key_value_groups) value_states = repeat_kv(value_states, num_key_value_groups) q = gather_seq_scatter_heads(q, seq_dim=2, head_dim=1) k_pe = gather_seq_scatter_heads(k_pe, seq_dim=2, head_dim=1) k_nope = gather_seq_scatter_heads(k_nope, seq_dim=2, head_dim=1) value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1) # (batch_size, num_head / sp_size, seq_length, head_size) full_q_len = q.size(2) # full_q_len = seq_length else: full_q_len = q_len q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1) cos, sin = self.rotary_emb(value_states, seq_len=full_q_len) q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids) query_states = k_pe.new_empty(bsz, self.num_heads // ulysses_sp_size, full_q_len, self.q_head_dim) query_states[:, :, :, : self.qk_nope_head_dim] = q_nope query_states[:, :, :, self.qk_nope_head_dim :] = q_pe key_states = k_pe.new_empty(bsz, self.num_heads // ulysses_sp_size, full_q_len, self.q_head_dim) key_states[:, :, :, : self.qk_nope_head_dim] = k_nope key_states[:, :, :, self.qk_nope_head_dim :] = k_pe if self.q_head_dim != self.v_head_dim: value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim]) # TODO: These transpose are quite inefficient but Flash Attention requires the layout # [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache # to be able to avoid many of these transpose/reshape/view. query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) dropout_rate = self.attention_dropout if self.training else 0.0 attn_output = _flash_attention_forward( query_states, key_states, value_states, attention_mask, full_q_len, dropout=dropout_rate, sliding_window=None, is_causal=self.is_causal, use_top_left_mask=flash_attn_supports_top_left_mask(), position_ids=position_ids, # important: pass position ids softmax_scale=self.softmax_scale, ) if ulysses_sp_size > 1: attn_output = gather_heads_scatter_seq(attn_output, head_dim=2, seq_dim=1) if self.q_head_dim != self.v_head_dim: attn_output = attn_output[:, :, :, : self.v_head_dim] attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim).contiguous() attn_output = self.o_proj(attn_output) if is_transformers_version_in_range(min_version="4.53.0"): return attn_output, None else: return attn_output, None, None
verl__models__transformers__kimi_vl.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from typing import Callable, Optional import torch if sys.version_info >= (3, 11): pass else: pass from transformers.cache_utils import Cache from transformers.modeling_flash_attention_utils import _flash_attention_forward from transformers.models.llama.modeling_llama import apply_rotary_pos_emb from transformers.utils import logging # Import compatibility wrapper for flash_attn_supports_top_left_mask from verl.utils.transformers_compat import flash_attn_supports_top_left_mask from verl.utils.ulysses import ( gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_world_size, validate_ulysses_config, ) logger = logging.get_logger(__name__) def llama_flash_attn_forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46 **kwargs, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: """ Adapted from transformers 4.47.1 to support Ulysses sequence parallelism. NOTE: This function is used for transformers versions in the range [4.45.0, 4.47.1]. """ output_attentions = False bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) # Flash attention requires the input to have the shape # batch_size x seq_length x head_dim x hidden_dim # therefore we just need to keep the original shape query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) # trade off: repeat first and then all to all # key_states = repeat_kv(key_states, self.num_key_value_groups) # value_states = repeat_kv(value_states, self.num_key_value_groups) ########## AlltoAll for Ulysses ########## ulysses_sp_size = get_ulysses_sequence_parallel_world_size() if ulysses_sp_size > 1: validate_ulysses_config(self.num_heads, ulysses_sp_size) # (bsz, n_head, seq_len/n, head_dim) -> (bsz, n_head/n, seq_len, head_dim) query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1) key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1) value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1) full_q_len = query_states.size(2) # full seq length if position_embeddings is None: logger.warning_once( "The attention layers in this model are transitioning from computing the RoPE embeddings internally " "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed " "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be " "removed and `position_embeddings` will be mandatory." ) cos, sin = self.rotary_emb(value_states, position_ids) else: cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_value is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # TODO: These transpose are quite inefficient but Flash Attention requires the layout # [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache # to be able to avoid many of these transpose/reshape/view. query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) dropout_rate = self.attention_dropout if self.training else 0.0 # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (LlamaRMSNorm handles it correctly) input_dtype = query_states.dtype if input_dtype == torch.float32: if torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() # Handle the case where the model is quantized elif hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype else: target_dtype = self.q_proj.weight.dtype logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to " f"the fact you have upcasted embedding or layer norm layers in float32. We will cast back the " f"input in {target_dtype}." ) query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype) attn_output = _flash_attention_forward( query_states, key_states, value_states, attention_mask, full_q_len, position_ids=position_ids, dropout=dropout_rate, sliding_window=getattr(self, "sliding_window", None), use_top_left_mask=flash_attn_supports_top_left_mask(), is_causal=self.is_causal, **kwargs, ) attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous() ########## AlltoAll for Ulysses ########## if ulysses_sp_size > 1: attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2) attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() attn_output = self.o_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value def llama_attn_forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: """ Adapted from transformers 4.49.0 to support Ulysses sequence parallelism for transformers >= 4.48.0. NOTE: This function has been tested only on transformers versions between 4.48.0 and 4.50.0. """ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS from transformers.models.llama.modeling_llama import eager_attention_forward bsz, q_len, _ = hidden_states.shape query_states = self.q_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2) key_states = self.k_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2) value_states = self.v_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2) ########## AlltoAll for Ulysses ########## ulysses_sp_size = get_ulysses_sequence_parallel_world_size() if ulysses_sp_size > 1: validate_ulysses_config(self.config.num_attention_heads, ulysses_sp_size) query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1) key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1) value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1) full_q_len = query_states.size(2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_value is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False): logger.warning_once( "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. " "Falling back to eager attention. This warning can be removed using the argument " '`attn_implementation="eager"` when loading the model.' ) else: attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous() ########## AlltoAll for Ulysses ########## if ulysses_sp_size > 1: attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2) attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
verl__models__transformers__llama.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Apply monkey-patch function to models """ import sys from types import SimpleNamespace from typing import Optional import torch from transformers.modeling_flash_attention_utils import _flash_attention_forward from transformers.modeling_utils import PreTrainedModel from verl.utils.import_utils import is_trl_available from verl.utils.transformers_compat import is_transformers_version_in_range from verl.utils.ulysses import ( gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_group, get_ulysses_sequence_parallel_world_size, slice_input_tensor, ) _PREFIX_GROUPER_PATCHED = False _PREFIX_GROUPER_SUPPORTED_ATTENTIONS = {"flash_attention_2", "flash_attention_3", "sdpa", "flex_attention", "eager"} def _create_prefix_grouper_wrapper(original_fn): """Wrap attention function to support prefix_grouper in kwargs.""" def wrapped(module, query, key, value, attention_mask, *args, **kwargs): prefix_grouper = kwargs.pop("prefix_grouper", None) if prefix_grouper is None: return original_fn(module, query, key, value, attention_mask, *args, **kwargs) def attn_func(q, k, v, attn_mask, *inner_args, **inner_kwargs): out, _ = original_fn(module, q, k, v, attn_mask, *inner_args, **inner_kwargs) return out return prefix_grouper.forward(attn_func, query, key, value, *args, **kwargs), None return wrapped def apply_prefix_grouper_patch(): """Patch ALL_ATTENTION_FUNCTIONS to support prefix_grouper parameter.""" global _PREFIX_GROUPER_PATCHED if _PREFIX_GROUPER_PATCHED: return from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS patched = [] for name in list(ALL_ATTENTION_FUNCTIONS.keys()): if name in _PREFIX_GROUPER_SUPPORTED_ATTENTIONS: ALL_ATTENTION_FUNCTIONS[name] = _create_prefix_grouper_wrapper(ALL_ATTENTION_FUNCTIONS[name]) patched.append(name) _PREFIX_GROUPER_PATCHED = True print(f"[PrefixGrouper] Patched: {patched}") def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=2, repeats=n_rep). The hidden states go from (batch, seqlen, num_key_value_heads, head_dim) to (batch, seqlen, num_attention_heads, head_dim) """ batch, slen, num_key_value_heads, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, :, None, :].expand(batch, slen, num_key_value_heads, n_rep, head_dim) return hidden_states.reshape(batch, slen, num_key_value_heads * n_rep, head_dim) def _ulysses_flash_attention_forward( query_states: torch.Tensor, key_states: torch.Tensor, value_states: torch.Tensor, attention_mask: Optional[torch.Tensor], query_length: int, *args, position_ids: Optional[torch.Tensor] = None, **kwargs, ): """Insert all-to-all before and after flash attention. DeepSpeed-Ulysses: https://arxiv.org/pdf/2309.14509 For transformers>=4.55, the flash attention api has changed, we need to pass the query_length after doing ulysses all2all. See https://github.com/huggingface/transformers/issues/40399 Args: query_states (torch.Tensor): (batch_size, seqlen/sp_size, nheads, head_dim) key_states (torch.Tensor): (batch_size, seqlen/sp_size, nheads_k, head_dim) value_states (torch.Tensor): (batch_size, seqlen/sp_size, nheads_k, head_dim) position_ids (torch.Tensor, optional): (batch_size, seqlen/sp_size) Returns: torch.Tensor: (batch_size, seqlen/sp_size, nheads, head_dim) """ ulysses_sp_size = get_ulysses_sequence_parallel_world_size() ########## AlltoAll for Ulysses ########## # TODO: Disable sp for ViT, there's no elegent way to determine whether it's ViT or not. # Use `position_ids` as condition since ViT doesn't pass it to flash attention. if ulysses_sp_size > 1 and position_ids is not None: # NOTE: repeat kv heads to be divided by sequence parallel. Instead of repeating nheads_q//nheads_k, # we choose to repeat sp_size//nheads_k, since flash_attention supports MQA/GQA. # For example: # - nheads_k=4, sp=8, repeats=2 # - nheads_k=8, sp=8, repeats=1 # - nheads_k=16, sp=8, repeats=1 repeats = max(ulysses_sp_size // key_states.size(2), 1) key_states = repeat_kv(key_states, repeats) value_states = repeat_kv(value_states, repeats) # (bsz, seq_len/n, n_head, head_dim) -> (bsz, seq_len, n_head/n, head_dim) query_states = gather_seq_scatter_heads(query_states, seq_dim=1, head_dim=2) key_states = gather_seq_scatter_heads(key_states, seq_dim=1, head_dim=2) value_states = gather_seq_scatter_heads(value_states, seq_dim=1, head_dim=2) # TODO: all_gather position_ids because `prepare_fa2_from_position_ids` needs it, we can eliminate # this all_gather by passing cu_seq_lens_q, cu_seq_lens_k, max_length_k, max_length_q explicitly. # https://github.com/huggingface/transformers/pull/33932 # (bsz, seq_len/n) -> (bsz, seq_len) position_ids_list = [torch.empty_like(position_ids) for _ in range(ulysses_sp_size)] torch.distributed.all_gather(position_ids_list, position_ids, group=get_ulysses_sequence_parallel_group()) position_ids = torch.concat(position_ids_list, dim=-1) # (bsz, seq_len, n_head/n, head_dim) query_length = query_states.size(1) attn_output = _flash_attention_forward( query_states, key_states, value_states, attention_mask, query_length, *args, position_ids=position_ids, **kwargs ) ########## AlltoAll for Ulysses ########## if ulysses_sp_size > 1 and position_ids is not None: # (bsz, seq_len, n_head/n, head_dim) -> (bsz, seq_len/n, n_head, head_dim) attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2) return attn_output def patch_vlm_for_ulysses_input_slicing(model_class: type): """ Applies a monkey patch to the forward method of a given model class to enable Ulysses sequence parallelism input slicing. """ def _create_ulysses_wrapped_decoder_forward(original_forward): def ulysses_wrapped_decoder_forward(self, *args, **kwargs): inputs_embeds = kwargs.get("inputs_embeds") position_ids = kwargs.get("position_ids") visual_pos_masks = kwargs.get("visual_pos_masks") deepstack_visual_embeds = kwargs.get("deepstack_visual_embeds") call_kwargs = kwargs.copy() current_ulysses_sp_size = get_ulysses_sequence_parallel_world_size() slice_now = ( inputs_embeds is not None and current_ulysses_sp_size > 1 and getattr(self, "_needs_initial_slice", True) ) if slice_now: call_kwargs["inputs_embeds"] = slice_input_tensor(inputs_embeds, dim=1, padding=False) call_kwargs["position_ids"] = slice_input_tensor(position_ids, dim=-1, padding=False) # Also slice visual_pos_masks and deepstack_visual_embeds for Qwen3 VL models if visual_pos_masks is not None: original_visual_mask = visual_pos_masks sliced_visual_mask = slice_input_tensor(visual_pos_masks, dim=1, padding=False) call_kwargs["visual_pos_masks"] = sliced_visual_mask if deepstack_visual_embeds is not None: sliced_embeds = [] num_visual_before = original_visual_mask.sum().item() num_visual_in_shard = sliced_visual_mask.sum().item() if num_visual_in_shard > 0 and num_visual_before > 0: # Calculate which visual embeddings belong to this shard # We need to find the offset of visual tokens in this shard from verl.utils.ulysses import get_ulysses_sequence_parallel_rank rank = get_ulysses_sequence_parallel_rank() seq_len = original_visual_mask.shape[1] local_seq_len = seq_len // current_ulysses_sp_size start_idx = rank * local_seq_len end_idx = start_idx + local_seq_len # Get total visual tokens before and up to the end of the shard's sequence slice # This correctly handles batches by summing across all samples visual_start = original_visual_mask[:, :start_idx].sum().item() if start_idx > 0 else 0 visual_end = original_visual_mask[:, :end_idx].sum().item() # Slice each tensor in deepstack_visual_embeds for embed in deepstack_visual_embeds: sliced_embeds.append(embed[visual_start:visual_end]) else: # No visual tokens in this shard, create empty tensors to maintain gradient flow for embed in deepstack_visual_embeds: sliced_embeds.append(embed[:0]) call_kwargs["deepstack_visual_embeds"] = sliced_embeds self._needs_initial_slice = False try: return original_forward(self, *args, **call_kwargs) finally: if slice_now: self._needs_initial_slice = True return ulysses_wrapped_decoder_forward original_forward = model_class.forward wrapped_forward = _create_ulysses_wrapped_decoder_forward(original_forward) model_class.forward = wrapped_forward print(f"Monkey patch {model_class.__name__}.forward for Ulysses SP input slicing.") def patch_forward_with_backends( model: PreTrainedModel, use_fused_kernels: bool = False, fused_kernels_backend: str = None, ): """ Choose the forward function based on the model and backend. Args: model (PreTrainedModel): The model to apply the monkey patch. use_fused_kernels (bool): Whether to use fused kernels. fused_kernels_backend (str): The backend to use for fused kernels. """ if not use_fused_kernels or fused_kernels_backend not in ["triton", "torch"]: print( f"Skipping monkey patch for {model.__class__.__name__} as use_fused_kernels is " f"{use_fused_kernels} or fused_kernels_backend is {fused_kernels_backend}" ) return forward_with_torch_backend_function = model.__class__.forward forward_with_triton_backend_function = model.__class__.forward if model.config.model_type in ["qwen2_5_vl", "qwen2_vl"]: from verl.models.transformers.qwen2_vl import forward_with_torch_backend, forward_with_triton_backend forward_with_torch_backend_function = forward_with_torch_backend forward_with_triton_backend_function = forward_with_triton_backend elif model.config.model_type in ["qwen3_vl", "qwen3_vl_moe"]: from verl.models.transformers.qwen3_vl import forward_with_torch_backend, forward_with_triton_backend forward_with_torch_backend_function = forward_with_torch_backend forward_with_triton_backend_function = forward_with_triton_backend elif model.config.model_type == "glm4v": from verl.models.transformers.glm4v import forward_with_torch_backend, forward_with_triton_backend forward_with_torch_backend_function = forward_with_torch_backend forward_with_triton_backend_function = forward_with_triton_backend else: from verl.models.transformers.dense_common import forward_with_torch_backend, forward_with_triton_backend forward_with_torch_backend_function = forward_with_torch_backend forward_with_triton_backend_function = forward_with_triton_backend if fused_kernels_backend == "triton": model.__class__.forward = forward_with_triton_backend_function print(f"Using Triton backend for fused kernels in {model.__class__.__name__}") elif fused_kernels_backend == "torch": model.__class__.forward = forward_with_torch_backend_function print(f"Using Torch backend for fused kernels in {model.__class__.__name__}") else: raise ValueError(f"Unsupported fused_kernels_backend: {fused_kernels_backend}. Choose 'triton' or 'torch'.") def apply_monkey_patch( model: PreTrainedModel, ulysses_sp_size: int = 1, use_remove_padding: bool = True, use_fused_kernels: bool = False, fused_kernels_backend: str = None, use_prefix_grouper: bool = False, use_tiled_mlp: bool = False, tiled_mlp_shards: int = 4, ): """ Apply monkey patch to the models for ulysses sequence parallel, fused kernel, tiled MLP and prefix grouper. In the end of this function forward function of the model is patched for fused kernel. If the model is not supported with fused kernel, please return after patch. Args: model: The model to apply the monkey patch. ulysses_sp_size: The size of ulysses sequence parallel. use_remove_padding: Whether to use remove padding. use_fused_kernels: Whether to use fused kernels. fused_kernels_backend: The backend to use for fused kernels. use_tiled_mlp: Whether to use TiledMLP for memory-efficient MLP computation. tiled_mlp_shards: Number of shards for TiledMLP (higher = lower memory, slightly slower). """ # Apply TiledMLP monkey patch for memory-efficient MLP computation if use_tiled_mlp: from verl.models.transformers.tiled_mlp import apply_tiled_mlp_monkey_patch model_type = getattr(model.config, "model_type", None) apply_tiled_mlp_monkey_patch(num_shards=tiled_mlp_shards, model_type=model_type) # Apply PrefixGrouper patch if enabled if use_prefix_grouper: apply_prefix_grouper_patch() """Replace _flash_attention_forward to _ulysses_flash_attention_forward""" module = sys.modules[model.__module__] try: num_attention_heads, num_key_value_heads = model.config.num_attention_heads, model.config.num_key_value_heads except AttributeError: num_attention_heads, num_key_value_heads = ( model.config.text_config.num_attention_heads, model.config.text_config.num_key_value_heads, ) assert num_attention_heads % ulysses_sp_size == 0, ( f"num_attention_heads {num_attention_heads} must be divisible by ulysses_sp_size {ulysses_sp_size}" ) assert num_key_value_heads % ulysses_sp_size == 0 or ulysses_sp_size % num_key_value_heads == 0, ( f"num_key_value_heads {num_key_value_heads} must be divisible by ulysses_sp_size " f"{ulysses_sp_size}or vise versa. Upon ulysses_sp_size % num_key_value_heads == 0," f"kv heads are repeated to ensure correctness." ) if is_trl_available(): from trl import AutoModelForCausalLMWithValueHead # type: ignore def state_dict(self, *args, **kwargs): return torch.nn.Module.state_dict(self, *args, **kwargs) AutoModelForCausalLMWithValueHead.state_dict = state_dict print("Monkey patch state_dict in AutoModelForCausalLMWithValueHead. ") # TODO: VLM models only, unify monkey patch to LLM models. if model.config.model_type in ["qwen2_5_vl", "qwen2_vl"]: # Step 1: patch model to support image-text mixed data if is_transformers_version_in_range(min_version="4.52.0"): from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import ( Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLModel, Qwen2_5_VLTextModel, ) from transformers.models.qwen2_vl.modeling_qwen2_vl import ( Qwen2VLForConditionalGeneration, Qwen2VLModel, Qwen2VLTextModel, ) else: from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLForConditionalGeneration from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLModel as Qwen2_5_VLTextModel from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLForConditionalGeneration from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLModel as Qwen2VLTextModel Qwen2_5_VLModel = SimpleNamespace(forward=None) Qwen2VLModel = SimpleNamespace(forward=None) from verl.models.transformers.qwen2_vl import forward_with_normal_backend, qwen2_vl_base_forward Qwen2_5_VLModel.forward = qwen2_vl_base_forward Qwen2VLModel.forward = qwen2_vl_base_forward Qwen2_5_VLForConditionalGeneration.forward = forward_with_normal_backend Qwen2VLForConditionalGeneration.forward = forward_with_normal_backend print(f"Monkey patch {model.__class__.__name__} model forward") # Step 2: patch attention to support ulysses parallelism if is_transformers_version_in_range(min_version="4.54.0"): from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLAttention from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLAttention elif is_transformers_version_in_range(min_version="4.53.0"): raise RuntimeError("Transformers 4.53.* is bugged. Use transformers 4.54.0 or later.") else: from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import ( Qwen2_5_VLFlashAttention2 as Qwen2_5_VLAttention, ) from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLFlashAttention2 as Qwen2VLAttention if use_remove_padding or ulysses_sp_size > 1: from verl.models.transformers.qwen2_vl import qwen2_vl_attn_forward Qwen2_5_VLAttention.forward = qwen2_vl_attn_forward Qwen2VLAttention.forward = qwen2_vl_attn_forward print(f"Monkey patch {model.__class__.__name__} attention layer") # Step 3: patch input for multimodal sequence parallelism if ulysses_sp_size > 1: patch_vlm_for_ulysses_input_slicing(Qwen2_5_VLTextModel) patch_vlm_for_ulysses_input_slicing(Qwen2VLTextModel) elif model.config.model_type in ["qwen3_vl", "qwen3_vl_moe"]: # Step 1: patch model to support image-text mixed data from transformers.models.qwen3_vl.modeling_qwen3_vl import ( Qwen3VLForConditionalGeneration, Qwen3VLModel, Qwen3VLTextModel, ) from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import ( Qwen3VLMoeForConditionalGeneration, Qwen3VLMoeModel, Qwen3VLMoeTextModel, ) from verl.models.transformers.qwen3_vl import ( forward_with_normal_backend, patch_qwen3_vl_moe_sparse_moe_block_forward, qwen3_vl_base_forward, ) Qwen3VLModel.forward = qwen3_vl_base_forward Qwen3VLMoeModel.forward = qwen3_vl_base_forward Qwen3VLForConditionalGeneration.forward = forward_with_normal_backend Qwen3VLMoeForConditionalGeneration.forward = forward_with_normal_backend print(f"Monkey patch {model.__class__.__name__} model forward") # Step 1.5: patch Qwen3VLMoeTextSparseMoeBlock to fix transformers 4.57.3 bug if model.config.model_type == "qwen3_vl_moe" and is_transformers_version_in_range(max_version="4.57.3"): patch_qwen3_vl_moe_sparse_moe_block_forward() # Step 2: patch input for multimodal sequence parallelism if ulysses_sp_size > 1: patch_vlm_for_ulysses_input_slicing(Qwen3VLTextModel) patch_vlm_for_ulysses_input_slicing(Qwen3VLMoeTextModel) elif model.config.model_type == "glm4v": # Step 1: patch model to support image-text mixed data from transformers.models.glm4v.modeling_glm4v import ( Glm4vForConditionalGeneration, Glm4vModel, Glm4vTextAttention, Glm4vTextModel, ) from verl.models.transformers.glm4v import forward_with_normal_backend, glm4v_base_forward Glm4vModel.forward = glm4v_base_forward Glm4vForConditionalGeneration.forward = forward_with_normal_backend print(f"Monkey patch {model.__class__.__name__} model forward") # Step 2: patch attention to support ulysses parallelism if use_remove_padding or ulysses_sp_size > 1: from verl.models.transformers.glm4v import glm4v_attn_forward Glm4vTextAttention.forward = glm4v_attn_forward print(f"Monkey patch {model.__class__.__name__} attention layer") # Step 3: patch input for multimodal sequence parallelism if ulysses_sp_size > 1: patch_vlm_for_ulysses_input_slicing(Glm4vTextModel) elif model.config.model_type == "kimi_vl": if use_remove_padding or ulysses_sp_size > 1: # TODO: Changes need to be made when transformers are adapted. from verl.models.transformers.kimi_vl import _ulysses_flash_attn_forward module.DeepseekV3FlashAttention2.forward = _ulysses_flash_attn_forward print("Monkey patch FlashAttention2.forward in KimiVL") if ulysses_sp_size > 1: patch_vlm_for_ulysses_input_slicing(module.DeepseekV3ForCausalLM) if use_fused_kernels: print("Not support fused kernels for KimiVL") return if use_remove_padding or ulysses_sp_size > 1: if hasattr(module, "_flash_attention_forward"): # transformers <= 4.47.1 or legacy models module._flash_attention_forward = _ulysses_flash_attention_forward print(f"Monkey patch _flash_attention_forward in {model.__module__}") else: from transformers.integrations import flash_attention flash_attention._flash_attention_forward = _ulysses_flash_attention_forward print(f"Monkey patch _flash_attention_forward in {flash_attention.__name__}") patch_forward_with_backends(model, use_fused_kernels=use_fused_kernels, fused_kernels_backend=fused_kernels_backend)
verl__models__transformers__monkey_patch.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Copyright 2025 The Qwen Team and The HuggingFace Inc. team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import torch.nn.functional as F import torch_npu from torch import nn from transformers.activations import ACT2FN from transformers.models.qwen2 import modeling_qwen2 from transformers.models.qwen2_5_vl import modeling_qwen2_5_vl from transformers.models.qwen3 import modeling_qwen3 from transformers.models.qwen3_moe import modeling_qwen3_moe from transformers.models.qwen3_next import modeling_qwen3_next from transformers.models.qwen3_vl import modeling_qwen3_vl from transformers.models.qwen3_vl_moe import modeling_qwen3_vl_moe from transformers.utils import logging logger = logging.get_logger(__name__) def rms_norm_forward_npu(self, x): """NPU optimized implementation for RMSNorm.""" if x.dtype != self.weight.dtype: x = x.to(self.weight.dtype) return torch_npu.npu_rms_norm(x, self.weight, epsilon=self.variance_epsilon)[0] def silu_forward_npu(self, hidden_state): """NPU optimized implementation for SiLU in `forward` func in MLP layer.""" gate_up = torch.cat((self.gate_proj(hidden_state), self.up_proj(hidden_state)), dim=-1) return self.down_proj(torch_npu.npu_swiglu(gate_up, dim=-1)) def apply_rotary_pos_emb_npu(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): """NPU optimized implementation for RoPE.""" cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = torch_npu.npu_rotary_mul(q, cos, sin) k_embed = torch_npu.npu_rotary_mul(k, cos, sin) return q_embed.to(q.dtype), k_embed.to(k.dtype) def qwen3_next_rms_norm_forward_npu(self, x): return torch_npu.npu_rms_norm(x.float(), 1.0 + self.weight.float(), epsilon=self.eps)[0].type_as(x) def qwen3_next_rms_norm_forward_gated_npu(self, hidden_states, gate=None): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) hidden_states = torch_npu.npu_rms_norm(hidden_states, self.weight.float(), epsilon=self.variance_epsilon)[0] hidden_states = hidden_states * F.silu(gate.to(torch.float32)) return hidden_states.to(input_dtype) def qwen3_next_apply_rotary_pos_emb_npu(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) # Keep half or full tensor for later concatenation rotary_dim = cos.shape[-1] q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:] k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:] q_embed = torch_npu.npu_rotary_mul(q_rot, cos, sin).to(q.dtype) k_embed = torch_npu.npu_rotary_mul(k_rot, cos, sin).to(k.dtype) q_embed = torch.cat([q_embed, q_pass], dim=-1) k_embed = torch.cat([k_embed, k_pass], dim=-1) return q_embed, k_embed class NPUGmmFunction(torch.autograd.Function): @staticmethod def forward(ctx, x, weight, group_list, group_list_type=1): """ Grouped Matmul(GMM) for Ascend NPU. Args: x (torch.Tensor): Input tensor, shape (tokens_num * top_k, hidden_size) weight (torch.Tensor): Expert weights, shape (n_experts, hidden_size, intermediate_size) group_list (torch.Tensor): Expert token counts, shape (n_experts,) - type 0: cumsum of tokens per expert - type 1: direct tokens per expert (default) """ ctx.save_for_backward(x, weight) ctx.group_list = group_list ctx.group_list_type = group_list_type output = torch_npu.npu_grouped_matmul( [x], [weight], bias=None, group_list=group_list, split_item=2, group_type=0, group_list_type=group_list_type )[0] return output @staticmethod def backward(ctx, grad_output): x, weight = ctx.saved_tensors group_list = ctx.group_list group_list_type = ctx.group_list_type dx = torch_npu.npu_grouped_matmul( [grad_output], [weight.transpose(1, 2)], bias=None, group_list=group_list, split_item=2, group_type=0, group_list_type=group_list_type, )[0] dw = torch_npu.npu_grouped_matmul( [x.transpose(0, 1)], [grad_output], bias=None, group_list=group_list, split_item=3, group_type=2, group_list_type=group_list_type, )[0] return dx, dw, None, None def _qwen3_sparse_moe_routed_forward_npu(self, hidden_states: torch.Tensor): """ Shared NPU routed-expert path for Qwen3Moe/Qwen3Next sparse MoE blocks. Returns: tuple: (flattened_input, routed_hidden_states, router_logits) """ hidden_dim = hidden_states.shape[-1] hidden_states = hidden_states.view(-1, hidden_dim) # router_logits: (batch * sequence_length, n_experts) router_logits = self.gate(hidden_states) routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float) routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1) if self.norm_topk_prob: # only diff with mixtral sparse moe block! routing_weights /= routing_weights.sum(dim=-1, keepdim=True) # we cast back to the input dtype routing_weights = routing_weights.to(hidden_states.dtype) # Loop over all available experts in the model and perform the computation on each expert # Concat all weights input_dtype = hidden_states.dtype up_weight_list = [e.up_proj.weight for e in self.experts] gate_weight_list = [e.gate_proj.weight for e in self.experts] down_weight_list = [e.down_proj.weight for e in self.experts] w1 = torch.stack(up_weight_list).transpose(1, 2).to(input_dtype) w2 = torch.stack(gate_weight_list).transpose(1, 2).to(input_dtype) w3 = torch.stack(down_weight_list).transpose(1, 2).to(input_dtype) permuted_tokens, row_ids_map = torch_npu.npu_moe_token_permute(hidden_states, selected_experts.to(torch.int32)) tokens_per_expert = torch.histc(selected_experts, bins=self.num_experts, min=0, max=self.num_experts) up_res = NPUGmmFunction.apply(permuted_tokens, w1, tokens_per_expert) gate_res = NPUGmmFunction.apply(permuted_tokens, w2, tokens_per_expert) act_res = torch_npu.npu_swiglu(torch.cat([gate_res, up_res], dim=-1)) down_res = NPUGmmFunction.apply(act_res, w3, tokens_per_expert) routed_hidden_states = torch_npu.npu_moe_token_unpermute(down_res, row_ids_map, probs=routing_weights) return hidden_states, routed_hidden_states, router_logits def qwen3_moe_sparse_moe_block_forward_npu(self, hidden_states: torch.Tensor) -> torch.Tensor: """NPU optimized implementation for `forward` in Qwen3MoeSparseMoeBlock.""" output_shape = hidden_states.shape _, routed_hidden_states, router_logits = _qwen3_sparse_moe_routed_forward_npu(self, hidden_states) final_hidden_states = routed_hidden_states.reshape(output_shape) return final_hidden_states, router_logits def qwen3_next_sparse_moe_block_forward_npu(self, hidden_states: torch.Tensor) -> torch.Tensor: """NPU optimized implementation for `forward` in Qwen3NextSparseMoeBlock.""" output_shape = hidden_states.shape hidden_states, routed_hidden_states, router_logits = _qwen3_sparse_moe_routed_forward_npu(self, hidden_states) shared_expert_output = self.shared_expert(hidden_states) shared_expert_output = torch.sigmoid(self.shared_expert_gate(hidden_states)) * shared_expert_output final_hidden_states = (routed_hidden_states + shared_expert_output).reshape(output_shape) return final_hidden_states, router_logits class NPUQwen3VLMoeTextExperts(nn.Module): """NPU optimized implementation for Qwen3VLMoeTextExperts.""" def __init__(self, config): super().__init__() self.num_experts = config.num_experts self.intermediate_size = config.moe_intermediate_size self.hidden_size = config.hidden_size self.expert_dim = self.intermediate_size self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_size, 2 * self.expert_dim)) self.down_proj = nn.Parameter(torch.empty((self.num_experts, self.expert_dim, self.hidden_size))) self.act_fn = ACT2FN[config.hidden_act] def forward( self, hidden_states: torch.Tensor, routing_weights: torch.Tensor, router_indices: torch.Tensor ) -> torch.Tensor: """ When training it is more efficient to just loop over the experts and compute the output for each expert as otherwise the memory would explode. For inference we can sacrifice some memory and compute the output for all experts at once. By repeating the inputs. Args: hidden_states (torch.Tensor): (batch_size * token_num, hidden_size) routing_weights (torch.Tensor): (batch_size * token_num, num_experts) router_indices (torch.Tensor): (batch_size * token_num, top_k) Returns: torch.Tensor """ batch_size = hidden_states.shape[0] hidden_states = hidden_states.reshape(-1, self.hidden_size) # (num_tokens, hidden_size) if self.training: permuted_hidden_states, row_ids_map = torch_npu.npu_moe_token_permute( hidden_states, router_indices.to(torch.int32) ) tokens_per_expert = torch.histc(router_indices, bins=self.num_experts, min=0, max=self.num_experts) intermediate_hidden_states = NPUGmmFunction.apply( permuted_hidden_states, self.gate_up_proj, tokens_per_expert ) intermediate_activations = torch_npu.npu_swiglu(intermediate_hidden_states, dim=-1) output = NPUGmmFunction.apply(intermediate_activations, self.down_proj, tokens_per_expert) num_tokens = hidden_states.shape[0] top_k = router_indices.shape[1] batch_idx = torch.arange(num_tokens, device=routing_weights.device) batch_idx = batch_idx.unsqueeze(1).expand(-1, top_k) selected_probs = routing_weights[batch_idx, router_indices] next_states = torch_npu.npu_moe_token_unpermute(output, row_ids_map, probs=selected_probs) next_states = next_states.view(batch_size, -1, self.hidden_size) else: hidden_states = hidden_states.repeat(self.num_experts, 1) hidden_states = hidden_states.view(self.num_experts, -1, self.hidden_size) gate_up = torch.bmm(hidden_states, self.gate_up_proj) gate, up = gate_up.chunk(2, dim=-1) # not supported for DTensors next_states = torch.bmm((up * self.act_fn(gate)), self.down_proj) next_states = next_states.reshape(self.num_experts, batch_size, -1, self.hidden_size) next_states = ( next_states * routing_weights.transpose(0, 1).view(self.num_experts, batch_size, -1)[..., None] ) next_states = next_states.sum(dim=0) return next_states class NPUQwen3VLMoeTextSparseMoeBlock(nn.Module): """NPU optimized implementation for Qwen3VLMoeTextSparseMoeBlock.""" def __init__(self, config): super().__init__() self.hidden_size = config.hidden_size self.num_experts = config.num_experts self.top_k = config.num_experts_per_tok self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False) self.experts = NPUQwen3VLMoeTextExperts(config) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size = hidden_states.shape[0] hidden_states = hidden_states.reshape(-1, self.hidden_size) router_logits = self.gate(hidden_states) routing_weights = torch.nn.functional.softmax(router_logits, dim=-1, dtype=torch.float) routing_weights, router_indices = torch.topk(routing_weights, self.top_k, dim=-1) routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True) routing_weights = routing_weights.to(router_logits.dtype) hidden_states = hidden_states.reshape(batch_size, -1, self.hidden_size) if not self.training: routing_weights = torch.zeros_like(router_logits).scatter_(1, router_indices, routing_weights) routed_out = self.experts(hidden_states, routing_weights, router_indices) return routed_out # Patches for Qwen2 Model modeling_qwen2.Qwen2RMSNorm.forward = rms_norm_forward_npu modeling_qwen2.Qwen2MLP.forward = silu_forward_npu modeling_qwen2.apply_rotary_pos_emb = apply_rotary_pos_emb_npu # Patches for Qwen2.5-VL Model modeling_qwen2_5_vl.Qwen2RMSNorm.forward = rms_norm_forward_npu modeling_qwen2_5_vl.Qwen2_5_VLMLP.forward = silu_forward_npu # 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 Model modeling_qwen3_moe.Qwen3MoeRMSNorm.forward = rms_norm_forward_npu modeling_qwen3_moe.Qwen3MoeSparseMoeBlock.forward = qwen3_moe_sparse_moe_block_forward_npu modeling_qwen3_moe.apply_rotary_pos_emb = apply_rotary_pos_emb_npu # Patches for Qwen3 VL Model modeling_qwen3_vl.Qwen3VLTextRMSNorm.forward = rms_norm_forward_npu modeling_qwen3_vl.Qwen3VLTextMLP.forward = silu_forward_npu # Patches for Qwen3-VL MoE Model modeling_qwen3_vl_moe.Qwen3VLMoeTextSparseMoeBlock = NPUQwen3VLMoeTextSparseMoeBlock modeling_qwen3_vl_moe.Qwen3VLMoeTextRMSNorm.forward = rms_norm_forward_npu modeling_qwen3_vl_moe.apply_rotary_pos_emb = apply_rotary_pos_emb_npu # Patches for Qwen3 Next Model modeling_qwen3_next.Qwen3NextSparseMoeBlock.forward = qwen3_next_sparse_moe_block_forward_npu modeling_qwen3_next.Qwen3NextRMSNormGated.forward = qwen3_next_rms_norm_forward_gated_npu modeling_qwen3_next.Qwen3NextRMSNorm.forward = qwen3_next_rms_norm_forward_npu modeling_qwen3_next.apply_rotary_pos_emb = qwen3_next_apply_rotary_pos_emb_npu
verl__models__transformers__npu_patch.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Callable, Optional import torch from transformers.cache_utils import Cache from transformers.modeling_flash_attention_utils import _flash_attention_forward from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv from transformers.utils import logging # Import compatibility wrapper for flash_attn_supports_top_left_mask from verl.utils.transformers_compat import flash_attn_supports_top_left_mask from verl.utils.ulysses import ( gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_world_size, validate_ulysses_config, ) logger = logging.get_logger(__name__) def qwen2_flash_attn_forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46 ): """ Adapted from transformers 4.47.1 to support Ulysses sequence parallelism. NOTE: This function is only tested on transformers versions between 4.45.0 and 4.47.1. """ bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) ########## AlltoAll for Ulysses ########## ulysses_sp_size = get_ulysses_sequence_parallel_world_size() if ulysses_sp_size > 1: validate_ulysses_config(self.num_heads, ulysses_sp_size) # (bsz, n_head, seq_len/n, head_dim) -> (bsz, n_head/n, seq_len, head_dim) query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1) key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1) value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1) full_q_len = query_states.size(2) # full seq length if position_embeddings is None: logger.warning_once( "The attention layers in this model are transitioning from computing the RoPE embeddings internally " "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed " "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be " "removed and `position_embeddings` will be mandatory." ) cos, sin = self.rotary_emb(value_states, position_ids) else: cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # repeat k/v heads if n_kv_heads < n_heads key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) dropout_rate = 0.0 if not self.training else self.attention_dropout # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in float16 just to be sure everything works as expected. input_dtype = query_states.dtype if input_dtype == torch.float32: if torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() # Handle the case where the model is quantized elif hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype else: target_dtype = self.q_proj.weight.dtype logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to " f"the fact you have upcasted embedding or layer norm layers in float32. We will cast back the " f"input in {target_dtype}." ) query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype) # Reashape to the expected shape for Flash Attention query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) if ( self.config.use_sliding_window and getattr(self.config, "sliding_window", None) is not None and self.layer_idx >= self.config.max_window_layers ): sliding_window = self.config.sliding_window else: sliding_window = None attn_output = _flash_attention_forward( query_states, key_states, value_states, attention_mask, full_q_len, position_ids=position_ids, dropout=dropout_rate, sliding_window=sliding_window, is_causal=self.is_causal, use_top_left_mask=flash_attn_supports_top_left_mask(), ) # use full_q_len to reshape attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous() ########## AlltoAll for Ulysses ########## if ulysses_sp_size > 1: attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2) attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() attn_output = self.o_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value def qwen2_attn_forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: """ Adapted from transformers 4.49.0 to support Ulysses sequence parallelism for transformers >= 4.48.0. NOTE: This function has been tested only on transformers versions between 4.48.0 and 4.50.0. """ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS bsz, q_len, _ = hidden_states.shape hidden_shape = (bsz, q_len, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) ########## AlltoAll for Ulysses ########## ulysses_sp_size = get_ulysses_sequence_parallel_world_size() if ulysses_sp_size > 1: validate_ulysses_config(self.config.num_attention_heads, ulysses_sp_size) # (bsz, n_head, seq_len/n, head_dim) -> (bsz, n_head/n, seq_len, head_dim) query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1) key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1) value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1) full_q_len = query_states.size(2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_value is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) sliding_window = None if ( self.config.use_sliding_window and getattr(self.config, "sliding_window", None) is not None and self.layer_idx >= self.config.max_window_layers ): sliding_window = self.config.sliding_window from transformers.models.qwen2.modeling_qwen2 import eager_attention_forward attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False): logger.warning_once( "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. " "Falling back to eager attention. This warning can be removed using the argument " '`attn_implementation="eager"` when loading the model.' ) else: attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, sliding_window=sliding_window, # main diff with Llama **kwargs, ) attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous() ########## AlltoAll for Ulysses ########## if ulysses_sp_size > 1: # (bsz, seq_len, n_head/n, head_dim) -> (bsz, seq_len/n, n_head, head_dim) attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2) attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
verl__models__transformers__qwen2.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import logging import os from dataclasses import dataclass from typing import Optional import torch import torch.distributed as dist from transformers.modeling_flash_attention_utils import _flash_attention_forward, fa_peft_integration_check from transformers.models.qwen2_vl.modeling_qwen2_vl import ( Qwen2VLAttention, Qwen2VLCausalLMOutputWithPast, Qwen2VLForConditionalGeneration, ) from transformers.utils import is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10 from verl.utils.device import is_npu_available from verl.utils.transformers_compat import is_transformers_version_in_range from verl.utils.ulysses import ( gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_group, get_ulysses_sequence_parallel_world_size, validate_ulysses_config, ) logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func _flash_supports_window_size = "window_size" in inspect.signature(flash_attn_func).parameters _flash_supports_deterministic = "deterministic" in inspect.signature(flash_attn_func).parameters _flash_use_top_left_mask = not is_flash_attn_greater_or_equal_2_10() if is_npu_available: from transformers.integrations.npu_flash_attention import npu_flash_attn_func as flash_attn_func from transformers.integrations.npu_flash_attention import npu_flash_attn_varlen_func as flash_attn_varlen_func from transformers.modeling_flash_attention_utils import flash_attn_supports_top_left_mask _flash_supports_window_size = "window_size" in inspect.signature(flash_attn_func).parameters _flash_supports_deterministic = "deterministic" in inspect.signature(flash_attn_func).parameters _flash_use_top_left_mask = flash_attn_supports_top_left_mask() _flash_deterministic_enabled = os.getenv("FLASH_ATTENTION_DETERMINISTIC", "0") == "1" def get_rope_index( processor, input_ids: torch.Tensor, image_grid_thw: Optional[torch.Tensor] = None, video_grid_thw: Optional[torch.Tensor] = None, second_per_grid_ts: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, ) -> torch.Tensor: """ Gets the position ids for Qwen2-VL, it should be generated before sharding the sequence. The batch dim has been removed and the input_ids should be a 1D tensor representing a single example. https://github.com/huggingface/transformers/blob/v4.52.4/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py#L1405 """ spatial_merge_size = processor.image_processor.merge_size tokens_per_second = 2 image_token_id = processor.tokenizer.convert_tokens_to_ids("<|image_pad|>") video_token_id = processor.tokenizer.convert_tokens_to_ids("<|video_pad|>") vision_start_token_id = processor.tokenizer.convert_tokens_to_ids("<|vision_start|>") if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): if attention_mask is None: attention_mask = torch.ones_like(input_ids) position_ids = torch.ones(3, input_ids.size(0), dtype=input_ids.dtype, device=input_ids.device) # (3, seqlen) image_index, video_index = 0, 0 input_ids = input_ids[attention_mask == 1] image_nums, video_nums = 0, 0 vision_start_indices = torch.argwhere(input_ids == vision_start_token_id) vision_tokens = input_ids[vision_start_indices + 1] image_nums = (vision_tokens == image_token_id).sum() video_nums = (vision_tokens == video_token_id).sum() input_tokens = input_ids.tolist() llm_pos_ids_list: list = [] st = 0 remain_images, remain_videos = image_nums, video_nums for _ in range(image_nums + video_nums): if image_token_id in input_tokens and remain_images > 0: ed_image = input_tokens.index(image_token_id, st) else: ed_image = len(input_tokens) + 1 if video_token_id in input_tokens and remain_videos > 0: ed_video = input_tokens.index(video_token_id, st) else: ed_video = len(input_tokens) + 1 if ed_image < ed_video: t, h, w = ( image_grid_thw[image_index][0], image_grid_thw[image_index][1], image_grid_thw[image_index][2], ) second_per_grid_t = 0 image_index += 1 remain_images -= 1 ed = ed_image else: t, h, w = ( video_grid_thw[video_index][0], video_grid_thw[video_index][1], video_grid_thw[video_index][2], ) second_per_grid_t = second_per_grid_ts[video_index] if second_per_grid_ts is not None else 1.0 video_index += 1 remain_videos -= 1 ed = ed_video llm_grid_t, llm_grid_h, llm_grid_w = ( t.item(), h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) text_len = ed - st st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w) t_index = (t_index * second_per_grid_t * tokens_per_second).long().flatten() h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) st = ed + llm_grid_t * llm_grid_h * llm_grid_w if st < len(input_tokens): st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 text_len = len(input_tokens) - st llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device) else: if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = position_ids.unsqueeze(0).expand(3, -1).to(input_ids.device) else: position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, -1).expand(3, -1) return position_ids def prepare_fa2_from_position_ids( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, position_ids: torch.Tensor ): assert position_ids.ndim == 2 # (batch_size, seq_length) query = query.contiguous().view(-1, query.size(-2), query.size(-1)) key = key.contiguous().view(-1, key.size(-2), key.size(-1)) value = value.contiguous().view(-1, value.size(-2), value.size(-1)) position_ids = position_ids.view(-1) cu_seqlens = torch.cat( ( (position_ids == 0).nonzero().view(-1).to(torch.int32), torch.tensor(position_ids.size(), device=position_ids.device, dtype=torch.int32), ) ) max_length = cu_seqlens.diff().max() # use cu_seqlens to infer max_length for qwen2vl mrope return (query, key, value, (cu_seqlens, cu_seqlens), (max_length, max_length)) def _custom_flash_attention_forward( query_states: torch.Tensor, key_states: torch.Tensor, value_states: torch.Tensor, attention_mask: Optional[torch.Tensor], query_length: int, is_causal: bool = True, position_ids: Optional[torch.Tensor] = None, sliding_window: Optional[int] = None, use_top_left_mask: bool = False, deterministic: Optional[bool] = None, **kwargs, ): """ Patches flash attention forward to handle 3D position ids in mrope. (3, batch_size, seq_length) """ # Assuming 4D tensors, key_states.shape[1] is the key/value sequence length (source length). use_sliding_windows = ( _flash_supports_window_size and sliding_window is not None and key_states.shape[1] > sliding_window ) flash_kwargs = {"window_size": (sliding_window, sliding_window)} if use_sliding_windows else {} if _flash_supports_deterministic: flash_kwargs["deterministic"] = deterministic if deterministic is not None else _flash_deterministic_enabled if kwargs.get("softcap") is not None: flash_kwargs["softcap"] = kwargs.pop("softcap") query_states, key_states, value_states = fa_peft_integration_check( query_states, key_states, value_states, target_dtype=torch.bfloat16 ) if position_ids is not None: assert position_ids.ndim == 2 # (batch_size, seq_length / sp_size) sp_size = get_ulysses_sequence_parallel_world_size() if sp_size > 1: # qkv: (batch_size, seq_length / sp_size, num_head, head_size) validate_ulysses_config(query_states.size(2), sp_size) query_states = gather_seq_scatter_heads(query_states, seq_dim=1, head_dim=2) key_states = gather_seq_scatter_heads(key_states, seq_dim=1, head_dim=2) value_states = gather_seq_scatter_heads(value_states, seq_dim=1, head_dim=2) position_ids_lst = [torch.empty_like(position_ids) for _ in range(sp_size)] position_ids = dist.all_gather(position_ids_lst, position_ids, group=get_ulysses_sequence_parallel_group()) position_ids = torch.cat(position_ids_lst, dim=-1) # (batch_size, seq_length) if position_ids is not None and query_length != 1 and not (torch.diff(position_ids, dim=-1) >= 0).all(): batch_size = query_states.size(0) q, k, v, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_q, max_seqlen_k) = prepare_fa2_from_position_ids( query_states, key_states, value_states, position_ids ) attn_output = flash_attn_varlen_func( q=q, k=k, v=v, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_k, dropout_p=kwargs.pop("dropout", 0.0), softmax_scale=kwargs.pop("softmax_scale", None), causal=is_causal, **flash_kwargs, ) attn_output = attn_output.view(batch_size, -1, attn_output.size(-2), attn_output.size(-1)) else: attn_output = _flash_attention_forward( query_states, key_states, value_states, attention_mask, query_length, is_causal=is_causal, sliding_window=sliding_window, use_top_left_mask=use_top_left_mask, deterministic=deterministic, **kwargs, ) # do not pass position_ids to old flash_attention_forward if sp_size > 1: # (batch_size, seq_length, num_head, head_size) attn_output = gather_heads_scatter_seq(attn_output, head_dim=2, seq_dim=1) return attn_output def qwen2_vl_attn_forward( self: "Qwen2VLAttention", hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46 **kwargs, ) -> tuple[torch.Tensor, None, None]: from transformers.models.qwen2_vl.modeling_qwen2_vl import apply_multimodal_rotary_pos_emb, repeat_kv bsz, q_len, _ = hidden_states.size() # q_len = seq_length / sp_size query_states = self.q_proj(hidden_states) # (batch_size, seq_length / sp_size, num_heads * head_size) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) # Because the input can be padded, the absolute sequence length depends on the max position id. cos, sin = position_embeddings query_states, key_states = apply_multimodal_rotary_pos_emb( query_states, key_states, cos, sin, self.rope_scaling["mrope_section"] ) key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) dropout_rate = 0.0 if not self.training else self.attention_dropout sliding_window = None if ( self.config.use_sliding_window and getattr(self.config, "sliding_window", None) is not None and self.layer_idx >= self.config.max_window_layers ): sliding_window = self.config.sliding_window # This is before the transpose q_len = query_states.shape[2] # FA2 uses non-transposed inputs query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) if position_ids.ndim == 3: position_ids = position_ids[0] attn_output = _custom_flash_attention_forward( query_states, key_states, value_states, attention_mask, query_length=q_len, is_causal=getattr(self, "is_causal", True), dropout=dropout_rate, sliding_window=sliding_window, use_top_left_mask=_flash_use_top_left_mask, position_ids=position_ids, # important: pass position ids ) # (batch_size, seq_length / sp_size, num_head, head_size) attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() attn_output = self.o_proj(attn_output) if is_transformers_version_in_range(min_version="4.54.0"): return attn_output, None else: return attn_output, None, None def _get_input_embeds( model: "Qwen2VLForConditionalGeneration", input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, ): inputs_embeds = model.get_input_embeddings()(input_ids) if pixel_values is not None: pixel_values = pixel_values.type(model.visual.dtype) image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) n_image_tokens = (input_ids == model.config.image_token_id).sum().item() n_image_features = image_embeds.shape[0] if n_image_tokens != n_image_features: raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" ) mask = input_ids == model.config.image_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) image_mask = mask_expanded.to(inputs_embeds.device) image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) 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 = model.visual(pixel_values_videos, grid_thw=video_grid_thw) n_video_tokens = (input_ids == model.config.video_token_id).sum().item() n_video_features = video_embeds.shape[0] if n_video_tokens != n_video_features: raise ValueError( f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" ) mask = input_ids == model.config.video_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) video_mask = mask_expanded.to(inputs_embeds.device) video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) if pixel_values is None and pixel_values_videos is None: # handle mixed text-image data config = model.config.vision_config patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2 pixel_values = torch.zeros((16, patch_dim), dtype=inputs_embeds.dtype, device=inputs_embeds.device) image_grid_thw = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device) image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) inputs_embeds += 0.0 * image_embeds.mean() if attention_mask is not None: attention_mask = attention_mask.to(inputs_embeds.device) return inputs_embeds, attention_mask def process_position_ids(position_ids: torch.Tensor) -> torch.Tensor: if position_ids.ndim != 3 or position_ids.size(0) != 4: # we concat the text position ids with the 3D vision position ids by default # see https://github.com/huggingface/transformers/pull/39447 raise ValueError("position_ids should be a 3D tensor of shape (4, batch_size, seq_length).") if is_transformers_version_in_range(max_version="4.53.3"): # transformers < 4.54.0 only accepts vision position ids, so we discard the text position ids here position_ids = position_ids[1:] return position_ids @dataclass class Qwen2VLCausalLMOutputForPPO(Qwen2VLCausalLMOutputWithPast): log_probs: Optional[torch.FloatTensor] = None entropy: Optional[torch.FloatTensor] = None def qwen2_vl_base_forward( self: "Qwen2VLForConditionalGeneration", input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, **kwargs, ): kwargs["inputs_embeds"], kwargs["attention_mask"] = _get_input_embeds( self, input_ids, attention_mask, pixel_values, pixel_values_videos, image_grid_thw, video_grid_thw ) # avoid lora module having multiple keyword arguments return self.language_model(input_ids=None, **kwargs) def qwen2_vl_forward( self: "Qwen2VLForConditionalGeneration", input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, **kwargs, ): if is_transformers_version_in_range(min_version="4.52.0"): return self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=process_position_ids(position_ids), pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, **kwargs, ) else: inputs_embeds, attention_mask = _get_input_embeds( self, input_ids, attention_mask, pixel_values, pixel_values_videos, image_grid_thw, video_grid_thw ) return self.model( input_ids=None, attention_mask=attention_mask, position_ids=process_position_ids(position_ids), inputs_embeds=inputs_embeds, **kwargs, ) def forward_with_normal_backend( self: Qwen2VLForConditionalGeneration, input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> "Qwen2VLCausalLMOutputWithPast": outputs = qwen2_vl_forward(self, input_ids, **kwargs) hidden_states = outputs[0] logits = self.lm_head(hidden_states) return Qwen2VLCausalLMOutputWithPast( logits=logits, hidden_states=outputs.hidden_states, ) def forward_with_torch_backend( self: Qwen2VLForConditionalGeneration, input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> tuple | Qwen2VLCausalLMOutputForPPO: from verl.utils.experimental.torch_functional import FusedLinearForPPO outputs = qwen2_vl_forward(self, input_ids, **kwargs) hidden_states = outputs[0] # Loss calculations if labels is not None: rolled_labels = torch.roll(labels, shifts=-1, dims=-1) elif input_ids is not None: rolled_labels = torch.roll(input_ids, shifts=-1, dims=-1) else: raise RuntimeError("To use forward_with_torch_backend, either labels or input_ids must be provided.") fused_linear_for_ppo = FusedLinearForPPO() log_probs, entropy = fused_linear_for_ppo.forward( hidden_states=hidden_states, vocab_weights=self.lm_head.weight, input_ids=rolled_labels, temperature=temperature, ) return Qwen2VLCausalLMOutputForPPO( log_probs=log_probs, entropy=entropy, hidden_states=outputs.hidden_states, ) def forward_with_triton_backend( self: Qwen2VLForConditionalGeneration, input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> tuple | Qwen2VLCausalLMOutputForPPO: from verl.utils.kernel.linear_cross_entropy import linear_cross_entropy outputs = qwen2_vl_forward(self, input_ids, **kwargs) hidden_states = outputs[0] # Loss calculations if labels is not None: rolled_labels = torch.roll(labels, shifts=-1, dims=-1) elif input_ids is not None: rolled_labels = torch.roll(input_ids, shifts=-1, dims=-1) else: raise RuntimeError("To use forward_with_triton_backend, either labels or input_ids must be provided.") log_probs, entropy = linear_cross_entropy( hidden_states, self.lm_head.weight, rolled_labels, temperature, "none", ) return Qwen2VLCausalLMOutputForPPO( log_probs=log_probs, entropy=entropy, hidden_states=outputs.hidden_states, )
verl__models__transformers__qwen2_vl.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import logging import os from dataclasses import dataclass from typing import Optional import torch from transformers.models.qwen3_vl.modeling_qwen3_vl import ( Qwen3VLCausalLMOutputWithPast, Qwen3VLForConditionalGeneration, ) logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) def get_rope_index( processor, input_ids: torch.Tensor, image_grid_thw: Optional[torch.Tensor] = None, video_grid_thw: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, **kwargs, ) -> torch.Tensor: """ Gets the position ids for Qwen3-VL, it should be generated before sharding the sequence. The batch dim has been removed and the input_ids should be a 1D tensor representing a single example. https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py#L916 """ spatial_merge_size = processor.image_processor.merge_size image_token_id = processor.image_token_id video_token_id = processor.video_token_id vision_start_token_id = processor.vision_start_token_id # Since we use timestamps to separate videos, # like <t1> <vision_start> <frame1> <vision_end> <t2> <vision_start> <frame2> <vision_end>, # the video_grid_thw should also be split if video_grid_thw is not None: video_grid_thw = torch.repeat_interleave(video_grid_thw, video_grid_thw[:, 0], dim=0) video_grid_thw[:, 0] = 1 if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): if attention_mask is None: attention_mask = torch.ones_like(input_ids) position_ids = torch.ones(3, input_ids.shape[0], dtype=input_ids.dtype, device=input_ids.device) image_index, video_index = 0, 0 attention_mask = attention_mask.to(input_ids.device) input_ids = input_ids[attention_mask == 1] image_nums, video_nums = 0, 0 vision_start_indices = torch.argwhere(input_ids == vision_start_token_id) vision_tokens = input_ids[vision_start_indices + 1] image_nums = (vision_tokens == image_token_id).sum() video_nums = (vision_tokens == video_token_id).sum() input_tokens = input_ids.tolist() llm_pos_ids_list: list = [] st = 0 remain_images, remain_videos = image_nums, video_nums for _ in range(image_nums + video_nums): if image_token_id in input_tokens and remain_images > 0: ed_image = input_tokens.index(image_token_id, st) else: ed_image = len(input_tokens) + 1 if video_token_id in input_tokens and remain_videos > 0: ed_video = input_tokens.index(video_token_id, st) else: ed_video = len(input_tokens) + 1 if ed_image < ed_video: t, h, w = ( image_grid_thw[image_index][0], image_grid_thw[image_index][1], image_grid_thw[image_index][2], ) image_index += 1 remain_images -= 1 ed = ed_image else: t, h, w = ( video_grid_thw[video_index][0], video_grid_thw[video_index][1], video_grid_thw[video_index][2], ) video_index += 1 remain_videos -= 1 ed = ed_video llm_grid_t, llm_grid_h, llm_grid_w = ( t.item(), h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) text_len = ed - st st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) # t_index is always 0 because llm_grid_t is always 1 # (we use timestamps to encode the temporal information for videos) t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten() h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) st = ed + llm_grid_t * llm_grid_h * llm_grid_w if st < len(input_tokens): st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 text_len = len(input_tokens) - st llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device) else: if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = position_ids.unsqueeze(0).expand(3, -1).to(attention_mask.device) else: position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, -1).expand(3, -1) return position_ids def _get_input_embeds( model: "Qwen3VLForConditionalGeneration", input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, ): inputs_embeds = model.get_input_embeddings()(input_ids) image_mask, video_mask = None, None if pixel_values is not None: pixel_values = pixel_values.type(model.visual.dtype) image_embeds, deepstack_image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) n_image_tokens = (input_ids == model.config.image_token_id).sum().item() n_image_features = image_embeds.shape[0] if n_image_tokens != n_image_features: raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" ) mask = input_ids == model.config.image_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) image_mask = mask_expanded.to(inputs_embeds.device) image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) 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_tokens = (input_ids == model.config.video_token_id).sum().item() n_video_features = video_embeds.shape[0] if n_video_tokens != n_video_features: raise ValueError( f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" ) mask = input_ids == model.config.video_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) video_mask = mask_expanded.to(inputs_embeds.device) video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) visual_pos_masks = None deepstack_visual_embeds = None if image_mask is not None and video_mask is not None: # aggregate visual_pos_masks and deepstack_visual_embeds image_mask = image_mask[..., 0] video_mask = video_mask[..., 0] visual_pos_masks = image_mask | video_mask deepstack_visual_embeds = [] image_mask_joint = image_mask[visual_pos_masks] video_mask_joint = video_mask[visual_pos_masks] for img_embed, vid_embed in zip(deepstack_image_embeds, deepstack_video_embeds, strict=False): embed_joint = img_embed.new_zeros(visual_pos_masks.sum(), img_embed.shape[-1]).to(img_embed.device) embed_joint[image_mask_joint, :] = img_embed embed_joint[video_mask_joint, :] = vid_embed deepstack_visual_embeds.append(embed_joint) elif image_mask is not None: image_mask = image_mask[..., 0] visual_pos_masks = image_mask deepstack_visual_embeds = deepstack_image_embeds elif video_mask is not None: video_mask = video_mask[..., 0] visual_pos_masks = video_mask deepstack_visual_embeds = deepstack_video_embeds if pixel_values is None and pixel_values_videos is None: config = model.config.vision_config patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2 pixel_values = torch.zeros((16, patch_dim), dtype=inputs_embeds.dtype, device=inputs_embeds.device) image_grid_thw = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device) image_embeds, dummy_deepstack_image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) inputs_embeds += 0.0 * image_embeds.mean() for emb in dummy_deepstack_image_embeds or []: inputs_embeds += 0.0 * emb.mean() if attention_mask is not None: attention_mask = attention_mask.to(inputs_embeds.device) return { "inputs_embeds": inputs_embeds, "attention_mask": attention_mask, "visual_pos_masks": visual_pos_masks, "deepstack_visual_embeds": deepstack_visual_embeds, } @dataclass class Qwen3VLCausalLMOutputForPPO(Qwen3VLCausalLMOutputWithPast): log_probs: Optional[torch.FloatTensor] = None entropy: Optional[torch.FloatTensor] = None def qwen3_vl_base_forward( self: "Qwen3VLForConditionalGeneration", input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, **kwargs, ): input_kwargs = _get_input_embeds( self, input_ids, attention_mask, pixel_values, pixel_values_videos, image_grid_thw, video_grid_thw ) # avoid lora module having multiple keyword arguments kwargs.update(input_kwargs) return self.language_model( input_ids=None, **kwargs, ) def forward_with_normal_backend( self: "Qwen3VLForConditionalGeneration", input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> "Qwen3VLCausalLMOutputForPPO": outputs = self.model(input_ids, **kwargs) hidden_states = outputs[0] logits = self.lm_head(hidden_states) return Qwen3VLCausalLMOutputForPPO( logits=logits, hidden_states=outputs.hidden_states, ) def forward_with_torch_backend( self: "Qwen3VLForConditionalGeneration", input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> "Qwen3VLCausalLMOutputForPPO": from verl.utils.experimental.torch_functional import FusedLinearForPPO outputs = self.model(input_ids, **kwargs) hidden_states = outputs[0] # Loss calculations if labels is not None: rolled_labels = torch.roll(labels, shifts=-1, dims=-1) elif input_ids is not None: rolled_labels = torch.roll(input_ids, shifts=-1, dims=-1) else: raise RuntimeError("To use forward_with_torch_backend, either labels or input_ids must be provided.") fused_linear_for_ppo = FusedLinearForPPO() log_probs, entropy = fused_linear_for_ppo.forward( hidden_states=hidden_states, vocab_weights=self.lm_head.weight, input_ids=rolled_labels, temperature=temperature, ) return Qwen3VLCausalLMOutputForPPO( log_probs=log_probs, entropy=entropy, hidden_states=outputs.hidden_states, ) def forward_with_triton_backend( self: "Qwen3VLForConditionalGeneration", input_ids: torch.LongTensor = None, labels: Optional[torch.LongTensor] = None, temperature: float = 1.0, **kwargs, ) -> "Qwen3VLCausalLMOutputForPPO": from verl.utils.kernel.linear_cross_entropy import linear_cross_entropy outputs = self.model(input_ids, **kwargs) hidden_states = outputs[0] # Loss calculations if labels is not None: rolled_labels = torch.roll(labels, shifts=-1, dims=-1) elif input_ids is not None: rolled_labels = torch.roll(input_ids, shifts=-1, dims=-1) else: raise RuntimeError("To use forward_with_triton_backend, either labels or input_ids must be provided.") log_probs, entropy = linear_cross_entropy( hidden_states, self.lm_head.weight, rolled_labels, temperature, "none", ) return Qwen3VLCausalLMOutputForPPO( log_probs=log_probs, entropy=entropy, hidden_states=outputs.hidden_states, ) def patch_qwen3_vl_moe_sparse_moe_block_forward(): """ Monkey patch to fix a bug in transformers 4.57.3 where Qwen3VLMoeTextSparseMoeBlock.forward incorrectly uses torch.zeros_like(hidden_states) instead of torch.zeros_like(router_logits) when creating router_weights (line 148 in modeling_qwen3_vl_moe.py). This is a minimal fix that only changes the problematic line while keeping the rest of the original implementation intact. """ try: from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import Qwen3VLMoeTextSparseMoeBlock except ImportError: # Model not available, skip patching return # Store the original forward method for reference original_forward = Qwen3VLMoeTextSparseMoeBlock.forward @functools.wraps(original_forward) def patched_forward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size = hidden_states.shape[0] hidden_states = hidden_states.reshape(-1, self.hidden_size) router_logits = self.gate(hidden_states) routing_weights = torch.nn.functional.softmax(router_logits, dim=-1, dtype=torch.float) routing_weights, router_indices = torch.topk(routing_weights, self.top_k, dim=-1) routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True) # BUG FIX: Original code incorrectly uses hidden_states here, should use router_logits routing_weights = routing_weights.to(router_logits.dtype) router_weights = torch.zeros_like(router_logits).scatter_(1, router_indices, routing_weights) hidden_states = hidden_states.reshape(batch_size, -1, self.hidden_size) routed_out = self.experts(hidden_states, router_weights, router_indices) return routed_out # Apply the patch Qwen3VLMoeTextSparseMoeBlock.forward = patched_forward logger.info("Monkey patched Qwen3VLMoeTextSparseMoeBlock.forward to fix router_weights bug")
verl__models__transformers__qwen3_vl.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ FSDP2-compatible TiledMLP implementation for memory-efficient MLP computation. This module provides a tiled MLP implementation that reduces peak memory usage by processing the MLP forward/backward pass in chunks (tiles). This is particularly useful for large models with FSDP2 training. """ import threading from typing import Optional import torch import torch.nn as nn class GradientAccumulator: """Gradient accumulator for TiledMLP (FSDP compatible). This class manages gradient accumulation across multiple shards during the backward pass of TiledMLP. It ensures correct gradient computation when processing input in chunks. """ def __init__(self, params: list[torch.nn.Parameter], total_shards: int, dtype: torch.dtype = None): self.params = params self.total_shards = total_shards self.grad_accumulation_dtype = dtype or torch.float32 self.accumulated_grads = {} self.hooks = [] self.lock = threading.Lock() for param in self.params: if param.grad is not None: self.accumulated_grads[param] = param.grad.to(self.grad_accumulation_dtype) param.grad = None else: self.accumulated_grads[param] = torch.zeros_like(param, dtype=self.grad_accumulation_dtype) def install_hooks(self, is_last_shard: bool): """Install gradient hooks for the current shard.""" self._remove_hooks() def create_hook(param): def hook(grad): with self.lock: grad_to_accum_dtype = grad.to(self.grad_accumulation_dtype) self.accumulated_grads[param] += grad_to_accum_dtype if is_last_shard: param.grad = None # Critical: prevent double accumulation final_grad = self.accumulated_grads[param].to(param.dtype) return final_grad return None return hook for param in self.params: if param.requires_grad: hook = param.register_hook(create_hook(param)) self.hooks.append(hook) def _remove_hooks(self): """Remove all registered hooks.""" for hook in self.hooks: hook.remove() self.hooks.clear() def cleanup(self): """Cleanup hooks and resources.""" self._remove_hooks() class TiledMLP(torch.autograd.Function): """TiledMLP implementation for memory-efficient MLP computation. This autograd function processes MLP forward/backward in tiles (chunks) to reduce peak memory usage. Compatible with FSDP2. """ @staticmethod def forward(ctx, fn, module, x, shards, compute_params): ctx.fn = fn ctx.module = module ctx.shards = shards ctx.compute_params = [p for p in compute_params if p.requires_grad] ctx.save_for_backward(x) # Split on dim=-2 (seqlen dimension) following Liger Kernel style x_shards = list(torch.chunk(x, chunks=shards, dim=-2)) with torch.no_grad(): output_shards = [fn(module, x_shard) for x_shard in x_shards] output_unsharded = torch.cat(output_shards, dim=-2) return output_unsharded @staticmethod def backward(ctx, *grads): fn = ctx.fn (x,) = ctx.saved_tensors module = ctx.module shards = ctx.shards compute_params = ctx.compute_params x_requires_grad = x.requires_grad x = x.detach() x.requires_grad_(x_requires_grad) # Flatten to [bs*seqlen, hidden_size] hidden_size = x.shape[-1] x_shape_orig = x.shape x = x.view(-1, hidden_size) incoming_grad = grads[0].view(-1, hidden_size) # Pre-allocate input gradient x_grad = torch.zeros_like(x) # Split on dim=0 x_shards = list(torch.chunk(x, chunks=shards, dim=0)) grad_accumulator = GradientAccumulator(compute_params, shards, dtype=x.dtype) for i, x_shard in enumerate(x_shards): x_shard.requires_grad_(x_requires_grad) shard_step = x_shards[i].shape[0] shard_offset = i * x_shards[0].shape[0] # narrow(0, ...) creates a contiguous view that can receive gradients x_shard.grad = x_grad.narrow(0, shard_offset, shard_step) incoming_grad_shard = incoming_grad.narrow(0, shard_offset, shard_step) is_last_shard = i + 1 == shards grad_accumulator.install_hooks(is_last_shard) with torch.enable_grad(): output = fn(module, x_shard) torch.autograd.backward(output, incoming_grad_shard) grad_accumulator.cleanup() del grad_accumulator # Restore original shape x_grad = x_grad.view(x_shape_orig) if x_requires_grad else None return (None, None, x_grad, None, None) def _mlp_forward_fn(module, x): """Forward function for LlamaMLP / Qwen2MLP / Qwen3MLP style.""" return module.down_proj(module.act_fn(module.gate_proj(x)) * module.up_proj(x)) # ============================================================================ # Monkey Patch Functions # ============================================================================ # Model type to MLP class mapping _MODEL_TYPE_TO_MLP_CLASS = { "llama": ("transformers.models.llama.modeling_llama", "LlamaMLP"), "qwen2": ("transformers.models.qwen2.modeling_qwen2", "Qwen2MLP"), "qwen2_5": ("transformers.models.qwen2.modeling_qwen2", "Qwen2MLP"), # Qwen2.5 uses Qwen2 MLP "qwen3": ("transformers.models.qwen3.modeling_qwen3", "Qwen3MLP"), } def apply_tiled_mlp_monkey_patch( num_shards: int = 4, model_type: Optional[str] = None, ): """Apply TiledMLP monkey patch based on model_type. This function MUST be called BEFORE model instantiation to take effect. It patches the MLP classes in transformers library to use TiledMLP for memory-efficient computation during training. Args: num_shards: Number of shards to split the input into. Higher values reduce peak memory but may slightly impact performance. model_type: The model type string (e.g., "llama", "qwen2", "qwen3"). If None, patches all supported model types. Returns: List of patched class names. """ if model_type is None: types_to_patch = list(_MODEL_TYPE_TO_MLP_CLASS.keys()) elif model_type in _MODEL_TYPE_TO_MLP_CLASS: types_to_patch = [model_type] else: raise ValueError( f"TiledMLP does not support model_type='{model_type}'. " f"Supported types: {list(_MODEL_TYPE_TO_MLP_CLASS.keys())}. " f"For SwiGLU-style MLPs, you can add support by extending _MODEL_TYPE_TO_MLP_CLASS " f"in verl/models/transformers/tiled_mlp.py" ) patched_classes = [] for mtype in types_to_patch: module_path, class_name = _MODEL_TYPE_TO_MLP_CLASS[mtype] try: import importlib module = importlib.import_module(module_path) mlp_class = getattr(module, class_name) _patch_mlp_class(mlp_class, _mlp_forward_fn, num_shards) if class_name not in patched_classes: patched_classes.append(class_name) except (ImportError, AttributeError) as e: print(f"Warning: Could not patch {mtype} MLP: {e}") if patched_classes: print(f"TiledMLP monkey patch applied to: {', '.join(patched_classes)} (shards={num_shards})") return patched_classes def _patch_mlp_class(mlp_class: type[nn.Module], forward_fn, num_shards: int): """Patch a single MLP class to use TiledMLP.""" def tiled_forward(self, x): compute_params = [p for p in self.parameters() if p.requires_grad] return TiledMLP.apply(forward_fn, self, x, num_shards, compute_params) mlp_class.forward = tiled_forward
verl__models__transformers__tiled_mlp.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def get_weight_loader(arch: str): from verl.models.mcore.loader import load_state_dict_to_megatron_gptmodel _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY = { "LlamaForCausalLM": load_state_dict_to_megatron_gptmodel, "Qwen2ForCausalLM": load_state_dict_to_megatron_gptmodel, } if arch in _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY: return _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY[arch] raise ValueError( f"Model architectures {arch} loader are not supported for now. Supported architectures: " f"{_MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY.keys()}" ) def get_weight_saver(arch: str): from verl.models.mcore.saver import ( merge_megatron_ckpt_gptmodel, merge_megatron_ckpt_gptmodel_dpskv3, merge_megatron_ckpt_gptmodel_mixtral, merge_megatron_ckpt_gptmodel_qwen2_5_vl, merge_megatron_ckpt_gptmodel_qwen_moe, ) _MODEL_WEIGHT_MEGATRON_SAVER_REGISTRY = { "LlamaForCausalLM": merge_megatron_ckpt_gptmodel, "Qwen2ForCausalLM": merge_megatron_ckpt_gptmodel, "MixtralForCausalLM": merge_megatron_ckpt_gptmodel_mixtral, "Qwen2MoeForCausalLM": merge_megatron_ckpt_gptmodel_qwen_moe, "Qwen2_5_VLForConditionalGeneration": merge_megatron_ckpt_gptmodel_qwen2_5_vl, "DeepseekV3ForCausalLM": merge_megatron_ckpt_gptmodel_dpskv3, "Qwen3ForCausalLM": merge_megatron_ckpt_gptmodel, "Qwen3ForTokenClassification": merge_megatron_ckpt_gptmodel, "Qwen3MoeForCausalLM": merge_megatron_ckpt_gptmodel_qwen_moe, "LlamaForTokenClassification": merge_megatron_ckpt_gptmodel, } if arch in _MODEL_WEIGHT_MEGATRON_SAVER_REGISTRY: return _MODEL_WEIGHT_MEGATRON_SAVER_REGISTRY[arch] raise ValueError( f"Model architectures {arch} saver are not supported for now. Supported architectures: " f"{_MODEL_WEIGHT_MEGATRON_SAVER_REGISTRY.keys()}" )
verl__models__weight_loader_registry.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Implement base data transfer protocol between any two functions, modules. We can subclass Protocol to define more detailed batch info with specific keys """ import contextlib import copy import logging import math import os import pickle from dataclasses import dataclass, field from typing import Any, Callable, Optional import numpy as np import ray import tensordict import torch import torch.distributed from packaging import version from packaging.version import parse as parse_version from tensordict import TensorDict from torch.utils.data import DataLoader from verl.utils.device import get_device_id, get_torch_device from verl.utils.py_functional import union_two_dict from verl.utils.torch_functional import allgather_dict_tensors __all__ = ["DataProto", "union_tensor_dict"] with contextlib.suppress(Exception): tensordict.set_lazy_legacy(False).set() if parse_version(tensordict.__version__) < parse_version("0.10.0"): tensordict.set_list_to_stack(True).set() class _DataProtoConfigMeta(type): _config = {} auto_padding_key = "_verl_auto_padding" @property def auto_padding(cls): enabled_by_env = os.getenv("VERL_AUTO_PADDING", "FALSE").upper() in ["TRUE", "1"] return enabled_by_env or cls._config.get(cls.auto_padding_key, False) @auto_padding.setter def auto_padding(cls, enabled: bool): assert isinstance(enabled, bool), f"enabled must be a boolean, got {enabled} as {type(enabled)}" cls._config[cls.auto_padding_key] = enabled class DataProtoConfig(metaclass=_DataProtoConfigMeta): pass _padding_size_key = "_padding_size_key_x123d" def pad_dataproto_to_divisor(data: "DataProto", size_divisor: int): """Pad a DataProto to size divisible by size_divisor Args: size_divisor (int): size divisor Returns: data: (DataProto): the padded DataProto pad_size (int) """ assert isinstance(data, DataProto), "data must be a DataProto" if len(data) % size_divisor != 0: pad_size = size_divisor - len(data) % size_divisor padding_protos = [] remaining_pad = pad_size while remaining_pad > 0: take_size = min(remaining_pad, len(data)) padding_protos.append(data[:take_size]) remaining_pad -= take_size data_padded = DataProto.concat([data] + padding_protos) else: if len(data) == 0: logging.warning("padding a DataProto with no item, no changed made") pad_size = 0 data_padded = data return data_padded, pad_size def unpad_dataproto(data: "DataProto", pad_size): """Unpad the data proto with pad_size. i.e. `data[:-pad_size]`""" if pad_size != 0: data = data[:-pad_size] return data def union_tensor_dict(tensor_dict1: TensorDict, tensor_dict2: TensorDict) -> TensorDict: """Union two tensordicts.""" assert tensor_dict1.batch_size == tensor_dict2.batch_size, ( f"Two tensor dict must have identical batch size. Got {tensor_dict1.batch_size} and {tensor_dict2.batch_size}" ) for key in tensor_dict2.keys(): if key not in tensor_dict1.keys(): tensor_dict1[key] = tensor_dict2[key] else: assert tensor_dict1[key].equal(tensor_dict2[key]), ( f"{key} in tensor_dict1 and tensor_dict2 are not the same object" ) return tensor_dict1 def _array_equal(array1: np.ndarray, array2: np.ndarray, visited: set[int]) -> bool: """ Recursively compares two NumPy arrays for strict equality, with special handling for object-dtype arrays, NaN values, and circular references. This function assumes that the two arguments provided are NumPy arrays. Args: array1: The first NumPy array. array2: The second NumPy array. Returns: True if the arrays' dtypes, shapes, and all elements are equal. """ # Check dtype and shape first, as this is the fastest failure path. if array1.dtype != array2.dtype or array1.shape != array2.shape: return False # For non-object dtypes, use NumPy's implementation with equal_nan=True. if array1.dtype != "object": return np.array_equal(array1, array2, equal_nan=True) # For object-dtype arrays, we must recursively compare each element. # We delegate to _deep_equal to handle elements, as they could be any # type, including other nested arrays or NaNs. return all(_deep_equal(x, y, visited) for x, y in zip(array1.flat, array2.flat, strict=False)) def _deep_equal(a: Any, b: Any, visited: set[int]) -> bool: """ Recursively performs a deep comparison between two Python objects. - Handles NaN values correctly (NaN == NaN evaluates to True). - Handling circular references. - Dispatches to _array_equal if both objects are NumPy arrays. - Otherwise, uses standard '==' comparison. """ if type(a) is not type(b): return False # If we have seen this object ID before on this path, it's a cycle. # Since we already know the types match, we can safely assume this part # of the structure is equal. obj_id = id(a) if obj_id in visited: return True visited.add(obj_id) # Perform the specific comparison based on type result = False if isinstance(a, float) and math.isnan(a) and math.isnan(b): result = True elif isinstance(a, np.ndarray): # We know b is also an ndarray due to the initial type check result = _array_equal(a, b, visited) else: # Standard equality for all other types result = a == b # Clean up the visited set on the way out of the recursion visited.remove(obj_id) return result def union_numpy_dict(tensor_dict1: dict[str, np.ndarray], tensor_dict2: dict[str, np.ndarray]) -> dict[str, np.ndarray]: for key, val in tensor_dict2.items(): if key in tensor_dict1: assert isinstance(tensor_dict2[key], np.ndarray) assert isinstance(tensor_dict1[key], np.ndarray) # to properly deal with nan and object type assert _deep_equal(tensor_dict1[key], tensor_dict2[key], visited=set()), ( f"`{key}` in tensor_dict1 and tensor_dict2 are not the same object." ) tensor_dict1[key] = val return tensor_dict1 def list_of_dict_to_dict_of_list(list_of_dict: list[dict]): if len(list_of_dict) == 0: return {} keys = list_of_dict[0].keys() output = {key: [] for key in keys} for data in list_of_dict: for key, item in data.items(): assert key in output output[key].append(item) return output def fold_batch_dim(data: "DataProto", new_batch_size): """ Fold a batch dim from [bsz, xxx] into [new_bsz, bsz // new_bsz, xxx] """ batch_size = data.batch.batch_size[0] assert batch_size % new_batch_size == 0 tensor: TensorDict = data.batch non_tensor = data.non_tensor_batch tensor = tensor.view(new_batch_size, -1) tensor.auto_batch_size_(batch_dims=1) for key, val in non_tensor.items(): non_tensor[key] = np.reshape(val, newshape=(new_batch_size, -1, *val.shape[1:])) return type(data)(batch=tensor, non_tensor_batch=non_tensor, meta_info=data.meta_info) def unfold_batch_dim(data: "DataProto", batch_dims=2): """ Unfold the first n dims as new batch dim """ tensor: TensorDict = data.batch non_tensor = data.non_tensor_batch tensor.auto_batch_size_(batch_dims=batch_dims) tensor = tensor.view(-1) batch_size = tensor.batch_size[0] non_tensor_new = {} for key, val in non_tensor.items(): non_tensor_new[key] = np.reshape(val, newshape=(batch_size, *val.shape[batch_dims:])) return type(data)(batch=tensor, non_tensor_batch=non_tensor_new, meta_info=data.meta_info) def serialize_single_tensor(obj: torch.Tensor) -> tuple[str, tuple[int, ...], int | memoryview]: data = obj.flatten().contiguous().view(torch.uint8).numpy() dtype = str(obj.dtype).removeprefix("torch.") return dtype, obj.shape, data def serialize_tensordict(batch: TensorDict) -> tuple[tuple[int, ...], Optional[str], dict[str, tuple[str, Any]]]: encoded_items: dict[str, tuple[Any]] = {} for k, v in batch.items(): if not v.is_nested: encoded_items[k] = serialize_single_tensor(v) else: layout = str(v.layout).removeprefix("torch.") data = [serialize_single_tensor(tensor) for tensor in v.unbind()] encoded_items[k] = (layout, data) batch_size = tuple(batch.batch_size) device = str(batch.device) if batch.device is not None else None return batch_size, device, encoded_items def deserialize_single_tensor(arr: Any) -> torch.Tensor: dtype, shape, data = arr torch_dtype = getattr(torch, dtype) assert isinstance(torch_dtype, torch.dtype) buffer = bytearray(data) # Create uint8 array arr = torch.frombuffer(buffer, dtype=torch.uint8) # Convert back to proper shape & type return arr.view(torch_dtype).view(shape) def deserialize_tensordict(arr: Any) -> TensorDict: batch_size, device, encoded_items = arr decoded_items: dict[str, Any] = {} for k, v in encoded_items.items(): if len(v) == 3: # decode single tensor decoded_items[k] = deserialize_single_tensor(v) elif len(v) == 2: # decode nested tensor layout, data = v torch_layout = getattr(torch, layout) decoded_items[k] = torch.nested.as_nested_tensor( [deserialize_single_tensor(tensor) for tensor in data], layout=torch_layout ) else: raise ValueError(f"Invalid tensor encoding format, expected length 2 or 3, got {len(v)}") return TensorDict(source=decoded_items, batch_size=batch_size, device=device) def collate_fn(x: list["DataProtoItem"]): batch = [] non_tensor_batch = [] for data in x: batch.append(data.batch) non_tensor_batch.append(data.non_tensor_batch) batch = torch.stack(batch).contiguous() non_tensor_batch = list_of_dict_to_dict_of_list(non_tensor_batch) for key, val in non_tensor_batch.items(): non_tensor_batch[key] = np.array(val, dtype=object) return DataProto(batch=batch, non_tensor_batch=non_tensor_batch) @dataclass class DataProtoItem: # TODO(zhangchi.usc1992) add consistency check batch: TensorDict = None non_tensor_batch: dict = field(default_factory=dict) meta_info: dict = field(default_factory=dict) @dataclass class DataProto: """ A DataProto is a data structure that aims to provide a standard protocol for data exchange between functions. It contains a batch (TensorDict) and a meta_info (Dict). The batch is a TensorDict https://pytorch.org/tensordict/. TensorDict allows you to manipulate a dictionary of Tensors like a single Tensor. Ideally, the tensors with the same batch size should be put inside batch. """ batch: TensorDict = None non_tensor_batch: dict = field(default_factory=dict) meta_info: dict = field(default_factory=dict) def __post_init__(self): # perform necessary checking self.check_consistency() def __len__(self): if self.batch is not None: return self.batch.batch_size[0] elif self.non_tensor_batch is not None and len(self.non_tensor_batch) > 0: random_key = list(self.non_tensor_batch.keys())[0] return self.non_tensor_batch[random_key].shape[0] else: return 0 def __getitem__(self, item): """ Enhanced indexing for DataProto objects. Args: item: Can be one of: - int: A single index - slice: A slice object (start:stop:step) - list: A list of indices - numpy.ndarray: An array of indices - torch.Tensor: A tensor of indices Returns: DataProto: For all indexing types except single integers DataProtoItem: Only for single integer indices """ # Case 1: Slice object - use the slice method if isinstance(item, slice): return self.slice(item.start, item.stop, item.step) # Case 2: List, numpy array, or torch tensor - use sel_idxs elif isinstance(item, list | np.ndarray | torch.Tensor): return self.select_idxs(item) # Case 3: Single integer - return DataProtoItem for backward compatibility elif isinstance(item, int | np.integer): tensor_data = self.batch[item] if self.batch is not None else None non_tensor_data = {key: val[item] for key, val in self.non_tensor_batch.items()} return DataProtoItem(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info) # # Case 4: Unsupported type else: raise TypeError(f"Indexing with {type(item)} is not supported") def __getstate__(self): if version.parse(tensordict.__version__) >= version.parse("0.5.0") and self.batch is not None: # Check if batch is empty to avoid torch.cat error in consolidate if len(self.batch.keys()) > 0: batch = self.batch.contiguous().consolidate() else: batch = self.batch else: batch = self.batch if os.getenv("VERL_DATAPROTO_SERIALIZATION_METHOD") == "numpy": if batch is not None: batch = serialize_tensordict(self.batch) return ( batch, self.non_tensor_batch, self.meta_info, ) else: import io buffer = io.BytesIO() torch.save(batch, buffer) buffer_bytes = buffer.getvalue() return buffer_bytes, self.non_tensor_batch, self.meta_info def __setstate__(self, data): batch_deserialized_bytes, non_tensor_batch, meta_info = data if os.getenv("VERL_DATAPROTO_SERIALIZATION_METHOD") == "numpy": if batch_deserialized_bytes is not None: self.batch = deserialize_tensordict(batch_deserialized_bytes) else: self.batch = None else: import io batch_deserialized = io.BytesIO(initial_bytes=batch_deserialized_bytes) batch = torch.load( batch_deserialized, weights_only=False, map_location="cpu" if not get_torch_device().is_available() else None, ) self.batch = batch self.non_tensor_batch = non_tensor_batch self.meta_info = meta_info def save_to_disk(self, filepath): with open(filepath, "wb") as f: pickle.dump(self, f) @staticmethod def load_from_disk(filepath) -> "DataProto": with open(filepath, "rb") as f: data = pickle.load(f) return data def print_size(self, prefix=""): size_of_tensordict = 0 if self.batch is not None: for _, tensor in self.batch.items(): size_of_tensordict += tensor.element_size() * tensor.numel() size_of_numpy_array = 0 for _, numpy_array in self.non_tensor_batch.items(): size_of_numpy_array += numpy_array.nbytes size_of_numpy_array /= 1024**3 size_of_tensordict /= 1024**3 message = f"Size of tensordict: {size_of_tensordict} GB, size of non_tensor_batch: {size_of_numpy_array} GB" if prefix: message = f"{prefix}, " + message print(message) def check_consistency(self): """Check the consistency of the DataProto. Mainly for batch and non_tensor_batch We expose this function as a public one so that user can call themselves directly """ if self.batch is not None: assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1" if self.non_tensor_batch is not None: for key, val in self.non_tensor_batch.items(): assert isinstance(val, np.ndarray) if self.batch is not None and self.non_tensor_batch is not None and len(self.non_tensor_batch) != 0: # TODO: we can actually lift this restriction if needed assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1 when non_tensor_batch is not empty." batch_size = self.batch.batch_size[0] for key, val in self.non_tensor_batch.items(): assert isinstance(val, np.ndarray), ( f"data in the non_tensor_batch must be a numpy.array with dtype=object, but for " f"{key=}, got {type(val)=}" ) assert val.shape[0] == batch_size, ( f"key {key} length {len(val)} is not equal to batch size {batch_size}" ) @classmethod def from_single_dict(cls, data: dict[str, torch.Tensor | np.ndarray], meta_info=None, auto_padding=False): """Create a DataProto from a dict of tensors and non_tensors""" tensors = {} non_tensors = {} for key, val in data.items(): if isinstance(val, torch.Tensor): tensors[key] = val elif isinstance(val, np.ndarray): non_tensors[key] = val else: raise ValueError(f"Unsupported type in data {type(val)}") return cls.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info, auto_padding=auto_padding) @classmethod def from_dict( cls, tensors: Optional[dict[str, torch.Tensor]] = None, non_tensors=None, meta_info=None, num_batch_dims=1, auto_padding=False, ): """Create a DataProto from a dict of tensors. This assumes that 1. All the tensor in tensors have the same dim0 2. Only dim0 is the batch dim """ assert num_batch_dims > 0, "num_batch_dims must be greater than zero" if non_tensors is not None: assert num_batch_dims == 1, "only support num_batch_dims=1 when non_tensors is not None." if tensors is None: tensors = {} if meta_info is None: meta_info = {} if non_tensors is None: non_tensors = {} assert isinstance(non_tensors, dict) # get and check batch size batch_size = None pivot_key = None for key, tensor in tensors.items(): if batch_size is None: batch_size = tensor.shape[:num_batch_dims] pivot_key = key else: current_batch = tensor.shape[:num_batch_dims] assert batch_size == current_batch, ( f"Not all the tensor in tensors have the same batch size with batch_dims={num_batch_dims}. " f"Got {pivot_key} has {batch_size}, {key} has {current_batch}" ) for key, val in non_tensors.items(): if not isinstance(val, np.ndarray): non_tensors[key] = np.array(val, dtype=object) tensor_dict = TensorDict(source=tensors, batch_size=batch_size) if tensors else None if auto_padding: meta_info[DataProtoConfig.auto_padding_key] = True return cls(batch=tensor_dict, non_tensor_batch=non_tensors, meta_info=meta_info) @classmethod def from_tensordict( cls, tensor_dict: TensorDict = None, meta_info=None, num_batch_dims=1, ): """Create a DataProto from a TensorDict. This assumes that 1. All the tensor in tensor_dict have the same dim0 2. Only dim0 is the batch dim """ assert version.parse(tensordict.__version__) >= version.parse("0.10.0"), ( "Build DataProto from TensorDict at least requires tensordict version 0.10.0" ) from tensordict import NonTensorData, NonTensorStack assert num_batch_dims > 0, "num_batch_dims must be greater than zero" if not all(isinstance(val, torch.Tensor) for val in tensor_dict.values()): assert num_batch_dims == 1, "only support num_batch_dims=1 when tensor_dict contains non tensor data." if meta_info is None: meta_info = {} batch = {} non_tensor_batch = {} batch_size = None for key, val in tensor_dict.items(): if isinstance(val, torch.Tensor): batch[key] = val if batch_size is None: batch_size = val.shape[:num_batch_dims] elif isinstance(val, NonTensorStack): non_tensor_batch[key] = np.array([elem.data for elem in val], dtype=object) elif isinstance(val, NonTensorData): meta_info[key] = val.data return cls( batch=TensorDict(batch, batch_size=batch_size), non_tensor_batch=non_tensor_batch, meta_info=meta_info, ) def to(self, device) -> "DataProto": """move the batch to device Args: device (torch.device, str): torch device Returns: DataProto: the current DataProto """ if self.batch is not None: self.batch = self.batch.to(device) return self def select(self, batch_keys=None, non_tensor_batch_keys=None, meta_info_keys=None, deepcopy=False) -> "DataProto": """Select a subset of the DataProto via batch_keys and meta_info_keys Args: batch_keys (list, optional): a list of strings indicating the keys in batch to select meta_info_keys (list, optional): a list of keys indicating the meta info to select Returns: DataProto: the DataProto with the selected batch_keys and meta_info_keys """ # TODO (zhangchi.usc1992) whether to copy if batch_keys is not None: batch_keys = tuple(batch_keys) sub_batch = self.batch.select(*batch_keys) else: sub_batch = self.batch if non_tensor_batch_keys is not None: non_tensor_batch = {key: val for key, val in self.non_tensor_batch.items() if key in non_tensor_batch_keys} else: non_tensor_batch = self.non_tensor_batch if deepcopy: non_tensor_batch = copy.deepcopy(non_tensor_batch) if meta_info_keys is not None: sub_meta_info = {key: val for key, val in self.meta_info.items() if key in meta_info_keys} else: sub_meta_info = self.meta_info if deepcopy: sub_meta_info = copy.deepcopy(sub_meta_info) return type(self)(batch=sub_batch, non_tensor_batch=non_tensor_batch, meta_info=sub_meta_info) def select_idxs(self, idxs): """ Select specific indices from the DataProto. Args: idxs (torch.Tensor or numpy.ndarray or list): Indices to select Returns: DataProto: A new DataProto containing only the selected indices """ if isinstance(idxs, list): idxs = torch.tensor(idxs) if idxs.dtype != torch.bool: idxs = idxs.type(torch.int32) if isinstance(idxs, np.ndarray): idxs_np = idxs idxs_torch = torch.from_numpy(idxs) else: # torch.Tensor idxs_torch = idxs idxs_np = idxs.detach().cpu().numpy() batch_size = int(idxs_np.sum()) if idxs_np.dtype == bool else idxs_np.shape[0] if self.batch is not None: # Use TensorDict's built-in indexing capabilities selected_batch = TensorDict( source={key: tensor[idxs_torch] for key, tensor in self.batch.items()}, batch_size=(batch_size,), device=self.batch.device, ) else: selected_batch = None selected_non_tensor = {} for key, val in self.non_tensor_batch.items(): selected_non_tensor[key] = val[idxs_np] return type(self)(batch=selected_batch, non_tensor_batch=selected_non_tensor, meta_info=self.meta_info) def slice(self, start=None, end=None, step=None): """ Slice the DataProto and return a new DataProto object. This is an improved version of direct slicing which returns a DataProtoItem. Args: start (int, optional): Start index. Defaults to None (start from beginning). end (int, optional): End index (exclusive). Defaults to None (go to end). step (int, optional): Step size. Defaults to None (step=1). Returns: DataProto: A new DataProto containing the sliced data Examples: # Using the slice method directly sliced_data = data_proto.slice(10, 20) # Using enhanced indexing (returns DataProto) sliced_data = data_proto[10:20] sliced_data = data_proto[::2] # Every other element # Using list indexing (returns DataProto) indices = [1, 5, 10] selected_data = data_proto[indices] # Single index still returns DataProtoItem single_item = data_proto[5] """ # Create a slice object slice_obj = slice(start, end, step) # Handle the batch data if self.batch is not None: # Use TensorDict's built-in slicing capabilities sliced_batch = self.batch[slice_obj] else: sliced_batch = None # Handle the non-tensor batch data sliced_non_tensor = {} for key, val in self.non_tensor_batch.items(): sliced_non_tensor[key] = val[slice_obj] # Return a new DataProto object return type(self)(batch=sliced_batch, non_tensor_batch=sliced_non_tensor, meta_info=self.meta_info) def pop(self, batch_keys=None, non_tensor_batch_keys=None, meta_info_keys=None) -> "DataProto": """Pop a subset of the DataProto via `batch_keys` and `meta_info_keys` Args: batch_keys (list, optional): a list of strings indicating the keys in batch to pop meta_info_keys (list, optional): a list of keys indicating the meta info to pop Returns: DataProto: the DataProto with the poped batch_keys and meta_info_keys """ if batch_keys is None: batch_keys = [] if meta_info_keys is None: meta_info_keys = [] if non_tensor_batch_keys is None: non_tensor_batch_keys = [] tensors = {} # tensor batch for key in batch_keys: assert key in self.batch.keys() tensors[key] = self.batch.pop(key) non_tensors = {} # non tensor batch for key in non_tensor_batch_keys: assert key in self.non_tensor_batch.keys() non_tensors[key] = self.non_tensor_batch.pop(key) meta_info = {} for key in meta_info_keys: assert key in self.meta_info.keys() meta_info[key] = self.meta_info.pop(key) return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info) def rename(self, old_keys=None, new_keys=None) -> "DataProto": """ Note that this function only rename the key in the batch """ def validate_input(keys): if keys is not None: if isinstance(keys, str): keys = [keys] elif isinstance(keys, list): pass else: raise TypeError(f"keys must be a list or a string, but got {type(keys)}") return keys old_keys = validate_input(old_keys) new_keys = validate_input(new_keys) if len(new_keys) != len(old_keys): raise ValueError( f"new_keys and old_keys must have the same length, but got {len(new_keys)} and {len(old_keys)}" ) self.batch.rename_key_(tuple(old_keys), tuple(new_keys)) return self def union(self, other: "DataProto") -> "DataProto": """Union with another DataProto. Union batch and meta_info separately. Throw an error if - there are conflict keys in batch and they are not equal - the batch size of two data batch is not the same - there are conflict keys in meta_info and they are not the same. Args: other (DataProto): another DataProto to union Returns: DataProto: the DataProto after union """ self.batch = union_tensor_dict(self.batch, other.batch) self.non_tensor_batch = union_numpy_dict(self.non_tensor_batch, other.non_tensor_batch) self.meta_info = union_two_dict(self.meta_info, other.meta_info) return self def make_iterator(self, mini_batch_size, epochs, seed=None, dataloader_kwargs=None): r"""Make an iterator from the DataProto. This is built upon that TensorDict can be used as a normal Pytorch dataset. See https://pytorch.org/tensordict/stable/tutorials/data_fashion for more details. Args: mini_batch_size (int): mini-batch size when iterating the dataset. We require that ``batch.batch_size[0] % mini_batch_size == 0``. epochs (int): number of epochs when iterating the dataset. dataloader_kwargs (Any): internally, it returns a DataLoader over the batch. The dataloader_kwargs is the kwargs passed to the DataLoader. Returns: Iterator: an iterator that yields a mini-batch data at a time. The total number of iteration steps is ``self.batch.batch_size * epochs // mini_batch_size`` """ assert self.batch.batch_size[0] % mini_batch_size == 0, f"{self.batch.batch_size[0]} % {mini_batch_size} != 0" # we can directly create a dataloader from TensorDict if dataloader_kwargs is None: dataloader_kwargs = {} if seed is not None: generator = torch.Generator() generator.manual_seed(seed) else: generator = None assert isinstance(dataloader_kwargs, dict) train_dataloader = DataLoader( dataset=self, batch_size=mini_batch_size, collate_fn=collate_fn, generator=generator, **dataloader_kwargs ) def get_data(): for _ in range(epochs): for d in train_dataloader: d.meta_info = self.meta_info yield d return iter(get_data()) def is_padding_enabled(self): """ Check if padding is enabled for the DataProto. Returns: bool: True if padding is enabled, False otherwise. """ dataproto_specific_padding = self.meta_info.get(DataProtoConfig.auto_padding_key, False) return dataproto_specific_padding or DataProtoConfig.auto_padding def padding(self, padding_size, padding_candidate=""): """Pad the DataProto by concating with padding_candidate.repeat(padding_size) Args: padding_size (int): the number of repeated padding_candidate padding_candidate: the item to be repeated and appended to the DataProto, only supporting ["first", "last"] """ if padding_size == 0: return padding_candidate = self.select_idxs([0 if padding_candidate == "first" else len(self) - 1]) padding_part = padding_candidate.repeat(padding_size) padded_dp = DataProto.concat([self, padding_part]) self.batch = padded_dp.batch self.non_tensor_batch = padded_dp.non_tensor_batch def chunk(self, chunks: int) -> list["DataProto"]: """Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split. Args: chunks (int): the number of chunks to split on dim=0 Returns: List[DataProto]: a list of DataProto after splitting """ if not self.is_padding_enabled(): assert len(self) % chunks == 0, ( f"only support equal chunk. Got size of DataProto {len(self)} and chunk {chunks}." ) bsz_in_batch = None if self.batch is not None: batch_lst = self.batch.chunk(chunks=chunks, dim=0) bsz_in_batch = np.array([batch.batch_size[0] for batch in batch_lst]) chunk_indices = np.cumsum(bsz_in_batch)[:-1] else: batch_lst = [None for _ in range(chunks)] non_tensor_batch_lst = [{} for _ in range(chunks)] for key, val in self.non_tensor_batch.items(): assert isinstance(val, np.ndarray) if bsz_in_batch is not None: non_tensor_lst = np.array_split(val, chunk_indices.tolist()) else: non_tensor_lst = np.array_split(val, chunks) assert len(non_tensor_lst) == chunks for i in range(chunks): non_tensor_batch_lst[i][key] = non_tensor_lst[i] output = [] for i in range(chunks): output.append( type(self)(batch=batch_lst[i], non_tensor_batch=non_tensor_batch_lst[i], meta_info=self.meta_info) ) return output def split(self, split_size: int) -> list["DataProto"]: """Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split. Args: split_size (int): the size of each split Returns: List[DataProto]: a list of DataProto after splitting """ return [self[i : i + split_size] for i in range(0, len(self), split_size)] @staticmethod def concat(data: list["DataProto"]) -> "DataProto": """Concat a list of DataProto. The batch is concatenated among dim=0. The meta_info is merged, with special handling for metrics from different workers. Args: data (List[DataProto]): list of DataProto Returns: DataProto: concatenated DataProto """ batch_lst = [] for batch in data: batch_lst.append(batch.batch) new_batch = torch.cat(batch_lst, dim=0) if batch_lst[0] is not None else None non_tensor_batch = list_of_dict_to_dict_of_list(list_of_dict=[d.non_tensor_batch for d in data]) for key, val in non_tensor_batch.items(): non_tensor_batch[key] = np.concatenate(val, axis=0) # Merge meta_info with special handling for metrics merged_meta_info = {} if data: # Merge non-metric meta_info and aggregate metrics from all workers. all_metrics = [] for d in data: for k, v in d.meta_info.items(): if k == "metrics": if v is not None: if isinstance(v, list): all_metrics.extend(v) else: all_metrics.append(v) else: if k in merged_meta_info: # Ensure consistency for overlapping non-metric keys assert merged_meta_info[k] == v, f"Conflicting values for meta_info key '{k}'" else: merged_meta_info[k] = v # Flatten list of dicts to dict of lists for consistent metrics structure if all_metrics: merged_meta_info["metrics"] = list_of_dict_to_dict_of_list(all_metrics) cls = type(data[0]) if len(data) > 0 else DataProto return cls(batch=new_batch, non_tensor_batch=non_tensor_batch, meta_info=merged_meta_info) def reorder(self, indices): """ Note that this operation is in-place """ indices_np = indices.detach().numpy() self.batch = self.batch[indices] self.non_tensor_batch = {key: val[indices_np] for key, val in self.non_tensor_batch.items()} def repeat(self, repeat_times=2, interleave=True): """ Repeat the batch data a specified number of times. Args: repeat_times (int): Number of times to repeat the data. interleave (bool): Whether to interleave the repeated data. Returns: DataProto: A new DataProto with repeated data. """ if self.batch is not None: if interleave: # Interleave the data repeated_tensors = { key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items() } else: # Stack the data repeated_tensors = { key: tensor.unsqueeze(0).expand(repeat_times, *tensor.shape).reshape(-1, *tensor.shape[1:]) for key, tensor in self.batch.items() } repeated_batch = TensorDict( source=repeated_tensors, batch_size=(self.batch.batch_size[0] * repeat_times,), ) else: repeated_batch = None repeated_non_tensor_batch = {} for key, val in self.non_tensor_batch.items(): if interleave: repeated_non_tensor_batch[key] = np.repeat(val, repeat_times, axis=0) else: repeated_non_tensor_batch[key] = np.tile(val, (repeat_times,) + (1,) * (val.ndim - 1)) return type(self)( batch=repeated_batch, non_tensor_batch=repeated_non_tensor_batch, meta_info=self.meta_info, ) def unfold_column_chunks(self, n_split: int, split_keys: Optional[list[str]] = None): """Split along the second dim into `n_split`, unfold it to the first dim (batch dim) Useful in passing grouped tensors that doesn't want to be shuffled in dataset. keys not in split_keys are repeated to match the shape Note that if the `split_keys` is not provided, it will repeat all the keys in the second dim. """ if self.batch is not None: unfolded_batch = {} for key in self.batch.keys(): if key in split_keys if split_keys is not None else False: shape = list(self.batch[key].shape) shape[0] = self.batch[key].shape[0] * n_split shape[1] = self.batch[key].shape[1] // n_split unfolded_batch[key] = self.batch[key].reshape(*shape) else: unfolded_batch[key] = torch.repeat_interleave(self.batch[key], n_split, dim=0) # locate the `unfolded_batch` as a TensorDict on the same device as the original batch unfolded_batch = TensorDict( source=unfolded_batch, batch_size=(self.batch.batch_size[0] * n_split,), device=self.batch.device ) else: unfolded_batch = None repeated_non_tensor_batch = {} for key, val in self.non_tensor_batch.items(): if key in split_keys: shape = list(val.shape) shape[0] = val.shape[0] * n_split shape[1] = val.shape[1] // n_split repeated_non_tensor_batch[key] = val.reshape(*shape) else: repeated_non_tensor_batch[key] = np.repeat(val, n_split, axis=0) return type(self)( batch=unfolded_batch, non_tensor_batch=repeated_non_tensor_batch, meta_info=self.meta_info, ) def sample_level_repeat(self, repeat_times): """ Repeat each row of the batch data a specified number of times. Args: repeat_times (torch.tensor, list, tuple, ndarray): Number of times to repeat the data. Returns: DataProto: A new DataProto with repeated data. """ if isinstance(repeat_times, tuple): repeat_times = list(repeat_times) elif isinstance(repeat_times, torch.Tensor): assert len(repeat_times.shape) == 1 repeat_times = repeat_times.tolist() elif isinstance(repeat_times, np.ndarray): assert len(repeat_times.shape) == 1 repeat_times = repeat_times.tolist() else: assert isinstance(repeat_times, list), ( f"repeat_times type must be in [list, torch.Tensor, np.ndarray, tuple], got {type(repeat_times)}" ) repeat_times = torch.tensor(repeat_times) if self.batch is not None: # Interleave the data repeated_tensors = { key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items() } repeated_batch = TensorDict( source=repeated_tensors, batch_size=(repeat_times.sum().item(),), device=self.batch.device, ) else: repeated_batch = None repeated_non_tensor_batch = {} for key, val in self.non_tensor_batch.items(): repeated_non_tensor_batch[key] = np.repeat(val, repeat_times, axis=0) return type(self)( batch=repeated_batch, non_tensor_batch=repeated_non_tensor_batch, meta_info=self.meta_info, ) def to_tensordict(self) -> TensorDict: """Convert this DataProto to TensorDict. Note that this requires tensordict version at least 0.10 Returns: """ assert parse_version(tensordict.__version__) >= parse_version("0.10"), ( "Convert DataProto to TensorDict at least requires tensordict version 0.10" ) tensor_batch = self.batch.to_dict() non_tensor_batch = self.non_tensor_batch from tensordict.tensorclass import NonTensorData, NonTensorStack from verl.utils import tensordict_utils as tu common_keys = set(tensor_batch.keys()) & set(non_tensor_batch.keys()) assert len(common_keys) == 0, f"tensor_batch and non_tensor_batch have common keys {common_keys}" for key, val in non_tensor_batch.items(): assert isinstance(val, np.ndarray) # Convert to NonTensorStack instead of plain list to handle nested structures tensor_batch[key] = NonTensorStack.from_list([NonTensorData(item) for item in val]) output = tu.get_tensordict(tensor_dict=tensor_batch, non_tensor_dict=self.meta_info) return output def get_data_info(self) -> str: """Return formatted information about stored data with nested type details. Returns: str: Formatted string showing tensor details and recursive metadata types """ info = ["batch"] for key, tensor in self.batch.items(): if hasattr(tensor, "shape") and hasattr(tensor, "dtype") and hasattr(tensor, "device"): info.append(f" {key}: {tuple(tensor.shape)} ({tensor.dtype}) {tensor.device}") elif hasattr(tensor, "shape") and hasattr(tensor, "dtype"): info.append(f" {key}: {tuple(tensor.shape)} ({tensor.dtype})") else: info.append(f" {key}: {type(tensor).__name__}") info.append("non_tensor_batch") for key, array in self.non_tensor_batch.items(): info.append(f" {key}: ndarray{array.shape} ({array.dtype})") info.append("meta_info") for k, v in self.meta_info.items(): type_info = self._get_type_info(v) info.append(f" {k}: {type_info}") return "\n".join(info) def _get_type_info(self, value): """Recursively get type information for nested structures""" if isinstance(value, list): elem_types = {self._get_type_info(v) for v in value[:3]} return f"list[{'|'.join(elem_types) if elem_types else '...'}]" if isinstance(value, tuple): elem_types = [self._get_type_info(v) for v in value] return f"tuple({', '.join(elem_types)})" if isinstance(value, dict): if not value: return "dict" k, v = next(iter(value.items())) return f"dict[{self._get_type_info(k)}: {self._get_type_info(v)}]" if isinstance(value, np.ndarray): return f"ndarray{value.shape} ({value.dtype})" return type(value).__name__ @dataclass class DataProtoFuture: """ DataProtoFuture aims to eliminate actual data fetching on driver. By doing so, the driver doesn't have to wait for data so that asynchronous execution becomes possible. DataProtoFuture contains a list of futures from another WorkerGroup of size world_size. - collect_fn is a Callable that reduces the list of futures to a DataProto - dispatch_fn is a Callable that partitions the DataProto into a list of DataProto of size world_size and then select Potential issue: we can optimize dispatch_fn(collect_fn) such that only needed data is fetched on destination - DataProtoFuture only supports directly passing from the output of a method to another input. You can't perform any operation on the DataProtoFuture in driver. """ collect_fn: Callable futures: list[ray.ObjectRef] dispatch_fn: Callable = None @staticmethod def concat(data: list[ray.ObjectRef]) -> "DataProtoFuture": output = DataProtoFuture(collect_fn=DataProto.concat, futures=data) return output def chunk(self, chunks: int) -> list["DataProtoFuture"]: from functools import partial arg_future_lst = [] for i in range(chunks): # note that we can't directly pass i and chunks def dispatch_fn(x, i, chunks): return x.chunk(chunks=chunks)[i] arg_future = DataProtoFuture( collect_fn=self.collect_fn, dispatch_fn=partial(dispatch_fn, i=i, chunks=chunks), futures=self.futures ) arg_future_lst.append(arg_future) return arg_future_lst def get(self): output = ray.get(self.futures) # dp_size. for o in output: assert isinstance(o, DataProto | TensorDict) if isinstance(output[0], DataProto): output = DataProto.concat(output) # select dp, concat elif isinstance(output[0], TensorDict): from verl.utils.tensordict_utils import concat_tensordict output = concat_tensordict(output) else: raise TypeError(f"Unknown type {type(o[0])} in DataProtoFuture") if self.dispatch_fn is not None: output = self.dispatch_fn(output) # split in batch dim, select using dp return output def all_gather_data_proto(data: DataProto, process_group): # Note that this is an inplace operator just like torch.distributed.all_gather group_size = torch.distributed.get_world_size(group=process_group) assert isinstance(data, DataProto) prev_device = data.batch.device data = data.to(get_device_id()) data.batch = allgather_dict_tensors(data.batch.contiguous(), size=group_size, group=process_group, dim=0) data = data.to(prev_device) # all gather non_tensor_batch all_non_tensor_batch = [None for _ in range(group_size)] torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=process_group) data.non_tensor_batch = {k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch}
verl__protocol.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from functools import partial, wraps from types import FunctionType from tensordict import TensorDict from verl.protocol import DataProtoFuture, _padding_size_key from verl.utils.py_functional import DynamicEnum from verl.utils.tensordict_utils import chunk_tensordict, concat_tensordict, contiguous from verl.utils.transferqueue_utils import BatchMeta # here we add a magic number of avoid user-defined function already have this attribute MAGIC_ATTR = "attrs_3141562937" class Dispatch(DynamicEnum): """Enum class defining different dispatch modes for distributed computation. Each mode represents a specific strategy for distributing data across different ranks in a distributed system. The modes are used to control how data is partitioned and processed across different worker groups. """ _registry = {} _next_value = 0 def init_predefined_dispatch_mode(): Dispatch.register("RANK_ZERO") Dispatch.register("ONE_TO_ALL") Dispatch.register("ALL_TO_ALL") Dispatch.register("DP_COMPUTE") Dispatch.register("DP_COMPUTE_PROTO") Dispatch.register("DP_COMPUTE_PROTO_WITH_FUNC") Dispatch.register("DP_COMPUTE_METRIC") # This is a special dispatch mode for vllm ExternalRayDistributedExecutor Dispatch.register("DIRECT_ROLLOUT_METHOD") class Execute(DynamicEnum): """Enum class defining different execution modes for distributed computation. These modes control how a function should be executed across different ranks in a distributed system. """ _registry = {} _next_value = 0 def init_predefined_execute_mode(): Execute.register("ALL") Execute.register("RANK_ZERO") # Initialize the two Dynamic Enum Classes init_predefined_dispatch_mode() init_predefined_execute_mode() def _consolidate_tuple_td(chunked_arg): return tuple(contiguous(val).consolidate() for val in chunked_arg) def _split_args_kwargs_data_proto(chunks, *args, **kwargs): from verl.protocol import DataProto, DataProtoFuture splitted_args = [] for arg in args: assert isinstance(arg, DataProto | DataProtoFuture | BatchMeta | TensorDict) if isinstance(arg, TensorDict): chunked_arg = chunk_tensordict(arg, chunks) chunked_arg = _consolidate_tuple_td(chunked_arg) else: chunked_arg = arg.chunk(chunks=chunks) assert len(chunked_arg) == chunks splitted_args.append(chunked_arg) splitted_kwargs = {} for key, val in kwargs.items(): assert isinstance(val, DataProto | DataProtoFuture | BatchMeta | TensorDict) if isinstance(val, TensorDict): chunked_kwarg = chunk_tensordict(val, chunks) chunked_kwarg = _consolidate_tuple_td(chunked_kwarg) else: chunked_kwarg = val.chunk(chunks=chunks) assert len(chunked_kwarg) == chunks splitted_kwargs[key] = chunked_kwarg return splitted_args, splitted_kwargs def _split_args_kwargs_data_proto_with_auto_padding(chunks, *args, **kwargs): from verl.protocol import DataProto, DataProtoFuture data_proto_len = None padding_size = None def _padding_and_split_data(obj, chunks): nonlocal data_proto_len, padding_size assert isinstance(obj, DataProto | DataProtoFuture) if isinstance(obj, DataProto) and obj.is_padding_enabled(): # for padding, we only support DataProto with same length if data_proto_len is None: data_proto_len = len(obj) padding_size = (chunks - (data_proto_len % chunks)) if (data_proto_len % chunks > 0) else 0 else: assert data_proto_len == len(obj), ( f"expecting all arg share same length of {data_proto_len}, but got {len(obj)}" ) obj.padding(padding_size=padding_size) return obj.chunk(chunks=chunks) splitted_args = [_padding_and_split_data(arg, chunks) for arg in args] splitted_kwargs = {key: _padding_and_split_data(val, chunks) for key, val in kwargs.items()} if padding_size is not None: splitted_kwargs[_padding_size_key] = padding_size return splitted_args, splitted_kwargs def dispatch_one_to_all(worker_group, *args, **kwargs): args = tuple([arg] * worker_group.world_size for arg in args) kwargs = {k: [v] * worker_group.world_size for k, v in kwargs.items()} return args, kwargs def dummy_direct_rollout_call(worker_group, *args, **kwargs): raise NotImplementedError("Direct rollout call is forbidden.") def dispatch_all_to_all(worker_group, *args, **kwargs): return args, kwargs def collect_all_to_all(worker_group, output): return output def _concat_data_proto_or_future(output: list): import ray from verl.protocol import DataProto, DataProtoFuture # make sure all the elements in output has the same type for o in output: assert type(o) is type(output[0]) o = output[0] if isinstance(o, DataProto): return DataProto.concat(output) elif isinstance(o, ray.ObjectRef): return DataProtoFuture.concat(output) elif isinstance(o, BatchMeta): return BatchMeta.concat(output) elif isinstance(o, TensorDict): return concat_tensordict(output) else: raise NotImplementedError def dispatch_dp_compute(worker_group, *args, **kwargs): from verl.single_controller.base.worker_group import WorkerGroup assert isinstance(worker_group, WorkerGroup) for arg in args: assert isinstance(arg, tuple | list) and len(arg) == worker_group.world_size for k, v in kwargs.items(): assert isinstance(v, tuple | list) and len(v) == worker_group.world_size return args, kwargs def collect_dp_compute(worker_group, output): from verl.single_controller.base.worker_group import WorkerGroup assert isinstance(worker_group, WorkerGroup) assert len(output) == worker_group.world_size return output def dispatch_dp_compute_data_proto(worker_group, *args, **kwargs): from verl.single_controller.base.worker_group import WorkerGroup assert isinstance(worker_group, WorkerGroup) # Note: enable auto padding for dp compute DatapProto splitted_args, splitted_kwargs = _split_args_kwargs_data_proto_with_auto_padding( worker_group.world_size, *args, **kwargs, ) return splitted_args, splitted_kwargs def dispatch_dp_compute_data_proto_with_func(worker_group, *args, **kwargs): from verl.single_controller.base.worker_group import WorkerGroup assert isinstance(worker_group, WorkerGroup) assert isinstance(args[0], FunctionType) # NOTE: The first one args is a function! splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(worker_group.world_size, *args[1:], **kwargs) splitted_args_with_func = [[args[0]] * worker_group.world_size] + splitted_args return splitted_args_with_func, splitted_kwargs def collect_dp_compute_data_proto(worker_group, output): import ray from verl.protocol import DataProto for o in output: assert isinstance(o, DataProto | ray.ObjectRef), f"expecting {o} to be DataProto, but got {type(o)}" output = collect_dp_compute(worker_group, output) return _concat_data_proto_or_future(output) def dispatch_nd_compute(dp_rank_mapping: list[int], dp_size, worker_group, *args, **kwargs): import os from verl.single_controller.base.worker_group import WorkerGroup from verl.utils.ray_utils import parallel_put assert isinstance(worker_group, WorkerGroup) max_workers = max(1, min(len(args[0]), os.cpu_count())) args = [parallel_put(arg, max_workers=max_workers) for arg in args] kwargs = {k: parallel_put(v, max_workers=max_workers) for k, v in kwargs.items()} all_args = [] for arg in args: assert isinstance(arg, tuple | list) and len(arg) == dp_size transformed_args = [] for i in range(worker_group.world_size): local_dp_rank = dp_rank_mapping[i] transformed_args.append(arg[local_dp_rank]) all_args.append(transformed_args) all_args = tuple(all_args) all_kwargs = {} for k, v in kwargs.items(): assert isinstance(v, tuple | list) and len(v) == dp_size transformed_v = [] for i in range(worker_group.world_size): local_dp_rank = dp_rank_mapping[i] transformed_v.append(v[local_dp_rank]) all_kwargs[k] = transformed_v return all_args, all_kwargs def collect_nd_compute(collect_mask: list[bool], worker_group, output): from verl.single_controller.base.worker_group import WorkerGroup assert isinstance(worker_group, WorkerGroup) assert len(output) == worker_group.world_size output_in_dp = [] for global_rank in range(worker_group.world_size): collect_dp_rank = collect_mask[global_rank] if collect_dp_rank: output_in_dp.append(output[global_rank]) return output_in_dp def dispatch_nd_compute_dataproto(dp_rank_mapping: list[int], dp_size, worker_group, *args, **kwargs): splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(dp_size, *args, **kwargs) return dispatch_nd_compute(dp_rank_mapping, dp_size, worker_group, *splitted_args, **splitted_kwargs) def collect_nd_compute_dataproto(collect_mask: list[bool], worker_group, output): output = collect_nd_compute(collect_mask, worker_group, output) import ray from verl.protocol import DataProto for o in output: assert isinstance(o, DataProto | ray.ObjectRef | BatchMeta | TensorDict), ( f"expecting {o} to be DataProto | ray.ObjectRef | BatchMeta | TensorDict, but got {type(o)}" ) return _concat_data_proto_or_future(output) def dispatch_lazy_compute_data_proto(mesh_name, worker_group, *args, **kwargs): from verl.single_controller.base.worker_group import WorkerGroup assert isinstance(worker_group, WorkerGroup) # query dispatch info of the worker group if mesh_name not in worker_group._dispatch_info: worker_group._dispatch_info[mesh_name] = worker_group._query_dispatch_info(mesh_name) assert len(worker_group._dispatch_info[mesh_name]) == worker_group.world_size dp_rank_mapping = worker_group._dispatch_info[mesh_name] # perform dispatch dp_size = max(dp_rank_mapping) + 1 return dispatch_nd_compute_dataproto(dp_rank_mapping, dp_size, worker_group, *args, **kwargs) def collect_lazy_compute_data_proto(mesh_name, worker_group, *args, **kwargs): from verl.single_controller.base.worker_group import WorkerGroup assert isinstance(worker_group, WorkerGroup) # the dispatch info is stored in the worker group assert mesh_name in worker_group._dispatch_info if mesh_name not in worker_group._collect_info: worker_group._collect_info[mesh_name] = worker_group._query_collect_info(mesh_name) assert len(worker_group._collect_info[mesh_name]) == worker_group.world_size # a boolean of whether the dp_rank is used for collect collect_mask = worker_group._collect_info[mesh_name] # perform dispatch return collect_nd_compute_dataproto(collect_mask, worker_group, *args, **kwargs) def make_nd_compute_dataproto_dispatch_fn(mesh_name): return { "dispatch_fn": partial(dispatch_lazy_compute_data_proto, mesh_name), "collect_fn": partial(collect_lazy_compute_data_proto, mesh_name), } # Global registry for dispatch mode. DISPATCH_MODE_FN_REGISTRY = { Dispatch.ONE_TO_ALL: { "dispatch_fn": dispatch_one_to_all, "collect_fn": collect_all_to_all, }, Dispatch.ALL_TO_ALL: { "dispatch_fn": dispatch_all_to_all, "collect_fn": collect_all_to_all, }, Dispatch.DP_COMPUTE: {"dispatch_fn": dispatch_dp_compute, "collect_fn": collect_dp_compute}, Dispatch.DP_COMPUTE_PROTO: { "dispatch_fn": dispatch_dp_compute_data_proto, "collect_fn": collect_dp_compute_data_proto, }, Dispatch.DP_COMPUTE_PROTO_WITH_FUNC: { "dispatch_fn": dispatch_dp_compute_data_proto_with_func, "collect_fn": collect_dp_compute_data_proto, }, Dispatch.DP_COMPUTE_METRIC: {"dispatch_fn": dispatch_dp_compute_data_proto, "collect_fn": collect_dp_compute}, Dispatch.DIRECT_ROLLOUT_METHOD: { "dispatch_fn": dummy_direct_rollout_call, "collect_fn": dummy_direct_rollout_call, }, } def get_predefined_dispatch_fn(dispatch_mode): return DISPATCH_MODE_FN_REGISTRY[dispatch_mode] def register_dispatch_mode(dispatch_mode_name, dispatch_fn, collect_fn): """ Register a new dispatch mode. """ dispatch_mode = Dispatch.register(dispatch_mode_name) _check_dispatch_mode(dispatch_mode) assert dispatch_mode not in DISPATCH_MODE_FN_REGISTRY, f"dispatch_mode_name {dispatch_mode_name} already exists" DISPATCH_MODE_FN_REGISTRY[dispatch_mode] = {"dispatch_fn": dispatch_fn, "collect_fn": collect_fn} def update_dispatch_mode(dispatch_mode, dispatch_fn, collect_fn): """ Update the dispatch mode. """ _check_dispatch_mode(dispatch_mode) assert dispatch_mode in DISPATCH_MODE_FN_REGISTRY, f"dispatch_mode {dispatch_mode} not found" DISPATCH_MODE_FN_REGISTRY[dispatch_mode] = {"dispatch_fn": dispatch_fn, "collect_fn": collect_fn} def get_predefined_execute_fn(execute_mode): """ Note that here we only asks execute_all and execute_rank_zero to be implemented Leave the choice of how these two functions handle argument 'blocking' to users """ predefined_execute_mode_fn = { Execute.ALL: {"execute_fn_name": "execute_all"}, Execute.RANK_ZERO: {"execute_fn_name": "execute_rank_zero"}, } return predefined_execute_mode_fn[execute_mode] def _check_dispatch_mode(dispatch_mode): assert isinstance(dispatch_mode, Dispatch | dict), ( f"dispatch_mode must be a Dispatch or a Dict. Got {dispatch_mode}" ) if isinstance(dispatch_mode, dict): necessary_keys = ["dispatch_fn", "collect_fn"] for key in necessary_keys: assert key in dispatch_mode, f"key {key} should be in dispatch_mode if it is a dictionary" def _check_execute_mode(execute_mode): assert isinstance(execute_mode, Execute), f"execute_mode must be a Execute. Got {execute_mode}" def _materialize_futures(*args, **kwargs): new_args = [] for arg in args: if isinstance(arg, DataProtoFuture): arg = arg.get() # add more type to materialize new_args.append(arg) for k, v in kwargs.items(): if isinstance(v, DataProtoFuture): kwargs[k] = v.get() new_args = tuple(new_args) return new_args, kwargs def register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.ALL, blocking=True, materialize_futures=True): """Register a function with distributed execution configuration. This decorator registers a function with specific dispatch and execution modes for distributed computation. It handles both synchronous and asynchronous functions, and optionally materializes futures before execution. Args: dispatch_mode: Dispatch mode for computation distribution. Default: Dispatch.ALL_TO_ALL. execute_mode: Execute mode for computation distribution. Default: Execute.ALL. blocking: Whether the execution should be blocking. Defaults to True. materialize_futures: Whether to materialize the data before dispatching. Defaults to True. Returns: A decorator that wraps the original function with distributed execution configuration. """ from verl.utils.transferqueue_utils import tqbridge _check_dispatch_mode(dispatch_mode=dispatch_mode) _check_execute_mode(execute_mode=execute_mode) def decorator(func): func = tqbridge(dispatch_mode=dispatch_mode)(func) @wraps(func) def inner(*args, **kwargs): if materialize_futures: args, kwargs = _materialize_futures(*args, **kwargs) return func(*args, **kwargs) @wraps(func) async def async_inner(*args, **kwargs): if materialize_futures: args, kwargs = _materialize_futures(*args, **kwargs) return await func(*args, **kwargs) wrapper = async_inner if inspect.iscoroutinefunction(func) else inner attrs = {"dispatch_mode": dispatch_mode, "execute_mode": execute_mode, "blocking": blocking} setattr(wrapper, MAGIC_ATTR, attrs) return wrapper return decorator
verl__single_controller__base__decorator.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ the class for Worker """ import os import socket import warnings from dataclasses import dataclass import ray from verl.utils.device import ( get_torch_device, get_visible_devices_keyword, is_npu_available, ) from .decorator import Dispatch, Execute, register @dataclass class DistRankInfo: tp_rank: int dp_rank: int pp_rank: int cp_rank: int @dataclass class DistGlobalInfo: tp_size: int dp_size: int pp_size: int cp_size: int class WorkerHelper: @staticmethod def _get_node_ip(): if os.getenv("WG_BACKEND", None) == "ray": return ray.util.get_node_ip_address() else: raise NotImplementedError("WG_BACKEND now just support ray mode.") @staticmethod def _get_free_port(): with socket.socket() as sock: sock.bind(("", 0)) return sock.getsockname()[1] def get_availale_master_addr_port(self): warnings.warn( "This function is deprecated due to typo in name; Please use `get_available_master_addr_port` instead", stacklevel=2, ) return self.get_available_master_addr_port() def get_available_master_addr_port(self): return self._get_node_ip().strip("[]"), str(self._get_free_port()) # we assume that in each WorkerGroup, there is a Master Worker class Worker(WorkerHelper): """A distributed worker that handles initialization and configuration for distributed training. This class manages worker initialization, configuration, and provides methods for executing distributed operations. It handles communication settings, device configuration, and worker metadata management. """ fused_worker_attr_name = "fused_worker_dict" def _register_dispatch_collect_info(self, mesh_name: str, dp_rank: int, is_collect: bool): """Register the dp_rank for a given mesh name. This function is meant to be called by the worker Args: mesh_name (str): Name of the mesh to register dp_rank for. dp_rank (int): dp_rank to register for the given mesh name. is_collect (bool): Whether the dp_rank is used for collect. """ if mesh_name in self.__dispatch_dp_rank or mesh_name in self.__collect_dp_rank: raise ValueError(f"mesh_name {mesh_name} has been registered") self.__dispatch_dp_rank[mesh_name] = dp_rank self.__collect_dp_rank[mesh_name] = is_collect @register(dispatch_mode=Dispatch.ONE_TO_ALL) def _query_dispatch_info(self, mesh_name: str): """Query the dispatch info for a given mesh name. Args: mesh_name (str): Name of the mesh to query dispatch info for. Returns: int: The dp_rank for the given mesh name. """ assert mesh_name in self.__dispatch_dp_rank, f"{mesh_name} is not registered in {self.__class__.__name__}" # note that each rank store its own dp_rank return self.__dispatch_dp_rank[mesh_name] @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 given mesh name. Args: mesh_name (str): Name of the mesh to query collect info for. Returns: bool: Whether the dp_rank is used for collect. """ assert mesh_name in self.__collect_dp_rank, f"{mesh_name} is not registered in {self.__class__.__name__}" return self.__collect_dp_rank[mesh_name] def get_dispatch_collect(self): """Get all registered dispatch and collect dp_ranks. Returns: dict[str, int]: A dictionary mapping mesh names to their dispatch dp_ranks. dict[str, bool]: A dictionary mapping mesh names to whether they are used for collect. """ return {"dispatch_dp_rank": self.__dispatch_dp_rank, "collect_dp_rank": self.__collect_dp_rank} def set_dispatch_collect(self, mesh_name: str, dispatch_dp_rank: dict[str, int], collect_dp_rank: dict[str, bool]): """Set the dispatch and collect dp_ranks for all registered meshes. Args: mesh_name (str): Mesh name to set dispatch and collect dp_ranks for. dispatch_dp_rank (dict[str, int]): A dictionary mapping mesh names to their dispatch dp_ranks. collect_dp_rank (dict[str, bool]): 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, ( f"{mesh_name} is already registered, {self.__collect_dp_rank.keys()}" ) for dp_rank in dispatch_dp_rank.values(): self.__dispatch_dp_rank[mesh_name] = dp_rank for is_collect in collect_dp_rank.values(): self.__collect_dp_rank[mesh_name] = is_collect @register(dispatch_mode=Dispatch.ONE_TO_ALL, blocking=True) def create_transferqueue_client(self, config): from verl.utils.transferqueue_utils import create_transferqueue_client create_transferqueue_client( client_id=f"worker_{self.rank}", config=config.transfer_queue, ) @classmethod def env_keys(cls): """The keys of the environment variables that are used to configure the Worker.""" return [ "WORLD_SIZE", "RANK", "LOCAL_WORLD_SIZE", "LOCAL_RANK", "MASTER_ADDR", "MASTER_PORT", get_visible_devices_keyword().upper(), ] def __init__(self, cuda_visible_devices=None) -> None: """Initialize the worker with environment settings and device configuration. Args: cuda_visible_devices (str, optional): CUDA visible devices configuration. Defaults to None. """ # construct a meta from environment variable. Note that the import must be inside the class because # it is executed remotely import os self._setup_env_cuda_visible_devices() world_size = int(os.environ["WORLD_SIZE"]) rank = int(os.environ["RANK"]) self._rank = rank self._world_size = world_size master_addr = os.environ["MASTER_ADDR"] master_port = os.environ["MASTER_PORT"] local_world_size = int(os.getenv("LOCAL_WORLD_SIZE", "1")) local_rank = int(os.getenv("LOCAL_RANK", "0")) store = { "_world_size": world_size, "_rank": rank, "_local_world_size": local_world_size, "_local_rank": local_rank, "_master_addr": master_addr, "_master_port": master_port, } if cuda_visible_devices is not None: store[f"_{get_visible_devices_keyword()}".lower()] = cuda_visible_devices self._configure_with_store(store=store) self.fused_worker_dict = {} self.__dispatch_dp_rank = {} self.__collect_dp_rank = {} def get_fused_worker_by_name(self, worker_name: str): """Get a fused worker by its name. Args: worker_name (str): Name of the worker to retrieve """ return self.fused_worker_dict.get(worker_name, None) def _setup_env_cuda_visible_devices(self): from verl.utils.ray_utils import ray_noset_visible_devices is_ray_noset_visible_devices = ray_noset_visible_devices() # Prevent use of clashing `{CUDA/HIP/ROCR}_VISIBLE_DEVICES`` rocr_val = os.environ.get("ROCR_VISIBLE_DEVICES", None) hip_val = os.environ.get("HIP_VISIBLE_DEVICES", None) cuda_val = os.environ.get("CUDA_VISIBLE_DEVICES", None) if hip_val: # Switch the use of HIP_VISIBLE_DEVICES to CUDA_VISIBLE_DEVICES for consistency. # Make sure that the HIP_VISIBLE_DEVICES is set to the same value as CUDA_VISIBLE_DEVICES # at this point. val = os.environ.pop("HIP_VISIBLE_DEVICES") hip_val = None if cuda_val: assert val == cuda_val, ( f"Please use the same HIP_VISIBLE_DEVICES or CUDA_VISIBLE_DEVICES, inconsistant values " f"found: {val} and {cuda_val}." ) else: cuda_val = val os.environ["CUDA_VISIBLE_DEVICES"] = val # os.environ["HIP_VISIBLE_DEVICES"] = val if rocr_val: # You must take care if both HIP/CUDA and ROCR env vars are set as they have # different meanings. Both env vars accept either a list of ints or a # list of UUIDs. The ROCR env var is processed first which then reduces # the number of GPUs that HIP can select from. # https://github.com/pytorch/pytorch/pull/144026 # To avoid the complexity of this, we simply gives out error if both are set # (Also to keep consistency with ray's practice with 2.45.0). # Otherwise, we will set ROCR_VISIBLE_DEVICES to CUDA_VISIBLE_DEVICES # and remove ROCR_VISIBLE_DEVICES. if cuda_val: raise ValueError("Please don't set ROCR_VISIBLE_DEVICES when HIP/CUDA_VISIBLE_DEVICES is set.") cuda_val = os.environ.pop("ROCR_VISIBLE_DEVICES") os.environ["CUDA_VISIBLE_DEVICES"] = cuda_val rocr_val = None if is_ray_noset_visible_devices: # NOTE: Ray will automatically set the *_VISIBLE_DEVICES # environment variable for each actor, unless # RAY_EXPERIMENTAL_NOSET_*_VISIBLE_DEVICES is set, # so we need to set local rank when the flag is set. device_name = "NPU" if is_npu_available else "GPU" local_rank = ray.get_runtime_context().get_accelerator_ids()[device_name][0] os.environ["LOCAL_RANK"] = local_rank get_torch_device().set_device(int(local_rank)) def _configure_with_store(self, store: dict): """ This function should only be called inside by WorkerGroup """ store_env_dict = {f"_{key.lower()}": store.get(f"_{key.lower()}", None) for key in type(self).env_keys()} self.__dict__.update(store_env_dict) # this is hacky # print(f"__dict__: {self.__dict__}") for key in type(self).env_keys(): val = self.__dict__.get(f"_{key.lower()}", None) if val is not None: # print(f"set {key} to {val}") os.environ[key] = str(val) os.environ["REDIS_STORE_SERVER_HOST"] = ( str(self._master_addr).replace("[", "").replace("]", "") if self._master_addr else "" ) def get_master_addr_port(self): """Get the master address and port for distributed communication.""" return self._master_addr, self._master_port def get_cuda_visible_devices(self): """Get the CUDA visible devices configuration.""" import os visible_devices = os.environ.get(get_visible_devices_keyword().upper(), "not set") return visible_devices @property def world_size(self): """Get the total number of workers in the distributed setup.""" return self._world_size @property def rank(self): """Get the rank of this worker in the distributed setup.""" return self._rank @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO_WITH_FUNC) def execute_with_func_generator(self, func, *args, **kwargs): """Execute a function with function generator dispatch mode. Args: func: Function to execute *args: Positional arguments for the function **kwargs: Keyword arguments for the function """ ret_proto = func(self, *args, **kwargs) return ret_proto @register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.RANK_ZERO) def execute_func_rank_zero(self, func, *args, **kwargs): """Execute a function in rank zero execution mode. Args: func: Function to execute *args: Positional arguments for the function **kwargs: Keyword arguments for the function """ result = func(*args, **kwargs) return result
verl__single_controller__base__worker.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ the class of WorkerGroup """ import logging import signal import threading import time from typing import Any, Callable from .decorator import MAGIC_ATTR, Dispatch, get_predefined_dispatch_fn, get_predefined_execute_fn class ResourcePool: """ Manages a pool of resources across multiple nodes, tracking process counts and GPU allocations. The class provides methods to calculate world size, local world sizes, and local ranks across all nodes in the pool. """ def __init__(self, process_on_nodes=None, max_colocate_count: int = 10, n_gpus_per_node=8) -> None: """Initialize the ResourcePool with node processes and GPU configuration. Args: process_on_nodes (List[int], optional): List of process counts per node. Defaults to empty list. max_colocate_count (int, optional): Maximum number of processes that can be colocated. Defaults to 10. n_gpus_per_node (int, optional): Number of GPUs available per node. Defaults to 8. """ if process_on_nodes is None: process_on_nodes = [] self._store = process_on_nodes self.max_colocate_count = max_colocate_count self.n_gpus_per_node = n_gpus_per_node # this is left for future huawei GPU that contains 16 GPUs per node def add_node(self, process_count): self._store.append(process_count) @property def world_size(self): """Total number of processes across all nodes in the pool.""" return sum(self._store) def __call__(self) -> Any: return self._store @property def store(self): return self._store def local_world_size_list(self) -> list[int]: """Returns a flat list where each process has its local world size.""" nested_local_world_size_list = [ [local_world_size for _ in range(local_world_size)] for local_world_size in self._store ] return [item for row in nested_local_world_size_list for item in row] def local_rank_list(self) -> list[int]: """Returns a flat list of local ranks for all processes across all nodes.""" nested_local_rank_list = [[i for i in range(local_world_size)] for local_world_size in self._store] return [item for row in nested_local_rank_list for item in row] class ClassWithInitArgs: """ Wrapper class that stores constructor arguments for deferred instantiation. This class is particularly useful for remote class instantiation where the actual construction needs to happen at a different time or location. """ def __init__(self, cls, *args, **kwargs) -> None: """Initialize the ClassWithInitArgs instance. Args: cls: The class to be instantiated later *args: Positional arguments for the class constructor **kwargs: Keyword arguments for the class constructor """ self.cls = cls self.args = args self.kwargs = kwargs self.fused_worker_used = False def __call__(self) -> Any: """Instantiate the stored class with the stored arguments.""" return self.cls(*self.args, **self.kwargs) def check_workers_alive(workers: list, is_alive: Callable, gap_time: float = 1) -> None: """Continuously monitors worker processes and raises SIGABRT if any worker dies. Args: workers (List): List of worker objects to monitor is_alive (Callable): Function to check if a worker is alive gap_time (float): Time interval between checks """ import time while True: for worker in workers: if not is_alive(worker): logging.warning(f"worker {worker} is not alive sending signal to main thread") signal.raise_signal(signal.SIGABRT) time.sleep(gap_time) class WorkerGroup: """ Base class for managing a group of workers in a distributed system. The class provides methods for worker management, aliveness checking, and method binding. """ fused_worker_execute_fn_name = "_fuw_execute" def __init__(self, resource_pool: ResourcePool, **kwargs) -> None: self._is_init_with_detached_workers = resource_pool is None self.fused_worker_used = False if resource_pool is not None: # handle the case when WorkGroup is attached to an existing one self._procecss_dispatch_config = resource_pool() else: self._procecss_dispatch_config = None self._workers = [] self._worker_names = [] self._dispatch_info = {} self._collect_info = {} self._master_addr = None self._master_port = None self._checker_thread: threading.Thread = None def _is_worker_alive(self, worker): """Check if a worker is alive. Must be implemented by derived classes.""" raise NotImplementedError("WorkerGroup._is_worker_alive called, should be implemented in derived class.") def _block_until_all_workers_alive(self) -> None: """Blocks until all workers in the group are alive.""" while True: all_state = [self._is_worker_alive(worker) for worker in self._workers] if False in all_state: time.sleep(1) else: break def start_worker_aliveness_check(self, every_n_seconds=1) -> None: """Starts a background thread to monitor worker aliveness. Args: every_n_seconds (int): Interval between aliveness checks """ # before starting checking worker aliveness, make sure all workers are already alive self._block_until_all_workers_alive() self._checker_thread = threading.Thread( target=check_workers_alive, args=(self._workers, self._is_worker_alive, every_n_seconds) ) self._checker_thread.start() @property def world_size(self): """Number of workers in the group.""" return len(self._workers) def _bind_worker_method(self, user_defined_cls, func_generator): """Binds worker methods to the WorkerGroup based on registered attributes. Args: user_defined_cls (type): The class containing methods to bind func_generator (Callable): Function that generates the bound method Returns: List[str]: List of method names that were successfully bound """ method_names = [] for method_name in dir(user_defined_cls): try: method = getattr(user_defined_cls, method_name) assert callable(method), f"{method_name} in {user_defined_cls} is not callable" except Exception: # if it is a property, it will fail because Class doesn't have instance property continue if hasattr(method, MAGIC_ATTR): # this method is decorated by register attribute = getattr(method, MAGIC_ATTR) assert isinstance(attribute, dict), f"attribute must be a dictionary. Got {type(attribute)}" assert "dispatch_mode" in attribute, "attribute must contain dispatch_mode in its key" dispatch_mode = attribute["dispatch_mode"] execute_mode = attribute["execute_mode"] blocking = attribute["blocking"] # get dispatch fn if isinstance(dispatch_mode, Dispatch): # get default dispatch fn fn = get_predefined_dispatch_fn(dispatch_mode=dispatch_mode) dispatch_fn = fn["dispatch_fn"] collect_fn = fn["collect_fn"] else: assert isinstance(dispatch_mode, dict) assert "dispatch_fn" in dispatch_mode assert "collect_fn" in dispatch_mode dispatch_fn = dispatch_mode["dispatch_fn"] collect_fn = dispatch_mode["collect_fn"] # get execute_fn_name execute_mode = get_predefined_execute_fn(execute_mode=execute_mode) wg_execute_fn_name = execute_mode["execute_fn_name"] # get execute_fn from string try: execute_fn = getattr(self, wg_execute_fn_name) assert callable(execute_fn), "execute_fn must be callable" except Exception: print(f"execute_fn {wg_execute_fn_name} is invalid") raise # bind a new method to the RayWorkerGroup func = func_generator( self, method_name, dispatch_fn=dispatch_fn, collect_fn=collect_fn, execute_fn=execute_fn, blocking=blocking, ) try: setattr(self, method_name, func) method_names.append(method_name) except Exception as e: raise ValueError(f"Fail to set method_name {method_name}") from e return method_names
verl__single_controller__base__worker_group.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import logging import os import socket from copy import deepcopy from dataclasses import dataclass, field from typing import Any, Optional import numpy as np import ray from ray.experimental.state.api import get_actor from ray.util.placement_group import PlacementGroup, placement_group from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy, PlacementGroupSchedulingStrategy from verl.protocol import DataProto, _padding_size_key from verl.single_controller.base import ClassWithInitArgs, ResourcePool, Worker, WorkerGroup from verl.single_controller.base.decorator import MAGIC_ATTR, Dispatch from verl.utils.device import get_device_name from verl.utils.py_functional import temp_env_var __all__ = ["Worker"] logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) def get_random_string(length: int) -> str: import random import string letters_digits = string.ascii_letters + string.digits return "".join(random.choice(letters_digits) for _ in range(length)) def func_generator(self, method_name, dispatch_fn, collect_fn, execute_fn, blocking): class Functor: def __call__(this, *args, **kwargs): args, kwargs = dispatch_fn(self, *args, **kwargs) padding_count = kwargs.pop(_padding_size_key, 0) output = execute_fn(method_name, *args, **kwargs) if blocking: output = ray.get(output) output = collect_fn(self, output) if padding_count > 0: if isinstance(output, DataProto): indices = [i for i in range(len(output))][:-padding_count] output = output.select_idxs(indices) elif isinstance(output, list): output = output[:-padding_count] return output # use class type to pass the method_name to get a better observability return type(method_name, (Functor,), {})() def sort_placement_group_by_node_ip(pgs: list[PlacementGroup]) -> list[PlacementGroup]: """ Sort the placement groups by node ip, all bundles in a single placement group should be on the same node. FSDPCheckpointManager saves sharded model states and optimizer states in local storage, which requires RANK to be consistent across nodes when resume from checkpoint. With this function, if there's only one resource pool and there's no node change, RANK should be consistent across nodes in multiple ray jobs, even if the whole ray cluster is restarted. """ node_ip = {node["NodeID"]: node["NodeManagerAddress"] for node in ray.nodes()} pg_ip = {} for pg in pgs: specs = ray._private.state.state.placement_group_table(pg.id) # all bunles should be on the same node node_id = specs["bundles_to_node_id"][0] pg_ip[pg.id] = node_ip[node_id] return sorted(pgs, key=lambda pg: pg_ip[pg.id]) @ray.remote def get_master_addr_port(master_port_range: Optional[list[int]] = None) -> tuple[str, str]: addr = ray.util.get_node_ip_address().strip("[]") if master_port_range is None: with socket.socket() as s: s.bind(("", 0)) port = s.getsockname()[1] else: port = master_port_range[0] while port < master_port_range[1]: try: with socket.socket() as s: s.bind(("", port)) break except OSError: port += 1 # Increment port number if already in use logger.info("Port %d is already in use, trying port %d", port - 1, port) else: raise RuntimeError(f"Could not find a free port in range {master_port_range}") return addr, str(port) class RayResourcePool(ResourcePool): def __init__( self, process_on_nodes: Optional[list[int]] = None, use_gpu: bool = True, name_prefix: str = None, max_colocate_count: int = 10, detached=False, accelerator_type: Optional[str] = None, ) -> None: super().__init__(process_on_nodes, max_colocate_count) self.use_gpu = use_gpu # print(f"in RayProcessDispatchConfiguration: name_prefix = {name_prefix}") self.name_prefix = get_random_string(length=6) if name_prefix is None else name_prefix self.pgs = None self.detached = detached self.accelerator_type = accelerator_type def get_placement_groups(self, strategy="STRICT_PACK", name=None, device_name="cuda"): if self.pgs is not None: return self.pgs pg_name_prefix = ( name if name else f"{self.name_prefix}verl_group_{'_'.join([str(count) for count in self._store])}:" ) # print(f"pg_name_prefix = {pg_name_prefix}") if device_name == "npu": device_name = "NPU" elif device_name == "cuda": device_name = "GPU" bundle = {"CPU": self.max_colocate_count} if self.use_gpu: bundle[device_name] = 1 if self.accelerator_type is not None: bundle[self.accelerator_type] = 1e-4 pg_scheme = [[bundle.copy() for _ in range(process_count)] for process_count in self._store] lifetime = "detached" if self.detached else None pgs = [ placement_group(bundles=bundles, strategy=strategy, name=pg_name_prefix + str(idx), lifetime=lifetime) for idx, bundles in enumerate(pg_scheme) ] ray.get([pg.ready() for pg in pgs]) self.pgs = sort_placement_group_by_node_ip(pgs) return pgs class SubRayResourcePool(RayResourcePool): def __init__( self, placement_groups: list[PlacementGroup], start_bundle_index: int, subgroup_world_size: int, **kwargs, ) -> None: super().__init__(**kwargs) self.pgs = placement_groups self.start_bundle_index = start_bundle_index self.subgroup_world_size = subgroup_world_size @property def world_size(self): return self.subgroup_world_size @dataclass class ResourcePoolManager: """ Define a resource pool specification. Resource pool will be initialized first. """ resource_pool_spec: dict[str, list[int]] mapping: dict[int, str] resource_pool_dict: dict[str, RayResourcePool] = field(default_factory=dict) def create_resource_pool(self): """Create Ray resource pools for distributed training. Initializes resource pools based on the resource pool specification, with each pool managing GPU resources across multiple nodes. For FSDP backend, uses max_colocate_count=1 to merge WorkerGroups. For Megatron backend, uses max_colocate_count>1 for different models. """ for resource_pool_name, process_on_nodes in self.resource_pool_spec.items(): # max_colocate_count means the number of WorkerGroups (i.e. processes) in each RayResourcePool # For FSDP backend, using max_colocate_count=3: actor_critic_ref, rollout, reward model (optional) # For Megatron backend, we recommend using max_colocate_count>1 # that can utilize different WorkerGroup for differnt models resource_pool = RayResourcePool( process_on_nodes=process_on_nodes, use_gpu=True, max_colocate_count=3, name_prefix=resource_pool_name ) self.resource_pool_dict[resource_pool_name] = resource_pool self._check_resource_available() def get_resource_pool(self, role) -> RayResourcePool: """Get the resource pool of the worker_cls""" return self.resource_pool_dict[self.mapping[role]] def get_n_gpus(self) -> int: """Get the number of gpus in this cluster.""" return sum([n_gpus for process_on_nodes in self.resource_pool_spec.values() for n_gpus in process_on_nodes]) def _check_resource_available(self): """Check if the resource pool can be satisfied in this ray cluster.""" node_available_resources = ray._private.state.available_resources_per_node() node_available_gpus = { node: node_info.get("GPU", 0) if "GPU" in node_info else node_info.get("NPU", 0) for node, node_info in node_available_resources.items() } # check total required gpus can be satisfied total_available_gpus = sum(node_available_gpus.values()) total_required_gpus = sum( [n_gpus for process_on_nodes in self.resource_pool_spec.values() for n_gpus in process_on_nodes] ) if total_available_gpus < total_required_gpus: raise ValueError( f"Total available GPUs {total_available_gpus} is less than total desired GPUs {total_required_gpus}" ) def extract_pg_from_exist( resource_pools: dict[str, RayResourcePool], src_role_names: list[str], resource_pool: RayResourcePool ) -> list: src_pgs = [ pg for role_name, resource_pool in resource_pools.items() for pg in resource_pool.get_placement_groups() if role_name in src_role_names ] sorted_src_pgs = sorted(src_pgs, key=lambda pg: pg.bundle_count, reverse=True) sorted_process_on_nodes = sorted([(val, idx) for idx, val in enumerate(resource_pool.store)], reverse=True) unsorted_pgs: list[tuple[int, PlacementGroup]] = [] searching_idx = 0 for request_process, original_idx in sorted_process_on_nodes: assert searching_idx < len(sorted_src_pgs), f"no enough nodes for request: searching {searching_idx} th node" assert request_process <= sorted_src_pgs[searching_idx].bundle_count, ( f"requesting {request_process} processes, bundle count cannot satisfy" ) unsorted_pgs.append((original_idx, sorted_src_pgs[searching_idx])) searching_idx += 1 return [pg for _, pg in sorted(unsorted_pgs)] # split a RayResourcePool or SubRayResourcePool into multiple SubRayResourcePool def split_resource_pool( resource_pool: RayResourcePool | SubRayResourcePool, split_size: int | list[int] ) -> list[SubRayResourcePool]: """ Split a RayResourcePool into multiple SubRayResourcePool. resouce_pool can also be a SubRayResourcePool (have been splited) for multiple-time spliting. Args: resource_pool (RayResourcePool | SubRayResourcePool): The resource pool to split. split_size (int | list[int]): The size of each split. If int, all splits will have the same size. If list[int], each element in the list represents the size of a split. Returns: list[SubRayResourcePool]: A list of SubRayResourcePool after splitting. """ # convert split_size to list[int] if isinstance(split_size, int): assert resource_pool.world_size % split_size == 0, "split_size must be a divisor of world_size" num_replica = resource_pool.world_size // split_size split_size_list = [split_size] * num_replica else: split_size_list = split_size assert sum(split_size_list) == resource_pool.world_size, "split_size must sum up to world_size" # judge if this resource pool has been splited if isinstance(resource_pool, SubRayResourcePool): start_bundle_idx_list = np.cumsum([resource_pool.start_bundle_index] + split_size_list[:-1]) else: start_bundle_idx_list = np.cumsum([0] + split_size_list[:-1]) # ensure resource_pool.pgs has been initialized placement_groups = resource_pool.get_placement_groups() split_resource_pools = [ SubRayResourcePool( process_on_nodes=resource_pool.store, use_gpu=resource_pool.use_gpu, name_prefix=f"{resource_pool.name_prefix}_split_{split_idx}", max_colocate_count=resource_pool.max_colocate_count, placement_groups=placement_groups, start_bundle_index=start_bundle_idx_list[split_idx], subgroup_world_size=split_size_list[split_idx], ) for split_idx in range(len(split_size_list)) ] return split_resource_pools def merge_resource_pool(rp1: RayResourcePool, rp2: RayResourcePool) -> RayResourcePool: assert rp1.use_gpu == rp2.use_gpu, "Both RayResourcePool must either use_gpu or not" assert rp1.max_colocate_count == rp2.max_colocate_count, "Both RayResourcePool must has the same max_colocate_count" assert rp1.n_gpus_per_node == rp2.n_gpus_per_node, "Both RayResourcePool must has the same n_gpus_per_node" assert rp1.detached == rp2.detached, "Detached ResourcePool cannot be merged with non-detached ResourcePool" new_store = rp1.store + rp2.store merged = type(rp1)( new_store, rp1.use_gpu, f"{rp1.name_prefix}_{rp2.name_prefix}", rp1.max_colocate_count, rp1.detached ) merged.pgs = rp1.get_placement_groups(device_name=get_device_name()) + rp2.get_placement_groups( device_name=get_device_name() ) return merged class RayClassWithInitArgs(ClassWithInitArgs): """A wrapper class for Ray actors with initialization arguments. This class extends ClassWithInitArgs to provide additional functionality for configuring and creating Ray actors with specific resource requirements and scheduling strategies. """ def __init__(self, cls, *args, **kwargs) -> None: # self._options = kwargs.pop('options', dict()) super().__init__(cls, *args, **kwargs) self._options = {} self._additional_resource = {} def set_additional_resource(self, additional_resource): """Set additional resource requirements for the actor. Args: additional_resource: Dictionary specifying additional resource requirements """ self._additional_resource = additional_resource def update_options(self, options: dict): """Update the Ray actor creation options. Args: options: Dictionary of options to update """ self._options.update(options) def __call__( self, placement_group, placement_group_bundle_idx, use_gpu: bool = True, num_gpus=1, sharing_with=None, device_name="cuda", ) -> Any: """Create and return a Ray actor with the configured options. Args: placement_group: Ray placement group for scheduling placement_group_bundle_idx: Index of the bundle in the placement group use_gpu: Whether to use GPU resources num_gpus: Number of GPUs to allocate sharing_with: Actor to share resources with device_name: Device for training Returns: A Ray actor handle with the configured options """ if sharing_with is not None: target_node_id = ray.get(sharing_with.get_node_id.remote()) visible_devices = ray.get(sharing_with.get_cuda_visible_devices.remote()) options = {"scheduling_strategy": NodeAffinitySchedulingStrategy(node_id=target_node_id, soft=False)} return self.cls.options(**options).remote(*self.args, cuda_visible_devices=visible_devices, **self.kwargs) options = { "scheduling_strategy": PlacementGroupSchedulingStrategy( placement_group=placement_group, placement_group_bundle_index=placement_group_bundle_idx ) } options.update(self._options) if use_gpu and device_name == "cuda": options["num_gpus"] = num_gpus if use_gpu and device_name == "npu": options["resources"] = {"NPU": num_gpus} if len(self._additional_resource) > 1: for k, v in self._additional_resource.items(): options[k] = v # print("cls:", self.cls) # print("args: ", self.args) # print("kwargs: ", self.kwargs) return self.cls.options(**options).remote(*self.args, **self.kwargs) class RayWorkerGroup(WorkerGroup): """A group of Ray workers that can be managed collectively. This class extends WorkerGroup to provide Ray-specific functionality for creating and managing groups of Ray actors with specific resource requirements and scheduling strategies. """ def __init__( self, resource_pool: RayResourcePool = None, ray_cls_with_init: RayClassWithInitArgs = None, bin_pack: bool = True, name_prefix: str = None, detached=False, worker_names=None, worker_handles: list[ray.actor.ActorHandle] = None, ray_wait_register_center_timeout: int = 300, **kwargs, ) -> None: """Initialize a RayWorkerGroup. Args: resource_pool: Resource pool for worker allocation ray_cls_with_init: Class with initialization arguments for workers bin_pack: Whether to use strict bin packing for resource allocation name_prefix: Prefix for worker names detached: Whether workers should be detached worker_names: Names of existing workers to attach to ray_wait_register_center_timeout: Timeout for waiting on register center **kwargs: Additional keyword arguments """ self._master_addr = kwargs.pop("master_addr", None) self._master_port = kwargs.pop("master_port", None) self.use_gpu = kwargs.pop("use_gpu", resource_pool.use_gpu if resource_pool is not None else True) self._ray_master_port_range = kwargs.pop("master_port_range", None) super().__init__(resource_pool=resource_pool, **kwargs) self.ray_cls_with_init = ray_cls_with_init self.name_prefix = get_random_string(length=6) if name_prefix is None else name_prefix self._ray_wait_register_center_timeout = ray_wait_register_center_timeout # Whether the WorkerGroup is a Colocate WorkerGroup created by FusedWorker. self.fused_worker_used = False if ray_cls_with_init is None else ray_cls_with_init.fused_worker_used # if a WorkerGroup is spawned from Colocate WorkerGroup, this indicates which sub-class is binded to # this WorkerGroup. self.sub_cls_name = "" self.device_name = kwargs.get("device_name", "cuda") self.profile_steps = kwargs.get("profile_steps", None) self.worker_nsight_options = kwargs.get("worker_nsight_options", None) self.customized_worker_env = kwargs.get("worker_env", {}) if self.worker_nsight_options is not None and self.worker_nsight_options["capture-range-end"] is None: self.worker_nsight_options["capture-range-end"] = f"repeat-shutdown:{6 * len(self.profile_steps)}" if worker_names is not None and (not self.fused_worker_used): assert self._is_init_with_detached_workers self._worker_names = worker_names if self._is_init_with_detached_workers: self._init_with_detached_workers(worker_names=worker_names, worker_handles=worker_handles) elif isinstance(resource_pool, SubRayResourcePool): self._init_with_subresource_pool( resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, bin_pack=bin_pack, detached=detached, worker_env=self.customized_worker_env, ) else: self._init_with_resource_pool( resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, bin_pack=bin_pack, detached=detached, worker_env=self.customized_worker_env, ) if ray_cls_with_init is not None: self._bind_worker_method(self.ray_cls_with_init.cls, func_generator) self.wg_dict = None self.method_names = [] def _is_worker_alive(self, worker: ray.actor.ActorHandle): """Check if a worker actor is still alive. Args: worker: Ray actor handle to check Returns: bool: True if the worker is alive, False otherwise """ worker_state_dict = get_actor(worker._actor_id.hex()) return worker_state_dict.get("state", "undefined") == "ALIVE" if worker_state_dict is not None else False def _init_with_detached_workers(self, worker_names, worker_handles): # ray.get_actor holds a weak reference to the actor, which causes actors garbage collected unexpectedly # if we only hold spawn RayWorkerGroup. By passing actor handle explicitly, spawn RayWorkerGroup have # strong reference to these actors. # https://github.com/ray-project/ray/pull/45699 workers = worker_handles if worker_handles else [ray.get_actor(name=name) for name in worker_names] self._workers = workers self._world_size = len(workers) def _get_master_addr_port(self, pg, bundle_index=0, master_port_range=None): """Get master addr and port for this worker group""" if self._master_addr is None and self._master_port is None: self._master_addr, self._master_port = ray.get( get_master_addr_port.options( scheduling_strategy=PlacementGroupSchedulingStrategy( placement_group=pg, placement_group_bundle_index=bundle_index ), ).remote(master_port_range=master_port_range) ) elif self._master_addr is not None and self._master_port is not None: logger.debug(f"{self._master_addr=} {self._master_port=}") else: raise ValueError( "Both 'master_addr' and 'master_port' must be provided if you intend to manually specify them, " "or neither should be provided to use Ray's default assignment." ) def _init_with_resource_pool( self, resource_pool, ray_cls_with_init, bin_pack, 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: Whether to use strict bin packing for resource allocation detached: Whether workers should be detached """ self.resource_pool = resource_pool strategy = "PACK" if bin_pack: strategy = "STRICT_PACK" pgs = resource_pool.get_placement_groups(strategy=strategy, device_name=self.device_name) world_size = resource_pool.world_size self._world_size = world_size # cia.add_kwarg("_world_size", world_size) rank = -1 local_world_size = resource_pool.store[0] for pg_idx, pg in enumerate(sort_placement_group_by_node_ip(pgs)): assert local_world_size <= pg.bundle_count, f"when generating for {self.name_prefix}, for the " if pg_idx == 0: self._get_master_addr_port(pg, bundle_index=0, master_port_range=self._ray_master_port_range) for local_rank in range(local_world_size): rank += 1 self._create_worker( rank=rank, pg_idx=pg_idx, pg=pg, local_rank=local_rank, resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, worker_env=worker_env, detached=detached, ) def _init_with_subresource_pool(self, resource_pool, ray_cls_with_init, bin_pack, detached, worker_env=None): """Initialize the worker group by creating new workers from a resource pool or sub resource pool. Args: resource_pool: Resource pool for worker allocation ray_cls_with_init: Class with initialization arguments for workers bin_pack: Whether to use strict bin packing for resource allocation detached: Whether workers should be detached """ strategy = "PACK" if bin_pack: strategy = "STRICT_PACK" pgs = resource_pool.get_placement_groups(strategy=strategy, device_name=self.device_name) world_size = resource_pool.world_size self._world_size = world_size rank = -1 local_world_size = resource_pool.store[0] self._get_master_addr_port( pgs[resource_pool.start_bundle_index // local_world_size], bundle_index=resource_pool.start_bundle_index % local_world_size, master_port_range=self._ray_master_port_range, ) for curr_rank in range(resource_pool.start_bundle_index, resource_pool.start_bundle_index + world_size): pg_idx = curr_rank // local_world_size pg = pgs[pg_idx] local_rank = curr_rank % local_world_size assert local_world_size <= pg.bundle_count, f"when generating for {self.name_prefix}, for the " rank += 1 self._create_worker( rank=rank, pg_idx=pg_idx, pg=pg, local_rank=local_rank, resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, worker_env=worker_env, detached=detached, ) def _create_worker(self, rank, pg_idx, pg, local_rank, resource_pool, ray_cls_with_init, worker_env, detached): world_size = resource_pool.world_size use_gpu = resource_pool.use_gpu if self.use_gpu and not use_gpu: raise ValueError("use_gpu is True but resource_pool.use_gpu is False") local_world_size = resource_pool.store[0] num_gpus = 1 / resource_pool.max_colocate_count # we pass in environment variable at option so that Worker can use environment variable to set env_vars = { "WORLD_SIZE": str(world_size), "RANK": str(rank), "WG_PREFIX": self.name_prefix, "WG_BACKEND": "ray", "RAY_LOCAL_WORLD_SIZE": str(local_world_size), "MASTER_ADDR": self._master_addr, "MASTER_PORT": self._master_port, } if worker_env is not None: logging.debug(f"Appending ray class env, origin: {env_vars}, customized env: {worker_env}") conflict_env_vars = set(env_vars.keys()) & set(worker_env.keys()) if len(conflict_env_vars) > 0: logging.error( f"User customized env vars conflict with system env: {conflict_env_vars} " f"Overriding may cause unexpected behavior." ) raise ValueError(f"Cannot override protected system env: {conflict_env_vars}") env_vars.update(worker_env) import re cia_name = type(ray_cls_with_init.cls).__name__ match = re.search(r"ActorClass\(([^)]+)\)", cia_name) # ray.remote(Obj) -> "ActorClass(Obj)" cia_name = match.group(1) if match else cia_name # "ActorClass(Obj)" -> "Obj" name = f"{self.name_prefix}{cia_name}_{pg_idx}:{local_rank}" # e.g. Worker_2:5 if self.profile_steps and self.device_name == "cuda": ray_cls_with_init.update_options( { "runtime_env": { "env_vars": env_vars, "nsight": self.worker_nsight_options, }, "name": name, } ) else: ray_cls_with_init.update_options({"runtime_env": {"env_vars": env_vars}, "name": name}) if detached: ray_cls_with_init.update_options({"lifetime": "detached"}) # create a worker worker = ray_cls_with_init( placement_group=pg, placement_group_bundle_idx=local_rank, use_gpu=self.use_gpu, num_gpus=num_gpus, device_name=self.device_name, ) self._workers.append(worker) self._worker_names.append(name) @property def worker_names(self): return self._worker_names @classmethod def from_detached( cls, name_prefix=None, worker_names=None, worker_handles=None, ray_cls_with_init=None, **kwargs, ): """Create a worker group from existing detached workers. Args: name_prefix: Prefix for worker names worker_names: Names of existing workers to attach to ray_cls_with_init: Class with initialization arguments for workers Returns: A new RayWorkerGroup instance """ worker_group = cls( resource_pool=None, ray_cls_with_init=ray_cls_with_init, name_prefix=name_prefix, worker_names=worker_names, worker_handles=worker_handles, **kwargs, ) return worker_group def spawn(self, prefix_set): """Spawn to a dictionary of worker groups, each with a subset of method with prefix. Args: prefix_set: Set of prefixes to create worker groups for Returns: Dictionary of worker groups keyed by prefix """ if self.fused_worker_used: return self.spawn_fused(prefix_set) def _rebind_actor_methods(worker_group, actor_name): prefix: str = actor_name + "_" for method_name in dir(worker_group): if method_name.startswith(prefix): original_method_name = method_name.removeprefix(prefix) method = getattr(worker_group, method_name) setattr(worker_group, original_method_name, method) new_worker_group_dict = {} for prefix in prefix_set: new_worker_group = self.from_detached( name_prefix=self.name_prefix, worker_names=self._worker_names, worker_handles=self._workers, ray_cls_with_init=self.ray_cls_with_init, profile_steps=self.profile_steps, worker_nsight_options=self.worker_nsight_options, ) _rebind_actor_methods(new_worker_group, prefix) new_worker_group_dict[prefix] = new_worker_group return new_worker_group_dict def spawn_fused(self, prefix_set): """Create a dictionary of worker groups for fused workers. Args: prefix_set: Set of prefixes to create worker groups for Returns: Dictionary of worker groups keyed by prefix """ wg_dict = dict() for key in prefix_set: new_wg = deepcopy(self) new_wg._bind_worker_method(self.ray_cls_with_init.cls.raw_cls_dict[key], func_generator) new_wg.sub_cls_name = key wg_dict[key] = new_wg return wg_dict def fuse(self, prefix_set): """Fuse multiple worker groups into the current worker group. Args: prefix_set: Set of prefixes to fuse into the worker group """ if self.wg_dict is None: self.wg_dict = self.spawn(prefix_set) for role_name, role_wg in self.wg_dict.items(): setattr(self, role_name, role_wg) self.method_names = self._bind_worker_method(self.ray_cls_with_init.cls, func_generator) def _execute_remote_single_worker(self, worker, method_name: str, *args, **kwargs): """Execute a method on a single worker remotely. Args: worker: The worker actor handle method_name: Name of the method to execute *args: Positional arguments for the method **kwargs: Keyword arguments for the method Returns: Remote object reference to the method execution """ if self.fused_worker_used and method_name not in self.method_names: remote_call = getattr(worker, self.fused_worker_execute_fn_name) return remote_call.remote(f"{self.sub_cls_name}_fwmn_{method_name}", *args, **kwargs) # fused worker not used remote_call = getattr(worker, method_name) return remote_call.remote(*args, **kwargs) def execute_rank_zero_sync(self, method_name: str, *args, **kwargs): """Execute a method on rank zero worker synchronously. Args: method_name: Name of the method to execute *args: Positional arguments for the method **kwargs: Keyword arguments for the method Returns: Result of the method execution """ return ray.get(self.execute_rank_zero_async(method_name, *args, **kwargs)) def execute_rank_zero_async(self, method_name: str, *args, **kwargs): """Execute a method on rank zero worker asynchronously. Args: method_name: Name of the method to execute *args: Positional arguments for the method **kwargs: Keyword arguments for the method Returns: Remote object reference to the method execution """ return self._execute_remote_single_worker(self._workers[0], method_name, *args, **kwargs) def execute_rank_zero(self, method_name: str, *args, **kwargs): """Alias for execute_rank_zero_async. Args: method_name: Name of the method to execute *args: Positional arguments for the method **kwargs: Keyword arguments for the method Returns: Remote object reference to the method execution """ return self.execute_rank_zero_async(method_name, *args, **kwargs) def execute_all(self, method_name: str, *args, **kwargs): """Alias for execute_all_async. Args: method_name: Name of the method to execute *args: Positional arguments for the method **kwargs: Keyword arguments for the method Returns: List of remote object references to the method executions """ return self.execute_all_async(method_name, *args, **kwargs) def execute_all_sync(self, method_name: str, *args, **kwargs): """Execute a method on all workers synchronously. Args: method_name: Name of the method to execute *args: Positional arguments for the method **kwargs: Keyword arguments for the method Returns: List of results from all workers """ return ray.get(self.execute_all_async(method_name, *args, **kwargs)) def execute_all_async(self, method_name: str, *args, **kwargs): """Execute a method on all workers asynchronously. Args: method_name: Name of the method to execute *args: Positional arguments for the method **kwargs: Keyword arguments for the method Returns: List of remote object references to the method executions """ # Here, we assume that if all arguments in args and kwargs are lists, # and their lengths match len(self._workers), we'll distribute each # element in these lists to the corresponding worker # print(f"execute_all_async: method {method_name}({args}, {kwargs})") length = len(self._workers) if all(isinstance(arg, list) for arg in args) and all(isinstance(kwarg, list) for kwarg in kwargs.values()): if all(len(arg) == length for arg in args) and all(len(kwarg) == length for kwarg in kwargs.values()): # print(f"splitting args and kwargs into {length} shards") result = [] for i in range(length): sliced_args = tuple(arg[i] for arg in args) sliced_kwargs = {k: v[i] for k, v in kwargs.items()} result.append( self._execute_remote_single_worker(self._workers[i], method_name, *sliced_args, **sliced_kwargs) ) return result return [self._execute_remote_single_worker(worker, method_name, *args, **kwargs) for worker in self._workers] @property def master_address(self): return self._master_addr @property def master_port(self): return self._master_port @property def workers(self): return self._workers @property def world_size(self): return self._world_size """ Utilities that enables creating workers inside the same ray.Actor, with code written in separate ray.Actors. """ # deprecated, switching to FusedWorker def _bind_workers_method_to_parent(cls, key, user_defined_cls): """ Binds the methods of each worker to the WorkerDict. Note that we only bind public methods that are decorated by register """ for method_name in dir(user_defined_cls): try: method = getattr(user_defined_cls, method_name) assert callable(method), f"{method_name} in {user_defined_cls} is not callable" except Exception: # if it is a property, it will fail because Class doesn't have instance property continue if hasattr(method, MAGIC_ATTR): def generate_function(name, key=key): def func(self, *args, **kwargs): # dispatch to the actual worker return getattr(self.worker_dict[key], name)(*args, **kwargs) async def async_func(self, *args, **kwargs): # dispatch to the actual worker return await getattr(self.worker_dict[key], name)(*args, **kwargs) wrapper = async_func if inspect.iscoroutinefunction(method) else func # noqa: B023 return wrapper func = generate_function(method_name) # pass MAGIC_ATTR for outer worker group attrs = getattr(method, MAGIC_ATTR) setattr(func, MAGIC_ATTR, attrs) try: # bind direct rollout method to class without prefix if attrs["dispatch_mode"] == Dispatch.DIRECT_ROLLOUT_METHOD and "rollout" in key: assert not hasattr(cls, method_name), ( f"conflict direct rollout method {method_name} with role {key}" ) setattr(cls, method_name, func) print(f"bind role {key} method {method_name} to class {cls}") else: method_name_with_prefix = key + "_" + method_name setattr(cls, method_name_with_prefix, func) except Exception as e: raise ValueError(f"Fail to set method_name {method_name}") from e def _unwrap_ray_remote(cls): if hasattr(cls, "__ray_actor_class__"): cls = cls.__ray_actor_class__ return cls def _determine_fsdp_megatron_base_class(mros: list): """ - megatron: base class should be MegatronWorker - fsdp: base class should be Worker """ for cls in mros[0]: if cls.__name__ == "MegatronWorker": return cls if cls.__name__ == "Worker": return cls raise ValueError(f"Cannot determine base class for {mros}") # deprecated, switching to FusedWorker def create_colocated_worker_cls(class_dict: dict[str, RayClassWithInitArgs]): """ This function should return a class instance that delegates the calls to every cls in cls_dict """ cls_dict = {} init_args_dict = {} worker_cls = _determine_fsdp_megatron_base_class( [cls.cls.__ray_actor_class__.__mro__ for cls in class_dict.values()] ) assert issubclass(worker_cls, Worker), f"worker_cls {worker_cls} should be a subclass of Worker" print(f"colocated worker base class {worker_cls}") for key, cls in class_dict.items(): cls_dict[key] = cls.cls init_args_dict[key] = {"args": cls.args, "kwargs": cls.kwargs} assert cls_dict.keys() == init_args_dict.keys() # TODO: create a class with customizable name class WorkerDict(worker_cls): def __init__(self): super().__init__() self.worker_dict = {} for key, user_defined_cls in cls_dict.items(): user_defined_cls = _unwrap_ray_remote(user_defined_cls) # directly instantiate the class without remote # in worker class, e.g. <verl.single_controller.base.worker.Worker> # when DISABLE_WORKER_INIT == 1 it will return immediately with temp_env_var("DISABLE_WORKER_INIT", "1"): self.worker_dict[key] = user_defined_cls( *init_args_dict[key].get("args", ()), **init_args_dict[key].get("kwargs", {}) ) # now monkey-patch the methods from inner class to WorkerDict for key, user_defined_cls in cls_dict.items(): user_defined_cls = _unwrap_ray_remote(user_defined_cls) _bind_workers_method_to_parent(WorkerDict, key, user_defined_cls) remote_cls = ray.remote(WorkerDict) remote_cls = RayClassWithInitArgs(cls=remote_cls) return remote_cls FusedWorkerCLSName = "FusedWorker" def create_colocated_worker_raw_cls(class_dict: dict[str, RayClassWithInitArgs]): """ This function returns a FusedWorker class. `FusedWorker.{class_name}` -> FusedClass Use `class_name` as a param to directly access the underlying class. `FusedWorker._fuw_execute("{class_name}_fwmn_{method_name}", *args, **kwargs)` First param must be "{class_name}_fwmn_{method_name}" in order to access `method_name` of underlying class `{class_name}`. `FusedWorker.fused_worker_dict` -> {"class_name": FusedClass} Stores all underlying classes. `FusedClass.fused_worker_dict` -> {"class_name": FusedClass} The same as `FusedWorker.fused_worker_dict`, enables underlying class to access other underlying classes. """ raw_cls_dict = {cls_name: _unwrap_ray_remote(cia.cls) for cls_name, cia in class_dict.items()} init_args_dict = {cls_name: cia.args for cls_name, cia in class_dict.items()} init_kwargs_dict = {cls_name: cia.kwargs for cls_name, cia in class_dict.items()} cls_names = list(class_dict.keys()) # FusedWorker_Actor_Critic class_name_renamed = "_".join([FusedWorkerCLSName] + cls_names) class FusedWorker(Worker): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cls_names = cls_names self.raw_cls_dict = raw_cls_dict self.init_args_dict = init_args_dict self.init_kwargs_dict = init_kwargs_dict for cls_name, udc, ud_args, ud_kwargs in zip( self.cls_names, self.raw_cls_dict.values(), self.init_args_dict.values(), self.init_kwargs_dict.values(), strict=True, ): with temp_env_var("DISABLE_WORKER_INIT", "1"): udc._get_ray_actor_cls_name = lambda x, name_renamed=class_name_renamed: name_renamed udc._get_ray_method_prefix = lambda x, name_prefixed=cls_name: f"{name_prefixed}_" # cls_name = "actor", "critic", udc = ActorWorker, CriticWorker self.fused_worker_dict[cls_name] = udc(*ud_args, **ud_kwargs) setattr(self, cls_name, self.fused_worker_dict[cls_name]) # injecting fused_worker to each sub worker so they can be aware of existence of each other for _, worker in self.fused_worker_dict.items(): setattr(worker, Worker.fused_worker_attr_name, self.fused_worker_dict) def _fuw_execute(self, method_name: str, *args, **kwargs): # for fused_worker, method_name is in a form of "{cls_name}_fwmn_{method_name}" # where fwmn stands "fused worker method name" names = method_name.split("_fwmn_") cls_name = names[0] method_name = names[1] assert cls_name in self.fused_worker_dict, ( f"calling {cls_name}'s {method_name}, but {cls_name} not in fused_worker_dict" ) udc_method = getattr(self.fused_worker_dict[cls_name], method_name) return udc_method(*args, **kwargs) renamed_fused_worker_cls = type(class_name_renamed, (FusedWorker,), {}) renamed_fused_worker_cls.is_fused_worker = True renamed_fused_worker_cls.raw_cls_dict = raw_cls_dict return renamed_fused_worker_cls def create_colocated_worker_cls_fused(class_dict: dict[str, RayClassWithInitArgs]): """ This function returns a RayClassWithInitArgs instance of FusedWorker, which is an replacement of `create_colocated_worker_cls`. WorkerGroup constructed using this class will be a colocated WorkerGroup, which will be referenced as `ColocateWorkerGroup` below. `ColocateWorkerGroup.spawn(prefix_set)` returns a dict of WorkerGroup {"class_name": WorkerGroup}, WorkerGroup in this dict will have methods of underlying class `class_name` attached. `ColocateWorkerGroup.fuse(prefix_set)` After executing this function, `ColocateWorkerGroup.{class_name}` will return WorkerGroup with methods of underlying class `class_name` attached. """ raw_colocated_worker_cls = create_colocated_worker_raw_cls(class_dict) remote_cls = ray.remote(raw_colocated_worker_cls) cia = RayClassWithInitArgs(cls=remote_cls) cia.fused_worker_used = True return cia
verl__single_controller__ray__base.py
# official torch 2.6.0 set_model_state_dict API leads to OOM # this is a copy of torch/distributed/checkpoint from torch 2.7.0 # From PyTorch: # Copyright (c) 2016- Facebook, Inc (Adam Paszke) # Copyright (c) 2014- Facebook, Inc (Soumith Chintala) # Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) # Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) # Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) # Copyright (c) 2011-2013 NYU (Clement Farabet) # Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) # Copyright (c) 2006 Idiap Research Institute (Samy Bengio) # Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) # From Caffe2: # Copyright (c) 2016-present, Facebook Inc. All rights reserved. # All contributions by Facebook: # Copyright (c) 2016 Facebook Inc. # All contributions by Google: # Copyright (c) 2015 Google Inc. # All rights reserved. # All contributions by Yangqing Jia: # Copyright (c) 2015 Yangqing Jia # All rights reserved. # All contributions by Kakao Brain: # Copyright 2019-2020 Kakao Brain # All contributions by Cruise LLC: # Copyright (c) 2022 Cruise LLC. # All rights reserved. # All contributions by Tri Dao: # Copyright (c) 2024 Tri Dao. # All rights reserved. # All contributions by Arm: # Copyright (c) 2021, 2023-2024 Arm Limited and/or its affiliates # All contributions from Caffe: # Copyright(c) 2013, 2014, 2015, the respective contributors # All rights reserved. # All other contributions: # Copyright(c) 2015, 2016 the respective contributors # All rights reserved. # Caffe2 uses a copyright model similar to Caffe: each contributor holds # copyright over their contributions to Caffe2. The project versioning records # all such contribution and copyright details. If a contributor wants to further # mark their specific copyright on a particular contribution, they should # indicate their copyright solely in the commit message of the change when it is # committed. # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America # and IDIAP Research Institute nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ruff: noqa: B028, UP038, UP007, E721, E501 # mypy: allow-untyped-defs import copy import io import math import weakref from collections.abc import Mapping, MutableMapping from typing import TYPE_CHECKING, Any, Callable, NamedTuple, Optional, Union, cast import torch import torch.distributed as dist import torch.nn.functional as F from torch.distributed._functional_collectives import AsyncCollectiveTensor if dist.is_available() or TYPE_CHECKING: from torch.distributed import distributed_c10d from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.tensor import DTensor, Replicate, distribute_tensor from torch.distributed.tensor._utils import compute_local_shape_and_global_offset def _identity_func( obj: torch.Tensor, pg: Optional[dist.ProcessGroup], device: Optional[torch.device], companion_obj: Any, ) -> torch.Tensor: return obj def _all_gather_sharded_tensor( sharded_tensor: "ShardedTensor", pg: Optional[dist.ProcessGroup] = None, device: Optional[torch.device] = None, ) -> torch.Tensor: if pg is None: pg = distributed_c10d._get_default_group() world_size = dist.get_world_size(pg) shards = sharded_tensor.local_shards() dim_0_size = sharded_tensor.size()[0] # type: ignore[index] tensor_numel = sharded_tensor.size().numel() # type: ignore[union-attr] chunk_size = math.ceil(dim_0_size / world_size) * tensor_numel // dim_0_size pg_device = distributed_c10d._get_pg_default_device(pg) if device is None else device if shards: local_tensor = shards[0].tensor.flatten() if local_tensor.device.type != pg_device.type: local_tensor = local_tensor.to(pg_device) num_padding = chunk_size - local_tensor.numel() if num_padding > 0: local_tensor = F.pad(local_tensor, [0, num_padding]) else: local_tensor = torch.zeros(chunk_size, dtype=sharded_tensor.dtype, device=pg_device) tensor = torch.empty( chunk_size * world_size, dtype=local_tensor.dtype, device=pg_device, ) dist.all_gather_into_tensor(tensor, local_tensor, group=pg) tensor = tensor.narrow(0, 0, tensor_numel).reshape(sharded_tensor.size()) return tensor class CompanionMismatch(Exception): pass def _iterate_state_dict( iter_object: Any, sharded_tensor_func: Callable, dtensor_func: Callable, tensor_func: Callable, *, pg: Optional[dist.ProcessGroup] = None, device: Optional[torch.device] = None, cpu_offload: bool = False, companion_obj: Any = None, ranks_only: tuple[int, ...] = (), type_check: bool = True, non_blocking: bool = True, ) -> dict[str, Any]: """Iterate through the state dict, applying the given functions to each tensor type. Args: iter_object (Any): the target state_dict. sharded_tensor_func (Callable): the function to apply to ShardedTensor dtensor_func (Callable): the function to apply to DTensor tensor_func (Callable): the function to apply to Tensor pg (Optional[dist.ProcessGroup]): process group passed to tensor functions device (Optional[torch.device]): device passed to tensor functions cpu_offload (bool): whether to offload the tensors to CPU memory. This option is ignored if a companion_obj is supplied. companion_obj (Any): A companion object to the state dict. If this object is supplied, we attempt to copy the tensor to the companion object. ranks_only (Tuple[int, ...]): if this tuple is empty, all ranks will have the same state_dicts. Otherwise only ranks that in ``ranks_only`` have the same state_dicts. Other ranks will get empty state_dicts. type_check (bool): check if the instance data type is a supported type that can be saved by DCP. The current supported data types are torch.Tensor, DTensor, int, float, str, list, dict, None. non_blocking (bool): whether to use non-blocking copy when copying to the companion object. """ # TODO: should we use pytree? cpu_device = torch.device("cpu") if isinstance(iter_object, ShardedTensor): ret = sharded_tensor_func(iter_object, pg, device, companion_obj) elif isinstance(iter_object, DTensor): ret = dtensor_func(iter_object, pg, device, companion_obj) elif isinstance(iter_object, torch.Tensor): ret = tensor_func(iter_object, pg, device, companion_obj) elif isinstance(iter_object, (int, float, str, bytes, io.BytesIO)) or iter_object is None: ret = iter_object elif isinstance(iter_object, dict): if companion_obj is not None and ( not isinstance(companion_obj, dict) or set(companion_obj.keys()) != set(iter_object.keys()) ): msg = "" if isinstance(companion_obj, dict) else f"{set(companion_obj.keys())=} {set(iter_object.keys())=}" raise CompanionMismatch(msg) ret = { key: _iterate_state_dict( value, sharded_tensor_func, dtensor_func, tensor_func, pg=pg, device=device, cpu_offload=cpu_offload, companion_obj=companion_obj[key] if companion_obj is not None else None, ranks_only=ranks_only, type_check=type_check, non_blocking=non_blocking, ) for key, value in iter_object.items() } elif isinstance(iter_object, (list, tuple)): if companion_obj is not None and ( not isinstance(companion_obj, (list, tuple)) or len(companion_obj) != len(iter_object) ): raise CompanionMismatch ret = [ _iterate_state_dict( v, sharded_tensor_func, dtensor_func, tensor_func, pg=pg, device=device, cpu_offload=cpu_offload, companion_obj=companion_obj[idx] if companion_obj is not None else None, ranks_only=ranks_only, type_check=type_check, non_blocking=non_blocking, ) for idx, v in enumerate(iter_object) ] if isinstance(iter_object, tuple): ret = tuple(ret) elif not type_check: ret = copy.deepcopy(iter_object) else: raise ValueError(f"Unexpected value type {type(iter_object)}") if not ranks_only or dist.get_rank(pg) in ranks_only: if isinstance(ret, torch.Tensor): if cpu_offload and companion_obj is None: ret = ret.to(cpu_device) if companion_obj is not None: if isinstance(companion_obj, DTensor): assert isinstance(ret, DTensor) companion_obj._local_tensor.copy_(ret._local_tensor, non_blocking=non_blocking) else: companion_obj.copy_(ret, non_blocking=non_blocking) ret = companion_obj else: ret = {} if isinstance(ret, dict) else None return ret def _gather_state_dict( state_dict: dict[str, Any], *, pg: Optional[dist.ProcessGroup] = None, device: Optional[torch.device] = None, cpu_offload: bool = False, ranks_only: tuple[int, ...] = (), type_check: bool = True, ) -> dict[str, Any]: """ Given a state_dict, this API gathers all the ShardedTensors or DTensors in the state_dict. Args: state_dict (Dict[str, Any]): the target sharded state_dict. pg (Optional[dist.ProcessGroup]): the process group that is used to gather ShardedTensor. Note that gathering a DTensor will use the DeviceMesh. So this argument will be ignored when gathering a DTensor. device: (Optional[torch.device]): the device that is used to perform allgather for ShardedTensor. Note that gathering a DTensor will use the DeviceMesh. So this argument will be ignored when gathering a DTensor. cpu_offload (bool): whether to offload the tensors to CPU memory. The default value is False. ranks_only: (Tuple[int, ...]): if this tuple is empty, all ranks will have the same state_dicts. Otherwise only ranks that in ``ranks_only`` have the same state_dicts. Other ranks will get empty state_dicts. type_check: (bool): check if the instance data type is a supported type that can be saved by DCP. The current supported data types are torch.Tensor, DTensor, int, float, str, list, dict, None. Returns: The gathered state dictionary. """ def sharded_tensor_func(value, pg, device, companion_obj): # ShardedTensor does not seem to record the original device type. # So if the tensor is moved to CPU, we won't know the original type. # As a result, we have to rely on the user to tell us the correct one. cpu_device = torch.device("cpu") output_tensor = _all_gather_sharded_tensor(value, pg, device) local_shard_device = value.local_shards()[0].tensor.device if value.local_shards() else cpu_device if output_tensor.device != local_shard_device: value = output_tensor.to(local_shard_device) else: value = output_tensor return value def dtensor_func(value, pg, device, companion_obj): if value.device != value.device_mesh.device_type: value = value.to(value.device_mesh.device_type) # FSDP all_gather: [Shard(0)] -> [Replicate()] # HSDP all_gather: [Replicate(), Shard(0)] -> [Replicate(), Replicate()] # 2D FSDP + TP all_gather: # - [Shard(0), Shard(n)] -> [Replicate(), Replicate()] # - [Shard(0), Replicate()] -> [Replicate(), Replicate()] placements = [Replicate() for _ in value.placements] value = value.redistribute( device_mesh=value.device_mesh, placements=placements, ) # Call `wait()` to force the tensor to be synchronous with respect # to the main stream. # See the discussion in https://github.com/pytorch/pytorch/pull/117799. value = value.to_local() if isinstance(value, AsyncCollectiveTensor): value = value.wait() return value return _iterate_state_dict( state_dict, sharded_tensor_func, dtensor_func, _identity_func, pg=pg, device=device, cpu_offload=cpu_offload, ranks_only=ranks_only, type_check=type_check, ) def _offload_state_dict_to_cpu( state_dict: dict[str, Any], *, ranks_only: tuple[int, ...] = (), type_check: bool = True, ) -> dict[str, Any]: """ Given a state_dict, this API offload all the tensors to CPU memory. Args: state_dict (Dict[str, Any]): the target state_dict. pg (Optional[dist.ProcessGroup]): the process group that is used to gather ShardedTensor. Note that gathering a DTensor will use the DeviceMesh. So this argument will be ignored when gathering a DTensor. ranks_only: (Tuple[int, ...]): if this tuple is empty, all ranks will have the same state_dicts. Otherwise only ranks that in ``ranks_only`` have the same state_dicts. Other ranks will get empty state_dicts. type_check: (bool): check if the instance data type is a supported type that can be saved by DCP. The current supported data types are torch.Tensor, DTensor, int, float, str, list, dict, None. Returns: The gathered state dictionary. """ ret = _iterate_state_dict( state_dict, _identity_func, _identity_func, _identity_func, pg=None, device=None, cpu_offload=True, ranks_only=ranks_only, type_check=type_check, ) return ret @torch.no_grad() def _copy_state_dict( state_dict: dict[str, Any], copy_state_dict: dict[str, Any], non_blocking: bool = False, type_check: bool = True, ) -> dict[str, Any]: """ Copies all tensors in a given state dict into a different state_dict with the same structure. Additionally, a copied state dict with the same value references is returned. Editing the keys on this state dict will not affect the passed in copy_state_dict (but the value references are the same). .. warning:: It is expected by this function that state_dict and copy_state_dict share the same structure and data types. .. warning:: The current supported data types are torch.Tensor, DTensor, int, float, str, list, dict, None. Args: state_dict (Dict[str, Any]): the target state_dict. copy_state_dict (Dict[str, Any]): The state dict we are copying into. This state_dict must have exactly the same structure as the source `state_dict`. non_blocking: (bool): Whether copy ops should be performed asynchronously type_check (bool): check if the instance data type is a supported type that can be saved by DCP. The current supported data types are torch.Tensor, DTensor, int, float, str, list, dict, None. Returns: State Dict copy """ return _iterate_state_dict( state_dict, _identity_func, _identity_func, _identity_func, pg=None, device=None, cpu_offload=False, ranks_only=(), companion_obj=copy_state_dict, type_check=type_check, non_blocking=non_blocking, ) @torch.no_grad() def _create_cpu_state_dict( state_dict: dict[str, Any], pin_memory: bool = False, share_memory: bool = False ) -> dict[str, Any]: """ Given a state_dict, create another state_dict with the same structure and elements. However, all tensors in the returned state_dict are new tensors on CPU. These tensors can be placed on pin_memory or share_memory based on the provided arguments. .. warning:: Setting both `pin_memory` and `share_memory` to True significantly increases the latency of this method because of the nuances which require us to register memory as pinned directly as opposed to relying on the pin_memory cache allocator. This option should only be used for long lived tensors which are required to be shared. This is not the case as long as at least one of `pin_memory` or `share_memory` is set to False. """ def tensor_func( obj: torch.Tensor, pg: Optional[dist.ProcessGroup], device: Optional[torch.device], _: Any, ) -> torch.Tensor: if len(obj.size()) == 0: return torch.tensor(0, dtype=obj.dtype) if share_memory: t = torch.empty(*tuple(obj.size()), dtype=obj.dtype) t = t.share_memory_() if pin_memory: def unpin_memory(t): succ = int(torch.cuda.cudart().cudaHostUnregister(t.data_ptr())) assert succ == 0, f"Unpinning shared memory failed with error-code: {succ}" weakref.finalize(t, unpin_memory, t) succ = int( torch.cuda.cudart().cudaHostRegister( t.data_ptr(), t.numel() * t.element_size(), 1, # lines up with 'cudaHostRegisterPortable' ) ) assert succ == 0, f"Pinning shared memory failed with error-code: {succ}" return t elif pin_memory: return torch.empty(*tuple(obj.size()), dtype=obj.dtype).pin_memory() else: return torch.empty(*tuple(obj.size()), dtype=obj.dtype) def dtensor_func( obj: DTensor, pg: Optional[dist.ProcessGroup], device: Optional[torch.device], _: Any, ) -> DTensor: if len(obj.size()) == 0: return obj if obj.device != torch.device("cpu"): ret = cast(DTensor, obj.to(device="cpu")) else: ret = copy.deepcopy(obj) ret._local_tensor = tensor_func(ret._local_tensor, pg, device, None) return ret ret = _iterate_state_dict( state_dict, _identity_func, dtensor_func, tensor_func, pg=None, device=None, cpu_offload=False, ranks_only=(), type_check=False, ) return ret def _check_state_dict_similarity( state_dict: dict[str, Any], compared_state_dict: dict[str, Any], ) -> bool: """ Given two state_dicts, check if the structures are the same. And if a [key, tensor] pair exist in one state_dict there must be the a corresponding pait, [key, other_tensor], in the other state_dict, where tensor and other_tensor have the same size and dtype. Return the check result. """ def tensor_func( obj: torch.Tensor, pg: Optional[dist.ProcessGroup], device: Optional[torch.device], companion_obj: Any, ) -> torch.Tensor: if companion_obj.dtype != obj.dtype or companion_obj.size() != obj.size(): raise CompanionMismatch return obj try: _iterate_state_dict( state_dict, _identity_func, _identity_func, tensor_func, pg=None, device=None, cpu_offload=False, ranks_only=(), companion_obj=compared_state_dict, type_check=False, ) except CompanionMismatch: return False return True class _TensorInfo(NamedTuple): size: torch.Size dtype: torch.dtype def _broadcast_tensors( full_state_dict: dict[str, Any], local_state_dict: dict[str, Any], keys: list[str], device: torch.device, pg: Optional[dist.ProcessGroup] = None, ) -> None: tensors = [] for key in keys: if dist.get_rank() == 0: full_state = full_state_dict[key] assert isinstance(full_state, torch.Tensor) full_tensor = full_state.detach().to(device) else: tensor_info = full_state_dict[key] full_tensor = torch.empty( size=tensor_info.size, device=device, dtype=tensor_info.dtype, ) tensors.append(full_tensor) local_state = local_state_dict.get(key, None) if local_state is None: continue elif isinstance(local_state, DTensor): local_state_dict[key] = (local_state, full_tensor) else: local_state_dict[key] = full_tensor if pg is None: pg = dist.distributed_c10d._get_default_group() if len(tensors) > 1: dist._broadcast_coalesced(pg, tensors, 500, 0) else: dist.broadcast(tensors[0], src=0, group=pg) _distribute_tensors(local_state_dict, keys, device, pg) def _distribute_tensors( local_state_dict: dict[str, Any], keys: list[str], device: torch.device, pg: Optional[dist.ProcessGroup] = None, ) -> None: if pg is None: pg = dist.distributed_c10d._get_default_group() for key in keys: _local_state = local_state_dict.get(key, None) if _local_state is None or torch.is_tensor(_local_state): continue local_state = _local_state[0] full_tensor = _local_state[1] shape, offset = compute_local_shape_and_global_offset( full_tensor.shape, local_state.device_mesh, local_state.placements ) slices = [ slice(cur_offset, cur_offset + cur_shape) for cur_shape, cur_offset in zip(shape, offset, strict=False) ] if local_state.is_meta: # Use .clone() here rather than view to clone and return only the sliced portion, minimizing memory access and cost. local_tensor = full_tensor[slices].detach().clone() # TODO: currently, we cannot handle strided sharding if the dp dimension is not even. For example, # one of the case that is not yet supported is when placements = (Shard(0), _StridedShard(0, sf=2)). ret = DTensor.from_local( local_tensor, local_state.device_mesh, local_state.placements, shape=local_state.shape, stride=local_state.stride(), ) else: ret = local_state # Copy full_tensor[slices] into local_state.to_local() to reduce memory footprint. ret.to_local().copy_(full_tensor[slices]) local_state_dict[key] = ret def _broadcast_state_dict( full_state_dict: dict[str, Any], local_state_dict: dict[str, Any], device: torch.device, pg: Optional[dist.ProcessGroup] = None, strict: bool = False, cpu_offload: bool = False, ) -> None: # Broadcast from rank0's `full_state_dict` to all ranks' `local_state_dict`. # If strict is True, any keys in `local_state_dict` but not in `full_state_dict` # will be removed from `local_state_dict`. ret = {} if dist.get_rank() == 0: for key, value in full_state_dict.items(): if not torch.is_tensor(value): ret[key] = value elif value.dim() == 0: ret[key] = value.cpu() else: ret[key] = _TensorInfo(value.size(), value.dtype) broadcast_list = [ret] dist.broadcast_object_list(broadcast_list, src=0, group=pg) ret = broadcast_list[0] # Gather values keys = [] local_state_dict_keys = set(local_state_dict.keys()) global_keys = set() for key, value in ret.items(): global_keys.add(key) if not isinstance(value, _TensorInfo): if key in local_state_dict: local_state_dict[key] = value continue if dist.get_rank() == 0: ret[key] = full_state_dict[key] keys.append(key) # Broadcast every tensor to avoid OOM for now. if len(keys) >= 1: _broadcast_tensors(ret, local_state_dict, keys, device, pg) if cpu_offload: for key in keys: local_state_dict[key] = local_state_dict[key].cpu() keys.clear() if strict: if missing_keys := (local_state_dict_keys - global_keys): for key in missing_keys: local_state_dict.pop(key) if keys: _broadcast_tensors(ret, local_state_dict, keys, device, pg) if cpu_offload: for key in keys: local_state_dict[key] = local_state_dict[key].cpu() def _distribute_state_dict( full_state_dict: dict[str, Any], local_state_dict: dict[str, Any], device: torch.device, pg: Optional[dist.ProcessGroup] = None, ) -> None: # Full_state_dict = True, broadcast_from_rank0 = False here. Each rank has # full_state_dict. Skip the broadcast in ``_broadcast_state_dict`` and # distribute tensors in each rank for key, value in full_state_dict.items(): if key not in full_state_dict: continue if not torch.is_tensor(value): local_state_dict[key] = value elif value.dim() == 0: local_state_dict[key] = value.cpu() else: assert isinstance(value, torch.Tensor) local_state = local_state_dict.get(key, None) if local_state is None: continue elif isinstance(local_state, DTensor): local_state_dict[key] = distribute_tensor( value.detach().to(device), local_state.device_mesh, local_state.placements, ) else: local_state_dict[key] = value.detach().to(device) # These APIs are from torch.distributed.checkpoint. # TODO: We should consolidate the code here as some not all modules can depend on # DCP. PATH_ITEM = Union[str, int] OBJ_PATH = tuple[PATH_ITEM, ...] FLATTEN_MAPPING = dict[str, OBJ_PATH] STATE_DICT_TYPE = dict[str, Any] CONTAINER_TYPE = MutableMapping[PATH_ITEM, Any] def _traverse_state_dict( state_dict: STATE_DICT_TYPE, visitor: Callable[[OBJ_PATH, Any], None], ) -> None: """ Invoke ``visitor`` for each value recursively in ``state_dict``. Mapping, list, and tuple will be flattened and other value types are treated as the terminal values and will invoke ``visitor``. """ def _traverse_obj(path: OBJ_PATH, value: Any) -> None: if isinstance(value, Mapping): for k, v in value.items(): _traverse_obj(path + (str(k),), v) elif isinstance(value, (list, tuple)): for i, v in enumerate(value): _traverse_obj(path + (i,), v) else: visitor(path, value) for key, value in state_dict.items(): _traverse_obj((str(key),), value) def _flatten_state_dict( state_dict: STATE_DICT_TYPE, ) -> tuple[STATE_DICT_TYPE, FLATTEN_MAPPING]: """ Flatten ``state_dict`` made of nested dicts and lists into a top level dictionary. Use ``unflatten_state_dict`` to revert this process. Returns: A tuple with the flatten state_dict and a mapping from original to new state_dict. N.B. The new keys are derived from the object paths, joined by dot. For example: ``{ 'a': {'b':...}}`` results in the key `a.b`. """ flattened: STATE_DICT_TYPE = {} mappings: FLATTEN_MAPPING = {} def flat_copy(path: OBJ_PATH, value: Any) -> None: new_fqn = ".".join(map(str, path)) if new_fqn in flattened: raise ValueError(f"duplicated flatten key {new_fqn}") flattened[new_fqn] = value mappings[new_fqn] = path _traverse_state_dict(state_dict, flat_copy) return flattened, mappings def _set_element(root_dict: STATE_DICT_TYPE, path: OBJ_PATH, value: Any) -> None: """Set ``value`` in ``root_dict`` along the ``path`` object path.""" cur_container = cast(CONTAINER_TYPE, root_dict) def extend_list(lst: list[Any], idx: int) -> None: while len(lst) <= idx: lst.append(None) for i in range(1, len(path)): prev_key = path[i - 1] key = path[i] def_val: CONTAINER_TYPE | list[Any] = {} if type(key) == str else [] if isinstance(cur_container, Mapping): cur_container = cast(CONTAINER_TYPE, cur_container.setdefault(prev_key, def_val)) else: extend_list(cur_container, prev_key) if cur_container[prev_key] is None: cur_container[prev_key] = def_val cur_container = cur_container[prev_key] key = path[-1] if type(key) == int: extend_list(cast(list[Any], cur_container), key) cur_container[key] = value def _unflatten_state_dict(state_dict: STATE_DICT_TYPE, mapping: FLATTEN_MAPPING) -> STATE_DICT_TYPE: """Restore the original nested state_dict according to ``mapping`` and the flattened ``state_dict``.""" nested: STATE_DICT_TYPE = {} for key, value in state_dict.items(): _set_element(nested, mapping[key], value) return nested
verl__third_party__torch__distributed___state_dict_utils.py
# official torch 2.6.0 set_model_state_dict API leads to OOM # this is a copy of torch/distributed/checkpoint from torch 2.7.0 # From PyTorch: # Copyright (c) 2016- Facebook, Inc (Adam Paszke) # Copyright (c) 2014- Facebook, Inc (Soumith Chintala) # Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) # Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) # Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) # Copyright (c) 2011-2013 NYU (Clement Farabet) # Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) # Copyright (c) 2006 Idiap Research Institute (Samy Bengio) # Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) # From Caffe2: # Copyright (c) 2016-present, Facebook Inc. All rights reserved. # All contributions by Facebook: # Copyright (c) 2016 Facebook Inc. # All contributions by Google: # Copyright (c) 2015 Google Inc. # All rights reserved. # All contributions by Yangqing Jia: # Copyright (c) 2015 Yangqing Jia # All rights reserved. # All contributions by Kakao Brain: # Copyright 2019-2020 Kakao Brain # All contributions by Cruise LLC: # Copyright (c) 2022 Cruise LLC. # All rights reserved. # All contributions by Tri Dao: # Copyright (c) 2024 Tri Dao. # All rights reserved. # All contributions by Arm: # Copyright (c) 2021, 2023-2024 Arm Limited and/or its affiliates # All contributions from Caffe: # Copyright(c) 2013, 2014, 2015, the respective contributors # All rights reserved. # All other contributions: # Copyright(c) 2015, 2016 the respective contributors # All rights reserved. # Caffe2 uses a copyright model similar to Caffe: each contributor holds # copyright over their contributions to Caffe2. The project versioning records # all such contribution and copyright details. If a contributor wants to further # mark their specific copyright on a particular contribution, they should # indicate their copyright solely in the commit message of the change when it is # committed. # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America # and IDIAP Research Institute nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ruff: noqa: B028, UP038, UP007, E721 # mypy: allow-untyped-defs import contextlib import functools import gc import warnings from collections.abc import Generator, Iterable from dataclasses import asdict, dataclass, field from itertools import chain from typing import Any, Callable, Optional, Union, cast, no_type_check import torch import torch.distributed as dist import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_PREFIX, ) from torch.distributed.fsdp import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateDictConfig, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictConfig, StateDictType, ) from torch.distributed.fsdp import ( FullyShardedDataParallel as FSDP, ) from torch.distributed.fsdp._common_utils import ( FSDP_WRAPPED_MODULE, _get_module_fsdp_state_if_fully_sharded_module, ) from torch.distributed.tensor import DTensor from torch.nn.modules.module import _IncompatibleKeys from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils._pytree import tree_map_only from verl.third_party.torch.distributed._state_dict_utils import ( _broadcast_state_dict, _distribute_state_dict, _flatten_state_dict, _gather_state_dict, _offload_state_dict_to_cpu, _unflatten_state_dict, ) __all__ = [ "FQNS_T", "PrimitiveType", "ValueType", "DictValueType", "ListDictValueType", "OptimizerStateType", "StateDictOptions", "get_model_state_dict", "get_optimizer_state_dict", "get_state_dict", "set_model_state_dict", "set_optimizer_state_dict", "set_state_dict", ] _FLAT_PARAM = "_flat_param" _PG = "param_groups" _PARAMS = "params" _STATE = "state" FQNS_T = set[str] PrimitiveType = Union[DTensor, ShardedTensor, torch.Tensor, int, float, str] ValueType = Union[PrimitiveType, list[PrimitiveType], tuple[PrimitiveType], dict[str, "ValueType"]] DictValueType = dict[str, ValueType] ListDictValueType = list[DictValueType] OptimizerStateType = dict[str, DictValueType | ListDictValueType] _patched_state_dict: set[Callable] = set() @contextlib.contextmanager def _gc_context(): is_enabled = gc.isenabled() gc.disable() try: yield finally: if is_enabled: gc.enable() @dataclass class StateDictOptions: """ This dataclass specifies how get_state_dict/set_state_dict will work. - ``full_state_dict``: if this is set to True, all the tensors in the returned state_dict will be gathered. No ShardedTensor and DTensor will be in the returned state_dict. - ``cpu_offload``: offload all the tensors to cpu. To prevent CPU OOM, if ``full_state_dict`` is also true, then only the rank0 will get the state_dict and all other ranks will get empty state_dict. - ``ignore_frozen_params``: if the value is True, the returned state_dict won't contain any frozen parameters -- the ``requires_grad`` is False. The default value is False. - ``keep_submodule_prefixes`` (deprecated): when ``submodules`` is not None, this option indicates whether to keep the submodule prefixes from the state_dict keys. or example, if the submodule is ``module.pretrain`` and the full FQN of the parameter is ``pretrain.layer1.weight`` of the param. When this option is True, the parameter's key in the returned state_dict will be ``pretrain.layer1.weight``. If the options is False, the key will be ``layer1.weight``. Note that if ``keep_submodule_prefixes`` is False, there may be conflicted FQNs, hence there should be only one submodule in ``submodules``. - ``strict``: the ``strict`` option when ``set_state_dict`` calls model.load_state_dict(). - ``broadcast_from_rank0``: when the option is True, rank0 should receive a full state_dict and will broadcast the tensors in the state_dict/ optim_state_dict one by one to other ranks. Other ranks will receive the tensors and shard according to the local shards in the model and optimizer. ``full_state_dict`` must be set to True when using this option. This option currently only supports DTensor, not the legacy ShardedTensor. """ full_state_dict: bool = False cpu_offload: bool = False ignore_frozen_params: bool = False keep_submodule_prefixes: bool = True strict: bool = True broadcast_from_rank0: bool = False flatten_optimizer_state_dict: bool = False dsd_fqn_modifiers: str = "_fqn_modifiers" @dataclass class _StateDictInfo(StateDictOptions): fqn_param_mapping: dict[ str | torch.Tensor, FQNS_T | torch.Tensor, ] = field(default_factory=dict) shared_params_mapping: dict[ str | torch.Tensor, FQNS_T | torch.Tensor, ] = field(default_factory=dict) submodule_prefixes: set[str] = field(default_factory=set) handle_model: bool = True handle_optim: bool = True fsdp_context: Callable = contextlib.nullcontext fsdp_modules: list[nn.Module] = field(default_factory=list) @functools.cache def _get_fqns( model: nn.Module, name: str, dsd_fqn_modifiers: str = "_fqn_modifiers", skip_ddp_prefix: bool = True, skip_compiler_prefix: bool = True, ) -> FQNS_T: """ This API is used to convert the name of a parameter to the FQNs. For FSDP without `use_orig_params`, the name of FlatParameter can be mapped to multiple original parameters. As a result, the return type of this function is `set[str]`. Args: module (nn.Module): the root model. name (str): the name skip_ddp_prefix (bool): whether to skip DDP's `module` prefix Returns: The canonical FQNs based on the model traversal. """ # Remove the checkpoint prefix, if it exists. name = name.replace(_CHECKPOINT_PREFIX, "") if "." not in name: return {name} obj_names = name.split(".") fqn_obj_names = [] curr_obj = model for i, curr_obj_name in enumerate(obj_names): if isinstance(curr_obj, DDP): assert curr_obj_name == "module" curr_obj = curr_obj.module if not skip_ddp_prefix: fqn_obj_names.append(curr_obj_name) elif isinstance(curr_obj, FSDP): if i < len(obj_names) - 1 and obj_names[i + 1] == _FLAT_PARAM: prefix = ".".join(fqn_obj_names) flat_param = getattr(curr_obj, _FLAT_PARAM) if prefix: prefix = f"{prefix}." return {f"{prefix}{fqn}" for fqn in flat_param._fqns} curr_obj = getattr(curr_obj, FSDP_WRAPPED_MODULE) if curr_obj_name != FSDP_WRAPPED_MODULE: fqn_obj_names.append(curr_obj_name) curr_obj = getattr(curr_obj, curr_obj_name) elif isinstance(curr_obj, torch._dynamo.eval_frame.OptimizedModule): assert curr_obj_name == "_orig_mod" curr_obj = curr_obj._orig_mod if not skip_compiler_prefix: fqn_obj_names.append(curr_obj_name) else: # In some modeuls, _fqn_modifiers would not shown in the state_dict keys, # skip them in the fqn to ensure load stat dict successfully for them. if hasattr(curr_obj, dsd_fqn_modifiers): if removed_fqn := getattr(curr_obj, dsd_fqn_modifiers)().get(curr_obj_name): if hasattr(curr_obj, removed_fqn): curr_obj = getattr(curr_obj, removed_fqn) fqn_obj_names.append(curr_obj_name) if curr_obj_name == nn.modules.module._EXTRA_STATE_KEY_SUFFIX: if i != len(obj_names) - 1: raise RuntimeError("Expect `_extra_state` to be the last obj name") else: curr_obj = getattr(curr_obj, curr_obj_name) return {".".join(fqn_obj_names).replace(_CHECKPOINT_PREFIX, "")} class _EXTRA_STATE: pass def _iterate_valid_model_state(model, dsd_fqn_modifiers="_fqn_modifiers"): visited_modules: set[nn.Module] = set() def recurse(module: nn.Module, curr_fqn: str) -> Generator: visited_modules.add(module) curr_fqn = f"{curr_fqn}." if curr_fqn else "" for name, submodule in module.named_children(): if submodule in visited_modules: continue # if user have state_dict_hooks in their model, they can add the state_dict key changes # at dsd_fqn_modifiers in input to align with the function of state_dict_hook if hasattr(module, dsd_fqn_modifiers) and name in getattr(module, dsd_fqn_modifiers)().values(): # skip _fqn_modifiers here thus remove the last `.` added new_fqn = curr_fqn[:-1] else: new_fqn = f"{curr_fqn}{name}" yield from recurse(submodule, new_fqn) for name, obj in chain(module.named_buffers(recurse=False), module.named_parameters(recurse=False)): if name in module._non_persistent_buffers_set: continue new_fqn = f"{curr_fqn}{name}" yield new_fqn, obj if getattr(module.__class__, "get_extra_state", nn.Module.get_extra_state) != nn.Module.get_extra_state: new_fqn = f"{curr_fqn}{nn.modules.module._EXTRA_STATE_KEY_SUFFIX}" yield new_fqn, _EXTRA_STATE() yield from recurse(model, "") def _verify_options( model: nn.Module, optims: tuple[torch.optim.Optimizer, ...], optim_only: bool, *, submodules: Optional[set[nn.Module]] = None, options: Optional[StateDictOptions] = None, ) -> _StateDictInfo: """ Verify the model and options passed by the user and generates _StateDictInfo. """ if submodules: warnings.warn( "Getting submodules only model/optim state_dict is deprecated and " "will be removed in 2.5. This feature can be achieved by manually " "filtering out the state_dict returned from get_state_dict.", FutureWarning, ) if optim_only and not optims: raise RuntimeError("Optimizers are not passed in but optim_only is set to True.") options = options or StateDictOptions() fqn_param_mapping: dict[str | torch.Tensor, set[str] | torch.Tensor] = {} shared_params_mapping: dict[str | torch.Tensor, set[str] | torch.Tensor] = {} for name, param in _iterate_valid_model_state(model): if isinstance(param, _EXTRA_STATE): continue fqns = _get_fqns(model, name) fqn = fqn_param_mapping.get(param, None) if fqn is not None: cast(set[str], fqn_param_mapping[param]).update(fqns) shared_params_mapping[param] = fqn_param_mapping[param] else: # We need to do copy as _get_fqns is lru_cached fqn_param_mapping[param] = fqns.copy() for fqn in fqns: if not isinstance(param, _EXTRA_STATE): fqn_param_mapping[fqn] = param for param_, fqns_ in list(shared_params_mapping.items()): for fqn in fqns_: shared_params_mapping[fqn] = cast(torch.Tensor, param_) submodule_prefixes: set[str] = set() if submodules: submodules = set(submodules) for name, module in model.named_modules(): if module not in submodules: continue fqns = _get_fqns(model, name) assert len(fqns) == 1, "Submodule FQN should only have 1 instance" submodule_prefixes.update(f"{fqn}." for fqn in fqns) if options.broadcast_from_rank0 and not options.full_state_dict: raise ValueError("full_state_dict must be True when broadcast_from_rank0 is True.") fsdp_modules = FSDP.fsdp_modules(model) state_dict_config: StateDictConfig optim_state_dict_config: OptimStateDictConfig fsdp_context: Callable if fsdp_modules: # FSDP API only work if at least one FSDP instance exists. if options.full_state_dict: state_dict_config = FullStateDictConfig(offload_to_cpu=options.cpu_offload, rank0_only=options.cpu_offload) optim_state_dict_config = FullOptimStateDictConfig( offload_to_cpu=options.cpu_offload, rank0_only=(options.cpu_offload or options.broadcast_from_rank0), ) state_dict_type = StateDictType.FULL_STATE_DICT else: state_dict_config = ShardedStateDictConfig( offload_to_cpu=options.cpu_offload, ) optim_state_dict_config = ShardedOptimStateDictConfig( offload_to_cpu=options.cpu_offload, ) state_dict_type = StateDictType.SHARDED_STATE_DICT @contextlib.contextmanager def fsdp_state_dict_type_without_warning( module, state_dict_type, state_dict_config, optim_state_dict_config, ): with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="FSDP.state_dict_type", category=FutureWarning) with FSDP.state_dict_type( module=module, state_dict_type=state_dict_type, state_dict_config=state_dict_config, optim_state_dict_config=optim_state_dict_config, ): yield fsdp_context = functools.partial( fsdp_state_dict_type_without_warning, module=model, state_dict_type=state_dict_type, state_dict_config=state_dict_config, optim_state_dict_config=optim_state_dict_config, ) else: fsdp_context = contextlib.nullcontext return _StateDictInfo( **asdict(options), fqn_param_mapping=fqn_param_mapping, shared_params_mapping=shared_params_mapping, submodule_prefixes=submodule_prefixes, fsdp_context=fsdp_context, fsdp_modules=cast(list[nn.Module], fsdp_modules), handle_model=not optim_only, handle_optim=(len(optims) > 0), ) def _verify_state_dict( model_state_dict: dict[str, ValueType], optim_state_dict: OptimizerStateType, info: _StateDictInfo, ) -> None: for module in info.fsdp_modules: fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module) assert fsdp_state is not None, "Expected a fsdp_state with a fsdp module." # Verify if the model_state_dict and optim_state_dict are valid. This API # should give the users an explicit error message to debug or report. if ( info.handle_model and not model_state_dict and not info.submodule_prefixes and not info.ignore_frozen_params and not (info.cpu_offload and info.full_state_dict) and info.strict and not info.broadcast_from_rank0 ): raise RuntimeError( "The option indicates that model state_dict is required to save " "or load, but model state_dict is empty." f"rank = {dist.get_rank()=}." ) if info.handle_optim: if not optim_state_dict and not (info.cpu_offload and info.full_state_dict) and (not info.broadcast_from_rank0): raise RuntimeError( "The option indicates that model state_dict is required to save, " f"or load but optim state_dict is empty. {optim_state_dict}" ) for key in model_state_dict.keys(): if _FLAT_PARAM in key: raise RuntimeError(f"{key} contains {_FLAT_PARAM}. This can happen if the model is not the root module.") def _state_dict_fn(obj: nn.Module | torch.optim.Optimizer, api: str) -> Callable: call = getattr(obj, api) if call in _patched_state_dict: call = functools.partial(getattr(obj.__class__, api), self=obj) return call def _maybe_full_or_cpu_state_dict(state_dict: dict[str, Any], info: _StateDictInfo) -> dict[str, Any]: if info.full_state_dict: ranks_only = () if (not info.cpu_offload or not torch.distributed.is_initialized()) else (0,) return _gather_state_dict(state_dict, cpu_offload=info.cpu_offload, ranks_only=ranks_only) elif info.cpu_offload: return _offload_state_dict_to_cpu(state_dict) else: return state_dict @torch.no_grad() def _get_model_state_dict(model: nn.Module, info: _StateDictInfo) -> dict[str, ValueType]: if not info.handle_model: return {} with info.fsdp_context(): state_dict = _state_dict_fn(model, "state_dict")() for key in list(state_dict.keys()): fqns = _get_fqns(model, key) assert len(fqns) == 1, (key, fqns) fqn = next(iter(fqns)) if fqn != key: # As we only support FSDP, DDP, and TP, the only cases are # wrapper-based DDP and compiler. Verify if the assumption # is correct. def verify(key, fqn) -> bool: if len(fqn) >= len(key): return False fqn_split = fqn.split(".") key_split = key.split(".") fqn_idx = 0 for key_idx, key_name in enumerate(key_split): if key_name == fqn_split[fqn_idx]: fqn_idx += 1 if fqn_idx == len(fqn_split): return key_idx == len(key_split) - 1 elif key_name in ("module", "_orig_mod"): continue else: return False return True if not verify(key, fqn): raise RuntimeError(f"An unexpected key, {key}, exists. FQN is {fqn}") state_dict[fqn] = state_dict.pop(key) if info.submodule_prefixes: new_state_dict: dict[str, ValueType] = {} # TODO: make this faster. for fqn in state_dict.keys(): for prefix in info.submodule_prefixes: if not fqn.startswith(prefix): continue if info.keep_submodule_prefixes: new_state_dict[fqn] = state_dict[fqn] else: new_fqn = fqn[len(prefix) :] new_state_dict[new_fqn] = state_dict[fqn] state_dict = new_state_dict if info.ignore_frozen_params: for key, param in model.named_parameters(): if param.requires_grad: continue fqns = _get_fqns(model, key) for fqn in fqns: state_dict.pop(fqn) for key, p in list(state_dict.items()): if torch.is_tensor(p) and p.is_meta: state_dict.pop(key) return _maybe_full_or_cpu_state_dict(state_dict, info) @torch.no_grad() def _load_model_state_dict( model: nn.Module, state_dict: dict[str, ValueType], info: _StateDictInfo, ) -> _IncompatibleKeys: if not info.handle_model or (not state_dict and not info.broadcast_from_rank0): return _IncompatibleKeys({}, {}) local_state_dict = {} for key, value in _iterate_valid_model_state(model, info.dsd_fqn_modifiers): fqns = _get_fqns(model, key, info.dsd_fqn_modifiers) fqns_with_prefix = _get_fqns( model, key, info.dsd_fqn_modifiers, skip_ddp_prefix=False, skip_compiler_prefix=False, ) for fqn, fqn_with_prefix in zip(fqns, fqns_with_prefix, strict=False): if (not info.broadcast_from_rank0 or dist.get_rank() == 0) and fqn != fqn_with_prefix: load_value = state_dict.pop(fqn, None) if load_value is None: if info.strict: raise RuntimeError(f"Missing key: {fqn}.") else: state_dict[fqn_with_prefix] = load_value local_state_dict[fqn_with_prefix] = value assign = False if info.broadcast_from_rank0 or info.full_state_dict: devices = set() for key, value in local_state_dict.items(): if torch.is_tensor(value) and value.dim() > 0: devices.add(value.device) # In lora state_dict, there could be multiple devices, with meta device inside. # Take the other device in the broadcast/distribtue, and set assign to True if torch.device("meta") in devices: devices.remove(torch.device("meta")) assign = True if len(devices) == 0: devices.add(dist.distributed_c10d._get_pg_default_device()) elif len(devices) > 1: raise ValueError("Multiple devices found") if info.broadcast_from_rank0: _broadcast_state_dict( state_dict, local_state_dict, device=devices.pop(), strict=info.strict, cpu_offload=info.cpu_offload, ) elif info.full_state_dict: _distribute_state_dict(state_dict, local_state_dict, device=devices.pop()) for fqn, local_state in local_state_dict.items(): state_dict[fqn] = local_state with info.fsdp_context(): return cast( _IncompatibleKeys, _state_dict_fn(model, "load_state_dict")(state_dict=state_dict, strict=info.strict, assign=assign), ) def _init_optim_state(optim: torch.optim.Optimizer) -> None: """ Initialize optim states by calling the step() with zero grads. """ if optim.state: # The optimizer state is initialized. return # There are some stateless optimizers like SGD. These optimizer will # not return in the above condition. So if gradients exist, we should also # return. If gradients do not exist, the following initialization should # not disturb SGD because the gradients and lr are both zero. for param_group in optim.param_groups: for param in param_group[_PARAMS]: if param.grad is not None: return for param_group in optim.param_groups: for param in param_group[_PARAMS]: if param.requires_grad: param.grad = torch.zeros_like(param) # Some optimizers will update parameters regardless of grads due to lr, so # make lr to zero when calling `step()`. lrs = [] for param_group in optim.param_groups: if "lr" in param_group: lrs.append(param_group["lr"]) param_group["lr"] = torch.tensor(0.0) if isinstance(param_group["lr"], torch.Tensor) else 0.0 optim.step(closure=None) # Whether to recover the "lr" should not matter too much as we will # restore checkpointing later. for param_group in optim.param_groups: if "lr" in param_group: param_group["lr"] = lrs.pop(0) optim.zero_grad(set_to_none=True) def _flatten_optim_state_dict(state_dict: OptimizerStateType) -> dict[str, ValueType]: """ This API flattens the optimizer state_dict to support optimizer resharding for MPMD, e.g., pipeline parallelism. Without the API, the original optimizer state_dict looks like: { "state": { "layer1.weight": { "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor }, "layer2.weight": { "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor }, }, "param_group": [ { "lr": 0.0, "betas": (0.9, 0.95), ..., "params": ["layer1.weight", "layer2.weight"] } ] } With this API, the optimizer state_dict looks like: { "state.layer1.weight.step": 10, "state.layer2.weight.step": 10, "state.layer1.weight.exp_avg": SomeTensor, "state.layer2.weight.exp_avg": SomeTensor, "state.layer1.weight.exp_avg_sq": SomeTensor, "state.layer2.weight.exp_avg_sq": SomeTensor, "param_group.layer1.weight.lr" : 0.1, "param_group.layer2.weight.lr" : 0.1, "param_group.layer1.weight.betas" : (0.9, 0.95), "param_group.layer2.weight.betas" : (0.9, 0.95), } Note that if any of the value is a container, like the betas in the example, this API won't flattent it. """ def _raise_if_type_not_supported(v): if not isinstance(v, (torch.Tensor, int, float)): raise NotImplementedError( f"Flattening optimizer state_dict only supports tensor, int, float states now. Type is {type(v)}." ) ret: dict[str, ValueType] = {} for fqn, state in cast(DictValueType, state_dict[_STATE]).items(): for k, v in cast(DictValueType, state).items(): _raise_if_type_not_supported(v) ret[f"{_STATE}.{fqn}.{k}"] = v for param_group in cast(ListDictValueType, state_dict[_PG]): fqns = param_group.pop(_PARAMS) for fqn in cast(list[str], fqns): for k, v in param_group.items(): ret[f"{_PG}.{fqn}.{k}"] = v return ret def _unflatten_optim_state_dict( optim: torch.optim.Optimizer, state_dict: dict[str, ValueType], info: _StateDictInfo, ) -> OptimizerStateType: """ This API unflattens the state_dict generated by _flatten_optim_state_dict(). See the docstring of _flatten_optim_state_dict() for more detail. """ state: DictValueType = {} pg_state: ListDictValueType = [] return_osd: OptimizerStateType = {_STATE: state, _PG: pg_state} for param_group in optim.param_groups: pg_state.append({_PARAMS: []}) for param in param_group[_PARAMS]: for fqn in info.fqn_param_mapping[param]: # If a parameter is shared, only one of the FQN will be used. # So we need to verify which if this fqn is actually used in # the state_dict. if fqn in info.shared_params_mapping: in_params = False for k in param_group.keys(): if k == _PARAMS: continue flatten_key = f"{_PG}.{fqn}.{k}" if flatten_key in state_dict: in_params = True break else: in_params = True if not in_params: continue params = pg_state[-1][_PARAMS] assert isinstance(params, list) # typing params.append(fqn) if not param.requires_grad: continue state[fqn] = {} for state_name in optim.state[param].keys(): cast(DictValueType, state[fqn])[state_name] = state_dict[f"{_STATE}.{fqn}.{state_name}"] first_param_fqn = cast(list[str], pg_state[-1][_PARAMS])[0] for k in param_group.keys(): if k == _PARAMS: continue value = state_dict[f"{_PG}.{first_param_fqn}.{k}"] if k not in pg_state[-1]: pg_state[-1][k] = value elif pg_state[-1][k] != value: raise RuntimeError( "All the parameters in the same parameter group should have " f"the same saved param_group value. But {first_param_fqn}.{k} " f"is {value} while other(s) is {pg_state[-1][k]}." ) return return_osd @torch.no_grad() def _get_optim_state_dict( model: nn.Module, optimizers: tuple[torch.optim.Optimizer, ...], info: _StateDictInfo, ) -> OptimizerStateType: if not info.handle_optim: return {} optim_state_dict: OptimizerStateType = {_STATE: {}, _PG: []} for optim in optimizers: _init_optim_state(optim) osd = _state_dict_fn(optim, "state_dict")() if info.fsdp_modules: with info.fsdp_context(): osd = FSDP.optim_state_dict(model, optim, osd) # We need to specially handle FlatParameter FSDP as # FlatParameter FSDP converts the FQNs. # There are no easy ways to do this conversion systematically. # We can only use a string replacment without correctness check. if not osd: continue for k in list(osd[_STATE].keys()): if "_orig_mod" in k: osd[_STATE][k.replace("_orig_mod.", "")] = osd[_STATE].pop(k) for g in osd[_PG]: params = [k.replace("_orig_mod.", "") for k in g[_PARAMS]] g[_PARAMS] = params else: params = list(chain.from_iterable(g[_PARAMS] for g in optim.param_groups)) param_pid_mapping = dict(zip(params, range(len(params)), strict=False)) fqn_pid_mapping = {} for key, param in model.named_parameters(): fqns = _get_fqns(model, key) assert len(fqns) == 1 fqn = next(iter(fqns)) if param not in param_pid_mapping: continue pid = param_pid_mapping[param] fqn_pid_mapping[fqn] = pid fqn_pid_mapping[pid] = fqn for key in list(osd[_STATE].keys()): fqn = fqn_pid_mapping[key] osd[_STATE][fqn] = osd[_STATE].pop(key) for group in osd[_PG]: group[_PARAMS] = [fqn_pid_mapping[pid] for pid in group[_PARAMS]] if not osd: continue cast(DictValueType, optim_state_dict[_STATE]).update(osd[_STATE]) cast(ListDictValueType, optim_state_dict[_PG]).extend(osd[_PG]) if info.flatten_optimizer_state_dict: optim_state_dict = cast(OptimizerStateType, _flatten_optim_state_dict(optim_state_dict)) return _maybe_full_or_cpu_state_dict(optim_state_dict, info) def _split_optim_state_dict( model: nn.Module, optim: torch.optim.Optimizer, optim_state_dict: OptimizerStateType, info: _StateDictInfo, ) -> OptimizerStateType: """ Extract the corresponding optim state_dict from ``optim_state_dict`` for ``optim`` and return the result optim state_dict. Args: model (nn.Module): the root model. optim (torch.optim.Optimizer): the optimizer. optim_state_dict (Dict[str, ValueType]): the superset optim state_dict that contains the optim state_dict of ``optim``. info (_StateDictInfo): state dict information. Returns: The optim state_dict of ``optim``. """ state: DictValueType = {} pg_state: ListDictValueType = [] return_osd: OptimizerStateType = {_STATE: state, _PG: pg_state} pg_mapping: dict[int, int] = {} if all(isinstance(k, int) for k in cast(DictValueType, optim_state_dict[_STATE]).keys()): return optim_state_dict for param_group in optim.param_groups: pg_state.append({_PARAMS: []}) for param in param_group[_PARAMS]: for fqn in info.fqn_param_mapping[param]: if fqn in info.shared_params_mapping: in_params = False for loaded_param_group in cast(ListDictValueType, optim_state_dict[_PG]): if fqn in cast(list[str], loaded_param_group[_PARAMS]): in_params = True break else: in_params = True if not in_params: continue params = pg_state[-1][_PARAMS] assert isinstance(params, list) params.append(fqn) if param.requires_grad: state[fqn] = cast(DictValueType, optim_state_dict[_STATE])[fqn] for loaded_param_group in cast(ListDictValueType, optim_state_dict[_PG]): if fqn in cast(list[str], loaded_param_group[_PARAMS]): pg_mapping[id(loaded_param_group)] = len(return_osd[_PG]) - 1 if len(param_group[_PARAMS]) == 0: # Param_group with empty params. ret = [] for loaded_param_group in cast(ListDictValueType, optim_state_dict[_PG]): if len(cast(list[str], loaded_param_group[_PARAMS])) == 0: ret.append(loaded_param_group) if len(ret) != 1: raise ValueError( "There are param groups that have zero parameters. " "In such a case, DSD only support exactly one param group " "with zero parameters." "But the loaded state_dict has zero or more than one param groups " "that have zero parameters." ) if len(optim_state_dict[_PG]) != len(optim.param_groups): raise ValueError( "When there is a parameter group that has zero parameters, multiple optimizers are not supported." ) pg_mapping[id(loaded_param_group)] = len(return_osd[_PG]) - 1 for param_group in cast(ListDictValueType, optim_state_dict[_PG]): pg_idx = pg_mapping.get(id(param_group), -1) if pg_idx == -1: continue for key, value in param_group.items(): if key == _PARAMS: continue # TODO: check if value is the same if exists. pg_state[pg_idx][key] = value return return_osd @torch.no_grad() def _load_optim_state_dict( model: nn.Module, optimizers: tuple[torch.optim.Optimizer, ...], state_dict: OptimizerStateType, info: _StateDictInfo, ) -> None: if not info.handle_optim: return for optim in optimizers: _init_optim_state(optim) if state_dict: if _STATE in state_dict: optim_state_dict = _split_optim_state_dict(model, optim, state_dict, info) else: optim_state_dict = _unflatten_optim_state_dict(optim, cast(dict[str, ValueType], state_dict), info) else: optim_state_dict = {} if info.fsdp_modules: # We need to specially handle FlatParameter FSDP as # FlatParameter FSDP converts the FQNs. for original_fqn, _ in model.named_parameters(): fqns = _get_fqns(model, original_fqn) fqns_with_compiler = _get_fqns(model, original_fqn, skip_compiler_prefix=False) if fqns == fqns_with_compiler: continue assert len(fqns) == 1 fqn = fqns.pop() fqn_with_compiler = fqns_with_compiler.pop() for g in optim_state_dict[_PG]: val = cast(dict[str, Any], g) params = [key.replace(fqn, fqn_with_compiler) for key in val[_PARAMS]] val[_PARAMS] = params osd_state = cast(DictValueType, optim_state_dict[_STATE]) for k in list(osd_state.keys()): if fqn in k: osd_state[k.replace(fqn, fqn_with_compiler)] = osd_state.pop(k) with info.fsdp_context(): optim_state_dict = FSDP.optim_state_dict_to_load(model, optim, optim_state_dict) elif info.full_state_dict: info.full_state_dict = False local_state_dict = _get_optim_state_dict(model, (optim,), info) info.full_state_dict = True device = None def _device(t): if t.dim() > 0: nonlocal device if device is None: device = t.device elif device != t.device: raise ValueError("Device mismatch") return t _ = tree_map_only(torch.Tensor, _device, local_state_dict) assert device is not None flatten_osd, osd_mapping = _flatten_state_dict(optim_state_dict) flatten_local_osd, local_osd_mapping = _flatten_state_dict(local_state_dict) if info.broadcast_from_rank0: _broadcast_state_dict(flatten_osd, flatten_local_osd, device=device) else: _distribute_state_dict(flatten_osd, flatten_local_osd, device=device) # The modifications listed seek to address the problem where optim might possess # dissimilar parameters in comparison to optim_state_dict. This is achieved by # incorporating differential parameters within local, which may result in optim # having additional parameters ultimately. for optim_key in flatten_osd.keys(): if optim_key not in flatten_local_osd: assert optim_key in osd_mapping flatten_local_osd[optim_key] = flatten_osd[optim_key] local_osd_mapping[optim_key] = osd_mapping[optim_key] optim_state_dict = _unflatten_state_dict(flatten_local_osd, local_osd_mapping) for pg in optim_state_dict[_PG]: if _PARAMS not in pg: cast(dict[str, ValueType], pg)[_PARAMS] = [] # Note that we do not have to convert the FQN back to param id here if # order in optim.param_groups[idx][_PARAMS] is the same as the one in # optim_state_dict[_PG][idx][_PARAMS]. _state_dict_fn(optim, "load_state_dict")(state_dict=optim_state_dict) def get_model_state_dict( model: nn.Module, *, submodules: Optional[set[nn.Module]] = None, options: Optional[StateDictOptions] = None, ) -> dict[str, ValueType]: """ Return the model state_dict of ``model``. See ``get_state_dict`` for the detail usage. Args: model (nn.Module): the nn.Module to the model. submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters that belong to the submodules. options (StateDictOptions): the options to control how model state_dict and optimizer state_dict should be returned. See `StateDictOptions` for the details. Returns: The state_dict for ``model``. :rtype: typing.Dict[str, ValueType] """ with _gc_context(): info = _verify_options( model, (), optim_only=False, submodules=submodules, options=options, ) model_state_dict = _get_model_state_dict(model, info) _verify_state_dict(model_state_dict, {}, info) return model_state_dict def get_optimizer_state_dict( model: nn.Module, optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer], *, submodules: Optional[set[nn.Module]] = None, options: Optional[StateDictOptions] = None, ) -> OptimizerStateType: """ Return the combined state_dict for optimizers. See ``get_state_dict`` for the detail usage. Args: model (nn.Module): the nn.Module to the model. optimizers (Union[None, Optimizer, Iterable[Optimizer]]): The optimizers that are used to optimize ``model``. submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters that belong to the submodules. options (StateDictOptions): the options to control how model state_dict and optimizer state_dict should be returned. See `StateDictOptions` for the details. Returns: The state_dict for ``optimizers``. :rtype: OptimizerStateType """ with _gc_context(): optimizers = (optimizers,) if isinstance(optimizers, torch.optim.Optimizer) else tuple(optimizers) info = _verify_options( model, optimizers, optim_only=True, submodules=submodules, options=options, ) optim_state_dict = _get_optim_state_dict(model, optimizers, info) _verify_state_dict({}, optim_state_dict, info) return optim_state_dict def get_state_dict( model: nn.Module, optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer], *, submodules: Optional[set[nn.Module]] = None, options: Optional[StateDictOptions] = None, ) -> tuple[dict[str, ValueType], OptimizerStateType]: """ Return the model state_dict and optimizers state_dict. ``get_state_dict`` can process any module that is parallelized by PyTorch FSDP/fully_shard, DDP/replicate, tensor_parallel/parallelize_module, and any combination of these parallelisms. The main functions of ``get_state_dict`` are: 1.) returning a model and optimizer state_dict that can be resharded with a different number of trainers and/or different parallelisms. 2.) hiding the parallelism-specific state_dict APIs. Users don't have to call these APIs. 3.) sanity checking the result state_dict. The keys of the result state dictionary are the canonical FQNs (Fully Qualified Names). A canonical FQN refers to the FQN based on a parameter's position in an nn.Module hierarchy. More specifically, a canonical FQN to a parameter is the FQN returned by ``module.named_parameters()`` or ``module.named_buffers()`` when the module is not distributed by any parallelisms. Since the optimizer internally uses parameter IDs to represent a parameter, there will be a conversion from the parameter IDs to the canonical FQNs when calling this API. ``get_state_dict`` can also process a module that is not parallelized. In such a case, ``get_state_dict`` only performs one function -- converting the optimizer parameter IDs to the canonical FQNs. Example: >>> # xdoctest: +SKIP >>> import torch >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP >>> from torch.nn.parallel import DistributedDataParallel as DDP >>> from torch.distributed.checkpoint.state_dict import get_state_dict >>> fsdp_model = FSDP(copy.deepcopy(model)) >>> fsdp_optim = torch.optim.Adam(model.parameters(), lr=1e-3) >>> ddp_model = DDP(copy.deepcopy(model)) >>> ddp_optim = torch.optim.Adam(model.parameters(), lr=1e-3) >>> ddp_state_dict, ddp_optim_state_dict = get_state_dict(ddp_model, ddp_optim) >>> fsdp_state_dict, fsdp_optim_state_dict = get_state_dict( ... fsdp_model, fsdp_optim ... ) >>> # if we simply call ddp_model.state_dict() and fsdp_model.state_dict(), >>> # the asserts will fail. >>> assert ddp_state_dict == fsdp_state_dict >>> assert ddp_optim_state == fsdp_optim_state_dict Args: model (nn.Module): the nn.Module to the model. optimizers (Union[None, Optimizer, Iterable[Optimizer]]): The optimizers that are used to optimize ``model``. submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters that belong to the submodules. options (StateDictOptions): the options to control how model state_dict and optimizer state_dict should be returned. See `StateDictOptions` for the details. Returns: ``Tuple`` that contain model state_dict and optimizer state_dict. :rtype: typing.Tuple[typing.Dict[str, ValueType], OptimizerStateType] """ with _gc_context(): optimizers = (optimizers,) if isinstance(optimizers, torch.optim.Optimizer) else tuple(optimizers) info = _verify_options( model, optimizers, optim_only=False, submodules=submodules, options=options, ) model_state_dict = _get_model_state_dict(model, info) optim_state_dict = _get_optim_state_dict(model, optimizers, info) _verify_state_dict(model_state_dict, optim_state_dict, info) return model_state_dict, optim_state_dict def _unflatten_model_state_dict( model: nn.Module, state_dict: dict[nn.Module, dict[str, ValueType]] | dict[str, ValueType], ) -> dict[str, ValueType]: if not state_dict: return {} if isinstance(next(iter(state_dict.keys())), nn.Module): warnings.warn( "Passing model_state_dict as a ``Dict[nn.Module, Dict[str, Any]]``" "is deprecated and will be removed in 2.5. If you need this " "feature, please preprocessing the model_state_dict to achieve the " "same functionality.", FutureWarning, ) cast_state_dict = cast(dict[nn.Module, dict[str, ValueType]], state_dict) new_state_dict: dict[str, ValueType] = {} for submodule, sub_state_dict in cast_state_dict.items(): for name, m in model.named_modules(): if m != submodule: continue fqns = _get_fqns(model, name) assert len(fqns) == 1, "FQNs for a submodule should only have 1 element" prefix = f"{next(iter(fqns))}." new_state_dict.update({prefix + subfqn: value for subfqn, value in sub_state_dict.items()}) return new_state_dict else: return cast(dict[str, ValueType], state_dict) def set_model_state_dict( model: nn.Module, model_state_dict: dict[str, ValueType], *, options: Optional[StateDictOptions] = None, ) -> _IncompatibleKeys: """Load the model state_dict. The counterpart of ``get_model_state_dict`` to set the state_dict to the model. See ``set_state_dict`` for the detail usage. Args: model (nn.Module): the nn.Module to the model. model_state_dict: (Dict[str, ValueType]): the model state_dict to load. If the key of the ``model_state_dict`` is nn.Module, the key is a submodule of ``model`` and the value should be the state_dict of the submodule. When loading the state_dict, the prefix of the submodule will be append to the state_dict. options (StateDictOptions): the options to control how model state_dict and optimizer state_dict should be loaded. See `StateDictOptions` for the details. Returns: ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields: * **missing_keys** is a list of str containing the missing keys * **unexpected_keys** is a list of str containing the unexpected keys :type model_state_dict: typing.Dict[str, ValueType] """ model_state_dict: dict[str, ValueType] = _unflatten_model_state_dict(model, model_state_dict) with _gc_context(): info = _verify_options(model, (), optim_only=False, options=options) _verify_state_dict(model_state_dict, {}, info) return _load_model_state_dict(model, model_state_dict, info) def set_optimizer_state_dict( model: nn.Module, optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer], optim_state_dict: OptimizerStateType, *, options: Optional[StateDictOptions] = None, ) -> None: """Load the optimizers state_dict. The counterpart of ``get_optimizer_state_dict`` to set the state_dict to the optimizers. See ``set_state_dict`` for the detail usage. WARN: ``set_optimizer_state_dict`` can only be called before ``backward()`` or after ``step()`` is called on the optimizers. Otherwise, the optimizer states won't be initialized correctly. Args: model (nn.Module): the nn.Module to the model. optimizers (Union[Optimizer, Iterable[Optimizer]]): The optimizers that are used to optimize ``model``. optim_state_dict: OptimizerStateType: the optimizer state_dict to load. options (StateDictOptions): the options to control how model state_dict and optimizer state_dict should be loaded. See `StateDictOptions` for the details. Returns: None :type optim_state_dict: typing.OptimizerStateType """ with _gc_context(): optimizers = (optimizers,) if isinstance(optimizers, torch.optim.Optimizer) else tuple(optimizers) info = _verify_options(model, optimizers, optim_only=True, options=options) _verify_state_dict({}, optim_state_dict, info) _load_optim_state_dict(model, optimizers, optim_state_dict, info) def set_state_dict( model: nn.Module, optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer], *, model_state_dict: dict[str, ValueType], optim_state_dict: OptimizerStateType, options: Optional[StateDictOptions] = None, ) -> _IncompatibleKeys: """Load the model state_dict and optimizers state_dict. The counterpart of ``get_state_dict`` to set the state_dict to the model and optimizers. The given ``model_state_dict`` and ``optim_state_dict`` do not have to be returned by ``get_state_dict`` but must meet the following requirements: 1) all FQNs are canonical FQNs as defined in ``get_state_dict``, 2) if a tensor is sharded, it must be either a ShardedTensor or DTensor, 3) optimizer state_dict cannot contain the parameter IDs; the keys should be the canonical FQNs. WARN: ``set_state_dict`` can only be called before ``backward()`` or after ``step()`` is called on the optimizers. Otherwise, the optimizer states won't be initialized correctly. Args: model (nn.Module): the nn.Module to the model. optimizers (Union[Optimizer, Iterable[Optimizer]]): The optimizers that are used to optimize ``model``. model_state_dict: (Union[Dict[nn.Module, Dict[str, ValueType]], Dict[str, ValueType]]): the model state_dict to load. If the key of the ``model_state_dict`` is nn.Module, the key is a submodule of ``model`` and the value should be the state_dict of the submodule. When loading the state_dict, the prefix of the submodule will be append to the state_dict. optim_state_dict: OptimizerStateType: the optimizer state_dict to load. options (StateDictOptions): the options to control how model state_dict and optimizer state_dict should be loaded. See `StateDictOptions` for the details. Returns: ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields: * **missing_keys** is a list of str containing the missing keys of the model state_dict. * **unexpected_keys** is a list of str containing the unexpected keys of the model state_dict. :type model_state_dict: typing.Dict[str, ValueType] :type optim_state_dict: typing.OptimizerStateType """ model_state_dict: dict[str, ValueType] = _unflatten_model_state_dict(model, model_state_dict) with _gc_context(): optimizers = (optimizers,) if isinstance(optimizers, torch.optim.Optimizer) else tuple(optimizers) info = _verify_options(model, optimizers, optim_only=not model_state_dict, options=options) _verify_state_dict(model_state_dict, optim_state_dict, info) _load_optim_state_dict(model, optimizers, optim_state_dict, info) return _load_model_state_dict(model, model_state_dict, info) # TODO: correct the state_dict function signature. # TODO: this API is not yet fully tested. Make it private @no_type_check def _patch_model_state_dict( model: nn.Module, *, options: Optional[StateDictOptions] = None, ) -> None: """Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model``. Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model`` to be a partial function to call ``get_state_dict`` and ``set_state_dict``. Example: from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.checkpoint.state_dict import patch_model_state_dict model = fsdp(model) patch_model_state_dict(model) Args: model (nn.Module): the nn.Module to the model. options (StateDictOptions): the options to control how model state_dict and optimizer state_dict should be loaded. See `StateDictOptions` for the details. Returns: None """ _state_dict_call = functools.partial( get_model_state_dict, model=model, options=options, ) def state_dict_call(): return _state_dict_call() model.state_dict = state_dict_call _load_state_dict_call = functools.partial( set_model_state_dict, model=model, options=options, ) def load_state_dict_call(state_dict: dict[str, Any]): _load_state_dict_call(model_state_dict=state_dict) model.load_state_dict = load_state_dict_call _patched_state_dict.add(state_dict_call) _patched_state_dict.add(load_state_dict_call) # TODO: correct the load_state_dict function signature. # TODO: this API is not yet fully tested. Make it private @no_type_check def _patch_optimizer_state_dict( model: nn.Module, *, optimizers: tuple[torch.optim.Optimizer, ...], options: Optional[StateDictOptions] = None, ) -> None: """Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers``. Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers`` to be a partial function to call ``get_state_dict`` and ``set_state_dict``. Note that if there are multiple optimizers, all of the optimizers will be patched. So users only need to call one of the state_dict() to get the full result. Example: from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.checkpoint.state_dict import patch_model_state_dict model = fsdp(model) patch_model_state_dict(model) Args: model (nn.Module): the nn.Module to the model. options (StateDictOptions): the options to control how model state_dict and optimizer state_dict should be loaded. See `StateDictOptions` for the details. Returns: None """ _state_dict_call = functools.partial( get_optimizer_state_dict, model=model, optimizers=optimizers, options=options, ) def state_dict_call(): return _state_dict_call() _load_state_dict_call = functools.partial( set_optimizer_state_dict, model=model, optimizers=optimizers, options=options, ) def load_state_dict_call(state_dict: dict[str, Any]): _load_state_dict_call(optim_state_dict=state_dict) _patched_state_dict.add(state_dict_call) _patched_state_dict.add(load_state_dict_call) optimizers = (optimizers,) if isinstance(optimizers, torch.optim.Optimizer) else tuple(optimizers) for optim in optimizers: optim.state_dict = state_dict_call optim.load_state_dict = load_state_dict_call
verl__third_party__torch__distributed__checkpoint__state_dict.py
# Copyright 2023-2024 SGLang Team # Copyright 2025 ModelBest Inc. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from typing import Any, Optional from uuid import uuid4 from verl.utils.rollout_trace import rollout_trace_op from .schemas import OpenAIFunctionToolSchema, ToolResponse class BaseTool: """Base class for tools. A tool should support the following methods: - `get_openai_tool_schema`: return the tool schema in OpenAI format. - `create`: create a tool instance for a trajectory. - `execute`: execute the tool. - `calc_reward`: calculate the reward respect to tool state. - `release`: release the tool instance. """ def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): self.config = config self.tool_schema = tool_schema or self.get_openai_tool_schema() assert self.tool_schema is not None, "Tool schema is not set!" self.name = self.tool_schema.function.name print(json.dumps(self.tool_schema.model_dump(exclude_unset=True, exclude_none=True), indent=2)) def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: return self.tool_schema async def create(self, instance_id: Optional[str] = None, **kwargs) -> tuple[str, ToolResponse]: """Create a tool instance. Args: instance_id: The instance id of the tool. Returns: The instance id of the tool. tool_creation_response: The response of the tool when creating the instance. """ if instance_id is None: return str(uuid4()), ToolResponse() else: return instance_id, ToolResponse() @rollout_trace_op async def execute(self, instance_id: str, parameters: dict[str, Any], **kwargs) -> tuple[ToolResponse, float, dict]: """Execute the tool. Args: instance_id: The instance id of the tool. parameters: The json string of the parameters of the tool. Returns: tool_response, tool_reward_score, tool_metrics tool_response: The ToolResponse object containing text, image, and/or video content. tool_reward_score: The step reward score of the tool. tool_metrics: The metrics of the tool. """ return ToolResponse(text="Updated the tool state."), 0.0, {} async def calc_reward(self, instance_id: str, **kwargs) -> float: """Calculate the reward of the tool. Args: instance_id: The instance id of the tool. Returns: The reward of the tool. """ return 0.0 async def release(self, instance_id: str, **kwargs) -> None: """Release the tool instance. Args: instance_id: The instance id of the tool. """ pass
verl__tools__base_tool.py
# Copyright 2023-2025 SGLang Team # Copyright Amazon.com, Inc. or its affiliates. # Copyright 2025 ModelBest Inc. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os from typing import Any, Optional from uuid import uuid4 from verl.utils.reward_score import geo3k from verl.utils.rollout_trace import rollout_trace_op from .base_tool import BaseTool from .schemas import OpenAIFunctionToolSchema, ToolResponse logger = logging.getLogger(__name__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) class Geo3kTool(BaseTool): """A demo tool for calculating the reward of geo3k. - `get_openai_tool_schema`: return the tool schema in OpenAI format. - `create`: create a tool instance for a trajectory. - `execute`: execute the tool. - `calc_reward`: calculate the reward respect to tool state. - `release`: release the tool instance. """ def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): """ _tool_schema = OpenAIFunctionToolSchema.model_validate({ "type": "function", "function": { "name": "calc_geo3k_reward", "description": "A tool for calculating the reward of geo3k", "parameters": { "type": "object", "properties": { "answer": { "type": "string", "description": "The answer to the question, enclosed in \\boxed{}", }, }, "required": ["answer"], }, } }) """ super().__init__(config, tool_schema) self._instance_dict = {} def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: return self.tool_schema async def create( self, instance_id: Optional[str] = None, ground_truth: Optional[str] = None, **kwargs ) -> tuple[str, ToolResponse]: if instance_id is None: instance_id = str(uuid4()) self._instance_dict[instance_id] = { "response": "", "ground_truth": ground_truth, "reward": 0.0, } return instance_id, ToolResponse() @rollout_trace_op async def execute(self, instance_id: str, parameters: dict[str, Any], **kwargs) -> tuple[ToolResponse, float, dict]: answer = parameters.get("answer", "") if not isinstance(answer, str): answer = str(answer) self._instance_dict[instance_id]["response"] = answer reward = await self.calc_reward(instance_id) # penalty for non improved answer submission tool_reward = 0.0 if reward > self._instance_dict[instance_id]["reward"] else -0.05 # update the reward self._instance_dict[instance_id]["reward"] = reward return ToolResponse(text=f"Current parsed {answer=} {reward=}"), tool_reward, {} async def calc_reward(self, instance_id: str, **kwargs) -> float: return geo3k.compute_score( self._instance_dict[instance_id]["response"], self._instance_dict[instance_id]["ground_truth"], use_boxed=False, format_score=0.0, ) async def release(self, instance_id: str, **kwargs) -> None: del self._instance_dict[instance_id]
verl__tools__geo3k_tool.py
# Copyright 2023-2024 SGLang Team # Copyright 2025 ModelBest Inc. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os from typing import Any, Optional from uuid import uuid4 from verl.utils.reward_score import gsm8k from verl.utils.rollout_trace import rollout_trace_op from .base_tool import BaseTool from .schemas import OpenAIFunctionToolSchema, ToolResponse logger = logging.getLogger(__name__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) class Gsm8kTool(BaseTool): """A demo tool for calculating the reward of gsm8k. - `get_openai_tool_schema`: return the tool schema in OpenAI format. - `create`: create a tool instance for a trajectory. - `execute`: execute the tool. - `calc_reward`: calculate the reward respect to tool state. - `release`: release the tool instance. """ def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): """ _tool_schema = OpenAIFunctionToolSchema.model_validate({ "type": "function", "function": { "name": "calc_gsm8k_reward", "description": "A tool for calculating the reward of gsm8k", "parameters": { "type": "object", "properties": { "answer": { "type": "string", "description": "The answer to the question", }, }, "required": ["answer"], }, } }) """ super().__init__(config, tool_schema) self._instance_dict = {} def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: return self.tool_schema async def create( self, instance_id: Optional[str] = None, ground_truth: Optional[str] = None, **kwargs ) -> tuple[str, ToolResponse]: if instance_id is None: instance_id = str(uuid4()) if ground_truth is None: ground_truth = kwargs.get("create_kwargs", {}).get("ground_truth", None) self._instance_dict[instance_id] = { "response": "", "ground_truth": ground_truth, "reward": 0.0, } return instance_id, ToolResponse() @rollout_trace_op async def execute(self, instance_id: str, parameters: dict[str, Any], **kwargs) -> tuple[ToolResponse, float, dict]: answer = parameters.get("answer", "") if not isinstance(answer, str): answer = str(answer) if answer.startswith("#### "): self._instance_dict[instance_id]["response"] = answer else: self._instance_dict[instance_id]["response"] = "#### " + answer reward = await self.calc_reward(instance_id) # penalty for non improved answer submission tool_reward = 0.0 if reward > self._instance_dict[instance_id]["reward"] else -0.05 # update the reward self._instance_dict[instance_id]["reward"] = reward return ToolResponse(text=f"Current parsed {answer=} {reward=}"), tool_reward, {} async def calc_reward(self, instance_id: str, **kwargs) -> float: return gsm8k.compute_score( self._instance_dict[instance_id]["response"], self._instance_dict[instance_id]["ground_truth"], method="flexible", format_score=0.0, score=1.0, ) async def release(self, instance_id: str, **kwargs) -> None: del self._instance_dict[instance_id]
verl__tools__gsm8k_tool.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023-2024 SGLang Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import threading from contextlib import ExitStack from enum import Enum from math import ceil, floor from typing import Any, Callable, Optional, TypeVar from uuid import uuid4 import ray import ray.actor from qwen_vl_utils import fetch_image from .base_tool import BaseTool from .schemas import OpenAIFunctionToolSchema, ToolResponse logger = logging.getLogger(__name__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) T = TypeVar("T") # Adapted from verl/tools/sandbox_fusion_tools.py class PoolMode(Enum): """Execution pool mode enumeration.""" ThreadMode = 1 ProcessMode = 2 @ray.remote(concurrency_groups={"acquire": 1, "release": 10}) class TokenBucketWorker: """Ray actor for rate limiting using token bucket algorithm.""" def __init__(self, rate_limit: int): self.rate_limit = rate_limit self.current_count = 0 # For observability self._semaphore = threading.Semaphore(rate_limit) @ray.method(concurrency_group="acquire") def acquire(self): """Acquire a token from the bucket.""" self._semaphore.acquire() self.current_count += 1 @ray.method(concurrency_group="release") def release(self): """Release a token back to the bucket.""" self._semaphore.release() self.current_count -= 1 def get_current_count(self): """Get current number of acquired tokens.""" return self.current_count class VisualExecutionWorker: """Worker for executing visual processing operations with optional rate limiting.""" def __init__(self, enable_global_rate_limit=True, rate_limit=10): self.rate_limit_worker = self._init_rate_limit(rate_limit) if enable_global_rate_limit else None def _init_rate_limit(self, rate_limit): """Initialize singleton rate limiter.""" return TokenBucketWorker.options(name="rate-limiter", get_if_exists=True).remote(rate_limit) def ping(self): """Health check method.""" return True def execute(self, fn: Callable[..., T], *fn_args, **fn_kwargs) -> T: """Execute function with optional rate limiting.""" if self.rate_limit_worker: with ExitStack() as stack: stack.callback(self.rate_limit_worker.release.remote) ray.get(self.rate_limit_worker.acquire.remote()) try: return fn(*fn_args, **fn_kwargs) except Exception as e: # TODO we should make this available to the tool caller logger.warning(f"Error when executing visual processing: {e}") else: return fn(*fn_args, **fn_kwargs) def init_visual_execution_pool( num_workers: int, enable_global_rate_limit=True, rate_limit=10, mode: PoolMode = PoolMode.ThreadMode ): """Initialize visual execution pool.""" if mode == PoolMode.ThreadMode: return ( ray.remote(VisualExecutionWorker) .options(max_concurrency=num_workers) .remote(enable_global_rate_limit=enable_global_rate_limit, rate_limit=rate_limit) ) else: raise NotImplementedError("Process mode is not implemented yet") class ImageZoomInTool(BaseTool): """A tool for zooming in on an image by cropping it based on a bounding box. This tool provides a zoom-in functionality by cropping a region from an image, with rate limiting and concurrent execution support through Ray. Methods: get_openai_tool_schema: Return the tool schema in OpenAI format create: Create a tool instance for a trajectory execute: Execute the zoom-in operation calc_reward: Calculate the reward with respect to tool state release: Release the tool instance """ MIN_DIMENSION = 28 def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): """ _tool_schema = OpenAIFunctionToolSchema.model_validate({ "type": "function", "function": { "name": "image_zoom_in_tool", "description": ( "Zoom in on a specific region of an image by cropping it based on a bounding box (bbox) and an " "optional object label." ), "parameters": { "type": "object", "properties": { "bbox_2d": { "type": "array", "items":{"type":"number"}, "minItems":4, "maxItems":4, "description": ( "The bounding box of the region to zoom in, as [x1, y1, x2, y2], where (x1, y1) is " "the top-left corner and (x2, y2) is the bottom-right corner." ), }, "label": { "type": "string", "description": "The name or label of the object in the specified bounding box (optional).", }, }, "required": ["bbox_2d"], }, } }) """ super().__init__(config, tool_schema) self._instance_dict = {} # Worker and rate limiting configuration self.num_workers = config.get("num_workers", 20) self.rate_limit = config.get("rate_limit", 50) self.timeout = config.get("timeout", 30) self.enable_global_rate_limit = config.get("enable_global_rate_limit", True) self.execution_pool = init_visual_execution_pool( num_workers=self.num_workers, enable_global_rate_limit=self.enable_global_rate_limit, rate_limit=self.rate_limit, mode=PoolMode.ThreadMode, ) logger.info(f"Initialized ImageZoomInTool with config: {config}") def _validate_bbox(self, left: float, top: float, right: float, bottom: float) -> bool: """Validate the bounding box dimensions and aspect ratio.""" try: if not (left < right and top < bottom): logger.warning(f"Invalid bbox shape: left={left}, top={top}, right={right}, bottom={bottom}") return False height = bottom - top width = right - left # Prevent division by zero for zero-sized boxes if min(height, width) == 0: logger.warning(f"Bbox has zero width or height: left={left}, top={top}, right={right}, bottom={bottom}") return False if max(height, width) / min(height, width) > 100: logger.warning(f"Bbox aspect ratio > 100: left={left}, top={top}, right={right}, bottom={bottom}") return False return True except Exception as e: logger.warning(f"Bbox validation error: {e}") return False def _maybe_resize_bbox(self, bbox_2d: list[float], image_width: int, image_height: int) -> Optional[list[float]]: """ Clamp, validate, and potentially resize a bounding box. This function ensures the final bounding box is within image bounds and meets the minimum dimension requirements. If the initial box is too small, it attempts to expand it from its center. It performs a final check to guarantee the output dimensions are valid. Returns: A valid bounding box as a list of coordinates, or None if validation fails. """ left, top, right, bottom = bbox_2d # 1. Clamp the initial bounding box to the image dimensions. left = max(0.0, float(left)) top = max(0.0, float(top)) right = min(float(image_width), float(right)) bottom = min(float(image_height), float(bottom)) # 2. If clamped bbox is invalid, return immediately. if not self._validate_bbox(left, top, right, bottom): return None current_bbox = [left, top, right, bottom] height = bottom - top width = right - left # 3. If the box is too small, attempt to resize it. if height < self.MIN_DIMENSION or width < self.MIN_DIMENSION: logger.info(f"Bbox {width}x{height} is smaller than {self.MIN_DIMENSION}, attempting resize.") center_x = (left + right) / 2.0 center_y = (top + bottom) / 2.0 min_dim = min(height, width) if min_dim == 0: # Safeguard for zero-area boxes return None # 1. Calculate the target dimensions to make the smallest side MIN_DIMENSION. ratio = self.MIN_DIMENSION / min_dim target_width = width * ratio target_height = height * ratio # 2. If the target size is larger than the image, scale it down to fit. # This preserves the aspect ratio while respecting image boundaries. if target_width > image_width: scale_down = image_width / target_width target_width = image_width target_height *= scale_down if target_height > image_height: scale_down = image_height / target_height target_height = image_height target_width *= scale_down # 3. Determine the coordinates for the box centered on the original center. new_half_width = target_width / 2.0 new_half_height = target_height / 2.0 new_left = center_x - new_half_width new_top = center_y - new_half_height # 4. Shift the box if it extends beyond the image boundaries to keep its size. if new_left < 0: new_left = 0 if new_top < 0: new_top = 0 if new_left + target_width > image_width: new_left = image_width - target_width if new_top + target_height > image_height: new_top = image_height - target_height new_right = new_left + target_width new_bottom = new_top + target_height # Use floor and ceil for final integer coordinates. current_bbox = [floor(new_left), floor(new_top), ceil(new_right), ceil(new_bottom)] # 4. Final validation on the resulting bounding box (either original or resized). final_left, final_top, final_right, final_bottom = current_bbox if not self._validate_bbox(final_left, final_top, final_right, final_bottom): logger.warning(f"Final bbox is invalid after processing: {current_bbox}") return None final_height = floor(final_bottom) - floor(final_top) final_width = floor(final_right) - floor(final_left) if final_height < self.MIN_DIMENSION or final_width < self.MIN_DIMENSION: logger.warning( f"Final bbox size ({final_width}x{final_height}) are still smaller than minimum ({self.MIN_DIMENSION})." f"Original bbox: {bbox_2d}, original image size: {image_width}x{image_height}" ) return None return current_bbox def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: return self.tool_schema async def create(self, instance_id: Optional[str] = None, **kwargs) -> tuple[str, ToolResponse]: """ Creates a new instance for image zoom-in tool. This method initializes a new session for an image, which can then be used for operations like zooming. It fetches the image from various sources and stores it internally. Args: instance_id: An optional unique identifier for the instance. If not provided, a new UUID will be generated. **kwargs: Should contain 'image' key with image data, or 'create_kwargs' containing {'image': image_data}. Image can be one of the following: - A PIL.Image.Image object. - A string containing an HTTP or HTTPS URL. - A string containing a local file path. - A string containing a file URI (e.g., "file:///path/to/image.jpg"). - A string containing a base64-encoded image in the format of "data:image/jpeg;base64,..." Returns: Tuple of (instance_id, ToolResponse) """ if instance_id is None: instance_id = str(uuid4()) # Handle create_kwargs parameter if passed create_kwargs = kwargs.get("create_kwargs", {}) if create_kwargs: kwargs.update(create_kwargs) # Get image from kwargs image = kwargs.get("image") if image is None: raise ValueError("Missing required 'image' parameter in kwargs") img = fetch_image({"image": image}) self._instance_dict[instance_id] = { "image": img, "response": "", "reward": 0.0, } return instance_id, ToolResponse() async def execute(self, instance_id: str, parameters: dict[str, Any], **kwargs) -> tuple[ToolResponse, float, dict]: bbox_2d = parameters.get("bbox_2d") label = parameters.get("label", "") if not bbox_2d or len(bbox_2d) != 4: return ( ToolResponse(text="Error: bbox_2d parameter is missing or not a list of 4 numbers."), -0.05, {"success": False}, ) instance_data = self._instance_dict[instance_id] image = instance_data["image"] image_width, image_height = image.size try: resized_bbox = self._maybe_resize_bbox(bbox_2d, image_width=image_width, image_height=image_height) if resized_bbox is None: error_msg = ( f"Error: The specified bounding box {bbox_2d} is invalid or results in a crop smaller than " f"the minimum size of {self.MIN_DIMENSION}x{self.MIN_DIMENSION}." ) logger.warning(f"Tool execution failed: {error_msg}") return ToolResponse(text=error_msg), -0.05, {"success": False} cropped_image = image.crop(resized_bbox) logger.info(f"Cropped image size: {cropped_image.size}") except Exception as e: logger.error(f"Error processing image zoom-in: {e}") return ToolResponse(text=f"Error processing image zoom-in: {e}"), -0.05, {"success": False} response_text = f"Zoomed in on the image to the region {bbox_2d}." if label: response_text = f"Zoomed in on the image to the region {bbox_2d} with label {label}." return ( ToolResponse( image=[cropped_image], text=response_text, ), 0.0, {"success": True}, ) async def release(self, instance_id: str, **kwargs) -> None: if instance_id in self._instance_dict: del self._instance_dict[instance_id]
verl__tools__image_zoom_in_tool.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging import os from typing import Any, Optional from uuid import uuid4 from fastmcp.exceptions import ClientError from verl.tools.utils.mcp_clients.McpClientManager import ClientManager from verl.utils.rollout_trace import rollout_trace_op from .base_tool import BaseTool from .schemas import OpenAIFunctionToolSchema, ToolResponse logger = logging.getLogger(__name__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) class MCPBaseTool(BaseTool): def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): super().__init__(config, tool_schema) self._instance_dict = {} self.timeout = config.get("timeout", 30) # TODO(hechanghao): create a global client manager to manage the rate limit, client and pool logger.info(f"Initialized MCPBaseTool with config: {config}") def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: """Return the OpenAI tool schema.""" return self.tool_schema async def create(self, instance_id: Optional[str] = None, **kwargs) -> tuple[str, ToolResponse]: """Create a tool instance. Args: instance_id: The instance id of the tool. Returns: The instance id of the tool. tool_crtool_creation_response: The response of the tool when creating the instance. """ if instance_id is None: instance_id = str(uuid4()) self._instance_dict[instance_id] = { "response": "", "reward": [], } return instance_id, ToolResponse() async def _call_tool(self, instance_id, parameters) -> tuple[str, dict]: err_msg = "" metadata = {} try: call_tool_result = await ClientManager.call_tool(self.name, parameters, self.timeout) logger.debug(f"Tool result for instance {instance_id} with tool {self.name}: {call_tool_result.content}") result, metadata = self._parse_tool_result(call_tool_result.content) except ClientError as e: err_msg = f"\n Tool call failed: {e}" except ConnectionError as e: err_msg = f"\n Connection failed: {e}" except Exception as e: err_msg = f"\n An unexpected error occurred: {e}" finally: if err_msg: result = err_msg metadata["api_request_error"] = err_msg else: metadata["api_request_error"] = None return result, metadata @rollout_trace_op async def execute(self, instance_id: str, parameters: dict[str, Any], **kwargs) -> tuple[ToolResponse, float, dict]: if self.name == "" or self.name is None or parameters is None: error_msg = "Error: 'parameters' is missing or empty." logger.error(f"[MCPTool] {error_msg} Received tool name: {self.name}, parameters: {parameters}") return ToolResponse(text=json.dumps({"result": error_msg})), 0.0, {} try: result_text, metadata = await self._call_tool(instance_id, parameters) # Store results in instance dictionary self._instance_dict[instance_id]["reward"].append(result_text.strip()) # Convert metadata to metrics metrics = { "query_count": metadata.get("query_count", 0), "status": metadata.get("status", "unknown"), "total_results": metadata.get("total_results", 0), "api_request_error": metadata.get("api_request_error"), } return ToolResponse(text=result_text), 0.0, metrics except Exception as e: error_result = json.dumps({"result": f"Tool execution failed: {e}"}) logger.error(f"[MCPBaseTool] Execution failed: {e}") return ToolResponse(text=error_result), 0.0, {"error": str(e)} async def calc_reward(self, instance_id: str, **kwargs) -> str: return self._instance_dict[instance_id]["reward"] async def release(self, instance_id: str, **kwargs) -> None: if instance_id in self._instance_dict: del self._instance_dict[instance_id] def _parse_tool_result(self, content: list) -> tuple[str, dict]: tools_content = [part.text for part in filter(lambda x: x.type == "text", content)] return " ".join(tools_content), {}
verl__tools__mcp_base_tool.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging import os import re from verl.tools.mcp_base_tool import MCPBaseTool from .schemas import OpenAIFunctionToolSchema logger = logging.getLogger(__name__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) class MCPSearchTool(MCPBaseTool): def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): super().__init__(config, tool_schema) def _parse_tool_result(self, content: list) -> tuple[str, dict]: res = "" res_cnt = 0 query_list = [] metadata = { "api_request_error": "", "status": "unknown", "total_results": 0, } try: for part in content: if part.type != "text": continue text = part.text.replace("'", '"') query_match = re.search(r'query"\s*:\s*"([^"]+)"', text) query = query_match.group(1) if query_match else "" query_list.append(query) title_matches = re.findall(r'"title"\s*:', text) title_count = len(title_matches) results_match = re.search(r'"results"\s*:\s*(\[.*?\])', text, re.DOTALL) results_content = results_match.group(1) if results_match else "" res += results_content res_cnt += title_count except json.JSONDecodeError: err_msg = "json parse error." logger.error(err_msg) metadata["api_request_error"] = err_msg metadata["status"] = "error" # update metadata metadata["status"] = "success" metadata["queries"] = query_list metadata["query_count"] = len(query_list) metadata["total_results"] = res_cnt return res, metadata
verl__tools__mcp_search_tool.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import threading from contextlib import ExitStack from enum import Enum from typing import Any, Callable, Optional, TypeVar from uuid import uuid4 import ray from verl.tools.base_tool import BaseTool from verl.utils.reward_score.sandbox_fusion.utils import _process_single_case from verl.utils.rollout_trace import rollout_trace_op from .schemas import OpenAIFunctionToolSchema, ToolResponse logger = logging.getLogger(__name__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) T = TypeVar("T") class PoolMode(Enum): ThreadMode = 1 ProcessMode = 2 @ray.remote(concurrency_groups={"acquire": 1, "release": 10}) class TokenBucketWorker: def __init__(self, rate_limit: int): self.rate_limit = rate_limit # this only used for observalability self.current_count = 0 self._semaphore = threading.Semaphore(rate_limit) @ray.method(concurrency_group="acquire") def acquire(self): self._semaphore.acquire() self.current_count += 1 @ray.method(concurrency_group="release") def release(self): self._semaphore.release() self.current_count -= 1 def get_current_count(self): return self.current_count class ExecutionWorker: def __init__(self, enable_global_rate_limit=True, rate_limit=10): self.rate_limit_worker = self._init_rate_limit(rate_limit) if enable_global_rate_limit else None def _init_rate_limit(self, rate_limit): # TODO validation for rate_limit # A Singleton Rate Limitor return TokenBucketWorker.options(name="rate-limiter", get_if_exists=True).remote(rate_limit) def ping(self): return True def execute(self, fn: Callable[..., T], *fn_args, **fn_kwargs) -> T: with ExitStack() as stack: stack.callback(self.rate_limit_worker.release.remote) ray.get(self.rate_limit_worker.acquire.remote()) try: return fn(*fn_args, **fn_kwargs) except Exception as e: # TODO we should make this available to the tool caller logger.warning(f"Error when executing code: {e}") def init_execution_pool( num_workers: int, enable_global_rate_limit=True, rate_limit=10, mode: PoolMode = PoolMode.ThreadMode ): if mode == PoolMode.ThreadMode: return ( ray.remote(ExecutionWorker) .options(max_concurrency=num_workers) .remote(enable_global_rate_limit=enable_global_rate_limit, rate_limit=rate_limit) ) else: raise NotImplementedError("Process mode is not implemented yet") # return ray.util.multiprocessing.Pool(processes=num_workers) class SandboxFusionTool(BaseTool): """A tool for executing the code using sanbox fusion image. - `get_openai_tool_schema`: return the tool schema in OpenAI format. - `create`: create a tool instance for a trajectory. - `execute`: execute the tool. - `calc_reward`: calculate the reward respect to tool state. - `release`: release the tool instance. """ def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): """ _tool_schema = OpenAIFunctionToolSchema.model_validate({ "type": "function", "function": { "name": "code_interpreter", "description": "A tool for execute code", "parameters": { "type": "object", "properties": { "code": { "type": "string", "description": "code needs to be execute and grad", }, }, "required": ["code"], }, } }) """ super().__init__(config, tool_schema) self._instance_dict = {} # TODO: better documentation for the config self.num_workers = config.get("num_workers", 10) self.rate_limit = config.get("rate_limit", 10) self.default_timeout = config.get("default_timeout", 30) self.default_language = config.get("default_language", "python") self.enable_global_rate_limit = config.get("enable_global_rate_limit", True) self.execution_pool = init_execution_pool( num_workers=self.num_workers, enable_global_rate_limit=self.enable_global_rate_limit, rate_limit=self.rate_limit, mode=PoolMode.ThreadMode, ) self.sandbox_fusion_url = config.get("sandbox_fusion_url", "") self.memory_limit_mb = config.get("memory_limit_mb", 1024) if self.sandbox_fusion_url == "": raise ValueError("sandbox_fusion_url is not set") log_msg = f"Init SandboxFusionTool with config: {config}" logger.info(log_msg) def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: return self.tool_schema async def create( self, instance_id: Optional[str] = None, ground_truth: Optional[str] = None, **kwargs ) -> tuple[str, ToolResponse]: if instance_id is None: instance_id = str(uuid4()) self._instance_dict[instance_id] = { "response": "", "ground_truth": ground_truth, "reward": [], } return instance_id, ToolResponse() @rollout_trace_op async def execute(self, instance_id: str, parameters: dict[str, Any], **kwargs) -> tuple[ToolResponse, float, dict]: code = parameters.get("code", "") timeout = parameters.get("timeout", self.default_timeout) language = parameters.get("language", self.default_language) if not isinstance(code, str): code = str(code) result = await self.execution_pool.execute.remote(self.execute_code, instance_id, code, timeout, language) # sandbox has no score or metrics, use Nones if isinstance(result, ToolResponse): return result, None, None return ToolResponse(text=None if result is None else str(result)), None, None def execute_code(self, instance_id, code, timeout=30, language="python"): result_status, metadata = _process_single_case( 0, None, None, self.sandbox_fusion_url, code, timeout, self.memory_limit_mb, language ) # we should always expect this since we don't have correct answer if metadata["run_status"] == "Finished": actual_output = metadata["stdout"] + metadata["stderr"] logger.debug(f"actual_output from sandbox fusion: {actual_output},{instance_id}") return ToolResponse(text=actual_output) else: return ToolResponse(text="no stdout here") async def calc_reward(self, instance_id: str, **kwargs) -> str: return self._instance_dict[instance_id]["reward"] async def release(self, instance_id: str, **kwargs) -> None: del self._instance_dict[instance_id]
verl__tools__sandbox_fusion_tools.py
# Copyright 2023-2024 SGLang Team # Copyright 2025 ModelBest Inc. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from typing import Any, Literal from pydantic import BaseModel, Field, model_validator class OpenAIFunctionPropertySchema(BaseModel): """The schema of a parameter in OpenAI format.""" type: str description: str | None = None enum: list[str] | None = None class OpenAIFunctionParametersSchema(BaseModel): """The schema of parameters in OpenAI format.""" type: str properties: dict[str, OpenAIFunctionPropertySchema] required: list[str] class OpenAIFunctionSchema(BaseModel): """The schema of a function in OpenAI format.""" name: str description: str parameters: OpenAIFunctionParametersSchema = Field( default_factory=lambda: OpenAIFunctionParametersSchema(type="object", properties={}, required=[]) ) strict: bool = False class OpenAIFunctionToolSchema(BaseModel): """The schema of a tool in OpenAI format.""" type: str function: OpenAIFunctionSchema class OpenAIFunctionParsedSchema(BaseModel): """The parsed schema of a tool in OpenAI format.""" name: str arguments: str # JSON string class OpenAIFunctionCallSchema(BaseModel): """The parsed schema of a tool in OpenAI format.""" name: str arguments: dict[str, Any] @staticmethod def from_openai_function_parsed_schema( parsed_schema: OpenAIFunctionParsedSchema, ) -> tuple["OpenAIFunctionCallSchema", bool]: has_decode_error = False try: arguments = json.loads(parsed_schema.arguments) except json.JSONDecodeError: arguments = {} has_decode_error = True # If the arguments is not a dict, it means the arguments is not a valid JSON string if not isinstance(arguments, dict): arguments = {} has_decode_error = True return OpenAIFunctionCallSchema(name=parsed_schema.name, arguments=arguments), has_decode_error class OpenAIFunctionToolCall(BaseModel): """The tool call in OpenAI format.""" id: str type: Literal["function"] = "function" function: OpenAIFunctionCallSchema class ToolResponse(BaseModel): """The response from a tool execution.""" text: str | None = None image: list[Any] | None = None video: list[Any] | None = None @model_validator(mode="before") @classmethod def initialize_request(cls, values): if "image" in values and not isinstance(values["image"], list): raise ValueError( f"Image must be a list, but got {type(values['image'])}. Please check the tool.execute(). " f"For single images, wrap in a list: [image]. " f"Example: {{'image': [img1]}} or {{'image': [img1, img2, ...]}}." ) if "video" in values and not isinstance(values["video"], list): raise ValueError( f"Video must be a list, but got {type(values['video'])}. Please check the tool.execute(). " f"For single videos, wrap in a list: [video]. " f"Example: {{'video': [video1]}} or {{'video': [video1, video2, ...]}}." ) return values def is_empty(self) -> bool: return not self.text and not self.image and not self.video def is_text_only(self) -> bool: return self.text and not self.image and not self.video
verl__tools__schemas.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023-2024 SGLang Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging import os import threading from contextlib import ExitStack from enum import Enum from typing import Any, Callable, Optional, TypeVar from uuid import uuid4 import ray import ray.actor from verl.tools.utils.search_r1_like_utils import perform_single_search_batch from verl.utils.rollout_trace import rollout_trace_op from .base_tool import BaseTool from .schemas import OpenAIFunctionToolSchema, ToolResponse logger = logging.getLogger(__name__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) T = TypeVar("T") # Adapted from verl/tools/sandbox_fusion_tools.py class PoolMode(Enum): """Execution pool mode enumeration.""" ThreadMode = 1 ProcessMode = 2 @ray.remote(concurrency_groups={"acquire": 1, "release": 10}) class TokenBucketWorker: """Ray actor for rate limiting using token bucket algorithm.""" def __init__(self, rate_limit: int): self.rate_limit = rate_limit self.current_count = 0 # For observability self._semaphore = threading.Semaphore(rate_limit) @ray.method(concurrency_group="acquire") def acquire(self): """Acquire a token from the bucket.""" self._semaphore.acquire() self.current_count += 1 @ray.method(concurrency_group="release") def release(self): """Release a token back to the bucket.""" self._semaphore.release() self.current_count -= 1 def get_current_count(self): """Get current number of acquired tokens.""" return self.current_count class SearchExecutionWorker: """Worker for executing search operations with optional rate limiting.""" def __init__(self, enable_global_rate_limit=True, rate_limit=10): self.rate_limit_worker = self._init_rate_limit(rate_limit) if enable_global_rate_limit else None def _init_rate_limit(self, rate_limit): """Initialize singleton rate limiter.""" return TokenBucketWorker.options(name="rate-limiter", get_if_exists=True).remote(rate_limit) def ping(self): """Health check method.""" return True def execute(self, fn: Callable[..., T], *fn_args, **fn_kwargs) -> T: """Execute function with optional rate limiting.""" if self.rate_limit_worker: with ExitStack() as stack: stack.callback(self.rate_limit_worker.release.remote) ray.get(self.rate_limit_worker.acquire.remote()) try: return fn(*fn_args, **fn_kwargs) except Exception as e: # TODO we should make this available to the tool caller logger.warning(f"Error when executing search: {e}") else: return fn(*fn_args, **fn_kwargs) def init_search_execution_pool( num_workers: int, enable_global_rate_limit=True, rate_limit=10, mode: PoolMode = PoolMode.ThreadMode ): """Initialize search execution pool.""" if mode == PoolMode.ThreadMode: return ( ray.remote(SearchExecutionWorker) .options(max_concurrency=num_workers) .remote(enable_global_rate_limit=enable_global_rate_limit, rate_limit=rate_limit) ) else: raise NotImplementedError("Process mode is not implemented yet") class SearchTool(BaseTool): """Search tool for retrieving information using external retrieval services. This tool provides search functionality with rate limiting and concurrent execution support through Ray. It integrates with external retrieval services to perform semantic search operations. Methods: get_openai_tool_schema: Return the tool schema in OpenAI format create: Create a tool instance for a trajectory execute: Execute the search tool calc_reward: Calculate the reward with respect to tool state release: Release the tool instance """ def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema): """Initialize SearchTool with configuration and schema. Args: config: Configuration dictionary containing tool settings tool_schema: OpenAI function tool schema definition Example tool_schema: { "type": "function", "function": { "name": "search", "description": "Searches for relevant information based on queries.", "parameters": { "type": "object", "properties": { "query_list": { "type": "array", "items": {"type": "string"}, "description": "List of search queries" } }, "required": ["query_list"] } } } """ super().__init__(config, tool_schema) self._instance_dict = {} # Worker and rate limiting configuration self.num_workers = config.get("num_workers", 120) self.rate_limit = config.get("rate_limit", 120) self.timeout = config.get("timeout", 30) self.enable_global_rate_limit = config.get("enable_global_rate_limit", True) self.execution_pool = init_search_execution_pool( num_workers=self.num_workers, enable_global_rate_limit=self.enable_global_rate_limit, rate_limit=self.rate_limit, mode=PoolMode.ThreadMode, ) # Retrieval service configuration self.retrieval_service_url = config.get("retrieval_service_url") assert self.retrieval_service_url, "Configuration must include 'retrieval_service_url'" self.topk = config.get("topk", 3) if self.retrieval_service_url == "": raise ValueError("retrieval_service_url is not set") logger.info(f"Initialized SearchTool with config: {config}") def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema: """Return the OpenAI tool schema.""" return self.tool_schema async def create(self, instance_id: Optional[str] = None, **kwargs) -> tuple[str, ToolResponse]: """Create a tool instance. Args: instance_id: The instance id of the tool. Returns: The instance id of the tool. tool_creation_response: The response of the tool when creating the instance. """ if instance_id is None: instance_id = str(uuid4()) self._instance_dict[instance_id] = { "response": "", "reward": [], } return instance_id, ToolResponse() def execute_search(self, instance_id: str, query_list: list, retrieval_service_url: str, topk: int, timeout: int): """Execute search operation using retrieval service. Args: instance_id: Tool instance ID query_list: List of search queries retrieval_service_url: URL of the retrieval service topk: Number of top results to return timeout: Request timeout in seconds Returns: Tuple of (result_text, metadata) """ result_text, metadata = perform_single_search_batch( retrieval_service_url=retrieval_service_url, query_list=query_list, topk=topk, concurrent_semaphore=None, # Ray handles concurrency control timeout=timeout, ) logger.debug(f"Search result for instance {instance_id}: {result_text}") return result_text, metadata @rollout_trace_op async def execute(self, instance_id: str, parameters: dict[str, Any], **kwargs) -> tuple[ToolResponse, float, dict]: """Execute the search tool. Args: instance_id: The instance ID of the tool parameters: Tool parameters containing query_list and optional timeout Returns: tool_response, tool_reward_score, tool_metrics tool_response: The response str of the tool. tool_reward_score: The step reward score of the tool. tool_metrics: The metrics of the tool. """ timeout = self.timeout query_list_from_params = parameters.get("query_list") if not query_list_from_params or not isinstance(query_list_from_params, list): error_msg = "Error: 'query_list' is missing, empty, or not a list in parameters." logger.error(f"[SearchTool] {error_msg} Received parameters: {parameters}") return ToolResponse(text=json.dumps({"result": error_msg})), 0.0, {} # Execute search using Ray execution pool try: result_text, metadata = await self.execution_pool.execute.remote( self.execute_search, instance_id, query_list_from_params, self.retrieval_service_url, self.topk, timeout ) # Store results in instance dictionary self._instance_dict[instance_id]["reward"].append(result_text.strip()) # Convert metadata to metrics metrics = { "query_count": metadata.get("query_count", 0), "status": metadata.get("status", "unknown"), "total_results": metadata.get("total_results", 0), "api_request_error": metadata.get("api_request_error"), } return ToolResponse(text=result_text), 0.0, metrics except Exception as e: error_result = json.dumps({"result": f"Search execution failed: {e}"}) logger.error(f"[SearchTool] Execution failed: {e}") return ToolResponse(text=error_result), 0.0, {"error": str(e)} async def calc_reward(self, instance_id: str, **kwargs) -> str: return self._instance_dict[instance_id]["reward"] async def release(self, instance_id: str, **kwargs) -> None: if instance_id in self._instance_dict: del self._instance_dict[instance_id]
verl__tools__search_tool.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import json import logging from typing import Any from fastmcp import Client from fastmcp.client.transports import SSETransport from verl.tools.utils.mcp_clients.utils import TokenBucket, mcp2openai logger = logging.getLogger(__name__) class MCPClientManager: rootServerName = "mcpServers" initialized = False clients = [] tool_client_mapping = {} rate_limiter = None async def initialize(self, config_path, rate_limit: float = 10.0): if self.initialized: return """Initialize the MCP Client Manager and start all clients""" result = self._load_config(config_path) servers = result[self.rootServerName] exclude_sse_servers = {self.rootServerName: {}} for server_name in servers.keys(): server = servers[server_name] if "auth_token" in server: transport = SSETransport(url=server["url"], headers={"Authorization": f"Bearer {server['auth_token']}"}) client = Client(transport) self.clients.append(client) else: exclude_sse_servers[self.rootServerName][server_name] = server if exclude_sse_servers[self.rootServerName]: self.clients.append(Client(exclude_sse_servers)) # Initialize rate limiter self.rate_limiter = TokenBucket(rate_limit) self.initialized = True async def call_tool(self, tool_name, parameters, timeout): # Apply rate limiting while not self.rate_limiter.acquire(): await asyncio.sleep(0.1) client = self.get_client_with_tool_name(tool_name) async with client: return await client.call_tool_mcp(tool_name, parameters) async def fetch_tool_schemas(self, tool_selected_list: list[str]) -> list[dict]: tool_schemas = [] for client in self.clients: async with client: tools = await client.list_tools_mcp() for tool in tools.tools: if not tool_selected_list: self.tool_client_mapping[tool.name] = client tool_schemas.append(mcp2openai(tool)) elif tool.name in tool_selected_list: self.tool_client_mapping[tool.name] = client tool_schemas.append(mcp2openai(tool)) return tool_schemas def get_client_with_tool_name(self, tool_name: str): return self.tool_client_mapping[tool_name] def _load_config(self, file: str) -> dict[str, Any]: try: with open(file) as f: return json.load(f) except FileNotFoundError: logger.warning(f'the "{file}" file was not found') except Exception: logger.error(f'there was an error reading the "{file}" file') return {} ClientManager = MCPClientManager()
verl__tools__utils__mcp_clients__McpClientManager.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import threading import time from mcp import Tool logger = logging.getLogger(__file__) class TokenBucket: def __init__(self, rate_limit: float): self.rate_limit = rate_limit # tokens per second self.tokens = rate_limit self.last_update = time.time() self.lock = threading.Lock() def acquire(self) -> bool: with self.lock: now = time.time() # Add new tokens based on time elapsed new_tokens = (now - self.last_update) * self.rate_limit self.tokens = min(self.rate_limit, self.tokens + new_tokens) self.last_update = now if self.tokens >= 1: self.tokens -= 1 return True return False def mcp2openai(mcp_tool: Tool) -> dict: """Convert a MCP Tool to an OpenAI ChatCompletionTool.""" openai_format = { "type": "function", "function": { "name": mcp_tool.name, "description": mcp_tool.description, "parameters": mcp_tool.inputSchema, "strict": False, }, } if not openai_format["function"]["parameters"].get("required", None): openai_format["function"]["parameters"]["required"] = [] return openai_format
verl__tools__utils__mcp_clients__utils.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023-2024 SGLang Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging import threading import time import traceback import uuid from typing import Any, Optional import requests DEFAULT_TIMEOUT = 30 # Default search request timeout MAX_RETRIES = 10 INITIAL_RETRY_DELAY = 1 API_TIMEOUT = 10 logger = logging.getLogger(__name__) def call_search_api( retrieval_service_url: str, query_list: list[str], topk: int = 3, return_scores: bool = True, timeout: int = DEFAULT_TIMEOUT, ) -> tuple[Optional[dict[str, Any]], Optional[str]]: """ Calls the remote search API to perform retrieval with retry logic for various errors, using increasing delay between retries. Logs internal calls with a unique ID. Args: retrieval_service_url: The URL of the retrieval service API. query_list: List of search queries. topk: Number of top results to return. return_scores: Whether to return scores. timeout: Request timeout in seconds. Returns: A tuple (response_json, error_message). If successful, response_json is the API's returned JSON object, error_message is None. If failed after retries, response_json is None, error_message contains the error information. """ request_id = str(uuid.uuid4()) log_prefix = f"[Search Request ID: {request_id}] " payload = {"queries": query_list, "topk": topk, "return_scores": return_scores} headers = {"Content-Type": "application/json", "Accept": "application/json"} last_error = None for attempt in range(MAX_RETRIES): try: logger.info( f"{log_prefix}Attempt {attempt + 1}/{MAX_RETRIES}: Calling search API at {retrieval_service_url}" ) response = requests.post( retrieval_service_url, headers=headers, json=payload, timeout=timeout, ) # Check for Gateway Timeout (504) and other server errors for retrying if response.status_code in [500, 502, 503, 504]: last_error = ( f"{log_prefix}API Request Error: Server Error ({response.status_code}) on attempt " f"{attempt + 1}/{MAX_RETRIES}" ) logger.warning(last_error) if attempt < MAX_RETRIES - 1: delay = INITIAL_RETRY_DELAY * (attempt + 1) logger.info(f"{log_prefix}Retrying after {delay} seconds...") time.sleep(delay) continue # Check for other HTTP errors (e.g., 4xx) response.raise_for_status() # If successful (status code 2xx) logger.info(f"{log_prefix}Search API call successful on attempt {attempt + 1}") return response.json(), None except requests.exceptions.ConnectionError as e: last_error = f"{log_prefix}Connection Error: {e}" logger.warning(last_error) if attempt < MAX_RETRIES - 1: delay = INITIAL_RETRY_DELAY * (attempt + 1) logger.info(f"{log_prefix}Retrying after {delay} seconds...") time.sleep(delay) continue except requests.exceptions.Timeout as e: last_error = f"{log_prefix}Timeout Error: {e}" logger.warning(last_error) if attempt < MAX_RETRIES - 1: delay = INITIAL_RETRY_DELAY * (attempt + 1) logger.info(f"{log_prefix}Retrying after {delay} seconds...") time.sleep(delay) continue except requests.exceptions.RequestException as e: last_error = f"{log_prefix}API Request Error: {e}" break # Exit retry loop on other request errors except json.JSONDecodeError as e: raw_response_text = response.text if "response" in locals() else "N/A" last_error = f"{log_prefix}API Response JSON Decode Error: {e}, Response: {raw_response_text[:200]}" break # Exit retry loop on JSON decode errors except Exception as e: last_error = f"{log_prefix}Unexpected Error: {e}" break # Exit retry loop on other unexpected errors # If loop finishes without returning success, return the last recorded error logger.error(f"{log_prefix}Search API call failed. Last error: {last_error}") return None, last_error.replace(log_prefix, "API Call Failed: ") if last_error else "API Call Failed after retries" def _passages2string(retrieval_result): """Convert retrieval results to formatted string.""" format_reference = "" for idx, doc_item in enumerate(retrieval_result): content = doc_item["document"]["contents"] title = content.split("\n")[0] text = "\n".join(content.split("\n")[1:]) format_reference += f"Doc {idx + 1} (Title: {title})\n{text}\n\n" return format_reference.strip() def perform_single_search_batch( retrieval_service_url: str, query_list: list[str], topk: int = 3, concurrent_semaphore: Optional[threading.Semaphore] = None, timeout: int = DEFAULT_TIMEOUT, ) -> tuple[str, dict[str, Any]]: """ Performs a single batch search for multiple queries (original search tool behavior). Args: retrieval_service_url: The URL of the retrieval service API. query_list: List of search queries. topk: Number of top results to return. concurrent_semaphore: Optional semaphore for concurrency control. timeout: Request timeout in seconds. Returns: A tuple (result_text, metadata). result_text: The search result JSON string. metadata: Metadata dictionary for the batch search. """ logger.info(f"Starting batch search for {len(query_list)} queries.") api_response = None error_msg = None try: if concurrent_semaphore: with concurrent_semaphore: api_response, error_msg = call_search_api( retrieval_service_url=retrieval_service_url, query_list=query_list, topk=topk, return_scores=True, timeout=timeout, ) else: api_response, error_msg = call_search_api( retrieval_service_url=retrieval_service_url, query_list=query_list, topk=topk, return_scores=True, timeout=timeout, ) except Exception as e: error_msg = f"API Request Exception during batch search: {e}" logger.error(f"Batch search: {error_msg}") traceback.print_exc() metadata = { "query_count": len(query_list), "queries": query_list, "api_request_error": error_msg, "api_response": None, "status": "unknown", "total_results": 0, "formatted_result": None, } result_text = json.dumps({"result": "Search request failed or timed out after retries."}, ensure_ascii=False) if error_msg: metadata["status"] = "api_error" result_text = json.dumps({"result": f"Search error: {error_msg}"}, ensure_ascii=False) logger.error(f"Batch search: API error occurred: {error_msg}") elif api_response: logger.debug(f"Batch search: API Response: {api_response}") metadata["api_response"] = api_response try: raw_results = api_response.get("result", []) if raw_results: pretty_results = [] total_results = 0 for retrieval in raw_results: formatted = _passages2string(retrieval) pretty_results.append(formatted) total_results += len(retrieval) if isinstance(retrieval, list) else 1 final_result = "\n---\n".join(pretty_results) result_text = json.dumps({"result": final_result}, ensure_ascii=False) metadata["status"] = "success" metadata["total_results"] = total_results metadata["formatted_result"] = final_result logger.info(f"Batch search: Successful, got {total_results} total results") else: result_text = json.dumps({"result": "No search results found."}, ensure_ascii=False) metadata["status"] = "no_results" metadata["total_results"] = 0 logger.info("Batch search: No results found") except Exception as e: error_msg = f"Error processing search results: {e}" result_text = json.dumps({"result": error_msg}, ensure_ascii=False) metadata["status"] = "processing_error" logger.error(f"Batch search: {error_msg}") else: metadata["status"] = "unknown_api_state" result_text = json.dumps( {"result": "Unknown API state (no response and no error message)."}, ensure_ascii=False ) logger.error("Batch search: Unknown API state.") return result_text, metadata
verl__tools__utils__search_r1_like_utils.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import importlib import logging import os import sys import threading from enum import Enum from omegaconf import OmegaConf from verl.tools.schemas import OpenAIFunctionToolSchema logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) class ToolType(Enum): NATIVE = "native" MCP = "mcp" async def initialize_mcp_tool(tool_cls, tool_config) -> list: from verl.tools.utils.mcp_clients.McpClientManager import ClientManager tool_list = [] mcp_servers_config_path = tool_config.mcp.mcp_servers_config_path tool_selected_list = tool_config.mcp.tool_selected_list if "tool_selected_list" in tool_config.mcp else None await ClientManager.initialize(mcp_servers_config_path, tool_config.config.rate_limit) # Wait for MCP client to be ready max_retries = 10 retry_interval = 2 # seconds for i in range(max_retries): tool_schemas = await ClientManager.fetch_tool_schemas(tool_selected_list) if tool_schemas: break if i < max_retries - 1: logger.debug(f"Waiting for MCP client to be ready, attempt {i + 1}/{max_retries}") await asyncio.sleep(retry_interval) else: raise RuntimeError("Failed to initialize MCP tools after maximum retries") # mcp registry assert len(tool_schemas), "mcp tool is empty" for tool_schema_dict in tool_schemas: logger.debug(f"tool_schema_dict: {tool_schema_dict}") tool_schema = OpenAIFunctionToolSchema.model_validate(tool_schema_dict) tool = tool_cls( config=OmegaConf.to_container(tool_config.config, resolve=True), tool_schema=tool_schema, ) tool_list.append(tool) return tool_list def get_tool_class(cls_name): module_name, class_name = cls_name.rsplit(".", 1) if module_name not in sys.modules: spec = importlib.util.find_spec(module_name) module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) else: module = sys.modules[module_name] tool_cls = getattr(module, class_name) return tool_cls def initialize_tools_from_config(tools_config_file): """Initialize tools from config file. Supports both NATIVE and MCP tool types. For MCP tools, a temporary event loop is created only when needed and properly closed after use to prevent memory leaks. """ tools_config = OmegaConf.load(tools_config_file) tool_list = [] # Lazy initialization for MCP support - only create event loop when needed tmp_event_loop = None thread = None def get_mcp_event_loop(): """Lazily create event loop and thread for MCP tools.""" nonlocal tmp_event_loop, thread if tmp_event_loop is None: tmp_event_loop = asyncio.new_event_loop() thread = threading.Thread(target=tmp_event_loop.run_forever, name="mcp tool list fetcher", daemon=True) thread.start() return tmp_event_loop def run_coroutine(coroutine): """Run coroutine in the MCP event loop.""" loop = get_mcp_event_loop() future = asyncio.run_coroutine_threadsafe(coroutine, loop) return future.result() try: for tool_config in tools_config.tools: cls_name = tool_config.class_name tool_type = ToolType(tool_config.config.type) tool_cls = get_tool_class(cls_name) match tool_type: case ToolType.NATIVE: if tool_config.get("tool_schema", None) is None: tool_schema = None else: tool_schema_dict = OmegaConf.to_container(tool_config.tool_schema, resolve=True) tool_schema = OpenAIFunctionToolSchema.model_validate(tool_schema_dict) tool = tool_cls( config=OmegaConf.to_container(tool_config.config, resolve=True), tool_schema=tool_schema, ) tool_list.append(tool) case ToolType.MCP: mcp_tools = run_coroutine(initialize_mcp_tool(tool_cls, tool_config)) tool_list.extend(mcp_tools) case _: raise NotImplementedError finally: # Properly cleanup event loop if it was created if tmp_event_loop is not None: # stop first and then close tmp_event_loop.call_soon_threadsafe(tmp_event_loop.stop) if thread is not None and thread.is_alive(): thread.join(timeout=5.0) tmp_event_loop.close() return tool_list
verl__tools__utils__tool_registry.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass, field from typing import Any, Optional from verl.base_config import BaseConfig __all__ = ["AlgoConfig", "FilterGroupsConfig", "KLControlConfig", "RolloutCorrectionConfig"] @dataclass class KLControlConfig(BaseConfig): """Configuration for KL control. The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config. Args: type (str): Type of KL control. Can be "fixed" or "adaptive". kl_coef (float): Initial coefficient for KL penalty. horizon (int): Horizon value for adaptive controller. target_kl (float): Target KL divergence for adaptive controller. """ type: str = "fixed" kl_coef: float = 0.001 horizon: int = 10000 target_kl: float = 0.1 @dataclass class FilterGroupsConfig(BaseConfig): """Configuration for filter groups (used in DAPO and Entropy). The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config. Args: enable (bool): Whether to enable filter groups. metric (Optional[str]): Metric to use for filtering: "acc", "score", "seq_reward", "seq_final_reward", etc. max_num_gen_batches (int): Non-positive values mean no upper limit. """ enable: bool = False metric: Optional[str] = None max_num_gen_batches: int = 0 @dataclass class RolloutCorrectionConfig(BaseConfig): """Configuration for Rollout Correction (addresses off-policy issues in RL training). The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config. Rollout Correction handles off-policiness from multiple sources: 1. Policy mismatch: Rollout policy (e.g., vLLM BF16) vs Training policy (e.g., FSDP FP32) 2. Model update staleness: Rollout data collected from older policy checkpoints 3. General off-policy scenarios: Any distribution shift between data collection and training For more details, see: "When Speed Kills Stability: Demystifying RL Collapse from the Training-Inference Mismatch" https://richardli.xyz/rl-collapse This typed config replaces the old dict-based approach and provides: - Type safety and validation - Clear documentation of all parameters - Named factory methods for common presets (TIS, MIS, etc.) - Sensible defaults Args: rollout_is (Optional[str]): IS weight aggregation level. - None: No IS weights (metrics only) - "token": Per-token IS weights (low variance, biased) - "sequence": Per-sequence IS weights (unbiased, high variance) Default: "sequence" rollout_is_threshold (float): Upper threshold for IS weight truncation/rejection. Typical range: 1.5-5.0 for token level, 2.0-10.0 for sequence level. Default: 2.0 rollout_is_batch_normalize (bool): Apply batch normalization to IS weights. - True: Normalize IS weights to have mean=1.0 within each batch - False: Use raw (truncated) IS weights (standard) - Reduces variance by ensuring average weight is 1.0 per batch - Only affects IS weight values, not rejection sampling Default: False (no batch normalization) rollout_rs (Optional[str]): Rejection sampling aggregation modes. Accepts a comma-delimited list (duplicates removed) of canonical options implemented in ``rollout_corr_helper``: - "token_k1": Token-level rejection with ``-log r`` (ratio thresholds supplied via ``rollout_rs_threshold`` as ``lower_upper``) - "token_k2": Token-level rejection with ``0.5 * (log r)^2`` (upper bound only) - "token_k3": Token-level rejection with ``exp(log r) - 1 - log r`` (upper bound only) - "seq_sum_k1": Sequence sum of ``-log r`` (ratio bounds) - "seq_sum_k2": Sequence sum of rejection with ``0.5 * (log r)^2`` (upper bound only) - "seq_sum_k3": Sequence sum of rejection with ``exp(log r) - 1 - log r`` (upper bound only) - "seq_mean_k1": Sequence mean of ``-log r`` (ratio bounds) - "seq_mean_k2": Sequence mean of rejection with ``0.5 * (log r)^2`` (upper bound only) - "seq_mean_k3": Sequence mean of rejection with ``exp(log r) - 1 - log r`` (upper bound only) - "seq_max_k2": Sequence max of rejection with ``0.5 * (log r)^2`` (upper bound only) - "seq_max_k3": Sequence max of rejection with ``exp(log r) - 1 - log r`` (upper bound only) names automatically. Default: None rollout_rs_threshold (Optional[Union[str, float]]): Threshold specification for rejection sampling. Provide one value per option (single entry is broadcast when multiple options are supplied). Ratio-based modes (``*k1``) expect ``lower_upper`` strings; supplying a single float implies only the upper ratio bound, with the lower bound inferred as its reciprocal. Divergence modes (k2/k3) expect positive upper bounds (float or string). Default: None bypass_mode (bool): Operating mode - bypass or decoupled. - True: Bypass mode - reuse rollout_log_prob as old_log_prob (2 policies) Uses compute_policy_loss_bypass_mode() with loss_type selection - False: Decoupled mode - compute old_log_prob separately (3 policies) Uses standard PPO loss with IS weight correction Default: False (decoupled mode) loss_type (str): Loss function type in bypass mode (bypass_mode=True). - "reinforce": REINFORCE-style policy gradient with explicit IS weights L = -E[w * log π(a|s) * A] where w = π_current / π_rollout - "ppo_clip": PPO clipped objective (IS handled by ratio, no explicit weights) L = -E[min(r*A, clip(r)*A)] where r = π_current / π_rollout Default: "ppo_clip" Example: # Create with defaults config = RolloutCorrectionConfig() # Decoupled PPO mode presets (3 policies: π_rollout, π_old, π_θ) # IS weights correct for gap between π_old and π_rollout config = RolloutCorrectionConfig.decoupled_token_is() # Token-TIS config = RolloutCorrectionConfig.decoupled_seq_is() # Seq-TIS config = RolloutCorrectionConfig.decoupled_seq_is_rs() # Seq-MIS config = RolloutCorrectionConfig.decoupled_geo_rs() # Geo-RS (ratio mode) # Bypass mode presets (2 policies: π_rollout = π_old, π_θ) # loss_type controls the loss function # PPO-clip presets (ratio handles IS, so no separate IS weights needed): config = RolloutCorrectionConfig.bypass_ppo_clip() # PPO-clip only config = RolloutCorrectionConfig.bypass_ppo_clip_geo_rs() # PPO-clip + Geo-RS config = RolloutCorrectionConfig.bypass_ppo_clip_k3_rs() # PPO-clip + K3-RS # REINFORCE presets (explicit IS weights): config = RolloutCorrectionConfig.bypass_pg_is() # REINFORCE + Seq-TIS config = RolloutCorrectionConfig.bypass_pg_geo_rs() # REINFORCE + Geo-RS config = RolloutCorrectionConfig.bypass_pg_geo_rs_seq_tis() # REINFORCE + Geo-RS + Seq-TIS config = RolloutCorrectionConfig.bypass_pg_geo_rs_token_tis() # REINFORCE + Geo-RS + Token-TIS # Decoupled Geometric ratio presets (length-normalized IS ratio) config = RolloutCorrectionConfig.decoupled_geo_rs_seq_tis() # Decoupled Geo-RS + Seq-TIS config = RolloutCorrectionConfig.decoupled_geo_rs_token_tis() # Decoupled Geo-RS + Token-TIS # Decoupled K3 KL Estimator presets (more stable for small KL values) config = RolloutCorrectionConfig.decoupled_k3_rs() # Decoupled K3-RS config = RolloutCorrectionConfig.decoupled_k3_rs_seq_tis() # Decoupled K3-RS + Seq-TIS config = RolloutCorrectionConfig.decoupled_k3_rs_token_tis() # Decoupled K3-RS + Token-TIS Reference: Liu, Li, Fu, Wang, Liu, Shen (2025) "When Speed Kills Stability: Demystifying RL Collapse from the Training-Inference Mismatch" https://richardli.xyz/rl-collapse """ rollout_is: Optional[str] = "sequence" rollout_is_threshold: float = 2.0 rollout_is_batch_normalize: bool = False rollout_rs: Optional[str] = None rollout_rs_threshold: Optional[str | float] = None bypass_mode: bool = False loss_type: str = "ppo_clip" @classmethod def decoupled_token_is(cls, threshold: float = 2.0) -> "RolloutCorrectionConfig": """Decoupled Mode with Token-level Importance Sampling. IS weight correction at token level in decoupled mode (three policies). Args: threshold (float): Upper threshold for IS weights. Default: 2.0 Returns: RolloutCorrectionConfig configured for decoupled mode with token-level IS """ return cls(rollout_is="token", rollout_is_threshold=threshold, rollout_rs=None) @classmethod def decoupled_seq_is(cls, threshold: float = 2.0) -> "RolloutCorrectionConfig": """Decoupled Mode with Sequence-level Importance Sampling. IS weight correction at sequence level in decoupled mode (three policies). Args: threshold (float): Upper threshold for IS weights. Default: 2.0 Returns: RolloutCorrectionConfig configured for decoupled mode with sequence-level IS """ return cls(rollout_is="sequence", rollout_is_threshold=threshold, rollout_rs=None) @classmethod def decoupled_seq_is_rs( cls, is_threshold: float = 2.0, rs_threshold: Optional[str | float] = "0.5_2.0", ) -> "RolloutCorrectionConfig": """Decoupled Mode with Sequence-level IS + Rejection Sampling. Sequence-level IS with sequence-level rejection sampling in decoupled mode. Rejects entire sequences based on sequence-level IS weight. Args: is_threshold (float): Upper threshold for IS weights. Default: 2.0 rs_threshold (Optional[Union[str, float]]): Upper threshold for rejection sampling. Default: 0.5_2.0 Returns: RolloutCorrectionConfig configured for decoupled mode with sequence IS + RS """ return cls( rollout_is="sequence", rollout_is_threshold=is_threshold, rollout_rs="seq_sum_k1", rollout_rs_threshold=rs_threshold, ) @classmethod def decoupled_geo_rs( cls, rs_threshold: Optional[str | float] = "0.999_1.001", ) -> "RolloutCorrectionConfig": """Decoupled Mode with Geometric Mean Rejection Sampling (ratio-based). Uses geometric mean IS ratio E[log(r)] for rejection sampling at sequence level. This is a ratio-based mode (ideal = 0.0) with [lower, upper] threshold bounds. Length-normalized but still uses IS ratio semantics. Args: rs_threshold (Optional[Union[str, float]]): Geometric RS threshold (upper). Default: 0.999_1.001 (±0.1%) Returns: RolloutCorrectionConfig configured for decoupled mode with Geo-RS """ return cls( rollout_is=None, rollout_rs="seq_mean_k1", rollout_rs_threshold=rs_threshold, ) @classmethod def bypass_ppo_clip(cls) -> "RolloutCorrectionConfig": """Bypass mode with PPO-clip loss. PPO clipped objective in bypass mode. The PPO ratio = π_θ/π_rollout already handles IS correction, so no explicit IS weights are applied. Skips old_log_prob computation for faster execution (2 policies instead of 3). Returns: RolloutCorrectionConfig configured for bypass mode with PPO-clip """ return cls( rollout_is=None, rollout_rs=None, bypass_mode=True, loss_type="ppo_clip", ) @classmethod def bypass_ppo_clip_geo_rs( cls, rs_threshold: Optional[str | float] = "0.999_1.001", ) -> "RolloutCorrectionConfig": """Bypass mode with PPO-clip loss and Geometric Mean RS (ratio-based). PPO clipped objective in bypass mode with geometric mean IS ratio RS. Uses E[log(r)] (ideal = 0.0) with [lower, upper] threshold bounds. Args: rs_threshold (Optional[Union[str, float]]): Geometric RS threshold (upper). Default: 0.999_1.001 (±0.1%) Returns: RolloutCorrectionConfig configured for bypass mode with PPO-clip + Geo-RS """ return cls( rollout_is=None, rollout_rs="seq_mean_k1", rollout_rs_threshold=rs_threshold, bypass_mode=True, loss_type="ppo_clip", ) @classmethod def bypass_ppo_clip_k3_rs( cls, rs_threshold: float = 0.01, ) -> "RolloutCorrectionConfig": """Bypass mode with PPO-clip loss and K3 Rejection Sampling. PPO clipped objective in bypass mode with K3 KL estimator RS to mask outliers. K3 is more stable than K1 for small KL values. The PPO ratio = π_θ/π_rollout already handles IS correction. Args: rs_threshold (float): Max allowed K3 divergence. Default: 0.01 Returns: RolloutCorrectionConfig configured for bypass mode with PPO-clip + K3-RS """ return cls( rollout_is=None, rollout_rs="seq_mean_k3", rollout_rs_threshold=rs_threshold, bypass_mode=True, loss_type="ppo_clip", ) @classmethod def bypass_pg_is(cls, threshold: float = 2.0) -> "RolloutCorrectionConfig": """Bypass mode with REINFORCE loss and IS Correction. Uses REINFORCE loss with explicit IS correction in bypass mode. No PPO clipping. Args: threshold (float): Upper threshold for IS weights. Default: 2.0 Returns: RolloutCorrectionConfig configured for bypass mode with REINFORCE + IS """ return cls( rollout_is="sequence", rollout_is_threshold=threshold, rollout_rs=None, bypass_mode=True, loss_type="reinforce", ) @classmethod def bypass_pg_geo_rs( cls, rs_threshold: Optional[str | float] = "0.999_1.001", ) -> "RolloutCorrectionConfig": """Bypass mode with REINFORCE loss and Geometric Mean RS (ratio-based). REINFORCE with geometric mean IS ratio rejection sampling in bypass mode. Uses E[log(r)] (ideal = 0.0) with [lower, upper] threshold bounds. Args: rs_threshold (Optional[Union[str, float]]): Geometric RS threshold (upper). Default: 0.999_1.001 (±0.1%) Returns: RolloutCorrectionConfig configured for bypass mode with REINFORCE + Geo-RS """ return cls( rollout_is=None, rollout_rs="seq_mean_k1", rollout_rs_threshold=rs_threshold, bypass_mode=True, loss_type="reinforce", ) @classmethod def decoupled_geo_rs_seq_tis( cls, is_threshold: float = 2.0, rs_threshold: Optional[str | float] = "0.999_1.001", ) -> "RolloutCorrectionConfig": """Decoupled mode with Geometric Mean RS and Sequence-level Truncated IS (ratio-based). Combines the Geometric Mean Filter (ratio-based validity check) with Clipped Sequence Weight (debiasing). Uses E[log(r)] (ideal = 0.0). Args: is_threshold (float): Upper threshold for sequence IS weights. Default: 2.0 rs_threshold (Optional[Union[str, float]]): Geometric RS threshold (upper). Default: 0.999_1.001 (±0.1%) Returns: RolloutCorrectionConfig configured for Geo-RS-Seq-TIS """ return cls( rollout_is="sequence", rollout_is_threshold=is_threshold, rollout_rs="seq_mean_k1", rollout_rs_threshold=rs_threshold, ) @classmethod def decoupled_geo_rs_token_tis( cls, is_threshold: float = 2.0, rs_threshold: Optional[str | float] = "0.999_1.001", ) -> "RolloutCorrectionConfig": """Decoupled mode with Geometric Mean RS and Token-level Truncated IS (ratio-based). Combines the Geometric Mean Filter (ratio-based validity check) with Token-level IS weights. Uses E[log(r)] (ideal = 0.0). Args: is_threshold (float): Upper threshold for token IS weights. Default: 2.0 rs_threshold (Optional[Union[str, float]]): Geometric RS threshold (upper). Default: 0.999_1.001 (±0.1%) Returns: RolloutCorrectionConfig configured for Geo-RS-Token-TIS """ return cls( rollout_is="token", rollout_is_threshold=is_threshold, rollout_rs="seq_mean_k1", rollout_rs_threshold=rs_threshold, ) @classmethod def bypass_pg_geo_rs_seq_tis( cls, is_threshold: float = 2.0, rs_threshold: Optional[str | float] = "0.999_1.001", ) -> "RolloutCorrectionConfig": """Bypass mode with REINFORCE loss, Geo-RS, and Sequence-level IS. Combines geometric mean IS ratio rejection with sequence-level IS in bypass mode with REINFORCE loss (no PPO clipping). Uses E[log(r)] (ideal = 0.0) with [lower, upper] threshold bounds. Args: is_threshold (float): Upper threshold for sequence IS weights. Default: 2.0 rs_threshold (Optional[Union[str, float]]): Geometric RS threshold (upper). Default: 0.999_1.001 (±0.1%) Returns: RolloutCorrectionConfig configured for bypass mode with REINFORCE + Geo-RS + Seq-TIS """ return cls( rollout_is="sequence", rollout_is_threshold=is_threshold, rollout_rs="seq_mean_k1", rollout_rs_threshold=rs_threshold, bypass_mode=True, loss_type="reinforce", ) @classmethod def bypass_pg_geo_rs_token_tis( cls, is_threshold: float = 2.0, rs_threshold: Optional[str | float] = "0.999_1.001", ) -> "RolloutCorrectionConfig": """Bypass mode with REINFORCE loss, Geo-RS, and Token-level IS. Combines geometric mean IS ratio rejection with token-level IS weights in bypass mode with REINFORCE loss (no PPO clipping). Uses E[log(r)] (ideal = 0.0) with [lower, upper] threshold bounds. Token-level IS has lower variance but introduces bias. Args: is_threshold (float): Upper threshold for token IS weights. Default: 2.0 rs_threshold (Optional[Union[str, float]]): Geometric RS threshold (upper). Default: 0.999_1.001 (±0.1%) Returns: RolloutCorrectionConfig configured for bypass mode with REINFORCE + Geo-RS + Token-TIS """ return cls( rollout_is="token", rollout_is_threshold=is_threshold, rollout_rs="seq_mean_k1", rollout_rs_threshold=rs_threshold, bypass_mode=True, loss_type="reinforce", ) @classmethod def decoupled_k3_rs( cls, rs_threshold: float = 0.01, ) -> "RolloutCorrectionConfig": """Decoupled mode with K3 KL Estimator Rejection Sampling. Uses K3 KL estimator at sequence level for rejection sampling. K3 = E[r - log(r) - 1] where r = π_train/π_rollout. More stable than geometric mean for small KL values. K3 >= 0 always (equals 0 when policies match exactly). Args: rs_threshold (float): Max allowed K3 divergence. Default: 0.01 Typical range: 0.001-0.1 Returns: RolloutCorrectionConfig configured for K3 RS """ return cls( rollout_is=None, rollout_rs="seq_mean_k3", rollout_rs_threshold=rs_threshold, ) @classmethod def decoupled_k3_rs_seq_tis( cls, is_threshold: float = 2.0, rs_threshold: float = 0.01, ) -> "RolloutCorrectionConfig": """Decoupled mode with K3 RS and Sequence-level Truncated IS. Combines K3 KL estimator rejection with sequence-level IS weights. K3 provides more stable outlier detection than geometric mean. Args: is_threshold (float): Upper threshold for sequence IS weights. Default: 2.0 rs_threshold (float): Max allowed K3 divergence. Default: 0.01 Returns: RolloutCorrectionConfig configured for K3-RS-Seq-TIS """ return cls( rollout_is="sequence", rollout_is_threshold=is_threshold, rollout_rs="seq_mean_k3", rollout_rs_threshold=rs_threshold, ) @classmethod def decoupled_k3_rs_token_tis( cls, is_threshold: float = 2.0, rs_threshold: float = 0.01, ) -> "RolloutCorrectionConfig": """Decoupled mode with K3 RS and Token-level Truncated IS. Combines K3 KL estimator rejection with token-level IS weights. K3 provides more stable outlier detection than geometric mean. Token-level IS has lower variance but introduces bias. Args: is_threshold (float): Upper threshold for token IS weights. Default: 2.0 rs_threshold (float): Max allowed K3 divergence. Default: 0.01 Returns: RolloutCorrectionConfig configured for K3-RS-Token-TIS """ return cls( rollout_is="token", rollout_is_threshold=is_threshold, rollout_rs="seq_mean_k3", rollout_rs_threshold=rs_threshold, ) @classmethod def disabled(cls) -> "RolloutCorrectionConfig": """Disabled - Metrics Only Mode. Computes and logs off-policy metrics without applying correction. Returns: RolloutCorrectionConfig with all correction disabled """ return cls(rollout_is=None, rollout_rs=None) @dataclass class AlgoConfig(BaseConfig): """Configuration for the algorithm. The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config. Args: gamma (float): Discount factor for future rewards. lam (float): Trade-off between bias and variance in the GAE estimator. adv_estimator (str): Advantage estimator type: "gae", "grpo", "reinforce_plus_plus", etc. norm_adv_by_std_in_grpo (bool): Whether to normalize advantages by std (specific to GRPO). use_kl_in_reward (bool): Whether to enable in-reward KL penalty. kl_penalty (str): How to estimate KL divergence: "kl", "abs", "mse", "low_var_kl", or "full". kl_ctrl (KLControlConfig): KL control configuration. use_pf_ppo (bool): Whether to enable preference feedback PPO. pf_ppo (dict[str, Any]): Preference feedback PPO settings. filter_groups (Optional[FilterGroupsConfig]): Filter groups configuration, used in DAPO and Entropy rollout_correction (Optional[RolloutCorrectionConfig]): Rollout Correction configuration. Addresses off-policy issues from policy mismatch, model staleness, and general distribution shifts. Set to None to disable entirely. Use factory methods for common presets: - RolloutCorrectionConfig.decoupled_token_is() - Decoupled mode with token-level IS - RolloutCorrectionConfig.decoupled_seq_is() - Decoupled mode with sequence-level IS - RolloutCorrectionConfig.decoupled_seq_is_rs() - Decoupled mode with sequence IS + RS - RolloutCorrectionConfig.decoupled_k1_rs() - Decoupled mode with K1-RS (divergence) - RolloutCorrectionConfig.decoupled_geo_rs() - Decoupled mode with Geo-RS (ratio) - RolloutCorrectionConfig.bypass_ppo_clip() - Bypass mode with PPO-clip - RolloutCorrectionConfig.bypass_ppo_clip_k1_rs() - Bypass mode with PPO-clip + K1-RS - RolloutCorrectionConfig.bypass_pg_is() - Bypass mode with REINFORCE + IS - RolloutCorrectionConfig.bypass_pg_k1_rs() - Bypass mode with REINFORCE + K1-RS For backward compatibility, you can still pass a dict, which will be converted to RolloutCorrectionConfig automatically. """ gamma: float = 1.0 lam: float = 1.0 adv_estimator: str = "gae" norm_adv_by_std_in_grpo: bool = True use_kl_in_reward: bool = False kl_penalty: str = "kl" kl_ctrl: KLControlConfig = field(default_factory=KLControlConfig) use_pf_ppo: bool = False pf_ppo: dict[str, Any] = field(default_factory=dict) filter_groups: Optional[FilterGroupsConfig] = None # Rollout Correction: corrects off-policy issues (policy mismatch, model staleness, distribution shifts) # Set to None to disable, use RolloutCorrectionConfig presets (e.g., .tis(), .mis()), or pass dict rollout_correction: Optional[RolloutCorrectionConfig] = None
verl__trainer__config__algorithm.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass, field from typing import Any, Optional from verl.base_config import BaseConfig __all__ = ["CheckpointConfig", "ProfileConfig", "BaseModelConfig"] @dataclass class CheckpointConfig(BaseConfig): """Configuration for model checkpointing. The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config. Args: save_contents (list[str]): What to include in saved checkpoints. Options: 'model', 'optimizer', 'extra', 'hf_model'. load_contents (list[str]): Contents to load from checkpoint. Defaults to same as save_contents. async_save (bool): Whether to save checkpoints asynchronously. Only implemented for Megatron as of now. """ 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(default_factory=dict) @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): Starting step for profiling. step_end (int): Ending step for profiling. save_path (Optional[str]): Path to save profiling results. """ profile_ranks: Optional[list[int]] = None step_start: int = -1 step_end: int = -1 save_path: Optional[str] = None @dataclass class BaseModelConfig(BaseConfig): """Base configuration for a model. Contains core settings for loading and initializing a pretrained model checkpoint. Args: path (str): Path to pretrained model weights. tokenizer_path (Optional[str]): Tokenizer path (defaults to actor's model path if not set). override_config (dict): Hugging Face config override. external_lib (Optional[str]): External model implementation (optional). trust_remote_code (bool): Whether to trust remote code from Hugging Face models. lora (dict[str, Any]): LoRA configuration dictionary. """ path: str = "~/models/deepseek-llm-7b-chat" tokenizer_path: Optional[str] = None override_config: dict[str, Any] = field(default_factory=dict) external_lib: Optional[str] = None trust_remote_code: bool = False lora: dict[str, Any] = field(default_factory=dict) @dataclass class ModuleConfig(BaseConfig): """Configuration for external Python module, which can be loaded, executed (and optionally, ``import``ed). Args: path (str, optional): Path to the module file to load and execute. name (str, optional): Name of the module to ``import``. Format: ``"import.path.to.module"``. If ``None``, the module will be loaded with a hased name and will not be added to ``sys.modules``, thus can not be ``import``ed as ``name``. """ path: Optional[str] = None name: Optional[str] = None
verl__trainer__config__config.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ray._private.runtime_env.constants import RAY_JOB_CONFIG_JSON_ENV_VAR PPO_RAY_RUNTIME_ENV = { "env_vars": { "TOKENIZERS_PARALLELISM": "true", "NCCL_DEBUG": "WARN", "VLLM_LOGGING_LEVEL": "WARN", "VLLM_ALLOW_RUNTIME_LORA_UPDATING": "true", "CUDA_DEVICE_MAX_CONNECTIONS": "1", # To prevent hanging or crash during synchronization of weights between actor and rollout # in disaggregated mode. See: # https://docs.vllm.ai/en/latest/usage/troubleshooting.html?h=nccl_cumem_enable#known-issues # https://github.com/vllm-project/vllm/blob/c6b0a7d3ba03ca414be1174e9bd86a97191b7090/vllm/worker/worker_base.py#L445 "NCCL_CUMEM_ENABLE": "0", # TODO: disable compile cache due to cache corruption issue # https://github.com/vllm-project/vllm/issues/31199 "VLLM_DISABLE_COMPILE_CACHE": "1", # Needed for multi-processes colocated on same NPU device # https://www.hiascend.com/document/detail/zh/canncommercial/83RC1/maintenref/envvar/envref_07_0143.html "HCCL_HOST_SOCKET_PORT_RANGE": "auto", "HCCL_NPU_SOCKET_PORT_RANGE": "auto", }, } def get_ppo_ray_runtime_env(): """ A filter function to return the PPO Ray runtime environment. To avoid repeat of some environment variables that are already set. """ working_dir = ( json.loads(os.environ.get(RAY_JOB_CONFIG_JSON_ENV_VAR, "{}")).get("runtime_env", {}).get("working_dir", None) ) runtime_env = { "env_vars": PPO_RAY_RUNTIME_ENV["env_vars"].copy(), **({"working_dir": None} if working_dir is None else {}), } for key in list(runtime_env["env_vars"].keys()): if os.environ.get(key) is not None: runtime_env["env_vars"].pop(key, None) return runtime_env
verl__trainer__constants_ppo.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ A lightweight one-file FSDP SFT Trainer TODO(zhangchi.usc1992) - Add calculation of mfu - Add validation """ import os os.environ["NCCL_DEBUG"] = "WARN" os.environ["TOKENIZERS_PARALLELISM"] = "true" import logging import re import time from contextlib import nullcontext import hydra import torch import torch.distributed from omegaconf import DictConfig, OmegaConf from peft import LoraConfig, TaskType, get_peft_model from tensordict import TensorDict from torch import nn from torch.distributed.device_mesh import DeviceMesh, init_device_mesh from torch.distributed.fsdp import CPUOffload, MixedPrecision, ShardingStrategy from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.utils.data import Dataset, DistributedSampler from torchdata.stateful_dataloader import StatefulDataLoader from tqdm import tqdm from transformers import AutoConfig, AutoModelForCausalLM, PreTrainedModel import verl.utils.hdfs_io as hdfs_io from verl.utils.attention_utils import index_first_axis, pad_input, rearrange, unpad_input from verl.utils.checkpoint.checkpoint_manager import find_latest_ckpt_path, get_checkpoint_tracker_filename from verl.utils.checkpoint.fsdp_checkpoint_manager import FSDPCheckpointManager from verl.utils.dataset import SFTDataset from verl.utils.dataset.multiturn_sft_dataset import MultiTurnSFTDataset from verl.utils.device import ( auto_set_device, get_device_id, get_device_name, is_cuda_available, is_npu_available, ) from verl.utils.distributed import destroy_global_process_group, initialize_global_process_group from verl.utils.fs import copy_to_local from verl.utils.fsdp_utils import ( CPUOffloadPolicy, MixedPrecisionPolicy, apply_fsdp2, fsdp2_clip_grad_norm_, fsdp2_load_full_state_dict, get_fsdp_wrap_policy, get_init_weight_context_manager, init_fn, ) from verl.utils.logger import log_with_rank from verl.utils.profiler import log_gpu_memory_usage from verl.utils.py_functional import convert_to_regular_types from verl.utils.torch_dtypes import PrecisionType from verl.utils.torch_functional import get_cosine_schedule_with_warmup, get_wsd_schedule_with_warmup from verl.utils.tracking import Tracking from verl.utils.ulysses import ( gather_outputs_and_unpad, get_ulysses_sequence_parallel_world_size, ulysses_pad_and_slice_inputs, ) from verl.workers.config.optimizer import build_optimizer from verl.workers.sharding_manager.fsdp_ulysses import FSDPUlyssesShardingManager logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_SFT_LOGGING_LEVEL", "WARN")) def extract_step(path): match = re.search(r"global_step_(\d+)", path) if match: return int(match.group(1)) return None class FSDPSFTTrainer: def __init__( self, config, device_mesh: DeviceMesh, ulysses_device_mesh: DeviceMesh, tokenizer, train_dataset: Dataset, val_dataset: Dataset, ): self.config = config self.device_mesh = device_mesh self.ulysses_device_mesh = ulysses_device_mesh self.sharding_manager = FSDPUlyssesShardingManager(self.ulysses_device_mesh) self.tokenizer = tokenizer if self.config.data.chat_template is not None: raise ValueError("Apply Chat template from config is not supported yet.") # normalize dp size self._normalize_config_bsz() # Set sequence parallel size self.config.ulysses_sequence_parallel_size = getattr(self.config, "ulysses_sequence_parallel_size", 1) self.use_remove_padding = getattr(self.config, "use_remove_padding", False) if self.device_mesh.get_rank() == 0: print(f"Using sequence parallel size: {self.config.ulysses_sequence_parallel_size}") print(f"Using remove padding: {self.use_remove_padding}") self._build_dataloader(train_dataset, val_dataset) self.lora = self.config.model.get("lora_adapter_path") is not None or self.config.model.lora_rank > 0 # Initialize resume-related variables self.resume_global_step = 0 # build model self._build_model_optimizer() # Initialize checkpoint manager self._init_checkpoint_manager() self.load_checkpoint() if self.device_mesh.get_rank() == 0: print(self.config) self.device_name = self.config.trainer.device def _normalize_config_bsz(self): dp_size = self.device_mesh.size(0) if not self.ulysses_device_mesh else self.ulysses_device_mesh.size(0) if self.device_mesh.get_rank() == 0: print(f"Normalize batch size by dp {dp_size}") assert self.config.data.train_batch_size % dp_size == 0, ( f"Global batch size {self.config.data.train_batch_size} is not divisible by dp size {dp_size}" ) self.config.data.train_batch_size //= dp_size assert self.config.data.train_batch_size % self.config.data.micro_batch_size_per_gpu == 0 def _build_dataloader(self, train_dataset, val_dataset): # build dataset config = self.config self.train_dataset, self.val_dataset = train_dataset, val_dataset # build dataloader # Use data parallel rank and size instead of global rank and world size # If doing SP, we need to use the local rank and size if self.config.ulysses_sequence_parallel_size > 1: rank = self.ulysses_device_mesh.get_local_rank("dp") world_size = self.ulysses_device_mesh.size(0) if self.ulysses_device_mesh.get_rank() == 0: print(f"Using SP rank {rank} and size {world_size} for data distribution") print("Each SP rank gets different data, but the same data WITHIN the same rank") else: rank = self.device_mesh.get_rank() world_size = self.device_mesh.size() if self.device_mesh.get_rank() == 0: print(f"Using FSDP rank {rank} and size {world_size} for data distribution") # Set pin_memory_device when pin_memory is enabled. device_name = get_device_name() self.train_sampler = DistributedSampler( self.train_dataset, shuffle=True, num_replicas=world_size, rank=rank, drop_last=True ) self.train_dataloader = StatefulDataLoader( dataset=self.train_dataset, batch_size=config.data.train_batch_size, sampler=self.train_sampler, num_workers=8, pin_memory=True, drop_last=True, pin_memory_device=device_name, ) self.val_sampler = DistributedSampler( self.val_dataset, shuffle=False, num_replicas=world_size, rank=rank, drop_last=True ) self.val_dataloader = StatefulDataLoader( dataset=self.val_dataset, batch_size=config.data.micro_batch_size_per_gpu, sampler=self.val_sampler, num_workers=8, pin_memory=True, drop_last=True, pin_memory_device=device_name, ) def _build_model_optimizer(self): # TODO (zhangchi.usc1992): # 1. support pretrain from random weights # 2. support init directly from sharded weights local_model_path = copy_to_local(src=self.config.model.partial_pretrain, verbose=True) if self.config.model.get("external_lib", None) is not None: # This is used to import external_lib into the huggingface systems import importlib importlib.import_module(self.config.model.external_lib) log_gpu_memory_usage("Before model allocation", logger=logger) trust_remote_code = self.config.model.trust_remote_code torch_dtype = self.config.model.fsdp_config.get("model_dtype", "fp32") torch_dtype = PrecisionType.to_dtype(torch_dtype) # load config first config = AutoConfig.from_pretrained(local_model_path, trust_remote_code=trust_remote_code) self.model_config = config if hasattr(self.model_config, "max_position_embeddings"): self.model_config.max_position_embeddings = max( self.model_config.max_position_embeddings, self.config.data.max_length ) if self.config.ulysses_sequence_parallel_size > 1: assert self.use_remove_padding, "Sequence parallel is only supported when remove_padding is enabled" # This may be very large init_context = get_init_weight_context_manager( use_meta_tensor=not config.tie_word_embeddings, mesh=self.device_mesh ) with init_context(): self.model: PreTrainedModel = AutoModelForCausalLM.from_pretrained( local_model_path, config=config, torch_dtype=torch_dtype, attn_implementation="flash_attention_2", trust_remote_code=trust_remote_code, ) if self.use_remove_padding or self.config.ulysses_sequence_parallel_size > 1: from verl.models.transformers.monkey_patch import apply_monkey_patch apply_monkey_patch(model=self.model, ulysses_sp_size=self.config.ulysses_sequence_parallel_size) # Apply Liger kernel if use_liger is enabled if self.config.model.get("use_liger", False): from liger_kernel.transformers.monkey_patch import _apply_liger_kernel_to_instance _apply_liger_kernel_to_instance(model=self.model) if self.lora: self.model.enable_input_require_grads() lora_adapter_path = self.config.model.get("lora_adapter_path") if lora_adapter_path is not None: from peft import PeftModel print(f"Loading pre-trained LoRA adapter for sft from: {lora_adapter_path}") local_adapter_path = copy_to_local(lora_adapter_path, use_shm=self.config.model.use_shm) self.model = PeftModel.from_pretrained(self.model, local_adapter_path, is_trainable=True) peft_config = self.model.peft_config["default"] # Ensure task_type is TaskType enum, not string if isinstance(peft_config.task_type, str): peft_config.task_type = TaskType.CAUSAL_LM else: # Convert config to regular Python types before creating PEFT model lora_config = { "task_type": TaskType.CAUSAL_LM, "r": self.config.model.lora_rank, "lora_alpha": self.config.model.lora_alpha, "target_modules": convert_to_regular_types(self.config.model.target_modules), "bias": "none", } self.model = get_peft_model(self.model, LoraConfig(**lora_config)) self.model = self.model.to(torch_dtype) if self.config.model.enable_gradient_checkpointing: self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) log_gpu_memory_usage("After model allocation", logger=logger) mixed_precision = MixedPrecision( param_dtype=torch.bfloat16, reduce_dtype=torch.float32, buffer_dtype=torch.float32 ) auto_wrap_policy = get_fsdp_wrap_policy( self.model, config=self.config.model.fsdp_config.wrap_policy, is_lora=self.lora, ) if self.device_mesh.get_rank() == 0: print(auto_wrap_policy) if not self.config.model.fsdp_config.cpu_offload: cpu_offload = None else: cpu_offload = CPUOffload(offload_params=self.config.model.fsdp_config.offload_params) fsdp_strategy = self.config.model.strategy if fsdp_strategy == "fsdp": self.fsdp_model = FSDP( self.model, cpu_offload=cpu_offload, param_init_fn=init_fn, use_orig_params=False, auto_wrap_policy=auto_wrap_policy, device_id=get_device_id(), sharding_strategy=ShardingStrategy.FULL_SHARD, mixed_precision=mixed_precision, sync_module_states=True, device_mesh=self.device_mesh, forward_prefetch=False, ) elif fsdp_strategy == "fsdp2": assert CPUOffloadPolicy is not None, "PyTorch version >= 2.4 is required for using fully_shard API (FSDP2)" mp_policy = MixedPrecisionPolicy( param_dtype=torch.bfloat16, reduce_dtype=torch.float32, cast_forward_inputs=True ) fsdp_kwargs = { "mesh": self.device_mesh, "mp_policy": mp_policy, "offload_policy": cpu_offload, "reshard_after_forward": True, } full_state = self.model.state_dict() apply_fsdp2(self.model, fsdp_kwargs, self.config.model.fsdp_config) fsdp2_load_full_state_dict(self.model, full_state, self.device_mesh, cpu_offload) self.fsdp_model = self.model else: raise NotImplementedError(f"not implement {fsdp_strategy}") log_gpu_memory_usage("After FSDP wrapping", logger=logger) self.optimizer = build_optimizer(self.fsdp_model.parameters(), self.config.optim) log_gpu_memory_usage("After initialize optimizer", logger=logger) self.steps_per_epoch = len(self.train_dataloader) self.total_steps = self.steps_per_epoch * self.config.trainer.total_epochs if self.device_mesh.get_rank() == 0: print( f"Number of steps/epoch {self.steps_per_epoch}, number of epochs " f"{self.config.trainer.total_epochs}, total number of steps {self.total_steps}" ) num_warmup_steps = int(self.total_steps * self.config.optim.lr_warmup_steps_ratio) if not hasattr(self.config.optim, "lr_scheduler") or self.config.optim.lr_scheduler == "cosine": self.lr_scheduler = get_cosine_schedule_with_warmup( optimizer=self.optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=self.total_steps ) elif self.config.optim.lr_scheduler == "wsd": self.lr_scheduler = get_wsd_schedule_with_warmup( optimizer=self.optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=self.total_steps ) else: raise ValueError(f"Unknown lr scheduler: {self.config.optim.lr_scheduler}") def _compute_loss_and_backward(self, batch, do_backward=True, n_micro_batches=1): """Compute loss with optional sequence parallelism and remove padding features""" use_sp = self.use_remove_padding and self.config.ulysses_sequence_parallel_size > 1 # Move inputs to GPU and prepare loss mask input_ids = batch["input_ids"].to(self.device_name) attention_mask = batch["attention_mask"].to(self.device_name) position_ids = batch["position_ids"].to(self.device_name) loss_mask = batch.pop("loss_mask")[:, 1:].reshape(-1).to(self.device_name) loss_fct = nn.CrossEntropyLoss(reduction="none") # Context manager for sequence parallel if needed context = self.sharding_manager if use_sp else nullcontext() with context, torch.autocast(device_type=self.device_name, dtype=torch.bfloat16): if not use_sp: # Standard forward pass without sequence parallel labels = input_ids[:, 1:].contiguous() output = self.fsdp_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, use_cache=False ) logits = output.logits shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels.contiguous() # Flatten the tokens shift_logits = shift_logits.view(-1, self.model.config.vocab_size) shift_labels = shift_labels.view(-1) # Enable model parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) loss = loss * loss_mask.to(loss.device) else: # IMPORTANT: We have a big assumption here, so we can shard the SAME sequence across SP ranks # i.e., each GPU has <1 sequence, and each SP group has 1 sequence # 1. All SP ranks will receive the *SAME* batch # 2. Different SP groups will receive *DIFFERENT* batches # This is implemented by the DistributedSampler batch_size, seqlen = input_ids.shape # Remove padding input_ids_rmpad, indices, *_ = unpad_input( input_ids.unsqueeze(-1), attention_mask ) # input_ids_rmpad (total_nnz, ...) input_ids_rmpad = input_ids_rmpad.transpose(0, 1) # (1, total_nnz) # Unpad position_ids to align rotary position_ids_rmpad = index_first_axis( rearrange(position_ids.unsqueeze(-1), "b s ... -> (b s) ..."), indices ).transpose(0, 1) # Pad and slice inputs for sequence parallelism input_ids_rmpad_sliced, position_ids_rmpad_padded, pad_size = ulysses_pad_and_slice_inputs( input_ids_rmpad, position_ids_rmpad, sp_size=get_ulysses_sequence_parallel_world_size() ) # For computing loss input_ids_rmpad_rolled = torch.roll(input_ids_rmpad, shifts=-1, dims=1) # (1, total_nnz) input_ids_rmpad_rolled, _, _ = ulysses_pad_and_slice_inputs( input_ids_rmpad_rolled, None, get_ulysses_sequence_parallel_world_size() ) input_ids_rmpad_rolled = input_ids_rmpad_rolled.squeeze(0) # ((total_nnz / sp) + pad) # Forward pass output = self.fsdp_model( input_ids=input_ids_rmpad_sliced, attention_mask=None, # Not needed with flash attention varlen position_ids=position_ids_rmpad_padded, use_cache=False, ) # Compute loss locally then aggregate logits_rmpad = output.logits.squeeze(0) input_ids_rmpad_rolled = input_ids_rmpad_rolled.to(logits_rmpad.device) loss = loss_fct(logits_rmpad, input_ids_rmpad_rolled) # Gather and unpad for sequence parallelism loss = gather_outputs_and_unpad(loss, gather_dim=0, unpad_dim=0, padding_size=pad_size) # This is the loss collected from all ulysses ranks full_loss = pad_input( hidden_states=loss.unsqueeze(-1), indices=indices, batch=batch_size, seqlen=seqlen ) full_loss = full_loss.squeeze(-1)[:, :-1] # Remove last token's loss full_loss = full_loss.reshape(-1) loss_mask = loss_mask.to(full_loss.device) loss = full_loss * loss_mask valid_token_this_rank = torch.sum(loss_mask) if self.config.data.balance_dp_token: torch.distributed.all_reduce(valid_token_this_rank) dp_size = self.ulysses_device_mesh.size("dp") if use_sp else torch.distributed.get_world_size() else: dp_size = 1 loss = torch.sum(loss) / (valid_token_this_rank + 1e-8) * dp_size loss = loss / n_micro_batches # normalize loss if do_backward: loss.backward() return loss def training_step(self, batch: TensorDict): start_time = time.time() self.fsdp_model.train() log_gpu_memory_usage("Before optimizer zero_grad", logger=logger) self.optimizer.zero_grad() log_gpu_memory_usage("After optimizer zero_grad", logger=logger) micro_batches = batch.split(self.config.data.micro_batch_size_per_gpu) n_micro_batches = len(micro_batches) step_loss = 0 for micro_batch in micro_batches: loss = self._compute_loss_and_backward(batch=micro_batch, n_micro_batches=n_micro_batches) step_loss += loss.item() if self.config.model.strategy == "fsdp": grad_norm = self.fsdp_model.clip_grad_norm_(max_norm=self.config.optim.clip_grad) elif self.config.model.strategy == "fsdp2": grad_norm = fsdp2_clip_grad_norm_(self.fsdp_model.parameters(), max_norm=self.config.optim.clip_grad) else: raise NotImplementedError(f"not implement {self.config.model.strategy}") log_gpu_memory_usage("Before optimizer step", logger=logger) # if grad_norm is not finite, skip the update if not torch.isfinite(grad_norm): print(f"WARN: grad_norm is not finite: {grad_norm}") self.optimizer.zero_grad() else: self.optimizer.step() log_gpu_memory_usage("After optimizer step", logger=logger) self.lr_scheduler.step() # reduce loss across dp ranks lr = self.lr_scheduler.get_last_lr()[0] log_gpu_memory_usage("After offload weights", logger=logger) step_loss = torch.tensor(step_loss).to(self.device_name) # compute time spent per step end_time = time.time() spend_time_per_step = end_time - start_time if is_cuda_available: torch.distributed.all_reduce(step_loss, op=torch.distributed.ReduceOp.AVG) elif is_npu_available: torch.distributed.all_reduce(step_loss) step_loss /= self.device_mesh.size(0) return { "train/loss": step_loss.detach().item(), "train/lr(1e-3)": lr * 1e3, "train/time(s)": spend_time_per_step, } def validation_step(self, batch: TensorDict): self.fsdp_model.eval() with torch.no_grad(): loss = self._compute_loss_and_backward(batch, do_backward=False) if is_cuda_available: torch.distributed.all_reduce(loss, op=torch.distributed.ReduceOp.AVG) elif is_npu_available: torch.distributed.all_reduce(loss) loss /= self.device_mesh.size(0) return loss def save_checkpoint(self, step): """Save checkpoint using FSDPCheckpointManager with improved tracking""" from verl.utils.fs import local_mkdir_safe # Determine checkpoint path local_global_step_folder = os.path.join(self.config.trainer.default_local_dir, f"global_step_{step}") if self.device_mesh.get_rank() == 0: print(f"Saving checkpoint to: {local_global_step_folder}") # Get max checkpoints to keep max_ckpt_to_keep = getattr(self.config.trainer, "max_ckpt_to_keep", None) # Use checkpoint manager to save self.checkpoint_manager.save_checkpoint( local_path=local_global_step_folder, global_step=step, max_ckpt_to_keep=max_ckpt_to_keep ) # Save dataloader state if self.device_mesh.get_rank() == 0: local_mkdir_safe(local_global_step_folder) dataloader_local_path = os.path.join(local_global_step_folder, "data.pt") # Use StatefulDataLoader's built-in state dict functionality dataloader_state_dict = self.train_dataloader.state_dict() torch.save(dataloader_state_dict, dataloader_local_path) print(f"Saved dataloader state to: {dataloader_local_path}") # Update latest checkpoint tracker (atomic write) tracker_file = get_checkpoint_tracker_filename(self.config.trainer.default_local_dir) temp_tracker_file = tracker_file + ".tmp" with open(temp_tracker_file, "w") as f: f.write(str(step)) os.rename(temp_tracker_file, tracker_file) print(f"Updated checkpoint tracker: {tracker_file}") # Copy to HDFS if configured if self.device_mesh.get_rank() == 0 and getattr(self.config.trainer, "default_hdfs_dir", None): hdfs_io.makedirs(self.config.trainer.default_hdfs_dir, exist_ok=True) hdfs_io.copy(src=local_global_step_folder, dst=self.config.trainer.default_hdfs_dir, dirs_exist_ok=True) torch.distributed.barrier() def _init_checkpoint_manager(self): """Initialize checkpoint manager with proper configuration""" # Get checkpoint configuration from config, with defaults checkpoint_config = getattr(self.config.trainer, "checkpoint", {}) # Set default values if not specified save_contents = checkpoint_config.get("save_contents", ["model", "optimizer", "extra"]) load_contents = checkpoint_config.get("load_contents", save_contents) # Create checkpoint config dict checkpoint_config_dict = { "load_contents": load_contents, "save_contents": save_contents, } # Convert to DictConfig for compatibility checkpoint_config_dict = DictConfig(checkpoint_config_dict) # Initialize checkpoint manager self.checkpoint_manager = FSDPCheckpointManager( model=self.fsdp_model, optimizer=self.optimizer, lr_scheduler=self.lr_scheduler, processing_class=self.tokenizer, checkpoint_config=checkpoint_config_dict, trust_remote_code=self.config.model.trust_remote_code, ) def load_checkpoint(self): # Determine resume path based on configuration checkpoint_path = self._determine_resume_path() if checkpoint_path is None: return 0 # extract resume step from checkpoint path resume_step = extract_step(checkpoint_path) if resume_step is None: log_with_rank( f"Warning: Could not extract step number from {checkpoint_path}, starting from step 0", logger=logger, rank=self.device_mesh.get_rank(), level=logging.WARNING, log_only_rank_0=True, ) return 0 self.resume_global_step = resume_step # Use checkpoint manager to load model state self.checkpoint_manager.load_checkpoint(checkpoint_path) log_with_rank( f"Successfully loaded model checkpoint from {checkpoint_path} (step {resume_step})", logger=logger, rank=self.device_mesh.get_rank(), log_only_rank_0=True, ) # Always load dataloader state for StatefulDataLoader self._load_dataloader_state(checkpoint_path) return resume_step def _load_dataloader_state(self, checkpoint_path: str): """Load dataloader state from checkpoint""" dataloader_path = os.path.join(checkpoint_path, "data.pt") if os.path.exists(dataloader_path): # Use StatefulDataLoader's built-in state dict functionality dataloader_state_dict = torch.load(dataloader_path, map_location="cpu", weights_only=False) self.train_dataloader.load_state_dict(dataloader_state_dict) log_with_rank( f"Successfully loaded dataloader state from {dataloader_path}", logger=logger, rank=self.device_mesh.get_rank(), log_only_rank_0=True, ) else: log_with_rank( f"Warning: No dataloader state found at {dataloader_path}, will start from scratch", logger=logger, rank=self.device_mesh.get_rank(), level=logging.WARNING, log_only_rank_0=True, ) def _determine_resume_path(self): """Determine the path to resume from based on resume_mode configuration""" resume_mode = getattr(self.config.trainer, "resume_mode", "auto") resume_from_path = getattr(self.config.trainer, "resume_from_path", None) if resume_mode == "disable": return None elif resume_mode == "auto": if resume_from_path is not None: assert os.path.exists(resume_from_path), ( "resume_from_path must be null or an existing path when resume_mode is 'auto'" ) assert "global_step_" in resume_from_path, "resume_from_path must specify the global_steps" return resume_from_path # Try to find the latest checkpoint in the default directory return self._find_latest_checkpoint() elif resume_mode == "resume_path": assert os.path.exists(resume_from_path), ( "resume_from_path must be an existing path when resume_mode is 'resume_path'" ) assert "global_step_" in resume_from_path, "resume_from_path must specify the global_steps" return resume_from_path else: raise ValueError(f"Invalid resume_mode: {resume_mode}. Must be 'auto', 'disable', or 'resume_path'") def _find_latest_checkpoint(self): """Find the latest checkpoint in the default local directory""" checkpoint_dir = self.config.trainer.default_local_dir if not os.path.exists(checkpoint_dir): return None latest_checkpoint = find_latest_ckpt_path(checkpoint_dir) if latest_checkpoint and self.device_mesh.get_rank() == 0: step_num = extract_step(latest_checkpoint) print(f"Found latest checkpoint: {latest_checkpoint} (step {step_num})") return latest_checkpoint def fit(self): rank = self.device_mesh.get_rank() # TODO: add a unified tracking if rank == 0: tracking = Tracking( project_name=self.config.trainer.project_name, experiment_name=self.config.trainer.experiment_name, default_backend=self.config.trainer.logger, config=OmegaConf.to_container(self.config, resolve=True), ) global_step = self.resume_global_step # Start from resumed step last_valid_metric = None # compute the total training steps. # the total training steps in SFT is mainly for early exit total_training_steps = len(self.train_dataloader) * self.config.trainer.total_epochs if self.config.trainer.total_training_steps is not None: total_training_steps = self.config.trainer.total_training_steps self.total_training_steps = total_training_steps log_with_rank( f"Total training steps: {self.total_training_steps},", logger=logger, rank=self.device_mesh.get_rank(), log_only_rank_0=True, ) # With StatefulDataLoader, we don't need to manually calculate epochs and steps # The dataloader will automatically resume from where it left off if global_step > 0: log_with_rank( f"StatefulDataLoader will automatically resume from global step: {global_step}", logger=logger, rank=self.device_mesh.get_rank(), log_only_rank_0=True, ) # Calculate which epoch we're starting from for sampler.set_epoch() start_epoch = global_step // self.steps_per_epoch train_time = 0 for epoch in range(start_epoch, self.config.trainer.total_epochs): self.train_sampler.set_epoch(epoch=epoch) for step_in_epoch, data in enumerate( tqdm( self.train_dataloader, initial=global_step % self.steps_per_epoch if epoch == start_epoch else 0, total=self.steps_per_epoch, desc=f"Epoch {epoch + 1}/{self.config.trainer.total_epochs}", disable=rank != 0, ) ): global_step += 1 data = TensorDict(data, batch_size=self.config.data.train_batch_size).to(self.device_name) metric = self.training_step(data) train_time += metric["train/time(s)"] if rank == 0: tracking.log(data=metric, step=global_step) is_last_step = global_step >= self.total_training_steps is_valid_step = global_step % self.config.trainer.test_freq == 0 is_save_step = global_step % self.config.trainer.save_freq == 0 # early exit or validation step if is_last_step or (self.config.trainer.test_freq > 0 and is_valid_step): # Perform validation val_losses = [] for val_data in self.val_dataloader: val_data = TensorDict(val_data, batch_size=self.config.data.micro_batch_size_per_gpu).to( self.device_name ) val_loss = self.validation_step(val_data) val_losses.append(val_loss) if rank == 0: val_loss = torch.mean(torch.stack(val_losses)) metric = {"val/loss": val_loss.detach().item()} tracking.log(data=metric, step=global_step) last_valid_metric = metric torch.distributed.barrier() if is_last_step or (self.config.trainer.save_freq > 0 and is_save_step): self.save_checkpoint(step=global_step) if is_last_step: if rank == 0: print(f"Total time for train steps: {train_time:.2f}s") print(f"Final validation metrics: {last_valid_metric}") return def run_sft(config): device_name = get_device_name() local_rank, rank, world_size = initialize_global_process_group() device_mesh = init_device_mesh(device_type=device_name, mesh_shape=(world_size,), mesh_dim_names=("fsdp",)) dp_size = world_size // config.ulysses_sequence_parallel_size ulysses_device_mesh = init_device_mesh( device_type=device_name, mesh_shape=(dp_size, config.ulysses_sequence_parallel_size), mesh_dim_names=("dp", "sp"), ) # build tokenizer and datasets first from verl.utils import hf_tokenizer local_model_path = copy_to_local(src=config.model.partial_pretrain, verbose=True) tokenizer = hf_tokenizer(local_model_path, trust_remote_code=config.model.trust_remote_code) train_dataset = create_sft_dataset( config.data.train_files, config.data, tokenizer, max_samples=config.data.get("train_max_samples", -1) ) val_dataset = create_sft_dataset( config.data.val_files, config.data, tokenizer, max_samples=config.data.get("val_max_samples", -1) ) trainer = FSDPSFTTrainer( config=config, device_mesh=device_mesh, ulysses_device_mesh=ulysses_device_mesh, tokenizer=tokenizer, train_dataset=train_dataset, val_dataset=val_dataset, ) trainer.fit() destroy_global_process_group() @hydra.main(config_path="config", config_name="sft_trainer", version_base=None) def main(config): # Automatically set `config.trainer.device = npu` when running on Ascend NPU. auto_set_device(config) run_sft(config) def create_sft_dataset(data_paths, data_config, tokenizer, max_samples=-1): """Create a dataset.""" # build dataset # First check if a custom dataset class is specified if data_config.custom_cls.get("path", None): from verl.utils.import_utils import load_extern_object dataset_cls = load_extern_object(data_config.custom_cls.path, data_config.custom_cls.name) # Then check if multi-turn dataset should be used elif data_config.get("multiturn", {}).get("enable", False): dataset_cls = MultiTurnSFTDataset # Default to single-turn dataset else: dataset_cls = SFTDataset # Create datasets based on the selected class dataset = dataset_cls(parquet_files=data_paths, tokenizer=tokenizer, config=data_config, max_samples=max_samples) return dataset if __name__ == "__main__": main()
verl__trainer__fsdp_sft_trainer.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Offline evaluate the performance of a generated file using reward model and ground truth verifier. The input is a parquet file that contains N generated sequences and (optional) the ground truth. """ from collections import defaultdict import hydra import numpy as np import pandas as pd import ray from omegaconf import OmegaConf from tqdm import tqdm from verl.trainer.ppo.reward import get_custom_reward_fn from verl.utils.fs import copy_to_local @ray.remote def process_item(config, data_source, response_lst, reward_data): reward_fn = get_custom_reward_fn(config) ground_truth = reward_data["ground_truth"] score_lst = [reward_fn(data_source, r, ground_truth) for r in response_lst] return data_source, np.mean(score_lst) @hydra.main(config_path="config", config_name="evaluation", version_base=None) def main(config): local_path = copy_to_local(config.data.path, use_shm=config.data.get("use_shm", False)) dataset = pd.read_parquet(local_path) responses = dataset[config.data.response_key] data_sources = dataset[config.data.data_source_key] reward_model_data = dataset[config.data.reward_model_key] total = len(dataset) # Initialize Ray if not ray.is_initialized(): ray.init(**OmegaConf.to_container(config.ray_kwargs.get("ray_init", {}))) # evaluate test_score based on data source data_source_reward = defaultdict(list) # Create remote tasks remote_tasks = [ process_item.remote(config, data_sources[i], responses[i], reward_model_data[i]) for i in range(total) ] # Process results as they come in with tqdm(total=total) as pbar: while len(remote_tasks) > 0: # Use ray.wait to get completed tasks done_ids, remote_tasks = ray.wait(remote_tasks) for result_id in done_ids: data_source, score = ray.get(result_id) data_source_reward[data_source].append(score) pbar.update(1) metric_dict = {} for data_source, rewards in data_source_reward.items(): metric_dict[f"test_score/{data_source}"] = np.mean(rewards) print(metric_dict) if __name__ == "__main__": main()
verl__trainer__main_eval.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Generate responses given a dataset of prompts """ import os import hydra import numpy as np import ray os.environ["NCCL_DEBUG"] = "WARN" os.environ["TOKENIZERS_PARALLELISM"] = "true" # os.environ['TORCH_COMPILE_DISABLE'] = '1' from pprint import pprint import pandas as pd from omegaconf import OmegaConf from verl import DataProto from verl.protocol import pad_dataproto_to_divisor, unpad_dataproto from verl.single_controller.ray import RayClassWithInitArgs, RayResourcePool, RayWorkerGroup from verl.utils import hf_tokenizer from verl.utils.fs import copy_to_local from verl.utils.hdfs_io import makedirs from verl.utils.model import compute_position_id_with_mask from verl.workers.fsdp_workers import ActorRolloutRefWorker @hydra.main(config_path="config", config_name="generation", version_base=None) def main(config): run_generation(config) def run_generation(config) -> None: if not ray.is_initialized(): # this is for local ray cluster default_runtime_env = {"env_vars": {"TOKENIZERS_PARALLELISM": "true", "NCCL_DEBUG": "WARN"}} ray_init_kwargs = config.ray_kwargs.get("ray_init", {}) runtime_env_kwargs = ray_init_kwargs.get("runtime_env", {}) runtime_env = OmegaConf.merge(default_runtime_env, runtime_env_kwargs) ray_init_kwargs = OmegaConf.create({**ray_init_kwargs, "runtime_env": runtime_env}) print(f"ray init kwargs: {ray_init_kwargs}") ray.init(**OmegaConf.to_container(ray_init_kwargs)) ray.get(main_task.remote(config)) @ray.remote(num_cpus=1) def main_task(config): pprint(OmegaConf.to_container(config, resolve=True)) # resolve=True will eval symbol values OmegaConf.resolve(config) local_path = copy_to_local(config.model.path) trust_remote_code = config.data.get("trust_remote_code", False) tokenizer = hf_tokenizer(local_path, trust_remote_code=trust_remote_code) if config.rollout.temperature == 0.0: assert config.data.n_samples == 1, "When temperature=0, n_samples must be 1." assert config.data.n_samples >= 1, "n_samples should always >= 1" # read dataset. Note that the dataset should directly contain chat template format (e.g., a list of dictionary) dataset = pd.read_parquet(config.data.path) chat_lst = dataset[config.data.prompt_key].tolist() chat_lst = [chat.tolist() for chat in chat_lst] tokenizer.padding_side = "left" if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token ray_cls_with_init = RayClassWithInitArgs(cls=ray.remote(ActorRolloutRefWorker), config=config, role="rollout") resource_pool = RayResourcePool(process_on_nodes=[config.trainer.n_gpus_per_node] * config.trainer.nnodes) wg = RayWorkerGroup( resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, device_name=config.trainer.device, ) wg.init_model() total_samples = len(dataset) config_batch_size = config.data.batch_size apply_chat_template_kwargs = config.data.get("apply_chat_template_kwargs", {}) num_batch = -(-total_samples // config_batch_size) output_lst = [[] for _ in range(config.data.n_samples)] for batch_idx in range(num_batch): print(f"[{batch_idx + 1}/{num_batch}] Start to process.") batch_chat_lst = chat_lst[batch_idx * config_batch_size : (batch_idx + 1) * config_batch_size] inputs = tokenizer.apply_chat_template( batch_chat_lst, add_generation_prompt=True, padding=True, truncation=True, max_length=config.rollout.prompt_length, return_tensors="pt", return_dict=True, tokenize=True, **apply_chat_template_kwargs, ) input_ids = inputs["input_ids"] attention_mask = inputs["attention_mask"] position_ids = compute_position_id_with_mask(attention_mask) batch_dict = {"input_ids": input_ids, "attention_mask": attention_mask, "position_ids": position_ids} data = DataProto.from_dict(batch_dict) data_padded, pad_size = pad_dataproto_to_divisor(data, wg.world_size) # START TO GENERATE FOR n_samples TIMES print(f"[{batch_idx + 1}/{num_batch}] Start to generate.") for n_sample in range(config.data.n_samples): output_padded = wg.generate_sequences(data_padded) output = unpad_dataproto(output_padded, pad_size=pad_size) output_texts = [] for i in range(len(output)): data_item = output[i] prompt_length = data_item.batch["prompts"].shape[-1] valid_response_length = data_item.batch["attention_mask"][prompt_length:].sum() valid_response_ids = data_item.batch["responses"][:valid_response_length] response_str = tokenizer.decode(valid_response_ids, skip_special_tokens=True) output_texts.append(response_str) output_lst[n_sample].extend(output_texts) # convert output_lst from (n_samples, n_data) to (n_data, n_sampels) output_lst = np.array(output_lst, dtype=object) output_lst = np.transpose(output_lst, axes=(1, 0)).tolist() # add to the data frame dataset["responses"] = output_lst # write to a new parquet output_dir = os.path.dirname(config.data.output_path) makedirs(output_dir, exist_ok=True) dataset.to_parquet(config.data.output_path) if __name__ == "__main__": main()
verl__trainer__main_generation.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Generate responses given a dataset of prompts """ import os import aiohttp import hydra import numpy as np import ray os.environ["NCCL_DEBUG"] = "WARN" os.environ["TOKENIZERS_PARALLELISM"] = "true" # os.environ['TORCH_COMPILE_DISABLE'] = '1' import asyncio from pprint import pprint import pandas as pd from omegaconf import OmegaConf from openai.types.chat import ChatCompletion from verl.utils.hdfs_io import makedirs from verl.workers.rollout.replica import get_rollout_replica_class async def start_server(config): tp_size = config.actor_rollout_ref.rollout.tensor_model_parallel_size num_replicas = (config.trainer.n_gpus_per_node * config.trainer.nnodes) // tp_size rollout_config = config.actor_rollout_ref.rollout model_config = config.actor_rollout_ref.model # create standalone rollout server rollout_server_class = get_rollout_replica_class(config.actor_rollout_ref.rollout.name) rollout_servers = [ rollout_server_class( replica_rank=replica_rank, config=rollout_config, model_config=model_config, gpus_per_node=config.trainer.n_gpus_per_node, ) for replica_rank in range(num_replicas) ] await asyncio.gather(*[server.init_standalone() for server in rollout_servers]) server_handles = [server._server_handle for server in rollout_servers] server_addresses = [server._server_address for server in rollout_servers] assert len(server_handles) == num_replicas assert len(server_addresses) == num_replicas return server_handles, server_addresses async def submit_request(server_address, **chat_complete_request): try: extra_headers = chat_complete_request.pop("extra_headers", {}) timeout = aiohttp.ClientTimeout(total=None) session = aiohttp.ClientSession(timeout=timeout) async with session.post( url=f"http://{server_address}/v1/chat/completions", headers={"Authorization": "Bearer token-abc123", **extra_headers}, json=chat_complete_request, ) as resp: data = await resp.json() return ChatCompletion(**data) finally: await session.close() async def generate_per_replica(server_address, model_path: str, n_samples: int, sampling_params: dict, chat_lst: list): # here we should sample n_samples for each chat_lst. # we use aiohttp to avoid hang in AsyncOpenAI when the number of requests is large. # client = AsyncOpenAI( # api_key="123-abc", # base_url=f"http://{server_address}/v1", # ) chat_complete_request = [ { "model": model_path, "messages": messages, **sampling_params, } for messages in chat_lst for _ in range(n_samples) ] tasks = [submit_request(server_address, **req) for req in chat_complete_request] results = await asyncio.gather(*tasks) return results async def generate( server_addresses: list, model_path: str, n_samples: int, sampling_params: dict, chat_numpy: np.ndarray ): num_replicas = len(server_addresses) chat_sub_array = np.array_split(chat_numpy, num_replicas) chat_sub_array = [chat.tolist() for chat in chat_sub_array] assert len(server_addresses) == len(chat_sub_array) results = await asyncio.gather( *[ generate_per_replica(server_addresses[i], model_path, n_samples, sampling_params, chat_sub_array[i]) for i in range(num_replicas) ] ) return results @hydra.main(config_path="config", config_name="ppo_trainer", version_base=None) def main(config): ray.init(runtime_env={"env_vars": {"TOKENIZERS_PARALLELISM": "true", "NCCL_DEBUG": "WARN", "VLLM_USE_V1": "1"}}) pprint(OmegaConf.to_container(config, resolve=True)) # resolve=True will eval symbol values OmegaConf.resolve(config) n_samples = config.actor_rollout_ref.rollout.n if config.actor_rollout_ref.rollout.temperature == 0.0: assert n_samples == 1, "When temperature=0, n_samples must be 1." assert n_samples >= 1, "n_samples should always >= 1" sampling_params = { "temperature": config.actor_rollout_ref.rollout.temperature, "top_p": config.actor_rollout_ref.rollout.top_p, # "top_k": config.actor_rollout_ref.rollout.top_k, "max_tokens": config.actor_rollout_ref.rollout.response_length, } from omegaconf import ListConfig train_files = config.data.train_files if not isinstance(train_files, list | ListConfig): train_files = [train_files] # read dataset. Note that the dataset should directly contain chat template format (e.g., a list of dictionary) datasets = [] for train_file in train_files: dataset = pd.read_parquet(train_file) datasets.append(dataset) # concat dataset dataset = pd.concat(datasets, axis=0, ignore_index=True) chat_lst = dataset[config.data.prompt_key].tolist() chat_lst = [chat.tolist() for chat in chat_lst] chat_numpy = np.array(chat_lst) # start native server server_handles, server_addresses = asyncio.run(start_server(config)) # run generate gen_results = asyncio.run( generate(server_addresses, config.actor_rollout_ref.model.path, n_samples, sampling_params, chat_numpy) ) # reshape results into a numpy array import itertools results = list(itertools.chain.from_iterable(gen_results)) # extract content from results results = np.array([result.choices[0].message.content for result in results]) results = np.reshape(results, (-1, n_samples)) assert results.shape == (len(chat_lst), n_samples) results = results.tolist() # add to the data frame dataset["responses"] = results # write to a new parquet output_dir = os.path.dirname(config.data.output_path) makedirs(output_dir, exist_ok=True) print(f"Saving results to {config.data.output_path}") dataset.to_parquet(config.data.output_path) if __name__ == "__main__": main()
verl__trainer__main_generation_server.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Note that we don't combine the main with ray_trainer as ray_trainer is used by other mpain. """ import os import socket import hydra import ray from omegaconf import OmegaConf from verl.experimental.dataset.sampler import AbstractSampler from verl.experimental.reward_loop import migrate_legacy_reward_impl from verl.trainer.constants_ppo import get_ppo_ray_runtime_env from verl.trainer.ppo.ray_trainer import RayPPOTrainer from verl.trainer.ppo.utils import need_critic, need_reference_policy from verl.utils.config import validate_config from verl.utils.device import auto_set_device, is_cuda_available from verl.utils.import_utils import load_extern_object @hydra.main(config_path="config", config_name="ppo_trainer", version_base=None) def main(config): """Main entry point for PPO training with Hydra configuration management. Args: config: Hydra configuration dictionary containing training parameters. """ # Automatically set `config.trainer.device = npu` when running on Ascend NPU. auto_set_device(config) config = migrate_legacy_reward_impl(config) run_ppo(config) # Define a function to run the PPO-like training process def run_ppo(config, task_runner_class=None) -> None: """Initialize Ray cluster and run distributed PPO training process. Args: config: Training configuration object containing all necessary parameters for distributed PPO training including Ray initialization settings, model paths, and training hyperparameters. task_runner_class: For recipe to change TaskRunner. """ # Check if Ray is not initialized if not ray.is_initialized(): # Initialize Ray with a local cluster configuration # Set environment variables in the runtime environment to control tokenizer parallelism, # NCCL debug level, VLLM logging level, and allow runtime LoRA updating # `num_cpus` specifies the number of CPU cores Ray can use, obtained from the configuration default_runtime_env = get_ppo_ray_runtime_env() ray_init_kwargs = config.ray_kwargs.get("ray_init", {}) runtime_env_kwargs = ray_init_kwargs.get("runtime_env", {}) if config.transfer_queue.enable: # Add runtime environment variables for transfer queue runtime_env_vars = runtime_env_kwargs.get("env_vars", {}) runtime_env_vars["TRANSFER_QUEUE_ENABLE"] = "1" runtime_env_kwargs["env_vars"] = runtime_env_vars runtime_env = OmegaConf.merge(default_runtime_env, runtime_env_kwargs) ray_init_kwargs = OmegaConf.create({**ray_init_kwargs, "runtime_env": runtime_env}) print(f"ray init kwargs: {ray_init_kwargs}") ray.init(**OmegaConf.to_container(ray_init_kwargs)) if task_runner_class is None: task_runner_class = ray.remote(num_cpus=1)(TaskRunner) # please make sure main_task is not scheduled on head # Create a remote instance of the TaskRunner class, and # Execute the `run` method of the TaskRunner instance remotely and wait for it to complete if ( is_cuda_available and config.global_profiler.tool == "nsys" and config.global_profiler.get("steps") is not None and len(config.global_profiler.get("steps", [])) > 0 ): from verl.utils.import_utils import is_nvtx_available assert is_nvtx_available(), "nvtx is not available in CUDA platform. Please 'pip3 install nvtx'" nsight_options = OmegaConf.to_container( config.global_profiler.global_tool_config.nsys.controller_nsight_options ) runner = task_runner_class.options(runtime_env={"nsight": nsight_options}).remote() else: runner = task_runner_class.remote() ray.get(runner.run.remote(config)) # [Optional] get the path of the timeline trace file from the configuration, default to None # This file is used for performance analysis timeline_json_file = config.ray_kwargs.get("timeline_json_file", None) if timeline_json_file: ray.timeline(filename=timeline_json_file) class TaskRunner: """Ray remote class for executing distributed PPO training tasks. This class encapsulates the main training logic and runs as a Ray remote actor to enable distributed execution across multiple nodes and GPUs. Attributes: role_worker_mapping: Dictionary mapping Role enums to Ray remote worker classes mapping: Dictionary mapping Role enums to resource pool IDs for GPU allocation """ def __init__(self): self.role_worker_mapping = {} self.mapping = {} def add_actor_rollout_worker(self, config): """Add actor rollout worker based on the actor strategy.""" from verl.single_controller.ray import RayWorkerGroup from verl.trainer.ppo.ray_trainer import Role use_legacy_worker_impl = config.trainer.get("use_legacy_worker_impl", "auto") # use new model engine implementation if use_legacy_worker_impl == "disable": from verl.workers.engine_workers import ActorRolloutRefWorker actor_rollout_cls = ActorRolloutRefWorker ray_worker_group_cls = RayWorkerGroup lora_rank = config.actor_rollout_ref.model.get("lora", {}).get("rank", 0) if lora_rank <= 0: lora_rank = config.actor_rollout_ref.model.get("lora_rank", 0) ref_in_actor = lora_rank > 0 or config.actor_rollout_ref.model.get("lora_adapter_path") is not None # NOTE: In new model engine, ref policy and actor rollout are in same ActorRolloutRefWorker, # while in legacy model engine, ref policy is in a separate ActorRolloutRefWorker. if need_reference_policy(config) and not ref_in_actor: role = Role.ActorRolloutRef else: role = Role.ActorRollout self.role_worker_mapping[role] = ray.remote(actor_rollout_cls) self.mapping[role] = "global_pool" return actor_rollout_cls, ray_worker_group_cls # Note: sync mode validation is now handled in RolloutConfig.__post_init__ # Always use async worker since sync mode is deprecated and rejected if config.actor_rollout_ref.actor.strategy in {"fsdp", "fsdp2"}: from verl.workers.fsdp_workers import AsyncActorRolloutRefWorker actor_rollout_cls = AsyncActorRolloutRefWorker ray_worker_group_cls = RayWorkerGroup elif config.actor_rollout_ref.actor.strategy == "megatron": from verl.workers.megatron_workers import AsyncActorRolloutRefWorker actor_rollout_cls = AsyncActorRolloutRefWorker ray_worker_group_cls = RayWorkerGroup elif config.actor_rollout_ref.actor.strategy == "veomni": raise NotImplementedError("VeOmni does not support legacy worker implementation") else: raise NotImplementedError self.role_worker_mapping[Role.ActorRollout] = ray.remote(actor_rollout_cls) self.mapping[Role.ActorRollout] = "global_pool" return actor_rollout_cls, ray_worker_group_cls def add_critic_worker(self, config): """Add critic worker to role mapping.""" use_legacy_worker_impl = config.trainer.get("use_legacy_worker_impl", "auto") if config.critic.strategy in {"fsdp", "fsdp2"}: if use_legacy_worker_impl in ["auto", "enable"]: from verl.workers.fsdp_workers import CriticWorker elif use_legacy_worker_impl == "disable": # we don't need to specialize critic worker. Just use TrainingWorker from verl.workers.engine_workers import TrainingWorker CriticWorker = TrainingWorker print("Using new worker implementation") else: raise ValueError(f"Invalid use_legacy_worker_impl: {use_legacy_worker_impl}") elif config.critic.strategy == "megatron": # TODO: switch this to TrainingWorker as well from verl.workers.megatron_workers import CriticWorker elif config.critic.strategy == "veomni": if use_legacy_worker_impl == "disable": from verl.workers.engine_workers import TrainingWorker CriticWorker = TrainingWorker print("Using new worker implementation") else: raise ValueError(f"Invalid use_legacy_worker_impl: {use_legacy_worker_impl}") else: raise NotImplementedError from verl.trainer.ppo.ray_trainer import Role self.role_worker_mapping[Role.Critic] = ray.remote(CriticWorker) self.mapping[Role.Critic] = "global_pool" def init_resource_pool_mgr(self, config): """Initialize resource pool manager.""" global_pool_id = "global_pool" resource_pool_spec = { global_pool_id: [config.trainer.n_gpus_per_node] * config.trainer.nnodes, } if config.reward.reward_model.enable_resource_pool: if config.reward.reward_model.n_gpus_per_node <= 0: raise ValueError("config.reward.reward_model.n_gpus_per_node must be greater than 0") if config.reward.reward_model.nnodes <= 0: raise ValueError("config.reward.reward_model.nnodes must be greater than 0") reward_pool = [config.reward.reward_model.n_gpus_per_node] * config.reward.reward_model.nnodes resource_pool_spec["reward_pool"] = reward_pool else: config.reward.reward_model.nnodes = config.trainer.nnodes config.reward.reward_model.n_gpus_per_node = config.trainer.n_gpus_per_node from verl.trainer.ppo.ray_trainer import ResourcePoolManager resource_pool_manager = ResourcePoolManager(resource_pool_spec=resource_pool_spec, mapping=self.mapping) return resource_pool_manager def add_reward_model_resource_pool(self, config): """Add reward model worker if enabled.""" from verl.trainer.ppo.ray_trainer import Role if config.reward.reward_model.enable: # we do not use reward model workers, so we only register reward model in resource pool # without continue to register reward model worker in role mapping if config.reward.reward_model.enable_resource_pool: self.mapping[Role.RewardModel] = "reward_pool" else: self.mapping[Role.RewardModel] = "global_pool" def add_ref_policy_worker(self, config, ref_policy_cls): """Add reference policy worker if KL loss or KL reward is used.""" from verl.trainer.ppo.ray_trainer import Role # Ref policy has been fused into ActorRolloutRefWorker in new model engine, # we don't need to add a separate ref policy worker group. use_legacy_worker_impl = config.trainer.get("use_legacy_worker_impl", "auto") if use_legacy_worker_impl == "disable": return if need_reference_policy(config): self.role_worker_mapping[Role.RefPolicy] = ray.remote(ref_policy_cls) self.mapping[Role.RefPolicy] = "global_pool" def run(self, config): """Execute the main PPO training workflow. This method sets up the distributed training environment, initializes workers, datasets, and reward functions, then starts the training process. Args: config: Training configuration object containing all parameters needed for setting up and running the PPO training process. """ # Print the initial configuration. `resolve=True` will evaluate symbolic values. from pprint import pprint from omegaconf import OmegaConf from verl.utils.fs import copy_to_local print(f"TaskRunner hostname: {socket.gethostname()}, PID: {os.getpid()}") pprint(OmegaConf.to_container(config, resolve=True)) OmegaConf.resolve(config) actor_rollout_cls, ray_worker_group_cls = self.add_actor_rollout_worker(config) self.add_critic_worker(config) self.add_reward_model_resource_pool(config) # Add a reference policy worker if KL loss or KL reward is used. self.add_ref_policy_worker(config, actor_rollout_cls) # validate config validate_config( config=config, use_reference_policy=need_reference_policy(config), use_critic=need_critic(config), ) # Download the checkpoint from HDFS to the local machine. # `use_shm` determines whether to use shared memory, which could lead to faster model loading if turned on local_path = copy_to_local( config.actor_rollout_ref.model.path, use_shm=config.actor_rollout_ref.model.get("use_shm", False) ) # Instantiate the tokenizer and processor. from verl.utils import hf_processor, hf_tokenizer trust_remote_code = config.data.get("trust_remote_code", False) tokenizer = hf_tokenizer(local_path, trust_remote_code=trust_remote_code) # Used for multimodal LLM, could be None processor = hf_processor(local_path, trust_remote_code=trust_remote_code, use_fast=True) resource_pool_manager = self.init_resource_pool_mgr(config) from verl.utils.dataset.rl_dataset import collate_fn # Create training and validation datasets. train_dataset = create_rl_dataset( config.data.train_files, config.data, tokenizer, processor, is_train=True, max_samples=config.data.get("train_max_samples", -1), ) val_dataset = create_rl_dataset( config.data.val_files, config.data, tokenizer, processor, is_train=False, max_samples=config.data.get("val_max_samples", -1), ) train_sampler = create_rl_sampler(config.data, train_dataset) # Initialize the PPO trainer. trainer = RayPPOTrainer( config=config, tokenizer=tokenizer, processor=processor, role_worker_mapping=self.role_worker_mapping, resource_pool_manager=resource_pool_manager, ray_worker_group_cls=ray_worker_group_cls, train_dataset=train_dataset, val_dataset=val_dataset, collate_fn=collate_fn, train_sampler=train_sampler, ) # Initialize the workers of the trainer. trainer.init_workers() # Start the training process. trainer.fit() def create_rl_dataset(data_paths, data_config, tokenizer, processor, is_train=True, max_samples: int = -1): """Create a dataset. Arguments: data_paths: List of paths to data files. data_config: The data config. tokenizer (Tokenizer): The tokenizer. processor (Processor): The processor. Returns: dataset (Dataset): The dataset. """ from verl.utils.dataset.rl_dataset import get_dataset_class # Get the dataset class dataset_cls = get_dataset_class(data_config) # Instantiate the dataset using the determined dataset class dataset = dataset_cls( data_files=data_paths, tokenizer=tokenizer, processor=processor, config=data_config, max_samples=max_samples, ) return dataset def create_rl_sampler(data_config, dataset): """Create a sampler for the dataset. Arguments: data_config: The data config. dataset (Dataset): The dataset. Returns: sampler (Sampler): The sampler. """ import torch from torch.utils.data import SequentialSampler # torch.utils.data.RandomSampler could not recover properly from torchdata.stateful_dataloader.sampler import RandomSampler if data_config.sampler is not None and data_config.sampler.get("class_path", None) is not None: curriculum_class = load_extern_object( data_config.sampler.class_path, data_config.sampler.class_name, ) sampler = curriculum_class( data_source=dataset, data_config=data_config, ) assert isinstance(sampler, AbstractSampler) assert data_config.get("dataloader_num_workers", 8) == 0, ( "If using curriculum, num_workers must be 0 to prevent data caching. " "If the dataloader caches data before the batch is done the " "curriculum sampler won't have the opportunity to reorder it. " ) # Use a sampler to facilitate checkpoint resumption. # If shuffling is enabled in the data configuration, create a random sampler. elif data_config.shuffle: train_dataloader_generator = torch.Generator() seed = data_config.get("seed") if seed is not None: train_dataloader_generator.manual_seed(seed) sampler = RandomSampler(data_source=dataset, generator=train_dataloader_generator) else: # If shuffling is disabled, use a sequential sampler to iterate through the dataset in order. sampler = SequentialSampler(data_source=dataset) return sampler if __name__ == "__main__": main()
verl__trainer__main_ppo.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Metrics related to the PPO trainer. """ from collections import defaultdict from functools import partial from typing import Any, Callable import numpy as np import torch import verl.utils.torch_functional as verl_F from verl import DataProto from verl.utils.import_utils import deprecated @deprecated("verl.utils.metric.reduce_metrics") def reduce_metrics(metrics: dict[str, list[Any]]) -> dict[str, Any]: """ Reduces a dictionary of metric lists by computing the mean of each list. Args: metrics: A dictionary mapping metric names to lists of metric values. Returns: A dictionary with the same keys but with each list replaced by its mean value. Example: >>> metrics = {"loss": [1.0, 2.0, 3.0], "accuracy": [0.8, 0.9, 0.7]} >>> reduce_metrics(metrics) {"loss": 2.0, "accuracy": 0.8} """ from verl.utils.metric import reduce_metrics return reduce_metrics(metrics) def _compute_response_info(batch: DataProto) -> dict[str, Any]: """ Computes information about prompts and responses from a batch. This is an internal helper function that extracts masks and lengths for prompts and responses. Args: batch: A DataProto object containing batch data with responses and attention masks. Returns: A dictionary containing: - response_mask: Attention mask for the response tokens - prompt_length: Tensor of prompt lengths for each item in the batch - response_length: Tensor of response lengths for each item in the batch """ response_length = batch.batch["responses"].shape[-1] prompt_mask = batch.batch["attention_mask"][:, :-response_length] response_mask = batch.batch["attention_mask"][:, -response_length:] prompt_length = prompt_mask.sum(-1).float() response_length = response_mask.sum(-1).float() # (batch_size,) return dict( response_mask=response_mask, prompt_length=prompt_length, response_length=response_length, ) def compute_data_metrics(batch: DataProto, use_critic: bool = True) -> dict[str, Any]: """ Computes various metrics from a batch of data for PPO training. This function calculates metrics related to scores, rewards, advantages, returns, values, and sequence lengths from a batch of data. It provides statistical information (mean, max, min) for each metric category. Args: batch: A DataProto object containing batch data with token-level scores, rewards, advantages, etc. use_critic: Whether to include critic-specific metrics. Defaults to True. Returns: A dictionary of metrics including: - critic/score/mean, max, min: Statistics about sequence scores - critic/rewards/mean, max, min: Statistics about sequence rewards - critic/advantages/mean, max, min: Statistics about advantages - critic/returns/mean, max, min: Statistics about returns - critic/values/mean, max, min: Statistics about critic values (if use_critic=True) - critic/vf_explained_var: Explained variance of the value function (if use_critic=True) - response_length/mean, max, min, clip_ratio: Statistics about response lengths - prompt_length/mean, max, min, clip_ratio: Statistics about prompt lengths - num_turns/mean, max, min: Statistics about the number of multi-turn conversations """ sequence_score = batch.batch["token_level_scores"].sum(-1) sequence_reward = batch.batch["token_level_rewards"].sum(-1) advantages = batch.batch["advantages"] returns = batch.batch["returns"] max_response_length = batch.batch["responses"].shape[-1] prompt_mask = batch.batch["attention_mask"][:, :-max_response_length].bool() response_mask = batch.batch["response_mask"].bool() max_prompt_length = prompt_mask.size(-1) response_info = _compute_response_info(batch) prompt_length = response_info["prompt_length"] response_length = response_info["response_length"] aborted_mask = (response_length == 0).bool() non_aborted_mask = ~aborted_mask non_aborted_sequence_score = sequence_score[non_aborted_mask] non_aborted_sequence_reward = sequence_reward[non_aborted_mask] score_mean = torch.mean(non_aborted_sequence_score).detach().item() score_max = torch.max(non_aborted_sequence_score).detach().item() score_min = torch.min(non_aborted_sequence_score).detach().item() reward_mean = torch.mean(non_aborted_sequence_reward).detach().item() reward_max = torch.max(non_aborted_sequence_reward).detach().item() reward_min = torch.min(non_aborted_sequence_reward).detach().item() valid_adv = torch.masked_select(advantages, response_mask) valid_returns = torch.masked_select(returns, response_mask) if use_critic: values = batch.batch["values"] valid_values = torch.masked_select(values, response_mask) return_diff_var = torch.var(valid_returns - valid_values) return_var = torch.var(valid_returns) # Aborted samples and non-aborted response length statistics # response_length_non_aborted/*: statistics computed on non-aborted samples only aborted_ratio = torch.mean(aborted_mask.float()).detach().item() non_aborted_response_length = response_length[non_aborted_mask] if non_aborted_response_length.numel() > 0: non_aborted_response_length_mean = torch.mean(non_aborted_response_length).detach().item() non_aborted_response_length_max = torch.max(non_aborted_response_length).detach().item() non_aborted_response_length_min = torch.min(non_aborted_response_length).detach().item() non_aborted_response_length_clip_ratio = ( torch.mean(torch.eq(non_aborted_response_length, max_response_length).float()).detach().item() ) else: raise ValueError("All samples are aborted, this should not happen.") metrics = { # score "critic/score/mean": score_mean, "critic/score/max": score_max, "critic/score/min": score_min, # reward "critic/rewards/mean": reward_mean, "critic/rewards/max": reward_max, "critic/rewards/min": reward_min, # adv "critic/advantages/mean": torch.mean(valid_adv).detach().item(), "critic/advantages/max": torch.max(valid_adv).detach().item(), "critic/advantages/min": torch.min(valid_adv).detach().item(), # returns "critic/returns/mean": torch.mean(valid_returns).detach().item(), "critic/returns/max": torch.max(valid_returns).detach().item(), "critic/returns/min": torch.min(valid_returns).detach().item(), **( { # values "critic/values/mean": torch.mean(valid_values).detach().item(), "critic/values/max": torch.max(valid_values).detach().item(), "critic/values/min": torch.min(valid_values).detach().item(), # vf explained var "critic/vf_explained_var": (1.0 - return_diff_var / (return_var + 1e-5)).detach().item(), } if use_critic else {} ), # response length "response_length/mean": torch.mean(response_length).detach().item(), "response_length/max": torch.max(response_length).detach().item(), "response_length/min": torch.min(response_length).detach().item(), "response_length/clip_ratio": torch.mean(torch.eq(response_length, max_response_length).float()) .detach() .item(), # response length (non-aborted only) # These statistics exclude aborted samples to avoid skew from zeros "response_length_non_aborted/mean": non_aborted_response_length_mean, "response_length_non_aborted/max": non_aborted_response_length_max, "response_length_non_aborted/min": non_aborted_response_length_min, "response_length_non_aborted/clip_ratio": non_aborted_response_length_clip_ratio, # aborted ratio # Fraction of samples whose response length is zero "response/aborted_ratio": aborted_ratio, # prompt length "prompt_length/mean": torch.mean(prompt_length).detach().item(), "prompt_length/max": torch.max(prompt_length).detach().item(), "prompt_length/min": torch.min(prompt_length).detach().item(), "prompt_length/clip_ratio": torch.mean(torch.eq(prompt_length, max_prompt_length).float()).detach().item(), } # multi-turn conversation if "__num_turns__" in batch.non_tensor_batch: num_turns = batch.non_tensor_batch["__num_turns__"] metrics["num_turns/min"] = num_turns.min() metrics["num_turns/max"] = num_turns.max() metrics["num_turns/mean"] = num_turns.mean() if "tool_call_counts" in batch.non_tensor_batch: tool_call_counts = batch.non_tensor_batch["tool_call_counts"] metrics["tool_call_counts/min"] = tool_call_counts.min() metrics["tool_call_counts/max"] = tool_call_counts.max() metrics["tool_call_counts/mean"] = tool_call_counts.mean() return metrics def compute_timing_metrics(batch: DataProto, timing_raw: dict[str, float]) -> dict[str, Any]: """ Computes timing metrics for different processing stages in PPO training. This function calculates both raw timing metrics (in seconds) and per-token timing metrics (in milliseconds) for various processing stages like generation, reference computation, value computation, advantage computation, and model updates. Args: batch: A DataProto object containing batch data with responses and attention masks. timing_raw: A dictionary mapping stage names to their execution times in seconds. Returns: A dictionary containing: - timing_s/{name}: Raw timing in seconds for each stage - timing_per_token_ms/{name}: Per-token timing in milliseconds for each stage Note: Different stages use different token counts for normalization: - "gen" uses only response tokens - Other stages ("ref", "values", "adv", "update_critic", "update_actor") use all tokens (prompt + response) """ response_info = _compute_response_info(batch) num_prompt_tokens = torch.sum(response_info["prompt_length"]).item() num_response_tokens = torch.sum(response_info["response_length"]).item() num_overall_tokens = num_prompt_tokens + num_response_tokens num_tokens_of_section = { "gen": num_response_tokens, **{name: num_overall_tokens for name in ["ref", "values", "adv", "update_critic", "update_actor"]}, } return { **{f"timing_s/{name}": value for name, value in timing_raw.items()}, **{ f"timing_per_token_ms/{name}": timing_raw[name] * 1000 / num_tokens_of_section[name] for name in set(num_tokens_of_section.keys()) & set(timing_raw.keys()) }, } def compute_throughout_metrics(batch: DataProto, timing_raw: dict[str, float], n_gpus: int) -> dict[str, Any]: """ Computes throughput metrics for PPO training. This function calculates performance metrics related to token processing speed, including the total number of tokens processed, time per step, and throughput (tokens per second per GPU). Args: batch: A DataProto object containing batch data with meta information about token counts. timing_raw: A dictionary mapping stage names to their execution times in seconds. Must contain a "step" key with the total step time. n_gpus: Number of GPUs used for training. Returns: A dictionary containing: - perf/total_num_tokens: Total number of tokens processed in the batch - perf/time_per_step: Time taken for the step in seconds - perf/throughput: Tokens processed per second per GPU Note: The throughput is calculated as total_tokens / (time * n_gpus) to normalize across different GPU counts. """ total_num_tokens = sum(batch.meta_info["global_token_num"]) time = timing_raw["step"] # estimated_flops, promised_flops = flops_function.estimate_flops(num_tokens, time) # f'Actual TFLOPs/s/GPU​': estimated_flops/(n_gpus), # f'Theoretical TFLOPs/s/GPU​': promised_flops, return { "perf/total_num_tokens": total_num_tokens, "perf/time_per_step": time, "perf/throughput": total_num_tokens / (time * n_gpus), } def compute_variance_proxy_metrics(batch: DataProto, gradient_norm: float = None) -> dict[str, float]: """ Compute variance proxy metrics using the simplified expected squared norm approach. This metric provides a computationally efficient way to monitor gradient variance during training. It works for any advantage estimator as long as sum_pi_squared is available from the actor. Theory: - Full variance: Var(g̃) = E[||g̃||²] - ||g_true||² - Simplified proxy (when ||g_true||² ≈ 0): Var(g̃) ≈ E[||g̃||²] - Using W-score approximation: E[||g̃||²] ≈ E[A² × W(τ)] Where W(τ) = Σ_t[1 - 2π_t(y_t) + Σπ²] is the score-norm proxy. """ metrics = {} # Check if we have the necessary data (sum_pi_squared is required for W-score) if "sum_pi_squared" not in batch.batch or "old_log_probs" not in batch.batch or "advantages" not in batch.batch: return metrics # Compute W(τ) = Σ_t[1 - 2π_t(y_t) + Σπ²] pi_t = torch.exp(batch.batch["old_log_probs"]) w_per_timestep = 1 - 2 * pi_t + batch.batch["sum_pi_squared"] # Get response mask to only consider valid tokens response_mask = batch.batch["response_mask"] # Use pre-computed rollout IS weights from batch (for variance proxy consistency with training loss) # IS weights are computed centrally in ray_trainer.py to avoid duplication rollout_is_weights = None if "rollout_is_weights" in batch.batch: # Extract pre-computed IS weights from batch (already computed in trainer) rollout_is_weights = batch.batch["rollout_is_weights"] # Scale W by (rollout IS weight)² for optimal baseline under biased estimation w_per_timestep = w_per_timestep * (rollout_is_weights**2).detach() # Note: IS weight statistics and mismatch metrics are logged in ray_trainer.py # Get scalar advantages (mean over timesteps) advantages = batch.batch["advantages"] # Compute mean advantage per trajectory using masked_mean advantages_scalar = verl_F.masked_mean(advantages, response_mask, axis=-1) # Compute W values (sum over timesteps) w_values = verl_F.masked_sum(w_per_timestep, response_mask, axis=-1) # ====== COMPUTE VARIANCE PROXIES ====== # Variance proxy should match the actual gradient computation: # - If IS weights were computed/applied: use them in variance proxy calculation # - Otherwise: compute on-policy variance proxy # ====== PROXY 1: Signal Strength ||ḡ||² ====== # The squared norm of the mean gradient (provided from training loop) proxy1_signal_strength = gradient_norm**2 if gradient_norm is not None else None # ====== PROXY 2: Total Power E[||ĝ_τ||²] ====== # Measures the average of squared gradient norms (Signal + Noise) if rollout_is_weights is not None: # Off-policy with IS correction applied: use clamped weights consistently with actual gradient computation rollout_is_weights_scalar = verl_F.masked_mean(rollout_is_weights, response_mask, axis=-1) # Recover original W (before IS correction was applied in line 657) # Clamp to avoid division by zero when IS weights are zero w_original = verl_F.masked_sum( w_per_timestep / torch.clamp((rollout_is_weights**2).detach(), min=1e-10), response_mask, axis=-1 ) # Clamp W to avoid negative values (which would cause NaN in sqrt) w_original = torch.clamp(w_original, min=0.0) # Proxy 2 for off-policy: E[ρ̄² × A² × W] proxy2_total_power = ((rollout_is_weights_scalar**2) * (advantages_scalar**2) * w_original).mean() else: # On-policy Proxy 2: E[A² × W] # Clamp W to avoid negative values (which would cause NaN in sqrt) w_values_clamped = torch.clamp(w_values, min=0.0) proxy2_total_power = (advantages_scalar**2 * w_values_clamped).mean() # ====== PROXY 3: Pure Noise - Variance of Mean Vector ====== # Requires ||ḡ||² from actual batch gradient # Formula: (1/(N-1)) × (Proxy2 - Proxy1) proxy3_pure_noise = None if proxy1_signal_strength is not None: batch_size = advantages_scalar.shape[0] if batch_size > 1: proxy3_pure_noise = (1.0 / (batch_size - 1)) * (proxy2_total_power - proxy1_signal_strength) # Ensure non-negative (can be negative due to numerical errors) proxy3_pure_noise = max( 0.0, proxy3_pure_noise.item() if torch.is_tensor(proxy3_pure_noise) else proxy3_pure_noise ) # Decompose into components for analysis expected_a_squared = (advantages_scalar**2).mean() expected_w = w_values.mean() metrics.update( { # Proxy 1: Signal Strength ||ḡ||² "variance_proxy/proxy1_signal_strength": ( proxy1_signal_strength if proxy1_signal_strength is not None else 0.0 ), # Proxy 2: Total Power E[||ĝ_τ||²] "variance_proxy/proxy2_total_power": proxy2_total_power.detach().item(), # Proxy 3: Pure Noise - Variance of Mean Vector "variance_proxy/proxy3_pure_noise": proxy3_pure_noise if proxy3_pure_noise is not None else 0.0, # Component metrics for debugging "variance_proxy/expected_a_squared": expected_a_squared.detach().item(), "variance_proxy/expected_w": expected_w.detach().item(), } ) return metrics def bootstrap_metric( data: list[Any], subset_size: int, reduce_fns: list[Callable[[np.ndarray], float]], n_bootstrap: int = 1000, seed: int = 42, ) -> list[tuple[float, float]]: """ Performs bootstrap resampling to estimate statistics of metrics. This function uses bootstrap resampling to estimate the mean and standard deviation of metrics computed by the provided reduction functions on random subsets of the data. Args: data: List of data points to bootstrap from. subset_size: Size of each bootstrap sample. reduce_fns: List of functions that compute a metric from a subset of data. n_bootstrap: Number of bootstrap iterations. Defaults to 1000. seed: Random seed for reproducibility. Defaults to 42. Returns: A list of tuples, where each tuple contains (mean, std) for a metric corresponding to each reduction function in reduce_fns. Example: >>> data = [1, 2, 3, 4, 5] >>> reduce_fns = [np.mean, np.max] >>> bootstrap_metric(data, 3, reduce_fns) [(3.0, 0.5), (4.5, 0.3)] # Example values """ np.random.seed(seed) data_np = np.array(data, dtype=object) n_data = len(data_np) # generate bootstrap indices, shape: (n_bootstrap, subset_size) bootstrap_idxs = np.random.choice(n_data, size=(n_bootstrap, subset_size), replace=True) # pre-allocate result array, shape: (n_fns, n_bootstrap) n_fns = len(reduce_fns) metric_results = np.empty((n_fns, n_bootstrap), dtype=np.float64) # compute metric results for each bootstrap sample for fn_idx, reduce_fn in enumerate(reduce_fns): # bootstrap sample and compute metric for boot_idx in range(n_bootstrap): sample = data_np[bootstrap_idxs[boot_idx]] metric_results[fn_idx, boot_idx] = reduce_fn(sample) # compute mean and std for each metric function result = [ (float(np.mean(metric_results[fn_idx])), float(np.std(metric_results[fn_idx]))) for fn_idx in range(n_fns) ] return result def calc_maj_val(data: list[dict[str, Any]], vote_key: str, val_key: str) -> float: """ Calculate a value based on majority voting. This function identifies the most common value for a specified vote key in the data, then returns the corresponding value for that majority vote. Args: data: List of dictionaries, where each dictionary contains both vote_key and val_key. vote_key: The key in each dictionary used for voting/counting. val_key: The key in each dictionary whose value will be returned for the majority vote. Returns: The value associated with the most common vote. Example: >>> data = [ ... {"pred": "A", "val": 0.9}, ... {"pred": "B", "val": 0.8}, ... {"pred": "A", "val": 0.7} ... ] >>> calc_maj_val(data, vote_key="pred", val_key="val") 0.9 # Returns the first "val" for the majority vote "A" """ vote2vals = defaultdict(list) for d in data: vote2vals[d[vote_key]].append(d[val_key]) vote2cnt = {k: len(v) for k, v in vote2vals.items()} maj_vote = max(vote2cnt, key=vote2cnt.get) maj_val = vote2vals[maj_vote][0] return maj_val def process_validation_metrics( data_sources: list[str], sample_uids: list[str], infos_dict: dict[str, list[Any]], seed: int = 42 ) -> dict[str, dict[str, dict[str, float]]]: """ Process validation metrics into a structured format with statistical analysis. This function organizes validation metrics by data source and prompt, then computes various statistical measures including means, standard deviations, best/worst values, and majority voting results. It also performs bootstrap sampling to estimate statistics for different sample sizes. Args: data_sources: List of data source identifiers for each sample. sample_uids: List of sample uids corresponding to each sample. infos_dict: Dictionary mapping variable names to lists of values for each sample. seed: Random seed for bootstrap sampling. Defaults to 42. Returns: A nested dictionary with the structure: { data_source: { variable_name: { metric_name: value } } } Where metric_name includes: - "mean@N": Mean value across N samples - "std@N": Standard deviation across N samples - "best@N/mean": Mean of the best values in bootstrap samples of size N - "best@N/std": Standard deviation of the best values in bootstrap samples - "worst@N/mean": Mean of the worst values in bootstrap samples - "worst@N/std": Standard deviation of the worst values in bootstrap samples - "maj@N/mean": Mean of majority voting results in bootstrap samples (if "pred" exists) - "maj@N/std": Standard deviation of majority voting results (if "pred" exists) Example: >>> data_sources = ["source1", "source1", "source2"] >>> sample_uids = ["uid1", "uid1", "uid2"] >>> infos_dict = {"score": [0.8, 0.9, 0.7], "pred": ["A", "A", "B"]} >>> result = process_validation_metrics(data_sources, sample_uids, infos_dict) >>> # result will contain statistics for each data source and variable """ # Group metrics by data source, prompt and variable data_src2uid2var2vals = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) for sample_idx, data_source in enumerate(data_sources): uid = sample_uids[sample_idx] var2vals = data_src2uid2var2vals[data_source][uid] for var_name, var_vals in infos_dict.items(): var2vals[var_name].append(var_vals[sample_idx]) np_mean = np.mean np_std = np.std reduce_fns_best_worst = [np.max, np.min] n_bootstrap = 1000 # 2. cache ns list def gen_ns(n_resps: int) -> list[int]: if n_resps <= 1: return [] ns = [] n = 2 while n < n_resps: ns.append(n) n *= 2 ns.append(n_resps) return ns ns_cache = {} # 3. cache metric results data_src2uid2var2metric = {} # 4. flatten loop for data_source, uid2var2vals in data_src2uid2var2vals.items(): # create uid dict uid_dict = data_src2uid2var2metric.setdefault(data_source, {}) for uid, var2vals in uid2var2vals.items(): pred_vals = var2vals.get("pred") has_pred = pred_vals is not None var_dict = uid_dict.setdefault(uid, {}) for var_name, var_vals in var2vals.items(): # skip empty or string values if not var_vals or isinstance(var_vals[0], str): continue # compute mean and std n_resps = len(var_vals) metric = {f"mean@{n_resps}": float(np_mean(var_vals))} if n_resps > 1: metric[f"std@{n_resps}"] = float(np_std(var_vals)) # cache ns list if n_resps not in ns_cache: ns_cache[n_resps] = gen_ns(n_resps) ns = ns_cache[n_resps] # compute best/worst metrics for n in ns: # compute best/worst metrics (bon_mean, bon_std), (won_mean, won_std) = bootstrap_metric( data=var_vals, subset_size=n, reduce_fns=reduce_fns_best_worst, n_bootstrap=n_bootstrap, seed=seed, ) metric[f"best@{n}/mean"] = bon_mean metric[f"best@{n}/std"] = bon_std metric[f"worst@{n}/mean"] = won_mean metric[f"worst@{n}/std"] = won_std # compute maj metrics if has_pred: # create vote_data vote_data = [ {"val": val, "pred": pred} for val, pred in zip(var_vals, pred_vals, strict=True) ] # compute maj metrics [(maj_n_mean, maj_n_std)] = bootstrap_metric( data=vote_data, subset_size=n, reduce_fns=[partial(calc_maj_val, vote_key="pred", val_key="val")], n_bootstrap=n_bootstrap, seed=seed, ) metric[f"maj@{n}/mean"] = maj_n_mean metric[f"maj@{n}/std"] = maj_n_std var_dict[var_name] = metric # Aggregate metrics across uids data_src2var2metric2uid_vals = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) for data_source, uid2var2metric in data_src2uid2var2metric.items(): for uid, var2metric in uid2var2metric.items(): for var_name, metric in var2metric.items(): for metric_name, metric_val in metric.items(): data_src2var2metric2uid_vals[data_source][var_name][metric_name].append(metric_val) data_src2var2metric2val = defaultdict(lambda: defaultdict(lambda: defaultdict(float))) for data_source, var2metric2uid_vals in data_src2var2metric2uid_vals.items(): for var_name, metric2uid_vals in var2metric2uid_vals.items(): for metric_name, uid_vals in metric2uid_vals.items(): data_src2var2metric2val[data_source][var_name][metric_name] = np.mean(uid_vals) return data_src2var2metric2val
verl__trainer__ppo__metric_utils.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import torch from prefix_grouper import PrefixGrouper from verl.utils.torch_functional import logprobs_from_logits def build_position_ids_for_prefix_grouper(prefix_grouper: PrefixGrouper) -> torch.Tensor: """Build position_ids for PrefixGrouper where each response restarts from prefix_len.""" num_samples = len(prefix_grouper.group_info) max_len = prefix_grouper.padding_mask.size(1) device = prefix_grouper.padding_mask.device position_ids = torch.zeros(num_samples, max_len, dtype=torch.long, device=device) for i, group in enumerate(prefix_grouper.group_info): prefix_len = group.prefix_len position_ids[i, :prefix_len] = torch.arange(prefix_len, device=device) cur_pos = prefix_len for suffix_len in group.suffix_lens: if suffix_len > 0: position_ids[i, cur_pos : cur_pos + suffix_len] = torch.arange( prefix_len, prefix_len + suffix_len, device=device ) cur_pos += suffix_len return position_ids def build_pg_from_micro_batch( micro_batch: dict, pad_token_id: int, padding_mode: str = "right", ): """Build PrefixGrouper from micro_batch dict containing prompts, responses, response_mask, uid.""" prompts = micro_batch["prompts"] responses = micro_batch["responses"] response_mask = micro_batch["response_mask"] uids = micro_batch["uid"] bs = responses.size(0) group_sizes = [] cur = 1 for i in range(1, bs): if uids[i] == uids[i - 1]: cur += 1 else: group_sizes.append(cur) cur = 1 group_sizes.append(cur) prefix_indices = [] cursor = 0 for gs in group_sizes: prefix_indices.append(cursor) cursor += gs prefix_indices = torch.tensor(prefix_indices, device=prompts.device) prefix_ids = prompts.index_select(0, prefix_indices) prefix_mask = prefix_ids.ne(pad_token_id) prefix_grouper = PrefixGrouper.from_ungrouped_masks( prefix_mask=prefix_mask, suffix_mask=response_mask, group_sizes=group_sizes, padding_mode=padding_mode, device=prompts.device, ) concat_input_ids = prefix_grouper.concat_input(prefix_ids, prefix_mask, responses, response_mask) attention_mask = prefix_grouper.padding_mask position_ids = build_position_ids_for_prefix_grouper(prefix_grouper) return ( prefix_grouper, concat_input_ids, attention_mask, position_ids, responses, response_mask, ) def pg_forward( model, prefix_grouper, concat_input_ids, attention_mask, position_ids, completion_ids, completion_mask, *, temperature=1.0, padding_mode="right", include_prefix_last=1, calculate_entropy=False, entropy_fn=None, ): logits = model( input_ids=concat_input_ids, attention_mask=attention_mask, position_ids=position_ids, use_cache=False, prefix_grouper=prefix_grouper, ).logits prefix_out, prefix_mask, suffix_out_raw, suffix_mask_raw = prefix_grouper.split_output( logits, include_prefix_last=include_prefix_last ) completion_ids_right = prefix_grouper.convert_padding( completion_ids, completion_mask, padding_mode=padding_mode, ) suffix_out = suffix_out_raw[:, :-1].float() suffix_mask = suffix_mask_raw[:, 1:] suffix_out /= temperature log_probs = logprobs_from_logits(suffix_out, completion_ids_right) entropy = None if calculate_entropy and entropy_fn is not None: entropy = entropy_fn(suffix_out) return log_probs, entropy, suffix_mask def forward_micro_batch_with_prefix_grouper( micro_batch: dict, model, temperature: float, calculate_entropy: bool, device_name: str, param_dtype, use_chunking_entropy: bool = False, ): """ Forward pass using PrefixGrouper for shared-prefix optimization. Args: micro_batch: Dict containing prompts, responses, response_mask, uid, etc. model: The actor module. temperature: Temperature for logits scaling. calculate_entropy: Whether to compute entropy. device_name: Device name for autocast. param_dtype: Parameter dtype for autocast. use_chunking_entropy: Whether to use chunking entropy function. Returns: tuple: (entropy, log_probs) where entropy may be None if not calculated. """ import verl.utils.torch_functional as verl_F entropy_fn = None if calculate_entropy: if use_chunking_entropy: entropy_fn = verl_F.entropy_from_logits_with_chunking else: entropy_fn = verl_F.entropy_from_logits pad_token_id = micro_batch.get("pad_token_id", 0) ( prefix_grouper, concat_input_ids, attention_mask, position_ids, responses, response_mask, ) = build_pg_from_micro_batch( micro_batch, pad_token_id=pad_token_id, padding_mode="right", ) with torch.autocast(device_type=device_name, dtype=param_dtype): log_probs, entropy, suffix_mask_from_pg = pg_forward( model=model, prefix_grouper=prefix_grouper, concat_input_ids=concat_input_ids, attention_mask=attention_mask, position_ids=position_ids, completion_ids=responses, completion_mask=response_mask, temperature=temperature, padding_mode="right", include_prefix_last=1, calculate_entropy=calculate_entropy, entropy_fn=entropy_fn, ) # Zero out padding positions padding_mask = suffix_mask_from_pg == 0 log_probs = log_probs.masked_fill(padding_mask, 0.0) if entropy is not None: entropy = entropy.masked_fill(padding_mask, 0.0) # Pad to target response length if needed target_response_length = responses.size(1) if log_probs.size(1) != target_response_length: batch_size = log_probs.size(0) current_len = log_probs.size(1) full_log_probs = log_probs.new_zeros(batch_size, target_response_length) full_log_probs[:, :current_len] = log_probs log_probs = full_log_probs if entropy is not None: full_entropy = entropy.new_zeros(batch_size, target_response_length) full_entropy[:, :current_len] = entropy entropy = full_entropy return entropy, log_probs
verl__trainer__ppo__prefix_grouper_utils.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023-2024 SGLang Team # Copyright 2025 ModelBest Inc. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PPO Trainer with Ray-based single controller. This trainer supports model-agonistic model initialization with huggingface """ import json import os import uuid from collections import defaultdict from copy import deepcopy from pprint import pprint from typing import Any, Optional import numpy as np import torch from omegaconf import OmegaConf, open_dict from torch.utils.data import Dataset, Sampler from torchdata.stateful_dataloader import StatefulDataLoader from tqdm import tqdm from verl import DataProto from verl.checkpoint_engine import CheckpointEngineManager from verl.experimental.dataset.sampler import AbstractCurriculumSampler from verl.protocol import pad_dataproto_to_divisor, unpad_dataproto from verl.single_controller.ray import RayClassWithInitArgs, RayWorkerGroup, ResourcePoolManager from verl.single_controller.ray.base import create_colocated_worker_cls from verl.trainer.config import AlgoConfig from verl.trainer.ppo import core_algos from verl.trainer.ppo.core_algos import AdvantageEstimator, agg_loss from verl.trainer.ppo.metric_utils import ( compute_data_metrics, compute_throughout_metrics, compute_timing_metrics, compute_variance_proxy_metrics, process_validation_metrics, ) from verl.trainer.ppo.reward import extract_reward from verl.trainer.ppo.utils import Role, WorkerType, need_critic, need_reference_policy, need_reward_model from verl.utils import tensordict_utils as tu from verl.utils.checkpoint.checkpoint_manager import find_latest_ckpt_path, should_save_ckpt_esi from verl.utils.config import omega_conf_to_dataclass from verl.utils.debug import marked_timer from verl.utils.import_utils import load_class_from_fqn from verl.utils.metric import reduce_metrics from verl.utils.py_functional import rename_dict from verl.utils.rollout_skip import RolloutSkip from verl.utils.seqlen_balancing import calculate_workload, get_seqlen_balanced_partitions, log_seqlen_unbalance from verl.utils.torch_functional import masked_mean from verl.utils.tracking import ValidationGenerationsLogger from verl.workers.config import FSDPEngineConfig from verl.workers.utils.padding import left_right_2_no_padding, no_padding_2_padding def apply_kl_penalty(data: DataProto, kl_ctrl: core_algos.AdaptiveKLController, kl_penalty="kl"): """Apply KL penalty to the token-level rewards. This function computes the KL divergence between the reference policy and current policy, then applies a penalty to the token-level rewards based on this divergence. Args: data (DataProto): The data containing batched model outputs and inputs. kl_ctrl (core_algos.AdaptiveKLController): Controller for adaptive KL penalty. kl_penalty (str, optional): Type of KL penalty to apply. Defaults to "kl". Returns: tuple: A tuple containing: - The updated data with token-level rewards adjusted by KL penalty - A dictionary of metrics related to the KL penalty """ response_mask = data.batch["response_mask"] token_level_scores = data.batch["token_level_scores"] batch_size = data.batch.batch_size[0] # compute kl between ref_policy and current policy # When apply_kl_penalty, algorithm.use_kl_in_reward=True, so the reference model has been enabled. kld = core_algos.kl_penalty( data.batch["old_log_probs"], data.batch["ref_log_prob"], kl_penalty=kl_penalty ) # (batch_size, response_length) kld = kld * response_mask beta = kl_ctrl.value token_level_rewards = token_level_scores - beta * kld current_kl = masked_mean(kld, mask=response_mask, axis=-1) # average over sequence current_kl = torch.mean(current_kl, dim=0).item() # according to https://github.com/huggingface/trl/blob/951ca1841f29114b969b57b26c7d3e80a39f75a0/trl/trainer/ppo_trainer.py#L837 kl_ctrl.update(current_kl=current_kl, n_steps=batch_size) data.batch["token_level_rewards"] = token_level_rewards metrics = {"actor/reward_kl_penalty": current_kl, "actor/reward_kl_penalty_coeff": beta} return data, metrics def compute_response_mask(data: DataProto): """Compute the attention mask for the response part of the sequence. This function extracts the portion of the attention mask that corresponds to the model's response, which is used for masking computations that should only apply to response tokens. Args: data (DataProto): The data containing batched model outputs and inputs. Returns: torch.Tensor: The attention mask for the response tokens. """ responses = data.batch["responses"] response_length = responses.size(1) attention_mask = data.batch["attention_mask"] return attention_mask[:, -response_length:] def compute_advantage( data: DataProto, adv_estimator: AdvantageEstimator, gamma: float = 1.0, lam: float = 1.0, num_repeat: int = 1, norm_adv_by_std_in_grpo: bool = True, config: Optional[AlgoConfig] = None, ) -> DataProto: """Compute advantage estimates for policy optimization. This function computes advantage estimates using various estimators like GAE, GRPO, REINFORCE++, etc. The advantage estimates are used to guide policy optimization in RL algorithms. Args: data (DataProto): The data containing batched model outputs and inputs. adv_estimator (AdvantageEstimator): The advantage estimator to use (e.g., GAE, GRPO, REINFORCE++). gamma (float, optional): Discount factor for future rewards. Defaults to 1.0. lam (float, optional): Lambda parameter for GAE. Defaults to 1.0. num_repeat (int, optional): Number of times to repeat the computation. Defaults to 1. norm_adv_by_std_in_grpo (bool, optional): Whether to normalize advantages by standard deviation in GRPO. Defaults to True. config (dict, optional): Configuration dictionary for algorithm settings. Defaults to None. Returns: DataProto: The updated data with computed advantages and returns. """ # Back-compatible with trainers that do not compute response mask in fit if "response_mask" not in data.batch.keys(): data.batch["response_mask"] = compute_response_mask(data) # prepare response group if adv_estimator == AdvantageEstimator.GAE: # Compute advantages and returns using Generalized Advantage Estimation (GAE) advantages, returns = core_algos.compute_gae_advantage_return( token_level_rewards=data.batch["token_level_rewards"], values=data.batch["values"], response_mask=data.batch["response_mask"], gamma=gamma, lam=lam, ) data.batch["advantages"] = advantages data.batch["returns"] = returns if config.get("use_pf_ppo", False): data = core_algos.compute_pf_ppo_reweight_data( data, config.pf_ppo.get("reweight_method"), config.pf_ppo.get("weight_pow"), ) elif adv_estimator == AdvantageEstimator.GRPO: # Initialize the mask for GRPO calculation grpo_calculation_mask = data.batch["response_mask"] # Call compute_grpo_outcome_advantage with parameters matching its definition advantages, returns = core_algos.compute_grpo_outcome_advantage( token_level_rewards=data.batch["token_level_rewards"], response_mask=grpo_calculation_mask, index=data.non_tensor_batch["uid"], norm_adv_by_std_in_grpo=norm_adv_by_std_in_grpo, ) data.batch["advantages"] = advantages data.batch["returns"] = returns else: # handle all other adv estimator type other than GAE and GRPO adv_estimator_fn = core_algos.get_adv_estimator_fn(adv_estimator) adv_kwargs = { "token_level_rewards": data.batch["token_level_rewards"], "response_mask": data.batch["response_mask"], "config": config, } if "uid" in data.non_tensor_batch: # optional adv_kwargs["index"] = data.non_tensor_batch["uid"] if "reward_baselines" in data.batch: # optional adv_kwargs["reward_baselines"] = data.batch["reward_baselines"] # Add sum_pi_squared for Optimal Token Baseline if adv_estimator in (AdvantageEstimator.OPTIMAL_TOKEN_BASELINE, AdvantageEstimator.TIR_OPTIMAL_TOKEN_BASELINE): # Check if sum_pi_squared is available assert "sum_pi_squared" in data.batch, ( "Step-dependent optimal baseline requires sum_pi_squared from actor. " "Please set actor.calculate_sum_pi_squared=True in config." ) adv_kwargs["sum_pi_squared"] = data.batch["sum_pi_squared"] # Get pre-computed rollout IS weights if available rollout_is_weights = data.batch.get("rollout_is_weights", None) adv_kwargs["rollout_is_weights"] = rollout_is_weights # calculate advantage estimator advantages, returns = adv_estimator_fn(**adv_kwargs) data.batch["advantages"] = advantages data.batch["returns"] = returns return data class RayPPOTrainer: """Distributed PPO trainer using Ray for scalable reinforcement learning. This trainer orchestrates distributed PPO training across multiple nodes and GPUs, managing actor rollouts, critic training, and reward computation with Ray backend. Supports various model architectures including FSDP, Megatron, vLLM, and SGLang integration. """ # TODO: support each role have individual ray_worker_group_cls, # i.e., support different backend of different role def __init__( self, config, tokenizer, role_worker_mapping: dict[Role, WorkerType], resource_pool_manager: ResourcePoolManager, ray_worker_group_cls: type[RayWorkerGroup] = RayWorkerGroup, processor=None, train_dataset: Optional[Dataset] = None, val_dataset: Optional[Dataset] = None, collate_fn=None, train_sampler: Optional[Sampler] = None, device_name=None, ): """ Initialize distributed PPO trainer with Ray backend. Note that this trainer runs on the driver process on a single CPU/GPU node. Args: config: Configuration object containing training parameters. tokenizer: Tokenizer used for encoding and decoding text. role_worker_mapping (dict[Role, WorkerType]): Mapping from roles to worker classes. resource_pool_manager (ResourcePoolManager): Manager for Ray resource pools. ray_worker_group_cls (RayWorkerGroup, optional): Class for Ray worker groups. Defaults to RayWorkerGroup. processor: Optional data processor, used for multimodal data train_dataset (Optional[Dataset], optional): Training dataset. Defaults to None. val_dataset (Optional[Dataset], optional): Validation dataset. Defaults to None. collate_fn: Function to collate data samples into batches. train_sampler (Optional[Sampler], optional): Sampler for the training dataset. Defaults to None. device_name (str, optional): Device name for training (e.g., "cuda", "cpu"). Defaults to None. """ # Store the tokenizer for text processing self.tokenizer = tokenizer self.processor = processor self.config = config self.hybrid_engine = config.actor_rollout_ref.hybrid_engine assert self.hybrid_engine, "Currently, only support hybrid engine" if self.hybrid_engine: assert Role.ActorRollout in role_worker_mapping or Role.ActorRolloutRef in role_worker_mapping, ( f"{role_worker_mapping.keys()=}" ) self.role_worker_mapping = role_worker_mapping self.resource_pool_manager = resource_pool_manager self.use_reference_policy = need_reference_policy(self.config) self.use_rm = need_reward_model(self.config) self.use_critic = need_critic(self.config) self.ray_worker_group_cls = ray_worker_group_cls self.device_name = device_name if device_name else self.config.trainer.device self.validation_generations_logger = ValidationGenerationsLogger( project_name=self.config.trainer.project_name, experiment_name=self.config.trainer.experiment_name, ) # if ref_in_actor is True, the reference policy will be actor without lora applied lora_rank = config.actor_rollout_ref.model.get("lora", {}).get("rank", 0) if lora_rank <= 0: lora_rank = config.actor_rollout_ref.model.get("lora_rank", 0) self.ref_in_actor = lora_rank > 0 or config.actor_rollout_ref.model.get("lora_adapter_path") is not None # define in-reward KL control # kl loss control currently not suppoorted if self.config.algorithm.use_kl_in_reward: self.kl_ctrl_in_reward = core_algos.get_kl_controller(self.config.algorithm.kl_ctrl) self.use_prefix_grouper = self.config.actor_rollout_ref.actor.get("use_prefix_grouper", False) self.use_legacy_worker_impl = config.trainer.get("use_legacy_worker_impl", "auto") self._create_dataloader(train_dataset, val_dataset, collate_fn, train_sampler) def _create_dataloader(self, train_dataset, val_dataset, collate_fn, train_sampler: Optional[Sampler]): """ Creates the train and validation dataloaders. """ # TODO: we have to make sure the batch size is divisible by the dp size from verl.trainer.main_ppo import create_rl_dataset, create_rl_sampler if train_dataset is None: train_dataset = create_rl_dataset( self.config.data.train_files, self.config.data, self.tokenizer, self.processor, max_samples=self.config.data.get("train_max_samples", -1), ) if val_dataset is None: val_dataset = create_rl_dataset( self.config.data.val_files, self.config.data, self.tokenizer, self.processor, max_samples=self.config.data.get("val_max_samples", -1), ) self.train_dataset, self.val_dataset = train_dataset, val_dataset if train_sampler is None: train_sampler = create_rl_sampler(self.config.data, self.train_dataset) if collate_fn is None: from verl.utils.dataset.rl_dataset import collate_fn as default_collate_fn collate_fn = default_collate_fn num_workers = self.config.data["dataloader_num_workers"] self.train_dataloader = StatefulDataLoader( dataset=self.train_dataset, batch_size=self.config.data.get("gen_batch_size", self.config.data.train_batch_size), num_workers=num_workers, drop_last=True, collate_fn=collate_fn, sampler=train_sampler, ) val_batch_size = self.config.data.val_batch_size # Prefer config value if set if val_batch_size is None: val_batch_size = len(self.val_dataset) self.val_dataloader = StatefulDataLoader( dataset=self.val_dataset, batch_size=val_batch_size, num_workers=num_workers, shuffle=self.config.data.get("validation_shuffle", True), drop_last=False, collate_fn=collate_fn, ) assert len(self.train_dataloader) >= 1, "Train dataloader is empty!" assert len(self.val_dataloader) >= 1, "Validation dataloader is empty!" print( f"Size of train dataloader: {len(self.train_dataloader)}, Size of val dataloader: " f"{len(self.val_dataloader)}" ) total_training_steps = len(self.train_dataloader) * self.config.trainer.total_epochs if self.config.trainer.total_training_steps is not None: total_training_steps = self.config.trainer.total_training_steps self.total_training_steps = total_training_steps print(f"Total training steps: {self.total_training_steps}") try: OmegaConf.set_struct(self.config, True) with open_dict(self.config): if OmegaConf.select(self.config, "actor_rollout_ref.actor.optim"): self.config.actor_rollout_ref.actor.optim.total_training_steps = total_training_steps if OmegaConf.select(self.config, "critic.optim"): self.config.critic.optim.total_training_steps = total_training_steps except Exception as e: print(f"Warning: Could not set total_training_steps in config. Structure missing? Error: {e}") def _dump_generations(self, inputs, outputs, gts, scores, reward_extra_infos_dict, dump_path): """Dump rollout/validation samples as JSONL.""" os.makedirs(dump_path, exist_ok=True) filename = os.path.join(dump_path, f"{self.global_steps}.jsonl") n = len(inputs) base_data = { "input": inputs, "output": outputs, "gts": gts, "score": scores, "step": [self.global_steps] * n, } for k, v in reward_extra_infos_dict.items(): if len(v) == n: base_data[k] = v lines = [] for i in range(n): entry = {k: v[i] for k, v in base_data.items()} lines.append(json.dumps(entry, ensure_ascii=False)) with open(filename, "w") as f: f.write("\n".join(lines) + "\n") print(f"Dumped generations to {filename}") def _log_rollout_data( self, batch: DataProto, reward_extra_infos_dict: dict, timing_raw: dict, rollout_data_dir: str ): """Log rollout data to disk. Args: batch (DataProto): The batch containing rollout data reward_extra_infos_dict (dict): Additional reward information to log timing_raw (dict): Timing information for profiling rollout_data_dir (str): Directory path to save the rollout data """ with marked_timer("dump_rollout_generations", timing_raw, color="green"): inputs = self.tokenizer.batch_decode(batch.batch["prompts"], skip_special_tokens=True) outputs = self.tokenizer.batch_decode(batch.batch["responses"], skip_special_tokens=True) scores = batch.batch["token_level_scores"].sum(-1).cpu().tolist() sample_gts = [item.non_tensor_batch.get("reward_model", {}).get("ground_truth", None) for item in batch] reward_extra_infos_to_dump = reward_extra_infos_dict.copy() if "request_id" in batch.non_tensor_batch: reward_extra_infos_dict.setdefault( "request_id", batch.non_tensor_batch["request_id"].tolist(), ) self._dump_generations( inputs=inputs, outputs=outputs, gts=sample_gts, scores=scores, reward_extra_infos_dict=reward_extra_infos_to_dump, dump_path=rollout_data_dir, ) def _maybe_log_val_generations(self, inputs, outputs, scores): """Log a table of validation samples to the configured logger (wandb or swanlab)""" generations_to_log = self.config.trainer.log_val_generations if generations_to_log == 0: return import numpy as np # Create tuples of (input, output, score) and sort by input text samples = list(zip(inputs, outputs, scores, strict=True)) samples.sort(key=lambda x: x[0]) # Sort by input text # Use fixed random seed for deterministic shuffling rng = np.random.RandomState(42) rng.shuffle(samples) # Take first N samples after shuffling samples = samples[:generations_to_log] # Log to each configured logger self.validation_generations_logger.log(self.config.trainer.logger, samples, self.global_steps) def _get_gen_batch(self, batch: DataProto) -> DataProto: reward_keys = set({"data_source", "reward_model", "extra_info", "uid"}) & batch.non_tensor_batch.keys() # pop those keys for generation batch_keys_to_pop = [] non_tensor_batch_keys_to_pop = set(batch.non_tensor_batch.keys()) - reward_keys gen_batch = batch.pop( batch_keys=batch_keys_to_pop, non_tensor_batch_keys=list(non_tensor_batch_keys_to_pop), ) # For agent loop, we need reward model keys to compute score. gen_batch.non_tensor_batch.update(batch.non_tensor_batch) return gen_batch def _compute_reward_colocate(self, batch: DataProto) -> tuple[torch.Tensor, dict[str, Any]] | torch.Tensor: """ compute reward use colocate reward model """ assert self.reward_loop_manager is not None, "RewardLoopManager is None" batch_reward = self.reward_loop_manager.compute_rm_score(batch) return batch_reward def _validate(self, merged: bool = False): data_source_lst = [] reward_extra_infos_dict: dict[str, list] = defaultdict(list) # Lists to collect samples for the table sample_inputs = [] sample_outputs = [] sample_gts = [] sample_scores = [] sample_turns = [] sample_uids = [] for test_data in self.val_dataloader: test_batch = DataProto.from_single_dict(test_data) if "uid" not in test_batch.non_tensor_batch: test_batch.non_tensor_batch["uid"] = np.array( [str(uuid.uuid4()) for _ in range(len(test_batch.batch))], dtype=object ) # repeat test batch test_batch = test_batch.repeat( repeat_times=self.config.actor_rollout_ref.rollout.val_kwargs.n, interleave=True ) ground_truths = [ item.non_tensor_batch.get("reward_model", {}).get("ground_truth", None) for item in test_batch ] sample_gts.extend(ground_truths) test_gen_batch = self._get_gen_batch(test_batch) test_gen_batch.meta_info = { "eos_token_id": self.tokenizer.eos_token_id, "pad_token_id": self.tokenizer.pad_token_id, "recompute_log_prob": False, "do_sample": self.config.actor_rollout_ref.rollout.val_kwargs.do_sample, "validate": True, "global_steps": self.global_steps, } print(f"test_gen_batch meta info: {test_gen_batch.meta_info}") # pad to be divisible by dp_size size_divisor = self.config.actor_rollout_ref.rollout.agent.num_workers test_gen_batch_padded, pad_size = pad_dataproto_to_divisor(test_gen_batch, size_divisor) test_output_gen_batch_padded = self.async_rollout_manager.generate_sequences(test_gen_batch_padded) if self.use_rm and "rm_scores" not in test_output_gen_batch_padded.batch.keys(): # for colocate reward models, we need to sleep rollout model # to spare GPU memory for reward model self.checkpoint_manager.sleep_replicas() batch_reward = self._compute_reward_colocate(test_output_gen_batch_padded) test_output_gen_batch_padded = test_output_gen_batch_padded.union(batch_reward) # wake up rollout model # replace with wake_up method once supported self.checkpoint_manager.update_weights() # unpad test_output_gen_batch = unpad_dataproto(test_output_gen_batch_padded, pad_size=pad_size) print("validation generation end") # Store generated outputs output_ids = test_output_gen_batch.batch["responses"] output_texts = [self.tokenizer.decode(ids, skip_special_tokens=True) for ids in output_ids] sample_outputs.extend(output_texts) test_batch = test_batch.union(test_output_gen_batch) test_batch.meta_info["validate"] = True # Store original inputs input_ids = test_batch.batch["prompts"] # TODO: Can we keep special tokens except for padding tokens? input_texts = [self.tokenizer.decode(ids, skip_special_tokens=True) for ids in input_ids] sample_inputs.extend(input_texts) sample_uids.extend(test_batch.non_tensor_batch["uid"]) # evaluate using reward_function reward_tensor, reward_extra_info = extract_reward(test_batch) scores = reward_tensor.sum(-1).cpu().tolist() sample_scores.extend(scores) reward_extra_infos_dict["reward"].extend(scores) for key, values in reward_extra_info.items(): if key not in reward_extra_infos_dict: reward_extra_infos_dict[key] = [] if isinstance(values, np.ndarray): reward_extra_infos_dict[key].extend(values.tolist()) else: reward_extra_infos_dict[key].extend(values if isinstance(values, list) else [values]) # collect num_turns of each prompt if "__num_turns__" in test_batch.non_tensor_batch: sample_turns.append(test_batch.non_tensor_batch["__num_turns__"]) data_source_lst.append(test_batch.non_tensor_batch.get("data_source", ["unknown"] * reward_tensor.shape[0])) self._maybe_log_val_generations(inputs=sample_inputs, outputs=sample_outputs, scores=sample_scores) # dump generations val_data_dir = self.config.trainer.get("validation_data_dir", None) if val_data_dir: self._dump_generations( inputs=sample_inputs, outputs=sample_outputs, gts=sample_gts, scores=sample_scores, reward_extra_infos_dict=reward_extra_infos_dict, dump_path=val_data_dir, ) for key_info, lst in reward_extra_infos_dict.items(): assert len(lst) == 0 or len(lst) == len(sample_scores), f"{key_info}: {len(lst)=}, {len(sample_scores)=}" if merged: print("_merge_validation_results validate result will be merged") return { "data_sources": data_source_lst, "sample_uids": sample_uids, "sample_turns": sample_turns, "reward_extra_infos_dict": reward_extra_infos_dict, } data_sources = np.concatenate(data_source_lst, axis=0) return self._val_metrics_update(data_sources, sample_uids, reward_extra_infos_dict, sample_turns) def _val_metrics_update(self, data_sources, sample_uids, reward_extra_infos_dict, sample_turns): data_src2var2metric2val = process_validation_metrics(data_sources, sample_uids, reward_extra_infos_dict) metric_dict = {} for data_source, var2metric2val in data_src2var2metric2val.items(): core_var = "acc" if "acc" in var2metric2val else "reward" for var_name, metric2val in var2metric2val.items(): n_max = max([int(name.split("@")[-1].split("/")[0]) for name in metric2val.keys()]) for metric_name, metric_val in metric2val.items(): if ( (var_name == core_var) and any(metric_name.startswith(pfx) for pfx in ["mean", "maj", "best"]) and (f"@{n_max}" in metric_name) ): metric_sec = "val-core" else: metric_sec = "val-aux" pfx = f"{metric_sec}/{data_source}/{var_name}/{metric_name}" metric_dict[pfx] = metric_val if len(sample_turns) > 0: sample_turns = np.concatenate(sample_turns) metric_dict["val-aux/num_turns/min"] = sample_turns.min() metric_dict["val-aux/num_turns/max"] = sample_turns.max() metric_dict["val-aux/num_turns/mean"] = sample_turns.mean() return metric_dict def _merge_validation_results(self, result_a, result_b): if result_a is None and result_b is None: return {} if result_a is None: result_a = {"data_sources": [], "sample_uids": [], "sample_turns": [], "reward_extra_infos_dict": {}} if result_b is None: result_b = {"data_sources": [], "sample_uids": [], "sample_turns": [], "reward_extra_infos_dict": {}} if not result_a.get("data_sources") and not result_b.get("data_sources"): return {} data_sources = np.concatenate(result_a["data_sources"] + result_b["data_sources"], axis=0) sample_uids = result_a["sample_uids"] + result_b["sample_uids"] sample_turns = result_a["sample_turns"] + result_b["sample_turns"] reward_extra_infos_dict = {} all_keys = set(result_a["reward_extra_infos_dict"].keys()) | set(result_b["reward_extra_infos_dict"].keys()) for key in all_keys: list_a = result_a["reward_extra_infos_dict"].get(key, []) list_b = result_b["reward_extra_infos_dict"].get(key, []) reward_extra_infos_dict[key] = list_a + list_b return self._val_metrics_update(data_sources, sample_uids, reward_extra_infos_dict, sample_turns) def init_workers(self): """Initialize distributed training workers using Ray backend. Creates: 1. Ray resource pools from configuration 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 actor_role = Role.ActorRolloutRef if Role.ActorRolloutRef in self.role_worker_mapping else Role.ActorRollout if self.hybrid_engine: actor_rollout_resource_pool = self.resource_pool_manager.get_resource_pool(actor_role) actor_rollout_cls = RayClassWithInitArgs( cls=self.role_worker_mapping[actor_role], config=self.config.actor_rollout_ref, role=str(actor_role), ) self.resource_pool_to_cls[actor_rollout_resource_pool][str(actor_role)] = actor_rollout_cls else: raise NotImplementedError # create critic if self.use_critic: resource_pool = self.resource_pool_manager.get_resource_pool(Role.Critic) from verl.workers.config import CriticConfig critic_cfg: CriticConfig = omega_conf_to_dataclass(self.config.critic) if self.use_legacy_worker_impl == "disable": # convert critic_cfg into TrainingWorkerConfig from verl.workers.engine_workers import TrainingWorkerConfig orig_critic_cfg = critic_cfg if orig_critic_cfg.strategy == "fsdp": engine_config: FSDPEngineConfig = orig_critic_cfg.model.fsdp_config engine_config.infer_max_token_len_per_gpu = critic_cfg.ppo_infer_max_token_len_per_gpu engine_config.max_token_len_per_gpu = critic_cfg.ppo_max_token_len_per_gpu else: raise NotImplementedError(f"Unknown strategy {orig_critic_cfg.strategy=}") critic_cfg = TrainingWorkerConfig( model_type="value_model", model_config=orig_critic_cfg.model_config, engine_config=engine_config, optimizer_config=orig_critic_cfg.optim, checkpoint_config=orig_critic_cfg.checkpoint, ) critic_cls = RayClassWithInitArgs(cls=self.role_worker_mapping[Role.Critic], config=critic_cfg) 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_policy_cls = RayClassWithInitArgs( self.role_worker_mapping[Role.RefPolicy], config=self.config.actor_rollout_ref, role=str(Role.RefPolicy), ) self.resource_pool_to_cls[resource_pool][str(Role.RefPolicy)] = ref_policy_cls # initialize WorkerGroup # NOTE: if you want to use a different resource pool for each role, which can support different parallel size, # you should not use `create_colocated_worker_cls`. # Instead, directly pass different resource pool to different worker groups. # See https://github.com/volcengine/verl/blob/master/examples/ray/tutorial.ipynb for more information. all_wg = {} wg_kwargs = {} # Setting up kwargs for RayWorkerGroup if OmegaConf.select(self.config.trainer, "ray_wait_register_center_timeout") is not None: wg_kwargs["ray_wait_register_center_timeout"] = self.config.trainer.ray_wait_register_center_timeout if OmegaConf.select(self.config.global_profiler, "steps") is not None: wg_kwargs["profile_steps"] = OmegaConf.select(self.config.global_profiler, "steps") # Only require nsight worker options when tool is nsys if OmegaConf.select(self.config.global_profiler, "tool") == "nsys": assert ( OmegaConf.select(self.config.global_profiler.global_tool_config.nsys, "worker_nsight_options") is not None ), "worker_nsight_options must be set when using nsys with profile_steps" wg_kwargs["worker_nsight_options"] = OmegaConf.to_container( OmegaConf.select(self.config.global_profiler.global_tool_config.nsys, "worker_nsight_options") ) wg_kwargs["device_name"] = self.device_name for resource_pool, class_dict in self.resource_pool_to_cls.items(): worker_dict_cls = create_colocated_worker_cls(class_dict=class_dict) wg_dict = self.ray_worker_group_cls( resource_pool=resource_pool, ray_cls_with_init=worker_dict_cls, **wg_kwargs, ) spawn_wg = wg_dict.spawn(prefix_set=class_dict.keys()) all_wg.update(spawn_wg) if self.use_critic: self.critic_wg = all_wg[str(Role.Critic)] if self.use_legacy_worker_impl == "disable": self.critic_wg.reset() # assign critic loss from functools import partial from verl.workers.utils.losses import value_loss value_loss_ = partial(value_loss, config=orig_critic_cfg) self.critic_wg.set_loss_fn(value_loss_) else: self.critic_wg.init_model() if self.use_reference_policy and not self.ref_in_actor: if str(Role.RefPolicy) in all_wg: self.ref_policy_wg = all_wg[str(Role.RefPolicy)] self.ref_policy_wg.init_model() else: # Model engine: ActorRolloutRefWorker assert str(Role.ActorRolloutRef) in all_wg, f"{all_wg.keys()=}" self.ref_policy_wg = all_wg[str(Role.ActorRolloutRef)] # we should create rollout at the end so that vllm can have a better estimation of kv cache memory self.actor_rollout_wg = all_wg[str(actor_role)] self.actor_rollout_wg.init_model() if self.ref_in_actor: self.ref_policy_wg = self.actor_rollout_wg # create reward loop manager from verl.experimental.reward_loop import RewardLoopManager # initalize reward loop manager # reward model (colocate or standalone): get resource_pool # no reward model: resource_pool = None resource_pool = self.resource_pool_manager.get_resource_pool(Role.RewardModel) if self.use_rm else None self.reward_loop_manager = RewardLoopManager( config=self.config, rm_resource_pool=resource_pool, ) # create async rollout manager and request scheduler # Note: mode is always "async" since sync mode is deprecated self.async_rollout_mode = True # Support custom AgentLoopManager via config manager_class_fqn = self.config.actor_rollout_ref.rollout.get("agent", {}).get("agent_loop_manager_class") if manager_class_fqn: AgentLoopManager = load_class_from_fqn(manager_class_fqn, "AgentLoopManager") else: from verl.experimental.agent_loop import AgentLoopManager # infrastructure overview: https://verl.readthedocs.io/en/latest/advance/reward_loop.html#architecture-design # agent_reward_loop: streaming reward computation with actor rollout # two conditions satisfied: (1) no reward model, or (2) reward model with extra resource pool enable_agent_reward_loop = not self.use_rm or self.config.reward.reward_model.enable_resource_pool # if enable_agent_reward_loop, we directly pass reward_loop_workers to agent loop manager # to stream reward computation with actor rollout reward_loop_worker_handles = self.reward_loop_manager.reward_loop_workers if enable_agent_reward_loop else None self.async_rollout_manager = AgentLoopManager( config=self.config, worker_group=self.actor_rollout_wg, rollout_resource_pool=actor_rollout_resource_pool, reward_loop_worker_handles=reward_loop_worker_handles, ) self.checkpoint_manager = CheckpointEngineManager( backend=self.config.actor_rollout_ref.rollout.checkpoint_engine.backend, trainer=self.actor_rollout_wg, replicas=self.async_rollout_manager.rollout_replicas, ) # sleep all replicas to load checkpoint self.checkpoint_manager.sleep_replicas() def _save_checkpoint(self): from verl.utils.fs import local_mkdir_safe # path: given_path + `/global_step_{global_steps}` + `/actor` local_global_step_folder = os.path.join( self.config.trainer.default_local_dir, f"global_step_{self.global_steps}" ) print(f"local_global_step_folder: {local_global_step_folder}") actor_local_path = os.path.join(local_global_step_folder, "actor") actor_remote_path = ( None if self.config.trainer.default_hdfs_dir is None else os.path.join(self.config.trainer.default_hdfs_dir, f"global_step_{self.global_steps}", "actor") ) remove_previous_ckpt_in_save = self.config.trainer.get("remove_previous_ckpt_in_save", False) if remove_previous_ckpt_in_save: print( "Warning: remove_previous_ckpt_in_save is deprecated," + " set max_actor_ckpt_to_keep=1 and max_critic_ckpt_to_keep=1 instead" ) max_actor_ckpt_to_keep = ( self.config.trainer.get("max_actor_ckpt_to_keep", None) if not remove_previous_ckpt_in_save else 1 ) max_critic_ckpt_to_keep = ( self.config.trainer.get("max_critic_ckpt_to_keep", None) if not remove_previous_ckpt_in_save else 1 ) self.actor_rollout_wg.save_checkpoint( actor_local_path, actor_remote_path, self.global_steps, max_ckpt_to_keep=max_actor_ckpt_to_keep ) if self.use_critic: critic_local_path = os.path.join(local_global_step_folder, str(Role.Critic)) critic_remote_path = ( None if self.config.trainer.default_hdfs_dir is None else os.path.join( self.config.trainer.default_hdfs_dir, f"global_step_{self.global_steps}", str(Role.Critic) ) ) self.critic_wg.save_checkpoint( critic_local_path, critic_remote_path, self.global_steps, max_ckpt_to_keep=max_critic_ckpt_to_keep ) # save dataloader local_mkdir_safe(local_global_step_folder) dataloader_local_path = os.path.join(local_global_step_folder, "data.pt") dataloader_state_dict = self.train_dataloader.state_dict() torch.save(dataloader_state_dict, dataloader_local_path) # latest checkpointed iteration tracker (for atomic usage) if ( hasattr(self.config.actor_rollout_ref.actor.checkpoint, "async_save") and self.config.actor_rollout_ref.actor.checkpoint.async_save ) or ( "async_save" in self.config.actor_rollout_ref.actor.checkpoint and self.config.actor_rollout_ref.actor.checkpoint["async_save"] ): print("skip write latest_checkpointed_iteration.txt when async_save is True") return local_latest_checkpointed_iteration = os.path.join( self.config.trainer.default_local_dir, "latest_checkpointed_iteration.txt" ) with open(local_latest_checkpointed_iteration, "w") as f: f.write(str(self.global_steps)) def _load_checkpoint(self): if self.config.trainer.resume_mode == "disable": return 0 # load from hdfs if self.config.trainer.default_hdfs_dir is not None: raise NotImplementedError("load from hdfs is not implemented yet") else: checkpoint_folder = self.config.trainer.default_local_dir # TODO: check path if not os.path.isabs(checkpoint_folder): working_dir = os.getcwd() checkpoint_folder = os.path.join(working_dir, checkpoint_folder) global_step_folder = find_latest_ckpt_path(checkpoint_folder) # None if no latest # find global_step_folder if self.config.trainer.resume_mode == "auto": if global_step_folder is None: print("Training from scratch") return 0 else: if self.config.trainer.resume_mode == "resume_path": assert isinstance(self.config.trainer.resume_from_path, str), "resume ckpt must be str type" assert "global_step_" in self.config.trainer.resume_from_path, ( "resume ckpt must specify the global_steps" ) global_step_folder = self.config.trainer.resume_from_path if not os.path.isabs(global_step_folder): working_dir = os.getcwd() global_step_folder = os.path.join(working_dir, global_step_folder) print(f"Load from checkpoint folder: {global_step_folder}") # set global step self.global_steps = int(global_step_folder.split("global_step_")[-1]) print(f"Setting global step to {self.global_steps}") print(f"Resuming from {global_step_folder}") actor_path = os.path.join(global_step_folder, "actor") critic_path = os.path.join(global_step_folder, str(Role.Critic)) # load actor self.actor_rollout_wg.load_checkpoint( actor_path, del_local_after_load=self.config.trainer.del_local_ckpt_after_load ) # load critic if self.use_critic: self.critic_wg.load_checkpoint( critic_path, del_local_after_load=self.config.trainer.del_local_ckpt_after_load ) # load dataloader, # TODO: from remote not implemented yet dataloader_local_path = os.path.join(global_step_folder, "data.pt") if os.path.exists(dataloader_local_path): dataloader_state_dict = torch.load(dataloader_local_path, weights_only=False) self.train_dataloader.load_state_dict(dataloader_state_dict) else: print(f"Warning: No dataloader state found at {dataloader_local_path}, will start from scratch") def _start_profiling(self, do_profile: bool) -> None: """Start profiling for all worker groups if profiling is enabled.""" if do_profile: self.actor_rollout_wg.start_profile(role="e2e", profile_step=self.global_steps) if self.use_reference_policy: self.ref_policy_wg.start_profile(profile_step=self.global_steps) if self.use_critic: self.critic_wg.start_profile(profile_step=self.global_steps) def _stop_profiling(self, do_profile: bool) -> None: """Stop profiling for all worker groups if profiling is enabled.""" if do_profile: self.actor_rollout_wg.stop_profile() if self.use_reference_policy: self.ref_policy_wg.stop_profile() if self.use_critic: self.critic_wg.stop_profile() def _get_dp_size(self, worker_group, role: str) -> int: """Get data parallel size from worker group dispatch info. This method retrieves the data parallel size by querying the dispatch info for the specified role. The dispatch info is cached for subsequent calls. Args: worker_group: The worker group to query dispatch info from. role: The role name (e.g., "actor", "critic") to get DP size for. Returns: The data parallel size (number of DP ranks). """ if role not in worker_group._dispatch_info: dp_rank_mapping = worker_group._query_dispatch_info(role) worker_group._dispatch_info[role] = dp_rank_mapping else: dp_rank_mapping = worker_group._dispatch_info[role] return max(dp_rank_mapping) + 1 def _balance_batch(self, batch: DataProto, metrics, logging_prefix="global_seqlen", keep_minibatch=False): """Reorder the data on single controller such that each dp rank gets similar total tokens. When use_prefix_grouper is enabled, uses group-level balancing to keep samples with the same uid together on the same rank for prefix sharing optimization. """ attention_mask = batch.batch["attention_mask"] batch_size = attention_mask.shape[0] global_seqlen_lst = batch.batch["attention_mask"].view(batch_size, -1).sum(-1) # (train_batch_size,) workload_lst = calculate_workload(global_seqlen_lst) # Get dp_size from dispatch info to correctly balance across data parallel ranks # Note: world_size may include tensor/pipeline parallel dimensions, but we only want DP dp_size = self._get_dp_size(self.actor_rollout_wg, "actor") # Use group-level balancing for PrefixGrouper to keep same-uid samples together if getattr(self, "use_prefix_grouper", False) and "uid" in batch.non_tensor_batch: from verl.utils.seqlen_balancing import get_group_balanced_partitions uid_list = list(batch.non_tensor_batch["uid"]) seqlen_list = global_seqlen_lst.tolist() # Count number of uid groups num_groups = len(set(uid_list)) if num_groups % dp_size != 0: raise ValueError( f"PrefixGrouper with balance_batch requires num_uid_groups ({num_groups}) " f"% dp_size ({dp_size}) == 0. " f"This ensures each rank gets equal number of groups. " f"Current batch_size={batch_size}, adjust batch_size to be a multiple of " f"dp_size * rollout.n." ) global_partition_lst = get_group_balanced_partitions( seqlen_list=seqlen_list, uid_list=uid_list, k_partitions=dp_size, ) elif keep_minibatch: # Decouple the DP balancing and mini-batching. minibatch_size = self.config.actor_rollout_ref.actor.get("ppo_mini_batch_size") minibatch_num = len(workload_lst) // minibatch_size global_partition_lst = [[] for _ in range(dp_size)] for i in range(minibatch_num): rearrange_minibatch_lst = get_seqlen_balanced_partitions( workload_lst[i * minibatch_size : (i + 1) * minibatch_size], k_partitions=dp_size, equal_size=True, ) for j, part in enumerate(rearrange_minibatch_lst): global_partition_lst[j].extend([x + minibatch_size * i for x in part]) else: global_partition_lst = get_seqlen_balanced_partitions(workload_lst, k_partitions=dp_size, equal_size=True) # Place smaller micro-batches at both ends to reduce the bubbles in pipeline parallel. # Skip reordering within partitions for PrefixGrouper to maintain uid grouping if not getattr(self, "use_prefix_grouper", False): for idx, partition in enumerate(global_partition_lst): partition.sort(key=lambda x: (workload_lst[x], x)) ordered_partition = partition[::2] + partition[1::2][::-1] global_partition_lst[idx] = ordered_partition # reorder based on index. The data will be automatically equally partitioned by dispatch function global_idx = torch.tensor([j for partition in global_partition_lst for j in partition]) batch.reorder(global_idx) global_balance_stats = log_seqlen_unbalance( seqlen_list=global_seqlen_lst.tolist(), partitions=global_partition_lst, prefix=logging_prefix ) metrics.update(global_balance_stats) def _compute_values(self, batch: DataProto) -> DataProto: if self.use_legacy_worker_impl == "disable": batch_td = batch.to_tensordict() # step 2: convert from padding to nopadding batch_td = left_right_2_no_padding(batch_td) # step 3: add meta info tu.assign_non_tensor(batch_td, compute_loss=False) output = self.critic_wg.infer_batch(batch_td) output = output.get() values = tu.get(output, "values") values = no_padding_2_padding(values, batch_td) values = tu.get_tensordict({"values": values.float()}) values = DataProto.from_tensordict(values) else: values = self.critic_wg.compute_values(batch) return values def _compute_ref_log_prob(self, batch: DataProto) -> DataProto: if self.use_legacy_worker_impl == "disable": # step 1: convert dataproto to tensordict. batch_td = batch.to_tensordict() # step 2: convert from padding to nopadding batch_td = left_right_2_no_padding(batch_td) # step 3: add meta info metadata = {"calculate_entropy": False, "compute_loss": False} if self.ref_in_actor: metadata["no_lora_adapter"] = True tu.assign_non_tensor(batch_td, **metadata) if self.ref_in_actor: output = self.actor_rollout_wg.compute_log_prob(batch_td) else: output = self.ref_policy_wg.compute_ref_log_prob(batch_td) # gather output log_probs = tu.get(output, "log_probs") # step 4. No padding to padding log_probs = no_padding_2_padding(log_probs, batch_td) # step 5: rebuild a tensordict and convert to dataproto ref_log_prob = tu.get_tensordict({"ref_log_prob": log_probs.float()}) ref_log_prob = DataProto.from_tensordict(ref_log_prob) else: ref_log_prob = self.ref_policy_wg.compute_ref_log_prob(batch) return ref_log_prob def _compute_old_log_prob(self, batch: DataProto): if self.use_legacy_worker_impl == "disable": # TODO: remove step 1, 2, 4 after we make the whole training tensordict and padding free # step 1: convert dataproto to tensordict. batch_td = batch.to_tensordict() # step 2: convert from padding to nopadding batch_td = left_right_2_no_padding(batch_td) # step 3: add meta info tu.assign_non_tensor(batch_td, calculate_entropy=True, compute_loss=False) output = self.actor_rollout_wg.compute_log_prob(batch_td) # gather output entropy = tu.get(output, "entropy") log_probs = tu.get(output, "log_probs") old_log_prob_mfu = tu.get(output, "metrics")["mfu"] # step 4. No padding to padding entropy = no_padding_2_padding(entropy, batch_td) log_probs = no_padding_2_padding(log_probs, batch_td) # step 5: rebuild a tensordict and convert to dataproto old_log_prob = tu.get_tensordict({"old_log_probs": log_probs.float(), "entropys": entropy.float()}) old_log_prob = DataProto.from_tensordict(old_log_prob) else: old_log_prob = self.actor_rollout_wg.compute_log_prob(batch) old_log_prob_mfu = 0 return old_log_prob, old_log_prob_mfu def _update_actor(self, batch: DataProto) -> DataProto: rollout_config = self.config.actor_rollout_ref.rollout batch.meta_info["multi_turn"] = rollout_config.multi_turn.enable # TODO: Make "temperature" single source of truth from generation. batch.meta_info["temperature"] = rollout_config.temperature # update actor if self.use_legacy_worker_impl == "disable": batch_td = batch.to_tensordict() # step 2: convert from padding to no-padding batch_td = left_right_2_no_padding(batch_td) calculate_entropy = self.config.actor_rollout_ref.actor.entropy_coeff != 0.0 ppo_mini_batch_size = self.config.actor_rollout_ref.actor.ppo_mini_batch_size ppo_mini_batch_size = ppo_mini_batch_size * self.config.actor_rollout_ref.rollout.n ppo_epochs = self.config.actor_rollout_ref.actor.ppo_epochs seed = self.config.actor_rollout_ref.actor.data_loader_seed shuffle = self.config.actor_rollout_ref.actor.shuffle tu.assign_non_tensor( batch_td, calculate_entropy=calculate_entropy, global_batch_size=ppo_mini_batch_size, mini_batch_size=ppo_mini_batch_size, epochs=ppo_epochs, seed=seed, dataloader_kwargs={"shuffle": shuffle}, ) actor_output = self.actor_rollout_wg.update_actor(batch_td) actor_output = tu.get(actor_output, "metrics") actor_output = rename_dict(actor_output, "actor/") # modify key name actor_output["perf/mfu/actor"] = actor_output.pop("actor/mfu") actor_output = DataProto.from_single_dict(data={}, meta_info={"metrics": actor_output}) else: actor_output = self.actor_rollout_wg.update_actor(batch) return actor_output def _update_critic(self, batch: DataProto) -> DataProto: if self.use_legacy_worker_impl == "disable": batch_td = batch.to_tensordict() # step 2: convert from padding to no-padding batch_td = left_right_2_no_padding(batch_td) ppo_mini_batch_size = self.config.critic.ppo_mini_batch_size ppo_mini_batch_size = ppo_mini_batch_size * self.config.actor_rollout_ref.rollout.n ppo_epochs = self.config.critic.ppo_epochs seed = self.config.critic.data_loader_seed shuffle = self.config.critic.shuffle tu.assign_non_tensor( batch_td, global_batch_size=ppo_mini_batch_size, mini_batch_size=ppo_mini_batch_size, epochs=ppo_epochs, seed=seed, dataloader_kwargs={"shuffle": shuffle}, ) output = self.critic_wg.train_mini_batch(batch_td) output = output.get() output = tu.get(output, "metrics") output = rename_dict(output, "critic/") # modify key name output["perf/mfu/critic"] = output.pop("critic/mfu") critic_output = DataProto.from_single_dict(data={}, meta_info={"metrics": output}) else: critic_output = self.critic_wg.update_critic(batch) return critic_output def fit(self): """ The training loop of PPO. The driver process only need to call the compute functions of the worker group through RPC to construct the PPO dataflow. The light-weight advantage computation is done on the driver process. """ from omegaconf import OmegaConf from verl.utils.tracking import Tracking logger = Tracking( project_name=self.config.trainer.project_name, experiment_name=self.config.trainer.experiment_name, default_backend=self.config.trainer.logger, config=OmegaConf.to_container(self.config, resolve=True), ) self.global_steps = 0 # load checkpoint and update weights before doing anything self._load_checkpoint() self.checkpoint_manager.update_weights() current_epoch = self.global_steps // len(self.train_dataloader) # perform validation before training # currently, we only support validation using the reward_function. if self.config.trainer.get("val_before_train", True): val_metrics = self._validate() assert val_metrics, f"{val_metrics=}" pprint(f"Initial validation metrics: {val_metrics}") logger.log(data=val_metrics, step=self.global_steps) if self.config.trainer.get("val_only", False): return if self.config.actor_rollout_ref.rollout.get("skip_rollout", False): rollout_skip = RolloutSkip(self.config, self.async_rollout_manager) rollout_skip.wrap_generate_sequences() # add tqdm progress_bar = tqdm(total=self.total_training_steps, initial=self.global_steps, desc="Training Progress") # we start from step 1 self.global_steps += 1 last_val_metrics = None self.max_steps_duration = 0 prev_step_profile = False curr_step_profile = ( self.global_steps in self.config.global_profiler.steps if self.config.global_profiler.steps is not None else False ) next_step_profile = False for epoch in range(current_epoch, self.config.trainer.total_epochs): for batch_dict in self.train_dataloader: if hasattr(self.actor_rollout_wg, "async_calls_finalize_fn_exec"): self.actor_rollout_wg.async_calls_finalize_fn_exec(blocking=False) metrics = {} timing_raw = {} with marked_timer("start_profile", timing_raw): self._start_profiling( not prev_step_profile and curr_step_profile if self.config.global_profiler.profile_continuous_steps else curr_step_profile ) batch: DataProto = DataProto.from_single_dict(batch_dict) batch.meta_info["temperature"] = self.config.actor_rollout_ref.rollout.temperature # add uid to batch batch.non_tensor_batch["uid"] = np.array( [str(uuid.uuid4()) for _ in range(len(batch.batch))], dtype=object ) gen_batch = self._get_gen_batch(batch) # pass global_steps to trace gen_batch.meta_info["global_steps"] = self.global_steps gen_batch_output = gen_batch.repeat( repeat_times=self.config.actor_rollout_ref.rollout.n, interleave=True ) is_last_step = self.global_steps >= self.total_training_steps with marked_timer("step", timing_raw): # generate a batch with marked_timer("gen", timing_raw, color="red"): if curr_step_profile: self.async_rollout_manager.start_profile() gen_batch_output = self.async_rollout_manager.generate_sequences(gen_batch_output) self.checkpoint_manager.sleep_replicas() if curr_step_profile: self.async_rollout_manager.stop_profile() timing_raw.update(gen_batch_output.meta_info["timing"]) gen_batch_output.meta_info.pop("timing", None) if self.config.algorithm.adv_estimator == AdvantageEstimator.REMAX: with marked_timer("gen_max", timing_raw, color="purple"): gen_baseline_batch = deepcopy(gen_batch) gen_baseline_batch.meta_info["do_sample"] = False if curr_step_profile: self.async_rollout_manager.start_profile() gen_baseline_output = self.async_rollout_manager.generate_sequences(gen_baseline_batch) self.checkpoint_manager.sleep_replicas() if curr_step_profile: self.async_rollout_manager.stop_profile() batch = batch.union(gen_baseline_output) # compute reward model score on batch rm_scores = None if self.use_rm and "rm_scores" not in batch.batch.keys(): batch_reward = self._compute_reward_colocate(batch) batch = batch.union(batch_reward) # Compute or extract reward for REMAX baseline reward_baseline_tensor = batch.batch["rm_scores"].sum(dim=-1) keys_to_pop = set(gen_baseline_output.batch.keys()) if rm_scores is not None: keys_to_pop.update(rm_scores.batch.keys()) batch.pop(batch_keys=list(keys_to_pop)) batch.batch["reward_baselines"] = reward_baseline_tensor del rm_scores, gen_baseline_batch, gen_baseline_output # repeat to align with repeated responses in rollout batch = batch.repeat(repeat_times=self.config.actor_rollout_ref.rollout.n, interleave=True) batch = batch.union(gen_batch_output) if "response_mask" not in batch.batch.keys(): batch.batch["response_mask"] = compute_response_mask(batch) # Balance the number of valid tokens across DP ranks. # NOTE: This usually changes the order of data in the `batch`, # which won't affect the advantage calculation (since it's based on uid), # but might affect the loss calculation (due to the change of mini-batching). if self.config.trainer.balance_batch: self._balance_batch(batch, metrics=metrics) # compute global_valid tokens batch.meta_info["global_token_num"] = torch.sum(batch.batch["attention_mask"], dim=-1).tolist() # get images_seqlens images_seqlens_all = [] for multi_modal_input in batch.non_tensor_batch["multi_modal_inputs"]: if "image_grid_thw" not in multi_modal_input.keys(): continue images_seqlens_all.extend(multi_modal_input["images_seqlens"].tolist()) batch.meta_info["images_seqlens"] = images_seqlens_all with marked_timer("reward", timing_raw, color="yellow"): # compute reward model score if self.use_rm and "rm_scores" not in batch.batch.keys(): batch_reward = self._compute_reward_colocate(batch) batch = batch.union(batch_reward) # extract reward_tensor and reward_extra_infos_dict for training reward_tensor, reward_extra_infos_dict = extract_reward(batch) # Operating Mode Selection: # - Bypass mode: Sets old_log_probs = rollout_log_probs (2 policies: π_rollout, π_θ) # - Decoupled mode: Recomputes old_log_probs as proximal anchor (3 policies: π_rollout, π_old, π_θ) # Note: π_old computed once per data batch, serves as stable reference during mini-batch updates rollout_corr_config = self.config.algorithm.get("rollout_correction", None) bypass_recomputing_logprobs = rollout_corr_config and rollout_corr_config.get("bypass_mode", False) if bypass_recomputing_logprobs: # Use `rollout_log_probs` from verl.trainer.ppo.rollout_corr_helper import apply_bypass_mode apply_bypass_mode( batch=batch, rollout_corr_config=rollout_corr_config, policy_loss_config=self.config.actor_rollout_ref.actor.policy_loss, ) else: # Recompute old_log_probs with marked_timer("old_log_prob", timing_raw, color="blue"): old_log_prob, old_log_prob_mfu = self._compute_old_log_prob(batch) entropys = old_log_prob.batch["entropys"] response_masks = batch.batch["response_mask"] actor_config = self.config.actor_rollout_ref.actor entropy_agg = agg_loss( loss_mat=entropys, loss_mask=response_masks, loss_agg_mode=actor_config.loss_agg_mode, loss_scale_factor=actor_config.loss_scale_factor, ) old_log_prob_metrics = { "actor/entropy": entropy_agg.detach().item(), "perf/mfu/actor_infer": old_log_prob_mfu, } metrics.update(old_log_prob_metrics) old_log_prob.batch.pop("entropys") if "routed_experts" in batch.batch and "routed_experts" in old_log_prob.batch: router_mode = getattr( self.config.actor_rollout_ref.actor.router_replay, "mode", "disabled" ) if router_mode == "R2": batch.batch.pop("routed_experts") else: old_log_prob.batch.pop("routed_experts") batch = batch.union(old_log_prob) if "rollout_log_probs" in batch.batch.keys(): # TODO: we may want to add diff of probs too. from verl.utils.debug.metrics import calculate_debug_metrics metrics.update(calculate_debug_metrics(batch)) assert "old_log_probs" in batch.batch, f'"old_log_prob" not in {batch.batch.keys()=}' if self.use_reference_policy: # compute reference log_prob with marked_timer(str(Role.RefPolicy), timing_raw, color="olive"): ref_log_prob = self._compute_ref_log_prob(batch) batch = batch.union(ref_log_prob) # compute values if self.use_critic: with marked_timer("values", timing_raw, color="cyan"): values = self._compute_values(batch) batch = batch.union(values) with marked_timer("adv", timing_raw, color="brown"): # we combine with rule-based rm reward_extra_infos_dict: dict[str, list] batch.batch["token_level_scores"] = reward_tensor if reward_extra_infos_dict: batch.non_tensor_batch.update({k: np.array(v) for k, v in reward_extra_infos_dict.items()}) # compute rewards. apply_kl_penalty if available if self.config.algorithm.use_kl_in_reward: batch, kl_metrics = apply_kl_penalty( batch, kl_ctrl=self.kl_ctrl_in_reward, kl_penalty=self.config.algorithm.kl_penalty ) metrics.update(kl_metrics) else: batch.batch["token_level_rewards"] = batch.batch["token_level_scores"] # Compute rollout correction: IS weights, rejection sampling, and metrics # Only runs in decoupled mode (computes once per batch using stable π_old) # In bypass mode, this is skipped - actor computes metrics from evolving π_θ vs π_rollout if ( rollout_corr_config is not None and "rollout_log_probs" in batch.batch and not bypass_recomputing_logprobs # Only in decoupled mode ): from verl.trainer.ppo.rollout_corr_helper import compute_rollout_correction_and_add_to_batch # Compute IS weights, apply rejection sampling, compute metrics batch, is_metrics = compute_rollout_correction_and_add_to_batch(batch, rollout_corr_config) # IS and off-policy metrics already have rollout_corr/ prefix metrics.update(is_metrics) # compute advantages, executed on the driver process norm_adv_by_std_in_grpo = self.config.algorithm.get( "norm_adv_by_std_in_grpo", True ) # GRPO adv normalization factor batch = compute_advantage( batch, adv_estimator=self.config.algorithm.adv_estimator, gamma=self.config.algorithm.gamma, lam=self.config.algorithm.lam, num_repeat=self.config.actor_rollout_ref.rollout.n, norm_adv_by_std_in_grpo=norm_adv_by_std_in_grpo, config=self.config.algorithm, ) # update critic if self.use_critic: with marked_timer("update_critic", timing_raw, color="pink"): critic_output = self._update_critic(batch) critic_output_metrics = reduce_metrics(critic_output.meta_info["metrics"]) metrics.update(critic_output_metrics) # implement critic warmup if self.config.trainer.critic_warmup <= self.global_steps: # update actor with marked_timer("update_actor", timing_raw, color="red"): actor_output = self._update_actor(batch) # Check if the ESI (Elastic Server Instance)/training plan is close to expiration. esi_close_to_expiration = should_save_ckpt_esi( max_steps_duration=self.max_steps_duration, redundant_time=self.config.trainer.esi_redundant_time, ) # Check if the conditions for saving a checkpoint are met. # The conditions include a mandatory condition (1) and # one of the following optional conditions (2/3/4): # 1. The save frequency is set to a positive value. # 2. It's the last training step. # 3. The current step number is a multiple of the save frequency. # 4. The ESI(Elastic Server Instance)/training plan is close to expiration. if self.config.trainer.save_freq > 0 and ( is_last_step or self.global_steps % self.config.trainer.save_freq == 0 or esi_close_to_expiration ): if esi_close_to_expiration: print("Force saving checkpoint: ESI instance expiration approaching.") with marked_timer("save_checkpoint", timing_raw, color="green"): self._save_checkpoint() # update weights from trainer to rollout with marked_timer("update_weights", timing_raw, color="red"): self.checkpoint_manager.update_weights() actor_output_metrics = reduce_metrics(actor_output.meta_info["metrics"]) metrics.update(actor_output_metrics) # Log rollout generations if enabled rollout_data_dir = self.config.trainer.get("rollout_data_dir", None) if rollout_data_dir: self._log_rollout_data(batch, reward_extra_infos_dict, timing_raw, rollout_data_dir) # validate if self.config.trainer.test_freq > 0 and ( is_last_step or self.global_steps % self.config.trainer.test_freq == 0 ): with marked_timer("testing", timing_raw, color="green"): val_metrics: dict = self._validate() if is_last_step: last_val_metrics = val_metrics metrics.update(val_metrics) with marked_timer("stop_profile", timing_raw): next_step_profile = ( self.global_steps + 1 in self.config.global_profiler.steps if self.config.global_profiler.steps is not None else False ) self._stop_profiling( curr_step_profile and not next_step_profile if self.config.global_profiler.profile_continuous_steps else curr_step_profile ) prev_step_profile = curr_step_profile curr_step_profile = next_step_profile steps_duration = timing_raw["step"] self.max_steps_duration = max(self.max_steps_duration, steps_duration) # training metrics metrics.update( { "training/global_step": self.global_steps, "training/epoch": epoch, } ) # collect metrics metrics.update(compute_data_metrics(batch=batch, use_critic=self.use_critic)) metrics.update(compute_timing_metrics(batch=batch, timing_raw=timing_raw)) # TODO: implement actual tflpo and theoretical tflpo n_gpus = self.resource_pool_manager.get_n_gpus() metrics.update(compute_throughout_metrics(batch=batch, timing_raw=timing_raw, n_gpus=n_gpus)) # compute variance proxy metrics gradient_norm = metrics.get("actor/grad_norm", None) metrics.update(compute_variance_proxy_metrics(batch=batch, gradient_norm=gradient_norm)) # Note: mismatch metrics (KL, PPL, etc.) are collected at line 1179 after advantage computation # this is experimental and may be changed/removed in the future in favor of a general-purpose one if isinstance(self.train_dataloader.sampler, AbstractCurriculumSampler): self.train_dataloader.sampler.update(batch=batch) # TODO: make a canonical logger that supports various backend logger.log(data=metrics, step=self.global_steps) progress_bar.update(1) self.global_steps += 1 if ( hasattr(self.config.actor_rollout_ref.actor, "profiler") and self.config.actor_rollout_ref.actor.profiler.tool == "torch_memory" ): self.actor_rollout_wg.dump_memory_snapshot( tag=f"post_update_step{self.global_steps}", sub_dir=f"step{self.global_steps}" ) if is_last_step: if hasattr(self.actor_rollout_wg, "async_calls_finalize_fn_exec"): self.actor_rollout_wg.async_calls_finalize_fn_exec(blocking=True) pprint(f"Final validation metrics: {last_val_metrics}") progress_bar.close() return # this is experimental and may be changed/removed in the future # in favor of a general-purpose data buffer pool if hasattr(self.train_dataset, "on_batch_end"): # The dataset may be changed after each training batch self.train_dataset.on_batch_end(batch=batch)
verl__trainer__ppo__ray_trainer.py
# Copyright 2025 Individual Contributor: Thibaut Barroyer # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import inspect import multiprocessing from functools import partial from typing import TYPE_CHECKING, Any, Optional, cast from verl import DataProto from verl.utils.reward_score import default_compute_score if TYPE_CHECKING: from omegaconf import DictConfig from verl.experimental.reward_loop.reward_manager.base import RawRewardFn, RewardManagerBase from verl.trainer.config.config import ModuleConfig from verl.workers.config.reward import RewardManagerConfig def _call_with_kwargs(raw_fn, extra_kwargs, *args, **kwargs): """Calls `raw_fn` by merging `extra_kwargs` into call-time `kwargs`, with `extra_kwargs` taking precedence. This function is used to merge additional keyword arguments with the original function's arguments. """ merged_kwargs = {**kwargs, **extra_kwargs} return raw_fn(*args, **merged_kwargs) async def _call_with_kwargs_async(raw_fn, extra_kwargs, *args, **kwargs): """Calls `raw_fn` by merging `extra_kwargs` into call-time `kwargs`, with `extra_kwargs` taking precedence. This function is used to merge additional keyword arguments with the original function's arguments. """ merged_kwargs = {**kwargs, **extra_kwargs} return await raw_fn(*args, **merged_kwargs) def get_custom_reward_fn(config: DictConfig) -> Optional[RawRewardFn]: """Load and return a custom reward function from external file. Dynamically imports a reward function from a specified file path and wraps it with additional keyword arguments from the configuration. Args: config (dict): Configuration dictionary containing custom_reward_function settings with 'path', 'name', and 'reward_kwargs' fields. Returns: callable or None: Wrapped reward function with merged kwargs, or None if no custom reward function is configured. Raises: FileNotFoundError: If the specified reward function file doesn't exist. RuntimeError: If there's an error loading the module from file. AttributeError: If the specified function name isn't found in the module. """ reward_fn_config = config.reward.get("custom_reward_function") or {} module_path = reward_fn_config.get("path") if not module_path: return None fn_name = reward_fn_config.get("name") assert fn_name is not None from verl.utils.import_utils import load_extern_object raw_fn = load_extern_object(module_path=module_path, object_name=fn_name) reward_kwargs = dict(reward_fn_config.get("reward_kwargs", {})) if not inspect.iscoroutinefunction(raw_fn): return partial(_call_with_kwargs, raw_fn, reward_kwargs) else: return partial(_call_with_kwargs_async, raw_fn, reward_kwargs) def load_reward_manager(config: DictConfig, tokenizer: Any, **reward_kwargs: Any) -> RewardManagerBase: """ Load and initialize a reward manager based on the configuration. Args: config: PPO trainer configuration object containing reward_model fields. tokenizer: Tokenizer object used for processing text. **reward_kwargs: Additional keyword arguments for the reward manager. Returns: 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_compute_score = compute_score reward_manager_cfg: RewardManagerConfig = config.reward.reward_manager reward_manager_cls: type[RewardManagerBase] if reward_manager_cfg.source == "register": from verl.experimental.reward_loop.reward_manager import get_reward_manager_cls reward_manager_cls = get_reward_manager_cls(reward_manager_cfg.name) elif reward_manager_cfg.source == "importlib": from verl.utils.import_utils import load_extern_object module_cfg: ModuleConfig | None = reward_manager_cfg.module assert module_cfg is not None and module_cfg.path is not None, ( f"Module path is required when {reward_manager_cfg.source=}, but got {module_cfg=}" ) reward_manager_cls_name = reward_manager_cfg.name reward_manager_cls = cast( "type[RewardManagerBase]", load_extern_object(module_path=module_cfg.path, object_name=reward_manager_cls_name), ) if compute_score is None: sandbox_config = config.reward.get("sandbox_fusion") sandbox_url = sandbox_config.get("url") if sandbox_config else None memory_limit_mb = sandbox_config.get("memory_limit_mb", 1024) if sandbox_config else 1024 if sandbox_url: sandbox_manager = multiprocessing.Manager() # Create a semaphore to control concurrent access to the sandbox _concurrent_semaphore = sandbox_manager.Semaphore(sandbox_config.get("max_concurrent", 64)) final_compute_score = partial( default_compute_score, sandbox_fusion_url=sandbox_url, concurrent_semaphore=_concurrent_semaphore, memory_limit_mb=memory_limit_mb, ) else: final_compute_score = default_compute_score # Instantiate and return the reward manager with the specified parameters return reward_manager_cls( config=config, tokenizer=tokenizer, compute_score=final_compute_score, **reward_kwargs, ) def extract_reward(batch: DataProto): """ Extract reward tensor and extra info from batch data. """ reward_tensor = batch.batch["rm_scores"] reward_extra_keys = batch.meta_info.get("reward_extra_keys", []) reward_extra_infos_dict = {key: batch.non_tensor_batch[key] for key in reward_extra_keys} return reward_tensor, reward_extra_infos_dict
verl__trainer__ppo__reward.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Rollout Correction Helper Module This module provides a complete pipeline to address **off-policy issues** in RL training, including: 1. Policy mismatch between rollout and training implementations (e.g., vLLM BFloat16 vs FSDP FP32) 2. Model update staleness (training on trajectories from older checkpoints) 3. General distribution shifts between data collection and training Its core capabilities include computing importance sampling (IS) weights, filtering outlier samples via rejection sampling (RS), and tracking metrics to diagnose and correct off-policy issues. ## Core Capabilities 1. **Multi-Granularity Aggregation**: - Importance Sampling (IS): Token-level Sequence-level - Rejection Sampling (RS): Divergence-based filters (token_k*, seq_sum_k*, seq_mean_k*, seq_max_k*) 2. **Memory-Efficient Design**: - Log-space computations to avoid numerical overflow/underflow. - Fixed safety bounds (exp(±20)) for stable exponentiation. - Metrics calculated without large intermediate tensors (prevents CUDA OOM). 3. **Comprehensive Metrics Tracking**: - IS/RS statistics (mean/max/min, effective sample size ESS, rejection rate). - Off-policy diagnostics (KL divergence, perplexity PPL, log PPL difference, χ² divergence). - Sequence-level breakdowns (deviation from ideal weights, outlier fraction). ## Key Interfaces & Usage - compute_rollout_correction_and_rejection_mask(): compute IS weights + rejection mask. - compute_rollout_correction_weights(): only compute truncated IS weights (for variance reduction, no outlier rejection). - compute_rollout_rejection_mask(): only filter outliers (for sample cleaning, no IS weight computation). - compute_offpolicy_metrics(): called by core functions to calculate off-policy diagnostics (KL/PPL/χ²) — no direct external calls needed. ### Integration Notes - Used in `ray_trainer.py` via `compute_rollout_correction_and_add_to_batch()` (batch training pipeline). - Used in `dp_actor.py` for distributed worker computations (distributed training scenarios). - All functions support batch inputs and valid token masking (via `response_mask`). ## References - "When Speed Kills Stability: Demystifying RL Collapse from the Training-Inference Mismatch": https://richardli.xyz/rl-collapse - Off-policy RL (theoretical basis for IS): https://fengyao.notion.site/off-policy-rl """ import math from typing import Any, Optional import torch import verl.utils.torch_functional as verl_F from verl.protocol import DataProto from verl.trainer.config.algorithm import RolloutCorrectionConfig from verl.workers.config.actor import PolicyLossConfig # Safety bound to prevent numerical overflow/underflow when exponentiating # exp(20) ≈ 485 million (upper limit for stable weights), exp(-20) ≈ 2e-9 (lower limit) SAFETY_BOUND = 20.0 SUPPORTED_ROLLOUT_RS_OPTIONS: set[str] = { "token_k1", "token_k2", "token_k3", "seq_sum_k1", "seq_sum_k2", "seq_sum_k3", "seq_mean_k1", "seq_mean_k2", "seq_mean_k3", "seq_max_k2", "seq_max_k3", } TOKEN_LEVEL_ROLLOUT_RS_OPTIONS: set[str] = {"token_k1", "token_k2", "token_k3"} def _parse_rollout_rs_thresholds( options: list[str], threshold_spec: Optional[str | float] ) -> dict[str, dict[str, Optional[float]]]: if threshold_spec is None: raise ValueError("rollout_rs_threshold must be provided for rejection sampling.") if isinstance(threshold_spec, int | float): raw_specs: list[str] = [str(threshold_spec)] elif isinstance(threshold_spec, str): raw_specs = [part.strip() for part in threshold_spec.split(",") if part.strip()] else: raise TypeError("rollout_rs_threshold must be a string or numeric value specifying per-option thresholds.") if not raw_specs: raise ValueError("rollout_rs_threshold must contain at least one threshold value.") if len(raw_specs) not in (1, len(options)): raise ValueError( f"rollout_rs_threshold expects either one threshold shared by all options or exactly " f"{len(options)} thresholds to match the provided rollout_rs options." ) if len(raw_specs) == 1 and len(options) > 1: raw_specs = raw_specs * len(options) thresholds: dict[str, dict[str, Optional[float]]] = {} for option, spec in zip(options, raw_specs, strict=False): if option.endswith("k1"): if "_" in spec: lower_str, upper_str = spec.split("_", 1) else: upper_str = spec lower_str = str(1.0 / float(upper_str)) try: lower = float(lower_str) upper = float(upper_str) except ValueError as exc: raise ValueError(f"Invalid numeric threshold '{spec}' for option '{option}'.") from exc if lower <= 0 or upper <= 0: raise ValueError(f"Thresholds for option '{option}' must be positive, got {spec}.") thresholds[option] = { "lower": lower, "upper": upper, } else: if "_" in spec: raise ValueError( f"rollout_rs_threshold for option '{option}' must provide a single upper bound " f"without '_'. Received '{spec}'." ) try: upper = float(spec) except ValueError as exc: raise ValueError(f"Invalid numeric threshold '{spec}' for option '{option}'.") from exc if upper <= 0: raise ValueError(f"Threshold for option '{option}' must be positive, got {spec}.") thresholds[option] = { "lower": None, "upper": upper, } return thresholds def compute_rollout_rejection_mask( log_ratio: torch.Tensor, response_mask: torch.Tensor, rollout_rs: str = "token_k1", rollout_rs_threshold: Optional[str | float] = None, ) -> tuple[torch.Tensor, dict[str, float]]: """Compute hard trust region mask using divergence estimators. This function enforces a hard trust region constraint by masking tokens/sequences where the estimated divergence (between training and rollout policies) exceeds a threshold. Unlike PPO's soft clipping, this provides a hard boundary. Multiple rejection criteria can be supplied via a comma separated `rollout_rs` string. All requested options must pass for a token/sequence to remain valid. Supported KL divergence-based modes (ideal = 0.0 unless noted): - "token_k{1,2,3}": Token-level divergences. - "seq_sum_k{1,2,3}": Sum of token divergences per sequence. - "seq_mean_k{1,2,3}": Mean of token divergences per sequence. - "seq_max_k{2,3}": Maximum token divergence per sequence. Args: log_ratio: Log ratio of training policy probability to rollout policy probability, shape (batch_size, seq_length). response_mask: Binary mask for valid tokens (1=valid, 0=padding), shape (batch_size, seq_length). rollout_rs: Comma separated rejection sampling options (e.g. "token_k1,seq_sum_k3"). rollout_rs_threshold: Threshold specification string (required). Provide one entry per rollout_rs option separated by commas. Each entry must be a positive number. For K1-style options (``*k1``), specify ``lower_upper`` (e.g. ``"0.1_1.2"``) to denote lower/upper ratio bounds; other options accept a single upper bound. Returns: Tuple containing: modified_response_mask: Response mask with trust region violations masked (0=rejected), shape (batch_size, seq_length). metrics: Dictionary of trust region metrics (all scalars). """ if rollout_rs is None or not isinstance(rollout_rs, str): raise ValueError("rollout_rs must be a non-empty string (comma separated for multiple options).") if rollout_rs_threshold is None: raise ValueError("rollout_rs_threshold must be provided for rejection sampling.") if log_ratio.shape[0] == 0: return response_mask, {} # rollout_rs supports chained criteria via comma separation (e.g. "token_k1,seq_mean_k3"). # Every listed option must pass; combined_mask aggregates them via logical AND. option_modes = [opt.strip() for opt in rollout_rs.split(",") if opt.strip()] if not option_modes: raise ValueError("rollout_rs must contain at least one valid option.") normalized_options: list[str] = [] seen: set[str] = set() for opt in option_modes: if opt not in SUPPORTED_ROLLOUT_RS_OPTIONS: raise ValueError( f"Invalid rollout_rs option: {opt}. Must be one of {sorted(SUPPORTED_ROLLOUT_RS_OPTIONS)}." ) if opt not in seen: normalized_options.append(opt) seen.add(opt) threshold_specs = _parse_rollout_rs_thresholds(normalized_options, rollout_rs_threshold) log_ratio_safe: torch.Tensor = torch.clamp(log_ratio, min=-SAFETY_BOUND, max=SAFETY_BOUND) token_k1: torch.Tensor = -log_ratio_safe token_k2: torch.Tensor = 0.5 * log_ratio_safe**2 token_k3: torch.Tensor = torch.exp(log_ratio_safe) - 1.0 - log_ratio_safe response_mask_bool: torch.Tensor = response_mask.bool() seq_valid_mask: torch.Tensor = response_mask.sum(dim=-1) > 0 # combined_mask accumulates per-option passes; any failure flips tokens to 0. combined_mask: torch.Tensor = torch.ones_like(response_mask, dtype=log_ratio.dtype) metrics: dict[str, float] = {} def _sequence_sum(values: torch.Tensor) -> torch.Tensor: return verl_F.masked_sum(values, response_mask, axis=-1) def _sequence_mean(values: torch.Tensor) -> torch.Tensor: return verl_F.masked_mean(values, response_mask, axis=-1) def _sequence_max(values: torch.Tensor) -> torch.Tensor: mask_bool = response_mask.bool() neg_inf = torch.tensor(float("-inf"), device=values.device, dtype=values.dtype) masked_values = values.masked_fill(~mask_bool, neg_inf) max_values = masked_values.max(dim=-1).values return torch.where(max_values == neg_inf, torch.zeros_like(max_values), max_values) for option_name in normalized_options: thresholds_info = threshold_specs[option_name] is_k1_option = option_name.endswith("k1") upper_value = thresholds_info["upper"] lower_value = thresholds_info["lower"] apply_lower_threshold = is_k1_option lower_log: Optional[float] = None upper_log: Optional[float] = None if is_k1_option: if lower_value is None or upper_value is None: raise ValueError( f"rollout_rs_threshold for option '{option_name}' must specify both lower and upper bounds." ) lower_log = math.log(lower_value) upper_log = math.log(upper_value) else: if upper_value is None: raise ValueError(f"rollout_rs_threshold for option '{option_name}' must specify an upper bound.") level = "sequence" if option_name not in TOKEN_LEVEL_ROLLOUT_RS_OPTIONS else "token" per_token_stat: torch.Tensor per_sequence_stat: Optional[torch.Tensor] = None token_keep_bool: torch.Tensor if option_name == "token_k1": if lower_log is None: raise ValueError("Threshold specification for token_k1 must include lower and upper bounds.") per_token_stat = token_k1 token_keep_bool = (per_token_stat >= lower_log) & (per_token_stat <= upper_log) elif option_name == "token_k2": per_token_stat = token_k2 token_keep_bool = per_token_stat <= upper_value elif option_name == "token_k3": per_token_stat = token_k3 token_keep_bool = per_token_stat <= upper_value elif option_name.startswith("seq_sum"): if option_name.endswith("k1"): if lower_log is None: raise ValueError( f"Threshold specification for option '{option_name}' must include lower and upper bounds." ) seq_stat = _sequence_sum(token_k1) seq_keep_bool_direct = (seq_stat >= lower_log) & (seq_stat <= upper_log) elif option_name.endswith("k2"): seq_stat = _sequence_sum(token_k2) seq_keep_bool_direct = seq_stat <= upper_value elif option_name.endswith("k3"): seq_stat = _sequence_sum(token_k3) seq_keep_bool_direct = seq_stat <= upper_value else: raise ValueError(f"Unsupported rollout_rs option: {option_name}.") per_sequence_stat = seq_stat token_keep_bool = seq_keep_bool_direct.unsqueeze(-1).expand_as(response_mask_bool) per_token_stat = seq_stat.unsqueeze(-1).expand_as(response_mask) elif option_name.startswith("seq_mean"): if option_name.endswith("k1"): if lower_log is None: raise ValueError( f"Threshold specification for option '{option_name}' must include lower and upper bounds." ) seq_stat = _sequence_mean(token_k1) seq_keep_bool_direct = (seq_stat >= lower_log) & (seq_stat <= upper_log) elif option_name.endswith("k2"): seq_stat = _sequence_mean(token_k2) seq_keep_bool_direct = seq_stat <= upper_value elif option_name.endswith("k3"): seq_stat = _sequence_mean(token_k3) seq_keep_bool_direct = seq_stat <= upper_value else: raise ValueError(f"Unsupported rollout_rs option: {option_name}.") per_sequence_stat = seq_stat token_keep_bool = seq_keep_bool_direct.unsqueeze(-1).expand_as(response_mask_bool) per_token_stat = seq_stat.unsqueeze(-1).expand_as(response_mask) elif option_name.startswith("seq_max"): if option_name.endswith("k2"): seq_stat = _sequence_max(token_k2) seq_keep_bool_direct = seq_stat <= upper_value elif option_name.endswith("k3"): seq_stat = _sequence_max(token_k3) seq_keep_bool_direct = seq_stat <= upper_value else: raise ValueError(f"Unsupported rollout_rs option: {option_name}.") per_sequence_stat = seq_stat token_keep_bool = seq_keep_bool_direct.unsqueeze(-1).expand_as(response_mask_bool) per_token_stat = seq_stat.unsqueeze(-1).expand_as(response_mask) else: raise ValueError(f"Unsupported rollout_rs option: {option_name}.") metrics_upper_threshold = upper_log if is_k1_option else upper_value metrics_lower_threshold = lower_log if (is_k1_option and lower_log is not None) else 0.0 token_keep_mask = token_keep_bool.to(dtype=log_ratio.dtype) combined_mask = combined_mask * token_keep_mask seq_keep_bool_tensor = (~((~token_keep_bool) & response_mask_bool)).all(dim=-1) option_metrics = compute_rs_metrics( option_name=option_name, rs_statistic=per_token_stat, response_mask=response_mask, seq_valid_mask=seq_valid_mask, level=level, per_sequence_values=per_sequence_stat, rollout_rs_threshold=metrics_upper_threshold, rollout_rs_threshold_lower=metrics_lower_threshold, apply_lower_threshold=apply_lower_threshold, ) metrics.update(option_metrics) token_masked_fraction = verl_F.masked_mean(1 - token_keep_mask, response_mask).item() seq_valid_float = seq_valid_mask.float() if seq_valid_float.sum() > 0: seq_keep_float = seq_keep_bool_tensor.to(dtype=log_ratio.dtype) seq_masked_fraction = (((1.0 - seq_keep_float) * seq_valid_float).sum() / seq_valid_float.sum()).item() else: seq_masked_fraction = 0.0 metrics[f"rollout_rs_{option_name}_masked_fraction"] = token_masked_fraction metrics[f"rollout_rs_{option_name}_seq_masked_fraction"] = seq_masked_fraction final_mask = combined_mask metrics["rollout_rs_masked_fraction"] = verl_F.masked_mean(1 - final_mask, response_mask).item() final_keep_bool = (final_mask > 0.5) & response_mask_bool seq_has_masked: torch.Tensor = (~final_keep_bool & response_mask_bool).any(dim=-1) metrics["rollout_rs_seq_masked_fraction"] = seq_has_masked.float().mean().item() modified_response_mask: torch.Tensor = (response_mask * final_mask).to(dtype=response_mask.dtype) return modified_response_mask, metrics def compute_rs_metrics( option_name: str, rs_statistic: torch.Tensor, response_mask: torch.Tensor, seq_valid_mask: torch.Tensor, *, level: str, per_sequence_values: Optional[torch.Tensor], rollout_rs_threshold: float, rollout_rs_threshold_lower: float, apply_lower_threshold: bool, ) -> dict[str, float]: """Compute metrics for hard trust region enforcement (per-option). Args: option_name: Original option string supplied by the user. rs_statistic: Trust region statistic (per token) used for thresholding. response_mask: Binary mask for valid tokens (1=valid, 0=padding). seq_valid_mask: Boolean mask indicating sequences with at least one valid token. level: "token" or "sequence" describing aggregation level. per_sequence_values: Optional per-sequence statistic (same semantics as rs_statistic). rollout_rs_threshold: Upper threshold. rollout_rs_threshold_lower: Lower threshold (ignored if ``apply_lower_threshold`` is False). apply_lower_threshold: Whether to mask/log metrics for values below the lower threshold. """ if not response_mask.any(): raise ValueError("response_mask must contain at least one valid token (1).") metrics: dict[str, float] = {} prefix = f"rollout_rs_{option_name}" mask_bool: torch.Tensor = response_mask.bool() # Compute sequence statistics (used by several metrics). if per_sequence_values is not None: seq_values = per_sequence_values else: seq_values = verl_F.masked_mean(rs_statistic, response_mask, axis=-1) if seq_values.dim() > 1: seq_values = seq_values.squeeze(-1) seq_values_valid = seq_values[seq_valid_mask] # Mean of the statistic (always reported). metrics[f"{prefix}_mean"] = verl_F.masked_mean(rs_statistic, response_mask).item() # Max/min values. if level == "sequence" and seq_values_valid.numel() > 0: metrics[f"{prefix}_max"] = seq_values_valid.max().item() metrics[f"{prefix}_min"] = seq_values_valid.min().item() else: metrics[f"{prefix}_max"] = rs_statistic.masked_fill(~mask_bool, float("-inf")).max().item() metrics[f"{prefix}_min"] = rs_statistic.masked_fill(~mask_bool, float("inf")).min().item() # Fractions above/below the thresholds. if level == "sequence" and seq_values_valid.numel() > 0: fraction_high = (seq_values_valid > rollout_rs_threshold).float().mean().item() fraction_low = ( (seq_values_valid < rollout_rs_threshold_lower).float().mean().item() if apply_lower_threshold else 0.0 ) else: fraction_high = verl_F.masked_mean((rs_statistic > rollout_rs_threshold).float(), response_mask).item() fraction_low = ( verl_F.masked_mean((rs_statistic < rollout_rs_threshold_lower).float(), response_mask).item() if apply_lower_threshold else 0.0 ) metrics[f"{prefix}_fraction_high"] = fraction_high metrics[f"{prefix}_fraction_low"] = fraction_low # Standard deviation (clamped for stability). mask_count: torch.Tensor = response_mask.sum() if mask_count > 1: if apply_lower_threshold: clamp_min = rollout_rs_threshold_lower else: clamp_min = 0.0 stat_for_std: torch.Tensor = rs_statistic.clamp(min=clamp_min, max=rollout_rs_threshold) mean_clamped: torch.Tensor = verl_F.masked_mean(stat_for_std, response_mask) stat_var: torch.Tensor = verl_F.masked_mean(stat_for_std.square(), response_mask) - mean_clamped.square() metrics[f"{prefix}_std"] = torch.sqrt(torch.clamp(stat_var, min=0.0)).item() else: metrics[f"{prefix}_std"] = 0.0 # Sequence-level summary metrics. if seq_values_valid.numel() > 0: metrics[f"{prefix}_seq_mean"] = seq_values_valid.mean().item() metrics[f"{prefix}_seq_std"] = seq_values_valid.std().item() if seq_values_valid.numel() > 1 else 0.0 metrics[f"{prefix}_seq_max"] = seq_values_valid.max().item() metrics[f"{prefix}_seq_min"] = seq_values_valid.min().item() metrics[f"{prefix}_seq_max_deviation"] = (seq_values_valid - 0.0).abs().max().item() metrics[f"{prefix}_seq_fraction_high"] = (seq_values_valid > rollout_rs_threshold).float().mean().item() if apply_lower_threshold: metrics[f"{prefix}_seq_fraction_low"] = ( (seq_values_valid < rollout_rs_threshold_lower).float().mean().item() ) else: metrics[f"{prefix}_seq_mean"] = 0.0 metrics[f"{prefix}_seq_std"] = 0.0 metrics[f"{prefix}_seq_max"] = 0.0 metrics[f"{prefix}_seq_min"] = 0.0 metrics[f"{prefix}_seq_max_deviation"] = 0.0 metrics[f"{prefix}_seq_fraction_high"] = 0.0 metrics[f"{prefix}_seq_fraction_low"] = 0.0 return metrics def compute_rollout_correction_weights( log_ratio: torch.Tensor, response_mask: torch.Tensor, rollout_is: str = "token", rollout_is_threshold: float = 2.0, rollout_is_batch_normalize: bool = False, ) -> tuple[torch.Tensor, dict[str, float]]: """Compute importance sampling weights to correct for off-policy distribution shifts. This function calculates IS weights (π_train / π_rollout) using log ratios for numerical stability. It supports multiple aggregation levels and truncates extreme weights to prevent training instability. Key design: - Log-space computations to avoid overflow - Truncation of extreme weights (TIS: Truncated Importance Sampling) - Optional batch normalization (normalize to mean=1.0) - Metrics tracking for weight distribution analysis Args: log_ratio: Log ratio of training policy probability to rollout policy probability, shape (batch_size, seq_length). response_mask: Binary mask for valid tokens (1=valid, 0=padding), shape (batch_size, seq_length). rollout_is: IS weight aggregation level, must be one of: - "token": Per-token weights (biased, low variance) - "sequence": Per-sequence weight (product of tokens; unbiased, high variance) rollout_is_threshold: Upper threshold for truncating extreme weights (e.g., 2.0), default 2.0. rollout_is_batch_normalize: Whether to normalize IS weights to have mean=1.0 per batch, default False. Returns: Tuple containing: rollout_is_weights: Truncated IS weights (masked to zero for padding tokens), shape (batch_size, seq_length). If batch_normalize=True, normalized to mean=1.0. metrics: Dictionary of IS weight metrics (all scalars), including: - rollout_is_mean/max/min: Statistic of weights (before batch normalization) - rollout_is_eff_sample_size: Effective sample size (ESS) - rollout_is_seq_*: Sequence-level weight statistics - rollout_is_batch_norm_factor: Normalization factor (only if batch_normalize=True) """ # Validate input parameters valid_is_levels = {"token", "sequence"} if rollout_is not in valid_is_levels: raise ValueError(f"Invalid rollout_is: {rollout_is}. Must be one of {valid_is_levels}.") if rollout_is_threshold <= 0: raise ValueError(f"rollout_is_threshold must be positive, got {rollout_is_threshold}.") # Compute IS weights from log ratio (handles different aggregation levels) if rollout_is == "token": # Per-token IS weight: exp(log(π_train/π_rollout)) with safety clamp log_ratio_for_metrics: torch.Tensor = log_ratio log_ratio_safe: torch.Tensor = torch.clamp(log_ratio, min=-SAFETY_BOUND, max=SAFETY_BOUND) rollout_is_weights: torch.Tensor = torch.exp(log_ratio_safe) elif rollout_is == "sequence": # Sequence-level IS weight: product of token ratios (exp(sum(log ratios))) log_ratio_sum: torch.Tensor = verl_F.masked_sum(log_ratio, response_mask, axis=-1).unsqueeze( -1 ) # Shape: (batch_size, 1) log_ratio_for_metrics = log_ratio_sum log_ratio_sum_safe: torch.Tensor = torch.clamp(log_ratio_sum, min=-SAFETY_BOUND, max=SAFETY_BOUND) rollout_is_weights = torch.exp(log_ratio_sum_safe).expand_as(log_ratio) # Broadcast to sequence length else: raise ValueError(f"Unsupported rollout_is: {rollout_is}") # Zero out weights for padding tokens using response mask rollout_is_weights = rollout_is_weights * response_mask # Compute IS weight metrics (BEFORE truncation to get accurate fraction_high/low) metrics: dict[str, float] = compute_is_metrics( rollout_is_weights=rollout_is_weights, log_ratio_for_metrics=log_ratio_for_metrics, response_mask=response_mask, rollout_is=rollout_is, rollout_is_threshold=rollout_is_threshold, ) # Truncate extreme weights (TIS: Truncated Importance Sampling) rollout_is_weights = rollout_is_weights.clamp(max=rollout_is_threshold) # Detach weights to prevent gradient flow (mathematically required by IS theory) # IS weights change the measure, not the objective. See §3.2.2 in docs/algo/rollout_corr_math.md rollout_is_weights = rollout_is_weights.detach() # Apply batch normalization if requested if rollout_is_batch_normalize: # Compute mean based on aggregation level mask_float = response_mask.to(dtype=rollout_is_weights.dtype) if rollout_is == "token": # Token-level: normalize over all token weights if torch.distributed.is_available() and torch.distributed.is_initialized(): weights_mean = verl_F.distributed_masked_mean(rollout_is_weights, mask_float) else: weights_mean = verl_F.masked_mean(rollout_is_weights, response_mask) elif rollout_is == "sequence": # Sequence-level: normalize over sequence weights (one weight per sequence) # For each sequence, compute mean over valid tokens (they all have the same weight) # then average across sequences seq_weights = verl_F.masked_mean(rollout_is_weights, response_mask, axis=-1) # (batch_size,) seq_mask = (response_mask.sum(dim=-1) > 0).to(dtype=rollout_is_weights.dtype) if torch.distributed.is_available() and torch.distributed.is_initialized(): weights_mean = verl_F.distributed_masked_mean(seq_weights, seq_mask) else: weights_mean = (seq_weights * seq_mask).sum() / seq_mask.sum().clamp_min(1e-8) else: raise ValueError(f"Unsupported rollout_is: {rollout_is}") # Normalize to mean=1.0 (avoid division by zero) if weights_mean > 1e-8: rollout_is_weights = rollout_is_weights / weights_mean metrics["rollout_is_batch_norm_factor"] = weights_mean.item() else: metrics["rollout_is_batch_norm_factor"] = 1.0 return rollout_is_weights, metrics def compute_is_metrics( rollout_is_weights: torch.Tensor, log_ratio_for_metrics: torch.Tensor, response_mask: torch.Tensor, rollout_is: str, rollout_is_threshold: float, ) -> dict[str, float]: """Compute comprehensive metrics for truncated importance sampling weights. This function calculates statistics for truncated IS weights (TIS), using log-space for accurate threshold checks and clamped weights for stable mean/std calculations. Args: rollout_is_weights: Truncated IS weights (π_train / π_rollout), shape (batch_size, seq_length). log_ratio_for_metrics: Log ratio of training to rollout probabilities (unclamped), shape varies by aggregation level. response_mask: Binary mask for valid tokens (1=valid, 0=padding), shape (batch_size, seq_length). rollout_is: IS weight aggregation level (matches compute_rollout_correction_weights). rollout_is_threshold: Upper threshold for truncated IS weights. Returns: Dictionary of IS weight metrics (all scalars). """ if not response_mask.any(): raise ValueError("response_mask must contain at least one valid token (1).") metrics: dict[str, float] = {} device: torch.device = rollout_is_weights.device # Default lower threshold (reciprocal of upper threshold) rollout_is_threshold_lower: float = 1.0 / rollout_is_threshold # Precompute log thresholds for accurate checks log_threshold_upper: torch.Tensor = torch.log(torch.tensor(rollout_is_threshold, device=device)) log_threshold_lower: torch.Tensor = torch.log(torch.tensor(rollout_is_threshold_lower, device=device)) # Compute metrics based on aggregation level if rollout_is == "sequence": # Sequence-level aggregation: use log-space for unclamped stats log_max: torch.Tensor = log_ratio_for_metrics.max() log_min: torch.Tensor = log_ratio_for_metrics.min() metrics["rollout_is_max"] = torch.exp(torch.clamp(log_max, max=SAFETY_BOUND)).item() metrics["rollout_is_min"] = torch.exp(log_min).item() # Mean uses truncated weights to avoid overflow metrics["rollout_is_mean"] = verl_F.masked_mean(rollout_is_weights, response_mask).item() # Fraction of weights exceeding thresholds (log-space for accuracy) exceeds_upper: torch.Tensor = log_ratio_for_metrics > log_threshold_upper below_lower: torch.Tensor = log_ratio_for_metrics < log_threshold_lower metrics["rollout_is_ratio_fraction_high"] = exceeds_upper.float().mean().item() metrics["rollout_is_ratio_fraction_low"] = below_lower.float().mean().item() else: # token-level # Token-level aggregation: compute directly from truncated weights metrics["rollout_is_mean"] = verl_F.masked_mean(rollout_is_weights, response_mask).item() # Fraction of tokens exceeding thresholds rollout_is_above_threshold: torch.Tensor = rollout_is_weights > rollout_is_threshold rollout_is_below_threshold: torch.Tensor = rollout_is_weights < rollout_is_threshold_lower metrics["rollout_is_ratio_fraction_high"] = verl_F.masked_mean( rollout_is_above_threshold.float(), response_mask ).item() metrics["rollout_is_ratio_fraction_low"] = verl_F.masked_mean( rollout_is_below_threshold.float(), response_mask ).item() # Max/min (mask out padding tokens) mask_bool: torch.Tensor = response_mask.bool() metrics["rollout_is_max"] = rollout_is_weights.masked_fill(~mask_bool, float("-inf")).max().item() metrics["rollout_is_min"] = rollout_is_weights.masked_fill(~mask_bool, float("inf")).min().item() # Compute standard deviation (using clamped weights for stability) mask_count: torch.Tensor = response_mask.sum() if mask_count > 1: weights_for_std: torch.Tensor = rollout_is_weights.clamp( min=rollout_is_threshold_lower, max=rollout_is_threshold ) mean_clamped: torch.Tensor = verl_F.masked_mean(weights_for_std, response_mask) rollout_is_var: torch.Tensor = ( verl_F.masked_mean(weights_for_std.square(), response_mask) - mean_clamped.square() ) metrics["rollout_is_std"] = torch.sqrt(torch.clamp(rollout_is_var, min=0.0)).item() else: metrics["rollout_is_std"] = 0.0 # Compute Effective Sample Size (ESS) for truncated weights weights_for_ess: torch.Tensor = rollout_is_weights.clamp(min=rollout_is_threshold_lower, max=rollout_is_threshold) mean_for_ess: torch.Tensor = verl_F.masked_mean(weights_for_ess, response_mask) is_weights_normalized: torch.Tensor = weights_for_ess / (mean_for_ess + 1e-8) # Avoid division by zero metrics["rollout_is_eff_sample_size"] = ( 1.0 / verl_F.masked_mean(is_weights_normalized.square(), response_mask).item() ) # Add sequence-level metrics if weights have batch dimension if rollout_is_weights.dim() > 1: seq_mean_weights: torch.Tensor = verl_F.masked_mean(rollout_is_weights, response_mask, axis=-1) metrics["rollout_is_seq_mean"] = seq_mean_weights.mean().item() metrics["rollout_is_seq_std"] = seq_mean_weights.std().item() if seq_mean_weights.numel() > 1 else 0.0 metrics["rollout_is_seq_max"] = seq_mean_weights.max().item() metrics["rollout_is_seq_min"] = seq_mean_weights.min().item() # Sequence deviation from ideal weight (1.0) seq_deviation: torch.Tensor = (seq_mean_weights - 1.0).abs() metrics["rollout_is_seq_max_deviation"] = seq_deviation.max().item() # Fraction of sequences with extreme weights metrics["rollout_is_seq_fraction_high"] = (seq_mean_weights > rollout_is_threshold).float().mean().item() metrics["rollout_is_seq_fraction_low"] = (seq_mean_weights < rollout_is_threshold_lower).float().mean().item() return metrics def compute_rollout_correction_and_rejection_mask( old_log_prob: torch.Tensor, rollout_log_prob: torch.Tensor, response_mask: torch.Tensor, rollout_is: Optional[str] = None, rollout_is_threshold: Optional[float] = 2.0, rollout_is_batch_normalize: bool = False, rollout_rs: Optional[str] = None, rollout_rs_threshold: Optional[str | float] = None, ) -> tuple[Optional[DataProto], torch.Tensor, dict[str, float]]: """Unified interface for computing IS weights and rejection masks. This function combines IS weight calculation (truncated) and rejection sampling (masked) into a single pipeline. Key design: - Separation of IS weights (for variance reduction) and rejection masks (for sample filtering) - Comprehensive metrics tracking for mismatch diagnosis Args: old_log_prob: Log probabilities from the training policy (e.g., FSDP FP32), shape (batch_size, seq_length). rollout_log_prob: Log probabilities from the rollout policy (e.g., vLLM BF16), shape (batch_size, seq_length). response_mask: Binary mask for valid tokens (1=valid, 0=padding), shape (batch_size, seq_length). rollout_is: IS weight aggregation level (see compute_rollout_correction_weights for options). Set to None to disable IS weight computation. rollout_is_threshold: Upper threshold for truncated IS weights (used if rollout_is is set), default 2.0. rollout_rs: Rejection sampling aggregation modes as a comma separated string (see compute_rollout_rejection_mask for the full list). Set to None to disable rejection sampling. rollout_rs_threshold: Threshold specification string (see compute_rollout_rejection_mask for details). Provide one threshold per option (comma separated). For K1-style options, specify ``lower_upper`` to denote the lower/upper ratio bounds. rollout_is_batch_normalize: Whether to normalize IS weights to have mean=1.0 per batch. Default: False. Returns: Tuple containing: rollout_is_weights_proto: DataProto with IS weights (None if rollout_is is None), key "rollout_is_weights", shape (batch_size, seq_length). modified_response_mask: Response mask with rejection sampling applied, shape (batch_size, seq_length). metrics: Dictionary of all metrics (prefixed with "rollout_corr/"), including: - IS weight statistics - Rejection sampling rates - Policy mismatch metrics (KL, PPL, etc.) """ # Validate input masks if not response_mask.any(): raise ValueError("response_mask must contain at least one valid token (1).") if old_log_prob.shape != rollout_log_prob.shape: raise ValueError( f"old_log_prob shape {old_log_prob.shape} does not match rollout_log_prob shape {rollout_log_prob.shape}." ) if old_log_prob.shape != response_mask.shape: raise ValueError( f"log_prob shape {old_log_prob.shape} does not match response_mask shape {response_mask.shape}." ) # Step 1: Compute log ratio (log(π_train / π_rollout)) log_ratio: torch.Tensor = old_log_prob - rollout_log_prob metrics: dict[str, float] = {} # Step 2: Compute IS weights (if enabled) rollout_is_weights: Optional[torch.Tensor] = None if rollout_is is not None and rollout_is_threshold is not None: rollout_is_weights, is_metrics = compute_rollout_correction_weights( log_ratio=log_ratio, response_mask=response_mask, rollout_is=rollout_is, rollout_is_threshold=rollout_is_threshold, rollout_is_batch_normalize=rollout_is_batch_normalize, ) metrics.update(is_metrics) # Step 3: Compute rejection mask (if enabled) modified_response_mask: torch.Tensor = response_mask.clone() if rollout_rs is not None: if rollout_rs_threshold is None: raise ValueError( "rollout_rs_threshold must be explicitly provided when rollout_rs is enabled. " "Set rollout_rs_threshold to the desired threshold value." ) modified_response_mask, rs_metrics = compute_rollout_rejection_mask( log_ratio=log_ratio, response_mask=response_mask, rollout_rs=rollout_rs, rollout_rs_threshold=rollout_rs_threshold, ) metrics.update(rs_metrics) # Step 4: Compute off-policy metrics (KL, PPL, χ², etc.) offpolicy_metrics: dict[str, float] = compute_offpolicy_metrics( old_log_prob=old_log_prob, rollout_log_prob=rollout_log_prob, response_mask=response_mask, ) metrics.update(offpolicy_metrics) # Step 6: Add "rollout_corr/" prefix to all metrics for logging consistency metrics_scalar: dict[str, float] = {} for key, value in metrics.items(): if isinstance(value, torch.Tensor): metrics_scalar[f"rollout_corr/{key}"] = value.item() else: metrics_scalar[f"rollout_corr/{key}"] = value # Step 7: Wrap IS weights in DataProto for consistency with API rollout_is_weights_proto: Optional[DataProto] = None if rollout_is_weights is not None: rollout_is_weights_proto = DataProto.from_dict(tensors={"rollout_is_weights": rollout_is_weights}) return rollout_is_weights_proto, modified_response_mask, metrics_scalar def compute_offpolicy_metrics( old_log_prob: torch.Tensor, rollout_log_prob: Optional[torch.Tensor], response_mask: torch.Tensor, ) -> dict[str, Any]: """Compute off-policy diagnostic metrics (helper function). This helper function operates on raw tensors and is used internally by: - compute_rollout_correction_and_rejection_mask() in this module (automatically included) - Tests (test_rollout_corr.py, test_rollout_corr_integration.py) These metrics help diagnose the off-policy gap between rollout and training policies, which can arise from: - Policy mismatch (e.g., vLLM BF16 vs FSDP FP32) - Model staleness (training on trajectories from older checkpoints) - General distribution shifts Key metrics: - kl: Direct KL divergence estimator KL(π_rollout || π_training) - k3_kl: K3 KL estimator for stability (more stable for small KL) - training_ppl: Perplexity of training policy - rollout_ppl: Perplexity of rollout policy - log_ppl_diff: Difference in log perplexities - ppl_ratio: Ratio of training PPL to rollout PPL - chi2_token: Token-level χ² divergence E[ρ²] - 1 - chi2_seq: Sequence-level χ² divergence E[(∏ρ_t)²] - 1 Args: old_log_prob: Log probabilities from training policy, shape (batch_size, seq_length) rollout_log_prob: Log probabilities from rollout policy, shape (batch_size, seq_length) response_mask: Mask for valid tokens, shape (batch_size, seq_length) Returns: Dictionary of off-policy metrics (without prefix) """ # Validate that we have at least one valid token assert response_mask.any(), "Expected at least one valid token in response_mask" metrics = {} # 1. Training policy perplexity (always available) # Formula: exp(-1/|T| * Σ log π_training(y_t|y_<t)) # where |T| is the number of tokens generated by the model mean_log_prob_training = verl_F.masked_mean(old_log_prob, response_mask, axis=-1) # (batch_size,) training_ppl = torch.exp(-mean_log_prob_training).mean() # Batch mean of per-sequence PPL metrics["training_ppl"] = training_ppl.detach().item() # Also log log-ppl for easier analysis (avoids exponential scale) metrics["training_log_ppl"] = (-mean_log_prob_training).mean().detach().item() # 2. Compute rollout off-policy metrics (only if rollout_log_probs available) if rollout_log_prob is not None: # 2a. kl: Direct estimator for KL(π_rollout || π_training) # This is the standard KL divergence: E[log(π_rollout) - log(π_training)] # Positive value means rollout policy is more confident than training policy metrics["kl"] = verl_F.masked_mean(rollout_log_prob - old_log_prob, response_mask).detach().item() # 2b. k3_kl: K3 estimator for KL(π_rollout || π_training) # More stable for small KL values using: E[exp(log_ratio) - log_ratio - 1] # Formula: KL ≈ E[r - log(r) - 1] where r = π_training/π_rollout log_ratio = old_log_prob - rollout_log_prob k3_kl_matrix = torch.exp(log_ratio) - log_ratio - 1 metrics["k3_kl"] = verl_F.masked_mean(k3_kl_matrix, response_mask).detach().item() # 2c. Rollout policy perplexity mean_log_prob_rollout = verl_F.masked_mean(rollout_log_prob, response_mask, axis=-1) # (batch_size,) rollout_ppl = torch.exp(-mean_log_prob_rollout).mean() # Batch mean of per-sequence PPL metrics["rollout_ppl"] = rollout_ppl.detach().item() metrics["rollout_log_ppl"] = (-mean_log_prob_rollout).mean().detach().item() # 2d. Log PPL difference (sequence-level perplexity difference) # log_ppl_diff = mean_log_prob_rollout - mean_log_prob_training # Since ppl = exp(-log_prob), we have: # log(ppl_ratio) = log(training_ppl/rollout_ppl) = log_ppl_diff # Positive value means training assigns lower probability (higher PPL) than rollout log_ppl_diff = mean_log_prob_rollout - mean_log_prob_training metrics["log_ppl_diff"] = log_ppl_diff.mean().detach().item() metrics["log_ppl_abs_diff"] = log_ppl_diff.abs().mean().detach().item() metrics["log_ppl_diff_max"] = log_ppl_diff.max().detach().item() metrics["log_ppl_diff_min"] = log_ppl_diff.min().detach().item() # 2e. PPL ratio (how much higher is training PPL vs rollout PPL) # Compute per-sequence ratio first, then average # For numerical stability, compute in log space using log_ppl_diff # Note: log_ppl_diff = log(ppl_ratio), so ppl_ratio = exp(log_ppl_diff) # This is the inverse of geometric IS: ppl_ratio_i = 1 / geometric_is_i for each sequence ppl_ratio = torch.exp(log_ppl_diff).mean() # mean(exp(log_ppl_diff)) = mean(ppl_ratio_i) metrics["ppl_ratio"] = ppl_ratio.detach().item() # 2f. Chi-squared divergence: χ²(π_training || π_rollout) = E_μ[ρ²] - 1 # where ρ = π_training / π_rollout and μ = π_rollout (rollout distribution) # This measures the variance of importance sampling weights # Token-level: E_token[ρ²] - 1 (averaged over all tokens) log_ratio_safe = torch.clamp(log_ratio, min=-SAFETY_BOUND, max=SAFETY_BOUND) rho_token = torch.exp(log_ratio_safe) # ρ = π_training / π_rollout (token-level) rho_squared_token = rho_token.square() chi2_token = verl_F.masked_mean(rho_squared_token, response_mask) - 1.0 metrics["chi2_token"] = chi2_token.detach().item() # Sequence-level: E_seq[(Π ρ_t)²] - 1 = E_seq[exp(2 * Σ log ρ_t)] - 1 log_ratio_sum = verl_F.masked_sum(log_ratio, response_mask, axis=-1) # Σ log ρ_t per sequence log_ratio_sum_safe = torch.clamp(log_ratio_sum, min=-SAFETY_BOUND, max=SAFETY_BOUND) rho_squared_seq = torch.exp(2.0 * log_ratio_sum_safe) # (Π ρ_t)² chi2_seq = rho_squared_seq.mean() - 1.0 metrics["chi2_seq"] = chi2_seq.detach().item() return metrics def compute_rollout_correction_and_add_to_batch( batch: DataProto, rollout_corr_config: RolloutCorrectionConfig ) -> tuple[DataProto, dict]: """Compute rollout correction weights and apply rejection sampling. Computes importance sampling weights to correct for off-policy issues between rollout and training policies. Applies rejection sampling by modifying response_mask. Always updates response_mask; conditionally adds IS weights. Key behavior: - response_mask: ALWAYS updated with rejection (RS exclusions removed from training) - rollout_is_weights: Added to batch ONLY if rollout_is parameter is set This separation ensures: - Rejection works independently of IS weight application - Metrics can be monitored before enabling IS weight correction Args: batch: DataProto with old_log_probs, rollout_log_probs, response_mask Returns: Tuple of (updated_batch, metrics): updated_batch: Batch with modified response_mask (always) and rollout_is_weights (if enabled) metrics: Dict of IS and off-policy metrics, all with "rollout_corr/" prefix Note: The implementation is copied from szrlee <szrlee@gmail.com>. """ # Get new API parameters directly from config rollout_is = rollout_corr_config.get("rollout_is", None) rollout_is_threshold = rollout_corr_config.get("rollout_is_threshold", 2.0) rollout_is_batch_normalize = rollout_corr_config.get("rollout_is_batch_normalize", False) rollout_rs = rollout_corr_config.get("rollout_rs", None) rollout_rs_threshold = rollout_corr_config.get("rollout_rs_threshold", None) # Compute IS weights and get modified response_mask rollout_is_weights, modified_response_mask, rollout_corr_metrics = compute_rollout_correction_and_rejection_mask( old_log_prob=batch.batch["old_log_probs"], rollout_log_prob=batch.batch["rollout_log_probs"], response_mask=batch.batch["response_mask"], rollout_is=rollout_is, rollout_is_threshold=rollout_is_threshold, rollout_is_batch_normalize=rollout_is_batch_normalize, rollout_rs=rollout_rs, rollout_rs_threshold=rollout_rs_threshold, ) # ALWAYS update response_mask with rejection applied batch.batch["response_mask"] = modified_response_mask # Add IS weights to batch if computed if rollout_is_weights is not None: batch = batch.union(rollout_is_weights) return batch, rollout_corr_metrics def compute_rollout_corr_metrics_from_logprobs( log_prob: torch.Tensor, rollout_log_prob: torch.Tensor, response_mask: torch.Tensor, ) -> dict[str, float]: """Compute rollout correction metrics from log probabilities during training. This function is used in the actor to compute metrics using the CURRENT policy log probabilities versus rollout log probabilities, allowing tracking of the off-policy gap as training progresses. It computes off-policy diagnostic metrics (KL, PPL, χ²) from log probabilities. Args: log_prob: Current policy log probabilities, shape (batch_size, seq_length) rollout_log_prob: Rollout policy log probabilities, shape (batch_size, seq_length) response_mask: Valid token mask, shape (batch_size, seq_length) Returns: Dictionary of metrics with "rollout_corr/" prefix """ # Compute off-policy diagnostic metrics offpolicy_metrics = compute_offpolicy_metrics( old_log_prob=log_prob, rollout_log_prob=rollout_log_prob, response_mask=response_mask, ) # Add rollout_corr/ prefix to all metrics metrics_with_prefix = {} for key, value in offpolicy_metrics.items(): if isinstance(value, torch.Tensor): metrics_with_prefix[f"rollout_corr/{key}"] = value.item() else: metrics_with_prefix[f"rollout_corr/{key}"] = value return metrics_with_prefix def apply_bypass_mode( batch: DataProto, rollout_corr_config: Optional[RolloutCorrectionConfig] = None, policy_loss_config: PolicyLossConfig = None, ) -> None: """ Setup bypass mode: Use rollout_log_probs as old_log_probs. Bypass mode skips expensive actor forward pass for old_log_prob computation by setting old_log_probs = rollout_log_probs (2 policies instead of 3). Uses compute_policy_loss_bypass_mode() which supports: - loss_type="ppo_clip" (default): PPO clipped objective (IS handled by ratio) - loss_type="reinforce": REINFORCE with explicit IS weights Both loss types benefit from rejection sampling (RS) which masks out-of-distribution samples. Note: The implementation is copied from szrlee <szrlee@gmail.com>. """ from omegaconf import open_dict if "rollout_log_probs" not in batch.batch: raise ValueError( "bypass_mode=True requires rollout_log_probs in batch. " "Ensure rollout worker is configured to calculate_log_probs=true." ) # Use rollout log probs as old log probs (zero-cost substitution) batch.batch["old_log_probs"] = batch.batch["rollout_log_probs"] with open_dict(policy_loss_config): # Pass rollout_correction config to actor for loss computation and metrics policy_loss_config["rollout_correction"] = rollout_corr_config # Always use bypass_mode loss function which handles both loss_types policy_loss_config["loss_mode"] = "bypass_mode"
verl__trainer__ppo__rollout_corr_helper.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from enum import Enum from omegaconf import DictConfig from verl.single_controller.base import Worker from verl.trainer.ppo.core_algos import AdvantageEstimator WorkerType = type[Worker] class Role(Enum): """ To create more roles dynamically, you can subclass Role and add new members """ Actor = 0 Rollout = 1 ActorRollout = 2 Critic = 3 RefPolicy = 4 RewardModel = 5 ActorRolloutRef = 6 Env = 7 def __str__(self): return self._get_role_string() def _get_role_string(self): role_mapping = { Role.Actor: "actor", Role.Rollout: "rollout", Role.ActorRollout: "actor_rollout", Role.Critic: "critic", Role.RefPolicy: "ref", Role.RewardModel: "rm", Role.ActorRolloutRef: "actor_rollout_ref", } return role_mapping.get(self, self.name.lower()) @classmethod def from_string(cls, name: str): string_mapping = { "actor": cls.Actor, "rollout": cls.Rollout, "actor_rollout": cls.ActorRollout, "critic": cls.Critic, "ref": cls.RefPolicy, "rm": cls.RewardModel, "actor_rollout_ref": cls.ActorRolloutRef, } role = string_mapping.get(name.lower()) if role is None: raise ValueError(f"No Role found for string: {name}") return role def need_reference_policy( config: DictConfig, ) -> bool: """Given the config, do we need ref policy.""" return config.algorithm.use_kl_in_reward or config.actor_rollout_ref.actor.use_kl_loss def need_reward_model( config: DictConfig, ) -> bool: """Given the config, do we need reward model.""" return config.reward.reward_model.enable def need_critic(config: DictConfig) -> bool: """Given a config, do we need critic.""" if config.critic.enable is not None: return bool(config.critic.enable) elif config.algorithm.adv_estimator == AdvantageEstimator.GAE: return True else: warnings.warn( "Disabled critic as algorithm.adv_estimator != gae. If it is not intended, please set critic.enable=True", stacklevel=2, ) return False
verl__trainer__ppo__utils.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from functools import partial from tensordict.tensorclass import NonTensorData os.environ["NCCL_DEBUG"] = "WARN" os.environ["TOKENIZERS_PARALLELISM"] = "true" import logging import hydra import torch import torch.distributed from omegaconf import OmegaConf from torch.utils.data import DistributedSampler from torchdata.stateful_dataloader import StatefulDataLoader from tqdm import tqdm from verl.utils import tensordict_utils as tu from verl.utils.checkpoint import CheckpointHandler from verl.utils.dataset.dataset_utils import SFTTensorCollator from verl.utils.dataset.multiturn_sft_dataset import MultiTurnSFTDataset from verl.utils.device import auto_set_device, get_device_name from verl.utils.distributed import destroy_global_process_group from verl.utils.logger import log_with_rank from verl.utils.memory_utils import aggressive_empty_cache from verl.utils.profiler import log_gpu_memory_usage from verl.utils.tracking import Tracking from verl.workers.engine_workers import TrainingWorker logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_SFT_LOGGING_LEVEL", "WARN")) class SFTTrainer: def __init__( self, config, ): self.config = config log_gpu_memory_usage(f"rank {torch.distributed.get_rank()}: Before SFTTrainer init", logger=logger) self.rank = torch.distributed.get_rank() self._build_config() self._build_dataset() self._build_engine() self._build_dataloader() self._init_engine() self._build_ckpt_handler() # Initialize resume-related variables self.resume_global_step = self.ckpt_handler.load_checkpoint() self.device_name = self.config.trainer.device if self.rank == 0: print(self.config) log_gpu_memory_usage(f"rank {self.rank}: After SFTTrainer init", logger=logger) def _build_ckpt_handler(self): resume_mode = getattr(self.config.trainer, "resume_mode", "auto") resume_from_path = getattr(self.config.trainer, "resume_from_path", None) max_ckpt_to_keep = getattr(self.config.trainer, "max_ckpt_to_keep", None) default_hdfs_dir = getattr(self.config.trainer, "default_hdfs_dir", None) self.ckpt_handler = CheckpointHandler( engine=self.engine, train_dataloader=self.train_dataloader, default_local_dir=self.config.trainer.default_local_dir, max_ckpt_to_keep=max_ckpt_to_keep, default_hdfs_dir=default_hdfs_dir, resume_mode=resume_mode, resume_from_path=resume_from_path, ) def _build_config(self): from verl.utils.config import omega_conf_to_dataclass self.model_config = omega_conf_to_dataclass(self.config.model) self.engine_config = omega_conf_to_dataclass(self.config.engine) self.optimizer_config = omega_conf_to_dataclass(self.config.optim) self.checkpoint_config = omega_conf_to_dataclass(self.config.checkpoint) self.profiler_config = omega_conf_to_dataclass(self.config.profiler) # check profile interval self.profiler_interval = self.config.trainer.profile_interval self._validate_profiler_interval() def _validate_profiler_interval(self): assert len(self.profiler_interval) == 2 self.start_profile_step = self.profiler_interval[0] self.end_profile_step = self.profiler_interval[1] assert self.end_profile_step >= self.start_profile_step if self.start_profile_step < 0: assert self.end_profile_step < 0 def _build_engine(self): from verl.workers.engine_workers import TrainingWorkerConfig from verl.workers.utils.losses import sft_loss self.loss_fn = partial(sft_loss, config=None) config = TrainingWorkerConfig( model_type="language_model", model_config=self.model_config, engine_config=self.engine_config, optimizer_config=self.optimizer_config, checkpoint_config=self.checkpoint_config, profiler_config=self.profiler_config, ) self.training_client = TrainingWorker(config=config) self.training_client.set_loss_fn(loss_fn=self.loss_fn) # Note that in SPMD world, this abstraction has to break self.engine = self.training_client.engine def _init_engine(self): # patch optimizer config if self.config.trainer.total_training_steps is not None: self.total_training_steps = self.config.trainer.total_training_steps else: self.total_training_steps = len(self.train_dataloader) * self.config.trainer.total_epochs self.optimizer_config.total_training_steps = self.total_training_steps self.steps_per_epoch = len(self.train_dataloader) # manage save and test frequency self.save_freq = self.config.trainer.save_freq if self.save_freq == "after_each_epoch": self.save_freq = self.steps_per_epoch self.test_freq = self.config.trainer.test_freq if self.test_freq == "after_each_epoch": self.test_freq = self.steps_per_epoch self.training_client.reset() def _build_dataset(self): config = self.config tokenizer = self.model_config.tokenizer processor = self.model_config.processor train_dataset = create_sft_dataset( config.data.train_files, config.data, tokenizer, processor, max_samples=config.data.get("train_max_samples", -1), ) if config.data.val_files: val_dataset = create_sft_dataset( config.data.val_files, config.data, tokenizer, processor, max_samples=config.data.get("val_max_samples", -1), ) else: val_dataset = None self.train_dataset, self.val_dataset = train_dataset, val_dataset def _build_dataloader(self): # build dataset config = self.config # build dataloader # Use data parallel rank and size instead of global rank and world size # Set pin_memory_device when pin_memory is enabled. device_name = get_device_name() dp_rank = self.engine.get_data_parallel_rank() dp_size = self.engine.get_data_parallel_size() 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_size // dp_size self.collate_fn = SFTTensorCollator(config.data.pad_mode) self.train_dataloader = StatefulDataLoader( dataset=self.train_dataset, batch_size=self.train_batch_size_per_dp, sampler=self.train_sampler, collate_fn=self.collate_fn, num_workers=self.config.data.num_workers, pin_memory=False, drop_last=True, pin_memory_device=device_name, ) if self.val_dataset: self.val_sampler = DistributedSampler( self.val_dataset, shuffle=False, num_replicas=dp_size, rank=dp_rank, drop_last=True ) self.val_dataloader = StatefulDataLoader( dataset=self.val_dataset, batch_size=self.train_batch_size_per_dp, sampler=self.val_sampler, collate_fn=self.collate_fn, num_workers=self.config.data.num_workers, pin_memory=False, drop_last=True, pin_memory_device=device_name, ) else: self.val_dataloader = None def _get_batch_seqlens(self, data): # mean over dp group is_nested = data["input_ids"].is_nested if is_nested: batch_seqlens: torch.Tensor = data["input_ids"].offsets().diff() else: batch_seqlens: torch.Tensor = data["attention_mask"].sum(dim=-1) batch_seqlens = batch_seqlens.to(self.device_name) # (global_bsz // dp) output_tensor = torch.empty( (batch_seqlens.shape[0] * self.engine.get_data_parallel_size(),), dtype=batch_seqlens.dtype, device=self.device_name, ) # (global_bsz,) torch.distributed.all_gather_into_tensor( output_tensor=output_tensor, input_tensor=batch_seqlens, group=self.engine.get_data_parallel_group(), ) batch_seqlens = output_tensor.tolist() return batch_seqlens def fit(self): is_logging = self.engine.is_mp_src_rank_with_outputs() and self.engine.get_data_parallel_rank() == 0 # TODO: add a unified tracking if is_logging: tracking = Tracking( project_name=self.config.trainer.project_name, experiment_name=self.config.trainer.experiment_name, default_backend=self.config.trainer.logger, config=OmegaConf.to_container(self.config, resolve=True), ) global_step = self.resume_global_step # Start from resumed step last_valid_metric = None log_with_rank( f"Total training steps: {self.total_training_steps},", logger=logger, rank=0, log_only_rank_0=True, ) # With StatefulDataLoader, we don't need to manually calculate epochs and steps # The dataloader will automatically resume from where it left off if global_step > 0: log_with_rank( f"StatefulDataLoader will automatically resume from global step: {global_step}", logger=logger, rank=0, log_only_rank_0=True, ) # Calculate which epoch we're starting from for sampler.set_epoch() start_epoch = global_step // self.steps_per_epoch meta_info = { "use_remove_padding": self.config.model.use_remove_padding, "use_dynamic_bsz": self.config.data.use_dynamic_bsz, "max_token_len_per_gpu": self.config.data.max_token_len_per_gpu, "micro_batch_size_per_gpu": self.config.data.micro_batch_size_per_gpu, "temperature": 1.0, "global_batch_size": self.global_batch_size, "pad_mode": self.config.data.pad_mode, "pad_token_id": self.model_config.tokenizer.pad_token_id, } train_time = 0 total_tokens = 0 for epoch in range(start_epoch, self.config.trainer.total_epochs): self.train_sampler.set_epoch(epoch=epoch) aggressive_empty_cache(force_sync=True) log_gpu_memory_usage(f"rank {self.rank}: At start of epoch {epoch}", logger=logger) for step_in_epoch, data in enumerate( tqdm( self.train_dataloader, initial=global_step % self.steps_per_epoch if epoch == start_epoch else 0, total=self.steps_per_epoch, desc=f"Epoch {epoch + 1}/{self.config.trainer.total_epochs}", disable=not is_logging, ) ): 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) # this is necessary. Otherwise, it is interpreted as NonTensorStack batch_seqlens_ntd = NonTensorData(batch_seqlens) tu.assign_non_tensor(data, update_lr_scheduler=True, global_token_num=batch_seqlens_ntd) # start profile in SPMD mode if global_step == self.start_profile_step: self.training_client.start_profile() # train for on batch output = self.training_client.train_batch(data=data) if global_step == self.end_profile_step: self.training_client.stop_profile() if self.engine.is_mp_src_rank_with_outputs(): metrics = tu.get(output, "metrics") # TODO: we can actual accumulate metrics for N steps and perform aggregate metrics for k in ["loss", "grad_norm", "lr", "mfu"]: if k in metrics.keys(): value = metrics.pop(k) metrics[f"train/{k}"] = value metrics["train/global_tokens"] = torch.sum( torch.tensor(batch_seqlens, device=self.device_name) ).item() total_tokens += metrics["train/global_tokens"] metrics["train/total_tokens(B)"] = total_tokens / 1e9 if self.engine.get_data_parallel_rank() == 0: tracking.log(data=metrics, step=global_step) is_last_step = global_step >= self.total_training_steps is_valid_step = global_step % self.test_freq == 0 is_save_step = global_step % self.save_freq == 0 # early exit or validation step if is_last_step and self.val_dataloader is not None or (self.test_freq > 0 and is_valid_step): # Perform validation val_losses = [] for val_data in self.val_dataloader: val_data = tu.get_tensordict(tensor_dict=val_data, non_tensor_dict=meta_info) output = self.training_client.infer_batch(val_data) if self.engine.is_mp_src_rank_with_outputs(): metrics = tu.get(output, "metrics") val_losses.append(metrics["loss"]) if self.engine.is_mp_src_rank_with_outputs(): val_loss = torch.mean(torch.tensor(val_losses, device=self.device_name)) # average over data parallel group torch.distributed.all_reduce( val_loss, op=torch.distributed.ReduceOp.AVG, group=self.engine.get_data_parallel_group() ) if is_logging: metric = {"val/loss": val_loss.detach().item()} tracking.log(data=metric, step=global_step) last_valid_metric = metric torch.distributed.barrier() if is_last_step or (self.save_freq > 0 and is_save_step): aggressive_empty_cache(force_sync=True) self.ckpt_handler.save_checkpoint(step=global_step) if is_last_step: if is_logging: print(f"Total time for train steps: {train_time:.2f}s") print(f"Final validation metrics: {last_valid_metric}") return def run_sft(config): from verl.utils.distributed import initialize_global_process_group initialize_global_process_group() trainer = SFTTrainer(config=config) trainer.fit() destroy_global_process_group() @hydra.main(config_path="config", config_name="sft_trainer_engine", version_base=None) def main(config): # Automatically set `config.trainer.device = npu` when running on Ascend NPU. auto_set_device(config) run_sft(config) def create_sft_dataset(data_paths, data_config, tokenizer, processor, max_samples=-1): """Create a dataset.""" # build dataset # First check if a custom dataset class is specified if data_config.custom_cls.get("path", None): from verl.utils.import_utils import load_extern_object dataset_cls = load_extern_object(data_config.custom_cls.path, data_config.custom_cls.name) else: # Default to multi-turn dataset dataset_cls = MultiTurnSFTDataset # Create datasets based on the selected class dataset = dataset_cls( parquet_files=data_paths, tokenizer=tokenizer, config=data_config, processor=processor, max_samples=max_samples ) return dataset if __name__ == "__main__": main()
verl__trainer__sft_trainer.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from functools import partial from tensordict.tensorclass import NonTensorData os.environ["NCCL_DEBUG"] = "WARN" os.environ["TOKENIZERS_PARALLELISM"] = "true" import logging import hydra import ray import torch import torch.distributed from omegaconf import OmegaConf from torch.utils.data import DistributedSampler from torchdata.stateful_dataloader import StatefulDataLoader from tqdm import tqdm from verl.utils import tensordict_utils as tu from verl.utils.checkpoint import CheckpointHandler, OrchestrationMode from verl.utils.dataset.dataset_utils import SFTTensorCollator from verl.utils.dataset.multiturn_sft_dataset import MultiTurnSFTDataset from verl.utils.device import auto_set_device, get_device_name from verl.utils.logger import log_with_rank from verl.utils.tracking import Tracking from verl.workers.engine_workers import TrainingWorker logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_SFT_LOGGING_LEVEL", "WARN")) class SFTTrainer: def __init__( self, config, ): self.config = config self._build_config() self._build_dataset() self._build_dataloader() self._build_engine() self._build_ckpt_handler() # Initialize resume-related variables self.resume_global_step = self.ckpt_handler.load_checkpoint() self.device_name = self.config.trainer.device print(self.config) def _build_ckpt_handler(self): resume_mode = getattr(self.config.trainer, "resume_mode", "auto") resume_from_path = getattr(self.config.trainer, "resume_from_path", None) max_ckpt_to_keep = getattr(self.config.trainer, "max_ckpt_to_keep", None) default_hdfs_dir = getattr(self.config.trainer, "default_hdfs_dir", None) self.ckpt_handler = CheckpointHandler( engine=self.training_client, train_dataloader=self.train_dataloader, default_local_dir=self.config.trainer.default_local_dir, max_ckpt_to_keep=max_ckpt_to_keep, default_hdfs_dir=default_hdfs_dir, resume_mode=resume_mode, resume_from_path=resume_from_path, mode=OrchestrationMode.RAY, ) def _build_config(self): from verl.utils.config import omega_conf_to_dataclass self.model_config = omega_conf_to_dataclass(self.config.model) self.engine_config = omega_conf_to_dataclass(self.config.engine) self.optimizer_config = omega_conf_to_dataclass(self.config.optim) self.checkpoint_config = omega_conf_to_dataclass(self.config.checkpoint) self.profiler_config = omega_conf_to_dataclass(self.config.profiler) # check profile interval self.profiler_interval = self.config.trainer.profile_interval self._validate_profiler_interval() def _validate_profiler_interval(self): assert len(self.profiler_interval) == 2 self.start_profile_step = self.profiler_interval[0] self.end_profile_step = self.profiler_interval[1] assert self.end_profile_step >= self.start_profile_step if self.start_profile_step < 0: assert self.end_profile_step < 0 def _build_engine(self): from verl.workers.engine_workers import TrainingWorkerConfig from verl.workers.utils.losses import sft_loss self.loss_fn = partial(sft_loss, config=None) config = TrainingWorkerConfig( model_type="language_model", model_config=self.model_config, engine_config=self.engine_config, optimizer_config=self.optimizer_config, checkpoint_config=self.checkpoint_config, profiler_config=self.profiler_config, ) # create resource pool and worker group from verl.single_controller.ray import RayClassWithInitArgs, RayResourcePool, RayWorkerGroup n_gpus_per_node = self.config.trainer.n_gpus_per_node nnodes = self.config.trainer.nnodes self.resource_pool = RayResourcePool(process_on_nodes=[n_gpus_per_node] * nnodes) ray_cls_with_init = RayClassWithInitArgs(ray.remote(TrainingWorker), config=config) self.training_client = RayWorkerGroup( resource_pool=self.resource_pool, ray_cls_with_init=ray_cls_with_init, device_name=self.config.trainer.device, ) self.training_client.set_loss_fn(loss_fn=self.loss_fn) self.training_client.reset() def _build_dataset(self): config = self.config tokenizer = self.model_config.tokenizer processor = self.model_config.processor train_dataset = create_sft_dataset( config.data.train_files, config.data, tokenizer, processor=processor, max_samples=config.data.get("train_max_samples", -1), ) if config.data.val_files: val_dataset = create_sft_dataset( config.data.val_files, config.data, tokenizer, processor=processor, max_samples=config.data.get("val_max_samples", -1), ) else: val_dataset = None self.train_dataset, self.val_dataset = train_dataset, val_dataset def _build_dataloader(self): # build dataset config = self.config # build dataloader # Use data parallel rank and size instead of global rank and world size # Set pin_memory_device when pin_memory is enabled. device_name = get_device_name() 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_size // dp_size self.collate_fn = SFTTensorCollator(config.data.pad_mode) self.train_dataloader = StatefulDataLoader( dataset=self.train_dataset, batch_size=self.train_batch_size_per_dp, sampler=self.train_sampler, collate_fn=self.collate_fn, num_workers=8, pin_memory=False, drop_last=True, pin_memory_device=device_name, ) if self.val_dataset: self.val_sampler = DistributedSampler( self.val_dataset, shuffle=False, num_replicas=dp_size, rank=dp_rank, drop_last=True ) self.val_dataloader = StatefulDataLoader( dataset=self.val_dataset, batch_size=self.train_batch_size_per_dp, sampler=self.val_sampler, collate_fn=self.collate_fn, num_workers=8, pin_memory=False, drop_last=True, pin_memory_device=device_name, ) else: self.val_dataloader = None # update if self.config.trainer.total_training_steps is not None: self.total_training_steps = self.config.trainer.total_training_steps else: self.total_training_steps = len(self.train_dataloader) * self.config.trainer.total_epochs self.optimizer_config.total_training_steps = self.total_training_steps self.steps_per_epoch = len(self.train_dataloader) # manage save and test frequency self.save_freq = self.config.trainer.save_freq if self.save_freq == "after_each_epoch": self.save_freq = self.steps_per_epoch self.test_freq = self.config.trainer.test_freq if self.test_freq == "after_each_epoch": self.test_freq = self.steps_per_epoch def _get_batch_seqlens(self, data): # mean over dp group is_nested = data["input_ids"].is_nested if is_nested: batch_seqlens: torch.Tensor = data["input_ids"].offsets().diff() else: batch_seqlens: torch.Tensor = data["attention_mask"].sum(dim=-1) return batch_seqlens def fit(self): tracking = Tracking( project_name=self.config.trainer.project_name, experiment_name=self.config.trainer.experiment_name, default_backend=self.config.trainer.logger, config=OmegaConf.to_container(self.config, resolve=True), ) global_step = self.resume_global_step # Start from resumed step last_valid_metric = None log_with_rank( f"Total training steps: {self.total_training_steps},", logger=logger, rank=0, log_only_rank_0=True, ) # With StatefulDataLoader, we don't need to manually calculate epochs and steps # The dataloader will automatically resume from where it left off if global_step > 0: log_with_rank( f"StatefulDataLoader will automatically resume from global step: {global_step}", logger=logger, rank=0, log_only_rank_0=True, ) # Calculate which epoch we're starting from for sampler.set_epoch() start_epoch = global_step // self.steps_per_epoch meta_info = { "use_remove_padding": self.config.model.use_remove_padding, "use_dynamic_bsz": self.config.data.use_dynamic_bsz, "max_token_len_per_gpu": self.config.data.max_token_len_per_gpu, "micro_batch_size_per_gpu": self.config.data.micro_batch_size_per_gpu, "temperature": 1.0, "global_batch_size": self.global_batch_size, "pad_mode": self.config.data.pad_mode, "pad_token_id": self.model_config.tokenizer.pad_token_id, } train_time = 0 total_tokens = 0 for epoch in range(start_epoch, self.config.trainer.total_epochs): self.train_sampler.set_epoch(epoch=epoch) for step_in_epoch, data in enumerate( tqdm( self.train_dataloader, initial=global_step % self.steps_per_epoch if epoch == start_epoch else 0, total=self.steps_per_epoch, desc=f"Epoch {epoch + 1}/{self.config.trainer.total_epochs}", ) ): 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).tolist() # this is necessary. Otherwise, it is interpreted as NonTensorStack batch_seqlens_ntd = NonTensorData(batch_seqlens) tu.assign_non_tensor(data, update_lr_scheduler=True, global_token_num=batch_seqlens_ntd) # start profile in SPMD mode if global_step == self.start_profile_step: self.training_client.start_profile() # train for on batch output = self.training_client.train_batch(data) output = output.get() if global_step == self.end_profile_step: self.training_client.stop_profile() metrics = tu.get(output, "metrics") # TODO: we can actual accumulate metrics for N steps and perform aggregate metrics metrics["train/loss"] = metrics.pop("loss") metrics["train/grad_norm"] = metrics.pop("grad_norm") metrics["train/lr"] = metrics.pop("lr") metrics["train/mfu"] = metrics.pop("mfu") metrics["train/global_tokens"] = torch.sum(torch.tensor(batch_seqlens, device=self.device_name)).item() total_tokens += metrics["train/global_tokens"] metrics["train/total_tokens(B)"] = total_tokens / 1e9 tracking.log(data=metrics, step=global_step) is_last_step = global_step >= self.total_training_steps is_valid_step = global_step % self.test_freq == 0 is_save_step = global_step % self.save_freq == 0 # early exit or validation step if is_last_step and self.val_dataloader is not None or (self.test_freq > 0 and is_valid_step): # Perform validation val_losses = [] for val_data in self.val_dataloader: val_data = tu.get_tensordict(tensor_dict=val_data, non_tensor_dict=meta_info) output = self.training_client.infer_batch(val_data) output = output.get() metrics = tu.get(output, "metrics") val_losses.append(metrics["loss"]) val_loss = torch.mean(torch.tensor(val_losses, device=self.device_name)) metric = {"val/loss": val_loss.detach().item()} tracking.log(data=metric, step=global_step) last_valid_metric = metric if is_last_step or (self.save_freq > 0 and is_save_step): self.ckpt_handler.save_checkpoint(step=global_step) if is_last_step: print(f"Total time for train steps: {train_time:.2f}s") print(f"Final validation metrics: {last_valid_metric}") return def run_sft(config): ray.init() trainer = SFTTrainer(config=config) trainer.fit() @hydra.main(config_path="config", config_name="sft_trainer_engine", version_base=None) def main(config): # Automatically set `config.trainer.device = npu` when running on Ascend NPU. auto_set_device(config) run_sft(config) def create_sft_dataset(data_paths, data_config, tokenizer, processor, max_samples=-1): """Create a dataset.""" # build dataset # First check if a custom dataset class is specified if data_config.custom_cls.get("path", None): from verl.utils.import_utils import load_extern_type dataset_cls = load_extern_type(data_config.custom_cls.path, data_config.custom_cls.name) else: # Default to multi-turn dataset dataset_cls = MultiTurnSFTDataset # Create datasets based on the selected class dataset = dataset_cls( parquet_files=data_paths, tokenizer=tokenizer, config=data_config, processor=processor, max_samples=max_samples ) return dataset if __name__ == "__main__": main()
verl__trainer__sft_trainer_ray.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Copyright (c) 2022-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functionality for CPU offloading of tensors saved for backward pass.""" from __future__ import annotations import functools import logging import os from typing import Any, Optional import torch from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from verl.utils.device import get_torch_device from verl.utils.fsdp_utils import FSDPModule as FSDP2 logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) def _get_unique_tensor_key(tensor): key = (tensor.untyped_storage().data_ptr() + tensor.storage_offset(), tensor.dtype) return key class FSDPParameterFilter: def __init__(self): self.model_parameters_storage = set() def __call__(self, tensor): return tensor.untyped_storage().data_ptr() not in self.model_parameters_storage def update_model_parameters(self, model): new_storage = set() for p in model.parameters(): new_storage.add(p.data.untyped_storage().data_ptr()) self.model_parameters_storage = new_storage class CpuOffloadHookWithOffloadHandler: """Context-manager that offloads/recovers tensors through an offload hander. The hook just offloads/recovers the tensor object to the handler through `tensor_push` and `tensor_pop` interface. How the offload-handler manages the offloading, recovering or prefetching timing is transparent to this hook. """ def __init__( self, offload_handler: OffloadHandler, handler_extra_kwargs: Optional[dict[str, Any]] = None, ) -> None: if handler_extra_kwargs is None: handler_extra_kwargs = {} self.offload_handler: OffloadHandler = offload_handler self.handler_extra_kwargs: dict[str, Any] = handler_extra_kwargs self.inside_context = False def __enter__(self): self.inside_context = True torch._C._autograd._push_saved_tensors_default_hooks(self.on_save_for_backward, self.on_get_saved_tensor) def __exit__(self, *args: Any): self.inside_context = False torch._C._autograd._pop_saved_tensors_default_hooks() def on_save_for_backward(self, tensor: torch.Tensor) -> Any: retrieve_identifier = self.offload_handler.tensor_push(tensor, **self.handler_extra_kwargs) return retrieve_identifier def on_get_saved_tensor(self, saved_state: Any) -> torch.Tensor: tensor = self.offload_handler.tensor_pop(saved_state, **self.handler_extra_kwargs) return tensor class OffloadHandler: """A base class for CPU offload-handler.""" def __init__(self) -> None: pass def tensor_push(self, tensor: torch.Tensor, **kwargs) -> Any: """Tensor push.""" raise NotImplementedError( "`tensor_push is not implented in OffloadHandler class. Inherit this class and implement your " "custom tensor_push." ) def tensor_pop(self, tensor_tag: Any, **kwargs): """Tensor pop.""" raise NotImplementedError( "`tensor_pop is not implented in OffloadHandler class. Inherit this class and implement your " "custom tensor_pop." ) class GroupCommitFunction(torch.autograd.Function): """this is a dummy op with output identical to input. However, it is necessary for marking a timepoint for offload handler to accomplish all synchronizations. Implementing it as a function is necessary because we need to actions in both forward and backward. """ @staticmethod def forward(ctx, tensor, cpu_offload_handler): # pylint: disable=missing-function-docstring cpu_offload_handler.on_group_commit_forward() ctx.cpu_offload_handler = cpu_offload_handler # return the identical tensor return tensor @staticmethod def backward(ctx, grad_output): # pylint: disable=missing-function-docstring cpu_offload_handler = ctx.cpu_offload_handler cpu_offload_handler.on_group_commit_backward() return grad_output, None group_prefetch_offload_commit = GroupCommitFunction.apply class SynchronizedGroupOffloadHandler(OffloadHandler): """Offload Handler that offloads/reloads in a synchronized way. The device-to-host and host-to-device copying happen in the same stream as the computation kernels, thus the copying will block computation. """ def __init__(self, num_offload_group, tensor_need_offloading_checker=(lambda _: True)) -> None: super().__init__() self.num_offload_group = num_offload_group self.tensor_need_offloading_checker = tensor_need_offloading_checker self.groupid_reset() def groupid_reset(self): """Groupid reset.""" # Data structures to label saved tensors and book-keep their cpu copies. # Currently, on push, create a new cpu tensor and copies; on pop, copies # the tensor back to gpu and deletes the cpu tensor. # These will increment whenever `group_commit()` is invoked self.current_group, self.tensor_count_current_group = (0, 0) self.torch_tensor_count = 0 self.tensor_tag_to_state = {} def on_group_commit_forward(self): """On group commit forward.""" # finishing up with updating current group and tensor count self.current_group += 1 # increment self.tensor_count_current_group = 0 # reset def on_group_commit_backward(self): """On group commit backward.""" self.current_group -= 1 assert self.current_group >= 0 @staticmethod def offload(src_tensor, pin_memory=True): """Offload.""" cpu_backup = torch.empty( src_tensor.size(), dtype=src_tensor.dtype, layout=src_tensor.layout, device="cpu", pin_memory=pin_memory, ) cpu_backup.copy_(src_tensor, non_blocking=True) state = (src_tensor.device, cpu_backup) return state @staticmethod def reload(state, non_blocking=None): """Reload.""" dev, cpu_backup = state if non_blocking is None: non_blocking = cpu_backup.is_pinned() return cpu_backup.to(dev, non_blocking=non_blocking) def tensor_push(self, tensor: torch.Tensor, **kwargs): """Tensor push.""" # obtain a unique tensor tag tensor_tag = (self.current_group, self.tensor_count_current_group) self.tensor_count_current_group += 1 assert tensor_tag not in self.tensor_tag_to_state if self.current_group < self.num_offload_group and self.tensor_need_offloading_checker(tensor): state = SynchronizedGroupOffloadHandler.offload(tensor) self.tensor_tag_to_state[tensor_tag] = state else: # will be offloaded together after group commit self.tensor_tag_to_state[tensor_tag] = tensor return tensor_tag def tensor_pop(self, tensor_tag, **kwargs): """Tensor pop.""" assert tensor_tag in self.tensor_tag_to_state state = self.tensor_tag_to_state.pop(tensor_tag) if isinstance(state, tuple): tensor = SynchronizedGroupOffloadHandler.reload(state) else: tensor = state return tensor class AsyncDoubleBufferGroupOffloadHandler(SynchronizedGroupOffloadHandler): """Compared to synchronize, this uses more memory because of the buffer but achieves better performance due to the overlapping. D2h and h2d copying are completely hidden behind computation if computation time of a layer is longer than host-device communication time. Bulk offloading with delay and bulk reloading with prefetch are implemented.""" def __init__( self, num_offload_group, # must be <= actual number of groups (number of commits) num_model_group, tensor_need_offloading_checker=(lambda t: True), ) -> None: super().__init__( num_offload_group=num_offload_group, tensor_need_offloading_checker=tensor_need_offloading_checker, ) # Number of layers in the model self.num_layers = num_model_group # Data Structure to maintain reference to activation tensors self.tensor_tag_to_buf = {} # Tracking the number of layers offloaded self.offloaded_group_count = 0 # Core data structure that decides the window for offloading self.layer_window_map = {} self.group_offload_mapping = {} # Logic to make offloading load balance across computation # for optimal CPU/GPU interconnect usage constant = 0 for i in range(self.num_offload_group): self.layer_window_map[i] = ((self.num_layers // self.num_offload_group) * (i + 1)) - 1 if i < (self.num_layers % self.num_offload_group): self.layer_window_map[i] += i + 1 constant = i + 1 else: self.layer_window_map[i] += constant # allocate streams and events for synchronization self.d2h_stream = get_torch_device().Stream() self.h2d_stream = get_torch_device().Stream() def tensor_push(self, tensor: torch.Tensor, **kwargs) -> Any: torch_stray_tensor = isinstance( tensor, torch._subclasses.fake_tensor.FakeTensor | torch._subclasses.functional_tensor.FunctionalTensor, ) need_offload = not torch_stray_tensor need_offload = need_offload and self.tensor_need_offloading_checker(tensor) if need_offload: # obtain a unique tensor tag tensor_tag = (self.current_group, self.tensor_count_current_group) self.tensor_count_current_group += 1 assert tensor_tag not in self.tensor_tag_to_state self.tensor_tag_to_state[tensor_tag] = tensor if self.current_group < self.num_offload_group: self.tensor_tag_to_buf[tensor_tag] = tensor else: tensor_tag = tensor return tensor_tag def tensor_pop(self, tensor_tag, **kwargs): """Tensor pop.""" if isinstance(tensor_tag, torch.Tensor): return tensor_tag assert tensor_tag in self.tensor_tag_to_state tensor = self.tensor_tag_to_state.pop(tensor_tag) self.tensor_tag_to_buf.pop(tensor_tag, None) # the tensor should have been copied back in on_group_commit_backward() # which invokes bulk_reload_group. assert not isinstance(tensor, tuple) return tensor def bulk_offload_group(self, group_to_offload): """Bulk offload group.""" offload_mapping = {} offload_size = 0 with get_torch_device().stream(self.d2h_stream): for tensor_tag, state in self.tensor_tag_to_state.items(): group_id, _ = tensor_tag if group_id == group_to_offload: assert not isinstance(state, tuple) key = _get_unique_tensor_key(state) if key not in offload_mapping: offload_mapping[key] = state # if offload, return the reference to cpu copy self.tensor_tag_to_state[tensor_tag] = (key, state.shape) for key, tensor in offload_mapping.items(): state = SynchronizedGroupOffloadHandler.offload(tensor) offload_size += tensor.numel() * tensor.element_size() offload_mapping[key] = state self.group_offload_mapping[group_to_offload] = offload_mapping def synchronize_on_group_commit_forward(self, current_group): """Synchronize on group commit forward.""" # For the first group, kickstart the offload after we have # the first compute completion if current_group == 0: self.d2h_stream.wait_stream(get_torch_device().current_stream()) self.bulk_offload_group(current_group) # Window map data structure helps us synchronize based on number # of layers offloaded if self.layer_window_map[self.offloaded_group_count] == current_group: # Stream synchronization both ways self.d2h_stream.wait_stream(get_torch_device().current_stream()) get_torch_device().current_stream().wait_stream(self.d2h_stream) # Time to free the activation memory after usage for tensor_tag, _ in self.tensor_tag_to_buf.items(): if tensor_tag[0] == self.offloaded_group_count: self.tensor_tag_to_buf[tensor_tag] = None # Time to offload the next group if self.offloaded_group_count < (self.num_offload_group - 1): self.bulk_offload_group(self.offloaded_group_count + 1) # Increment the offload group count to keep track self.offloaded_group_count += 1 def on_group_commit_forward(self): """This function will cause host device synchronization""" # handle synchronization events self.synchronize_on_group_commit_forward(self.current_group) super().on_group_commit_forward() @torch.no_grad def bulk_reload_group(self, group_to_reload): """Bulk reload group.""" assert group_to_reload < self.num_offload_group with get_torch_device().stream(self.h2d_stream): # move back tensors offload_mapping = self.group_offload_mapping.pop(group_to_reload) assert offload_mapping is not None for key, state in offload_mapping.items(): offload_mapping[key] = SynchronizedGroupOffloadHandler.reload(state) for tensor_label, state in self.tensor_tag_to_state.items(): group_id, _ = tensor_label if group_id == group_to_reload and not isinstance(state, torch.Tensor): assert isinstance(state, tuple), f"{group_id} {state}" key, shape = state recovered_tensor = offload_mapping[key].view(shape) self.tensor_tag_to_state[tensor_label] = recovered_tensor def on_group_commit_backward(self): # first decrement the current group. # after last commit in forward, the group will +1; in backward it -1. # Finally it should be decremented to 0. self.current_group -= 1 assert self.current_group >= 0 # Layer window data structure helps us to reload at right times if self.layer_window_map[self.offloaded_group_count - 1] == self.current_group: # Stream synchronization both ways self.h2d_stream.wait_stream(get_torch_device().current_stream()) get_torch_device().current_stream().wait_stream(self.h2d_stream) # Time to reload the next group self.bulk_reload_group(self.offloaded_group_count - 1) # Decrease the offloading group counter self.offloaded_group_count -= 1 if self.offloaded_group_count > 1 else 0 # Last group computation needs to wait till all the reloads complete if self.current_group == 0: get_torch_device().current_stream().wait_stream(self.h2d_stream) self.offloaded_group_count = 0 def get_activation_offload_context( num_layers: int = 1, model_layers: int = 1, tensor_need_offloading_checker=(lambda t: True) ): cpu_offload_handler = AsyncDoubleBufferGroupOffloadHandler( num_offload_group=num_layers, num_model_group=model_layers, tensor_need_offloading_checker=tensor_need_offloading_checker, ) def group_prefetch_offload_commit_async(tensor): return group_prefetch_offload_commit(tensor, cpu_offload_handler) return ( CpuOffloadHookWithOffloadHandler(offload_handler=cpu_offload_handler), group_prefetch_offload_commit_async, ) class ActivationHandler: def __init__(self, offload_ctx, sync_func, tensor_filter, enable_ckpt): self._offload_ctx = offload_ctx self._sync_func = sync_func self._enable_ckpt = enable_ckpt self._tensor_filter = tensor_filter if enable_ckpt: self.checkpoint_fn = functools.partial( torch.utils.checkpoint.checkpoint, use_reentrant=True, ) def pre_forward(self, module): if module.training: self._offload_ctx.__enter__() self._tensor_filter.update_model_parameters(module) def post_forward(self, module): if module.training: self._offload_ctx.__exit__(None, None, None) def _pack_kwargs(self, *args, **kwargs): kwarg_keys = [] flat_args = list(args) for k, v in kwargs.items(): kwarg_keys.append(k) flat_args.append(v) return tuple(flat_args), tuple(kwarg_keys) def _unpack_kwargs(self, flat_args, kwarg_keys): assert len(kwarg_keys) <= len(flat_args), f"too many keys {len(kwarg_keys)} vs. {len(flat_args)}" if len(kwarg_keys) == 0: return flat_args, {} args = flat_args[: -len(kwarg_keys)] kwargs = dict(zip(kwarg_keys, flat_args[-len(kwarg_keys) :], strict=True)) return args, kwargs def _ckpt_forward(self, forward_method, *args, **kwargs): flat_args, kwarg_keys = self._pack_kwargs(*args, **kwargs) def my_function(*inputs): # unpack back into args and kwargs nonlocal forward_method, kwarg_keys unpacked_args, unpacked_kwargs = self._unpack_kwargs(inputs, kwarg_keys) # run original module return forward_method(*unpacked_args, **unpacked_kwargs) return self.checkpoint_fn( my_function, *flat_args, ) def forward(self, module, forward_method, *args, **kwargs): if not module.training: return forward_method(*args, **kwargs) if not self._enable_ckpt: ret = forward_method(*args, **kwargs) else: ret = self._ckpt_forward(forward_method, *args, **kwargs) binded_tensor = ret if isinstance(ret, tuple): binded_tensor = ret[0] binded_tensor = self._sync_func(binded_tensor) final_ret = binded_tensor if isinstance(ret, tuple): final_ret = (final_ret,) + ret[1:] return final_ret def wrap_module_forward_method(self, module): orig_method = module.forward handler = self @functools.wraps(orig_method) def wrapped_method(model_self, *args, **kwargs): nonlocal handler handler.pre_forward(model_self) out = handler.forward(model_self, orig_method, *args, **kwargs) handler.post_forward(model_self) return out module.forward = wrapped_method.__get__(module, type(module)) def enable_activation_offloading(model, strategy, enable_ckpt=False): """ Enable activation offloading for the model. It groups activations by TransformerLayer and offloads activation groups asynchronously. This means that the offloading of the i-th activation group and the computation of the i+1-th activation group happen at the same time, and there are at most two activation groups in GPU memory. Args: model: the model to enable activation offloading strategy: the training strategy of the model, such as "fsdp" enable_ckpt: whether activation checkpointing(also called gradient checkpointing) has been enabled for the model Note: For best efficiency, activation offloading is usually combined with activation checkpointing. However, this implementation of activation offloading is conflicted with the implementation of activation checkpointing in some training strategies. This function resolves this conflict, and therefore requires the "strategy" and "enable_ckpt" arguments. Returns: """ assert strategy == "fsdp" or strategy == "fsdp2", "activation offloading only supports fsdp strategy" layers = [] def get_layers(module): for name, child in module.named_children(): if not isinstance(child, FSDP | FSDP2): get_layers(child) else: wrapped_module = child if isinstance(child, FSDP): wrapped_module = child._fsdp_wrapped_module # In some cases, torch.nn.Embedding is wrapped with FSDP alone. However, the activation # size of torch.nn.Embedding is small, so it's not necessary to offload it. if not isinstance(wrapped_module, torch.nn.Embedding): layers.append(child) get_layers(model) if len(layers) < 3: logger.warning(f"Find only {len(layers)} fsdp layers, not necessary to enable async activation offloading") return tensor_filter = FSDPParameterFilter() context, sync_func = get_activation_offload_context(len(layers) - 1, len(layers), tensor_filter) if enable_ckpt: # The implementation of activation checkpointing in transformers library is incompatible with # activation offloading, # so it will be disabled, but this implementation supports another version of activation checkpointing, so that # these two features can be enabled at the same time. for module in model.modules(): if hasattr(module, "gradient_checkpointing_disable"): module.gradient_checkpointing_disable() handler = ActivationHandler(context, sync_func, tensor_filter, enable_ckpt) for layer in layers: module = layer if isinstance(layer, FSDP): module = module._fsdp_wrapped_module handler.wrap_module_forward_method(module)
verl__utils__activation_offload.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Callable _index_first_axis, _pad_input, _rearrange, _unpad_input = None, None, None, None def _get_attention_functions() -> tuple[Callable, Callable, Callable, Callable]: """Dynamically import attention functions based on available hardware.""" from verl.utils.device import is_torch_npu_available global _index_first_axis, _pad_input, _rearrange, _unpad_input if is_torch_npu_available(check_device=False): from verl.utils.npu_flash_attn_utils import index_first_axis, pad_input, rearrange, unpad_input else: from flash_attn.bert_padding import index_first_axis, pad_input, rearrange, unpad_input _index_first_axis, _pad_input, _rearrange, _unpad_input = index_first_axis, pad_input, rearrange, unpad_input return _index_first_axis, _pad_input, _rearrange, _unpad_input def index_first_axis(*args, **kwargs): """ Unified entry point for `index_first_axis` across CUDA and NPU backends. Dynamically dispatches to the appropriate device-specific implementation: - On CUDA: `flash_attn.bert_padding.index_first_axis` - On NPU: `transformers.integrations.npu_flash_attention.index_first_axis` (falls back to `transformers.modeling_flash_attention_utils._index_first_axis` in newer versions of transformers). Users can call this function directly without worrying about the underlying device. """ func, *_ = _get_attention_functions() return func(*args, **kwargs) def pad_input(*args, **kwargs): """ Unified entry point for `pad_input` across CUDA and NPU backends. Dynamically dispatches to the appropriate device-specific implementation: - On CUDA: `flash_attn.bert_padding.pad_input` - On NPU: `transformers.integrations.npu_flash_attention.pad_input` (falls back to `transformers.modeling_flash_attention_utils._pad_input` in newer versions of transformers). Users can call this function directly without worrying about the underlying device. """ _, func, *_ = _get_attention_functions() return func(*args, **kwargs) def rearrange(*args, **kwargs): """ Unified entry point for `rearrange` across CUDA and NPU backends. Dynamically dispatches to the appropriate device-specific implementation: - On CUDA: `flash_attn.bert_padding.rearrange` - On NPU: `transformers.integrations.npu_flash_attention.rearrange` (falls back to `einops.rearrange` if no dedicated NPU implementation exists). Users can call this function directly without worrying about the underlying device. """ *_, func, _ = _get_attention_functions() return func(*args, **kwargs) def unpad_input(*args, **kwargs): """ Unified entry point for `unpad_input` across CUDA and NPU backends. Dynamically dispatches to the appropriate device-specific implementation: - On CUDA: `flash_attn.bert_padding.unpad_input` - On NPU: `transformers.integrations.npu_flash_attention.unpad_input` (falls back to `transformers.modeling_flash_attention_utils._unpad_input` in newer versions of transformers). Users can call this function directly without worrying about the underlying device. """ *_, func = _get_attention_functions() return func(*args, **kwargs) __all__ = ["index_first_axis", "pad_input", "rearrange", "unpad_input"]
verl__utils__attention_utils.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates import logging import os logger = logging.getLogger(__name__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) def initialize_system_prompt(tokenizer, **apply_chat_template_kwargs) -> list[int]: """ Initialize system prompt tokens for chat templates that support them. Args: tokenizer: The tokenizer with a chat template **apply_chat_template_kwargs: Additional arguments for apply_chat_template Returns: List of token IDs for the system prompt, or empty list if not supported """ token1 = tokenizer.apply_chat_template( [{"role": "user", "content": ""}], add_generation_prompt=False, tokenize=True ) token2 = tokenizer.apply_chat_template( [{"role": "user", "content": ""}] * 2, add_generation_prompt=False, tokenize=True ) # get system prompt tokens system_prompt = token1[: -(len(token2) - len(token1))] return system_prompt def extract_system_prompt_and_generation(tokenizer): token1 = tokenizer.apply_chat_template( [{"role": "user", "content": ""}], add_generation_prompt=False, tokenize=True ) token2 = tokenizer.apply_chat_template( [{"role": "user", "content": ""}] * 2, add_generation_prompt=False, tokenize=True ) # get system prompt tokens system_prompt = token1[: -(len(token2) - len(token1))] # get generate prompt tokens token3 = tokenizer.apply_chat_template([{"role": "user", "content": ""}], add_generation_prompt=True, tokenize=True) generate_prompt = token3[len(token1) :] return system_prompt, generate_prompt
verl__utils__chat_template.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TODO: add unit tests import logging import os import re from enum import Enum import torch import verl.utils.hdfs_io as hdfs_io from verl.single_controller import WorkerGroup from verl.utils.checkpoint.checkpoint_manager import find_latest_ckpt_path, get_checkpoint_tracker_filename from verl.utils.logger import log_with_rank from verl.workers.engine import BaseEngine def extract_step(path): match = re.search(r"global_step_(\d+)", path) if match: return int(match.group(1)) return None logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_SFT_LOGGING_LEVEL", "WARN")) class OrchestrationMode(Enum): SPMD = 0 RAY = 1 class CheckpointHandler: """ Checkpoint handler handles the path, global_step of a checkpoint folder. Currently, it only works with a single model. We can expand it to support multiple models. It is expected to be used with SPMD style (e.g., torchrun) """ def __init__( self, engine: BaseEngine | WorkerGroup, train_dataloader, *, default_local_dir, max_ckpt_to_keep=None, default_hdfs_dir=None, resume_mode="auto", resume_from_path=None, mode=OrchestrationMode.SPMD, ): self.default_local_dir = default_local_dir self.max_ckpt_to_keep = max_ckpt_to_keep self.default_hdfs_dir = default_hdfs_dir self.resume_mode = resume_mode self.resume_from_path = resume_from_path self.engine = engine self.train_dataloader = train_dataloader self.mode = mode if self.mode == OrchestrationMode.SPMD: self.rank = torch.distributed.get_rank() self.is_mp_src_rank_with_outputs = self.engine.is_mp_src_rank_with_outputs() self.dp_rank = self.engine.get_data_parallel_rank() elif self.mode == OrchestrationMode.RAY: self.rank = 0 self.is_mp_src_rank_with_outputs = True self.dp_rank = 0 else: raise ValueError(f"Unknown {self.mode=}") def save_checkpoint(self, step): """Save checkpoint using FSDPCheckpointManager with improved tracking""" from verl.utils.fs import local_mkdir_safe # Determine checkpoint path local_global_step_folder = os.path.join(self.default_local_dir, f"global_step_{step}") if self.rank == 0: print(f"Saving checkpoint to: {local_global_step_folder}") # Get max checkpoints to keep max_ckpt_to_keep = self.max_ckpt_to_keep # Use checkpoint manager to save self.engine.save_checkpoint( local_path=local_global_step_folder, global_step=step, max_ckpt_to_keep=max_ckpt_to_keep ) # Save dataloader state. Note that we only save the iterator in the train_dataloader. # So it's identical in each dp rank. if self.is_mp_src_rank_with_outputs: dp_rank = self.dp_rank local_mkdir_safe(local_global_step_folder) dataloader_local_path = os.path.join(local_global_step_folder, f"data_{dp_rank}.pt") # Use StatefulDataLoader's built-in state dict functionality dataloader_state_dict = self.train_dataloader.state_dict() torch.save(dataloader_state_dict, dataloader_local_path) print(f"Saved dataloader state to: {dataloader_local_path}") if self.rank == 0: # Update latest checkpoint tracker (atomic write) tracker_file = get_checkpoint_tracker_filename(self.default_local_dir) temp_tracker_file = tracker_file + ".tmp" with open(temp_tracker_file, "w") as f: f.write(str(step)) os.rename(temp_tracker_file, tracker_file) print(f"Updated checkpoint tracker: {tracker_file}") # Copy to HDFS if configured if self.rank == 0 and self.default_hdfs_dir: hdfs_io.makedirs(self.default_hdfs_dir, exist_ok=True) hdfs_io.copy(src=local_global_step_folder, dst=self.default_hdfs_dir, dirs_exist_ok=True) if self.mode == OrchestrationMode.SPMD: torch.distributed.barrier() def load_checkpoint(self): # Determine resume path based on configuration checkpoint_path = self._determine_resume_path() if checkpoint_path is None: return 0 # extract resume step from checkpoint path resume_step = extract_step(checkpoint_path) if resume_step is None: log_with_rank( f"Warning: Could not extract step number from {checkpoint_path}, starting from step 0", logger=logger, rank=self.rank, level=logging.WARNING, log_only_rank_0=True, ) return 0 self.resume_global_step = resume_step # Use checkpoint manager to load model state self.engine.load_checkpoint(checkpoint_path) # Always load dataloader state for StatefulDataLoader self._load_dataloader_state(checkpoint_path) return resume_step def _load_dataloader_state(self, checkpoint_path: str): """Load dataloader state from checkpoint""" dp_rank = self.dp_rank dataloader_path = os.path.join(checkpoint_path, f"data_{dp_rank}.pt") if os.path.exists(dataloader_path): # Use StatefulDataLoader's built-in state dict functionality dataloader_state_dict = torch.load(dataloader_path, map_location="cpu", weights_only=False) self.train_dataloader.load_state_dict(dataloader_state_dict) log_with_rank( f"Successfully loaded dataloader state from {dataloader_path}", logger=logger, rank=self.rank, log_only_rank_0=True, ) else: log_with_rank( f"Warning: No dataloader state found at {dataloader_path}, will start from scratch", logger=logger, rank=self.rank, level=logging.WARNING, log_only_rank_0=True, ) def _determine_resume_path(self): """Determine the path to resume from based on resume_mode configuration""" resume_mode = self.resume_mode resume_from_path = self.resume_from_path if resume_mode == "disable": return None elif resume_mode == "auto": if resume_from_path is not None: assert os.path.exists(resume_from_path), ( "resume_from_path must be null or an existing path when resume_mode is 'auto'" ) assert "global_step_" in resume_from_path, "resume_from_path must specify the global_steps" return resume_from_path # Try to find the latest checkpoint in the default directory return self._find_latest_checkpoint() elif resume_mode == "resume_path": assert os.path.exists(resume_from_path), ( "resume_from_path must be an existing path when resume_mode is 'resume_path'" ) assert "global_step_" in resume_from_path, "resume_from_path must specify the global_steps" return resume_from_path else: raise ValueError(f"Invalid resume_mode: {resume_mode}. Must be 'auto', 'disable', or 'resume_path'") def _find_latest_checkpoint(self): """Find the latest checkpoint in the default local directory""" checkpoint_dir = self.default_local_dir if not os.path.exists(checkpoint_dir): return None latest_checkpoint = find_latest_ckpt_path(checkpoint_dir) if latest_checkpoint and self.rank == 0: step_num = extract_step(latest_checkpoint) print(f"Found latest checkpoint: {latest_checkpoint} (step {step_num})") return latest_checkpoint
verl__utils__checkpoint__checkpoint_handler.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import random import shutil import numpy as np import torch import torch.distributed from omegaconf import DictConfig from transformers import PreTrainedTokenizer, ProcessorMixin from verl.trainer.config import CheckpointConfig from verl.utils.device import get_device_name, get_torch_device class BaseCheckpointManager: """ A checkpoint manager that saves and loads the following states in a SPMD way: - model - optimizer - lr_scheduler - extra_states We save - sharded model states and optimizer states - full lr_scheduler states - huggingface tokenizer and config for ckpt merge """ def __init__( self, model, optimizer: torch.optim.Optimizer, lr_scheduler: torch.optim.lr_scheduler.LRScheduler = None, processing_class: PreTrainedTokenizer | ProcessorMixin = None, checkpoint_config: DictConfig | CheckpointConfig = None, ): self.checkpoint_config = checkpoint_config checkpoint_load_contents = checkpoint_config.get("load_contents", None) if checkpoint_config else None checkpoint_save_contents = checkpoint_config.get("save_contents", None) if checkpoint_config else None if checkpoint_load_contents is None: checkpoint_load_contents = ["model", "optimizer", "extra"] if checkpoint_save_contents is None: checkpoint_save_contents = ["model", "optimizer", "extra"] self.previous_global_step = None self.previous_saved_paths = [] self.model = model self.optimizer = optimizer self.lr_scheduler = lr_scheduler self.processing_class = processing_class self.checkpoint_load_contents = checkpoint_load_contents self.checkpoint_save_contents = checkpoint_save_contents self.rank = torch.distributed.get_rank() self.world_size = torch.distributed.get_world_size() @property def should_save_model(self) -> bool: """ Returns True if 'model' is in checkpoint_save_contents, indicating the model state should be saved. """ return "model" in self.checkpoint_save_contents @property def should_save_optimizer(self) -> bool: """ Returns True if 'optimizer' is in checkpoint_save_contents, indicating the optimizer state should be saved. """ return "optimizer" in self.checkpoint_save_contents @property def should_save_extra(self) -> bool: """ Returns True if 'extra' is in checkpoint_save_contents, indicating the extra state should be saved. """ return "extra" in self.checkpoint_save_contents @property def should_save_hf_model(self) -> bool: """ Returns True if 'hf_model' is in checkpoint_save_contents, indicating the model should be converted to hf model and saved. """ return "hf_model" in self.checkpoint_save_contents @property def should_load_model(self) -> bool: """ Returns True if 'model' is in checkpoint_load_contents, indicating the model state should be loaded. """ return "model" in self.checkpoint_load_contents @property def should_load_optimizer(self) -> bool: """ Returns True if 'optimizer' is in checkpoint_load_contents, indicating the optimizer state should be loaded. """ return "optimizer" in self.checkpoint_load_contents @property def should_load_extra(self) -> bool: """ Returns True if 'extra' is in checkpoint_load_contents, indicating the extra state should be loaded. """ return "extra" in self.checkpoint_load_contents def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load: bool = False): raise NotImplementedError def save_checkpoint( self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep: int = None ): raise NotImplementedError @staticmethod def checkpath(local_path: str, hdfs_path: str): assert local_path is not None or hdfs_path is not None, "local_path and hdfs_path cannot be both None" return local_path is not None, local_path if local_path is not None else hdfs_path def remove_previous_save_local_path(self, path): if isinstance(path, str): path = [path] for p in path: abs_path = os.path.abspath(p) print(f"Checkpoint manager remove previous save local path: {abs_path}") if not os.path.exists(abs_path): continue shutil.rmtree(abs_path, ignore_errors=True) def ensure_checkpoint_capacity(self, max_ckpt_to_keep: int): """ Remove old checkpoints to make room for a new one, keeping a safety buffer. With max_ckpt_to_keep=1, this does nothing - we keep the existing checkpoint until the new save completes successfully (handled by register_checkpoint). For max_ckpt_to_keep >= 2, we keep (max_ckpt_to_keep - 1) checkpoints before save. """ if not (max_ckpt_to_keep and isinstance(max_ckpt_to_keep, int) and max_ckpt_to_keep > 1): return if len(self.previous_saved_paths) >= max_ckpt_to_keep: keep_start = len(self.previous_saved_paths) - max_ckpt_to_keep + 1 self.remove_previous_save_local_path(self.previous_saved_paths[:keep_start]) self.previous_saved_paths = self.previous_saved_paths[keep_start:] def register_checkpoint(self, new_path: str, max_ckpt_to_keep: int): """ Register a successfully saved checkpoint and enforce retention limit. Adds the new checkpoint path to tracking and removes excess old checkpoints beyond max_ckpt_to_keep. """ self.previous_saved_paths.append(new_path) if not (max_ckpt_to_keep and isinstance(max_ckpt_to_keep, int) and max_ckpt_to_keep > 0): return if len(self.previous_saved_paths) > max_ckpt_to_keep: keep_start = len(self.previous_saved_paths) - max_ckpt_to_keep self.remove_previous_save_local_path(self.previous_saved_paths[:keep_start]) self.previous_saved_paths = self.previous_saved_paths[keep_start:] @staticmethod def get_rng_state(): rng_state = { "cpu": torch.get_rng_state(), "numpy": np.random.get_state(), "random": random.getstate(), } if get_device_name() != "cpu": rng_state[get_device_name()] = get_torch_device().get_rng_state() return rng_state @staticmethod def load_rng_state(rng_state): torch.set_rng_state(rng_state["cpu"]) np.random.set_state(rng_state["numpy"]) random.setstate(rng_state["random"]) if get_device_name() != "cpu": get_torch_device().set_rng_state(rng_state[get_device_name()]) def find_latest_ckpt_path(path, directory_format="global_step_{}"): """ Return the most recent checkpoint directory based on a tracker file. Args: path (str): Base directory containing the checkpoint tracker. directory_format (str): Template for checkpoint subfolders with one placeholder for the iteration number (default "global_step_{}"). Returns: str or None: Full path to the latest checkpoint directory, or None if the tracker or checkpoint folder is missing. """ if path is None: return None tracker_file = get_checkpoint_tracker_filename(path) if not os.path.exists(tracker_file): if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0: print(f"Checkpoint tracker file does not exist: {tracker_file}") return None with open(tracker_file, "rb") as f: iteration = int(f.read().decode()) ckpt_path = os.path.join(path, directory_format.format(iteration)) if not os.path.exists(ckpt_path): print("Checkpoint does not exist: %s", ckpt_path) return None print("Found checkpoint: %s", ckpt_path) return ckpt_path def get_checkpoint_tracker_filename(root_path: str): """ Tracker file rescords the latest chckpoint during training to restart from. """ return os.path.join(root_path, "latest_checkpointed_iteration.txt") def should_save_ckpt_esi(max_steps_duration: float, save_ckpt_duration: float = 60, redundant_time: float = 0) -> bool: """ Determine if checkpoint should be saved based on capacity esi expiration. Args: max_steps_duration: Max estimated time (seconds) required to complete one training step save_ckpt_duration: Estimated time (seconds) required to save checkpoint (default: 60) redundant_time: Additional buffer time (seconds) for unexpected delays (default: 0) """ exp_ts_mlp = os.getenv("MLP_CURRENT_CAPACITY_BLOCK_EXPIRATION_TIMESTAMP") # vemlp exp_ts_aws = os.getenv("SAGEMAKER_CURRENT_CAPACITY_BLOCK_EXPIRATION_TIMESTAMP") # aws if exp_ts_mlp: try: import time remaining = float(exp_ts_mlp) - time.time() except ValueError: return False return ( remaining > 0 and max_steps_duration > 0 and remaining <= save_ckpt_duration + max_steps_duration + redundant_time ) elif exp_ts_aws: from datetime import datetime, timedelta expiration_time = datetime.fromtimestamp(int(exp_ts_aws)) time_difference = expiration_time - datetime.now() threshold_minutes = (save_ckpt_duration + max_steps_duration + redundant_time) / 60 return time_difference < timedelta(minutes=threshold_minutes) else: return False
verl__utils__checkpoint__checkpoint_manager.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging import os import warnings from dataclasses import asdict, dataclass from typing import Optional import torch import torch.distributed from accelerate import init_empty_weights from omegaconf import DictConfig from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictType from transformers import GenerationConfig, PreTrainedTokenizer, ProcessorMixin from transformers.dynamic_module_utils import custom_object_save from verl.utils.device import is_cuda_available from verl.utils.fs import copy_to_local, is_non_local, local_mkdir_safe from verl.utils.fsdp_utils import fsdp_version, get_fsdp_full_state_dict, get_fsdp_state_ctx from verl.utils.logger import log_with_rank from .checkpoint_manager import BaseCheckpointManager # Setup logging logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO")) @dataclass class FSDPConfig: """Configuration for FSDP checkpointing. Args: FSDP_version (int): Version of FSDP being used. world_size (int): Number of processes in the distributed training setup. """ FSDP_version: int world_size: int class FSDPCheckpointManager(BaseCheckpointManager): """ Manage FSDP checkpointing in SPMD training. - Saves/loads per-rank sharded model & optimizer states - Persists full lr_scheduler and RNG state - Stores HF tokenizer/processor and model/config for unified restore Args: model (FSDP): Wrapped model instance. optimizer (Optimizer): Training optimizer. lr_scheduler (LRScheduler): Learning-rate scheduler. processing_class (PreTrainedTokenizer or ProcessorMixin, optional): Pre-/post-processing artifact handler. checkpoint_contents DictConfig: Configuration for checkpoint contents. - 'load': Components to load; must contain 'model'. Defaults to ['model', 'optimizer', 'extra']. - 'save': Components to save; must contain 'model'. Defaults to ['model', 'optimizer', 'extra']. trust_remote_code: Whether to trust_remote_code when loading the model configuration """ def __init__( self, model: FSDP, optimizer: Optional[torch.optim.Optimizer] = None, lr_scheduler: Optional[torch.optim.lr_scheduler.LRScheduler] = None, processing_class: PreTrainedTokenizer | ProcessorMixin = None, checkpoint_config: DictConfig = None, trust_remote_code: bool = False, **kwargs, ): if processing_class is None and "tokenizer" in kwargs: warnings.warn( "`tokenizer` is deprecated. use `processing_class` instead.", DeprecationWarning, stacklevel=2 ) processing_class = kwargs.pop("tokenizer") super().__init__( model, optimizer, lr_scheduler=lr_scheduler, processing_class=processing_class, checkpoint_config=checkpoint_config, ) self.trust_remote_code = trust_remote_code def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load=False): """ Load an FSDP checkpoint for this rank. Downloads and loads: - model and optimizer shards - extra state dict (scheduler + RNG) Args: local_path: Directory with per-rank checkpoint files. hdfs_path: Unused (for API compatibility). del_local_after_load: Remove local files after loading. """ if local_path is None: return # check if the checkpoint_load_contents is valid if self.should_load_model: assert self.model is not None, "model must be provided when checkpoint_contents.load includes ['model']" if self.should_load_optimizer: assert self.optimizer is not None, ( "optimizer must be provided when checkpoint_contents.load includes ['optimizer']" ) # every rank download its own checkpoint state_dict_cfg = ( ShardedStateDictConfig(offload_to_cpu=True if is_cuda_available else False) if self.should_load_model else None ) optim_cfg = ( ShardedOptimStateDictConfig(offload_to_cpu=True if is_cuda_available else False) if self.should_load_optimizer else None ) with get_fsdp_state_ctx(self.model, StateDictType.SHARDED_STATE_DICT, state_dict_cfg, optim_cfg): if self.should_load_model: remote_model_path = os.path.join(local_path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt") local_model_path = copy_to_local(remote_model_path) model_state_dict = torch.load(local_model_path, weights_only=False) self.model.load_state_dict(model_state_dict) log_with_rank(f"Loaded model from {remote_model_path}", rank=self.rank, logger=logger) if self.should_load_optimizer: remote_optim_path = os.path.join(local_path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt") local_optim_path = copy_to_local(remote_optim_path) optimizer_state_dict = torch.load(local_optim_path, weights_only=False) self.optimizer.load_state_dict(optimizer_state_dict) log_with_rank(f"Loaded optimizer from {remote_optim_path}", rank=self.rank, logger=logger) if self.should_load_extra: remote_extra_state_path = os.path.join( local_path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt" ) local_extra_state_path = copy_to_local(remote_extra_state_path) extra_state_dict = torch.load(local_extra_state_path, weights_only=False) # recover random state if "rng" in extra_state_dict: # 'rng' may not exist for backward compatibility self.load_rng_state(extra_state_dict["rng"]) log_with_rank(f"Loaded rng from {remote_extra_state_path}", rank=self.rank, logger=logger) lr_scheduler_state_dict = extra_state_dict["lr_scheduler"] if lr_scheduler_state_dict is not None and self.lr_scheduler is not None: self.lr_scheduler.load_state_dict(lr_scheduler_state_dict) log_with_rank(f"Loaded lr_scheduler from {remote_extra_state_path}", rank=self.rank, logger=logger) if self.rank == 0 and del_local_after_load: try: os.remove(local_model_path) if is_non_local(local_model_path) else None os.remove(local_optim_path) if is_non_local(local_optim_path) else None os.remove(local_extra_state_path) if is_non_local(local_extra_state_path) else None except Exception as e: log_with_rank( f"remove local resume ckpt file after loading failed, exception {e} will be ignored", rank=self.rank, logger=logger, ) # wait for everyone to load checkpoints torch.distributed.barrier() def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep=None): """ Save an FSDP checkpoint for this rank. Writes: - model & optimizer shard files - extra state dict (scheduler + RNG) - HF tokenizer/processor and model/config on rank 0 - optional full HF model under 'huggingface/' if requested Rotates old checkpoints, keeping at most `max_ckpt_to_keep`. Args: local_path: Target directory for checkpoint files. hdfs_path: Unused (for API compatibility). global_step: Current training step (used for bookkeeping). max_ckpt_to_keep: Number of recent checkpoints to retain. """ if local_path is None: return # record the previous global step self.previous_global_step = global_step if self.rank == 0: self.ensure_checkpoint_capacity(max_ckpt_to_keep) local_path = local_mkdir_safe(local_path) torch.distributed.barrier() # check if the checkpoint_save_contents is valid if self.should_save_model: assert self.model is not None, "model must be provided when checkpoint_contents.save includes ['model']" if self.should_save_optimizer: assert self.optimizer is not None, ( "optimizer must be provided when checkpoint_contents.save includes ['optimizer']" ) # every rank will save its own model and optim shard state_dict_cfg = ShardedStateDictConfig(offload_to_cpu=True if is_cuda_available else False) optim_cfg = ShardedOptimStateDictConfig(offload_to_cpu=True if is_cuda_available else False) with warnings.catch_warnings(): warnings.simplefilter("ignore") with get_fsdp_state_ctx(self.model, StateDictType.SHARDED_STATE_DICT, state_dict_cfg, optim_cfg): model_path = os.path.join(local_path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt") optim_path = os.path.join(local_path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt") extra_path = os.path.join(local_path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt") if self.should_save_model: model_state_dict = self.model.state_dict() torch.save(model_state_dict, model_path) log_with_rank(f"Saved model to {os.path.abspath(model_path)}", rank=self.rank, logger=logger) if self.should_save_optimizer: optimizer_state_dict = self.optimizer.state_dict() torch.save(optimizer_state_dict, optim_path) log_with_rank(f"Saved optim to {os.path.abspath(optim_path)}", rank=self.rank, logger=logger) if self.should_save_extra: lr_scheduler_state_dict = self.lr_scheduler.state_dict() if self.lr_scheduler is not None else None extra_state_dict = { "lr_scheduler": lr_scheduler_state_dict, "rng": self.get_rng_state(), } torch.save(extra_state_dict, extra_path) log_with_rank(f"Saved extra_state to {os.path.abspath(extra_path)}", rank=self.rank, logger=logger) if self.rank == 0: # Save HF tokenizer/processor and model config on rank 0 to huggingface/ directory, no matter whether # huggingface model is requested to be saved or not. if fsdp_version(self.model) == 1: unwrap_model = self.model._fsdp_wrapped_module else: unwrap_model = self.model hf_config_tokenizer_path = os.path.join(local_path, "huggingface") local_mkdir_safe(hf_config_tokenizer_path) model_config = unwrap_model.config generation_config = None if unwrap_model.can_generate() and hasattr(model_config, "name_or_path") and model_config.name_or_path: try: # Some model's name_or_path is empty if not initialized from pretrained, # in this cases, we don't save generation config. generation_config = GenerationConfig.from_pretrained(model_config.name_or_path) generation_config.save_pretrained(hf_config_tokenizer_path) except Exception: # if the generation config isn't available, we don't save it pass if hasattr(model_config, "auto_map") and None in model_config.auto_map: model_config.auto_map = {k: v for k, v in model_config.auto_map.items() if k is not None} model_config.save_pretrained(hf_config_tokenizer_path) if self.processing_class is not None: self.processing_class.save_pretrained(hf_config_tokenizer_path) log_with_rank( f"Saved model config and tokenizer class to {os.path.abspath(hf_config_tokenizer_path)}", rank=self.rank, logger=logger, log_only_rank_0=True, ) # If we have a custom model, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if hasattr(model_config, "auto_map"): custom_object_save(unwrap_model, hf_config_tokenizer_path, config=model_config) # Also save runtime FSDP config fsdp_config_path = os.path.join(local_path, "fsdp_config.json") fsdp_config = FSDPConfig( FSDP_version=fsdp_version(self.model), world_size=self.world_size, ) with open(fsdp_config_path, "w") as f: json.dump(asdict(fsdp_config), f, indent=4) # wait for everyone to dump to local torch.distributed.barrier() if self.should_save_hf_model: # Only rank 0 will save hf model and, # offload to cpu to save LLMs which may be too large to fit in one GPU state_dict = get_fsdp_full_state_dict(self.model, offload_to_cpu=True, rank0_only=True) if self.rank == 0: hf_local_path = os.path.join(local_path, "huggingface") os.makedirs(hf_local_path, exist_ok=True) if "ForTokenClassification" in model_config.architectures[0]: from transformers import AutoModelForTokenClassification auto_model_cls = AutoModelForTokenClassification elif "ForCausalLM" in model_config.architectures[0]: from transformers import AutoModelForCausalLM auto_model_cls = AutoModelForCausalLM elif "ForConditionalGeneration" in model_config.architectures[0]: # Handle different transformers versions for Vision2Seq models import transformers from packaging import version if version.parse(transformers.__version__) >= version.parse("4.54.0"): # transformers >= 4.54.0 uses AutoModelForImageTextToText from transformers import AutoModelForImageTextToText auto_model_cls = AutoModelForImageTextToText else: # transformers < 4.54.0 uses AutoModelForVision2Seq from transformers import AutoModelForVision2Seq auto_model_cls = AutoModelForVision2Seq else: raise NotImplementedError(f"Unknown architecture {model_config['architectures']}") with init_empty_weights(): save_model = auto_model_cls.from_config( model_config, torch_dtype=torch.bfloat16, trust_remote_code=self.trust_remote_code ) save_model.to_empty(device="cpu") if save_model.can_generate(): if generation_config is not None: save_model.generation_config = generation_config else: print( f"Warning: {self.__class__.__name__}.save_checkpoint: Generation config file not found " f"in, using a generation config created from the model config when saving hf_model." ) save_model.save_pretrained(hf_local_path, state_dict=state_dict) log_with_rank( f"Saved hf_model to {os.path.abspath(hf_local_path)}", rank=self.rank, logger=logger, log_only_rank_0=True, ) del state_dict del save_model # wait for rank0 to dump hf_model to local torch.distributed.barrier() if self.rank == 0: self.register_checkpoint(local_path, max_ckpt_to_keep)
verl__utils__checkpoint__fsdp_checkpoint_manager.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import json import logging import os import random from collections.abc import Callable from dataclasses import asdict import megatron.core import numpy as np import torch import torch.distributed from megatron.core import dist_checkpointing, mpu, tensor_parallel from megatron.core.dist_checkpointing.mapping import ShardedObject from megatron.core.transformer.enums import AttnBackend from packaging import version from transformers import GenerationConfig from verl.models.weight_loader_registry import get_weight_saver from verl.utils.device import get_device_name, get_torch_device from verl.utils.fs import is_non_local, local_mkdir_safe from verl.utils.logger import log_with_rank from verl.utils.megatron.dist_checkpointing import load_dist_checkpointing, save_dist_checkpointing from verl.utils.megatron_utils import ( get_dist_checkpoint_path, get_hf_model_checkpoint_path, get_transformer_config_checkpoint_path, ) from .checkpoint_manager import BaseCheckpointManager # Setup logging logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO")) mcore_ge_014 = version.parse(megatron.core.__version__) >= version.parse("0.14.0") if not mcore_ge_014: logger.warning( "Detected megatron.core %s, recommend upgrading to >= 0.14.0 for better checkpoint compatibility", megatron.core.__version__, ) class MegatronCheckpointManager(BaseCheckpointManager): """ Checkpoint manager for Megatron-LM distributed training. This class manages the saving and loading of model checkpoints in a Megatron-LM distributed training environment. It handles various aspects of checkpointing including model states, optimizer states, learning rate schedulers, and random number generator states, ensuring compatibility with HuggingFace formats. Key features: - Distributed checkpoint saving and loading using Megatron's dist_checkpointing - Support for tensor parallel, pipeline parallel, and data parallel configurations - Automatic handling of model state dictionaries across multiple pipeline stages - Integration with HuggingFace model configurations and tokenizers - Random number generator state management for reproducibility - Support for both synchronous and asynchronous checkpoint operations The manager automatically handles: - Directory structure creation based on global steps and process ranks - Model configuration and tokenizer saving in HuggingFace format - Optimizer and scheduler state persistence - CUDA RNG state management for deterministic training - Checkpoint cleanup and retention policies Args: model: The Megatron model instance to checkpoint optimizer: The optimizer instance (optional) lr_scheduler: The learning rate scheduler instance (optional) Attributes: model: Reference to the Megatron model being checkpointed optimizer: Reference to the optimizer (if provided) lr_scheduler: Reference to the learning rate scheduler (if provided) rank: Current process rank in the distributed setup Example: ```python checkpoint_manager = MegatronCheckpointManager( model=megatron_model, optimizer=optimizer, lr_scheduler=scheduler ) checkpoint_manager.save_checkpoint( local_path="checkpoints/step_1000", global_step=1000 ) checkpoint_manager.load_checkpoint( local_path="checkpoints/step_1000" ) ``` """ def __init__( self, config, checkpoint_config, model_config, transformer_config, role, model: torch.nn.ModuleList, arch: str, hf_config, param_dtype: torch.dtype, share_embeddings_and_output_weights: bool, processing_class, optimizer, optimizer_scheduler, use_distributed_optimizer: bool, use_checkpoint_opt_param_scheduler: bool = False, use_dist_checkpointing: bool = True, bridge=None, provider=None, peft_cls=None, **kwargs, ): super().__init__( model, optimizer=optimizer, lr_scheduler=optimizer_scheduler, processing_class=processing_class, checkpoint_config=checkpoint_config, ) self.arch = arch self.config = config self.transformer_config = transformer_config self.role = role self.is_value_model = False if self.role in ["reward", "critic"]: self.is_value_model = True self.model_config = model_config self.hf_config = hf_config self.param_dtype = param_dtype self.share_embeddings_and_output_weights = share_embeddings_and_output_weights self.model_path = self.config.model.path self.use_distributed_optimizer = use_distributed_optimizer self.use_checkpoint_opt_param_scheduler = use_checkpoint_opt_param_scheduler self.bridge = bridge self.provider = provider self.vanilla_bridge = self.provider is None self.peft_cls = peft_cls self.rank = torch.distributed.get_rank() # Megatron-Bridge is Okay to load/save HF checkpoint for value model as well self.use_dist_checkpointing = ( use_dist_checkpointing or not self.bridge or (self.vanilla_bridge and self.is_value_model) ) self.use_hf_checkpoint = not self.use_dist_checkpointing self.weight_saver = None if self.bridge is None: self.weight_saver = get_weight_saver(self.arch) def get_rng_state(self, use_dist_ckpt: bool = True, data_parallel_random_init: bool = False): """collect rng state across data parallel ranks""" rng_state = { "random_rng_state": random.getstate(), "np_rng_state": np.random.get_state(), "torch_rng_state": torch.get_rng_state(), "rng_tracker_states": tensor_parallel.get_cuda_rng_tracker().get_states(), } if get_device_name() != "cpu": rng_state[f"{get_device_name()}_rng_state"] = get_torch_device().get_rng_state() rng_state_list = None if torch.distributed.is_initialized() and mpu.get_data_parallel_world_size() > 1 and data_parallel_random_init: rng_state_list = [None for i in range(mpu.get_data_parallel_world_size())] torch.distributed.all_gather_object(rng_state_list, rng_state, group=mpu.get_data_parallel_group()) else: rng_state_list = [rng_state] if use_dist_ckpt: pp_rank = mpu.get_pipeline_model_parallel_rank() pp_size = mpu.get_pipeline_model_parallel_world_size() tp_rank = mpu.get_tensor_model_parallel_rank() tp_size = mpu.get_tensor_model_parallel_world_size() rng_state_list = ShardedObject( "rng_state", rng_state_list, (pp_size, tp_size), (pp_rank, tp_rank), replica_id=mpu.get_data_parallel_rank(with_context_parallel=True), ) return rng_state_list def get_checkpoint_name( self, checkpoints_path, pipeline_parallel=None, tensor_rank=None, pipeline_rank=None, cp_rank=None, expert_parallel=None, expert_rank=None, return_base_dir=True, basename="model.pt", ): """Determine the directory name for this rank's checkpoint.""" # Use both the tensor and pipeline MP rank. if pipeline_parallel is None: pipeline_parallel = mpu.get_pipeline_model_parallel_world_size() > 1 if tensor_rank is None: tensor_rank = mpu.get_tensor_model_parallel_rank() if pipeline_rank is None: pipeline_rank = mpu.get_pipeline_model_parallel_rank() if cp_rank is None: cp_rank = mpu.get_context_parallel_rank() if expert_parallel is None: expert_parallel = mpu.get_expert_model_parallel_world_size() > 1 if expert_rank is None: expert_rank = mpu.get_expert_model_parallel_rank() # Use both the tensor and pipeline MP rank. If using the distributed # optimizer, then the optimizer's path must additionally include the # data parallel rank. # due to the fact that models are identical across cp ranks, cp rank is not used in the checkpoint path if not pipeline_parallel: common_path = os.path.join(checkpoints_path, f"mp_rank_{tensor_rank:02d}") else: common_path = os.path.join(checkpoints_path, f"mp_rank_{tensor_rank:02d}_{pipeline_rank:03d}") if expert_parallel: common_path = common_path + f"_{expert_rank:03d}" os.makedirs(common_path, exist_ok=True) if return_base_dir: return common_path return os.path.join(common_path, basename) def generate_state_dict( self, generate_model: bool = True, generate_optimizer: bool = True, generate_extra: bool = True, is_loading: bool = False, metadata: dict | None = None, ): # For save dist checkpointing state_dict = {} base_metadata = metadata or self._build_sharded_state_dict_metadata() # Should always generate model state dict # All ranks Save Model to reduce memory pressure # Get sharded state dict, notice that state_dict will collect among dp groups, causing memory pressure for vpp_rank, model in enumerate(self.model): if len(self.model) > 1: mpu.set_virtual_pipeline_model_parallel_rank(vpp_rank) key = f"model{vpp_rank}" if len(self.model) > 1 else "model" else: key = "model" if hasattr(model, "module"): model = model.module # GPTModel's sharded_state_dict function when having mtp requires metadata['dp_cp_group'] model_metadata = dict(base_metadata) model_metadata["dp_cp_group"] = mpu.get_data_parallel_group(with_context_parallel=True) kwargs = {"metadata": model_metadata} state_dict[key] = model.sharded_state_dict(**kwargs) # Optimizer State Dict if generate_optimizer: torch.distributed.barrier() sharded_state_dict_kwargs = {"is_loading": is_loading} if base_metadata is not None: # https://github.com/NVIDIA/Megatron-LM/blob/core_v0.14.0/megatron/core/optimizer/distrib_optimizer.py#L1109-L1123 if mcore_ge_014: sharded_state_dict_kwargs["metadata"] = base_metadata optimizer_sharded_states = self.optimizer.sharded_state_dict(state_dict, **sharded_state_dict_kwargs) state_dict["optimizer"] = optimizer_sharded_states if self.lr_scheduler is not None: lr_state_dict = self.lr_scheduler.state_dict() state_dict["lr_scheduler"] = lr_state_dict if not generate_model: state_dict.pop("model", None) # RNG States State Dict if generate_extra: torch.distributed.barrier() rng_state = self.get_rng_state() state_dict["rng_state"] = rng_state return state_dict def _build_sharded_state_dict_metadata(self) -> dict: """Builds metadata used for sharded_state_dict versioning. The whole content metadata is passed to ``sharded_state_dict`` model and optimizer methods and therefore affects only the logic behind sharded_state_dict creation. The content metadata should be minimalistic, ideally flat (or with a single nesting level) and with semantically meaningful flag names (e.g. `distrib_optim_sharding_type`). In particular, a simple integer (or SemVer) versioning flag (e.g. `metadata['version'] = 3.4`) is discouraged, because the metadata serves for all models and optimizers and it's practically impossible to enforce a linearly increasing versioning for this whole space. """ metadata: dict = {} if not mcore_ge_014: # For backward compatibility with Megatron core < v0.14.0 if self.use_distributed_optimizer: metadata["distrib_optim_sharding_type"] = "fully_sharded_model_space" return metadata if self.use_distributed_optimizer: megatron_config = getattr(self.config, self.role, self.config).megatron dist_ckpt_optim_fully_reshardable = megatron_config.dist_ckpt_optim_fully_reshardable distrib_optim_fully_reshardable_mem_efficient = ( megatron_config.distrib_optim_fully_reshardable_mem_efficient ) if dist_ckpt_optim_fully_reshardable: metadata["distrib_optim_sharding_type"] = "fully_reshardable" metadata["distrib_optim_fully_reshardable_mem_efficient"] = ( distrib_optim_fully_reshardable_mem_efficient ) else: metadata["distrib_optim_sharding_type"] = "dp_reshardable" metadata["singleton_local_shards"] = False metadata["chained_optim_avoid_prefix"] = True return metadata def load_rng_states(self, rng_states, data_parallel_random_init=False, use_dist_ckpt=True): # access rng_state for data parallel rank if data_parallel_random_init: rng_states = rng_states[mpu.get_data_parallel_rank()] else: rng_states = rng_states[0] random.setstate(rng_states["random_rng_state"]) np.random.set_state(rng_states["np_rng_state"]) torch.set_rng_state(rng_states["torch_rng_state"]) if get_device_name() != "cpu": get_torch_device().set_rng_state(rng_states[f"{get_device_name()}_rng_state"]) # Check for empty states array if not rng_states["rng_tracker_states"]: raise KeyError tensor_parallel.get_cuda_rng_tracker().set_states(rng_states["rng_tracker_states"]) def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load=False): if local_path is not None: assert os.path.exists(local_path), f"Checkpoint path {local_path} does not exist." # For load optimizer dist_ckpt try: import transformer_engine torch.serialization.add_safe_globals([torch.optim.AdamW]) torch.serialization.add_safe_globals([transformer_engine.pytorch.optimizers.fused_adam.FusedAdam]) except Exception: pass dist_checkpoint_path = get_dist_checkpoint_path(local_path) load_content_metadata = getattr(dist_checkpointing, "load_content_metadata", None) if load_content_metadata is None: # For backward compatibility sharded_sd_metadata = None else: sharded_sd_metadata = load_content_metadata(checkpoint_dir=dist_checkpoint_path) if sharded_sd_metadata is None: if self.use_distributed_optimizer: # Backward-compatibility with old checkpoints which don't have content versioning # Can be removed after ending support for MLM optimizer checkpoints with MCore < v0.13 # (for MCore v0.13+ checkpoints `sharded_sd_metadata is not None`) sharded_sd_metadata = { "distrib_optim_sharding_type": "fully_sharded_model_space", } else: sharded_sd_metadata = self._build_sharded_state_dict_metadata() # Get State Dict for loading sharded_state_dict = self.generate_state_dict( self.should_load_model and self.use_dist_checkpointing, self.should_load_optimizer, self.should_load_extra, is_loading=True, metadata=sharded_sd_metadata, ) log_with_rank(f"Generated state dict for loading: {sharded_state_dict.keys()}", rank=self.rank, logger=logger) # Load Dist Checkpointing state_dict = load_dist_checkpointing( sharded_state_dict=sharded_state_dict, ckpt_dir=dist_checkpoint_path, ) if self.should_load_model and self.use_dist_checkpointing: assert "model" in state_dict or any( f"model{vpp_rank}" in state_dict for vpp_rank in range(len(self.model)) ), f"Model state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}." for vpp_rank, model in enumerate(self.model): if len(self.model) == 1: model_state_dict = state_dict["model"] else: assert f"model{vpp_rank}" in state_dict, f"model{vpp_rank} not found in state_dict" model_state_dict = state_dict[f"model{vpp_rank}"] mpu.set_virtual_pipeline_model_parallel_rank(vpp_rank) self.model[vpp_rank].load_state_dict(model_state_dict) log_with_rank(f"Loaded sharded model checkpoint from {local_path}", rank=self.rank, logger=logger) # Skip HF checkpoint loading if PEFT is used elif self.should_load_model and self.use_hf_checkpoint and self.peft_cls is None: hf_model_path = get_hf_model_checkpoint_path(local_path) if self.vanilla_bridge: self.bridge.load_weights(self.model, hf_model_path) else: self.bridge.load_hf_weights(self.model, hf_model_path) log_with_rank(f"Loaded HF model checkpoint from {hf_model_path} with bridge", rank=self.rank, logger=logger) # Load PEFT adapter checkpoint if available if self.should_load_model and self.peft_cls is not None: adapter_ckpt_path = os.path.join(local_path, "adapter_checkpoint") if os.path.exists(adapter_ckpt_path): from verl.utils.megatron_peft_utils import load_adapter_checkpoint # TODO: a better format for adapter checkpoint, waiting megatron-bridge support load_adapter_checkpoint( self.model, adapter_ckpt_path, ) log_with_rank( f"Loaded adapter checkpoint from {adapter_ckpt_path}", rank=self.rank, logger=logger, ) else: log_with_rank( f"PEFT config is set but no adapter checkpoint found at {adapter_ckpt_path}", rank=self.rank, logger=logger, ) if self.should_load_optimizer: assert "optimizer" in state_dict, ( f"Optimizer state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}." ) optimizer_state_dict = state_dict["optimizer"] self.optimizer.load_state_dict(optimizer_state_dict) log_with_rank(f"Loaded optimizer checkpoint from {local_path}", rank=self.rank, logger=logger) if self.use_checkpoint_opt_param_scheduler: assert "lr_scheduler" in state_dict, ( f"LR scheduler state dict not found in {state_dict.keys()}. Please check the checkpoint file " f"{local_path}." ) lr_scheduler_state_dict = state_dict["lr_scheduler"] if self.lr_scheduler is not None: self.lr_scheduler.load_state_dict(lr_scheduler_state_dict) log_with_rank(f"Loaded LR scheduler checkpoint from {local_path}", rank=self.rank, logger=logger) if self.should_load_extra: assert "rng_state" in state_dict, ( f"RNG state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}." ) rng_state = state_dict["rng_state"] self.load_rng_states(rng_state) log_with_rank(f"Loaded RNG states from {local_path}", rank=self.rank, logger=logger) if del_local_after_load: try: os.remove(local_path) if is_non_local(local_path) else None except Exception as e: log_with_rank( f"remove local resume ckpt file after loading failed, exception {e} will be ignored", rank=self.rank, logger=logger, ) def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep=None): # record the previous global step self.previous_global_step = global_step if not self.checkpoint_config.async_save: self.ensure_checkpoint_capacity(max_ckpt_to_keep) local_path = local_mkdir_safe(local_path) dist_checkpoint_path = get_dist_checkpoint_path(local_path) # Note that model weights, optimizer states, and extra states are generated # together in a state dict, we save them in one time if self.use_dist_checkpointing: # Generate state dict for saving sharded_sd_metadata = self._build_sharded_state_dict_metadata() state_dict = self.generate_state_dict( self.should_save_model, self.should_save_optimizer, self.should_save_extra, metadata=sharded_sd_metadata, ) log_with_rank(f"Generated state dict for saving: {state_dict.keys()}", rank=self.rank, logger=logger) for vpp_rank, model in enumerate(self.model): if len(self.model) > 1: model_i_keys = state_dict[f"model{vpp_rank}"].keys() log_with_rank(f"Generated state dict for saving: {model_i_keys}", rank=self.rank, logger=logger) else: log_with_rank( f"Generated state dict for saving: {state_dict['model'].keys()}", rank=self.rank, logger=logger ) # Start Async save if enabled async_save_request = save_dist_checkpointing( sharded_state_dict=state_dict, ckpt_path=dist_checkpoint_path, async_save=self.checkpoint_config.async_save, content_metadata=sharded_sd_metadata, ) # Synchronize all async save requests if not self.checkpoint_config.async_save: assert async_save_request is None, "Async save request should be None when not using async save." torch.distributed.barrier() else: assert self.use_hf_checkpoint, "When not using distributed checkpointing, use_hf_checkpoint should be True." # Generate optimizer and exra state dicts sharded_sd_metadata = self._build_sharded_state_dict_metadata() state_dict = self.generate_state_dict( generate_model=False, generate_optimizer=self.should_save_optimizer, generate_extra=self.should_save_extra, metadata=sharded_sd_metadata, ) # Save optimizer and extra states to local path # Start Async save if enabled async_save_request = save_dist_checkpointing( sharded_state_dict=state_dict, ckpt_path=dist_checkpoint_path, async_save=self.checkpoint_config.async_save, content_metadata=sharded_sd_metadata, ) # Synchronize all async save requests if not self.checkpoint_config.async_save: assert async_save_request is None, "Async save request should be None when not using async save." torch.distributed.barrier() if self.should_save_model: # Save adapter-only checkpoint if PEFT is enabled if self.peft_cls is not None: from verl.utils.megatron_peft_utils import save_adapter_checkpoint adapter_ckpt_path = os.path.join(local_path, "adapter_checkpoint") # Save adapter weights only (much smaller than full model) save_adapter_checkpoint( self.model, adapter_ckpt_path, self.rank, ) log_with_rank( f"Saved adapter-only checkpoint to {adapter_ckpt_path}", rank=self.rank, logger=logger, log_only_rank_0=True, ) elif self.use_hf_checkpoint: # Use mbridge to save HF model checkpoint log_with_rank(f"Saving HF model checkpoint to {local_path} with bridge", rank=self.rank, logger=logger) hf_ckpt_path = get_hf_model_checkpoint_path(local_path) if self.vanilla_bridge: extended_args = {} mbridge_config = getattr(self.checkpoint_config, "mbridge_config", None) or {} for sig in inspect.signature(self.bridge.save_weights).parameters: if sig == "weights_path" or sig == "models": continue if sig in mbridge_config: extended_args[sig] = mbridge_config[sig] self.bridge.save_weights(self.model, hf_ckpt_path, **extended_args) else: self.bridge.save_hf_weights(self.model, hf_ckpt_path) log_with_rank(f"Saved bridge checkpoint to {hf_ckpt_path}", rank=self.rank, logger=logger) # Only rank 0 saves the hf config and tokenizer to huggingface path # No matter whether we save hf model or not if self.rank == 0: # Save tokenizer hf_config_tokenizer_path = get_hf_model_checkpoint_path(local_path) if self.processing_class is not None: self.processing_class.save_pretrained(hf_config_tokenizer_path) # Save huggingface config self.hf_config.save_pretrained(hf_config_tokenizer_path) if hasattr(self.hf_config, "name_or_path") and self.hf_config.name_or_path: try: generation_config = GenerationConfig.from_pretrained(self.hf_config.name_or_path) generation_config.save_pretrained(hf_config_tokenizer_path) except Exception: # if the generation config isn't available, we don't save it pass log_with_rank( f"Saved Huggingface config and tokenizer to {hf_config_tokenizer_path}", rank=self.rank, logger=logger, log_only_rank_0=True, ) if self.should_save_extra: if self.rank == 0: # Save transformer config print(self.transformer_config) bypass_keys = [ "finalize_model_grads_func", "grad_scale_func", "no_sync_func", "grad_sync_func", "param_sync_func", "generation_config", "_pg_collection", ] backup = {} for k in bypass_keys: if hasattr(self.transformer_config, k): backup[k] = getattr(self.transformer_config, k, None) delattr(self.transformer_config, k) transformer_config_dict = asdict(self.transformer_config) for k in backup: setattr(self.transformer_config, k, backup[k]) to_convert_types = {torch.dtype: str, AttnBackend: str} ignore_types = [Callable] pop_keys = [] for key, value in transformer_config_dict.items(): if type(value) in to_convert_types: transformer_config_dict[key] = to_convert_types[type(value)](value) if type(value) in ignore_types: pop_keys.append(key) if callable(value): pop_keys.append(key) for key in pop_keys: transformer_config_dict.pop(key) transformer_config_path = get_transformer_config_checkpoint_path(local_path) with open(transformer_config_path, "w") as f: json.dump(transformer_config_dict, f, indent=2) if self.should_save_hf_model and not self.use_hf_checkpoint: # wait for everyone to dump to local if self.bridge is not None: hf_model_ckpt_path = get_hf_model_checkpoint_path(local_path) if self.vanilla_bridge: extended_args = {} mbridge_config = getattr(self.checkpoint_config, "mbridge_config", None) or {} for sig in inspect.signature(self.bridge.save_weights).parameters: if sig == "weights_path" or sig == "models": continue if sig in mbridge_config: extended_args[sig] = mbridge_config[sig] self.bridge.save_weights(self.model, hf_model_ckpt_path, **extended_args) else: self.bridge.save_hf_weights(self.model, hf_model_ckpt_path) else: state_dict = self.weight_saver( self.model, self.hf_config, dtype=self.param_dtype, is_value_model=self.is_value_model, tie_word_embeddings=self.share_embeddings_and_output_weights, ) torch.distributed.barrier() if self.rank == 0: hf_model_ckpt_path = get_hf_model_checkpoint_path(local_path) import warnings from accelerate import init_empty_weights with init_empty_weights(), warnings.catch_warnings(): warnings.simplefilter("ignore") if "mistral7b-rm" in self.config.model.path: from transformers import MistralForSequenceClassification model = MistralForSequenceClassification.from_pretrained( self.config.model.path ) # use score head instead of lm_head state_dict["score.weight"] = state_dict["score.weight"] else: from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained(self.config.model.path, torch_dtype="auto") model.save_pretrained(hf_model_ckpt_path, state_dict=state_dict) log_with_rank( f"Saved Huggingface config and tokenizer to {hf_model_ckpt_path}", rank=self.rank, logger=logger, log_only_rank_0=True, ) if hdfs_path is not None: log_with_rank( f"Uploading checkpoint to {hdfs_path}", rank=self.rank, logger=logger, log_only_rank_0=True ) from verl.utils import hdfs_io hdfs_io.makedirs(hdfs_path, exist_ok=True) hdfs_io.copy(src=hf_model_ckpt_path, dst=hdfs_path, dirs_exist_ok=True) log_with_rank( f"HDFS checkpoint uploaded to {hdfs_path}", rank=self.rank, logger=logger, log_only_rank_0=True, ) def finalize_save_fn(): # Rank 0 uploads checkpoint to HDFS if hdfs_path is provided log_with_rank( f"Dist checkpointing save completed for {dist_checkpoint_path}", rank=self.rank, logger=logger ) if self.rank == 0: if hdfs_path is not None: log_with_rank(f"Uploading checkpoint to {hdfs_path}", rank=self.rank, logger=logger) from verl.utils import hdfs_io hdfs_io.makedirs(hdfs_path, exist_ok=True) hdfs_io.copy(src=dist_checkpoint_path, dst=hdfs_path, dirs_exist_ok=True) hdfs_io.copy(src=hf_config_tokenizer_path, dst=hdfs_path, dirs_exist_ok=True) # update latest_checkpointed_iteration.txt when async_save is True if self.checkpoint_config.async_save and self.rank == 0: log_with_rank( f"Update latest_checkpointed_iteration.txt to step {global_step}", rank=self.rank, logger=logger, ) local_latest_checkpointed_iteration = os.path.join( os.path.dirname(os.path.dirname(local_path)), "latest_checkpointed_iteration.txt" ) with open(local_latest_checkpointed_iteration, "w") as f: f.write(str(global_step)) self.register_checkpoint(local_path, max_ckpt_to_keep) if self.checkpoint_config.async_save: assert async_save_request is not None, "Async save request should not be None when using async save." async_save_request.add_finalize_fn(finalize_save_fn) from megatron.core.dist_checkpointing.strategies.base import async_calls async_calls.schedule_async_request(async_save_request) else: finalize_save_fn()
verl__utils__checkpoint__megatron_checkpoint_manager.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import is_dataclass from typing import Any, Optional from omegaconf import DictConfig, ListConfig, OmegaConf __all__ = ["omega_conf_to_dataclass", "validate_config"] def omega_conf_to_dataclass(config: DictConfig | dict, dataclass_type: Optional[type[Any]] = None) -> Any: """ Convert an OmegaConf DictConfig to a dataclass. Args: config: The OmegaConf DictConfig or dict to convert. dataclass_type: The dataclass type to convert to. When dataclass_type is None, the DictConfig must contain _target_ to be instantiated via hydra.instantiate API. Returns: The dataclass instance. """ # Got an empty config if not config: return dataclass_type if dataclass_type is None else dataclass_type() # Got an object if not isinstance(config, DictConfig | ListConfig | dict | list): return config if dataclass_type is None: assert "_target_" in config, ( "When dataclass_type is not provided, config must contain _target_. " "See trainer/config/ppo_trainer.yaml algorithm section for an example. " f"Got config: {config}" ) from hydra.utils import instantiate return instantiate(config, _convert_="partial") if not is_dataclass(dataclass_type): raise ValueError(f"{dataclass_type} must be a dataclass") cfg = OmegaConf.create(config) # in case it's a dict # pop _target_ to avoid hydra instantiate error, as most dataclass do not have _target_ # Updated (vermouth1992) We add _target_ to BaseConfig so that it is compatible. # Otherwise, this code path can't support recursive instantiation. # if "_target_" in cfg: # cfg.pop("_target_") cfg_from_dataclass = OmegaConf.structured(dataclass_type) # let cfg override the existing vals in `cfg_from_dataclass` cfg_merged = OmegaConf.merge(cfg_from_dataclass, cfg) # now convert to `dataclass_type` config_object = OmegaConf.to_object(cfg_merged) return config_object def update_dict_with_config(dictionary: dict, config: DictConfig): for key in dictionary: if hasattr(config, key): dictionary[key] = getattr(config, key) def validate_config( config: DictConfig, use_reference_policy: bool, use_critic: bool, ) -> None: """Validate an OmegaConf DictConfig. Args: config (DictConfig): The OmegaConf DictConfig to validate. use_reference_policy (bool): is ref policy needed use_critic (bool): is critic needed """ # number of GPUs total n_gpus = config.trainer.n_gpus_per_node * config.trainer.nnodes if not config.actor_rollout_ref.actor.use_dynamic_bsz: if config.actor_rollout_ref.actor.strategy == "megatron": model_parallel_size = ( config.actor_rollout_ref.actor.megatron.tensor_model_parallel_size * config.actor_rollout_ref.actor.megatron.pipeline_model_parallel_size ) assert ( n_gpus % (model_parallel_size * config.actor_rollout_ref.actor.megatron.context_parallel_size) == 0 ), ( f"n_gpus ({n_gpus}) must be divisible by model_parallel_size ({model_parallel_size}) times " f"context_parallel_size ({config.actor_rollout_ref.actor.megatron.context_parallel_size})" ) megatron_dp = n_gpus // ( model_parallel_size * config.actor_rollout_ref.actor.megatron.context_parallel_size ) minimal_bsz = megatron_dp * config.actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu else: minimal_bsz = n_gpus # 1. Check total batch size for data correctness real_train_batch_size = config.data.train_batch_size * config.actor_rollout_ref.rollout.n assert real_train_batch_size % minimal_bsz == 0, ( f"real_train_batch_size ({real_train_batch_size}) must be divisible by minimal possible batch size " f"({minimal_bsz})" ) # A helper function to check "micro_batch_size" vs "micro_batch_size_per_gpu" # We throw an error if the user sets both. The new convention is "..._micro_batch_size_per_gpu". def check_mutually_exclusive(mbs, mbs_per_gpu, name: str): """Validate mutually exclusive micro batch size configuration options. Ensures that users don't set both deprecated micro_batch_size and the new micro_batch_size_per_gpu parameters simultaneously. Args: mbs: Deprecated micro batch size parameter value. mbs_per_gpu: New micro batch size per GPU parameter value. name (str): Configuration section name for error messages. Raises: ValueError: If both parameters are set or neither is set. """ settings = { "actor_rollout_ref.ref": "log_prob_micro_batch_size", "actor_rollout_ref.rollout": "log_prob_micro_batch_size", } if name in settings: param = settings[name] param_per_gpu = f"{param}_per_gpu" if mbs is None and mbs_per_gpu is None: raise ValueError(f"[{name}] Please set at least one of '{name}.{param}' or '{name}.{param_per_gpu}'.") if mbs is not None and mbs_per_gpu is not None: raise ValueError( f"[{name}] You have set both '{name}.{param}' AND '{name}.{param_per_gpu}'. Please remove " f"'{name}.{param}' because only '*_{param_per_gpu}' is supported (the former is deprecated)." ) # Actor validation done in ActorConfig.__post_init__ and validate() actor_config = omega_conf_to_dataclass(config.actor_rollout_ref.actor) actor_config.validate(n_gpus, config.data.train_batch_size, config.actor_rollout_ref.model) if not config.actor_rollout_ref.actor.use_dynamic_bsz: if use_reference_policy: # reference: log_prob_micro_batch_size vs. log_prob_micro_batch_size_per_gpu check_mutually_exclusive( config.actor_rollout_ref.ref.log_prob_micro_batch_size, config.actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu, "actor_rollout_ref.ref", ) # The rollout section also has log_prob_micro_batch_size vs. log_prob_micro_batch_size_per_gpu check_mutually_exclusive( config.actor_rollout_ref.rollout.log_prob_micro_batch_size, config.actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu, "actor_rollout_ref.rollout", ) if config.algorithm.use_kl_in_reward and config.actor_rollout_ref.actor.use_kl_loss: print("NOTICE: You have both enabled in-reward kl and kl loss.") # critic if use_critic: critic_config = omega_conf_to_dataclass(config.critic) critic_config.validate(n_gpus, config.data.train_batch_size) if config.data.get("val_batch_size", None) is not None: print( "WARNING: val_batch_size is deprecated." + " Validation datasets are sent to inference engines as a whole batch," + " which will schedule the memory themselves." ) # check eval config if config.actor_rollout_ref.rollout.val_kwargs.do_sample: assert config.actor_rollout_ref.rollout.temperature > 0, ( "validation gen temperature should be greater than 0 when enabling do_sample" ) # check LoRA rank in vLLM lora_config = config.actor_rollout_ref.model.get("lora", {}) lora_rank = lora_config.get("rank", 0) if lora_rank <= 0: lora_rank = config.actor_rollout_ref.model.get("lora_rank", 0) if lora_config.get("merge", False): lora_rank = 0 if lora_rank > 0 and config.actor_rollout_ref.rollout.name == "vllm": from verl.workers.rollout.vllm_rollout.utils import get_vllm_max_lora_rank get_vllm_max_lora_rank(lora_rank) print("[validate_config] All configuration checks passed successfully!")
verl__utils__config.py
# Copyright 2025 Bytedance Ltd. and/or its affiliates # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from enum import Enum import torch from tensordict.tensorclass import NonTensorData class DatasetPadMode(str, Enum): """Padding mode for dataset""" RIGHT = "right" LEFT_RIGHT = "left_right" NO_PADDING = "no_padding" class SFTTensorCollator: """ A custom collate_fn that handles batching of sequences. 1. for variable-length sequences, convert them into NestedTensors. 2. for fixed-length sequences, use default_collate. """ def __init__(self, pad_mode: DatasetPadMode = DatasetPadMode.LEFT_RIGHT): self.pad_mode = pad_mode def __call__(self, batch: list[dict[str, any]]) -> dict[str, any]: if self.pad_mode == DatasetPadMode.NO_PADDING: return self.collate_variable_batch(batch) elif self.pad_mode in [DatasetPadMode.RIGHT, DatasetPadMode.LEFT_RIGHT]: from torch.utils.data import default_collate return default_collate(batch) else: raise NotImplementedError(f"pad_mode {self.pad_mode} not implemented") def collate_variable_batch(self, batch: list[dict[str, any]]) -> dict[str, any]: """ Collates a list of samples into a single batch. Args: batch: A list of dictionary samples from the dataset. Returns: A dictionary representing the batched data, with variable-length sequences converted to NestedTensors. """ final_batch = {} tensor_keys = set().union(*(d.keys() for d in batch)) # Handle tensor values by creating a NestedTensor. for key in tensor_keys: if isinstance(batch[0][key], torch.Tensor): tensors = [item[key] for item in batch] final_batch[key] = torch.nested.as_nested_tensor(tensors, layout=torch.jagged) else: tensors = [NonTensorData(item.get(key)) for item in batch] final_batch[key] = torch.stack(tensors, dim=0) return final_batch
verl__utils__dataset__dataset_utils.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2025 ModelBest Inc. and/or its affiliates # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Multi-turn SFT dataset that supports training on conversation data with multiple turns """ import logging import os import re from functools import wraps from typing import Any, Optional import numpy as np import pandas as pd import torch import torch.nn.functional as F from omegaconf import DictConfig, ListConfig from torch.utils.data import Dataset from transformers import PreTrainedTokenizer, ProcessorMixin from verl.models.transformers.qwen2_vl import get_rope_index from verl.utils import hf_tokenizer from verl.utils.chat_template import extract_system_prompt_and_generation from verl.utils.dataset.dataset_utils import DatasetPadMode from verl.utils.dataset.vision_utils import process_image, process_video from verl.utils.fs import copy_local_path_from_hdfs logger = logging.getLogger(__file__) logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) def once(func): """Decorator to ensure a function runs only once. Subsequent calls do nothing.""" @wraps(func) def wrapper(*args, **kwargs): if not hasattr(wrapper, "called"): wrapper.called = True return func(*args, **kwargs) return wrapper @once def print_assembled_message(tokenizer, message_list, input_ids, loss_mask, attn_mask, tools): """ Print the message after applying the chat template """ tokenized = tokenizer.apply_chat_template(message_list, add_generation_prompt=False, tokenize=False, tools=tools) sep = "\n\n" str = f"tokenized entire message:\n{tokenized}" str += sep str += f"tokenized seperately :\n{tokenizer.decode(input_ids)}" logger.debug(str) def convert_nested_value_to_list_recursive(data_item): if isinstance(data_item, dict): return {k: convert_nested_value_to_list_recursive(v) for k, v in data_item.items()} elif isinstance(data_item, list): return [convert_nested_value_to_list_recursive(elem) for elem in data_item] elif isinstance(data_item, np.ndarray): # Convert to list, then recursively process the elements of the new list return convert_nested_value_to_list_recursive(data_item.tolist()) else: # Base case: item is already a primitive type (int, str, float, bool, etc.) return data_item class MultiTurnSFTDataset(Dataset): """ Dataset for multi-turn conversations where each assistant response should be trained Args: data_files (str or list): Path(s) to Parquet file(s). tokenizer (PreTrainedTokenizer): For the tokenization of text to token IDs. config (DictConfig): Options like cache_dir, prompt_key, max_prompt_length, truncation, etc. processor (ProcessorMixin, optional): Multimodal preprocessor for images/videos. max_samples (int, optional): Limit the number of samples. Defaults to -1 (use all). """ def __init__( self, parquet_files: str | list[str], tokenizer: PreTrainedTokenizer, config: DictConfig, processor: Optional[ProcessorMixin] = None, max_samples: int = -1, ): # Set defaults and extract parameters from config if provided config = config or {} self.pad_mode = config.get("pad_mode", "right") assert self.pad_mode in ["right", "no_padding"], ( f"Expect pad_mode to be 'right' or 'no_padding'. Got {self.pad_mode}" ) self.truncation = config.get("truncation", "error") # for right padding self.max_length = config.get("max_length", 1024) # Get messages_key from the new multiturn config structure self.messages_key = config.get("messages_key", "messages") self.image_key = config.get("image_key", "images") self.video_key = config.get("video_key", "videos") self.image_patch_size = config.get( "image_patch_size", processor.image_processor.patch_size if processor else None ) self.tools_key = config.get("tools_key", "tools") self.enable_thinking_key = config.get("enable_thinking_key", "enable_thinking") self.enable_thinking_default = config.get("enable_thinking_default", None) self.apply_chat_template_kwargs = config.get("apply_chat_template_kwargs", {}) self.shuffle = config.get("shuffle", False) self.seed = config.get("seed") self.max_samples = max_samples self.ignore_input_ids_mismatch = config.get("ignore_input_ids_mismatch", False) assert self.truncation in ["error", "left", "right"] if not isinstance(parquet_files, list | ListConfig): parquet_files = [parquet_files] self.parquet_files = parquet_files if isinstance(tokenizer, str): tokenizer = hf_tokenizer(tokenizer) self.tokenizer: PreTrainedTokenizer = tokenizer self.processor = processor self._download() self._read_files_and_process() def _download(self): for i, parquet_file in enumerate(self.parquet_files): self.parquet_files[i] = copy_local_path_from_hdfs(parquet_file, verbose=True) def _read_files_and_process(self): def series_to_item(ls): import numpy import pandas while isinstance(ls, pandas.core.series.Series | numpy.ndarray) and len(ls) == 1: ls = ls[0] return ls dataframes = [] for parquet_file in self.parquet_files: # default loader loads some list as np.ndarray, which fails the tokenizer dataframe = pd.read_parquet(parquet_file, dtype_backend="pyarrow") dataframes.append(dataframe) self.dataframe = pd.concat(dataframes) total = len(self.dataframe) print(f"dataset len: {len(self.dataframe)}") if self.max_samples > 0 and self.max_samples < total: if self.shuffle: rngs_args = (self.seed,) if self.seed is not None else () rng = np.random.default_rng(*rngs_args) indices = rng.choice(total, size=self.max_samples, replace=False) else: indices = np.arange(self.max_samples) self.dataframe = self.dataframe.iloc[indices.tolist()] print(f"selected {self.max_samples} random samples out of {total}") # Extract messages list from dataframe self.messages = self.dataframe[self.messages_key].apply(convert_nested_value_to_list_recursive).tolist() # Extract tools list from dataframe if self.tools_key in self.dataframe.columns: self.tools = self.dataframe[self.tools_key].apply(convert_nested_value_to_list_recursive).tolist() else: self.tools = None # Extract enable_thinking list from dataframe if self.enable_thinking_key in self.dataframe.columns: self.enable_thinking = self.dataframe[self.enable_thinking_key].tolist() else: self.enable_thinking = None # system prompt: <|im_start|>system\nYou are a helpful assistant.<|im_end|>\n # generation prompt: <|im_start|>assistant\n self.system_prompt, self.generation_prompt = extract_system_prompt_and_generation(self.tokenizer) def __len__(self): return len(self.messages) def _process_single_message( self, index: int, message: dict[str, Any], full_message: list, tools: Optional[list[dict[str, Any]]] = None, enable_thinking: Optional[bool] = None, ) -> tuple[list[int], list[int], list[int]]: """ Process a single message and return its tokenized representation. Args: index: turn index in the conversation message: A single message dictionary images: List of images to be used videos: List of videos to be used tools: List of tools to be used enable_thinking: Whether to enable thinking mode Returns: Tuple of (input_ids, loss_mask, attention_mask, dict[str, torch.Tensor]) """ processor = self.processor if self.processor is not None else self.tokenizer apply_chat_template_kwargs = {**self.apply_chat_template_kwargs} if enable_thinking is not None: apply_chat_template_kwargs["enable_thinking"] = enable_thinking inputs = processor.apply_chat_template( [message], tools=tools, add_generation_prompt=False, tokenize=True, return_dict=True, return_tensors="pt", **apply_chat_template_kwargs, ) inputs = dict(inputs) input_ids = inputs.pop("input_ids")[0] attention_mask = inputs.pop("attention_mask")[0] # remove system prompt if exists if index != 0 and message["role"] != "system": input_ids = input_ids[len(self.system_prompt) :] attention_mask = attention_mask[len(self.system_prompt) :] if message["role"] == "assistant": loss_mask = torch.ones_like(attention_mask) # mask out generation prompt if assistant message loss_mask[: len(self.generation_prompt)] = 0 else: loss_mask = torch.zeros_like(attention_mask) return input_ids, loss_mask, attention_mask, inputs def _build_messages(self, example: dict): """Replace <image> and <video> placeholder in messages with corresponding image and video which is required by processor.apply_chat_template. - <image>: {"type": "image", "image": image} - <video>: {"type": "video", "video": video} Args: example: Row dictionary from dataframe. Returns: messages: List of messages with replaced placeholder. """ messages: list = example[self.messages_key] images = example[self.image_key] if self.image_key in example else [] videos = example[self.video_key] if self.video_key in example else [] image_offset, video_offset = 0, 0 for message in messages: if self.image_key not in example and self.video_key not in example: continue assert self.processor is not None, "processor is needed to process image and video" content = message["content"] if not isinstance(content, str): continue content_list = [] segments = re.split("(<image>|<video>)", content) segments = [item for item in segments if item != ""] for segment in segments: if segment == "<image>": image = process_image(images[image_offset], image_patch_size=self.image_patch_size) content_list.append({"type": "image", "image": image}) image_offset += 1 elif segment == "<video>": video = process_video(videos[video_offset], image_patch_size=self.image_patch_size) content_list.append({"type": "video", "video": video}) video_offset += 1 else: content_list.append({"type": "text", "text": segment}) message["content"] = content_list assert image_offset == len(images), f"image_offset {image_offset} != len(images) {len(images)}" assert video_offset == len(videos), f"video_offset {video_offset} != len(videos) {len(videos)}" return messages def __getitem__(self, item): row_dict: dict = self.dataframe.iloc[item].to_dict() messages = self._build_messages(row_dict) tools = self.tools[item] if self.tools is not None else None enable_thinking = ( self.enable_thinking[item] if self.enable_thinking is not None else self.enable_thinking_default ) # 1. tokenize each message input_ids, loss_mask, attention_mask, multi_modal_inputs = [], [], [], {} for i, message in enumerate(messages): _input_ids, _loss_mask, _attention_mask, _inputs = self._process_single_message( index=i, message=message, full_message=messages, tools=tools if i == 0 else None, enable_thinking=enable_thinking, ) input_ids.append(_input_ids) loss_mask.append(_loss_mask) attention_mask.append(_attention_mask) for k, v in _inputs.items(): multi_modal_inputs.setdefault(k, []).append(v) input_ids = torch.cat(input_ids, dim=0) loss_mask = torch.cat(loss_mask, dim=0) attention_mask = torch.cat(attention_mask, dim=0) assert input_ids.shape == loss_mask.shape == attention_mask.shape, ( f"Shape mismatch: {input_ids.shape}, {loss_mask.shape}, {attention_mask.shape}" ) print_assembled_message(self.tokenizer, messages, input_ids, loss_mask, attention_mask, tools) self.sanity_check(input_ids, messages, tools, enable_thinking) # Since the tokenizer may return user-customized results, we need to filter out inconsistent tensor shapes keys_to_remove = [] for k, v in multi_modal_inputs.items(): if len(v) > 0 and v[0] is not None and isinstance(v[0], torch.Tensor): # Check if all tensors in the list have the same shape first_shape = v[0].shape[1:] if not all(tensor.shape[1:] == first_shape for tensor in v): keys_to_remove.append(k) for k in keys_to_remove: del multi_modal_inputs[k] for k, v in multi_modal_inputs.items(): multi_modal_inputs[k] = torch.concat(v, dim=0) # 2. handle position_ids for Qwen-VL series models if self.processor is not None and "Qwen2VLImageProcessor" in self.processor.image_processor.__class__.__name__: image_grid_thw = multi_modal_inputs.get("image_grid_thw", None) video_grid_thw = multi_modal_inputs.get("video_grid_thw", None) second_per_grid_ts = multi_modal_inputs.get("second_per_grid_ts", None) vision_position_ids = get_rope_index( self.processor, input_ids=input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, second_per_grid_ts=second_per_grid_ts, attention_mask=attention_mask, ) # (3, seq_len) text_position_ids = torch.arange(input_ids.shape[0], dtype=torch.long).unsqueeze(0) # (1, seq_len) position_ids = torch.cat((text_position_ids, vision_position_ids), dim=0) # (4, seq_length) else: position_ids = torch.arange(input_ids.shape[0], dtype=torch.long) # (seq_len,) # 3. handle padding sequence_length = input_ids.shape[0] # Handle sequence length if self.pad_mode == DatasetPadMode.RIGHT: if sequence_length < self.max_length: # Pad sequences pad_token_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else 0 padded_input_ids = torch.full((self.max_length - sequence_length,), pad_token_id, dtype=input_ids.dtype) padded_attention_mask = torch.zeros((self.max_length - sequence_length,), dtype=attention_mask.dtype) padded_loss_mask = torch.zeros((self.max_length - sequence_length,), dtype=loss_mask.dtype) input_ids = torch.cat((input_ids, padded_input_ids)) attention_mask = torch.cat((attention_mask, padded_attention_mask)) loss_mask = torch.cat((loss_mask, padded_loss_mask)) position_ids = F.pad(position_ids, (0, self.max_length - sequence_length), value=0) elif sequence_length > self.max_length: if self.truncation == "left": input_ids = input_ids[-self.max_length :] attention_mask = attention_mask[-self.max_length :] loss_mask = loss_mask[-self.max_length :] position_ids = position_ids[..., -self.max_length :] elif self.truncation == "right": input_ids = input_ids[: self.max_length] attention_mask = attention_mask[: self.max_length] loss_mask = loss_mask[: self.max_length] position_ids = position_ids[..., : self.max_length] elif self.truncation == "error": raise ValueError(f"{sequence_length=} is larger than {self.max_length=}") else: raise ValueError(f"Unknown truncation method {self.truncation}") res = { "input_ids": input_ids, "attention_mask": attention_mask, "position_ids": position_ids, "loss_mask": loss_mask, } if len(multi_modal_inputs) > 0: res["multi_modal_inputs"] = multi_modal_inputs return res elif self.pad_mode == DatasetPadMode.NO_PADDING: # truncate input_ids if it is longer than max_length if len(input_ids) > self.max_length: input_ids = input_ids[: self.max_length] loss_mask = loss_mask[: self.max_length] position_ids = position_ids[..., : self.max_length] # return nested tensor with out padding res = { "input_ids": input_ids, "position_ids": position_ids, "loss_mask": loss_mask, } if len(multi_modal_inputs) > 0: res["multi_modal_inputs"] = multi_modal_inputs return res else: raise ValueError(f"Unknown pad mode {self.pad_mode}") def sanity_check(self, input_ids: torch.Tensor, messages: list[dict], tools: list[dict], enable_thinking: bool): """Check concatenated input_ids of apply_chat_template to each turn equals apply_chat_template to whole messages. """ processor = self.processor if self.processor is not None else self.tokenizer apply_chat_template_kwargs = {**self.apply_chat_template_kwargs} if enable_thinking is not None: apply_chat_template_kwargs["enable_thinking"] = enable_thinking inputs = processor.apply_chat_template( messages, tools=tools, add_generation_prompt=False, tokenize=True, return_dict=True, return_tensors="pt", **apply_chat_template_kwargs, ) error_message = ( "MultiTurnSFTDataset apply_chat_template to each turn separately and concat `input_ids` " "as a whole sequence, which may not equal to apply_chat_template to whole messages at once.\n" "For example, Qwen Thinking series models add <think></think> tags to last turn, please check " "your tokenizer chat template settings.\n" "Set `ignore_input_ids_mismatch=True` to ignore input_ids mismatch and use the concatenated " "input_ids as the final input_ids. " ) if not torch.equal(input_ids, inputs["input_ids"].squeeze(0)): if self.ignore_input_ids_mismatch: logger.warning_once(error_message) else: raise AssertionError(error_message)
verl__utils__dataset__multiturn_sft_dataset.py
# Copyright 2024 Bytedance Ltd. and/or its affiliates # Copyright 2023-2024 SGLang Team # Copyright 2025 ModelBest Inc. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import logging import os import re import traceback from collections import defaultdict from io import BytesIO from typing import Optional import datasets import numpy as np import torch from omegaconf import DictConfig, ListConfig from PIL import Image from torch.utils.data import Dataset from transformers import PreTrainedTokenizer, ProcessorMixin from verl.utils.import_utils import load_extern_object logger = logging.getLogger(__name__) def collate_fn(data_list: list[dict]) -> dict: """ Collate a batch of sample dicts into batched tensors and arrays. Args: data_list: List of dicts mapping feature names to torch.Tensor or other values. Returns: Dict where tensor entries are stacked into a torch.Tensor of shape (batch_size, \\*dims) and non-tensor entries are converted to np.ndarray of dtype object with shape (batch_size,). """ tensors = defaultdict(list) non_tensors = defaultdict(list) for data in data_list: for key, val in data.items(): if isinstance(val, torch.Tensor): tensors[key].append(val) else: non_tensors[key].append(val) for key, val in tensors.items(): tensors[key] = torch.stack(val, dim=0) for key, val in non_tensors.items(): non_tensors[key] = np.fromiter(val, dtype=object, count=len(val)) return {**tensors, **non_tensors} class RLHFDataset(Dataset): """ Load and preprocess RLHF data from Parquet files. - Caches files locally. - Reads into a HuggingFace Dataset and tokenizes prompts. - Optionally handles images/videos via a ProcessorMixin. - Filters prompts over a max length. - Supports resuming from checkpoints. Args: data_files (str or list): Path(s) to Parquet file(s). tokenizer (PreTrainedTokenizer): For the tokenization of text to token IDs. config (DictConfig): Options like cache_dir, prompt_key, max_prompt_length, truncation, etc. processor (ProcessorMixin, optional): Multimodal preprocessor for images/videos. """ def __init__( self, data_files: str | list[str], tokenizer: PreTrainedTokenizer, config: DictConfig, processor: Optional[ProcessorMixin] = None, max_samples: int = -1, ): if not isinstance(data_files, list | ListConfig): data_files = [data_files] self.data_files = copy.deepcopy(data_files) self.original_data_files = copy.deepcopy(data_files) # use for resume self.tokenizer = tokenizer self.processor = processor self.max_samples = max_samples self.config = config self.cache_dir = os.path.expanduser(config.get("cache_dir", "~/.cache/verl/rlhf")) self.prompt_key = config.get("prompt_key", "prompt") self.image_key = config.get("image_key", "images") self.video_key = config.get("video_key", "videos") self.image_patch_size = config.get("image_patch_size", 14) self.max_prompt_length = config.get("max_prompt_length", 1024) self.return_raw_chat = config.get("return_raw_chat", False) self.return_full_prompt = config.get("return_full_prompt", False) self.truncation = config.get("truncation", "error") self.filter_overlong_prompts = config.get("filter_overlong_prompts", True) self.apply_chat_template_kwargs = config.get("apply_chat_template_kwargs", {}) self.tool_config_path = config.get("tool_config_path", None) self.tool_schemas = None if self.tool_config_path: try: from verl.tools.utils.tool_registry import initialize_tools_from_config tool_list = initialize_tools_from_config(self.tool_config_path) # match ToolAgentLoop behaviour: model_dump to plain dicts self.tool_schemas = [ tool.tool_schema.model_dump(exclude_unset=True, exclude_none=True) for tool in tool_list ] except Exception as e: logger.warning("Failed to initialize tools from %s: %s", self.tool_config_path, e) self.tool_schemas = None self.num_workers = config.get("filter_overlong_prompts_workers", max(1, os.cpu_count() // 4)) self.num_workers = min(self.num_workers, os.cpu_count()) if self.num_workers is not None else None self.use_shm = config.get("use_shm", False) self.chat_template_func = config.get("chat_template_func", None) self.need_tools_kwargs = config.get("need_tools_kwargs", False) self.filter_prompts = config.get("filter_prompts", True) self.serialize_dataset = False self.return_multi_modal_inputs = config.get("return_multi_modal_inputs", True) self.shuffle = config.get("shuffle", False) self.seed = config.get("seed") self._download() self._read_files_and_tokenize() def _download(self, use_origin_parquet=False): from verl.utils.fs import copy_to_local data_files = self.data_files if not use_origin_parquet else self.original_data_files for i, parquet_file in enumerate(data_files): self.data_files[i] = copy_to_local(src=parquet_file, cache_dir=self.cache_dir, use_shm=self.use_shm) def _read_files_and_tokenize(self): dataframes = [] for parquet_file in self.data_files: # read files and cache if parquet_file.endswith(".parquet"): dataframe = datasets.load_dataset("parquet", data_files=parquet_file)["train"] elif parquet_file.endswith(".json"): dataframe = datasets.load_dataset("json", data_files=parquet_file)["train"] else: raise ValueError(f"Unsupported file format: {parquet_file}") dataframes.append(dataframe) self.dataframe: datasets.Dataset = datasets.concatenate_datasets(dataframes) total = len(self.dataframe) print(f"dataset len: {len(self.dataframe)}") if self.max_samples > 0 and self.max_samples < total: if self.shuffle: rngs_args = (self.seed,) if self.seed is not None else () rng = np.random.default_rng(*rngs_args) indices = rng.choice(total, size=self.max_samples, replace=False) else: indices = np.arange(self.max_samples) self.dataframe = self.dataframe.select(indices.tolist()) print(f"selected {self.max_samples} random samples out of {total}") self.dataframe = self.maybe_filter_out_long_prompts(self.dataframe) def maybe_filter_out_long_prompts(self, dataframe: datasets.Dataset = None): # filter out too long prompts if self.filter_overlong_prompts: tokenizer = self.tokenizer processor = self.processor prompt_key = self.prompt_key image_key = self.image_key video_key = self.video_key if processor is not None: from verl.utils.dataset.vision_utils import process_image, process_video def doc2len(doc) -> int: try: messages = self._build_messages(doc) # pass tool schemas if available so the processor can format prompts apply_kwargs = dict(**self.apply_chat_template_kwargs) if self.tool_schemas is not None: apply_kwargs["tools"] = self.tool_schemas raw_prompt = self.processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=False, **apply_kwargs ) if image_key in doc and doc[image_key]: images = [ process_image(image, image_patch_size=self.image_patch_size) for image in doc[image_key] ] else: images = None if video_key in doc and doc[video_key]: videos, video_metadata = zip( *[ process_video( video, image_patch_size=self.image_patch_size, return_video_metadata=True ) for video in doc[video_key] ], strict=True, ) videos = list(videos) video_metadata = list(video_metadata) videos_kwargs = {"video_metadata": video_metadata, "do_sample_frames": False} else: videos = None videos_kwargs = {} return len( processor(text=[raw_prompt], images=images, videos=videos, videos_kwargs=videos_kwargs)[ "input_ids" ][0] ) except Exception: print("Error processing one of the samples, skipping...") traceback.print_exc() return self.max_prompt_length + 1 else: def doc2len(doc) -> int: try: apply_kwargs = dict(**self.apply_chat_template_kwargs) if self.tool_schemas is not None: apply_kwargs["tools"] = self.tool_schemas return len( tokenizer.apply_chat_template(doc[prompt_key], add_generation_prompt=True, **apply_kwargs) ) except Exception: print("Error processing one of the samples, skipping...") traceback.print_exc() return self.max_prompt_length + 1 dataframe = dataframe.filter( lambda doc: doc2len(doc) <= self.max_prompt_length, num_proc=self.num_workers, desc=f"Filtering prompts longer than {self.max_prompt_length} tokens", ) print(f"filter dataset len: {len(dataframe)}") return dataframe def resume_dataset_state(self): self.serialize_dataset = not hasattr(self, "original_data_files") # resume dataframe if not it's serialized in data.pt if not self.serialize_dataset: self._download(use_origin_parquet=True) # download and resume from original parquet files self._read_files_and_tokenize() else: print(r"old dataloader ckpt file is used, please train from scratch for better ckpt performance") def __getstate__(self): if not self.serialize_dataset: state = self.__dict__.copy() if "dataframe" in state: del state["dataframe"] return state return self.__dict__.copy() def __len__(self): return len(self.dataframe) def _build_messages(self, example: dict): """Replace <image> and <video> placeholder in messages with corresponding image and video which is required by processor.apply_chat_template. - <image>: {"type": "image", **image} - <video>: {"type": "video", **video} Args: example: Row dictionary from dataframe. Returns: messages: List of messages with replaced placeholder. """ messages: list = example[self.prompt_key] # When concatenating image and video datasets, pop will return None for image or video sample images = example.pop(self.image_key, None) or [] videos = example.pop(self.video_key, None) or [] image_offset, video_offset = 0, 0 for message in messages: if not images and not videos: continue assert self.processor is not None, "processor is needed to process image and video" content = message["content"] if not isinstance(content, str): continue content_list = [] segments = re.split("(<image>|<video>)", content) segments = [item for item in segments if item != ""] for segment in segments: if segment == "<image>": assert image_offset < len(images), f"image_offset {image_offset} >= len(images) {len(images)}" image = images[image_offset] if isinstance(image, Image.Image): image = image.convert("RGB") content_list.append({"type": "image", "image": image}) elif isinstance(image, dict): if "bytes" in image: image["image"] = Image.open(BytesIO(image["bytes"])) content_list.append({"type": "image", **image}) else: raise TypeError(f"image must be dict or PIL.Image, unsupported image type: {type(image)}") image_offset += 1 elif segment == "<video>": assert video_offset < len(videos), f"video_offset {video_offset} >= len(videos) {len(videos)}" content_list.append({"type": "video", **videos[video_offset]}) video_offset += 1 else: content_list.append({"type": "text", "text": segment}) message["content"] = content_list assert image_offset == len(images), f"image_offset {image_offset} != len(images) {len(images)}" assert video_offset == len(videos), f"video_offset {video_offset} != len(videos) {len(videos)}" return messages def __getitem__(self, item): """For rollout, apply_chat_template has been moved to AgentLoop, so we only return raw_prompt here.""" row_dict: dict = self.dataframe[item] row_dict["raw_prompt"] = self._build_messages(row_dict) # TODO(wuxibin): We still need a dummy tensor to make sure DataProto.batch is not empty. # Remove this after deprecate DataProto by TensorDict. row_dict["dummy_tensor"] = torch.tensor([0], dtype=torch.uint8) # add index for each prompt if "extra_info" not in row_dict or row_dict["extra_info"] is None: row_dict["extra_info"] = dict() index = row_dict.get("extra_info", {}).get("index", 0) tools_kwargs = row_dict.get("extra_info", {}).get("tools_kwargs", {}) interaction_kwargs = row_dict.get("extra_info", {}).get("interaction_kwargs", {}) need_tools_kwargs = row_dict.get("extra_info", {}).get("need_tools_kwargs", self.need_tools_kwargs) if need_tools_kwargs and not tools_kwargs: logger.warning("tools_kwargs is empty for index {}, data source: {}", index, row_dict["data_source"]) row_dict["index"] = index row_dict["tools_kwargs"] = tools_kwargs row_dict["interaction_kwargs"] = interaction_kwargs return row_dict @classmethod async def process_vision_info( cls, messages: list[dict], image_patch_size, config: DictConfig, ) -> tuple[list[Image.Image], list[tuple[torch.Tensor, dict]]]: """Extract images and videos from messages. This method is called by AgentLoop (e.g SingleTurnAgentLoop) before apply_chat_template to the `raw_prompt` from dataset. User may customize RLHFDataset and override this method to support custom vision extraction. >>> messages = kwargs["raw_prompt"] >>> images, videos = RLHFDataset.process_vision_info(messages, image_patch_size) >>> videos, video_metadatas = zip(*videos) >>> raw_prompt = processor.apply_chat_template(messages, tokenize=False) >>> inputs = processor(text=[raw_prompt], images=images, videos=videos, ... video_metadata=video_metadatas, do_sample_frames=False) Args: messages: List of messages from dataset `raw_prompt`. image_patch_size: Image patch size for processor. config: Config for dataset. Returns: images: List of images. videos: List of videos, each video is a tuple of (video_tensor, video_metadata). """ from qwen_vl_utils import process_vision_info images, videos = process_vision_info(messages, image_patch_size=image_patch_size, return_video_metadata=True) return images, videos def split(self, num_splits: int): """ split the dataset into num_splits sub-datasets Args: num_splits: specified number of splits Returns: List[RLHFDataset]: list of RLHFDataset splits Raises: ValueError: if num_splits is not a positive integer """ if not isinstance(num_splits, int) or num_splits <= 0: raise ValueError(f"num_splits must be a positive integer, got {num_splits}") if not hasattr(self, "dataframe"): raise AttributeError( "dataframe not found in RLHFDataset\n" "reason: _read_files_and_tokenize() not called or Parquet file loading failed" ) if self.dataframe is None: raise ValueError("RLHFDataset dataframe 为 None!") total_samples = len(self.dataframe) print(f"total_samples: {total_samples}") if total_samples == 0: raise ValueError("Cannot split an empty dataset") if total_samples % num_splits != 0: raise ValueError(f"Cannot split dataset size {total_samples} into {num_splits} splits") split_size = total_samples // num_splits splits = [] for i in range(num_splits): start_idx = i * split_size end_idx = (i + 1) * split_size if i < num_splits - 1 else total_samples split_dataframe = self.dataframe.select(range(start_idx, end_idx)) split_dataset = RLHFDataset( data_files=self.data_files, tokenizer=self.tokenizer, config=self.config, processor=self.processor, max_samples=self.max_samples, ) split_dataset.dataframe = split_dataframe split_dataset.serialize_dataset = self.serialize_dataset split_dataset.original_data_files = self.original_data_files splits.append(split_dataset) return splits def get_dataset_class(data_config: DictConfig): """Get RLHF dataset class. Args: data_config: The data config. Returns: dataset_cls: The dataset class. """ # Check if a custom dataset class is specified in the data configuration # and if the path to the custom class is provided if "custom_cls" in data_config and data_config.custom_cls.get("path", None) is not None: # Dynamically load the custom dataset class dataset_cls = load_extern_object(data_config.custom_cls.path, data_config.custom_cls.name) # Verify that the custom dataset class inherits from torch.utils.data.Dataset if not issubclass(dataset_cls, Dataset): raise TypeError( f"The custom dataset class '{data_config.custom_cls.name}' from " f"'{data_config.custom_cls.path}' must inherit from torch.utils.data.Dataset" ) else: # Use the default RLHFDataset class if no custom class is specified dataset_cls = RLHFDataset print(f"Using dataset class: {dataset_cls.__name__}") return dataset_cls
verl__utils__dataset__rl_dataset.py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from typing import Optional import numpy as np import pandas as pd import torch from torch.utils.data import Dataset from verl.utils import hf_tokenizer def download_files_distributed(download_fn): import torch.distributed if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: # download files download_fn() torch.distributed.barrier() else: # download anyway download_fn() class RMDataset(Dataset): def __init__( self, parquet_files: str | list[str], tokenizer, prompt_key="prompt", chosen_key="chosen", rejected_key="rejected", max_length=1024, add_eos=True, cache_dir="~/.cache/verl/rm", max_samples: int = -1, shuffle: bool = False, seed: Optional[int] = None, ): if not isinstance(parquet_files, list): parquet_files = [parquet_files] self.parquet_files = parquet_files self.max_samples = max_samples self.shuffle = shuffle self.seed = seed self.cache_dir = os.path.expanduser(cache_dir) if isinstance(tokenizer, str): tokenizer = hf_tokenizer(tokenizer) self.tokenizer = tokenizer self.prompt_key = prompt_key self.chosen_key = chosen_key self.rejected_key = rejected_key self.add_eos = add_eos self.max_length = max_length self._download() self._read_files_and_tokenize() def _download(self): def _download_files(): from verl.utils.fs import copy, is_non_local os.makedirs(self.cache_dir, exist_ok=True) assert os.path.exists(self.cache_dir) for i, parquet_file in enumerate(self.parquet_files): if is_non_local(parquet_file): dst = os.path.join(self.cache_dir, os.path.basename(parquet_file)) if not os.path.exists(dst): copy(src=parquet_file, dst=dst) self.parquet_files[i] = dst download_files_distributed(_download_files) def _read_files_and_tokenize(self): dataframes = [] for parquet_file in self.parquet_files: # read parquet files and cache dataframe = pd.read_parquet(parquet_file) dataframes.append(dataframe) self.dataframe = pd.concat(dataframes) total = len(self.dataframe) print(f"dataset len: {len(self.dataframe)}") if self.max_samples > 0 and self.max_samples < total: if self.shuffle: rngs_args = (self.seed,) if self.seed is not None else () rng = np.random.default_rng(*rngs_args) indices = rng.choice(total, size=self.max_samples, replace=False) else: indices = np.arange(self.max_samples) self.dataframe = self.dataframe.iloc[indices.tolist()] print(f"selected {self.max_samples} random samples out of {total}") self.prompts = self.dataframe[self.prompt_key].tolist() self.chosen_responses = self.dataframe[self.chosen_key].tolist() self.rejected_responses = self.dataframe[self.rejected_key].tolist() def __len__(self): return len(self.prompts) def _pad_to_length(self, input_ids, attention_mask): curr_length = input_ids.shape[-1] if curr_length < self.max_length: input_ids = torch.cat( (input_ids, torch.zeros(size=(self.max_length - curr_length,), dtype=input_ids.dtype)), dim=-1 ) attention_mask = torch.cat( (attention_mask, torch.zeros(size=(self.max_length - curr_length,), dtype=attention_mask.dtype)), dim=-1 ) elif curr_length > self.max_length: input_ids = input_ids[: self.max_length] attention_mask = attention_mask[: self.max_length] return input_ids, attention_mask def __getitem__(self, item): prompt = self.prompts[item] chosen_response = self.chosen_responses[item] rejected_response = self.rejected_responses[item] prompt_ids = self.tokenizer(prompt, return_tensors="pt")["input_ids"][0] chosen_response_ids = self.tokenizer(chosen_response, return_tensors="pt")["input_ids"][0] rejected_response_ids = self.tokenizer(rejected_response, return_tensors="pt")["input_ids"][0] if self.add_eos: chosen_response_ids = torch.cat((chosen_response_ids, torch.tensor([self.tokenizer.eos_token_id])), dim=-1) rejected_response_ids = torch.cat( (rejected_response_ids, torch.tensor([self.tokenizer.eos_token_id])), dim=-1 ) chosen_input_ids = torch.cat((prompt_ids, chosen_response_ids), dim=-1) chosen_attention_mask = torch.ones_like(chosen_input_ids) rejected_input_ids = torch.cat((prompt_ids, rejected_response_ids), dim=-1) rejected_attention_mask = torch.ones_like(rejected_input_ids) chosen_input_ids, chosen_attention_mask = self._pad_to_length(chosen_input_ids, chosen_attention_mask) rejected_input_ids, rejected_attention_mask = self._pad_to_length(rejected_input_ids, rejected_attention_mask) input_ids = torch.stack((chosen_input_ids, rejected_input_ids), dim=0) attention_mask = torch.stack((chosen_attention_mask, rejected_attention_mask), dim=0) return { "input_ids": input_ids, "attention_mask": attention_mask, }
verl__utils__dataset__rm_dataset.py