[
  {
    "path": "readme.md",
    "content": "# \n<div align=\"center\">\n\n# ToRL: Scaling Tool-Integrated RL\n\n</div>\n\n<p align=\"center\">\n  📄 <a href=\"https://arxiv.org/pdf/2503.23383\" target=\"_blank\">Paper</a> &nbsp; | &nbsp;\n  🌐 <a href=\"https://github.com/GAIR-NLP/ToRL/tree/main/data/torl_data\" target=\"_blank\">Dataset</a> &nbsp; | &nbsp;\n  📘 <a href=\"https://huggingface.co/GAIR/ToRL-7B\" target=\"_blank\">Model</a>\n</p>\n\n\n<div align=\"center\">\n<img src=\"assets/abstract_aime.png\" width=\"700\" alt=\"torl-abstarct-1\">\n</div>\n\n> Performance comparison of ToRL versus baseline models(16-step moving). Both plots show AIME24 Accuracy (%) against training steps across 1.5B and 7B models. In both cases, **ToRL(Ours)** significantly outperforms the baseline without tool and Qwen-2.5-Math-Instruct-TIR, achieving up to **12\\%(1.5B)** and **14\\%(7B)** higher.\n\n\n<div align=\"center\">\n<img src=\"assets/abstract_case.png\" width=\"700\" alt=\"torl-abstarct-2\">\n</div>\n\n> **Emergent cognitive behavior** during training. ToRL first cross-validates the tool's output with reasoning results. Upon detecting inconsistencies, it engages in reflection and further verification through tool calls.\n\n\n## Releases\n\n[2025/03/28] We're releasing the following components:\n\n- 🚀 **Training**: Complete implementation of our training pipeline\n- 🔥 **[ToRL Dataset](https://github.com/GAIR-NLP/ToRL/tree/main/data/torl_data)**: Our curated dataset of 28k mathematical questions\n- 🤖 **[ToRL Model](https://huggingface.co/GAIR/ToRL)**: Model training with ToRL.\n\n## Overview\n\nThis repository presents **ToRL (Tool-Integrated Reinforcement Learning)**, a framework that challenges traditional approaches to tool integration in language models by enabling LLMs to autonomously discover and refine tool usage strategies through reinforcement learning. Unlike prior methods constrained by supervised fine-tuning or predefined tool patterns, ToRL demonstrates that **exploration-driven learning** with computational tools can unlock emergent cognitive behaviors and achieve state-of-the-art performance on complex reasoning tasks. Notably, our approach operates directly from base models without imitation learning, achieving **43.3% accuracy on AIME2024** with a 7B model—matching the performance of larger 32B models trained with RL.  \n\n\n### Key Findings  \n- **Autonomous Tool Integration**: Models learn **when and how** to invoke tools (e.g., code interpreters) through RL-driven exploration, eliminating dependency on human-curated tool usage patterns.  \n- **Emergent Cognitive Abilities**:  \n  - Self-correction by cross-validating code execution results with reasoning steps  \n  - Adaptive strategy selection between tool-based and pure-reasoning approaches  \n  - Self-regulation of ineffective tool calls without explicit supervision  \n\n### ToRL Performance\n1.5B Model Performance across challenging mathematical benchmarks:\n\n| Model                            | SFT/RL | Tool | AIME24 | AIME25 | MATH500 | Olympiad | AMC23 | Avg   |\n|----------------------------------|--------|------|--------|--------|---------|----------|-------|-------|\n| Qwen2.5-Math-1.5B-Instruct       | RL     | ❌    | 10.0   | 10.0   | 66.0    | 31.0     | 62.5  | 35.9  |\n| Qwen2.5-Math-1.5B-Instruct-TIR   | RL     |  ✅    | 13.3   | 13.3   | 73.8    | 41.3     | 55.0  | 41.3  |\n| **ToRL-1.5B(Ours)**              | RL     |  ✅    | **26.7 (+13.3)** | **26.7 (+13.3)** | **77.8 (+3.0)** | **44.0 (+2.7)** | **67.5 (+5.0)** | **48.5 (+7.2)** |\n\n\n7B Model Performance across challenging mathematical benchmarks:\n| Model                            | SFT/RL | Tool | AIME24 | AIME25 | MATH500 | Olympiad | AMC23 | Avg   |\n|----------------------------------|--------|------|--------|--------|---------|----------|-------|-------|\n| Qwen2.5-Math-7B-Instruct         | RL     | ❌    | 10.0   | 16.7   | 74.8    | 32.4     | 65.0  | 39.8  |\n| Qwen2.5-Math-7B-Instruct-TIR     | RL     |  ✅    | 26.7   | 16.7   | 78.8    | 45.0     | 70.0  | 47.4  |\n| SimpleRL-Zero                     | RL     | ❌    | 33.3   | 6.7    | 77.2    | 37.6     | 62.5  | 43.5  |\n| rStar-Math-7B                    | SFT    | ❌    | 26.7   | -      | 78.4    | 47.1     | 47.5  | -     |\n| Eurus-2-7B-PRIME                  | RL     | ❌    | 26.7   | 13.3   | 79.2    | 42.1     | 57.4  | 43.1  |\n| **ToRL-7B(Ours)**                 | RL     |  ✅    | **43.3 (+10.0)** | **30.0 (+13.3)** | **82.2 (+3.0)** | **49.9 (+2.8)** | **75.0 (+5.0)** | **62.1 (+14.7)** |\n\n### Cognitive Behavior via RL Scaling\n\nIn the left figure, the code initially generate by the model encountered an execution error, then it is corrected by model and is successfully executed.\n\nIn the right figure, the model first derives an incorrect result based on natural language reasoning, then discovers the error during code verification and makes corrections\n\n<div style=\"display: flex; justify-content: center; gap: 20px;\">\n    <img src=\"assets/case1.png\" width=\"350\" alt=\"cases\">\n    <img src=\"assets/case2.png\" width=\"350\" alt=\"cases2\">\n</div>\n\n\n\n\n## Quick Start\n\n### Preparing the Sandbox Environment  \nAccording to the instructions provided in [https://github.com/bytedance/SandboxFusion](https://github.com/bytedance/SandboxFusion), install SandboxFusion and launch it.  \n\n```\n# The following command can be used to install the sandbox environment \n# to avoid dependency conflicts.  \n# The sandbox environment must be named \"sandbox-runtime\".  \nconda create -n sandbox-runtime python==3.11  \npip install -r runtime/python/requirement.txt  \n\npip install poetry  \npoetry install  \nmkdir -p docs/build  \nmake run-online  \n```  \n\nReplace the `sandbox_url` on line `109` of `verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py` with the your sandbox.  \n\n### Environment setup\n```\npip install -r requirements.txt\npip install wandb jsonlines math-verify hydra-core==1.4.0.dev1 sortedcontainers qwen-agent[code_interpreter] qwen-agent[python_executor]\n```\n\n### Training\n\nExecute `bash scripts/torl_1.5b` to run ToRL.\n\n\n## Acknowledgements\n\nOur work builds upon the insightful technical reports from [DeepSeek R1](https://github.com/deepseek-ai/DeepSeek-R1) and [Kimi-k1.5](https://github.com/MoonshotAI/Kimi-k1.5) teams. We extend our appreciation to the [Qwen-Math](https://github.com/QwenLM/Qwen2.5-Math) team for their open-source model, to the creators of [VeRL](https://github.com/volcengine/verl) and [vLLM](https://github.com/vllm-project/vllm) for providing the essential reinforcement learning framework and inference infrastructure, respectively, that enabled this research. and to the [Qwen-Agent](https://github.com/QwenLM/Qwen-Agent) and [Sandbox Fusion](https://github.com/bytedance/SandboxFusion) team, which provided the necessary tools for our research.\n\n## Citation\n\nIf you find this work useful, please cite our paper:\n\n```bibtex\n@misc{li2025torlscalingtoolintegratedrl,\n      title={ToRL: Scaling Tool-Integrated RL}, \n      author={Xuefeng Li and Haoyang Zou and Pengfei Liu},\n      year={2025},\n      eprint={2503.23383},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL},\n      url={https://arxiv.org/abs/2503.23383}, \n}\n```\n"
  },
  {
    "path": "requirements.txt",
    "content": "accelerate==1.5.2\naiohappyeyeballs==2.6.1\naiohttp==3.11.14\naiohttp-cors==0.8.0\naiosignal==1.3.2\nairportsdata==20250224\nannotated-types==0.7.0\nantlr4-python3-runtime==4.9.3\nanyio==4.9.0\nastor==0.8.1\nasync-timeout==5.0.1\nattrs==25.3.0\nblake3==1.0.4\ncachetools==5.5.2\ncertifi==2025.1.31\ncharset-normalizer==3.4.1\nclick==8.1.8\ncloudpickle==3.1.1\ncodetiming==1.4.0\ncolorful==0.5.6\ncompressed-tensors==0.9.2\ncupy-cuda12x==13.4.1\ndatasets==3.4.1\ndepyf==0.18.0\ndill==0.3.8\ndiskcache==5.6.3\ndistlib==0.3.9\ndistro==1.9.0\ndnspython==2.7.0\ndocker-pycreds==0.4.0\neinops==0.8.1\nemail_validator==2.2.0\nexceptiongroup==1.2.2\nfastapi==0.115.11\nfastapi-cli==0.0.7\nfastrlock==0.8.3\nfilelock==3.18.0\nflash_attn==2.7.4.post1\nfrozenlist==1.5.0\nfsspec==2024.12.0\ngguf==0.10.0\ngitdb==4.0.12\nGitPython==3.1.44\ngoogle-api-core==2.24.2\ngoogle-auth==2.38.0\ngoogleapis-common-protos==1.69.2\ngrpcio==1.71.0\nh11==0.14.0\nhttpcore==1.0.7\nhttptools==0.6.4\nhttpx==0.28.1\nhuggingface-hub==0.29.3\nhydra-core==1.3.2\nidna==3.10\nimportlib_metadata==8.6.1\ninteregular==0.3.3\nJinja2==3.1.6\njiter==0.9.0\njsonschema==4.23.0\njsonschema-specifications==2024.10.1\nlark==1.2.2\nliger_kernel==0.5.5\nllvmlite==0.43.0\nlm-format-enforcer==0.10.11\nmarkdown-it-py==3.0.0\nMarkupSafe==3.0.2\nmdurl==0.1.2\nmistral_common==1.5.4\nmpmath==1.3.0\nmsgpack==1.1.0\nmsgspec==0.19.0\nmultidict==6.2.0\nmultiprocess==0.70.16\nnest-asyncio==1.6.0\nnetworkx==3.4.2\nninja==1.11.1.4\nnumba==0.60.0\nnumpy==1.26.4\nnvidia-cublas-cu12==12.4.5.8\nnvidia-cuda-cupti-cu12==12.4.127\nnvidia-cuda-nvrtc-cu12==12.4.127\nnvidia-cuda-runtime-cu12==12.4.127\nnvidia-cudnn-cu12==9.1.0.70\nnvidia-cufft-cu12==11.2.1.3\nnvidia-curand-cu12==10.3.5.147\nnvidia-cusolver-cu12==11.6.1.9\nnvidia-cusparse-cu12==12.3.1.170\nnvidia-cusparselt-cu12==0.6.2\nnvidia-nccl-cu12==2.21.5\nnvidia-nvjitlink-cu12==12.4.127\nnvidia-nvtx-cu12==12.4.127\nomegaconf==2.3.0\nopenai==1.68.2\nopencensus==0.11.4\nopencensus-context==0.1.3\nopencv-python-headless==4.11.0.86\norjson==3.10.15\noutlines==0.1.11\noutlines_core==0.1.26\npackaging==24.2\npandas==2.2.3\npartial-json-parser==0.2.1.1.post5\npeft==0.15.0\npillow==11.1.0\nplatformdirs==4.3.7\nprometheus-fastapi-instrumentator==7.1.0\nprometheus_client==0.21.1\npropcache==0.3.0\nproto-plus==1.26.1\nprotobuf==5.29.4\npsutil==7.0.0\npy-cpuinfo==9.0.0\npy-spy==0.4.0\npyarrow==19.0.1\npyasn1==0.6.1\npyasn1_modules==0.4.1\npybind11==2.13.6\npycountry==24.6.1\npydantic==2.10.6\npydantic_core==2.27.2\nPygments==2.19.1\npylatexenc==2.10\npython-dateutil==2.9.0.post0\npython-dotenv==1.0.1\npython-json-logger==3.3.0\npython-multipart==0.0.20\npytz==2025.1\nPyYAML==6.0.2\npyzmq==26.3.0\nray==2.44.0\nreferencing==0.36.2\nregex==2024.11.6\nrequests==2.32.3\nrich==13.9.4\nrich-toolkit==0.13.2\nrpds-py==0.23.1\nrsa==4.9\nsafetensors==0.5.3\nscipy==1.15.2\nsentencepiece==0.2.0\nsentry-sdk==2.24.0\nsetproctitle==1.3.5\nshellingham==1.5.4\nsix==1.17.0\nsmart-open==7.1.0\nsmmap==5.0.2\nsniffio==1.3.1\nstarlette==0.46.1\nsympy==1.13.1\ntensordict==0.6.0\ntiktoken==0.9.0\ntokenizers==0.21.1\ntorch==2.6.0\ntorchaudio==2.6.0\ntorchdata==0.11.0\ntorchvision==0.21.0\ntqdm==4.67.1\ntransformers==4.50.0\ntriton==3.2.0\ntyper==0.15.2\ntyping_extensions==4.12.2\ntzdata==2025.1\nurllib3==2.3.0\nuvicorn==0.34.0\nuvloop==0.21.0\nvirtualenv==20.29.3\nvllm==0.8.1\nwandb==0.19.8\nwatchfiles==1.0.4\nwebsockets==15.0.1\nwrapt==1.17.2\nxformers==0.0.29.post2\nxgrammar==0.1.16\nxxhash==3.5.0\nyarl==1.18.3\nzipp==3.21.0\n"
  },
  {
    "path": "scripts/torl_1.5b.sh",
    "content": "policy_path=Qwen/Qwen2.5-Math-1.5B\nrollout_batch_size=128\nn_samples_per_prompts=16\nepisode=300\ntemperature=1.0\nbatch_size=1024\nlr=1e-6\nkl_loss_coef=0.0\nkl_coef=0.0\nentropy_coeff=0\nmax_gen_length=3072\nnumcall=1\ndataset_name=torl_data\nrun_name=rl.grpo_qwen.math.1.5b_${dataset_name}_numcall${numcall}\ndata_path=../data/${dataset_name}\nsamples_save_path=../data/samples/$run_name\n\npython3 -m verl.trainer.main_ppo \\\n    algorithm.adv_estimator=grpo \\\n    data.train_files=$data_path/train.parquet \\\n    data.val_files=$data_path/test.parquet \\\n    data.train_batch_size=$rollout_batch_size \\\n    data.val_batch_size=2048 \\\n    data.max_prompt_length=400 \\\n    data.max_response_length=$max_gen_length \\\n    data.template_type=tir_base_0309 \\\n    actor_rollout_ref.model.path=$policy_path \\\n    actor_rollout_ref.actor.optim.lr=$lr \\\n    actor_rollout_ref.model.use_remove_padding=True \\\n    actor_rollout_ref.actor.ppo_mini_batch_size=$batch_size \\\n    actor_rollout_ref.actor.use_dynamic_bsz=True \\\n    actor_rollout_ref.actor.use_kl_loss=True \\\n    actor_rollout_ref.actor.kl_loss_coef=$kl_loss_coef \\\n    actor_rollout_ref.actor.kl_loss_type=low_var_kl \\\n    actor_rollout_ref.actor.entropy_coeff=$entropy_coeff \\\n    actor_rollout_ref.model.enable_gradient_checkpointing=True \\\n    actor_rollout_ref.actor.fsdp_config.param_offload=True \\\n    actor_rollout_ref.actor.fsdp_config.optimizer_offload=True \\\n    actor_rollout_ref.rollout.tensor_model_parallel_size=1 \\\n    actor_rollout_ref.rollout.name=vllm \\\n    actor_rollout_ref.rollout.num_llm_calls_available=$numcall \\\n    actor_rollout_ref.rollout.temperature=$temperature \\\n    actor_rollout_ref.rollout.top_p=1.0 \\\n    actor_rollout_ref.rollout.gpu_memory_utilization=0.85 \\\n    actor_rollout_ref.rollout.n=$n_samples_per_prompts \\\n    actor_rollout_ref.rollout.log_prob_use_dynamic_bsz=True \\\n    actor_rollout_ref.rollout.max_num_seqs=1024 \\\n    actor_rollout_ref.ref.log_prob_use_dynamic_bsz=True \\\n    actor_rollout_ref.ref.fsdp_config.param_offload=True \\\n    algorithm.kl_ctrl.kl_coef=$kl_coef \\\n    trainer.logger=['console','wandb'] \\\n    trainer.project_name=torl \\\n    trainer.experiment_name=${run_name} \\\n    trainer.n_gpus_per_node=8 \\\n    trainer.nnodes=1 \\\n    trainer.save_freq=20 \\\n    trainer.test_freq=4 \\\n    trainer.default_local_dir=path_to_save/${run_name} \\\n    trainer.resume_mode=auto \\\n    trainer.samples_save_path=$samples_save_path \\\n    trainer.total_epochs=$episode $@"
  },
  {
    "path": "verl/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\n\nversion_folder = os.path.dirname(os.path.join(os.path.abspath(__file__)))\n\nwith open(os.path.join(version_folder, 'version/version')) as f:\n    __version__ = f.read().strip()\n\nfrom .protocol import DataProto\n\nfrom .utils.logging_utils import set_basic_config\nimport logging\n\nset_basic_config(level=logging.WARNING)\n\nfrom . import single_controller\n\n__all__ = ['DataProto', \"__version__\"]\n\nif os.getenv('VERL_USE_MODELSCOPE', 'False').lower() == 'true':\n    import importlib\n    if importlib.util.find_spec(\"modelscope\") is None:\n        raise ImportError(f'You are using the modelscope hub, please install modelscope by `pip install modelscope -U`')\n    # Patch hub to download models from modelscope to speed up.\n    from modelscope.utils.hf_util import patch_hub\n    patch_hub()\n"
  },
  {
    "path": "verl/models/README.md",
    "content": "# Models\nCommon modelzoo such as huggingface/transformers stuggles when using Pytorch native model parallelism. Following the design principle of vLLM, we keep a simple, parallelizable, highly-optimized with packed inputs in verl. \n## Adding a New Huggingface Model\n### Step 1: Copy the model file from HF to verl\n- Add a new file under verl/models/hf\n- Copy ONLY the model file from huggingface/transformers/models to verl/models/hf\n\n### Step 2: Modify the model file to use packed inputs\n- Remove all the code related to inference (kv cache)\n- Modify the inputs to include only\n    - input_ids (total_nnz,)\n    - cu_seqlens (total_nnz + 1,)\n    - max_seqlen_in_batch: int\n- Note that this requires using flash attention with causal mask.\n\n### Step 2.5: Add tests\n- Add a test to compare this version and the huggingface version\n- Following the infrastructure and add tests to tests/models/hf\n\n### Step 3: Add a function to apply tensor parallelism\n- Please follow\n    - https://pytorch.org/docs/stable/distributed.tensor.parallel.html\n    - https://pytorch.org/tutorials/intermediate/TP_tutorial.html\n- General comments\n    - Tensor Parallelism in native Pytorch is NOT auto-parallelism. The way it works is to specify how model parameters and input/output reshards using configs. These configs are then registered as hooks to perform input/output resharding before/after model forward.\n\n### Step 4: Add a function to apply data parallelism\n- Please use FSDP2 APIs\n- See demo here https://github.com/pytorch/torchtitan/blob/main/torchtitan/parallelisms/parallelize_llama.py#L413\n\n### Step 5: Add a function to apply pipeline parallelism\n- Comes in Pytorch 2.4\n- Currently only in alpha in nightly version\n- Check torchtitan for more details\n\n"
  },
  {
    "path": "verl/models/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/models/llama/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/models/llama/megatron/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .modeling_llama_megatron import (\n    # original model with megatron\n    ParallelLlamaModel,\n    ParallelLlamaForCausalLM,\n    # rmpad with megatron\n    ParallelLlamaForCausalLMRmPad,\n    ParallelLlamaForValueRmPad,\n    # rmpad with megatron and pipeline parallelism\n    ParallelLlamaForCausalLMRmPadPP,\n    ParallelLlamaForValueRmPadPP)\n"
  },
  {
    "path": "verl/models/llama/megatron/checkpoint_utils/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/models/llama/megatron/checkpoint_utils/llama_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport importlib\nfrom packaging.version import Version\nimport torch\nimport time\nfrom typing import Dict, Any, Callable, Optional\nimport torch.distributed as dist\n\n\ndef _megatron_calc_layer_map(config):\n    \"\"\"Calculate the mapping of global layer_idx to local layer_idx\n    Returns:\n        layer_map (Dict: int -> tuple(int, int, int)):\n            mapping from the global layer index to\n            a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model)\n    \"\"\"\n    import megatron\n    from megatron.core import mpu\n\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n\n    layer_map = dict()\n    num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n    assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n    for pp_rank_idx in range(pp_size):\n        for virtual_pp_rank_idx in range(virtual_pp_size):\n            layer_offset = (virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) +\n                            pp_rank_idx * num_layers_per_model)\n            for layer_idx in range(num_layers_per_model):\n                layer_map[layer_offset + layer_idx] = (\n                    pp_rank_idx,\n                    virtual_pp_rank_idx,\n                    layer_idx,\n                )\n    return layer_map\n\n\ndef load_state_dict_to_megatron_llama(state_dict, wrapped_models, config, params_dtype, is_value_model=False):\n    \"\"\"Load merged state_dict to sharded Megatron module in training.\n    \"\"\"\n    import megatron\n    from megatron.core import mpu\n    from megatron.training.utils import print_rank_0, unwrap_model\n    from megatron.core.transformer.module import Float16Module\n    from megatron.core import DistributedDataParallel as LocalDDP\n    from torch.nn.parallel import DistributedDataParallel as torchDDP\n\n    start_time = time.time()\n\n    def _get_gpt_model(model):\n        return model\n\n    def broadcast_params(module):\n        for param in module.parameters():\n            torch.distributed.broadcast(param.data,\n                                        src=mpu.get_data_parallel_src_rank(),\n                                        group=mpu.get_data_parallel_group())\n\n    dp_rank = mpu.get_data_parallel_rank()\n    pp_rank = mpu.get_pipeline_model_parallel_rank()\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n    mp_group = mpu.get_model_parallel_group()\n\n    if torch.distributed.get_rank() == 0:\n        assert mp_group.rank() == 0, f\"mp_rank:[{mp_group.rank}] != 0 on rank #0\"\n        assert pp_rank == 0, f\"pp_rank:[{pp_rank}] != 0 on rank #0\"\n        assert dp_rank == 0, f\"dp_rank:[{dp_rank}] != 0 on rank #0\"\n\n    if not isinstance(wrapped_models, (list, tuple)):\n        wrapped_models = list(wrapped_models)\n\n    assert len(wrapped_models) == virtual_pp_size\n    num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n    assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n    models = [None] * len(wrapped_models)\n\n    for i, wrapped_model in enumerate(wrapped_models):\n        models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module))\n        gpt_model_module = _get_gpt_model(models[i])\n        assert len(gpt_model_module.model.layers) == num_layers_per_model\n\n    def _broadcast_tensor(tensor, name) -> torch.Tensor:\n        \"\"\"broadcast tensor from rank0 across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        if torch.distributed.get_rank() == 0:\n            if name in state_dict:\n                weight = state_dict[name]\n                tensor_shape = weight.shape\n            else:\n                tensor_shape = None\n        else:\n            weight = None\n            tensor_shape = None\n\n        obj_list = [tensor_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        tensor_shape = obj_list[0]\n\n        if tensor_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tensor:[{name}] not in state_dict, skip load\")\n            return\n\n        if tensor is None:\n            tensor = torch.empty(\n                tensor_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        if torch.distributed.get_rank() == 0:\n            tensor.data.copy_(weight)\n        dist.broadcast(tensor, src=0, group=mp_group)\n\n    def _broadcast_tp_shard_tensor_vocab(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        if torch.distributed.get_rank() == 0:\n            if name in state_dict:\n                full_weight = state_dict[name]\n\n                if mutate_func is not None:\n                    full_weight = mutate_func(full_weight)\n                tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim)\n                chunk_shape = tensor_chunk[0].shape\n            else:\n                chunk_shape = None\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{name}] not in state_dict, skip loading\")\n            return\n\n        if tensor is None:\n            sync_tensor = torch.empty(\n                chunk_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        else:\n            assert (tensor.shape == chunk_shape\n                   ), f\"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}\"\n            sync_tensor = torch.empty_like(tensor, device=torch.cuda.current_device(), requires_grad=False)\n\n        for i in range(tp_size):\n            if torch.distributed.get_rank() == 0:\n                sync_tensor.data.copy_(tensor_chunk[i])\n            dist.broadcast(sync_tensor, src=0, group=mp_group)\n            if (i == tp_rank) and (tensor is not None):\n                tensor.data.copy_(sync_tensor)\n\n    def _broadcast_tp_shard_tensor(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        if torch.distributed.get_rank() == 0:\n            if name in state_dict:\n                full_weight = state_dict[name]\n                if mutate_func is not None:\n                    full_weight = mutate_func(full_weight)\n                tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim)\n                chunk_shape = tensor_chunk[0].shape\n            else:\n                chunk_shape = None\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{name}] not in state_dict, skip loading\")\n            return\n\n        if tensor is None:\n            sync_tensor = torch.empty(\n                chunk_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        else:\n            assert (tensor.shape == chunk_shape\n                   ), f\"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}\"\n            sync_tensor = torch.empty_like(tensor, device=torch.cuda.current_device(), requires_grad=False)\n\n        for i in range(tp_size):\n            if torch.distributed.get_rank() == 0:\n                sync_tensor.data.copy_(tensor_chunk[i])\n            dist.broadcast(sync_tensor, src=0, group=mp_group)\n            if (i == tp_rank) and (tensor is not None):\n                tensor.data.copy_(sync_tensor)\n\n    def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        if torch.distributed.get_rank() == 0:\n            gate_weight = state_dict[gate_name]\n            up_weight = state_dict[up_name]\n            new_gate_up_weight = torch.empty(config.intermediate_size * 2,\n                                             config.hidden_size,\n                                             dtype=params_dtype,\n                                             device=torch.cuda.current_device())\n            for i in range(tp_size):\n                intermediate_size_tp = config.intermediate_size // tp_size\n                gate_weight_tp = gate_weight[i * intermediate_size_tp:(i + 1) * intermediate_size_tp]\n                up_weight_tp = up_weight[i * intermediate_size_tp:(i + 1) * intermediate_size_tp]\n                new_gate_up_weight[intermediate_size_tp * 2 * i:intermediate_size_tp * 2 * (i + 1)].copy_(\n                    torch.cat([gate_weight_tp, up_weight_tp], dim=0))\n\n            tensor_chunk = torch.chunk(new_gate_up_weight, tp_size, dim=0)\n            chunk_shape = tensor_chunk[0].shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{gate_name, up_name}] not in state_dict, skip loading\")\n            return\n\n        if tensor is None:\n            sync_tensor = torch.empty(\n                chunk_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        else:\n            assert (\n                tensor.shape == chunk_shape\n            ), f\"rank #{torch.distributed.get_rank() == 0:} tensor {gate_name, up_name} shape {tensor.shape} != {chunk_shape}\"\n            sync_tensor = torch.empty_like(tensor, device=torch.cuda.current_device(), requires_grad=False)\n\n        for i in range(tp_size):\n            if torch.distributed.get_rank() == 0:\n                sync_tensor.data.copy_(tensor_chunk[i])\n            dist.broadcast(sync_tensor, src=0, group=mp_group)\n            if (i == tp_rank) and (tensor is not None):\n                tensor.data.copy_(sync_tensor)\n\n    def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        if torch.distributed.get_rank() == 0:\n            assert (q_name in state_dict and k_name in state_dict and v_name in state_dict)\n            full_weight_q = state_dict[q_name]\n            full_weight_k = state_dict[k_name]\n            full_weight_v = state_dict[v_name]\n\n            hidden_size_per_head = config.hidden_size // config.num_attention_heads\n\n            if config.num_key_value_heads >= tp_size:\n                q_size_tp = config.hidden_size // tp_size\n                kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size\n                total_size = q_size_tp + 2 * kv_size_tp\n                new_weight_qkv = torch.empty(total_size * tp_size,\n                                             config.hidden_size,\n                                             dtype=params_dtype,\n                                             device=torch.cuda.current_device())\n                for i in range(tp_size):\n                    q_part = full_weight_q[i * q_size_tp:(i + 1) * q_size_tp]\n                    k_part = full_weight_k[i * kv_size_tp:(i + 1) * kv_size_tp]\n                    v_part = full_weight_v[i * kv_size_tp:(i + 1) * kv_size_tp]\n                    new_weight_qkv[i * total_size:(i + 1) * total_size].copy_(torch.cat([q_part, k_part, v_part],\n                                                                                        dim=0))\n\n            else:\n                q_size_tp = config.hidden_size // tp_size\n                kv_size_tp = hidden_size_per_head\n                total_size = q_size_tp + 2 * kv_size_tp\n                new_weight_qkv = torch.empty(total_size * tp_size,\n                                             config.hidden_size,\n                                             dtype=params_dtype,\n                                             device=torch.cuda.current_device())\n                for i in range(tp_size):\n                    q_part = full_weight_q[i * q_size_tp:(i + 1) * q_size_tp]\n                    start_idx = i * config.num_key_value_heads // tp_size * hidden_size_per_head\n                    end_idx = (i * config.num_key_value_heads // tp_size + 1) * hidden_size_per_head\n                    k_part = full_weight_k[start_idx:end_idx]\n                    v_part = full_weight_v[start_idx:end_idx]\n                    new_weight_qkv[i * total_size:(i + 1) * total_size].copy_(torch.cat([q_part, k_part, v_part],\n                                                                                        dim=0))\n\n            tensor_chunk = torch.chunk(new_weight_qkv, tp_size, dim=0)\n            chunk_shape = tensor_chunk[0].shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{name}] not in state_dict, skip loading\")\n            return\n\n        if tensor is None:\n            sync_tensor = torch.empty(\n                chunk_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        else:\n            assert (tensor.shape == chunk_shape\n                   ), f\"rank #{torch.distributed.get_rank()} tensor {q_name} shape {tensor.shape} != {chunk_shape}\"\n            sync_tensor = torch.empty_like(tensor, device=torch.cuda.current_device(), requires_grad=False)\n\n        for i in range(tp_size):\n            if torch.distributed.get_rank() == 0:\n                sync_tensor.data.copy_(tensor_chunk[i])\n            dist.broadcast(sync_tensor, src=0, group=mp_group)\n            if (i == tp_rank) and (tensor is not None):\n                tensor.data.copy_(sync_tensor)\n\n    if dp_rank == 0:\n        # Embeddings\n        # -------------------\n        print_rank_0(\"loading embeddings...\")\n        gpt_model_module = _get_gpt_model(models[0])\n        embed_tokens_weight = None\n        if pp_rank == 0:\n            embed_tokens_weight = gpt_model_module.model.embed_tokens.weight\n        _broadcast_tp_shard_tensor_vocab(embed_tokens_weight, \"model.embed_tokens.weight\")\n\n        # Transformer layers\n        # -------------------\n        layer_map = _megatron_calc_layer_map(config)\n\n        for layer in range(config.num_hidden_layers):\n            print_rank_0(f\"loading layer #{layer}...\")\n            layer_name = f\"model.layers.{layer}\"\n            dst_pp_rank, dst_virtual_pp_rank, dst_layer_idx = layer_map[layer]\n\n            gpt_model_module = _get_gpt_model(models[dst_virtual_pp_rank])\n            sync_layer = gpt_model_module.model.layers[dst_layer_idx]\n\n            _broadcast_tensor(\n                sync_layer.input_layernorm.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.input_layernorm.weight\",\n            )\n\n            _broadcast_tp_shard_tensor_qkv(\n                sync_layer.self_attn.qkv_proj.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.self_attn.q_proj.weight\",\n                f\"{layer_name}.self_attn.k_proj.weight\",\n                f\"{layer_name}.self_attn.v_proj.weight\",\n            )\n\n            _broadcast_tp_shard_tensor(\n                sync_layer.self_attn.o_proj.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.self_attn.o_proj.weight\",\n                chunk_dim=1,\n            )\n\n            _broadcast_tensor(\n                sync_layer.post_attention_layernorm.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.post_attention_layernorm.weight\",\n            )\n\n            _broadcast_tp_shard_tensor_gate_up(sync_layer.mlp.gate_up_proj.weight if dst_pp_rank == pp_rank else None,\n                                               f\"{layer_name}.mlp.gate_proj.weight\", f\"{layer_name}.mlp.up_proj.weight\")\n\n            _broadcast_tp_shard_tensor(\n                sync_layer.mlp.down_proj.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.mlp.down_proj.weight\",\n                chunk_dim=1,\n            )\n        # Final Layernorm\n        # -------------------\n        print_rank_0(\"loading final layernorm...\")\n        gpt_model_module = _get_gpt_model(models[-1])\n        _broadcast_tensor(\n            getattr(gpt_model_module.model.norm, \"weight\", None),\n            \"model.norm.weight\",\n        )\n\n        print_rank_0(\"loading lm_head...\")\n        lm_head_weight = None\n        if pp_rank + 1 == pp_size:\n            lm_head_weight = gpt_model_module.lm_head.weight\n\n        if is_value_model:\n            # if torch.distributed.get_rank() == 0:\n            if 'lm_head.weight' in state_dict and state_dict['lm_head.weight'].shape[0] == 1:\n                _broadcast_tensor(lm_head_weight, \"lm_head.weight\")\n            elif 'reward_head.weight' in state_dict and state_dict['reward_head.weight'].shape[0] == 1:\n                _broadcast_tensor(lm_head_weight, \"reward_head.weight\")\n                print_rank_0('load lm_head from value_head weight')\n            else:\n                _broadcast_tensor(None, \"lm_head.weight\")\n                print_rank_0('fail to match lm_head in value_model')\n            # else:\n\n            #     _broadcast_tensor(lm_head_weight, \"lm_head.weight\")\n\n        else:\n            _broadcast_tp_shard_tensor(lm_head_weight, \"lm_head.weight\")\n    dist.barrier()\n    # Broadcast weights inside data parallel groups\n    for wrapped_model in wrapped_models:\n        broadcast_params(wrapped_model)\n\n    torch.cuda.empty_cache()\n    print_rank_0(f\"loading megatron ckpt done, time elapsed {time.time() - start_time}s\")\n"
  },
  {
    "path": "verl/models/llama/megatron/checkpoint_utils/llama_saver.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport importlib\nfrom packaging.version import Version\nfrom torch.nn.parallel import DistributedDataParallel as torchDDP\nimport torch\nimport time\nfrom typing import Optional\nimport torch.distributed as dist\n\nimport megatron\nfrom megatron import get_args\nfrom megatron.core import mpu\nfrom megatron.core.transformer.module import Float16Module\nfrom megatron.core.distributed import DistributedDataParallel as LocalDDP\n\nfrom megatron.training.utils import print_rank_0, unwrap_model\n\n\ndef _megatron_calc_global_rank(tp_rank: int = 0, dp_rank: int = 0, pp_rank: int = 0):\n    \"\"\"given TP,DP,PP rank to get the global rank.\"\"\"\n\n    args = get_args()\n    tp_size = mpu.get_tensor_model_parallel_world_size()\n    dp_size = mpu.get_data_parallel_world_size()\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    assert (tp_size * dp_size * pp_size == torch.distributed.get_world_size()\n           ), f\"{tp_size} x {dp_size} x {pp_size} != {torch.distributed.get_world_size()}\"\n    if args.switch_dp_and_pp_grouping:\n        # TP-PP-DP grouping\n        return (dp_rank * pp_size + pp_rank) * tp_size + tp_rank\n    else:\n        # TP-DP-PP grouping\n        return (pp_rank * dp_size + dp_rank) * tp_size + tp_rank\n\n\ndef _megatron_calc_layer_map(config):\n    \"\"\"Calculate the mapping of global layer_idx to local layer_idx\n    Returns:\n        layer_map (Dict: int -> tuple(int, int, int)):\n            mapping from the global layer index to\n            a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model)\n    \"\"\"\n    import megatron\n    from megatron.core import mpu\n\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n\n    args = megatron.get_args()\n    layer_map = dict()\n    num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n    assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n    for pp_rank_idx in range(pp_size):\n        for virtual_pp_rank_idx in range(virtual_pp_size):\n            layer_offset = (virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) +\n                            pp_rank_idx * num_layers_per_model)\n            for layer_idx in range(num_layers_per_model):\n                layer_map[layer_offset + layer_idx] = (\n                    pp_rank_idx,\n                    virtual_pp_rank_idx,\n                    layer_idx,\n                )\n    return layer_map\n\n\ndef merge_megatron_ckpt_llama(wrapped_models, config, is_value_model=False, dtype='bf16'):\n    \"\"\"Merge sharded parameters of a Megatron module into a merged checkpoint.\n\n    Args:\n        wrapped_models (list of megatron.core.distributed.DistributedDataParallel):\n            The local DDP wrapped megatron modules.\n        dtype (str or None):\n            The data type of state_dict. if None, the data type of the original parameters\n            is used.\n        gpt_model_key: key to access model\n    Returns:\n        state_dict (dict):\n            The merged state_dict in rank 0, and an empty dictionary in other ranks.\n    \"\"\"\n    start_time = time.time()\n    args = megatron.get_args()\n\n    def _get_gpt_model(model):\n        return model\n\n    dp_rank = mpu.get_data_parallel_rank()\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    pp_rank = mpu.get_pipeline_model_parallel_rank()\n    virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n    mp_group = mpu.get_model_parallel_group()\n\n    if dist.get_rank() == 0:\n        assert mp_group.rank() == 0, f\"mp_rank:[{mp_group.rank}] != 0 on rank #0\"\n        assert pp_rank == 0, f\"pp_rank:[{pp_rank}] != 0 on rank #0\"\n        assert dp_rank == 0, f\"dp_rank:[{dp_rank}] != 0 on rank #0\"\n\n    if not isinstance(wrapped_models, (list, tuple)):\n        wrapped_models = list(wrapped_models)\n\n    assert len(wrapped_models) == virtual_pp_size\n    num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n    assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n    models = [None] * len(wrapped_models)\n\n    for i, wrapped_model in enumerate(wrapped_models):\n        models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module))\n        assert len(models[i].model.layers\n                  ) == num_layers_per_model, 'len model layers {} not equal to num_layers_per_model {}'.format(\n                      len(models[i].model.layers), num_layers_per_model)\n\n    state_dict = dict()\n\n    def _get_cpu_tensor(tensor: torch.Tensor):\n        if tensor is None:\n            return None\n        if tensor.device == torch.device(\"cpu\"):\n            return tensor.detach().clone()\n        return tensor.detach().cpu()\n\n    def _broadcast_tensor(tensor, name, src_pp_rank) -> torch.Tensor:\n        \"\"\"broadcast tensor across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n        if torch.distributed.get_rank() == src_rank:\n            if tensor is None:\n                weight = None\n                tensor_shape = None\n            else:\n                weight = tensor\n                tensor_shape = weight.shape\n        else:\n            weight = None\n            tensor_shape = None\n\n        obj_list = [tensor_shape]\n        dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n        tensor_shape = obj_list[0]\n\n        if tensor_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tensor:[{name}] not exist, skip collect\")\n            return\n\n        if weight is None:\n            weight = torch.empty(\n                tensor_shape,\n                dtype=args.params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n\n        dist.broadcast(weight, src=src_rank, group=mp_group)\n\n        if torch.distributed.get_rank() == 0:\n            state_dict[name] = _get_cpu_tensor(weight)\n\n    def _broadcast_tp_shard_tensor(tensor, name, src_pp_rank, concat_dim=0, mutate_func=None) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n        if torch.distributed.get_rank() == src_rank:\n            chunk_shape = tensor.shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{name}] not exist, skip collecting\")\n            return\n\n        buffer_tensor = torch.empty(\n            chunk_shape,\n            dtype=args.params_dtype,\n            device=torch.cuda.current_device(),\n            requires_grad=False,\n        )\n\n        chunk_tensors = [None] * tp_size\n\n        for i in range(tp_size):\n            cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n            sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n            dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n            if torch.distributed.get_rank() == 0:\n                chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n        if torch.distributed.get_rank() == 0:\n            full_tensor = torch.concat(chunk_tensors, dim=concat_dim)\n            if mutate_func is not None:\n                full_tensor = mutate_func(full_tensor)\n            state_dict[name] = full_tensor\n\n    def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name, src_pp_rank) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n        if torch.distributed.get_rank() == src_rank:\n            chunk_shape = tensor.shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{gate_name, up_name}] not exist, skip collecting\")\n            return\n\n        buffer_tensor = torch.empty(\n            chunk_shape,\n            dtype=args.params_dtype,\n            device=torch.cuda.current_device(),\n            requires_grad=False,\n        )\n\n        chunk_tensors = [None] * tp_size\n\n        for i in range(tp_size):\n            cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n            sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n            dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n            if torch.distributed.get_rank() == 0:\n                chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n        if torch.distributed.get_rank() == 0:\n            full_tensor = torch.concat(chunk_tensors, dim=0)\n            intermediate_size_tp = config.intermediate_size // tp_size\n            gate_weight_list = []\n            up_weight_list = []\n            for i in range(tp_size):\n                gate_up_weight_tp = full_tensor[intermediate_size_tp * 2 * i:intermediate_size_tp * 2 * (i + 1)]\n                gate_weight_tp = gate_up_weight_tp[:intermediate_size_tp]\n                up_weight_tp = gate_up_weight_tp[intermediate_size_tp:]\n                gate_weight_list.append(gate_weight_tp)\n                up_weight_list.append(up_weight_tp)\n\n            state_dict[gate_name] = torch.cat(gate_weight_list, dim=0)\n            state_dict[up_name] = torch.cat(up_weight_list, dim=0)\n\n    def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, src_pp_rank):\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n        if torch.distributed.get_rank() == src_rank:\n            chunk_shape = tensor.shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{q_name}] not exist, skip collecting\")\n            return\n\n        buffer_tensor = torch.empty(\n            chunk_shape,\n            dtype=args.params_dtype,\n            device=torch.cuda.current_device(),\n            requires_grad=False,\n        )\n\n        chunk_tensors = [None] * tp_size\n\n        for i in range(tp_size):\n            cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n            sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n            dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n            if torch.distributed.get_rank() == 0:\n                chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n        if torch.distributed.get_rank() == 0:\n            full_tensor = torch.concat(chunk_tensors, dim=0)\n            q_weight_list = []\n            k_weight_list = []\n            v_weight_list = []\n            hidden_size_per_head = config.hidden_size // config.num_attention_heads\n\n            if config.num_key_value_heads >= tp_size:\n                q_size_tp = config.hidden_size // tp_size\n                kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size\n                total_size = q_size_tp + 2 * kv_size_tp\n                for i in range(tp_size):\n                    qkv_part = full_tensor[i * total_size:(i + 1) * total_size]\n                    q_part = qkv_part[:q_size_tp]\n                    k_part = qkv_part[q_size_tp:q_size_tp + kv_size_tp]\n                    v_part = qkv_part[q_size_tp + kv_size_tp:total_size]\n                    q_weight_list.append(q_part)\n                    k_weight_list.append(k_part)\n                    v_weight_list.append(v_part)\n            else:\n                q_size_tp = config.hidden_size // tp_size\n                kv_size_tp = hidden_size_per_head\n                total_size = q_size_tp + 2 * kv_size_tp\n                for i in range(tp_size):\n                    qkv_part = full_tensor[i * total_size:(i + 1) * total_size]\n                    q_part = qkv_part[:q_size_tp]\n                    k_part = qkv_part[q_size_tp:q_size_tp + kv_size_tp]\n                    v_part = qkv_part[q_size_tp + kv_size_tp:total_size]\n                    q_weight_list.append(q_part)\n                    if i * config.num_key_value_heads % tp_size == 0:\n                        k_weight_list.append(k_part)\n                        v_weight_list.append(v_part)\n\n            state_dict[q_name] = torch.cat(q_weight_list, dim=0)\n            state_dict[k_name] = torch.cat(k_weight_list, dim=0)\n            state_dict[v_name] = torch.cat(v_weight_list, dim=0)\n\n    # empty cache before collecting weights\n    torch.cuda.empty_cache()\n    # Embeddings\n    # -------------------\n    if dp_rank == 0:\n        # Embeddings\n        # -------------------\n        print_rank_0(\"collecting embeddings...\")\n        gpt_model_module = _get_gpt_model(models[0])\n        _broadcast_tp_shard_tensor(\n            gpt_model_module.model.embed_tokens.weight if pp_rank == 0 else None,\n            \"model.embed_tokens.weight\",\n            src_pp_rank=0,\n        )\n\n        # Transformer layers\n        # -------------------\n        layer_map = _megatron_calc_layer_map(config)\n        for layer in range(config.num_hidden_layers):\n            print_rank_0(f\"collecting layer #{layer}...\")\n            layer_name = f\"model.layers.{layer}\"\n            src_pp_rank, src_virtual_pp_rank, src_layer_idx = layer_map[layer]\n\n            gpt_model_module = _get_gpt_model(models[src_virtual_pp_rank])\n            sync_layer = gpt_model_module.model.layers[src_layer_idx]\n\n            _broadcast_tensor(\n                sync_layer.input_layernorm.weight,\n                f\"{layer_name}.input_layernorm.weight\",\n                src_pp_rank=src_pp_rank,\n            )\n\n            _broadcast_tp_shard_tensor_qkv(\n                sync_layer.self_attn.qkv_proj.weight,\n                f\"{layer_name}.self_attn.q_proj.weight\",\n                f\"{layer_name}.self_attn.k_proj.weight\",\n                f\"{layer_name}.self_attn.v_proj.weight\",\n                src_pp_rank=src_pp_rank,\n            )\n\n            _broadcast_tp_shard_tensor(\n                sync_layer.self_attn.o_proj.weight,\n                f\"{layer_name}.self_attn.o_proj.weight\",\n                concat_dim=1,\n                src_pp_rank=src_pp_rank,\n            )\n\n            _broadcast_tensor(\n                sync_layer.post_attention_layernorm.weight,\n                f\"{layer_name}.post_attention_layernorm.weight\",\n                src_pp_rank=src_pp_rank,\n            )\n\n            _broadcast_tp_shard_tensor_gate_up(sync_layer.mlp.gate_up_proj.weight,\n                                               f\"{layer_name}.mlp.gate_proj.weight\",\n                                               f\"{layer_name}.mlp.up_proj.weight\",\n                                               src_pp_rank=src_pp_rank)\n\n            _broadcast_tp_shard_tensor(\n                sync_layer.mlp.down_proj.weight,\n                f\"{layer_name}.mlp.down_proj.weight\",\n                concat_dim=1,\n                src_pp_rank=src_pp_rank,\n            )\n\n        # Final Layernorm\n        # -------------------\n        print_rank_0(\"collecting final layernorm...\")\n        gpt_model_module = _get_gpt_model(models[-1])\n        _broadcast_tensor(\n            getattr(gpt_model_module.model.norm, \"weight\", None),\n            \"model.norm.weight\",\n            src_pp_rank=pp_size - 1,\n        )\n\n        print_rank_0(\"collecting lm_head...\")\n\n        if is_value_model:\n            _broadcast_tensor(getattr(gpt_model_module.lm_head, \"weight\", None) if pp_rank == pp_size - 1 else None,\n                              \"reward_head.weight\",\n                              src_pp_rank=pp_size - 1)\n\n        else:\n            _broadcast_tp_shard_tensor(\n                getattr(gpt_model_module.lm_head, \"weight\", None) if pp_rank == pp_size - 1 else None,\n                \"lm_head.weight\",\n                src_pp_rank=pp_size - 1,\n            )\n\n    dist.barrier()\n\n    torch.cuda.empty_cache()\n    if torch.distributed.get_rank() == 0:\n        if dtype == \"fp16\":\n            dtype = torch.float16\n        elif dtype == \"bf16\":\n            dtype = torch.bfloat16\n        elif dtype is None or dtype == \"fp32\":\n            dtype = torch.float32\n        else:\n            print(f'Unknown/unsupported dtype to save: {dtype}\"')\n            exit(1)\n        for k, v in state_dict.items():\n            if dtype != v.dtype:\n                state_dict[k] = v.to(dtype)\n\n    print_rank_0(f\"merge megatron ckpt done, time elapsed {time.time() - start_time}s\")\n    return state_dict\n"
  },
  {
    "path": "verl/models/llama/megatron/layers/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .parallel_attention import ParallelLlamaAttention\nfrom .parallel_decoder import ParallelLlamaDecoderLayer, ParallelLlamaDecoderLayerRmPad\nfrom .parallel_mlp import ParallelLlamaMLP\nfrom .parallel_rmsnorm import ParallelLlamaRMSNorm\n"
  },
  {
    "path": "verl/models/llama/megatron/layers/parallel_attention.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nfrom typing import Optional, Tuple\n\nimport torch\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core import tensor_parallel\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers import LlamaConfig\nfrom verl.models.llama.megatron.layers.parallel_linear import QKVParallelLinear\n\nfrom verl.utils.megatron import tensor_parallel as tp_utils\n\n\nclass LlamaRotaryEmbedding(nn.Module):\n\n    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):\n        super().__init__()\n\n        self.dim = dim\n        self.max_position_embeddings = max_position_embeddings\n        self.base = base\n        inv_freq = 1.0 / (self.base**(torch.arange(0, self.dim, 2).float().to(device) / self.dim))\n        self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n\n        # Build here to make `torch.jit.trace` work.\n        self._set_cos_sin_cache(seq_len=max_position_embeddings,\n                                device=self.inv_freq.device,\n                                dtype=torch.get_default_dtype())\n\n    def _set_cos_sin_cache(self, seq_len, device, dtype):\n        self.max_seq_len_cached = seq_len\n        t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)\n\n        freqs = torch.einsum(\"i,j->ij\", t, self.inv_freq)\n        # Different from paper, but it uses a different permutation in order to obtain the same calculation\n        emb = torch.cat((freqs, freqs), dim=-1)\n        self.register_buffer(\"cos_cached\", emb.cos().to(dtype), persistent=False)\n        self.register_buffer(\"sin_cached\", emb.sin().to(dtype), persistent=False)\n\n    def forward(self, x, seq_len=None):\n        # x: [bs, num_attention_heads, seq_len, head_size]\n        if seq_len > self.max_seq_len_cached:\n            self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)\n\n        return (\n            self.cos_cached[:seq_len].to(dtype=x.dtype),\n            self.sin_cached[:seq_len].to(dtype=x.dtype),\n        )\n\n\nclass LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):\n    \"\"\"LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev\"\"\"\n\n    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):\n        self.scaling_factor = scaling_factor\n        super().__init__(dim, max_position_embeddings, base, device)\n\n    def _set_cos_sin_cache(self, seq_len, device, dtype):\n        self.max_seq_len_cached = seq_len\n        t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)\n        t = t / self.scaling_factor\n\n        freqs = torch.einsum(\"i,j->ij\", t, self.inv_freq)\n        # Different from paper, but it uses a different permutation in order to obtain the same calculation\n        emb = torch.cat((freqs, freqs), dim=-1)\n        self.register_buffer(\"cos_cached\", emb.cos().to(dtype), persistent=False)\n        self.register_buffer(\"sin_cached\", emb.sin().to(dtype), persistent=False)\n\n\nclass LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):\n    \"\"\"LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla\"\"\"\n\n    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):\n        self.scaling_factor = scaling_factor\n        super().__init__(dim, max_position_embeddings, base, device)\n\n    def _set_cos_sin_cache(self, seq_len, device, dtype):\n        self.max_seq_len_cached = seq_len\n\n        if seq_len > self.max_position_embeddings:\n            base = self.base * ((self.scaling_factor * seq_len / self.max_position_embeddings) -\n                                (self.scaling_factor - 1))**(self.dim / (self.dim - 2))\n            inv_freq = 1.0 / (base**(torch.arange(0, self.dim, 2).float().to(device) / self.dim))\n            self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n\n        t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)\n\n        freqs = torch.einsum(\"i,j->ij\", t, self.inv_freq)\n        # Different from paper, but it uses a different permutation in order to obtain the same calculation\n        emb = torch.cat((freqs, freqs), dim=-1)\n        self.register_buffer(\"cos_cached\", emb.cos().to(dtype), persistent=False)\n        self.register_buffer(\"sin_cached\", emb.sin().to(dtype), persistent=False)\n\n\ndef rotate_half(x):\n    \"\"\"Rotates half the hidden dims of the input.\"\"\"\n    x1 = x[..., :x.shape[-1] // 2]\n    x2 = x[..., x.shape[-1] // 2:]\n    return torch.cat((-x2, x1), dim=-1)\n\n\ndef apply_rotary_pos_emb(q, k, cos, sin, position_ids):\n    cos = cos[position_ids].unsqueeze(1)  # [bs, 1, seq_len, dim]\n    sin = sin[position_ids].unsqueeze(1)  # [bs, 1, seq_len, dim]\n    q_embed = (q * cos) + (rotate_half(q) * sin)\n    k_embed = (k * cos) + (rotate_half(k) * sin)\n    return q_embed, k_embed\n\n\ndef repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n    \"\"\"\n    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n    \"\"\"\n    batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n    if n_rep == 1:\n        return hidden_states\n    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)\n    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n\nclass ParallelLlamaAttention(nn.Module):\n    \"\"\"Multi-headed attention from 'Attention Is All You Need' paper\"\"\"\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.config = config\n        self.megatron_config = megatron_config\n        self.hidden_size = config.hidden_size\n        self.num_heads = config.num_attention_heads\n        self.head_dim = self.hidden_size // self.num_heads\n        self.num_key_value_heads = config.num_key_value_heads\n        self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n        self.max_position_embeddings = config.max_position_embeddings\n        self.rope_theta = config.rope_theta\n\n        # assign values after tp\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        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}'\n        assert self.num_key_value_heads % tp_size == 0, \\\n            f'num_key_value_heads must be divisible by tp_size. Got num_key_value_heads={self.num_key_value_heads}, tp_size={tp_size}'\n\n        self.num_heads_per_tp = self.num_heads // tp_size\n        self.num_key_value_heads_per_tp = self.num_key_value_heads // tp_size\n        self.hidden_size_per_tp = self.hidden_size // tp_size\n\n        if (self.head_dim * self.num_heads) != self.hidden_size:\n            raise ValueError(f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n                             f\" and `num_heads`: {self.num_heads}).\")\n\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear()\n\n        if megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            assert row_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, megatron_config)\n            tp_utils.update_kwargs_with_config(row_kwargs, megatron_config)\n\n        # [self.q_size, self.k_size, self.v_size]\n        self.qkv_proj = QKVParallelLinear(input_size=self.hidden_size,\n                                          num_heads=self.num_heads,\n                                          num_key_value_heads=self.num_key_value_heads,\n                                          head_dim=self.head_dim,\n                                          bias=config.attention_bias,\n                                          gather_output=False,\n                                          skip_bias_add=False,\n                                          **column_kwargs)\n\n        self.q_size = self.num_heads_per_tp * self.head_dim\n        self.k_size = self.num_key_value_heads_per_tp * self.head_dim\n        self.v_size = self.num_key_value_heads_per_tp * self.head_dim\n\n        self.o_proj = tensor_parallel.RowParallelLinear(input_size=self.num_heads * self.head_dim,\n                                                        output_size=self.hidden_size,\n                                                        bias=config.attention_bias,\n                                                        input_is_parallel=True,\n                                                        skip_bias_add=False,\n                                                        **row_kwargs)\n\n        self._init_rope()\n\n    def _init_rope(self):\n        if self.config.rope_scaling is None:\n            self.rotary_emb = LlamaRotaryEmbedding(\n                self.head_dim,\n                max_position_embeddings=self.max_position_embeddings,\n                base=self.rope_theta,\n            )\n        else:\n            scaling_type = self.config.rope_scaling[\"type\"]\n            scaling_factor = self.config.rope_scaling[\"factor\"]\n            if scaling_type == \"linear\":\n                self.rotary_emb = LlamaLinearScalingRotaryEmbedding(\n                    self.head_dim,\n                    max_position_embeddings=self.max_position_embeddings,\n                    scaling_factor=scaling_factor,\n                    base=self.rope_theta,\n                )\n            elif scaling_type == \"dynamic\":\n                self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(\n                    self.head_dim,\n                    max_position_embeddings=self.max_position_embeddings,\n                    scaling_factor=scaling_factor,\n                    base=self.rope_theta,\n                )\n            else:\n                raise ValueError(f\"Unknown RoPE scaling type {scaling_type}\")\n\n    def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):\n        return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n        bsz, q_len, _ = hidden_states.size()\n        qkv = self.qkv_proj(hidden_states)[0]\n        query_states, key_states, value_states = qkv.split([self.q_size, self.k_size, self.v_size], dim=-1)\n\n        query_states = query_states.view(bsz, q_len, self.num_heads_per_tp, self.head_dim).transpose(1, 2)\n        key_states = key_states.view(bsz, q_len, self.num_key_value_heads_per_tp, self.head_dim).transpose(1, 2)\n        value_states = value_states.view(bsz, q_len, self.num_key_value_heads_per_tp, self.head_dim).transpose(1, 2)\n\n        kv_seq_len = key_states.shape[-2]\n        cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)\n        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)\n\n        key_states = repeat_kv(key_states, self.num_key_value_groups)\n        value_states = repeat_kv(value_states, self.num_key_value_groups)\n\n        attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)\n\n        if attn_weights.size() != (bsz, self.num_heads_per_tp, q_len, kv_seq_len):\n            raise ValueError(\n                f\"Attention weights should be of size {(bsz, self.num_heads_per_tp, q_len, kv_seq_len)}, but is\"\n                f\" {attn_weights.size()}\")\n\n        if attention_mask is not None:\n            if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):\n                raise ValueError(\n                    f\"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}\")\n            attn_weights = attn_weights + attention_mask\n\n        # upcast attention to fp32\n        attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)\n        attn_output = torch.matmul(attn_weights, value_states)\n\n        if attn_output.size() != (bsz, self.num_heads_per_tp, q_len, self.head_dim):\n            raise ValueError(\n                f\"`attn_output` should be of size {(bsz, self.num_heads_per_tp, q_len, self.head_dim)}, but is\"\n                f\" {attn_output.size()}\")\n\n        attn_output = attn_output.transpose(1, 2).contiguous()\n        attn_output = attn_output.reshape(bsz, q_len, self.hidden_size_per_tp)\n        attn_output = self.o_proj(attn_output)[0]\n        return attn_output\n\n\n\"\"\"\nRemove padding Attention\n- Using Flash-attn 2\n- Compatible with sequence parallel\n\"\"\"\n\nfrom transformers.utils import is_flash_attn_2_available\nimport torch.nn.functional as F\n\nfrom einops import rearrange\n\nif is_flash_attn_2_available():\n    from flash_attn import flash_attn_varlen_func\n    from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input  # noqa\n\n\ndef apply_rotary_pos_emb_rmpad(q, k, cos, sin, position_ids, indices, sequence_length):\n    batch_size = position_ids.shape[0]\n\n    q = pad_input(q, indices, batch_size, sequence_length)  # (batch_size, seqlen, num_head, head_dim)\n    k = pad_input(k, indices, batch_size, sequence_length)\n    cos = cos[position_ids].unsqueeze(2)  # [bs, seq_len, 1, dim]\n    sin = sin[position_ids].unsqueeze(2)  # [bs, seq_len, 1, dim]\n    q_embed = (q * cos) + (rotate_half(q) * sin)\n    k_embed = (k * cos) + (rotate_half(k) * sin)\n\n    q_embed = index_first_axis(rearrange(q_embed, \"b s ... -> (b s) ...\"), indices)\n    k_embed = index_first_axis(rearrange(k_embed, \"b s ... -> (b s) ...\"), indices)\n\n    return q_embed, k_embed\n\n\nfrom flash_attn.layers.rotary import apply_rotary_emb\n\n\n# use flash-attn rotary embeddings with rmpad\n# cos/sin shoudl be: (seq_length, rotary_dim / 2)\ndef apply_rotary_pos_emb_rmpad_flash(q, k, cos, sin, cu_seqlens, max_seqlen):\n    q_embed = apply_rotary_emb(q,\n                               cos,\n                               sin,\n                               interleaved=False,\n                               inplace=False,\n                               cu_seqlens=cu_seqlens,\n                               max_seqlen=max_seqlen)\n    k_embed = apply_rotary_emb(k,\n                               cos,\n                               sin,\n                               interleaved=False,\n                               inplace=False,\n                               cu_seqlens=cu_seqlens,\n                               max_seqlen=max_seqlen)\n    return q_embed, k_embed\n\n\nclass ParallelLlamaAttentionRmPad(ParallelLlamaAttention):\n\n    def forward(self,\n                hidden_states: torch.Tensor,\n                position_ids: Optional[torch.LongTensor] = None,\n                sequence_length: int = None,\n                indices: torch.Tensor = None,\n                cu_seqlens: torch.Tensor = None,\n                max_seqlen_in_batch: int = None):\n        total_nnz, _, _ = hidden_states.size()  # This is the total_nnz padded after sequence parallel\n\n        if self.megatron_config.sequence_parallel:\n            total_nnz = total_nnz * mpu.get_tensor_model_parallel_world_size()\n\n        qkv = self.qkv_proj(hidden_states)[0]\n        query_states, key_states, value_states = qkv.split([self.q_size, self.k_size, self.v_size],\n                                                           dim=-1)  # (total_nnz, 1, hidden_size)\n\n        if self.megatron_config.sequence_parallel:\n            sequence_parallel_pad = total_nnz - cu_seqlens[-1]\n            total_nnz = cu_seqlens[-1]  # total_nnz before sp padding\n            query_states = query_states[:total_nnz]\n            key_states = key_states[:total_nnz]\n            value_states = value_states[:total_nnz]\n\n        # Flash attention requires the input to have the shape\n        # batch_size x seq_length x head_dime x hidden_dim\n        # therefore we just need to keep the original shape\n        query_states = query_states.view(total_nnz, self.num_heads_per_tp, self.head_dim)\n        key_states = key_states.view(total_nnz, self.num_key_value_heads_per_tp, self.head_dim)\n        value_states = value_states.view(total_nnz, self.num_key_value_heads_per_tp, self.head_dim)\n\n        cos, sin = self.rotary_emb(value_states, seq_len=sequence_length)\n        cos, sin = cos[:, :cos.shape[1] // 2], sin[:, :sin.shape[1] // 2]  # flash attn only needs half\n        query_states, key_states = apply_rotary_pos_emb_rmpad_flash(query_states,\n                                                                    key_states,\n                                                                    cos,\n                                                                    sin,\n                                                                    cu_seqlens=cu_seqlens,\n                                                                    max_seqlen=max_seqlen_in_batch)\n        # query_states, key_states = apply_rotary_pos_emb_rmpad(query_states, key_states, cos, sin, position_ids, indices,\n\n        # TODO: llama does not have dropout in the config??\n        # It is recommended to use dropout with FA according to the docs\n        # when training.\n        dropout_rate = 0.0  # if not self.training else self.attn_dropout\n\n        # In PEFT, usually we cast the layer norms in float32 for training stability reasons\n        # therefore the input hidden states gets silently casted in float32. Hence, we need\n        # cast them back in float16 just to be sure everything works as expected.\n        # This might slowdown training & inference so it is recommended to not cast the LayerNorms\n        # in fp32. (LlamaRMSNorm handles it correctly)\n        input_dtype = query_states.dtype\n        if input_dtype == torch.float32:\n            query_states = query_states.to(torch.float16)\n            key_states = key_states.to(torch.float16)\n            value_states = value_states.to(torch.float16)\n\n        attn_output_unpad = flash_attn_varlen_func(\n            query_states,\n            key_states,\n            value_states,\n            cu_seqlens_q=cu_seqlens,\n            cu_seqlens_k=cu_seqlens,\n            max_seqlen_q=max_seqlen_in_batch,\n            max_seqlen_k=max_seqlen_in_batch,\n            dropout_p=dropout_rate,\n            softmax_scale=None,\n            causal=True,\n        )\n\n        attn_output_unpad = attn_output_unpad.to(input_dtype)\n        attn_output_unpad = attn_output_unpad.reshape(total_nnz, 1, self.hidden_size_per_tp).contiguous()\n\n        # sequence parallel reduce_scatter is performed inside RowColumnParallel if enabled\n        # Here we need to repad\n        if self.megatron_config.sequence_parallel:\n            attn_output_unpad = F.pad(attn_output_unpad, pad=(0, 0, 0, 0, 0, sequence_parallel_pad))\n\n        attn_output_unpad = self.o_proj(attn_output_unpad)[0]\n        return attn_output_unpad\n"
  },
  {
    "path": "verl/models/llama/megatron/layers/parallel_decoder.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Optional, Tuple\n\nimport torch\nfrom torch import nn\nfrom transformers import LlamaConfig\nfrom megatron.core import ModelParallelConfig\n\nfrom .parallel_attention import ParallelLlamaAttention, ParallelLlamaAttentionRmPad\nfrom .parallel_mlp import ParallelLlamaMLP\nfrom .parallel_rmsnorm import ParallelLlamaRMSNorm\n\n\nclass ParallelLlamaDecoderLayer(nn.Module):\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.hidden_size = config.hidden_size\n        self.self_attn = ParallelLlamaAttention(config=config, megatron_config=megatron_config)\n\n        self.mlp = ParallelLlamaMLP(config, megatron_config=megatron_config)\n        self.input_layernorm = ParallelLlamaRMSNorm(config, megatron_config)\n        self.post_attention_layernorm = ParallelLlamaRMSNorm(config, megatron_config)\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n        \"\"\"\n        Args:\n            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\n            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size\n                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.\n            output_attentions (`bool`, *optional*):\n                Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n                returned tensors for more detail.\n            use_cache (`bool`, *optional*):\n                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding\n                (see `past_key_values`).\n            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states\n        \"\"\"\n\n        residual = hidden_states\n\n        hidden_states = self.input_layernorm(hidden_states)\n\n        # Note: sequence parallel is hidden inside ColumnParallelLinear\n        # reduce scatter is hidden inside RowParallelLinear\n\n        # Self Attention\n        hidden_states = self.self_attn(\n            hidden_states=hidden_states,\n            attention_mask=attention_mask,\n            position_ids=position_ids,\n        )\n\n        # TODO: add sequence parallel operator reduce_scatter here\n\n        hidden_states = residual + hidden_states\n\n        # Fully Connected\n        residual = hidden_states\n        hidden_states = self.post_attention_layernorm(hidden_states)\n\n        # TODO: add sequence parallel operator all_gather here\n\n        hidden_states = self.mlp(hidden_states)\n\n        # TODO: add sequence parallel operator reduce_scatter here\n\n        hidden_states = residual + hidden_states\n\n        outputs = hidden_states\n\n        return outputs\n\n\nclass ParallelLlamaDecoderLayerRmPad(nn.Module):\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.config = config\n        self.megatron_config = megatron_config\n        self.hidden_size = config.hidden_size\n        self.self_attn = ParallelLlamaAttentionRmPad(config=config, megatron_config=megatron_config)\n\n        self.mlp = ParallelLlamaMLP(config, megatron_config=megatron_config)\n        self.input_layernorm = ParallelLlamaRMSNorm(config, megatron_config)\n        self.post_attention_layernorm = ParallelLlamaRMSNorm(config, megatron_config)\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        position_ids: Optional[torch.LongTensor] = None,\n        sequence_length: int = None,\n        indices: torch.Tensor = None,\n        cu_seqlens: int = None,\n        max_seqlen_in_batch: int = None\n    ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n        residual = hidden_states  # (total_nnz // sp, 1, hidden_size)\n\n        hidden_states = self.input_layernorm(hidden_states)\n\n        # Self Attention\n        # (total_nnz // sp, 1, hidden_size) -> all-gather (total_nnz, 1, hidden_size)\n        # -> col + row -> reduce-scatter -> (total_nnz // sp, 1, hidden_size)\n        hidden_states = self.self_attn(hidden_states=hidden_states,\n                                       position_ids=position_ids,\n                                       sequence_length=sequence_length,\n                                       indices=indices,\n                                       cu_seqlens=cu_seqlens,\n                                       max_seqlen_in_batch=max_seqlen_in_batch)\n\n        hidden_states = residual + hidden_states\n\n        # Fully Connected\n        # shape changes same as attn\n        residual = hidden_states\n        hidden_states = self.post_attention_layernorm(hidden_states)\n        hidden_states = self.mlp(hidden_states)\n        hidden_states = residual + hidden_states\n\n        outputs = hidden_states\n\n        return outputs\n"
  },
  {
    "path": "verl/models/llama/megatron/layers/parallel_linear.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/linear.py\n\nfrom typing import Optional, Tuple\n\nfrom megatron.core import tensor_parallel\n\n\nclass QKVParallelLinear(tensor_parallel.ColumnParallelLinear):\n\n    def __init__(self,\n                 input_size,\n                 num_heads,\n                 num_key_value_heads,\n                 head_dim,\n                 *,\n                 bias=True,\n                 gather_output=True,\n                 skip_bias_add=False,\n                 **kwargs):\n        # Keep input parameters, and already restrict the head numbers\n        self.input_size = input_size\n        self.q_output_size = num_heads * head_dim\n        self.kv_output_size = num_key_value_heads * head_dim\n        self.head_dim = head_dim\n        self.gather_output = gather_output\n        self.skip_bias_add = skip_bias_add\n\n        input_size = self.input_size\n        output_size = (num_heads + 2 * num_key_value_heads) * self.head_dim\n\n        super().__init__(input_size=input_size,\n                         output_size=output_size,\n                         bias=bias,\n                         gather_output=gather_output,\n                         skip_bias_add=skip_bias_add,\n                         **kwargs)\n\n\nclass MergedColumnParallelLinear(tensor_parallel.ColumnParallelLinear):\n\n    def __init__(self,\n                 input_size,\n                 gate_ouput_size,\n                 up_output_size,\n                 *,\n                 bias=True,\n                 gather_output=True,\n                 skip_bias_add=False,\n                 **kwargs):\n        # Keep input parameters, and already restrict the head numbers\n        self.input_size = input_size\n        self.output_size = gate_ouput_size + up_output_size\n        self.gather_output = gather_output\n        self.skip_bias_add = skip_bias_add\n\n        super().__init__(input_size=self.input_size,\n                         output_size=self.output_size,\n                         bias=bias,\n                         gather_output=gather_output,\n                         skip_bias_add=skip_bias_add,\n                         **kwargs)\n"
  },
  {
    "path": "verl/models/llama/megatron/layers/parallel_mlp.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core import tensor_parallel\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers.activations import ACT2FN\nfrom verl.models.llama.megatron.layers.parallel_linear import MergedColumnParallelLinear\n\nfrom verl.utils.megatron import tensor_parallel as tp_utils\n\n\nclass ParallelLlamaMLP(nn.Module):\n\n    def __init__(self, config, megatron_config: ModelParallelConfig = None) -> None:\n        super().__init__()\n        self.config = config\n        self.hidden_size = config.hidden_size\n        self.intermediate_size = config.intermediate_size\n        # The weight is only [hidden_size, intermediate_size // model_parallel_world_size]\n\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear()\n\n        if megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            assert row_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(row_kwargs, megatron_config)\n            tp_utils.update_kwargs_with_config(column_kwargs, megatron_config)\n\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        self.gate_up_proj = MergedColumnParallelLinear(\n            input_size=self.hidden_size,\n            gate_ouput_size=self.intermediate_size,\n            up_output_size=self.intermediate_size,\n            bias=False,\n            gather_output=False,\n            skip_bias_add=False,\n            **column_kwargs,\n        )\n        self.gate_size = self.intermediate_size // tp_size\n\n        self.down_proj = tensor_parallel.RowParallelLinear(input_size=self.intermediate_size,\n                                                           output_size=self.hidden_size,\n                                                           bias=False,\n                                                           input_is_parallel=True,\n                                                           skip_bias_add=False,\n                                                           **row_kwargs)\n\n        self.act_fn = ACT2FN[config.hidden_act]\n\n    def forward(self, x):\n        gate_up = self.gate_up_proj(x)[0]\n        gate, up = gate_up.split(self.gate_size, dim=-1)\n        return self.down_proj(self.act_fn(gate) * up)[0]\n"
  },
  {
    "path": "verl/models/llama/megatron/layers/parallel_rmsnorm.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numbers\nimport torch\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers import LlamaConfig\n\nfrom apex.normalization.fused_layer_norm import fused_rms_norm_affine\nfrom verl.utils.megatron import sequence_parallel as sp_utils\n\n\nclass ParallelLlamaRMSNorm(nn.Module):\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):\n        \"\"\"\n        LlamaRMSNorm is equivalent to T5LayerNorm\n        \"\"\"\n        super().__init__()\n        if isinstance(config.hidden_size, numbers.Integral):\n            normalized_shape = (config.hidden_size,)\n        self.normalized_shape = torch.Size(normalized_shape)\n        self.weight = nn.Parameter(torch.ones(self.normalized_shape))\n        self.variance_epsilon = config.rms_norm_eps\n\n        if megatron_config.sequence_parallel:\n            sp_utils.mark_parameter_as_sequence_parallel(self.weight)\n\n    def forward(self, hidden_states):\n        return fused_rms_norm_affine(input=hidden_states,\n                                     weight=self.weight,\n                                     normalized_shape=self.normalized_shape,\n                                     eps=self.variance_epsilon,\n                                     memory_efficient=True)"
  },
  {
    "path": "verl/models/llama/megatron/modeling_llama_megatron.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"PyTorch LLaMA model with Megatron-style acceleration.\"\"\"\n\nfrom typing import Optional, Tuple, Union\n\nimport torch\nimport torch.utils.checkpoint\nfrom megatron.core import tensor_parallel\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers.modeling_outputs import BaseModelOutputWithPast\nfrom transformers.models.llama.configuration_llama import LlamaConfig\nfrom transformers.models.llama.modeling_llama import CausalLMOutputWithPast\n\nfrom verl.utils.megatron import sequence_parallel as sp_utils\nfrom verl.utils.megatron import tensor_parallel as tp_utils\nfrom .layers import ParallelLlamaDecoderLayer, ParallelLlamaRMSNorm, ParallelLlamaDecoderLayerRmPad\n\"\"\"\nTODO: \n1. Add weight initialization. Here we need to be careful on TP weight init.\n2. Add sequence parallel\n3. Load checkpoint from meta LLama pretrained checkpoint\n\"\"\"\n\n\n# Copied from transformers.models.bart.modeling_bart._make_causal_mask\ndef _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device):\n    \"\"\"\n    Make causal mask used for bi-directional self-attention.\n    \"\"\"\n    bsz, tgt_len = input_ids_shape\n    mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)\n    mask_cond = torch.arange(mask.size(-1), device=device)\n    mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)\n    mask = mask.to(dtype)\n    return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len)\n\n\n# Copied from transformers.models.bart.modeling_bart._expand_mask\ndef _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):\n    \"\"\"\n    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.\n    \"\"\"\n    bsz, src_len = mask.size()\n    tgt_len = tgt_len if tgt_len is not None else src_len\n\n    expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)\n\n    inverted_mask = 1.0 - expanded_mask\n\n    return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)\n\n\nclass ParallelLlamaModel(nn.Module):\n    \"\"\"\n    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]\n\n    Args:\n        config: LlamaConfig\n    \"\"\"\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.padding_idx = config.pad_token_id\n        self.vocab_size = config.vocab_size\n        embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding()\n        if megatron_config is not None:\n            assert embedding_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config)\n        self.embed_tokens = tensor_parallel.VocabParallelEmbedding(num_embeddings=config.vocab_size,\n                                                                   embedding_dim=config.hidden_size,\n                                                                   **embedding_kwargs)\n\n        self.layers = nn.ModuleList(\n            [ParallelLlamaDecoderLayer(config, megatron_config) for _ in range(config.num_hidden_layers)])\n        self.norm = ParallelLlamaRMSNorm(config, megatron_config)\n\n    # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask\n    def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds):\n        # create causal mask\n        # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n        combined_attention_mask = None\n        if input_shape[-1] > 1:\n            combined_attention_mask = _make_causal_mask(\n                input_shape,\n                inputs_embeds.dtype,\n                device=inputs_embeds.device,\n            )\n\n        if attention_mask is not None:\n            # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n            expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype,\n                                              tgt_len=input_shape[-1]).to(inputs_embeds.device)\n            combined_attention_mask = (expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask +\n                                       combined_attention_mask)\n\n        return combined_attention_mask\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, BaseModelOutputWithPast]:\n        \"\"\"\n\n        Args:\n            input_ids: input ids. shape (batch_size, seq_length)\n            attention_mask: attention_mask. shape (batch_size, seq_length)\n            position_ids: position ids. shape (batch_size, seq_length)\n\n        Returns:\n\n        \"\"\"\n        batch_size, seq_length = input_ids.shape\n        inputs_embeds = self.embed_tokens(input_ids)\n        # embed positions\n\n        attention_mask = self._prepare_decoder_attention_mask(attention_mask, (batch_size, seq_length), inputs_embeds)\n\n        hidden_states = inputs_embeds\n\n        for idx, decoder_layer in enumerate(self.layers):\n            layer_outputs = decoder_layer(\n                hidden_states,\n                attention_mask=attention_mask,\n                position_ids=position_ids,\n            )\n\n            hidden_states = layer_outputs\n\n        hidden_states = self.norm(hidden_states)\n\n        return hidden_states\n\n\nclass ParallelLlamaForCausalLM(nn.Module):\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.model = ParallelLlamaModel(config, megatron_config=megatron_config)\n        self.vocab_size = config.vocab_size\n\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n\n        self.lm_head = tensor_parallel.ColumnParallelLinear(input_size=config.hidden_size,\n                                                            output_size=config.vocab_size,\n                                                            bias=False,\n                                                            gather_output=False,\n                                                            skip_bias_add=False,\n                                                            **column_kwargs)\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        r\"\"\"\n        Args:\n            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n        Returns:\n        ```\"\"\"\n\n        # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n        outputs = self.model(\n            input_ids=input_ids,\n            attention_mask=attention_mask,\n            position_ids=position_ids,\n        )\n\n        hidden_states = outputs\n        logits = self.lm_head(hidden_states)[0]\n\n        logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits)\n\n        logits = logits.float()\n        return CausalLMOutputWithPast(\n            loss=None,\n            logits=logits,\n            past_key_values=None,\n            hidden_states=None,\n            attentions=None,\n        )\n\n\nfrom flash_attn.bert_padding import index_first_axis, pad_input, unpad_input  # noqa\n\n\nclass ParallelLlamaModelRmPad(nn.Module):\n    \"\"\"\n    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]\n\n    Args:\n        config: LlamaConfig\n    \"\"\"\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.padding_idx = config.pad_token_id\n        self.vocab_size = config.vocab_size\n        embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding()\n        self.megatron_config = megatron_config\n        if megatron_config is not None:\n            assert embedding_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config)\n        self.embed_tokens = tensor_parallel.VocabParallelEmbedding(num_embeddings=config.vocab_size,\n                                                                   embedding_dim=config.hidden_size,\n                                                                   **embedding_kwargs)\n\n        self.layers = nn.ModuleList(\n            [ParallelLlamaDecoderLayerRmPad(config, megatron_config) for _ in range(config.num_hidden_layers)])\n        self.norm = ParallelLlamaRMSNorm(config, megatron_config)\n\n    def forward(self,\n                input_ids: torch.Tensor,\n                position_ids: Optional[torch.LongTensor] = None,\n                sequence_length: int = None,\n                indices: torch.Tensor = None,\n                cu_seqlens: int = None,\n                max_seqlen_in_batch: int = None) -> Union[Tuple, BaseModelOutputWithPast]:\n        \"\"\"\n\n        Args:\n            input_ids: input ids. shape (1, totol_nnz)\n            position_ids: position ids. shape (batch_size, seq_length)\n\n        Returns:\n\n        \"\"\"\n        inputs_embeds = self.embed_tokens(input_ids)  # (1, total_nnz) -> (1, total_nnz, hidden_size)\n\n        # (1, total_nnz, hidden_size) -> (total_nnz, 1, hidden_size) -> (total_nnz // sp, 1, hidden_size)\n        inputs_embeds = inputs_embeds.transpose(0, 1)\n        if self.megatron_config.sequence_parallel:\n            inputs_embeds = tensor_parallel.scatter_to_sequence_parallel_region(inputs_embeds)\n\n        hidden_states = inputs_embeds\n        for idx, decoder_layer in enumerate(self.layers):\n            layer_outputs = decoder_layer(hidden_states,\n                                          position_ids=position_ids,\n                                          sequence_length=sequence_length,\n                                          indices=indices,\n                                          cu_seqlens=cu_seqlens,\n                                          max_seqlen_in_batch=max_seqlen_in_batch)\n\n            hidden_states = layer_outputs\n\n        hidden_states = self.norm(hidden_states)\n\n        return hidden_states\n\n\nclass ParallelLlamaForCausalLMRmPad(nn.Module):\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.config = config\n        self.megatron_config = megatron_config\n        self.model = ParallelLlamaModelRmPad(config, megatron_config=megatron_config)\n        self.vocab_size = config.vocab_size\n        self._init_head()\n\n    def _init_head(self):\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if self.megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n        self.lm_head = tensor_parallel.ColumnParallelLinear(input_size=self.config.hidden_size,\n                                                            output_size=self.config.vocab_size,\n                                                            bias=False,\n                                                            gather_output=False,\n                                                            skip_bias_add=False,\n                                                            **column_kwargs)\n\n    def _forward_head(self, hidden_states):\n        # all_gather from sequence parallel region is performed inside lm_head\n        logits = self.lm_head(hidden_states)[0]\n        logits = logits.float()  # (total_nnz_padded, 1, vocab_size // tp)\n        logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits)  # (total_nnz_padded, 1, vocab_size)\n        return logits\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        r\"\"\"\n        Args:\n            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n        Returns:\n        ```\"\"\"\n        batch_size, sequence_length = input_ids.shape\n\n        # remove padding here\n        input_ids, indices, cu_seqlens, max_seqlen_in_batch, *_ = unpad_input(input_ids.unsqueeze(dim=-1),\n                                                                              attention_mask)  # (total_nnz, 1)\n\n        # pad input_ids to multiple of tp for all tp ranks\n        # TODO: for better performance, the sp padding should be removed at each layer. Not sure the performance gap\n        if self.megatron_config.sequence_parallel:\n            input_ids = sp_utils.pad_to_sequence_parallel(input_ids)\n\n        input_ids = input_ids.transpose(0, 1)  # (1, total_nnz+pad)\n\n        outputs = self.model(input_ids=input_ids,\n                             position_ids=position_ids,\n                             sequence_length=sequence_length,\n                             indices=indices,\n                             cu_seqlens=cu_seqlens,\n                             max_seqlen_in_batch=max_seqlen_in_batch)\n\n        hidden_states = outputs\n\n        logits = self._forward_head(hidden_states)\n\n        # remove padding from sequence parallel\n        if self.megatron_config.sequence_parallel:\n            totol_nnz = cu_seqlens[-1]\n            logits = logits[:totol_nnz]  # (total_nnz_padded)\n\n        logits = torch.squeeze(logits, dim=1)  # remove the artificial batch dimension\n        # add removed padding back\n        logits = pad_input(logits, indices, batch_size,\n                           seqlen=sequence_length)  # (batch_size, sequence_length, vocab_size)\n\n        return CausalLMOutputWithPast(\n            loss=None,\n            logits=logits,\n            past_key_values=None,\n            hidden_states=None,\n            attentions=None,\n        )\n\n\nclass ParallelLlamaForValueRmPad(ParallelLlamaForCausalLMRmPad):\n\n    def _init_head(self):\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if self.megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n        self.lm_head = nn.Linear(in_features=self.config.hidden_size, out_features=1, bias=False)\n        # lm_head is effectively the same as sequence parallel\n        sp_utils.mark_parameter_as_sequence_parallel(self.lm_head.weight)\n\n    def _forward_head(self, hidden_states):\n        logits = self.lm_head(hidden_states)  # (total_nnz_padded // tp, 1, 1)\n        logits = logits.float()\n        if self.megatron_config.sequence_parallel:\n            logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False)\n        return logits\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        output = super().forward(input_ids, attention_mask, position_ids)\n        output.logits = torch.squeeze(output.logits, dim=-1)\n        return output\n\n\n\"\"\"\nSupport pipeline parallelism\n\"\"\"\n\n\nclass ParallelLlamaModelRmPadPP(nn.Module):\n    \"\"\"\n    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]\n    This model definition supports pipeline parallelism. To support pp and vpp,\n    - This model only contains layer in this pp stage and vpp chunk\n    - When calling get_model in Megatron, this rank will instantiate all the vpp chunks in this pp.\n    Args:\n        config: LlamaConfig\n    \"\"\"\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig, pre_process, post_process):\n        super().__init__()\n        self.padding_idx = config.pad_token_id\n        self.vocab_size = config.vocab_size\n        self.pre_process = pre_process\n        self.post_process = post_process\n        self.megatron_config = megatron_config\n        embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding()\n        if megatron_config is not None:\n            assert embedding_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config)\n        if pre_process:\n            self.embed_tokens = tensor_parallel.VocabParallelEmbedding(num_embeddings=config.vocab_size,\n                                                                       embedding_dim=config.hidden_size,\n                                                                       **embedding_kwargs)\n        else:\n            self.embed_tokens = None\n\n        # pp_rank = megatron_config.pipeline_model_parallel_rank\n        pp_size = megatron_config.pipeline_model_parallel_size\n        self.num_layer_per_pp = config.num_hidden_layers // pp_size\n        vpp_size = megatron_config.virtual_pipeline_model_parallel_size\n\n        if vpp_size is not None:\n            self.num_layer_vpp_chunk = self.num_layer_per_pp // vpp_size\n            self.num_layer_this_model = self.num_layer_vpp_chunk\n            # vpp_rank = megatron_config.virtual_pipeline_model_parallel_rank\n            # self.offset = vpp_rank * (\n            #         config.num_hidden_layers // megatron_config.virtual_pipeline_model_parallel_size) + \\\n            #             (megatron_config.pipeline_model_parallel_rank * self.num_layer_vpp_chunk)\n        else:\n            self.num_layer_this_model = self.num_layer_per_pp\n            # self.offset = pp_rank * self.num_layer_per_pp\n\n        layers = []\n        for i in range(self.num_layer_this_model):\n            layer = ParallelLlamaDecoderLayerRmPad(config, megatron_config)\n            # setattr(layer, 'hidden_layer_index', self.offset + i)\n            layers.append(layer)\n\n        self.layers = nn.ModuleList(layers)\n\n        if post_process:\n            self.norm = ParallelLlamaRMSNorm(config, megatron_config)\n        else:\n            self.norm = None\n\n    def set_input_tensor(self, input_tensor):\n        \"\"\"Set input tensor to be used instead of forward()'s input.\n\n        When doing pipeline parallelism the input from the previous\n        stage comes from communication, not from the input, so the\n        model's forward_step_func won't have it. This function is thus\n        used by internal code to bypass the input provided by the\n        forward_step_func\"\"\"\n        self.input_tensor = input_tensor\n\n    def forward(self,\n                input_ids: torch.Tensor,\n                position_ids: Optional[torch.LongTensor] = None,\n                sequence_length: int = None,\n                indices: torch.Tensor = None,\n                cu_seqlens: int = None,\n                max_seqlen_in_batch: int = None) -> Union[Tuple, BaseModelOutputWithPast]:\n        \"\"\"\n\n        Args:\n            input_ids: input ids. shape (1, totol_nnz)\n            position_ids: position ids. shape (batch_size, seq_length)\n\n        Returns:\n\n        \"\"\"\n        if self.pre_process:\n            inputs_embeds = self.embed_tokens(input_ids)  # (1, total_nnz) -> (1, total_nnz, hidden_size)\n\n            # vocab parallel embedding will not do sequence parallel reduce-scatter in open source megatron\n            # so need to deal with it by handle here:\n            # (1, total_nnz, hidden_size) -> (total_nnz, 1, hidden_size) -> (total_nnz // sp, 1, hidden_size)\n            inputs_embeds = inputs_embeds.transpose(0, 1)\n            if self.megatron_config.sequence_parallel:\n                inputs_embeds = tensor_parallel.scatter_to_sequence_parallel_region(inputs_embeds)\n\n            hidden_states = inputs_embeds\n        else:\n            # self.hidden_states should be passed by Megatron\n            hidden_states = self.input_tensor\n\n        for idx, decoder_layer in enumerate(self.layers):\n            layer_outputs = decoder_layer(hidden_states,\n                                          position_ids=position_ids,\n                                          sequence_length=sequence_length,\n                                          indices=indices,\n                                          cu_seqlens=cu_seqlens,\n                                          max_seqlen_in_batch=max_seqlen_in_batch)\n\n            hidden_states = layer_outputs\n\n        if self.post_process:\n            hidden_states = self.norm(hidden_states)\n\n        return hidden_states\n\n\nclass ParallelLlamaForCausalLMRmPadPP(nn.Module):\n\n    def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig, pre_process, post_process,\n                 share_embeddings_and_output_weights):\n        super().__init__()\n        self.config = config\n        self.megatron_config = megatron_config\n        self.model = ParallelLlamaModelRmPadPP(config,\n                                               megatron_config=megatron_config,\n                                               pre_process=pre_process,\n                                               post_process=post_process)\n        self.share_embeddings_and_output_weights = share_embeddings_and_output_weights\n        self.vocab_size = config.vocab_size\n        self.pre_process = pre_process\n        self.post_process = post_process\n        if post_process:\n            self._init_head()\n\n    def set_input_tensor(self, input_tensor):\n        \"\"\"Set input tensor to be used instead of forward()'s input.\n\n        When doing pipeline parallelism the input from the previous\n        stage comes from communication, not from the input, so the\n        model's forward_step_func won't have it. This function is thus\n        used by internal code to bypass the input provided by the\n        forward_step_func\"\"\"\n        assert len(input_tensor) == 1\n        self.model.set_input_tensor(input_tensor[0])\n\n    def _init_head(self):\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if self.megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n        self.lm_head = tensor_parallel.ColumnParallelLinear(input_size=self.config.hidden_size,\n                                                            output_size=self.config.vocab_size,\n                                                            bias=False,\n                                                            gather_output=False,\n                                                            skip_bias_add=False,\n                                                            **column_kwargs)\n\n    def _forward_head(self, hidden_states):\n        # all_gather from sequence parallel region is performed inside lm_head\n        # logits shape before forward_head hidden_states.shape: [4, 32, 4096]\n        logits = self.lm_head(hidden_states)[0]\n        # logits shape after forward_head logits.shape: [8, 32, 8]\n        logits = logits.float()  # (total_nnz_padded, 1, vocab_size // tp)\n        return logits\n\n    def forward(\n        self,\n        # original input\n        *,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        r\"\"\"\n        Args:\n            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n        Returns:\n        ```\"\"\"\n\n        # Note that input_ids, attention_mask and position_ids should be passed to every pp layer.\n        # In the first pp, input_ids will be used, in other pp layers hidden_states will be used inside self.model\n        batch_size, sequence_length = input_ids.shape\n        # remove padding here\n        input_ids_rmpad, indices, cu_seqlens, max_seqlen_in_batch, *_ = unpad_input(input_ids.unsqueeze(dim=-1),\n                                                                                    attention_mask)  # (total_nnz, 1)\n\n        # pad input_ids to multiple of tp for all tp ranks\n        # TODO: for better performance, the sp padding should be removed at each layer. Not sure the performance gap\n        if self.megatron_config.sequence_parallel:\n            input_ids_rmpad = sp_utils.pad_to_sequence_parallel(input_ids_rmpad)\n\n        input_ids_rmpad = input_ids_rmpad.transpose(0, 1)  # (1, total_nnz+pad)\n\n        outputs = self.model(input_ids=input_ids_rmpad,\n                             position_ids=position_ids,\n                             sequence_length=sequence_length,\n                             indices=indices,\n                             cu_seqlens=cu_seqlens,\n                             max_seqlen_in_batch=max_seqlen_in_batch)\n\n        if self.post_process:\n            hidden_states = outputs\n            # print(f'hidden_states.shape = {hidden_states.shape}') # torch.Size([4, 32, 4096])\n            logits = self._forward_head(hidden_states)\n            logits = torch.squeeze(logits, dim=1)  # remove the artificial batch dimension # torch.Size([8, 32, 16])\n\n            # remove padding from sequence parallel\n            if self.megatron_config.sequence_parallel:\n                totol_nnz = cu_seqlens[-1]\n                logits = logits[:totol_nnz]  # (total_nnz_padded)\n            # add removed padding back. If input is already rmpad, we let the caller pad_input\n            logits = pad_input(logits, indices, batch_size,\n                               seqlen=sequence_length)  # (batch_size, sequence_length, vocab_size)\n\n            return CausalLMOutputWithPast(\n                loss=None,\n                logits=logits,\n                past_key_values=None,\n                hidden_states=None,\n                attentions=None,\n            )\n        else:\n            return outputs\n\n\nclass ParallelLlamaForValueRmPadPP(ParallelLlamaForCausalLMRmPadPP):\n\n    def _init_head(self):\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if self.megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n        self.lm_head = nn.Linear(in_features=self.config.hidden_size, out_features=1, bias=False)\n        # lm_head is effectively the same as sequence parallel\n        sp_utils.mark_parameter_as_sequence_parallel(self.lm_head.weight)\n\n    def _forward_head(self, hidden_states):\n        logits = self.lm_head(hidden_states)  # (total_nnz_padded // tp, 1, 1)\n        logits = logits.float()\n        if self.megatron_config.sequence_parallel:\n            logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False)\n        return logits\n\n    def forward(\n        self,\n        *,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        output = super().forward(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids)\n        if self.post_process:\n            output.logits = torch.squeeze(output.logits, dim=-1)\n            return output\n        else:\n            return output\n"
  },
  {
    "path": "verl/models/qwen2/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/models/qwen2/megatron/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .modeling_qwen2_megatron import (\n    # original model with megatron\n    ParallelQwen2Model,\n    ParallelQwen2ForCausalLM,\n    # rmpad with megatron\n    ParallelQwen2ForCausalLMRmPad,\n    ParallelQwen2ForValueRmPad,\n    # rmpad with megatron and pipeline parallelism\n    ParallelQwen2ForCausalLMRmPadPP,\n    ParallelQwen2ForValueRmPadPP)\n"
  },
  {
    "path": "verl/models/qwen2/megatron/checkpoint_utils/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport time\nfrom typing import Dict, Any, Callable, Optional\nimport torch.distributed as dist\n\n\ndef _megatron_calc_layer_map(config):\n    \"\"\"Calculate the mapping of global layer_idx to local layer_idx\n    Returns:\n        layer_map (Dict: int -> tuple(int, int, int)):\n            mapping from the global layer index to\n            a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model)\n    \"\"\"\n    import megatron\n    from megatron.core import mpu\n\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n\n    layer_map = dict()\n    num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n    assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n    for pp_rank_idx in range(pp_size):\n        for virtual_pp_rank_idx in range(virtual_pp_size):\n            layer_offset = (virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) +\n                            pp_rank_idx * num_layers_per_model)\n            for layer_idx in range(num_layers_per_model):\n                layer_map[layer_offset + layer_idx] = (\n                    pp_rank_idx,\n                    virtual_pp_rank_idx,\n                    layer_idx,\n                )\n    return layer_map\n\n\ndef load_state_dict_to_megatron_qwen2(state_dict, wrapped_models, config, params_dtype, is_value_model=False):\n    \"\"\"Load merged state_dict to sharded Megatron module in training.\n    \"\"\"\n    import megatron\n    from megatron.core import mpu\n    from megatron.training.utils import print_rank_0, unwrap_model\n    from megatron.core.transformer.module import Float16Module\n    from megatron.core import DistributedDataParallel as LocalDDP\n    from torch.nn.parallel import DistributedDataParallel as torchDDP\n\n    start_time = time.time()\n\n    def _get_gpt_model(model):\n        return model\n\n    def broadcast_params(module):\n        for param in module.parameters():\n            torch.distributed.broadcast(param.data,\n                                        src=mpu.get_data_parallel_src_rank(),\n                                        group=mpu.get_data_parallel_group())\n\n    dp_rank = mpu.get_data_parallel_rank()\n    pp_rank = mpu.get_pipeline_model_parallel_rank()\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n    mp_group = mpu.get_model_parallel_group()\n\n    if torch.distributed.get_rank() == 0:\n        assert mp_group.rank() == 0, f\"mp_rank:[{mp_group.rank}] != 0 on rank #0\"\n        assert pp_rank == 0, f\"pp_rank:[{pp_rank}] != 0 on rank #0\"\n        assert dp_rank == 0, f\"dp_rank:[{dp_rank}] != 0 on rank #0\"\n\n    if not isinstance(wrapped_models, (list, tuple)):\n        wrapped_models = list(wrapped_models)\n\n    assert len(wrapped_models) == virtual_pp_size\n    num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n    assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n    models = [None] * len(wrapped_models)\n\n    for i, wrapped_model in enumerate(wrapped_models):\n        models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module))\n        gpt_model_module = _get_gpt_model(models[i])\n        assert len(gpt_model_module.model.layers) == num_layers_per_model\n\n    def _broadcast_tensor(tensor, name) -> torch.Tensor:\n        \"\"\"broadcast tensor from rank0 across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        if torch.distributed.get_rank() == 0:\n            if name in state_dict:\n                weight = state_dict[name]\n                tensor_shape = weight.shape\n            else:\n                tensor_shape = None\n        else:\n            weight = None\n            tensor_shape = None\n\n        obj_list = [tensor_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        tensor_shape = obj_list[0]\n\n        if tensor_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tensor:[{name}] not in state_dict, skip load\")\n            return\n\n        if tensor is None:\n            tensor = torch.empty(\n                tensor_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        if torch.distributed.get_rank() == 0:\n            tensor.data.copy_(weight)\n        dist.broadcast(tensor, src=0, group=mp_group)\n\n    def _broadcast_tp_shard_tensor_vocab(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        if torch.distributed.get_rank() == 0:\n            if name in state_dict:\n                full_weight = state_dict[name]\n\n                if mutate_func is not None:\n                    full_weight = mutate_func(full_weight)\n                tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim)\n                chunk_shape = tensor_chunk[0].shape\n            else:\n                chunk_shape = None\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{name}] not in state_dict, skip loading\")\n            return\n\n        if tensor is None:\n            sync_tensor = torch.empty(\n                chunk_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        else:\n            assert (tensor.shape == chunk_shape\n                   ), f\"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}\"\n            sync_tensor = torch.empty_like(tensor, device=torch.cuda.current_device(), requires_grad=False)\n\n        for i in range(tp_size):\n            if torch.distributed.get_rank() == 0:\n                sync_tensor.data.copy_(tensor_chunk[i])\n            dist.broadcast(sync_tensor, src=0, group=mp_group)\n            if (i == tp_rank) and (tensor is not None):\n                tensor.data.copy_(sync_tensor)\n\n    def _broadcast_tp_shard_tensor(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        if torch.distributed.get_rank() == 0:\n            if name in state_dict:\n                full_weight = state_dict[name]\n                if mutate_func is not None:\n                    full_weight = mutate_func(full_weight)\n                tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim)\n                chunk_shape = tensor_chunk[0].shape\n            else:\n                chunk_shape = None\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{name}] not in state_dict, skip loading\")\n            return\n\n        if tensor is None:\n            sync_tensor = torch.empty(\n                chunk_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        else:\n            assert (tensor.shape == chunk_shape\n                   ), f\"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}\"\n            sync_tensor = torch.empty_like(tensor, device=torch.cuda.current_device(), requires_grad=False)\n\n        for i in range(tp_size):\n            if torch.distributed.get_rank() == 0:\n                sync_tensor.data.copy_(tensor_chunk[i])\n            dist.broadcast(sync_tensor, src=0, group=mp_group)\n            if (i == tp_rank) and (tensor is not None):\n                tensor.data.copy_(sync_tensor)\n\n    def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        if torch.distributed.get_rank() == 0:\n            gate_weight = state_dict[gate_name]\n            up_weight = state_dict[up_name]\n            new_gate_up_weight = torch.empty(config.intermediate_size * 2,\n                                             config.hidden_size,\n                                             dtype=params_dtype,\n                                             device=torch.cuda.current_device())\n            for i in range(tp_size):\n                intermediate_size_tp = config.intermediate_size // tp_size\n                gate_weight_tp = gate_weight[i * intermediate_size_tp:(i + 1) * intermediate_size_tp]\n                up_weight_tp = up_weight[i * intermediate_size_tp:(i + 1) * intermediate_size_tp]\n                new_gate_up_weight[intermediate_size_tp * 2 * i:intermediate_size_tp * 2 * (i + 1)].copy_(\n                    torch.cat([gate_weight_tp, up_weight_tp], dim=0))\n\n            tensor_chunk = torch.chunk(new_gate_up_weight, tp_size, dim=0)\n            chunk_shape = tensor_chunk[0].shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{gate_name, up_name}] not in state_dict, skip loading\")\n            return\n\n        if tensor is None:\n            sync_tensor = torch.empty(\n                chunk_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        else:\n            assert (\n                tensor.shape == chunk_shape\n            ), f\"rank #{torch.distributed.get_rank() == 0:} tensor {gate_name, up_name} shape {tensor.shape} != {chunk_shape}\"\n            sync_tensor = torch.empty_like(tensor, device=torch.cuda.current_device(), requires_grad=False)\n\n        for i in range(tp_size):\n            if torch.distributed.get_rank() == 0:\n                sync_tensor.data.copy_(tensor_chunk[i])\n            dist.broadcast(sync_tensor, src=0, group=mp_group)\n            if (i == tp_rank) and (tensor is not None):\n                tensor.data.copy_(sync_tensor)\n\n    def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, bias=False) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        if torch.distributed.get_rank() == 0:\n            assert (q_name in state_dict and k_name in state_dict and v_name in state_dict)\n            full_weight_q = state_dict[q_name]\n            full_weight_k = state_dict[k_name]\n            full_weight_v = state_dict[v_name]\n\n            hidden_size_per_head = config.hidden_size // config.num_attention_heads\n\n            if config.num_key_value_heads >= tp_size:\n                q_size_tp = config.hidden_size // tp_size\n                kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size\n                total_size = q_size_tp + 2 * kv_size_tp\n                if not bias:\n                    new_weight_qkv = torch.empty(total_size * tp_size,\n                                                 config.hidden_size,\n                                                 dtype=params_dtype,\n                                                 device=torch.cuda.current_device())\n                else:\n                    new_weight_qkv = torch.empty(total_size * tp_size,\n                                                 dtype=params_dtype,\n                                                 device=torch.cuda.current_device())\n                for i in range(tp_size):\n                    q_part = full_weight_q[i * q_size_tp:(i + 1) * q_size_tp]\n                    k_part = full_weight_k[i * kv_size_tp:(i + 1) * kv_size_tp]\n                    v_part = full_weight_v[i * kv_size_tp:(i + 1) * kv_size_tp]\n                    new_weight_qkv[i * total_size:(i + 1) * total_size].copy_(torch.cat([q_part, k_part, v_part],\n                                                                                        dim=0))\n\n            else:\n                q_size_tp = config.hidden_size // tp_size\n                kv_size_tp = hidden_size_per_head\n                total_size = q_size_tp + 2 * kv_size_tp\n                if not bias:\n                    new_weight_qkv = torch.empty(total_size * tp_size,\n                                                 config.hidden_size,\n                                                 dtype=params_dtype,\n                                                 device=torch.cuda.current_device())\n                else:\n                    new_weight_qkv = torch.empty(total_size * tp_size,\n                                                 dtype=params_dtype,\n                                                 device=torch.cuda.current_device())\n                for i in range(tp_size):\n                    q_part = full_weight_q[i * q_size_tp:(i + 1) * q_size_tp]\n                    start_idx = i * config.num_key_value_heads // tp_size * hidden_size_per_head\n                    end_idx = (i * config.num_key_value_heads // tp_size + 1) * hidden_size_per_head\n                    k_part = full_weight_k[start_idx:end_idx]\n                    v_part = full_weight_v[start_idx:end_idx]\n                    new_weight_qkv[i * total_size:(i + 1) * total_size].copy_(torch.cat([q_part, k_part, v_part],\n                                                                                        dim=0))\n\n            tensor_chunk = torch.chunk(new_weight_qkv, tp_size, dim=0)\n            chunk_shape = tensor_chunk[0].shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{name}] not in state_dict, skip loading\")\n            return\n\n        if tensor is None:\n            sync_tensor = torch.empty(\n                chunk_shape,\n                dtype=params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n        else:\n            assert (tensor.shape == chunk_shape\n                   ), f\"rank #{torch.distributed.get_rank()} tensor {q_name} shape {tensor.shape} != {chunk_shape}\"\n            sync_tensor = torch.empty_like(tensor, device=torch.cuda.current_device(), requires_grad=False)\n\n        for i in range(tp_size):\n            if torch.distributed.get_rank() == 0:\n                sync_tensor.data.copy_(tensor_chunk[i])\n            dist.broadcast(sync_tensor, src=0, group=mp_group)\n            if (i == tp_rank) and (tensor is not None):\n                tensor.data.copy_(sync_tensor)\n\n    if dp_rank == 0:\n        # Embeddings\n        # -------------------\n        print_rank_0(\"loading embeddings...\")\n        gpt_model_module = _get_gpt_model(models[0])\n        embed_tokens_weight = None\n        if pp_rank == 0:\n            embed_tokens_weight = gpt_model_module.model.embed_tokens.weight\n        _broadcast_tp_shard_tensor_vocab(embed_tokens_weight, \"model.embed_tokens.weight\")\n\n        # Transformer layers\n        # -------------------\n        layer_map = _megatron_calc_layer_map(config)\n\n        for layer in range(config.num_hidden_layers):\n            print_rank_0(f\"loading layer #{layer}...\")\n            layer_name = f\"model.layers.{layer}\"\n            dst_pp_rank, dst_virtual_pp_rank, dst_layer_idx = layer_map[layer]\n\n            gpt_model_module = _get_gpt_model(models[dst_virtual_pp_rank])\n            sync_layer = gpt_model_module.model.layers[dst_layer_idx]\n\n            _broadcast_tensor(\n                sync_layer.input_layernorm.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.input_layernorm.weight\",\n            )\n\n            _broadcast_tp_shard_tensor_qkv(\n                sync_layer.self_attn.qkv_proj.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.self_attn.q_proj.weight\",\n                f\"{layer_name}.self_attn.k_proj.weight\",\n                f\"{layer_name}.self_attn.v_proj.weight\",\n            )\n\n            _broadcast_tp_shard_tensor_qkv(sync_layer.self_attn.qkv_proj.bias if dst_pp_rank == pp_rank else None,\n                                           f\"{layer_name}.self_attn.q_proj.bias\",\n                                           f\"{layer_name}.self_attn.k_proj.bias\",\n                                           f\"{layer_name}.self_attn.v_proj.bias\",\n                                           bias=True)\n\n            _broadcast_tp_shard_tensor(\n                sync_layer.self_attn.o_proj.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.self_attn.o_proj.weight\",\n                chunk_dim=1,\n            )\n\n            _broadcast_tensor(\n                sync_layer.post_attention_layernorm.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.post_attention_layernorm.weight\",\n            )\n\n            _broadcast_tp_shard_tensor_gate_up(sync_layer.mlp.gate_up_proj.weight if dst_pp_rank == pp_rank else None,\n                                               f\"{layer_name}.mlp.gate_proj.weight\", f\"{layer_name}.mlp.up_proj.weight\")\n\n            _broadcast_tp_shard_tensor(\n                sync_layer.mlp.down_proj.weight if dst_pp_rank == pp_rank else None,\n                f\"{layer_name}.mlp.down_proj.weight\",\n                chunk_dim=1,\n            )\n        # Final Layernorm\n        # -------------------\n        print_rank_0(\"loading final layernorm...\")\n        gpt_model_module = _get_gpt_model(models[-1])\n        _broadcast_tensor(\n            getattr(gpt_model_module.model.norm, \"weight\", None),\n            \"model.norm.weight\",\n        )\n\n        print_rank_0(\"loading lm_head...\")\n        lm_head_weight = None\n        if pp_rank + 1 == pp_size:\n            lm_head_weight = gpt_model_module.lm_head.weight\n\n        if is_value_model:\n            # if torch.distributed.get_rank() == 0:\n            if 'lm_head.weight' in state_dict and state_dict['lm_head.weight'].shape[0] == 1:\n                _broadcast_tensor(lm_head_weight, \"lm_head.weight\")\n            elif 'reward_head.weight' in state_dict and state_dict['reward_head.weight'].shape[0] == 1:\n                _broadcast_tensor(lm_head_weight, \"reward_head.weight\")\n                print_rank_0('load lm_head from value_head weight')\n            else:\n                _broadcast_tensor(None, \"lm_head.weight\")\n                print_rank_0('fail to match lm_head in value_model')\n            # else:\n\n            #     _broadcast_tensor(lm_head_weight, \"lm_head.weight\")\n\n        else:\n            _broadcast_tp_shard_tensor(lm_head_weight, \"lm_head.weight\")\n    dist.barrier()\n    # Broadcast weights inside data parallel groups\n    for wrapped_model in wrapped_models:\n        broadcast_params(wrapped_model)\n\n    torch.cuda.empty_cache()\n    print_rank_0(f\"loading megatron ckpt done, time elapsed {time.time() - start_time}s\")\n"
  },
  {
    "path": "verl/models/qwen2/megatron/checkpoint_utils/qwen2_saver.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport megatron\nfrom megatron.core import mpu\nfrom megatron.training.utils import print_rank_0, unwrap_model\nfrom megatron.core.transformer.module import Float16Module\nfrom megatron.core.distributed import DistributedDataParallel as LocalDDP\nfrom torch.nn.parallel import DistributedDataParallel as torchDDP\nimport torch\nimport time\nfrom typing import Optional\nimport torch.distributed as dist\nfrom megatron import get_args\n\n\ndef _megatron_calc_global_rank(tp_rank: int = 0, dp_rank: int = 0, pp_rank: int = 0):\n    \"\"\"given TP,DP,PP rank to get the global rank.\"\"\"\n\n    args = get_args()\n    tp_size = mpu.get_tensor_model_parallel_world_size()\n    dp_size = mpu.get_data_parallel_world_size()\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    assert (tp_size * dp_size * pp_size == torch.distributed.get_world_size()\n           ), f\"{tp_size} x {dp_size} x {pp_size} != {torch.distributed.get_world_size()}\"\n    if args.switch_dp_and_pp_grouping:\n        # TP-PP-DP grouping\n        return (dp_rank * pp_size + pp_rank) * tp_size + tp_rank\n    else:\n        # TP-DP-PP grouping\n        return (pp_rank * dp_size + dp_rank) * tp_size + tp_rank\n\n\ndef _megatron_calc_layer_map(config):\n    \"\"\"Calculate the mapping of global layer_idx to local layer_idx\n    Returns:\n        layer_map (Dict: int -> tuple(int, int, int)):\n            mapping from the global layer index to\n            a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model)\n    \"\"\"\n    import megatron\n    from megatron.core import mpu\n\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n\n    args = megatron.get_args()\n    layer_map = dict()\n    num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n    assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n    for pp_rank_idx in range(pp_size):\n        for virtual_pp_rank_idx in range(virtual_pp_size):\n            layer_offset = (virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) +\n                            pp_rank_idx * num_layers_per_model)\n            for layer_idx in range(num_layers_per_model):\n                layer_map[layer_offset + layer_idx] = (\n                    pp_rank_idx,\n                    virtual_pp_rank_idx,\n                    layer_idx,\n                )\n    return layer_map\n\n\ndef merge_megatron_ckpt_llama(wrapped_models, config, is_value_model=False, dtype='bf16'):\n    \"\"\"Merge sharded parameters of a Megatron module into a merged checkpoint.\n\n    Args:\n        wrapped_modelss (list of megatron.core.distributed.DistributedDataParallel):\n            The local DDP wrapped megatron modules.\n        dtype (str or None):\n            The data type of state_dict. if None, the data type of the original parameters\n            is used.\n        gpt_model_key: key to access model\n    Returns:\n        state_dict (dict):\n            The merged state_dict in rank 0, and an empty dictionary in other ranks.\n    \"\"\"\n    start_time = time.time()\n    args = megatron.get_args()\n\n    def _get_gpt_model(model):\n        return model\n\n    dp_rank = mpu.get_data_parallel_rank()\n    pp_size = mpu.get_pipeline_model_parallel_world_size()\n    pp_rank = mpu.get_pipeline_model_parallel_rank()\n    virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n    mp_group = mpu.get_model_parallel_group()\n\n    if dist.get_rank() == 0:\n        assert mp_group.rank() == 0, f\"mp_rank:[{mp_group.rank}] != 0 on rank #0\"\n        assert pp_rank == 0, f\"pp_rank:[{pp_rank}] != 0 on rank #0\"\n        assert dp_rank == 0, f\"dp_rank:[{dp_rank}] != 0 on rank #0\"\n\n    if not isinstance(wrapped_models, (list, tuple)):\n        wrapped_models = list(wrapped_models)\n\n    assert len(wrapped_models) == virtual_pp_size\n    num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n    assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n    models = [None] * len(wrapped_models)\n\n    for i, wrapped_model in enumerate(wrapped_models):\n        models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module))\n        assert len(models[i].model.layers\n                  ) == num_layers_per_model, 'len model layers {} not equal to num_layers_per_model {}'.format(\n                      len(models[i].model.layers), num_layers_per_model)\n\n    state_dict = dict()\n\n    def _get_cpu_tensor(tensor: torch.Tensor):\n        if tensor is None:\n            return None\n        if tensor.device == torch.device(\"cpu\"):\n            return tensor.detach().clone()\n        return tensor.detach().cpu()\n\n    def _broadcast_tensor(tensor, name, src_pp_rank) -> torch.Tensor:\n        \"\"\"broadcast tensor across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n        if torch.distributed.get_rank() == src_rank:\n            if tensor is None:\n                weight = None\n                tensor_shape = None\n            else:\n                weight = tensor\n                tensor_shape = weight.shape\n        else:\n            weight = None\n            tensor_shape = None\n\n        obj_list = [tensor_shape]\n        dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n        tensor_shape = obj_list[0]\n\n        if tensor_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tensor:[{name}] not exist, skip collect\")\n            return\n\n        if weight is None:\n            weight = torch.empty(\n                tensor_shape,\n                dtype=args.params_dtype,\n                device=torch.cuda.current_device(),\n                requires_grad=False,\n            )\n\n        dist.broadcast(weight, src=src_rank, group=mp_group)\n\n        if torch.distributed.get_rank() == 0:\n            state_dict[name] = _get_cpu_tensor(weight)\n\n    def _broadcast_tp_shard_tensor(tensor, name, src_pp_rank, concat_dim=0, mutate_func=None) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n        if torch.distributed.get_rank() == src_rank:\n            chunk_shape = tensor.shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{name}] not exist, skip collecting\")\n            return\n\n        buffer_tensor = torch.empty(\n            chunk_shape,\n            dtype=args.params_dtype,\n            device=torch.cuda.current_device(),\n            requires_grad=False,\n        )\n\n        chunk_tensors = [None] * tp_size\n\n        for i in range(tp_size):\n            cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n            sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n            dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n            if torch.distributed.get_rank() == 0:\n                chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n        if torch.distributed.get_rank() == 0:\n            full_tensor = torch.concat(chunk_tensors, dim=concat_dim)\n            if mutate_func is not None:\n                full_tensor = mutate_func(full_tensor)\n            state_dict[name] = full_tensor\n\n    def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name, src_pp_rank) -> torch.Tensor:\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n        if torch.distributed.get_rank() == src_rank:\n            chunk_shape = tensor.shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{gate_name, up_name}] not exist, skip collecting\")\n            return\n\n        buffer_tensor = torch.empty(\n            chunk_shape,\n            dtype=args.params_dtype,\n            device=torch.cuda.current_device(),\n            requires_grad=False,\n        )\n\n        chunk_tensors = [None] * tp_size\n\n        for i in range(tp_size):\n            cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n            sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n            dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n            if torch.distributed.get_rank() == 0:\n                chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n        if torch.distributed.get_rank() == 0:\n            full_tensor = torch.concat(chunk_tensors, dim=0)\n            intermediate_size_tp = config.intermediate_size // tp_size\n            gate_weight_list = []\n            up_weight_list = []\n            for i in range(tp_size):\n                gate_up_weight_tp = full_tensor[intermediate_size_tp * 2 * i:intermediate_size_tp * 2 * (i + 1)]\n                gate_weight_tp = gate_up_weight_tp[:intermediate_size_tp]\n                up_weight_tp = gate_up_weight_tp[intermediate_size_tp:]\n                gate_weight_list.append(gate_weight_tp)\n                up_weight_list.append(up_weight_tp)\n\n            state_dict[gate_name] = torch.cat(gate_weight_list, dim=0)\n            state_dict[up_name] = torch.cat(up_weight_list, dim=0)\n\n    def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, src_pp_rank):\n        \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n        nonlocal state_dict\n        nonlocal mp_group\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n        if torch.distributed.get_rank() == src_rank:\n            chunk_shape = tensor.shape\n        else:\n            chunk_shape = None\n\n        obj_list = [chunk_shape]\n        dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n        chunk_shape = obj_list[0]\n        if chunk_shape is None:\n            # all or none ranks in the mp_group should reach here\n            print_rank_0(f\"tp_shard tensor:[{q_name}] not exist, skip collecting\")\n            return\n\n        buffer_tensor = torch.empty(\n            chunk_shape,\n            dtype=args.params_dtype,\n            device=torch.cuda.current_device(),\n            requires_grad=False,\n        )\n\n        chunk_tensors = [None] * tp_size\n\n        for i in range(tp_size):\n            cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n            sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n            dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n            if torch.distributed.get_rank() == 0:\n                chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n        if torch.distributed.get_rank() == 0:\n            full_tensor = torch.concat(chunk_tensors, dim=0)\n            q_weight_list = []\n            k_weight_list = []\n            v_weight_list = []\n            hidden_size_per_head = config.hidden_size // config.num_attention_heads\n\n            if config.num_key_value_heads >= tp_size:\n                q_size_tp = config.hidden_size // tp_size\n                kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size\n                total_size = q_size_tp + 2 * kv_size_tp\n                for i in range(tp_size):\n                    qkv_part = full_tensor[i * total_size:(i + 1) * total_size]\n                    q_part = qkv_part[:q_size_tp]\n                    k_part = qkv_part[q_size_tp:q_size_tp + kv_size_tp]\n                    v_part = qkv_part[q_size_tp + kv_size_tp:total_size]\n                    q_weight_list.append(q_part)\n                    k_weight_list.append(k_part)\n                    v_weight_list.append(v_part)\n            else:\n                q_size_tp = config.hidden_size // tp_size\n                kv_size_tp = hidden_size_per_head\n                total_size = q_size_tp + 2 * kv_size_tp\n                for i in range(tp_size):\n                    qkv_part = full_tensor[i * total_size:(i + 1) * total_size]\n                    q_part = qkv_part[:q_size_tp]\n                    k_part = qkv_part[q_size_tp:q_size_tp + kv_size_tp]\n                    v_part = qkv_part[q_size_tp + kv_size_tp:total_size]\n                    q_weight_list.append(q_part)\n                    if i * config.num_key_value_heads % tp_size == 0:\n                        k_weight_list.append(k_part)\n                        v_weight_list.append(v_part)\n\n            state_dict[q_name] = torch.cat(q_weight_list, dim=0)\n            state_dict[k_name] = torch.cat(k_weight_list, dim=0)\n            state_dict[v_name] = torch.cat(v_weight_list, dim=0)\n\n    # empty cache before collecting weights\n    torch.cuda.empty_cache()\n    # Embeddings\n    # -------------------\n    if dp_rank == 0:\n        # Embeddings\n        # -------------------\n        print_rank_0(\"collecting embeddings...\")\n        gpt_model_module = _get_gpt_model(models[0])\n        _broadcast_tp_shard_tensor(\n            gpt_model_module.model.embed_tokens.weight if pp_rank == 0 else None,\n            \"model.embed_tokens.weight\",\n            src_pp_rank=0,\n        )\n\n        # Transformer layers\n        # -------------------\n        layer_map = _megatron_calc_layer_map(config)\n        for layer in range(config.num_hidden_layers):\n            print_rank_0(f\"collecting layer #{layer}...\")\n            layer_name = f\"model.layers.{layer}\"\n            src_pp_rank, src_virtual_pp_rank, src_layer_idx = layer_map[layer]\n\n            gpt_model_module = _get_gpt_model(models[src_virtual_pp_rank])\n            sync_layer = gpt_model_module.model.layers[src_layer_idx]\n\n            _broadcast_tensor(\n                sync_layer.input_layernorm.weight,\n                f\"{layer_name}.input_layernorm.weight\",\n                src_pp_rank=src_pp_rank,\n            )\n\n            _broadcast_tp_shard_tensor_qkv(\n                sync_layer.self_attn.qkv_proj.weight,\n                f\"{layer_name}.self_attn.q_proj.weight\",\n                f\"{layer_name}.self_attn.k_proj.weight\",\n                f\"{layer_name}.self_attn.v_proj.weight\",\n                src_pp_rank=src_pp_rank,\n            )\n\n            _broadcast_tp_shard_tensor(\n                sync_layer.self_attn.o_proj.weight,\n                f\"{layer_name}.self_attn.o_proj.weight\",\n                concat_dim=1,\n                src_pp_rank=src_pp_rank,\n            )\n\n            _broadcast_tensor(\n                sync_layer.post_attention_layernorm.weight,\n                f\"{layer_name}.post_attention_layernorm.weight\",\n                src_pp_rank=src_pp_rank,\n            )\n\n            _broadcast_tp_shard_tensor_gate_up(sync_layer.mlp.gate_up_proj.weight,\n                                               f\"{layer_name}.mlp.gate_proj.weight\",\n                                               f\"{layer_name}.mlp.up_proj.weight\",\n                                               src_pp_rank=src_pp_rank)\n\n            _broadcast_tp_shard_tensor(\n                sync_layer.mlp.down_proj.weight,\n                f\"{layer_name}.mlp.down_proj.weight\",\n                concat_dim=1,\n                src_pp_rank=src_pp_rank,\n            )\n\n        # Final Layernorm\n        # -------------------\n        print_rank_0(\"collecting final layernorm...\")\n        gpt_model_module = _get_gpt_model(models[-1])\n        _broadcast_tensor(\n            getattr(gpt_model_module.model.norm, \"weight\", None),\n            \"model.norm.weight\",\n            src_pp_rank=pp_size - 1,\n        )\n\n        print_rank_0(\"collecting lm_head...\")\n\n        if is_value_model:\n            _broadcast_tensor(getattr(gpt_model_module.lm_head, \"weight\", None) if pp_rank == pp_size - 1 else None,\n                              \"reward_head.weight\",\n                              src_pp_rank=pp_size - 1)\n\n        else:\n            _broadcast_tp_shard_tensor(\n                getattr(gpt_model_module.lm_head, \"weight\", None) if pp_rank == pp_size - 1 else None,\n                \"lm_head.weight\",\n                src_pp_rank=pp_size - 1,\n            )\n\n    dist.barrier()\n\n    torch.cuda.empty_cache()\n    if torch.distributed.get_rank() == 0:\n        if dtype == \"fp16\":\n            dtype = torch.float16\n        elif dtype == \"bf16\":\n            dtype = torch.bfloat16\n        elif dtype is None or dtype == \"fp32\":\n            dtype = torch.float32\n        else:\n            print(f'Unknown/unsupported dtype to save: {dtype}\"')\n            exit(1)\n        for k, v in state_dict.items():\n            if dtype != v.dtype:\n                state_dict[k] = v.to(dtype)\n\n    print_rank_0(f\"merge megatron ckpt done, time elapsed {time.time() - start_time}s\")\n    return state_dict\n"
  },
  {
    "path": "verl/models/qwen2/megatron/layers/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .parallel_attention import ParallelQwen2Attention\nfrom .parallel_decoder import ParallelQwen2DecoderLayer, ParallelQwen2DecoderLayerRmPad\nfrom .parallel_mlp import ParallelQwen2MLP\nfrom .parallel_rmsnorm import ParallelQwen2RMSNorm\n"
  },
  {
    "path": "verl/models/qwen2/megatron/layers/parallel_attention.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nfrom typing import Optional, Tuple\n\nimport torch\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core import tensor_parallel\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers import Qwen2Config\nfrom verl.models.qwen2.megatron.layers.parallel_linear import QKVParallelLinear\n\nfrom verl.utils.megatron import tensor_parallel as tp_utils\n\n\nclass Qwen2RotaryEmbedding(nn.Module):\n\n    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):\n        super().__init__()\n\n        self.dim = dim\n        self.max_position_embeddings = max_position_embeddings\n        self.base = base\n        inv_freq = 1.0 / (self.base**(torch.arange(0, self.dim, 2).float().to(device) / self.dim))\n        self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n\n        # Build here to make `torch.jit.trace` work.\n        self._set_cos_sin_cache(seq_len=max_position_embeddings,\n                                device=self.inv_freq.device,\n                                dtype=torch.get_default_dtype())\n\n    def _set_cos_sin_cache(self, seq_len, device, dtype):\n        self.max_seq_len_cached = seq_len\n        t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)\n\n        freqs = torch.einsum(\"i,j->ij\", t, self.inv_freq)\n        # Different from paper, but it uses a different permutation in order to obtain the same calculation\n        emb = torch.cat((freqs, freqs), dim=-1)\n        self.register_buffer(\"cos_cached\", emb.cos().to(dtype), persistent=False)\n        self.register_buffer(\"sin_cached\", emb.sin().to(dtype), persistent=False)\n\n    def forward(self, x, seq_len=None):\n        # x: [bs, num_attention_heads, seq_len, head_size]\n        if seq_len > self.max_seq_len_cached:\n            self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)\n\n        return (\n            self.cos_cached[:seq_len].to(dtype=x.dtype),\n            self.sin_cached[:seq_len].to(dtype=x.dtype),\n        )\n\n\nclass Qwen2LinearScalingRotaryEmbedding(Qwen2RotaryEmbedding):\n    \"\"\"Qwen2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev\"\"\"\n\n    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):\n        self.scaling_factor = scaling_factor\n        super().__init__(dim, max_position_embeddings, base, device)\n\n    def _set_cos_sin_cache(self, seq_len, device, dtype):\n        self.max_seq_len_cached = seq_len\n        t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)\n        t = t / self.scaling_factor\n\n        freqs = torch.einsum(\"i,j->ij\", t, self.inv_freq)\n        # Different from paper, but it uses a different permutation in order to obtain the same calculation\n        emb = torch.cat((freqs, freqs), dim=-1)\n        self.register_buffer(\"cos_cached\", emb.cos().to(dtype), persistent=False)\n        self.register_buffer(\"sin_cached\", emb.sin().to(dtype), persistent=False)\n\n\nclass Qwen2DynamicNTKScalingRotaryEmbedding(Qwen2RotaryEmbedding):\n    \"\"\"Qwen2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla\"\"\"\n\n    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):\n        self.scaling_factor = scaling_factor\n        super().__init__(dim, max_position_embeddings, base, device)\n\n    def _set_cos_sin_cache(self, seq_len, device, dtype):\n        self.max_seq_len_cached = seq_len\n\n        if seq_len > self.max_position_embeddings:\n            base = self.base * ((self.scaling_factor * seq_len / self.max_position_embeddings) -\n                                (self.scaling_factor - 1))**(self.dim / (self.dim - 2))\n            inv_freq = 1.0 / (base**(torch.arange(0, self.dim, 2).float().to(device) / self.dim))\n            self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n\n        t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)\n\n        freqs = torch.einsum(\"i,j->ij\", t, self.inv_freq)\n        # Different from paper, but it uses a different permutation in order to obtain the same calculation\n        emb = torch.cat((freqs, freqs), dim=-1)\n        self.register_buffer(\"cos_cached\", emb.cos().to(dtype), persistent=False)\n        self.register_buffer(\"sin_cached\", emb.sin().to(dtype), persistent=False)\n\n\ndef rotate_half(x):\n    \"\"\"Rotates half the hidden dims of the input.\"\"\"\n    x1 = x[..., :x.shape[-1] // 2]\n    x2 = x[..., x.shape[-1] // 2:]\n    return torch.cat((-x2, x1), dim=-1)\n\n\ndef apply_rotary_pos_emb(q, k, cos, sin, position_ids):\n    cos = cos[position_ids].unsqueeze(1)  # [bs, 1, seq_len, dim]\n    sin = sin[position_ids].unsqueeze(1)  # [bs, 1, seq_len, dim]\n    q_embed = (q * cos) + (rotate_half(q) * sin)\n    k_embed = (k * cos) + (rotate_half(k) * sin)\n    return q_embed, k_embed\n\n\ndef repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n    \"\"\"\n    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n    \"\"\"\n    batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n    if n_rep == 1:\n        return hidden_states\n    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)\n    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n\nclass ParallelQwen2Attention(nn.Module):\n    \"\"\"Multi-headed attention from 'Attention Is All You Need' paper\"\"\"\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.config = config\n        self.megatron_config = megatron_config\n        self.hidden_size = config.hidden_size\n        self.num_heads = config.num_attention_heads\n        self.head_dim = self.hidden_size // self.num_heads\n        self.num_key_value_heads = config.num_key_value_heads\n        self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n        self.max_position_embeddings = config.max_position_embeddings\n        self.rope_theta = config.rope_theta\n\n        # assign values after tp\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        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}'\n        assert self.num_key_value_heads % tp_size == 0, \\\n            f'num_key_value_heads must be divisible by tp_size. Got num_key_value_heads={self.num_key_value_heads}, tp_size={tp_size}'\n\n        self.num_heads_per_tp = self.num_heads // tp_size\n        self.num_key_value_heads_per_tp = self.num_key_value_heads // tp_size\n        self.hidden_size_per_tp = self.hidden_size // tp_size\n\n        if (self.head_dim * self.num_heads) != self.hidden_size:\n            raise ValueError(f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n                             f\" and `num_heads`: {self.num_heads}).\")\n\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear()\n\n        if megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            assert row_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, megatron_config)\n            tp_utils.update_kwargs_with_config(row_kwargs, megatron_config)\n\n        # [self.q_size, self.k_size, self.v_size]\n        self.qkv_proj = QKVParallelLinear(\n            input_size=self.hidden_size,\n            num_heads=self.num_heads,\n            num_key_value_heads=self.num_key_value_heads,\n            head_dim=self.head_dim,\n            # bias=config.attention_bias,\n            bias=True,\n            gather_output=False,\n            skip_bias_add=False,\n            **column_kwargs)\n\n        self.q_size = self.num_heads_per_tp * self.head_dim\n        self.k_size = self.num_key_value_heads_per_tp * self.head_dim\n        self.v_size = self.num_key_value_heads_per_tp * self.head_dim\n\n        self.o_proj = tensor_parallel.RowParallelLinear(\n            input_size=self.num_heads * self.head_dim,\n            output_size=self.hidden_size,\n            # bias=config.attention_bias,\n            bias=False,\n            input_is_parallel=True,\n            skip_bias_add=False,\n            **row_kwargs)\n\n        self._init_rope()\n\n    def _init_rope(self):\n        self.rotary_emb = Qwen2RotaryEmbedding(\n            self.head_dim,\n            max_position_embeddings=self.max_position_embeddings,\n            base=self.rope_theta,\n        )\n\n    def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):\n        return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n        bsz, q_len, _ = hidden_states.size()\n        qkv = self.qkv_proj(hidden_states)[0]\n        query_states, key_states, value_states = qkv.split([self.q_size, self.k_size, self.v_size], dim=-1)\n\n        query_states = query_states.view(bsz, q_len, self.num_heads_per_tp, self.head_dim).transpose(1, 2)\n        key_states = key_states.view(bsz, q_len, self.num_key_value_heads_per_tp, self.head_dim).transpose(1, 2)\n        value_states = value_states.view(bsz, q_len, self.num_key_value_heads_per_tp, self.head_dim).transpose(1, 2)\n\n        kv_seq_len = key_states.shape[-2]\n        cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)\n        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)\n\n        key_states = repeat_kv(key_states, self.num_key_value_groups)\n        value_states = repeat_kv(value_states, self.num_key_value_groups)\n\n        attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)\n\n        if attn_weights.size() != (bsz, self.num_heads_per_tp, q_len, kv_seq_len):\n            raise ValueError(\n                f\"Attention weights should be of size {(bsz, self.num_heads_per_tp, q_len, kv_seq_len)}, but is\"\n                f\" {attn_weights.size()}\")\n\n        if attention_mask is not None:\n            if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):\n                raise ValueError(\n                    f\"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}\")\n            attn_weights = attn_weights + attention_mask\n\n        # upcast attention to fp32\n        attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)\n        attn_output = torch.matmul(attn_weights, value_states)\n\n        if attn_output.size() != (bsz, self.num_heads_per_tp, q_len, self.head_dim):\n            raise ValueError(\n                f\"`attn_output` should be of size {(bsz, self.num_heads_per_tp, q_len, self.head_dim)}, but is\"\n                f\" {attn_output.size()}\")\n\n        attn_output = attn_output.transpose(1, 2).contiguous()\n        attn_output = attn_output.reshape(bsz, q_len, self.hidden_size_per_tp)\n        attn_output = self.o_proj(attn_output)[0]\n        return attn_output\n\n\n\"\"\"\nRemove padding Attention\n- Using Flash-attn 2\n- Compatible with sequence parallel\n\"\"\"\n\nfrom transformers.utils import is_flash_attn_2_available\nimport torch.nn.functional as F\n\nfrom einops import rearrange\n\nif is_flash_attn_2_available():\n    from flash_attn import flash_attn_varlen_func\n    from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input  # noqa\n\n\ndef apply_rotary_pos_emb_rmpad(q, k, cos, sin, position_ids, indices, sequence_length):\n    batch_size = position_ids.shape[0]\n\n    q = pad_input(q, indices, batch_size, sequence_length)  # (batch_size, seqlen, num_head, head_dim)\n    k = pad_input(k, indices, batch_size, sequence_length)\n    cos = cos[position_ids].unsqueeze(2)  # [bs, seq_len, 1, dim]\n    sin = sin[position_ids].unsqueeze(2)  # [bs, seq_len, 1, dim]\n    q_embed = (q * cos) + (rotate_half(q) * sin)\n    k_embed = (k * cos) + (rotate_half(k) * sin)\n\n    q_embed = index_first_axis(rearrange(q_embed, \"b s ... -> (b s) ...\"), indices)\n    k_embed = index_first_axis(rearrange(k_embed, \"b s ... -> (b s) ...\"), indices)\n\n    return q_embed, k_embed\n\n\nfrom flash_attn.layers.rotary import apply_rotary_emb\n\n\n# use flash-attn rotary embeddings with rmpad\n# cos/sin shoudl be: (seq_length, rotary_dim / 2)\ndef apply_rotary_pos_emb_rmpad_flash(q, k, cos, sin, cu_seqlens, max_seqlen):\n    q_embed = apply_rotary_emb(q,\n                               cos,\n                               sin,\n                               interleaved=False,\n                               inplace=False,\n                               cu_seqlens=cu_seqlens,\n                               max_seqlen=max_seqlen)\n    k_embed = apply_rotary_emb(k,\n                               cos,\n                               sin,\n                               interleaved=False,\n                               inplace=False,\n                               cu_seqlens=cu_seqlens,\n                               max_seqlen=max_seqlen)\n    return q_embed, k_embed\n\n\nclass ParallelQwen2AttentionRmPad(ParallelQwen2Attention):\n\n    def forward(self,\n                hidden_states: torch.Tensor,\n                position_ids: Optional[torch.LongTensor] = None,\n                sequence_length: int = None,\n                indices: torch.Tensor = None,\n                cu_seqlens: torch.Tensor = None,\n                max_seqlen_in_batch: int = None):\n        total_nnz, _, _ = hidden_states.size()  # This is the total_nnz padded after sequence parallel\n\n        if self.megatron_config.sequence_parallel:\n            total_nnz = total_nnz * mpu.get_tensor_model_parallel_world_size()\n\n        qkv = self.qkv_proj(hidden_states)[0]\n        query_states, key_states, value_states = qkv.split([self.q_size, self.k_size, self.v_size],\n                                                           dim=-1)  # (total_nnz, 1, hidden_size)\n\n        if self.megatron_config.sequence_parallel:\n            sequence_parallel_pad = total_nnz - cu_seqlens[-1]\n            total_nnz = cu_seqlens[-1]  # total_nnz before sp padding\n            query_states = query_states[:total_nnz]\n            key_states = key_states[:total_nnz]\n            value_states = value_states[:total_nnz]\n\n        # Flash attention requires the input to have the shape\n        # batch_size x seq_length x head_dime x hidden_dim\n        # therefore we just need to keep the original shape\n        query_states = query_states.view(total_nnz, self.num_heads_per_tp, self.head_dim)\n        key_states = key_states.view(total_nnz, self.num_key_value_heads_per_tp, self.head_dim)\n        value_states = value_states.view(total_nnz, self.num_key_value_heads_per_tp, self.head_dim)\n\n        cos, sin = self.rotary_emb(value_states, seq_len=sequence_length)\n        cos, sin = cos[:, :cos.shape[1] // 2], sin[:, :sin.shape[1] // 2]  # flash attn only needs half\n        query_states, key_states = apply_rotary_pos_emb_rmpad_flash(query_states,\n                                                                    key_states,\n                                                                    cos,\n                                                                    sin,\n                                                                    cu_seqlens=cu_seqlens,\n                                                                    max_seqlen=max_seqlen_in_batch)\n        # query_states, key_states = apply_rotary_pos_emb_rmpad(query_states, key_states, cos, sin, position_ids, indices,\n\n        # It is recommended to use dropout with FA according to the docs\n        # when training.\n        dropout_rate = 0.0  # if not self.training else self.attn_dropout\n\n        # In PEFT, usually we cast the layer norms in float32 for training stability reasons\n        # therefore the input hidden states gets silently casted in float32. Hence, we need\n        # cast them back in float16 just to be sure everything works as expected.\n        # This might slowdown training & inference so it is recommended to not cast the LayerNorms\n        # in fp32. (Qwen2RMSNorm handles it correctly)\n        input_dtype = query_states.dtype\n        if input_dtype == torch.float32:\n            query_states = query_states.to(torch.float16)\n            key_states = key_states.to(torch.float16)\n            value_states = value_states.to(torch.float16)\n\n        attn_output_unpad = flash_attn_varlen_func(\n            query_states,\n            key_states,\n            value_states,\n            cu_seqlens_q=cu_seqlens,\n            cu_seqlens_k=cu_seqlens,\n            max_seqlen_q=max_seqlen_in_batch,\n            max_seqlen_k=max_seqlen_in_batch,\n            dropout_p=dropout_rate,\n            softmax_scale=None,\n            causal=True,\n        )\n\n        attn_output_unpad = attn_output_unpad.to(input_dtype)\n        attn_output_unpad = attn_output_unpad.reshape(total_nnz, 1, self.hidden_size_per_tp).contiguous()\n\n        # sequence parallel reduce_scatter is performed inside RowColumnParallel if enabled\n        # Here we need to repad\n        if self.megatron_config.sequence_parallel:\n            attn_output_unpad = F.pad(attn_output_unpad, pad=(0, 0, 0, 0, 0, sequence_parallel_pad))\n\n        attn_output_unpad = self.o_proj(attn_output_unpad)[0]\n        return attn_output_unpad\n"
  },
  {
    "path": "verl/models/qwen2/megatron/layers/parallel_decoder.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Optional, Tuple\n\nimport torch\nfrom torch import nn\nfrom transformers import Qwen2Config\nfrom megatron.core import ModelParallelConfig\n\nfrom .parallel_attention import ParallelQwen2Attention, ParallelQwen2AttentionRmPad\nfrom .parallel_mlp import ParallelQwen2MLP\nfrom .parallel_rmsnorm import ParallelQwen2RMSNorm\n\n\nclass ParallelQwen2DecoderLayer(nn.Module):\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.hidden_size = config.hidden_size\n        self.self_attn = ParallelQwen2Attention(config=config, megatron_config=megatron_config)\n\n        self.mlp = ParallelQwen2MLP(config, megatron_config=megatron_config)\n        self.input_layernorm = ParallelQwen2RMSNorm(config, megatron_config)\n        self.post_attention_layernorm = ParallelQwen2RMSNorm(config, megatron_config)\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n        \"\"\"\n        Args:\n            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\n            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size\n                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.\n            output_attentions (`bool`, *optional*):\n                Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n                returned tensors for more detail.\n            use_cache (`bool`, *optional*):\n                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding\n                (see `past_key_values`).\n            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states\n        \"\"\"\n\n        residual = hidden_states\n\n        hidden_states = self.input_layernorm(hidden_states)\n\n        # Note: sequence parallel is hidden inside ColumnParallelLinear\n        # reduce scatter is hidden inside RowParallelLinear\n\n        # Self Attention\n        hidden_states = self.self_attn(\n            hidden_states=hidden_states,\n            attention_mask=attention_mask,\n            position_ids=position_ids,\n        )\n\n        # TODO: add sequence parallel operator reduce_scatter here\n\n        hidden_states = residual + hidden_states\n\n        # Fully Connected\n        residual = hidden_states\n        hidden_states = self.post_attention_layernorm(hidden_states)\n\n        # TODO: add sequence parallel operator all_gather here\n\n        hidden_states = self.mlp(hidden_states)\n\n        # TODO: add sequence parallel operator reduce_scatter here\n\n        hidden_states = residual + hidden_states\n\n        outputs = hidden_states\n\n        return outputs\n\n\nclass ParallelQwen2DecoderLayerRmPad(nn.Module):\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.config = config\n        self.megatron_config = megatron_config\n        self.hidden_size = config.hidden_size\n        self.self_attn = ParallelQwen2AttentionRmPad(config=config, megatron_config=megatron_config)\n\n        self.mlp = ParallelQwen2MLP(config, megatron_config=megatron_config)\n        self.input_layernorm = ParallelQwen2RMSNorm(config, megatron_config)\n        self.post_attention_layernorm = ParallelQwen2RMSNorm(config, megatron_config)\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        position_ids: Optional[torch.LongTensor] = None,\n        sequence_length: int = None,\n        indices: torch.Tensor = None,\n        cu_seqlens: int = None,\n        max_seqlen_in_batch: int = None\n    ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n        residual = hidden_states  # (total_nnz // sp, 1, hidden_size)\n\n        hidden_states = self.input_layernorm(hidden_states)\n\n        # Self Attention\n        # (total_nnz // sp, 1, hidden_size) -> all-gather (total_nnz, 1, hidden_size)\n        # -> col + row -> reduce-scatter -> (total_nnz // sp, 1, hidden_size)\n        hidden_states = self.self_attn(hidden_states=hidden_states,\n                                       position_ids=position_ids,\n                                       sequence_length=sequence_length,\n                                       indices=indices,\n                                       cu_seqlens=cu_seqlens,\n                                       max_seqlen_in_batch=max_seqlen_in_batch)\n\n        hidden_states = residual + hidden_states\n\n        # Fully Connected\n        # shape changes same as attn\n        residual = hidden_states\n        hidden_states = self.post_attention_layernorm(hidden_states)\n        hidden_states = self.mlp(hidden_states)\n        hidden_states = residual + hidden_states\n\n        outputs = hidden_states\n\n        return outputs\n"
  },
  {
    "path": "verl/models/qwen2/megatron/layers/parallel_linear.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/linear.py\n\nfrom typing import Optional, Tuple\n\nfrom megatron.core import tensor_parallel\n\n\nclass QKVParallelLinear(tensor_parallel.ColumnParallelLinear):\n\n    def __init__(self,\n                 input_size,\n                 num_heads,\n                 num_key_value_heads,\n                 head_dim,\n                 *,\n                 bias=True,\n                 gather_output=True,\n                 skip_bias_add=False,\n                 **kwargs):\n        # Keep input parameters, and already restrict the head numbers\n        self.input_size = input_size\n        self.q_output_size = num_heads * head_dim\n        self.kv_output_size = num_key_value_heads * head_dim\n        self.head_dim = head_dim\n        self.gather_output = gather_output\n        self.skip_bias_add = skip_bias_add\n\n        input_size = self.input_size\n        output_size = (num_heads + 2 * num_key_value_heads) * self.head_dim\n\n        super().__init__(input_size=input_size,\n                         output_size=output_size,\n                         bias=bias,\n                         gather_output=gather_output,\n                         skip_bias_add=skip_bias_add,\n                         **kwargs)\n\n\nclass MergedColumnParallelLinear(tensor_parallel.ColumnParallelLinear):\n\n    def __init__(self,\n                 input_size,\n                 gate_ouput_size,\n                 up_output_size,\n                 *,\n                 bias=True,\n                 gather_output=True,\n                 skip_bias_add=False,\n                 **kwargs):\n        # Keep input parameters, and already restrict the head numbers\n        self.input_size = input_size\n        self.output_size = gate_ouput_size + up_output_size\n        self.gather_output = gather_output\n        self.skip_bias_add = skip_bias_add\n\n        super().__init__(input_size=self.input_size,\n                         output_size=self.output_size,\n                         bias=bias,\n                         gather_output=gather_output,\n                         skip_bias_add=skip_bias_add,\n                         **kwargs)\n"
  },
  {
    "path": "verl/models/qwen2/megatron/layers/parallel_mlp.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core import tensor_parallel\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers.activations import ACT2FN\nfrom verl.models.qwen2.megatron.layers.parallel_linear import MergedColumnParallelLinear\n\nfrom verl.utils.megatron import tensor_parallel as tp_utils\n\n\nclass ParallelQwen2MLP(nn.Module):\n\n    def __init__(self, config, megatron_config: ModelParallelConfig = None) -> None:\n        super().__init__()\n        self.config = config\n        self.hidden_size = config.hidden_size\n        self.intermediate_size = config.intermediate_size\n        # The weight is only [hidden_size, intermediate_size // model_parallel_world_size]\n\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear()\n\n        if megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            assert row_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(row_kwargs, megatron_config)\n            tp_utils.update_kwargs_with_config(column_kwargs, megatron_config)\n\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n\n        self.gate_up_proj = MergedColumnParallelLinear(\n            input_size=self.hidden_size,\n            gate_ouput_size=self.intermediate_size,\n            up_output_size=self.intermediate_size,\n            bias=False,\n            gather_output=False,\n            skip_bias_add=False,\n            **column_kwargs,\n        )\n        self.gate_size = self.intermediate_size // tp_size\n\n        self.down_proj = tensor_parallel.RowParallelLinear(input_size=self.intermediate_size,\n                                                           output_size=self.hidden_size,\n                                                           bias=False,\n                                                           input_is_parallel=True,\n                                                           skip_bias_add=False,\n                                                           **row_kwargs)\n\n        self.act_fn = ACT2FN[config.hidden_act]\n\n    def forward(self, x):\n        gate_up = self.gate_up_proj(x)[0]\n        gate, up = gate_up.split(self.gate_size, dim=-1)\n        return self.down_proj(self.act_fn(gate) * up)[0]\n"
  },
  {
    "path": "verl/models/qwen2/megatron/layers/parallel_rmsnorm.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numbers\nimport torch\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers import Qwen2Config\n\nfrom apex.normalization.fused_layer_norm import fused_rms_norm_affine\nfrom verl.utils.megatron import sequence_parallel as sp_utils\n\n\nclass ParallelQwen2RMSNorm(nn.Module):\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n        \"\"\"\n        Qwen2RMSNorm is equivalent to T5LayerNorm\n        \"\"\"\n        super().__init__()\n        if isinstance(config.hidden_size, numbers.Integral):\n            normalized_shape = (config.hidden_size,)\n        self.normalized_shape = torch.Size(normalized_shape)\n        self.weight = nn.Parameter(torch.ones(self.normalized_shape))\n        self.variance_epsilon = config.rms_norm_eps\n\n        if megatron_config.sequence_parallel:\n            sp_utils.mark_parameter_as_sequence_parallel(self.weight)\n\n    def forward(self, hidden_states):\n        return fused_rms_norm_affine(input=hidden_states,\n                                     weight=self.weight,\n                                     normalized_shape=self.normalized_shape,\n                                     eps=self.variance_epsilon,\n                                     memory_efficient=True)"
  },
  {
    "path": "verl/models/qwen2/megatron/modeling_qwen2_megatron.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" PyTorch Qwen2 model.\"\"\"\n\nfrom typing import Optional, Tuple, Union\n\nimport torch\nimport torch.utils.checkpoint\nfrom megatron.core import tensor_parallel, parallel_state\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers.modeling_outputs import BaseModelOutputWithPast\nfrom transformers.models.qwen2.configuration_qwen2 import Qwen2Config\nfrom transformers.models.qwen2.modeling_qwen2 import CausalLMOutputWithPast\n\nfrom verl.utils.megatron import sequence_parallel as sp_utils\nfrom verl.utils.megatron import tensor_parallel as tp_utils\nfrom .layers import ParallelQwen2DecoderLayer, ParallelQwen2RMSNorm, ParallelQwen2DecoderLayerRmPad\n\"\"\"\nTODO: \n1. Add weight initialization. Here we need to be careful on TP weight init.\n2. Add sequence parallel\n3. Load checkpoint from Qwen2 pretrained checkpoint\n\"\"\"\n\n\n# Copied from transformers.models.bart.modeling_bart._make_causal_mask\ndef _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device):\n    \"\"\"\n    Make causal mask used for bi-directional self-attention.\n    \"\"\"\n    bsz, tgt_len = input_ids_shape\n    mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)\n    mask_cond = torch.arange(mask.size(-1), device=device)\n    mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)\n    mask = mask.to(dtype)\n    return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len)\n\n\n# Copied from transformers.models.bart.modeling_bart._expand_mask\ndef _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):\n    \"\"\"\n    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.\n    \"\"\"\n    bsz, src_len = mask.size()\n    tgt_len = tgt_len if tgt_len is not None else src_len\n\n    expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)\n\n    inverted_mask = 1.0 - expanded_mask\n\n    return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)\n\n\nclass ParallelQwen2Model(nn.Module):\n    \"\"\"\n    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]\n\n    Args:\n        config: Qwen2Config\n    \"\"\"\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.padding_idx = config.pad_token_id\n        self.vocab_size = config.vocab_size\n        embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding()\n        if megatron_config is not None:\n            assert embedding_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config)\n        self.embed_tokens = tensor_parallel.VocabParallelEmbedding(num_embeddings=config.vocab_size,\n                                                                   embedding_dim=config.hidden_size,\n                                                                   **embedding_kwargs)\n\n        self.layers = nn.ModuleList(\n            [ParallelQwen2DecoderLayer(config, megatron_config) for _ in range(config.num_hidden_layers)])\n        self.norm = ParallelQwen2RMSNorm(config, megatron_config)\n\n    # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask\n    def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds):\n        # create causal mask\n        # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n        combined_attention_mask = None\n        if input_shape[-1] > 1:\n            combined_attention_mask = _make_causal_mask(\n                input_shape,\n                inputs_embeds.dtype,\n                device=inputs_embeds.device,\n            )\n\n        if attention_mask is not None:\n            # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n            expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype,\n                                              tgt_len=input_shape[-1]).to(inputs_embeds.device)\n            combined_attention_mask = (expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask +\n                                       combined_attention_mask)\n\n        return combined_attention_mask\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, BaseModelOutputWithPast]:\n        \"\"\"\n\n        Args:\n            input_ids: input ids. shape (batch_size, seq_length)\n            attention_mask: attention_mask. shape (batch_size, seq_length)\n            position_ids: position ids. shape (batch_size, seq_length)\n\n        Returns:\n\n        \"\"\"\n        batch_size, seq_length = input_ids.shape\n        inputs_embeds = self.embed_tokens(input_ids)\n        # embed positions\n\n        attention_mask = self._prepare_decoder_attention_mask(attention_mask, (batch_size, seq_length), inputs_embeds)\n\n        hidden_states = inputs_embeds\n\n        for idx, decoder_layer in enumerate(self.layers):\n            layer_outputs = decoder_layer(\n                hidden_states,\n                attention_mask=attention_mask,\n                position_ids=position_ids,\n            )\n\n            hidden_states = layer_outputs\n\n        hidden_states = self.norm(hidden_states)\n\n        return hidden_states\n\n\nclass ParallelQwen2ForCausalLM(nn.Module):\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.model = ParallelQwen2Model(config, megatron_config=megatron_config)\n        self.vocab_size = config.vocab_size\n\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n\n        self.lm_head = tensor_parallel.ColumnParallelLinear(input_size=config.hidden_size,\n                                                            output_size=config.vocab_size,\n                                                            bias=False,\n                                                            gather_output=False,\n                                                            skip_bias_add=False,\n                                                            **column_kwargs)\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        r\"\"\"\n        Args:\n            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n        Returns:\n        ```\"\"\"\n\n        # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n        outputs = self.model(\n            input_ids=input_ids,\n            attention_mask=attention_mask,\n            position_ids=position_ids,\n        )\n\n        hidden_states = outputs\n        logits = self.lm_head(hidden_states)[0]\n\n        logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits)\n\n        logits = logits.float()\n        return CausalLMOutputWithPast(\n            loss=None,\n            logits=logits,\n            past_key_values=None,\n            hidden_states=None,\n            attentions=None,\n        )\n\n\nfrom flash_attn.bert_padding import index_first_axis, pad_input, unpad_input  # noqa\n\n\nclass ParallelQwen2ModelRmPad(nn.Module):\n    \"\"\"\n    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]\n\n    Args:\n        config: Qwen2Config\n    \"\"\"\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.padding_idx = config.pad_token_id\n        self.vocab_size = config.vocab_size\n        embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding()\n        self.megatron_config = megatron_config\n        if megatron_config is not None:\n            assert embedding_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config)\n        self.embed_tokens = tensor_parallel.VocabParallelEmbedding(num_embeddings=config.vocab_size,\n                                                                   embedding_dim=config.hidden_size,\n                                                                   **embedding_kwargs)\n\n        self.layers = nn.ModuleList(\n            [ParallelQwen2DecoderLayerRmPad(config, megatron_config) for _ in range(config.num_hidden_layers)])\n        self.norm = ParallelQwen2RMSNorm(config, megatron_config)\n\n    def forward(self,\n                input_ids: torch.Tensor,\n                position_ids: Optional[torch.LongTensor] = None,\n                sequence_length: int = None,\n                indices: torch.Tensor = None,\n                cu_seqlens: int = None,\n                max_seqlen_in_batch: int = None) -> Union[Tuple, BaseModelOutputWithPast]:\n        \"\"\"\n\n        Args:\n            input_ids: input ids. shape (1, totol_nnz)\n            position_ids: position ids. shape (batch_size, seq_length)\n\n        Returns:\n\n        \"\"\"\n        inputs_embeds = self.embed_tokens(input_ids)  # (1, total_nnz) -> (1, total_nnz, hidden_size)\n\n        # (1, total_nnz, hidden_size) -> (total_nnz, 1, hidden_size) -> (total_nnz // sp, 1, hidden_size)\n        inputs_embeds = inputs_embeds.transpose(0, 1)\n        if self.megatron_config.sequence_parallel:\n            inputs_embeds = tensor_parallel.scatter_to_sequence_parallel_region(inputs_embeds)\n\n        hidden_states = inputs_embeds\n        for idx, decoder_layer in enumerate(self.layers):\n            layer_outputs = decoder_layer(hidden_states,\n                                          position_ids=position_ids,\n                                          sequence_length=sequence_length,\n                                          indices=indices,\n                                          cu_seqlens=cu_seqlens,\n                                          max_seqlen_in_batch=max_seqlen_in_batch)\n\n            hidden_states = layer_outputs\n\n        hidden_states = self.norm(hidden_states)\n\n        return hidden_states\n\n\nclass ParallelQwen2ForCausalLMRmPad(nn.Module):\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n        super().__init__()\n        self.config = config\n        self.megatron_config = megatron_config\n        self.model = ParallelQwen2ModelRmPad(config, megatron_config=megatron_config)\n        self.vocab_size = config.vocab_size\n        self._init_head()\n\n    def _init_head(self):\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if self.megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n        self.lm_head = tensor_parallel.ColumnParallelLinear(input_size=self.config.hidden_size,\n                                                            output_size=self.config.vocab_size,\n                                                            bias=False,\n                                                            gather_output=False,\n                                                            skip_bias_add=False,\n                                                            **column_kwargs)\n\n    def _forward_head(self, hidden_states):\n        # all_gather from sequence parallel region is performed inside lm_head\n        logits = self.lm_head(hidden_states)[0]\n        logits = logits.float()  # (total_nnz_padded, 1, vocab_size // tp)\n        logits = tensor_parallel.gather_from_tensor_model_parallel_region(logits)  # (total_nnz_padded, 1, vocab_size)\n        return logits\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        r\"\"\"\n        Args:\n            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n        Returns:\n        ```\"\"\"\n        batch_size, sequence_length = input_ids.shape\n\n        # remove padding here\n        input_ids, indices, cu_seqlens, max_seqlen_in_batch, *_ = unpad_input(input_ids.unsqueeze(dim=-1),\n                                                                              attention_mask)  # (total_nnz, 1)\n\n        # pad input_ids to multiple of tp for all tp ranks\n        # TODO: for better performance, the sp padding should be removed at each layer. Not sure the performance gap\n        if self.megatron_config.sequence_parallel:\n            input_ids = sp_utils.pad_to_sequence_parallel(input_ids)\n\n        input_ids = input_ids.transpose(0, 1)  # (1, total_nnz+pad)\n\n        outputs = self.model(input_ids=input_ids,\n                             position_ids=position_ids,\n                             sequence_length=sequence_length,\n                             indices=indices,\n                             cu_seqlens=cu_seqlens,\n                             max_seqlen_in_batch=max_seqlen_in_batch)\n\n        hidden_states = outputs\n\n        logits = self._forward_head(hidden_states)\n\n        # remove padding from sequence parallel\n        if self.megatron_config.sequence_parallel:\n            totol_nnz = cu_seqlens[-1]\n            logits = logits[:totol_nnz]  # (total_nnz_padded)\n\n        logits = torch.squeeze(logits, dim=1)  # remove the artificial batch dimension\n        # add removed padding back\n        logits = pad_input(logits, indices, batch_size,\n                           seqlen=sequence_length)  # (batch_size, sequence_length, vocab_size)\n\n        return CausalLMOutputWithPast(\n            loss=None,\n            logits=logits,\n            past_key_values=None,\n            hidden_states=None,\n            attentions=None,\n        )\n\n\nclass ParallelQwen2ForValueRmPad(ParallelQwen2ForCausalLMRmPad):\n\n    def _init_head(self):\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if self.megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n        self.lm_head = nn.Linear(in_features=self.config.hidden_size, out_features=1, bias=False)\n        # lm_head is effectively the same as sequence parallel\n        sp_utils.mark_parameter_as_sequence_parallel(self.lm_head.weight)\n\n    def _forward_head(self, hidden_states):\n        logits = self.lm_head(hidden_states)  # (total_nnz_padded // tp, 1, 1)\n        logits = logits.float()\n        if self.megatron_config.sequence_parallel:\n            logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False)\n        return logits\n\n    def forward(\n        self,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        output = super().forward(input_ids, attention_mask, position_ids)\n        output.logits = torch.squeeze(output.logits, dim=-1)\n        return output\n\n\n\"\"\"\nSupport pipeline parallelism\n\"\"\"\n\n\nclass ParallelQwen2ModelRmPadPP(nn.Module):\n    \"\"\"\n    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]\n    This model definition supports pipeline parallelism. To support pp and vpp,\n    - This model only contains layer in this pp stage and vpp chunk\n    - When calling get_model in Megatron, this rank will instantiate all the vpp chunks in this pp.\n    Args:\n        config: Qwen2Config\n    \"\"\"\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig, pre_process, post_process):\n        super().__init__()\n        self.padding_idx = config.pad_token_id\n        self.vocab_size = config.vocab_size\n        self.pre_process = pre_process\n        self.post_process = post_process\n        self.megatron_config = megatron_config\n        embedding_kwargs = tp_utils.get_default_kwargs_for_parallel_embedding()\n        if megatron_config is not None:\n            assert embedding_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(embedding_kwargs, self.megatron_config)\n        if pre_process:\n            self.embed_tokens = tensor_parallel.VocabParallelEmbedding(num_embeddings=config.vocab_size,\n                                                                       embedding_dim=config.hidden_size,\n                                                                       **embedding_kwargs)\n        else:\n            self.embed_tokens = None\n\n        # pp_rank = megatron_config.pipeline_model_parallel_rank\n        pp_size = megatron_config.pipeline_model_parallel_size\n        self.num_layer_per_pp = config.num_hidden_layers // pp_size\n        vpp_size = megatron_config.virtual_pipeline_model_parallel_size\n\n        if vpp_size is not None:\n            self.num_layer_vpp_chunk = self.num_layer_per_pp // vpp_size\n            self.num_layer_this_model = self.num_layer_vpp_chunk\n            # vpp_rank = megatron_config.virtual_pipeline_model_parallel_rank\n            # self.offset = vpp_rank * (\n            #         config.num_hidden_layers // megatron_config.virtual_pipeline_model_parallel_size) + \\\n            #             (megatron_config.pipeline_model_parallel_rank * self.num_layer_vpp_chunk)\n        else:\n            self.num_layer_this_model = self.num_layer_per_pp\n            # self.offset = pp_rank * self.num_layer_per_pp\n\n        layers = []\n        for i in range(self.num_layer_this_model):\n            layer = ParallelQwen2DecoderLayerRmPad(config, megatron_config)\n            # setattr(layer, 'hidden_layer_index', self.offset + i)\n            layers.append(layer)\n\n        self.layers = nn.ModuleList(layers)\n\n        if post_process:\n            self.norm = ParallelQwen2RMSNorm(config, megatron_config)\n        else:\n            self.norm = None\n\n    def set_input_tensor(self, input_tensor):\n        \"\"\"Set input tensor to be used instead of forward()'s input.\n\n        When doing pipeline parallelism the input from the previous\n        stage comes from communication, not from the input, so the\n        model's forward_step_func won't have it. This function is thus\n        used by internal code to bypass the input provided by the\n        forward_step_func\"\"\"\n        self.input_tensor = input_tensor\n\n    def forward(self,\n                input_ids: torch.Tensor,\n                position_ids: Optional[torch.LongTensor] = None,\n                sequence_length: int = None,\n                indices: torch.Tensor = None,\n                cu_seqlens: int = None,\n                max_seqlen_in_batch: int = None) -> Union[Tuple, BaseModelOutputWithPast]:\n        \"\"\"\n\n        Args:\n            input_ids: input ids. shape (1, totol_nnz)\n            position_ids: position ids. shape (batch_size, seq_length)\n\n        Returns:\n\n        \"\"\"\n        if self.pre_process:\n            inputs_embeds = self.embed_tokens(input_ids)  # (1, total_nnz) -> (1, total_nnz, hidden_size)\n\n            # vocab parallel embedding will not do sequence parallel reduce-scatter in open source megatron\n            # so need to deal with it by handle here:\n            # (1, total_nnz, hidden_size) -> (total_nnz, 1, hidden_size) -> (total_nnz // sp, 1, hidden_size)\n            inputs_embeds = inputs_embeds.transpose(0, 1)\n            if self.megatron_config.sequence_parallel:\n                inputs_embeds = tensor_parallel.scatter_to_sequence_parallel_region(inputs_embeds)\n\n            hidden_states = inputs_embeds\n        else:\n            # self.hidden_states should be passed by Megatron\n            hidden_states = self.input_tensor\n\n        for idx, decoder_layer in enumerate(self.layers):\n            layer_outputs = decoder_layer(hidden_states,\n                                          position_ids=position_ids,\n                                          sequence_length=sequence_length,\n                                          indices=indices,\n                                          cu_seqlens=cu_seqlens,\n                                          max_seqlen_in_batch=max_seqlen_in_batch)\n\n            hidden_states = layer_outputs\n\n        if self.post_process:\n            hidden_states = self.norm(hidden_states)\n\n        return hidden_states\n\n\nclass ParallelQwen2ForCausalLMRmPadPP(nn.Module):\n\n    def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig, pre_process, post_process,\n                 share_embeddings_and_output_weights):\n        super().__init__()\n        self.config = config\n        self.megatron_config = megatron_config\n        self.model = ParallelQwen2ModelRmPadPP(config,\n                                               megatron_config=megatron_config,\n                                               pre_process=pre_process,\n                                               post_process=post_process)\n        self.share_embeddings_and_output_weights = share_embeddings_and_output_weights\n        self.vocab_size = config.vocab_size\n        self.pre_process = pre_process\n        self.post_process = post_process\n        if post_process:\n            self._init_head()\n        if pre_process or post_process:\n            self.setup_embeddings_and_output_layer()\n\n    def set_input_tensor(self, input_tensor):\n        \"\"\"Set input tensor to be used instead of forward()'s input.\n\n        When doing pipeline parallelism the input from the previous\n        stage comes from communication, not from the input, so the\n        model's forward_step_func won't have it. This function is thus\n        used by internal code to bypass the input provided by the\n        forward_step_func\"\"\"\n        assert len(input_tensor) == 1\n        self.model.set_input_tensor(input_tensor[0])\n\n    def _init_head(self):\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if self.megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n        self.lm_head = tensor_parallel.ColumnParallelLinear(input_size=self.config.hidden_size,\n                                                            output_size=self.config.vocab_size,\n                                                            bias=False,\n                                                            gather_output=False,\n                                                            skip_bias_add=False,\n                                                            skip_weight_param_allocation=self.pre_process and\n                                                            self.share_embeddings_and_output_weights,\n                                                            **column_kwargs)\n\n    def setup_embeddings_and_output_layer(self) -> None:\n        \"\"\"Sets up embedding layer in first stage and output layer in last stage.\n\n        This function initalizes word embeddings in the final stage when we are\n        using pipeline parallelism and sharing word embeddings, and sets up param\n        attributes on the embedding and output layers.\n        \"\"\"\n        # Set `is_embedding_or_output_parameter` attribute.\n        if self.pre_process:\n            self.model.embed_tokens.weight.is_embedding_or_output_parameter = True\n        if self.post_process and self.lm_head.weight is not None:\n            self.lm_head.weight.is_embedding_or_output_parameter = True\n\n        if not self.share_embeddings_and_output_weights:\n            return\n\n        if parallel_state.get_pipeline_model_parallel_world_size() == 1:\n            # Zero out wgrad if sharing embeddings between two layers on same\n            # pipeline stage to make sure grad accumulation into main_grad is\n            # correct and does not include garbage values (e.g., from torch.empty).\n            self.shared_embedding_or_output_weight().zero_out_wgrad = True\n            return\n\n        if parallel_state.is_pipeline_first_stage() and self.pre_process and not self.post_process:\n            self.shared_embedding_or_output_weight().shared_embedding = True\n\n        if self.post_process and not self.pre_process:\n            assert not parallel_state.is_pipeline_first_stage()\n            # set word_embeddings weights to 0 here, then copy first\n            # stage's weights using all_reduce below.\n            self.lm_head.weight.data.fill_(0)\n            self.lm_head.weight.shared = True\n            self.lm_head.weight.shared_embedding = True\n\n        if torch.distributed.is_initialized():\n            if parallel_state.is_rank_in_embedding_group():\n                weight = self.shared_embedding_or_output_weight()\n                weight.data = weight.data.cuda()\n                torch.distributed.all_reduce(weight.data, group=parallel_state.get_embedding_group())\n\n    def shared_embedding_or_output_weight(self) -> torch.Tensor:\n        if self.pre_process:\n            return self.model.embed_tokens.weight\n        elif self.post_process:\n            return self.lm_head.weight\n        return None\n\n    def _forward_head(self, hidden_states):\n        # all_gather from sequence parallel region is performed inside lm_head\n        # print(f'logits shape before forward_head: {hidden_states.shape}, vocab_size = {self.config.vocab_size}') # [4, 32, 4096]\n        output_weight = None\n        if self.share_embeddings_and_output_weights:\n            output_weight = self.shared_embedding_or_output_weight()\n        logits = self.lm_head(hidden_states, weight=output_weight)[0]\n        # print(f'logits shape after forward_head: {logits.shape}') # [8, 32, 8]\n        logits = logits.float()  # (total_nnz_padded, 1, vocab_size // tp)\n        return logits\n\n    def forward(\n        self,\n        # original input\n        *,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        r\"\"\"\n        Args:\n            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n        Returns:\n        ```\"\"\"\n\n        # Note that input_ids, attention_mask and position_ids should be passed to every pp layer.\n        # In the first pp, input_ids will be used, in other pp layers hidden_states will be used inside self.model\n        batch_size, sequence_length = input_ids.shape\n        # remove padding here\n        input_ids_rmpad, indices, cu_seqlens, max_seqlen_in_batch, *_ = unpad_input(input_ids.unsqueeze(dim=-1),\n                                                                                    attention_mask)  # (total_nnz, 1)\n\n        # pad input_ids to multiple of tp for all tp ranks\n        # TODO: for better performance, the sp padding should be removed at each layer. Not sure the performance gap\n        if self.megatron_config.sequence_parallel:\n            input_ids_rmpad = sp_utils.pad_to_sequence_parallel(input_ids_rmpad)\n\n        input_ids_rmpad = input_ids_rmpad.transpose(0, 1)  # (1, total_nnz+pad)\n\n        outputs = self.model(input_ids=input_ids_rmpad,\n                             position_ids=position_ids,\n                             sequence_length=sequence_length,\n                             indices=indices,\n                             cu_seqlens=cu_seqlens,\n                             max_seqlen_in_batch=max_seqlen_in_batch)\n\n        if self.post_process:\n            hidden_states = outputs\n            logits = self._forward_head(hidden_states)\n            logits = torch.squeeze(logits, dim=1)  # remove the artificial batch dimension # torch.Size([8, 32, 16])\n\n            # remove padding from sequence parallel\n            if self.megatron_config.sequence_parallel:\n                totol_nnz = cu_seqlens[-1]\n                logits = logits[:totol_nnz]  # (total_nnz_padded)\n            # add removed padding back. If input is already rmpad, we let the caller pad_input\n            logits = pad_input(logits, indices, batch_size,\n                               seqlen=sequence_length)  # (batch_size, sequence_length, vocab_size)\n\n            return CausalLMOutputWithPast(\n                loss=None,\n                logits=logits,\n                past_key_values=None,\n                hidden_states=None,\n                attentions=None,\n            )\n        else:\n            return outputs\n\n\nclass ParallelQwen2ForValueRmPadPP(ParallelQwen2ForCausalLMRmPadPP):\n\n    def _init_head(self):\n        column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()\n        if self.megatron_config is not None:\n            assert column_kwargs.get('config', False), 'must have ModelParallelConfig'\n            tp_utils.update_kwargs_with_config(column_kwargs, self.megatron_config)\n        self.lm_head = nn.Linear(in_features=self.config.hidden_size, out_features=1, bias=False)\n        # lm_head is effectively the same as sequence parallel\n        sp_utils.mark_parameter_as_sequence_parallel(self.lm_head.weight)\n\n    def _forward_head(self, hidden_states):\n        logits = self.lm_head(hidden_states)  # (total_nnz_padded // tp, 1, 1)\n        logits = logits.float()\n        if self.megatron_config.sequence_parallel:\n            logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False)\n        return logits\n\n    def forward(\n        self,\n        *,\n        input_ids: torch.LongTensor = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n    ) -> Union[Tuple, CausalLMOutputWithPast]:\n        output = super().forward(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids)\n        if self.post_process:\n            output.logits = torch.squeeze(output.logits, dim=-1)\n            return output\n        else:\n            return output\n"
  },
  {
    "path": "verl/models/registry.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport importlib\nfrom typing import List, Optional, Type\n\nimport torch.nn as nn\n\n# Supported models using HF Rmpad\n# TODO(sgm): HF may supported more than listed here, we should add more after testing\n_MODELS_SUPPORT_RMPAD = {'llama', 'mistral', 'gemma', 'qwen2', 'qwen2_vl', 'qwen2_5_vl'}\n\n\ndef check_model_support_rmpad(model_type: str):\n    assert isinstance(model_type, str)\n    if not model_type in _MODELS_SUPPORT_RMPAD:\n        raise ValueError(f\"Model architecture {model_type} is not supported for now. \"\n                         f\"RMPad supported architectures: {_MODELS_SUPPORT_RMPAD}.\"\n                         f\"Please set `use_remove_padding=False` in the model config.\")\n\n    if model_type in (\"qwen2_vl\", \"qwen2_5_vl\"):  # patch remove padding for qwen2vl mrope\n        from verl.models.transformers.qwen2_vl import ulysses_flash_attn_forward\n        from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLFlashAttention2\n        from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLFlashAttention2\n\n        Qwen2VLFlashAttention2.forward = ulysses_flash_attn_forward\n        Qwen2_5_VLFlashAttention2.forward = ulysses_flash_attn_forward\n        print(\"Qwen2vl patch applied!\")\n\n\n# Supported models in Megatron-LM\n# Architecture -> (module, class).\n_MODELS = {\n    \"LlamaForCausalLM\":\n        (\"llama\", (\"ParallelLlamaForCausalLMRmPadPP\", \"ParallelLlamaForValueRmPadPP\", \"ParallelLlamaForCausalLMRmPad\")),\n    \"Qwen2ForCausalLM\":\n        (\"qwen2\", (\"ParallelQwen2ForCausalLMRmPadPP\", \"ParallelQwen2ForValueRmPadPP\", \"ParallelQwen2ForCausalLMRmPad\")),\n    \"MistralForCausalLM\": (\"mistral\", (\"ParallelMistralForCausalLMRmPadPP\", \"ParallelMistralForValueRmPadPP\",\n                                       \"ParallelMistralForCausalLMRmPad\"))\n}\n\n\n# return model class\nclass ModelRegistry:\n\n    @staticmethod\n    def load_model_cls(model_arch: str, value=False) -> Optional[Type[nn.Module]]:\n        if model_arch not in _MODELS:\n            return None\n\n        megatron = \"megatron\"\n\n        module_name, model_cls_name = _MODELS[model_arch]\n        if not value:  # actor/ref\n            model_cls_name = model_cls_name[0]\n        elif value:  # critic/rm\n            model_cls_name = model_cls_name[1]\n\n        module = importlib.import_module(f\"verl.models.{module_name}.{megatron}.modeling_{module_name}_megatron\")\n        return getattr(module, model_cls_name, None)\n\n    @staticmethod\n    def get_supported_archs() -> List[str]:\n        return list(_MODELS.keys())\n"
  },
  {
    "path": "verl/models/transformers/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/models/transformers/llama.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nfrom typing import Optional, Tuple, Callable\nimport sys\nif sys.version_info >= (3, 11):\n    from typing import Unpack\nelse:\n    from typing_extensions import Unpack\n\nfrom transformers.models.llama.modeling_llama import apply_rotary_pos_emb\nfrom transformers.cache_utils import Cache\nfrom transformers.utils import logging\nfrom transformers.modeling_flash_attention_utils import _flash_attention_forward\nfrom verl.utils.ulysses import gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_world_size\n\nlogger = logging.get_logger(__name__)\n\ndef llama_flash_attn_forward(\n        self,\n        hidden_states: torch.Tensor,\n        attention_mask: Optional[torch.LongTensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n        past_key_value: Optional[Cache] = None,\n        output_attentions: bool = False,\n        use_cache: bool = False,\n        cache_position: Optional[torch.LongTensor] = None,\n        position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,  # will become mandatory in v4.46\n        **kwargs,\n    ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n    \"\"\"\n    Adapted from transformers 4.47.1 to support Ulysses sequence parallelism.\n\n    NOTE: This function is used for transformers versions in the range [4.45.0, 4.47.1].\n    \"\"\"\n    output_attentions = False\n\n    bsz, q_len, _ = hidden_states.size()\n\n    query_states = self.q_proj(hidden_states)\n    key_states = self.k_proj(hidden_states)\n    value_states = self.v_proj(hidden_states)\n\n    # Flash attention requires the input to have the shape\n    # batch_size x seq_length x head_dim x hidden_dim\n    # therefore we just need to keep the original shape\n    query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)\n    key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n    value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n\n    # trade off: repeat first and then all to all\n    # key_states = repeat_kv(key_states, self.num_key_value_groups)\n    # value_states = repeat_kv(value_states, self.num_key_value_groups)\n\n    ########## AlltoAll for Ulysses ##########\n    ulysses_sp_size = get_ulysses_sequence_parallel_world_size()\n\n    if ulysses_sp_size > 1:\n        # (bsz, n_head, seq_len/n, head_dim) -> (bsz, n_head/n, seq_len, head_dim)\n        query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1)\n        key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1)\n        value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1)\n\n    full_q_len = query_states.size(2)  # full seq length\n\n    if position_embeddings is None:\n        logger.warning_once(\n            \"The attention layers in this model are transitioning from computing the RoPE embeddings internally \"\n            \"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed \"\n            \"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be \"\n            \"removed and `position_embeddings` will be mandatory.\")\n        cos, sin = self.rotary_emb(value_states, position_ids)\n    else:\n        cos, sin = position_embeddings\n    query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)\n\n    if past_key_value is not None:\n        # sin and cos are specific to RoPE models; cache_position needed for the static cache\n        cache_kwargs = {\"sin\": sin, \"cos\": cos, \"cache_position\": cache_position}\n        key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)\n\n    # 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\n    # to be able to avoid many of these transpose/reshape/view.\n    query_states = query_states.transpose(1, 2)\n    key_states = key_states.transpose(1, 2)\n    value_states = value_states.transpose(1, 2)\n\n    dropout_rate = self.attention_dropout if self.training else 0.0\n\n    # In PEFT, usually we cast the layer norms in float32 for training stability reasons\n    # therefore the input hidden states gets silently casted in float32. Hence, we need\n    # cast them back in the correct dtype just to be sure everything works as expected.\n    # This might slowdown training & inference so it is recommended to not cast the LayerNorms\n    # in fp32. (LlamaRMSNorm handles it correctly)\n\n    input_dtype = query_states.dtype\n    if input_dtype == torch.float32:\n        if torch.is_autocast_enabled():\n            target_dtype = torch.get_autocast_gpu_dtype()\n        # Handle the case where the model is quantized\n        elif hasattr(self.config, \"_pre_quantization_dtype\"):\n            target_dtype = self.config._pre_quantization_dtype\n        else:\n            target_dtype = self.q_proj.weight.dtype\n\n        logger.warning_once(\n            f\"The input hidden states seems to be silently casted in float32, this might be related to\"\n            f\" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in\"\n            f\" {target_dtype}.\")\n\n        query_states = query_states.to(target_dtype)\n        key_states = key_states.to(target_dtype)\n        value_states = value_states.to(target_dtype)\n\n    attn_output = _flash_attention_forward(\n        query_states,\n        key_states,\n        value_states,\n        attention_mask,\n        full_q_len,\n        position_ids=position_ids,\n        dropout=dropout_rate,\n        sliding_window=getattr(self, \"sliding_window\", None),\n        use_top_left_mask=self._flash_attn_uses_top_left_mask,\n        is_causal=self.is_causal,\n        **kwargs,\n    )\n\n    attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous()\n    ########## AlltoAll for Ulysses ##########\n    if ulysses_sp_size > 1:\n        attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2)\n    attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()\n    attn_output = self.o_proj(attn_output)\n\n    if not output_attentions:\n        attn_weights = None\n\n    return attn_output, attn_weights, past_key_value\n\n\ndef llama_attn_forward(\n    self,\n    hidden_states: torch.Tensor,\n    position_embeddings: Tuple[torch.Tensor, torch.Tensor],\n    attention_mask: Optional[torch.Tensor],\n    past_key_value: Optional[Cache] = None,\n    cache_position: Optional[torch.LongTensor] = None,\n    **kwargs,\n) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n    \"\"\"\n    Adapted from transformers 4.49.0 to support Ulysses sequence parallelism for transformers >= 4.48.0.\n\n    NOTE: This function has been tested only on transformers versions between 4.48.0 and 4.49.0.\n    \"\"\"\n    from transformers.models.llama.modeling_llama import eager_attention_forward\n    from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS\n    bsz, q_len, _ = hidden_states.shape\n\n    query_states = self.q_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2)\n    key_states = self.k_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2)\n    value_states = self.v_proj(hidden_states).view(bsz, q_len, -1, self.head_dim).transpose(1, 2)\n\n    ########## AlltoAll for Ulysses ##########\n    ulysses_sp_size = get_ulysses_sequence_parallel_world_size()\n\n    if ulysses_sp_size > 1:\n        query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1)\n        key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1)\n        value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1)\n\n    full_q_len = query_states.size(2)\n\n    cos, sin = position_embeddings\n    query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)\n\n    if past_key_value is not None:\n        # sin and cos are specific to RoPE models; cache_position needed for the static cache\n        cache_kwargs = {\"sin\": sin, \"cos\": cos, \"cache_position\": cache_position}\n        key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)\n\n    attention_interface: Callable = eager_attention_forward\n    if self.config._attn_implementation != \"eager\":\n        if self.config._attn_implementation == \"sdpa\" and kwargs.get(\"output_attentions\", False):\n            logger.warning_once(\n                \"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to \"\n                'eager attention. This warning can be removed using the argument `attn_implementation=\"eager\"` when loading the model.'\n            )\n        else:\n            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]\n\n    attn_output, attn_weights = attention_interface(\n        self,\n        query_states,\n        key_states,\n        value_states,\n        attention_mask,\n        dropout=0.0 if not self.training else self.attention_dropout,\n        scaling=self.scaling,\n        **kwargs,\n    )\n\n    attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous()\n    ########## AlltoAll for Ulysses ##########\n    if ulysses_sp_size > 1:\n        attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2)\n    attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()\n    attn_output = self.o_proj(attn_output)\n    return attn_output, attn_weights\n"
  },
  {
    "path": "verl/models/transformers/monkey_patch.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nApply monkey-patch function to models\n\"\"\"\n\n\ndef apply_monkey_patch_to_llama():\n    if is_transformers_version_in_range(\"4.45.0\", \"4.47.1\"):\n        from transformers.models.llama.modeling_llama import LlamaFlashAttention2\n        from verl.models.transformers.llama import llama_flash_attn_forward\n        LlamaFlashAttention2.forward = llama_flash_attn_forward\n    elif is_transformers_version_in_range(\"4.48.0\", \"4.49.0\"):\n        from transformers.models.llama.modeling_llama import LlamaAttention\n        from verl.models.transformers.llama import llama_attn_forward\n        LlamaAttention.forward = llama_attn_forward\n\n\ndef apply_monkey_patch_to_qwen2():\n    if is_transformers_version_in_range(\"4.45.0\", \"4.47.1\"):\n        from transformers.models.qwen2.modeling_qwen2 import Qwen2FlashAttention2\n        from verl.models.transformers.qwen2 import qwen2_flash_attn_forward\n        Qwen2FlashAttention2.forward = qwen2_flash_attn_forward\n    elif is_transformers_version_in_range(\"4.48.0\", \"4.49.0\"):\n        from transformers.models.qwen2.modeling_qwen2 import Qwen2Attention\n        from verl.models.transformers.qwen2 import qwen2_attn_forward\n        Qwen2Attention.forward = qwen2_attn_forward\n\n\n_PATCH_NAME_TO_FUNC = {\n    'llama': apply_monkey_patch_to_llama,\n    'qwen2': apply_monkey_patch_to_qwen2,\n}\n\nfrom transformers import PretrainedConfig\n\n\ndef apply_monkey_patch(config: PretrainedConfig, verbose=True):\n    if not is_transformers_version_in_range(\"4.45.0\", \"4.49.0\"):\n        raise AssertionError(\"The installed `transformers` version doesn't support ulysses patch. \"\n                             \"Please install a version between 4.45.0 and 4.49.0 to use this ulysses feature.\")\n    success_apply_monkey_patch = False\n    if config.model_type in _PATCH_NAME_TO_FUNC:\n        _PATCH_NAME_TO_FUNC[config.model_type]()\n        success_apply_monkey_patch = True\n\n    if success_apply_monkey_patch and verbose:\n        print(f'Applying monkey patch to model {config.model_type}')\n    elif not success_apply_monkey_patch:\n        raise NotImplementedError(f'Ulysses for model {config.model_type} is not implemented, \\\n                                   please set `ulysses_sequence_parallel_size=1`')\n\n    return success_apply_monkey_patch\n\n\nfrom functools import lru_cache\nfrom packaging import version\nimport importlib.metadata\n\n\n@lru_cache()\ndef is_transformers_version_in_range(min_version: str, max_version: str) -> bool:\n    try:\n        # Get the installed version of the transformers library\n        transformers_version = importlib.metadata.version(\"transformers\")\n    except importlib.metadata.PackageNotFoundError:\n        raise ModuleNotFoundError(\"The `transformers` package is not installed.\")\n\n    # Check if the version is within the specified range\n    return version.parse(min_version) <= version.parse(transformers_version) <= version.parse(max_version)\n"
  },
  {
    "path": "verl/models/transformers/qwen2.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nfrom typing import Optional, Tuple, Callable\n\nfrom transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv\nfrom transformers.cache_utils import Cache\nfrom transformers.utils import logging\nfrom transformers.modeling_flash_attention_utils import _flash_attention_forward\nfrom transformers.processing_utils import Unpack\nfrom verl.utils.ulysses import gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_world_size\n\nlogger = logging.get_logger(__name__)\n\n\ndef qwen2_flash_attn_forward(\n        self,\n        hidden_states: torch.Tensor,\n        attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n        past_key_value: Optional[Cache] = None,\n        output_attentions: bool = False,\n        use_cache: bool = False,\n        cache_position: Optional[torch.LongTensor] = None,\n        position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,  # will become mandatory in v4.46\n):\n    \"\"\"\n    Adapted from transformers 4.47.1 to support Ulysses sequence parallelism.\n\n    NOTE: This function is only tested on transformers versions between 4.45.0 and 4.47.1.\n    \"\"\"\n    bsz, q_len, _ = hidden_states.size()\n\n    query_states = self.q_proj(hidden_states)\n    key_states = self.k_proj(hidden_states)\n    value_states = self.v_proj(hidden_states)\n\n    query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)\n    key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)\n    value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)\n\n    ########## AlltoAll for Ulysses ##########\n    ulysses_sp_size = get_ulysses_sequence_parallel_world_size()\n\n    if ulysses_sp_size > 1:\n        # (bsz, n_head, seq_len/n, head_dim) -> (bsz, n_head/n, seq_len, head_dim)\n        query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1)\n        key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1)\n        value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1)\n\n    full_q_len = query_states.size(2)  # full seq length\n\n    if position_embeddings is None:\n        logger.warning_once(\n            \"The attention layers in this model are transitioning from computing the RoPE embeddings internally \"\n            \"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed \"\n            \"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be \"\n            \"removed and `position_embeddings` will be mandatory.\")\n        cos, sin = self.rotary_emb(value_states, position_ids)\n    else:\n        cos, sin = position_embeddings\n    query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)\n\n    if past_key_value is not None:\n        cache_kwargs = {\"sin\": sin, \"cos\": cos, \"cache_position\": cache_position}  # Specific to RoPE models\n        key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)\n\n    # repeat k/v heads if n_kv_heads < n_heads\n    key_states = repeat_kv(key_states, self.num_key_value_groups)\n    value_states = repeat_kv(value_states, self.num_key_value_groups)\n    dropout_rate = 0.0 if not self.training else self.attention_dropout\n\n    # In PEFT, usually we cast the layer norms in float32 for training stability reasons\n    # therefore the input hidden states gets silently casted in float32. Hence, we need\n    # cast them back in float16 just to be sure everything works as expected.\n    input_dtype = query_states.dtype\n    if input_dtype == torch.float32:\n        if torch.is_autocast_enabled():\n            target_dtype = torch.get_autocast_gpu_dtype()\n        # Handle the case where the model is quantized\n        elif hasattr(self.config, \"_pre_quantization_dtype\"):\n            target_dtype = self.config._pre_quantization_dtype\n        else:\n            target_dtype = self.q_proj.weight.dtype\n\n        logger.warning_once(\n            f\"The input hidden states seems to be silently casted in float32, this might be related to\"\n            f\" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in\"\n            f\" {target_dtype}.\")\n\n        query_states = query_states.to(target_dtype)\n        key_states = key_states.to(target_dtype)\n        value_states = value_states.to(target_dtype)\n\n    # Reashape to the expected shape for Flash Attention\n    query_states = query_states.transpose(1, 2)\n    key_states = key_states.transpose(1, 2)\n    value_states = value_states.transpose(1, 2)\n\n    if (self.config.use_sliding_window and getattr(self.config, \"sliding_window\", None) is not None and\n            self.layer_idx >= self.config.max_window_layers):\n        sliding_window = self.config.sliding_window\n    else:\n        sliding_window = None\n\n    attn_output = _flash_attention_forward(\n        query_states,\n        key_states,\n        value_states,\n        attention_mask,\n        full_q_len,\n        position_ids=position_ids,\n        dropout=dropout_rate,\n        sliding_window=sliding_window,\n        is_causal=self.is_causal,\n        use_top_left_mask=self._flash_attn_uses_top_left_mask,\n    )\n\n    # use full_q_len to reshape\n    attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous()\n    ########## AlltoAll for Ulysses ##########\n    if ulysses_sp_size > 1:\n        attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2)\n    attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()\n    attn_output = self.o_proj(attn_output)\n\n    if not output_attentions:\n        attn_weights = None\n\n    return attn_output, attn_weights, past_key_value\n\n\ndef qwen2_attn_forward(\n    self,\n    hidden_states: torch.Tensor,\n    position_embeddings: Tuple[torch.Tensor, torch.Tensor],\n    attention_mask: Optional[torch.Tensor],\n    past_key_value: Optional[Cache] = None,\n    cache_position: Optional[torch.LongTensor] = None,\n    **kwargs,\n) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n    \"\"\"\n    Adapted from transformers 4.49.0 to support Ulysses sequence parallelism for transformers >= 4.48.0.\n\n    NOTE: This function has been tested only on transformers versions between 4.48.0 and 4.49.0.\n    \"\"\"\n    from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS\n    bsz, q_len, _ = hidden_states.shape\n    hidden_shape = (bsz, q_len, -1, self.head_dim)\n\n    query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)\n    key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)\n    value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)\n\n    ########## AlltoAll for Ulysses ##########\n    ulysses_sp_size = get_ulysses_sequence_parallel_world_size()\n\n    if ulysses_sp_size > 1:\n        # (bsz, n_head, seq_len/n, head_dim) -> (bsz, n_head/n, seq_len, head_dim)\n        query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1)\n        key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1)\n        value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1)\n\n    full_q_len = query_states.size(2)\n\n    cos, sin = position_embeddings\n    query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)\n\n    if past_key_value is not None:\n        # sin and cos are specific to RoPE models; cache_position needed for the static cache\n        cache_kwargs = {\"sin\": sin, \"cos\": cos, \"cache_position\": cache_position}\n        key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)\n\n    sliding_window = None\n    if (self.config.use_sliding_window and getattr(self.config, \"sliding_window\", None) is not None and\n            self.layer_idx >= self.config.max_window_layers):\n        sliding_window = self.config.sliding_window\n\n    from transformers.models.qwen2.modeling_qwen2 import eager_attention_forward\n    attention_interface: Callable = eager_attention_forward\n    if self.config._attn_implementation != \"eager\":\n        if self.config._attn_implementation == \"sdpa\" and kwargs.get(\"output_attentions\", False):\n            logger.warning_once(\n                \"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to \"\n                'eager attention. This warning can be removed using the argument `attn_implementation=\"eager\"` when loading the model.'\n            )\n        else:\n            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]\n\n    attn_output, attn_weights = attention_interface(\n        self,\n        query_states,\n        key_states,\n        value_states,\n        attention_mask,\n        dropout=0.0 if not self.training else self.attention_dropout,\n        scaling=self.scaling,\n        sliding_window=sliding_window,  # main diff with Llama\n        **kwargs,\n    )\n\n    attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous()\n    ########## AlltoAll for Ulysses ##########\n    if ulysses_sp_size > 1:\n        # (bsz, seq_len, n_head/n, head_dim) -> (bsz, seq_len/n, n_head, head_dim)\n        attn_output = gather_heads_scatter_seq(attn_output, seq_dim=1, head_dim=2)\n    attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()\n    attn_output = self.o_proj(attn_output)\n    return attn_output, attn_weights\n"
  },
  {
    "path": "verl/models/transformers/qwen2_vl.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Optional, Tuple\nimport inspect\nimport torch\nimport os\nfrom transformers.utils import is_flash_attn_greater_or_equal\nfrom transformers.modeling_flash_attention_utils import _flash_attention_forward\nfrom verl.utils.ulysses import gather_heads_scatter_seq, gather_seq_scatter_heads, get_ulysses_sequence_parallel_world_size\n\ntry:\n    from flash_attn import flash_attn_func, flash_attn_varlen_func\n\n    _flash_supports_window_size = \"window_size\" in list(inspect.signature(flash_attn_func).parameters)\nexcept ImportError:\n    flash_attn_varlen_func = None\n\n\ndef get_rope_index(\n    processor,\n    input_ids: torch.Tensor,\n    image_grid_thw: Optional[torch.Tensor] = None,\n    video_grid_thw: Optional[torch.Tensor] = None,\n    second_per_grid_ts: Optional[torch.Tensor] = None,\n    attention_mask: Optional[torch.Tensor] = None,\n) -> torch.Tensor:\n    \"\"\"\n    Gets the position ids for Qwen2-VL, it should be generated before sharding the sequence.\n    The batch dim has been removed and the input_ids should be a 1D tensor representing a single example.\n    https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py#L1546\n    \"\"\"\n    spatial_merge_size = processor.image_processor.merge_size\n    tokens_per_second = 2\n    image_token_id = processor.tokenizer.convert_tokens_to_ids(\"<|image_pad|>\")\n    video_token_id = processor.tokenizer.convert_tokens_to_ids(\"<|video_pad|>\")\n    vision_start_token_id = processor.tokenizer.convert_tokens_to_ids(\"<|vision_start|>\")\n    if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):\n        if attention_mask is None:\n            attention_mask = torch.ones_like(input_ids)\n\n        position_ids = torch.ones(3, input_ids.size(0), dtype=input_ids.dtype, device=input_ids.device)  # (3, seqlen)\n        image_index, video_index = 0, 0\n        input_ids = input_ids[attention_mask == 1]\n        image_nums, video_nums = 0, 0\n        vision_start_indices = torch.argwhere(input_ids == vision_start_token_id)\n        vision_tokens = input_ids[vision_start_indices + 1]\n        image_nums = (vision_tokens == image_token_id).sum()\n        video_nums = (vision_tokens == video_token_id).sum()\n        input_tokens = input_ids.tolist()\n        llm_pos_ids_list: list = []\n        st = 0\n        remain_images, remain_videos = image_nums, video_nums\n        for _ in range(image_nums + video_nums):\n            if image_token_id in input_tokens and remain_images > 0:\n                ed_image = input_tokens.index(image_token_id, st)\n            else:\n                ed_image = len(input_tokens) + 1\n            if video_token_id in input_tokens and remain_videos > 0:\n                ed_video = input_tokens.index(video_token_id, st)\n            else:\n                ed_video = len(input_tokens) + 1\n            if ed_image < ed_video:\n                t, h, w = (\n                    image_grid_thw[image_index][0],\n                    image_grid_thw[image_index][1],\n                    image_grid_thw[image_index][2],\n                )\n                second_per_grid_t = 0\n                image_index += 1\n                remain_images -= 1\n                ed = ed_image\n            else:\n                t, h, w = (\n                    video_grid_thw[video_index][0],\n                    video_grid_thw[video_index][1],\n                    video_grid_thw[video_index][2],\n                )\n                if second_per_grid_ts is not None:\n                    second_per_grid_t = second_per_grid_ts[video_index]\n                else:\n                    second_per_grid_t = 1.0\n\n                video_index += 1\n                remain_videos -= 1\n                ed = ed_video\n\n            llm_grid_t, llm_grid_h, llm_grid_w = (\n                t.item(),\n                h.item() // spatial_merge_size,\n                w.item() // spatial_merge_size,\n            )\n            text_len = ed - st\n\n            st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0\n            llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)\n\n            t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w)\n            t_index = (t_index * second_per_grid_t * tokens_per_second).long().flatten()\n            h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()\n            w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()\n            llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)\n            st = ed + llm_grid_t * llm_grid_h * llm_grid_w\n\n        if st < len(input_tokens):\n            st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0\n            text_len = len(input_tokens) - st\n            llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)\n\n        llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)\n        position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device)\n    else:\n        if attention_mask is not None:\n            position_ids = attention_mask.long().cumsum(-1) - 1\n            position_ids.masked_fill_(attention_mask == 0, 1)\n            position_ids = position_ids.unsqueeze(0).expand(3, -1).to(input_ids.device)\n        else:\n            position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, -1).expand(3, -1)\n\n    return position_ids\n\n\ndef prepare_fa2_from_position_ids(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,\n                                  position_ids: torch.Tensor):\n    query = query.view(-1, query.size(-2), query.size(-1))\n    key = key.view(-1, key.size(-2), key.size(-1))\n    value = value.view(-1, value.size(-2), value.size(-1))\n    position_ids = position_ids.flatten()\n    indices_q = torch.arange(position_ids.size(0), device=position_ids.device, dtype=torch.int32)\n    cu_seqlens = torch.cat((\n        indices_q[position_ids == 0],\n        torch.tensor(position_ids.size(), device=position_ids.device, dtype=torch.int32),\n    ))\n    max_length = cu_seqlens.diff().max()  # use cu_seqlens to infer max_length for qwen2vl mrope\n    return (query, key, value, indices_q, (cu_seqlens, cu_seqlens), (max_length, max_length))\n\n\ndef flash_attention_forward(\n    query_states: torch.Tensor,\n    key_states: torch.Tensor,\n    value_states: torch.Tensor,\n    attention_mask: torch.Tensor,\n    query_length: int,\n    is_causal: bool = True,\n    position_ids: Optional[torch.Tensor] = None,\n    sliding_window: Optional[int] = None,\n    use_top_left_mask: bool = False,\n    deterministic: Optional[bool] = None,\n    **kwargs,\n):\n    \"\"\"\n    Patches flash attention forward to handle 3D position ids in mrope. (3, batch_size, seq_length)\n    \"\"\"\n    if not use_top_left_mask:\n        causal = is_causal\n    else:\n        causal = is_causal and query_length != 1\n\n    # Assuming 4D tensors, key_states.shape[1] is the key/value sequence length (source length).\n    use_sliding_windows = (_flash_supports_window_size and sliding_window is not None and\n                           key_states.shape[1] > sliding_window)\n    flash_kwargs = {\"window_size\": (sliding_window, sliding_window)} if use_sliding_windows else {}\n\n    if is_flash_attn_greater_or_equal(\"2.4.1\"):\n        if deterministic is None:\n            deterministic = os.environ.get(\"FLASH_ATTENTION_DETERMINISTIC\", \"0\") == \"1\"\n        flash_kwargs[\"deterministic\"] = deterministic\n\n    if position_ids is not None and query_length != 1 and not (torch.diff(position_ids[0], dim=-1) >= 0).all():\n        batch_size = query_states.size(0)\n        query_states, key_states, value_states, _, cu_seq_lens, max_seq_lens = prepare_fa2_from_position_ids(\n            query_states, key_states, value_states, position_ids[0])  # remove channel dimension\n        cu_seqlens_q, cu_seqlens_k = cu_seq_lens\n        max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens\n        attn_output = flash_attn_varlen_func(\n            query_states,\n            key_states,\n            value_states,\n            cu_seqlens_q=cu_seqlens_q,\n            cu_seqlens_k=cu_seqlens_k,\n            max_seqlen_q=max_seqlen_in_batch_q,\n            max_seqlen_k=max_seqlen_in_batch_k,\n            dropout_p=kwargs.pop(\"dropout\", 0.0),\n            softmax_scale=kwargs.pop(\"softmax_scale\", None),\n            causal=causal,\n            **flash_kwargs,\n        )\n        attn_output = attn_output.view(batch_size, -1, attn_output.size(-2), attn_output.size(-1))\n    else:\n        attn_output = _flash_attention_forward(\n            query_states,\n            key_states,\n            value_states,\n            attention_mask,\n            query_length,\n            is_causal=is_causal,\n            sliding_window=sliding_window,\n            use_top_left_mask=use_top_left_mask,\n            deterministic=deterministic,\n            **kwargs,\n        )  # do not pass position_ids to old flash_attention_forward\n\n    return attn_output\n\n\ndef ulysses_flash_attn_forward(\n    self,\n    hidden_states: torch.Tensor,\n    attention_mask: Optional[torch.Tensor] = None,\n    position_ids: Optional[torch.LongTensor] = None,\n    position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,  # will become mandatory in v4.46\n    **kwargs,\n) -> Tuple[torch.Tensor, None, None]:\n    from transformers.models.qwen2_vl.modeling_qwen2_vl import repeat_kv, apply_multimodal_rotary_pos_emb\n\n    bsz, q_len, _ = hidden_states.size()  # q_len = seq_length / sp_size\n    query_states = self.q_proj(hidden_states)  # (batch_size, seq_length / sp_size, num_heads * head_size)\n    key_states = self.k_proj(hidden_states)\n    value_states = self.v_proj(hidden_states)\n\n    query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)\n    key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n    value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n\n    ulysses_sp_size = get_ulysses_sequence_parallel_world_size()\n\n    if ulysses_sp_size > 1:\n        key_states = repeat_kv(key_states, self.num_key_value_groups)\n        value_states = repeat_kv(value_states, self.num_key_value_groups)\n        query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1)\n        key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1)\n        value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1)\n        # (batch_size, num_head / sp_size, seq_length, head_size)\n        full_q_len = query_states.size(2)  # full_q_len = seq_length\n    else:\n        full_q_len = q_len\n\n    # Because the input can be padded, the absolute sequence length depends on the max position id.\n    if position_embeddings is None:\n        cos, sin = self.rotary_emb(value_states, position_ids)\n    else:\n        cos, sin = position_embeddings\n\n    query_states, key_states = apply_multimodal_rotary_pos_emb(query_states, key_states, cos, sin,\n                                                               self.rope_scaling[\"mrope_section\"])\n    dropout_rate = 0.0 if not self.training else self.attention_dropout\n\n    # Reashape to the expected shape for Flash Attention\n    query_states = query_states.transpose(1, 2)\n    key_states = key_states.transpose(1, 2)\n    value_states = value_states.transpose(1, 2)\n\n    if (self.config.use_sliding_window and getattr(self.config, \"sliding_window\", None) is not None and\n            self.layer_idx >= self.config.max_window_layers):\n        sliding_window = self.config.sliding_window\n    else:\n        sliding_window = None\n\n    attn_output = flash_attention_forward(\n        query_states,\n        key_states,\n        value_states,\n        attention_mask,\n        full_q_len,\n        dropout=dropout_rate,\n        sliding_window=sliding_window,\n        is_causal=self.is_causal,\n        use_top_left_mask=self._flash_attn_uses_top_left_mask,\n        position_ids=position_ids,  # important: pass position ids\n    )  # (batch_size, seq_length, num_head / sp_size, head_size)\n    if ulysses_sp_size > 1:\n        attn_output = gather_heads_scatter_seq(attn_output, head_dim=2, seq_dim=1)\n\n    attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()\n    attn_output = self.o_proj(attn_output)\n    return attn_output, None, None\n"
  },
  {
    "path": "verl/models/weight_loader_registry.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\ndef get_weight_loader(arch: str):\n    from verl.models.llama.megatron.checkpoint_utils.llama_loader import load_state_dict_to_megatron_llama\n    from verl.models.qwen2.megatron.checkpoint_utils.qwen2_loader import load_state_dict_to_megatron_qwen2\n    _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY = {\n        'LlamaForCausalLM': load_state_dict_to_megatron_llama,\n        'Qwen2ForCausalLM': load_state_dict_to_megatron_qwen2,\n    }\n\n    if arch in _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY:\n        return _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {_MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY.keys()}\")\n"
  },
  {
    "path": "verl/protocol.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nImplement base data transfer protocol between any two functions, modules.\nWe can subclass Protocol to define more detailed batch info with specific keys\n\"\"\"\n\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport copy\nfrom dataclasses import dataclass, field\nfrom typing import Callable, Dict, List, Union\n\nimport torch\nimport tensordict\nfrom tensordict import TensorDict\nfrom torch.utils.data import DataLoader, Dataset\n\nfrom verl.utils.py_functional import union_two_dict\n\n__all__ = ['DataProto', 'union_tensor_dict']\n\ntry:\n    tensordict.set_lazy_legacy(False).set()\nexcept:\n    pass\n\n\ndef pad_dataproto_to_divisor(data: 'DataProto', size_divisor: int):\n    \"\"\"Pad a DataProto to size divisible by size_divisor\n\n    Args:\n        size_divisor (int): size divisor\n\n    Returns:\n        data: (DataProto): the padded DataProto\n        pad_size (int)\n    \"\"\"\n    assert isinstance(data, DataProto), 'data must be a DataProto'\n    if len(data) % size_divisor != 0:\n        pad_size = size_divisor - len(data) % size_divisor\n        padding_protos = []\n        remaining_pad = pad_size\n        while remaining_pad > 0:\n            take_size = min(remaining_pad, len(data))\n            padding_protos.append(data[:take_size])\n            remaining_pad -= take_size\n        data_padded = DataProto.concat([data] + padding_protos)\n    else:\n        pad_size = 0\n        data_padded = data\n    return data_padded, pad_size\n\n\ndef unpad_dataproto(data: 'DataProto', pad_size):\n    if pad_size != 0:\n        data = data[:-pad_size]\n    return data\n\n\ndef union_tensor_dict(tensor_dict1: TensorDict, tensor_dict2: TensorDict) -> TensorDict:\n    \"\"\"Union two tensordicts.\"\"\"\n    assert tensor_dict1.batch_size == tensor_dict2.batch_size, \\\n        f'Two tensor dict must have identical batch size. Got {tensor_dict1.batch_size} and {tensor_dict2.batch_size}'\n    for key in tensor_dict2.keys():\n        if key not in tensor_dict1.keys():\n            tensor_dict1[key] = tensor_dict2[key]\n        else:\n            assert tensor_dict1[key].equal(tensor_dict2[key]), \\\n                f'{key} in tensor_dict1 and tensor_dict2 are not the same object'\n\n    return tensor_dict1\n\n\ndef union_numpy_dict(tensor_dict1: dict[str, np.ndarray], tensor_dict2: dict[str, np.ndarray]) -> dict[str, np.ndarray]:\n    for key, val in tensor_dict2.items():\n        if key in tensor_dict1:\n            assert isinstance(tensor_dict2[key], np.ndarray)\n            assert isinstance(tensor_dict1[key], np.ndarray)\n            # to properly deal with nan and object type\n            assert pd.DataFrame(tensor_dict2[key]).equals(pd.DataFrame(tensor_dict1[key])), \\\n                f'{key} in tensor_dict1 and tensor_dict2 are not the same object'\n        tensor_dict1[key] = val\n\n    return tensor_dict1\n\n\ndef list_of_dict_to_dict_of_list(list_of_dict: list[dict]):\n    if len(list_of_dict) == 0:\n        return {}\n    keys = list_of_dict[0].keys()\n    output = {key: [] for key in keys}\n    for data in list_of_dict:\n        for key, item in data.items():\n            assert key in output\n            output[key].append(item)\n    return output\n\n\ndef fold_batch_dim(data: 'DataProto', new_batch_size):\n    \"\"\"\n    Fold a batch dim from [bsz, xxx] into [new_bsz, bsz // new_bsz, xxx]\n    \"\"\"\n    batch_size = data.batch.batch_size[0]\n\n    assert batch_size % new_batch_size == 0\n\n    tensor: TensorDict = data.batch\n    non_tensor = data.non_tensor_batch\n\n    tensor = tensor.view(new_batch_size, -1)\n    tensor.auto_batch_size_(batch_dims=1)\n\n    for key, val in non_tensor.items():\n        non_tensor[key] = np.reshape(val, newshape=(new_batch_size, -1, *val.shape[1:]))\n\n    return DataProto(batch=tensor, non_tensor_batch=non_tensor, meta_info=data.meta_info)\n\n\ndef unfold_batch_dim(data: 'DataProto', batch_dims=2):\n    \"\"\"\n    Unfold the first n dims as new batch dim\n    \"\"\"\n    tensor: TensorDict = data.batch\n    non_tensor = data.non_tensor_batch\n    tensor.auto_batch_size_(batch_dims=batch_dims)\n    tensor = tensor.view(-1)\n\n    batch_size = tensor.batch_size[0]\n\n    non_tensor_new = {}\n\n    for key, val in non_tensor.items():\n        non_tensor_new[key] = np.reshape(val, newshape=(batch_size, *val.shape[batch_dims:]))\n\n    return DataProto(batch=tensor, non_tensor_batch=non_tensor_new, meta_info=data.meta_info)\n\n\ndef collate_fn(x: list['DataProtoItem']):\n    batch = []\n    non_tensor_batch = []\n    for data in x:\n        batch.append(data.batch)\n        non_tensor_batch.append(data.non_tensor_batch)\n    batch = torch.stack(batch).contiguous()\n    non_tensor_batch = list_of_dict_to_dict_of_list(non_tensor_batch)\n    for key, val in non_tensor_batch.items():\n        non_tensor_batch[key] = np.array(val, dtype=object)\n    return DataProto(batch=batch, non_tensor_batch=non_tensor_batch)\n\n\n@dataclass\nclass DataProtoItem:\n    # TODO(zhangchi.usc1992) add consistency check\n    batch: TensorDict = None\n    non_tensor_batch: Dict = field(default_factory=dict)\n    meta_info: Dict = field(default_factory=dict)\n\n\n@dataclass\nclass DataProto:\n    \"\"\"\n    A DataProto is a data structure that aims to provide a standard protocol for data exchange between functions.\n    It contains a batch (TensorDict) and a meta_info (Dict). The batch is a TensorDict https://pytorch.org/tensordict/.\n    TensorDict allows you to manipulate a dictionary of Tensors like a single Tensor. Ideally, the tensors with the\n    same batch size should be put inside batch.\n    \"\"\"\n    batch: TensorDict = None\n    non_tensor_batch: Dict = field(default_factory=dict)\n    meta_info: Dict = field(default_factory=dict)\n\n    def __post_init__(self):\n        # perform necessary checking\n        self.check_consistency()\n\n    def __len__(self):\n        if self.batch is not None:\n            return self.batch.batch_size[0]\n        elif self.non_tensor_batch is not None and len(self.non_tensor_batch) > 0:\n            random_key = list(self.non_tensor_batch.keys())[0]\n            return self.non_tensor_batch[random_key].shape[0]\n        else:\n            return 0\n\n    def __getitem__(self, item):\n        tensor_data = self.batch[item]\n        non_tensor_data = {key: val[item] for key, val in self.non_tensor_batch.items()}\n        return DataProtoItem(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info)\n\n    def __getstate__(self):\n        import io\n        buffer = io.BytesIO()\n        if tensordict.__version__ >= '0.5.0' and self.batch is not None:\n            self.batch = self.batch.contiguous()\n            self.batch = self.batch.consolidate()\n        torch.save(self.batch, buffer)\n        buffer_bytes = buffer.getvalue()\n        return buffer_bytes, self.non_tensor_batch, self.meta_info\n\n    def __setstate__(self, data):\n        import io\n        batch_deserialized_bytes, non_tensor_batch, meta_info = data\n        batch_deserialized = io.BytesIO(initial_bytes=batch_deserialized_bytes)\n        batch = torch.load(batch_deserialized,\n                           weights_only=False,\n                           map_location='cpu' if not torch.cuda.is_available() else None)\n        self.batch = batch\n        self.non_tensor_batch = non_tensor_batch\n        self.meta_info = meta_info\n\n    def save_to_disk(self, filepath):\n        with open(filepath, 'wb') as f:\n            pickle.dump(self, f)\n\n    @staticmethod\n    def load_from_disk(filepath) -> 'DataProto':\n        with open(filepath, 'rb') as f:\n            data = pickle.load(f)\n            return data\n\n    def print_size(self, prefix=\"\"):\n        size_of_tensordict = 0\n        for key, tensor in self.batch.items():\n            size_of_tensordict += tensor.element_size() * tensor.numel()\n        size_of_numpy_array = 0\n        for key, numpy_array in self.non_tensor_batch.items():\n            size_of_numpy_array += numpy_array.nbytes\n\n        size_of_numpy_array /= 1024**3\n        size_of_tensordict /= 1024**3\n\n        message = f'Size of tensordict: {size_of_tensordict} GB, size of non_tensor_batch: {size_of_numpy_array} GB'\n\n        if prefix:\n            message = f'{prefix}, ' + message\n        print(message)\n\n    def check_consistency(self):\n        \"\"\"Check the consistency of the DataProto. Mainly for batch and non_tensor_batch\n        We expose this function as a public one so that user can call themselves directly\n        \"\"\"\n        if self.batch is not None:\n            assert len(self.batch.batch_size) == 1, 'only support num_batch_dims=1'\n\n        if self.non_tensor_batch is not None:\n            for key, val in self.non_tensor_batch.items():\n                assert isinstance(val, np.ndarray)\n\n        if self.batch is not None and len(self.non_tensor_batch) != 0:\n            # TODO: we can actually lift this restriction if needed\n            assert len(self.batch.batch_size) == 1, 'only support num_batch_dims=1 when non_tensor_batch is not empty.'\n\n            batch_size = self.batch.batch_size[0]\n            for key, val in self.non_tensor_batch.items():\n                assert isinstance(\n                    val, np.ndarray\n                ) and val.dtype == object, 'data in the non_tensor_batch must be a numpy.array with dtype=object'\n                assert val.shape[\n                    0] == batch_size, f'key {key} length {len(val)} is not equal to batch size {batch_size}'\n\n    @classmethod\n    def from_single_dict(cls, data: Dict[str, Union[torch.Tensor, np.ndarray]], meta_info=None):\n        tensors = {}\n        non_tensors = {}\n\n        for key, val in data.items():\n            if isinstance(val, torch.Tensor):\n                tensors[key] = val\n            elif isinstance(val, np.ndarray):\n                non_tensors[key] = val\n            else:\n                raise ValueError(f'Unsupported type in data {type(val)}')\n\n        return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info)\n\n    @classmethod\n    def from_dict(cls, tensors: Dict[str, torch.Tensor], non_tensors=None, meta_info=None, num_batch_dims=1):\n        \"\"\"Create a DataProto from a dict of tensors. This assumes that\n        1. All the tensor in tensors have the same dim0\n        2. Only dim0 is the batch dim\n        \"\"\"\n        assert len(tensors) > 0, 'tensors must not be empty'\n        assert num_batch_dims > 0, 'num_batch_dims must be greater than zero'\n        if non_tensors is not None:\n            assert num_batch_dims == 1, 'only support num_batch_dims=1 when non_tensors is not None.'\n\n        if meta_info is None:\n            meta_info = {}\n        if non_tensors is None:\n            non_tensors = {}\n\n        assert isinstance(non_tensors, dict)\n\n        # get and check batch size\n        batch_size = None\n        pivot_key = None\n        for key, tensor in tensors.items():\n            if batch_size is None:\n                batch_size = tensor.shape[:num_batch_dims]\n                pivot_key = key\n            else:\n                current_batch = tensor.shape[:num_batch_dims]\n                assert batch_size == current_batch, \\\n                    f'Not all the tensor in tensors have the same batch size with batch_dims={num_batch_dims}. Got {pivot_key} has {batch_size}, {key} has {current_batch}'\n\n        for key, val in non_tensors.items():\n            non_tensors[key] = np.array(val, dtype=object)\n\n        tensor_dict = TensorDict(source=tensors, batch_size=batch_size)\n        return cls(batch=tensor_dict, non_tensor_batch=non_tensors, meta_info=meta_info)\n\n    def to(self, device) -> 'DataProto':\n        \"\"\"move the batch to device\n\n        Args:\n            device (torch.device, str): torch device\n\n        Returns:\n            DataProto: the current DataProto\n\n        \"\"\"\n        if self.batch is not None:\n            self.batch = self.batch.to(device)\n        return self\n\n    def select(self, batch_keys=None, non_tensor_batch_keys=None, meta_info_keys=None, deepcopy=False) -> 'DataProto':\n        \"\"\"Select a subset of the DataProto via batch_keys and meta_info_keys\n\n        Args:\n            batch_keys (list, optional): a list of strings indicating the keys in batch to select\n            meta_info_keys (list, optional): a list of keys indicating the meta info to select\n\n        Returns:\n            DataProto: the DataProto with the selected batch_keys and meta_info_keys\n        \"\"\"\n        # TODO (zhangchi.usc1992) whether to copy\n        if batch_keys is not None:\n            batch_keys = tuple(batch_keys)\n            sub_batch = self.batch.select(*batch_keys)\n        else:\n            sub_batch = self.batch\n\n        if non_tensor_batch_keys is not None:\n            non_tensor_batch = {key: val for key, val in self.non_tensor_batch.items() if key in non_tensor_batch_keys}\n        else:\n            non_tensor_batch = self.non_tensor_batch\n\n        if deepcopy:\n            non_tensor_batch = copy.deepcopy(non_tensor_batch)\n\n        if meta_info_keys is not None:\n            sub_meta_info = {key: val for key, val in self.meta_info.items() if key in meta_info_keys}\n        else:\n            sub_meta_info = self.meta_info\n\n        if deepcopy:\n            sub_meta_info = copy.deepcopy(sub_meta_info)\n\n        return DataProto(batch=sub_batch, non_tensor_batch=non_tensor_batch, meta_info=sub_meta_info)\n\n    def pop(self, batch_keys=None, non_tensor_batch_keys=None, meta_info_keys=None) -> 'DataProto':\n        \"\"\"Pop a subset of the DataProto via `batch_keys` and `meta_info_keys`\n\n        Args:\n            batch_keys (list, optional): a list of strings indicating the keys in batch to pop\n            meta_info_keys (list, optional): a list of keys indicating the meta info to pop\n\n        Returns:\n            DataProto: the DataProto with the poped batch_keys and meta_info_keys\n        \"\"\"\n        assert batch_keys is not None\n        if meta_info_keys is None:\n            meta_info_keys = []\n        if non_tensor_batch_keys is None:\n            non_tensor_batch_keys = []\n\n        tensors = {}\n        # tensor batch\n        for key in batch_keys:\n            assert key in self.batch.keys()\n            tensors[key] = self.batch.pop(key)\n        non_tensors = {}\n        # non tensor batch\n        for key in non_tensor_batch_keys:\n            assert key in self.non_tensor_batch.keys()\n            non_tensors[key] = self.non_tensor_batch.pop(key)\n        meta_info = {}\n        for key in meta_info_keys:\n            assert key in self.meta_info.keys()\n            meta_info[key] = self.meta_info.pop(key)\n        return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info)\n\n    def rename(self, old_keys=None, new_keys=None) -> 'DataProto':\n        \"\"\"\n        Note that this function only rename the key in the batch\n        \"\"\"\n\n        def validate_input(keys):\n            if keys is not None:\n                if isinstance(keys, str):\n                    keys = [keys]\n                elif isinstance(keys, list):\n                    pass\n                else:\n                    raise TypeError(f'keys must be a list or a string, but got {type(keys)}')\n            return keys\n\n        old_keys = validate_input(old_keys)\n        new_keys = validate_input(new_keys)\n\n        if len(new_keys) != len(old_keys):\n            raise ValueError(\n                f'new_keys and old_keys must have the same length, but got {len(new_keys)} and {len(old_keys)}')\n\n        self.batch.rename_key_(tuple(old_keys), tuple(new_keys))\n\n        return self\n\n    def union(self, other: 'DataProto') -> 'DataProto':\n        \"\"\"Union with another DataProto. Union batch and meta_info separately.\n        Throw an error if\n\n        - there are conflict keys in batch and they are not equal\n        - the batch size of two data batch is not the same\n        - there are conflict keys in meta_info and they are not the same.\n\n        Args:\n            other (DataProto): another DataProto to union\n\n        Returns:\n            DataProto: the DataProto after union\n        \"\"\"\n        self.batch = union_tensor_dict(self.batch, other.batch)\n        self.non_tensor_batch = union_numpy_dict(self.non_tensor_batch, other.non_tensor_batch)\n        self.meta_info = union_two_dict(self.meta_info, other.meta_info)\n        return self\n\n    def make_iterator(self, mini_batch_size, epochs, seed=None, dataloader_kwargs=None):\n        r\"\"\"Make an iterator from the DataProto. This is built upon that TensorDict can be used as a normal Pytorch\n        dataset. See https://pytorch.org/tensordict/tutorials/data_fashion for more details.\n\n\n        Args:\n            mini_batch_size (int): mini-batch size when iterating the dataset. We require that ``batch.batch_size[0] % mini_batch_size == 0``.\n            epochs (int): number of epochs when iterating the dataset.\n            dataloader_kwargs (Any): internally, it returns a DataLoader over the batch. The dataloader_kwargs is the kwargs passed to the DataLoader.\n\n        Returns:\n            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``\n        \"\"\"\n        assert self.batch.batch_size[0] % mini_batch_size == 0, f\"{self.batch.batch_size[0]} % {mini_batch_size} != 0\"\n        # we can directly create a dataloader from TensorDict\n        if dataloader_kwargs is None:\n            dataloader_kwargs = {}\n\n        if seed is not None:\n            generator = torch.Generator()\n            generator.manual_seed(seed)\n        else:\n            generator = None\n\n        assert isinstance(dataloader_kwargs, Dict)\n        train_dataloader = DataLoader(dataset=self,\n                                      batch_size=mini_batch_size,\n                                      collate_fn=collate_fn,\n                                      generator=generator,\n                                      **dataloader_kwargs)\n\n        def get_data():\n            for _ in range(epochs):\n                for d in train_dataloader:\n                    d.meta_info = self.meta_info\n                    yield d\n\n        return iter(get_data())\n\n    def chunk(self, chunks: int) -> List['DataProto']:\n        \"\"\"Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split.\n\n        Args:\n            chunks (int): the number of chunks to split on dim=0\n\n        Returns:\n            List[DataProto]: a list of DataProto after splitting\n        \"\"\"\n        assert len(\n            self) % chunks == 0, f'only support equal chunk. Got size of DataProto {len(self)} and chunk {chunks}.'\n\n        if self.batch is not None:\n            batch_lst = self.batch.chunk(chunks=chunks, dim=0)\n        else:\n            batch_lst = [None for _ in range(chunks)]\n\n        non_tensor_batch_lst = [{} for _ in range(chunks)]\n        for key, val in self.non_tensor_batch.items():\n            assert isinstance(val, np.ndarray)\n            non_tensor_lst = np.array_split(val, chunks)\n            assert len(non_tensor_lst) == chunks\n            for i in range(chunks):\n                non_tensor_batch_lst[i][key] = non_tensor_lst[i]\n\n        output = []\n        for i in range(chunks):\n            output.append(\n                DataProto(batch=batch_lst[i], non_tensor_batch=non_tensor_batch_lst[i], meta_info=self.meta_info))\n\n        return output\n\n    @staticmethod\n    def concat(data: List['DataProto']) -> 'DataProto':\n        \"\"\"Concat a list of DataProto. The batch is concatenated among dim=0.\n        The meta_info is assumed to be identical and will use the first one.\n\n        Args:\n            data (List[DataProto]): list of DataProto\n\n        Returns:\n            DataProto: concatenated DataProto\n        \"\"\"\n        batch_lst = []\n        for batch in data:\n            batch_lst.append(batch.batch)\n        if batch_lst[0] is not None:\n            new_batch = torch.cat(batch_lst, dim=0)\n        else:\n            new_batch = None\n\n        non_tensor_batch = list_of_dict_to_dict_of_list(list_of_dict=[d.non_tensor_batch for d in data])\n        for key, val in non_tensor_batch.items():\n            non_tensor_batch[key] = np.concatenate(val, axis=0)\n\n        return DataProto(batch=new_batch, non_tensor_batch=non_tensor_batch, meta_info=data[0].meta_info)\n\n    def reorder(self, indices):\n        \"\"\"\n        Note that this operation is in-place\n        \"\"\"\n        indices_np = indices.detach().numpy()\n        self.batch = self.batch[indices]\n        self.non_tensor_batch = {key: val[indices_np] for key, val in self.non_tensor_batch.items()}\n\n    def repeat(self, repeat_times=2, interleave=True):\n        \"\"\"\n        Repeat the batch data a specified number of times.\n\n        Args:\n            repeat_times (int): Number of times to repeat the data.\n            interleave (bool): Whether to interleave the repeated data.\n\n        Returns:\n            DataProto: A new DataProto with repeated data.\n        \"\"\"\n        if self.batch is not None:\n            if interleave:\n                # Interleave the data\n                repeated_tensors = {\n                    key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items()\n                }\n            else:\n                # Stack the data\n                repeated_tensors = {\n                    key: tensor.unsqueeze(0).expand(repeat_times, *tensor.shape).reshape(-1, *tensor.shape[1:])\n                    for key, tensor in self.batch.items()\n                }\n\n            repeated_batch = TensorDict(\n                source=repeated_tensors,\n                batch_size=(self.batch.batch_size[0] * repeat_times,),\n            )\n        else:\n            repeated_batch = None\n\n        repeated_non_tensor_batch = {}\n        for key, val in self.non_tensor_batch.items():\n            if interleave:\n                repeated_non_tensor_batch[key] = np.repeat(val, repeat_times, axis=0)\n            else:\n                repeated_non_tensor_batch[key] = np.tile(val, (repeat_times,) + (1,) * (val.ndim - 1))\n\n        return DataProto(\n            batch=repeated_batch,\n            non_tensor_batch=repeated_non_tensor_batch,\n            meta_info=self.meta_info,\n        )\n\n\nimport ray\n\n\n@dataclass\nclass DataProtoFuture:\n    \"\"\"\n    DataProtoFuture aims to eliminate actual data fetching on driver. By doing so, the driver doesn't have to wait\n    for data so that asynchronous execution becomes possible. \n    DataProtoFuture contains a list of futures from another WorkerGroup of size world_size.\n    - collect_fn is a Callable that reduces the list of futures to a DataProto\n    - dispatch_fn is a Callable that partitions the DataProto into a list of DataProto of size world_size and then select\n\n    Potential issue: we can optimize dispatch_fn(collect_fn) such that only needed data is fetched on destination\n    - DataProtoFuture only supports directly passing from the output of a method to another input. You can't perform any\n    operation on the DataProtoFuture in driver.\n    \"\"\"\n    collect_fn: Callable\n    futures: List[ray.ObjectRef]\n    dispatch_fn: Callable = None\n\n    @staticmethod\n    def concat(data: List[ray.ObjectRef]) -> 'DataProtoFuture':\n        output = DataProtoFuture(collect_fn=DataProto.concat, futures=data)\n        return output\n\n    def chunk(self, chunks: int) -> List['DataProtoFuture']:\n        from functools import partial\n\n        arg_future_lst = []\n        for i in range(chunks):\n            # note that we can't directly pass i and chunks\n            def dispatch_fn(x, i, chunks):\n                return x.chunk(chunks=chunks)[i]\n\n            arg_future = DataProtoFuture(collect_fn=self.collect_fn,\n                                         dispatch_fn=partial(dispatch_fn, i=i, chunks=chunks),\n                                         futures=self.futures)\n            arg_future_lst.append(arg_future)\n        return arg_future_lst\n\n    def get(self):\n        output = ray.get(self.futures)  # dp_size.\n        for o in output:\n            assert isinstance(o, DataProto)\n        output = self.collect_fn(output)  # select dp, concat\n        if self.dispatch_fn is not None:\n            output = self.dispatch_fn(output)  # split in batch dim, select using dp\n        return output\n"
  },
  {
    "path": "verl/single_controller/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\n\nversion_folder = os.path.dirname(os.path.join(os.path.abspath(__file__)))\n\n# Note(haibin.lin): single_controller.__version__ is deprecated\nwith open(os.path.join(os.path.join(version_folder, os.pardir), 'version/version')) as f:\n    __version__ = f.read().strip()\n\nfrom . import base\nfrom .base import *\n\n__all__ = base.__all__"
  },
  {
    "path": "verl/single_controller/base/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .worker import Worker\nfrom .worker_group import WorkerGroup, ClassWithInitArgs, ResourcePool\n\n__all__ = ['Worker', 'WorkerGroup', 'ClassWithInitArgs', 'ResourcePool']"
  },
  {
    "path": "verl/single_controller/base/decorator.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom enum import Enum\nfrom functools import wraps\nfrom typing import Dict, List, Tuple\nfrom types import FunctionType\nfrom verl.protocol import DataProtoFuture\n\n# here we add a magic number of avoid user-defined function already have this attribute\nMAGIC_ATTR = 'attrs_3141562937'\n\n\nclass Dispatch(Enum):\n    RANK_ZERO = 0\n    ONE_TO_ALL = 1\n    ALL_TO_ALL = 2\n    MEGATRON_COMPUTE = 3\n    MEGATRON_PP_AS_DP = 4\n    MEGATRON_PP_ONLY = 5\n    MEGATRON_COMPUTE_PROTO = 6\n    MEGATRON_PP_AS_DP_PROTO = 7\n    DP_COMPUTE = 8\n    DP_COMPUTE_PROTO = 9\n    DP_COMPUTE_PROTO_WITH_FUNC = 10\n    DP_COMPUTE_METRIC = 11\n\n\nclass Execute(Enum):\n    ALL = 0\n    RANK_ZERO = 1\n\n\ndef _split_args_kwargs_data_proto(chunks, *args, **kwargs):\n    from verl.protocol import DataProto, DataProtoFuture\n    splitted_args = []\n    for arg in args:\n        assert isinstance(arg, (DataProto, DataProtoFuture))\n        splitted_args.append(arg.chunk(chunks=chunks))\n\n    splitted_kwargs = {}\n    for key, val in kwargs.items():\n        assert isinstance(val, (DataProto, DataProtoFuture))\n        splitted_kwargs[key] = val.chunk(chunks=chunks)\n\n    return splitted_args, splitted_kwargs\n\n\ndef dispatch_one_to_all(worker_group, *args, **kwargs):\n    args = tuple([arg] * worker_group.world_size for arg in args)\n    kwargs = {k: [v] * worker_group.world_size for k, v in kwargs.items()}\n    return args, kwargs\n\n\ndef dispatch_all_to_all(worker_group, *args, **kwargs):\n    return args, kwargs\n\n\ndef collect_all_to_all(worker_group, output):\n    return output\n\n\ndef dispatch_megatron_compute(worker_group, *args, **kwargs):\n    \"\"\"\n    User passes in dp data. The data is dispatched to all tp/pp ranks with the same dp\n    \"\"\"\n    from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n    assert isinstance(worker_group,\n                      MegatronWorkerGroup), f'worker_group must be MegatronWorkerGroup, Got {type(worker_group)}'\n\n    all_args = []\n    for arg in args:\n        assert isinstance(arg, (Tuple, List)) and len(arg) == worker_group.dp_size\n        transformed_args = []\n        for i in range(worker_group.world_size):\n            local_dp_rank = worker_group.get_megatron_rank_info(rank=i).dp_rank\n            transformed_args.append(arg[local_dp_rank])\n        all_args.append(transformed_args)\n    all_args = tuple(all_args)\n\n    all_kwargs = {}\n    for k, v in kwargs.items():\n        assert isinstance(v, (Tuple, List)) and len(v) == worker_group.dp_size\n        transformed_v = []\n        for i in range(worker_group.world_size):\n            local_dp_rank = worker_group.get_megatron_rank_info(rank=i).dp_rank\n            transformed_v.append(v[local_dp_rank])\n        all_kwargs[k] = transformed_v\n    return all_args, all_kwargs\n\n\ndef collect_megatron_compute(worker_group, output):\n    \"\"\"\n    Only collect the data from the tp=0 and pp=last and every dp ranks\n    \"\"\"\n    from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n    assert isinstance(worker_group, MegatronWorkerGroup)\n    output_in_dp = []\n    pp_size = worker_group.get_megatron_global_info().pp_size\n    for global_rank in range(worker_group.world_size):\n        local_rank_info = worker_group.get_megatron_rank_info(rank=global_rank)\n        if local_rank_info.tp_rank == 0 and local_rank_info.pp_rank == pp_size - 1:\n            output_in_dp.append(output[global_rank])\n    return output_in_dp\n\n\ndef dispatch_megatron_compute_data_proto(worker_group, *args, **kwargs):\n    \"\"\"\n    All the args and kwargs must be DataProto. The batch will be chunked by dp_size and passed to each rank\n    \"\"\"\n    from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n    assert isinstance(worker_group, MegatronWorkerGroup)\n\n    splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(worker_group.dp_size, *args, **kwargs)\n    return dispatch_megatron_compute(worker_group, *splitted_args, **splitted_kwargs)\n\n\ndef _concat_data_proto_or_future(output: List):\n    from verl.protocol import DataProto, DataProtoFuture\n    import ray\n\n    # make sure all the elements in output has the same type\n    for o in output:\n        assert type(o) == type(output[0])\n\n    o = output[0]\n\n    if isinstance(o, DataProto):\n        return DataProto.concat(output)\n    elif isinstance(o, ray.ObjectRef):\n        return DataProtoFuture.concat(output)\n    else:\n        raise NotImplementedError\n\n\ndef collect_megatron_compute_data_proto(worker_group, output):\n    \"\"\"\n    Each output must be a DataProto. We concat the dim=0 of output\n    \"\"\"\n    from verl.protocol import DataProto\n    import ray\n\n    output = collect_megatron_compute(worker_group, output)\n    for o in output:\n        assert isinstance(o, (DataProto, ray.ObjectRef)), f\"expecting {o} to be DataProto, but got {type(o)}\"\n\n    return _concat_data_proto_or_future(output)\n\n\ndef dispatch_megatron_pp_as_dp(worker_group, *args, **kwargs):\n    \"\"\"\n    treat pp as dp.\n    \"\"\"\n    from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n    assert isinstance(worker_group, MegatronWorkerGroup)\n\n    pp_size = worker_group.pp_size\n    dp_size = worker_group.dp_size\n\n    pp_dp_size = pp_size * dp_size\n\n    all_args = []\n    for arg in args:\n        assert isinstance(arg, (List, Tuple)) and len(arg) == pp_dp_size\n        transformed_args = []\n        for i in range(worker_group.world_size):\n            local_dp_rank = worker_group.get_megatron_rank_info(rank=i).dp_rank\n            local_pp_rank = worker_group.get_megatron_rank_info(rank=i).pp_rank\n            # compute the rank in arg. Note that the order is dp then pp\n            # Also note that the outputs within a pp group will be firstly allgathered, then only the output of pp0 will be collected.\n            # For pp=2 dp=4, a batch of data \"ABCDEFGH\" should be dispatched and collected in below order:\n            #    dispatch:       pp_allgther:        collect:\n            #   dp 0 1 2 3      dp  0  1  2  3\n            # pp +---------+  pp +-------------+\n            #  0 | A C E G |   0 | AB CD EF GH |     ABCDEFGH\n            #  1 | B D F H |   1 | AB CD EF GH |\n            #    +---------+     +-------------+\n            arg_rank = local_dp_rank * worker_group.pp_size + local_pp_rank\n\n            transformed_args.append(arg[arg_rank])\n        all_args.append(transformed_args)\n    all_args = tuple(all_args)\n\n    all_kwargs = {}\n    for k, v in kwargs.items():\n        assert isinstance(v, (List, Tuple)) and len(v) == pp_dp_size, f'expect len(v)=={pp_dp_size}, got {len(v)}'\n        transformed_v = []\n        for i in range(worker_group.world_size):\n            local_dp_rank = worker_group.get_megatron_rank_info(rank=i).dp_rank\n            local_pp_rank = worker_group.get_megatron_rank_info(rank=i).pp_rank\n            # compute the rank in arg. Note that the order is dp then pp\n            arg_rank = local_dp_rank * worker_group.pp_size + local_pp_rank\n            transformed_v.append(v[arg_rank])\n        all_kwargs[k] = transformed_v\n    return all_args, all_kwargs\n\n\ndef collect_megatron_pp_as_dp(worker_group, output):\n    \"\"\"\n    treat pp as dp. Only collect data on tp=0\n    \"\"\"\n    from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n    assert isinstance(worker_group, MegatronWorkerGroup)\n    output_in_dp = []\n    for global_rank in range(worker_group.world_size):\n        local_rank_info = worker_group.get_megatron_rank_info(rank=global_rank)\n        if local_rank_info.tp_rank == 0 and local_rank_info.pp_rank == 0:\n            output_in_dp.append(output[global_rank])\n    return output_in_dp\n\n\ndef collect_megatron_pp_only(worker_group, output):\n    \"\"\"\n    Only collect output of megatron pp. This is useful when examine weight names as they are identical in tp/dp\n    \"\"\"\n    from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n    assert isinstance(worker_group, MegatronWorkerGroup)\n    output_in_pp = []\n    for global_rank in range(worker_group.world_size):\n        local_rank_info = worker_group.get_megatron_rank_info(rank=global_rank)\n        if local_rank_info.tp_rank == 0 and local_rank_info.dp_rank == 0:\n            output_in_pp.append(output[global_rank])\n    return output_in_pp\n\n\ndef dispatch_megatron_pp_as_dp_data_proto(worker_group, *args, **kwargs):\n    from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n    assert isinstance(worker_group, MegatronWorkerGroup)\n\n    pp_dp_size = worker_group.dp_size * worker_group.pp_size\n    splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(pp_dp_size, *args, **kwargs)\n    return dispatch_megatron_pp_as_dp(worker_group, *splitted_args, **splitted_kwargs)\n\n\ndef collect_megatron_pp_as_dp_data_proto(worker_group, output):\n    from verl.protocol import DataProto\n    from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n    assert isinstance(worker_group, MegatronWorkerGroup)\n\n    output = collect_megatron_pp_as_dp(worker_group, output)\n    return _concat_data_proto_or_future(output)\n\n\ndef dispatch_dp_compute(worker_group, *args, **kwargs):\n    from verl.single_controller.base.worker_group import WorkerGroup\n    assert isinstance(worker_group, WorkerGroup)\n    for arg in args:\n        assert isinstance(arg, (Tuple, List)) and len(arg) == worker_group.world_size\n    for k, v in kwargs.items():\n        assert isinstance(v, (Tuple, List)) and len(v) == worker_group.world_size\n    return args, kwargs\n\n\ndef collect_dp_compute(worker_group, output):\n    from verl.single_controller.base.worker_group import WorkerGroup\n    assert isinstance(worker_group, WorkerGroup)\n    assert len(output) == worker_group.world_size\n    return output\n\n\ndef dispatch_dp_compute_data_proto(worker_group, *args, **kwargs):\n    from verl.single_controller.base.worker_group import WorkerGroup\n    assert isinstance(worker_group, WorkerGroup)\n    splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(worker_group.world_size, *args, **kwargs)\n    return splitted_args, splitted_kwargs\n\n\ndef dispatch_dp_compute_data_proto_with_func(worker_group, *args, **kwargs):\n    from verl.single_controller.base.worker_group import WorkerGroup\n    assert isinstance(worker_group, WorkerGroup)\n    assert type(args[0]) == FunctionType  # NOTE: The first one args is a function!\n\n    splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(worker_group.world_size, *args[1:], **kwargs)\n    splitted_args_with_func = [[args[0]] * worker_group.world_size] + splitted_args\n    return splitted_args_with_func, splitted_kwargs\n\n\ndef collect_dp_compute_data_proto(worker_group, output):\n    from verl.protocol import DataProto\n    import ray\n\n    for o in output:\n        assert isinstance(o, (DataProto, ray.ObjectRef)), f\"expecting {o} to be DataProto, but got {type(o)}\"\n\n    output = collect_dp_compute(worker_group, output)\n    return _concat_data_proto_or_future(output)\n\n\ndef get_predefined_dispatch_fn(dispatch_mode):\n    predefined_dispatch_mode_fn = {\n        Dispatch.ONE_TO_ALL: {\n            'dispatch_fn': dispatch_one_to_all,\n            'collect_fn': collect_all_to_all,\n        },\n        Dispatch.ALL_TO_ALL: {\n            'dispatch_fn': dispatch_all_to_all,\n            'collect_fn': collect_all_to_all,\n        },\n        Dispatch.MEGATRON_COMPUTE: {\n            'dispatch_fn': dispatch_megatron_compute,\n            'collect_fn': collect_megatron_compute,\n        },\n        Dispatch.MEGATRON_PP_AS_DP: {\n            'dispatch_fn': dispatch_megatron_pp_as_dp,\n            'collect_fn': collect_megatron_pp_as_dp,\n        },\n        Dispatch.MEGATRON_PP_ONLY: {\n            'dispatch_fn': dispatch_one_to_all,\n            'collect_fn': collect_megatron_pp_only\n        },\n        Dispatch.MEGATRON_COMPUTE_PROTO: {\n            'dispatch_fn': dispatch_megatron_compute_data_proto,\n            'collect_fn': collect_megatron_compute_data_proto\n        },\n        Dispatch.MEGATRON_PP_AS_DP_PROTO: {\n            'dispatch_fn': dispatch_megatron_pp_as_dp_data_proto,\n            'collect_fn': collect_megatron_pp_as_dp_data_proto\n        },\n        Dispatch.DP_COMPUTE: {\n            'dispatch_fn': dispatch_dp_compute,\n            'collect_fn': collect_dp_compute\n        },\n        Dispatch.DP_COMPUTE_PROTO: {\n            'dispatch_fn': dispatch_dp_compute_data_proto,\n            'collect_fn': collect_dp_compute_data_proto\n        },\n        Dispatch.DP_COMPUTE_PROTO_WITH_FUNC: {\n            'dispatch_fn': dispatch_dp_compute_data_proto_with_func,\n            'collect_fn': collect_dp_compute_data_proto\n        },\n        Dispatch.DP_COMPUTE_METRIC: {\n            'dispatch_fn': dispatch_dp_compute_data_proto,\n            'collect_fn': collect_dp_compute\n        }\n    }\n    return predefined_dispatch_mode_fn[dispatch_mode]\n\n\ndef get_predefined_execute_fn(execute_mode):\n    \"\"\"\n    Note that here we only asks execute_all and execute_rank_zero to be implemented\n    Leave the choice of how these two functions handle argument 'blocking' to users\n    \"\"\"\n    predefined_execute_mode_fn = {\n        Execute.ALL: {\n            'execute_fn_name': 'execute_all'\n        },\n        Execute.RANK_ZERO: {\n            'execute_fn_name': 'execute_rank_zero'\n        }\n    }\n    return predefined_execute_mode_fn[execute_mode]\n\n\ndef _check_dispatch_mode(dispatch_mode):\n    assert isinstance(dispatch_mode,\n                      (Dispatch, Dict)), f'dispatch_mode must be a Dispatch or a Dict. Got {dispatch_mode}'\n    if isinstance(dispatch_mode, Dict):\n        necessary_keys = ['dispatch_fn', 'collect_fn']\n        for key in necessary_keys:\n            assert key in dispatch_mode, f'key {key} should be in dispatch_mode if it is a dictionary'\n\n\ndef _check_execute_mode(execute_mode):\n    assert isinstance(execute_mode, Execute), f'execute_mode must be a Execute. Got {execute_mode}'\n\n\ndef _materialize_futures(*args, **kwargs):\n    new_args = []\n    for arg in args:\n        if isinstance(arg, DataProtoFuture):\n            arg = arg.get()\n        # add more type to materialize\n        new_args.append(arg)\n    for k, v in kwargs.items():\n        if isinstance(v, DataProtoFuture):\n            kwargs[k] = v.get()\n\n    new_args = tuple(new_args)\n    return new_args, kwargs\n\n\ndef register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.ALL, blocking=True, materialize_futures=True):\n    _check_dispatch_mode(dispatch_mode=dispatch_mode)\n    _check_execute_mode(execute_mode=execute_mode)\n\n    def decorator(func):\n\n        @wraps(func)\n        def inner(*args, **kwargs):\n            if materialize_futures:\n                args, kwargs = _materialize_futures(*args, **kwargs)\n            return func(*args, **kwargs)\n\n        attrs = {'dispatch_mode': dispatch_mode, 'execute_mode': execute_mode, 'blocking': blocking}\n        setattr(inner, MAGIC_ATTR, attrs)\n        return inner\n\n    return decorator\n"
  },
  {
    "path": "verl/single_controller/base/megatron/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/single_controller/base/megatron/worker.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom verl.single_controller.base.worker import Worker, DistRankInfo, DistGlobalInfo\n\n\nclass MegatronWorker(Worker):\n\n    def __init__(self, cuda_visible_devices=None) -> None:\n        super().__init__(cuda_visible_devices)\n\n    def get_megatron_global_info(self):\n        from megatron.core import parallel_state as mpu\n        tp_size = mpu.get_tensor_model_parallel_world_size()\n        dp_size = mpu.get_data_parallel_world_size()\n        pp_size = mpu.get_pipeline_model_parallel_world_size()\n        info = DistGlobalInfo(tp_size=tp_size, dp_size=dp_size, pp_size=pp_size)\n        return info\n\n    def get_megatron_rank_info(self):\n        from megatron.core import parallel_state as mpu\n        tp_rank = mpu.get_tensor_model_parallel_rank()\n        dp_rank = mpu.get_data_parallel_rank()\n        pp_rank = mpu.get_pipeline_model_parallel_rank()\n        info = DistRankInfo(tp_rank=tp_rank, dp_rank=dp_rank, pp_rank=pp_rank)\n        return info"
  },
  {
    "path": "verl/single_controller/base/megatron/worker_group.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Dict\n\nfrom .worker import DistRankInfo, DistGlobalInfo\nfrom verl.single_controller.base import ResourcePool, WorkerGroup\n\n\nclass MegatronWorkerGroup(WorkerGroup):\n\n    def __init__(self, resource_pool: ResourcePool, **kwargs):\n        super().__init__(resource_pool=resource_pool, **kwargs)\n        self._megatron_rank_info = None\n        self._megatron_global_info: DistGlobalInfo = None\n\n    def init_megatron(self, default_megatron_kwargs: Dict = None):\n        raise NotImplementedError(f\"MegatronWorkerGroup.init_megatron should be overwritten\")\n\n    def get_megatron_rank_info(self, rank: int) -> DistRankInfo:\n        assert 0 <= rank < self.world_size, f'rank must be from [0, world_size), Got {rank}'\n        return self._megatron_rank_info[rank]\n\n    @property\n    def tp_size(self):\n        assert self._megatron_global_info is not None, \"MegatronWorkerGroup._megatron_global_info must be initialized\"\n        return self._megatron_global_info.tp_size\n\n    @property\n    def dp_size(self):\n        assert self._megatron_global_info is not None, \"MegatronWorkerGroup._megatron_global_info must be initialized\"\n        return self._megatron_global_info.dp_size\n\n    @property\n    def pp_size(self):\n        assert self._megatron_global_info is not None, \"MegatronWorkerGroup._megatron_global_info must be initialized\"\n        return self._megatron_global_info.pp_size\n\n    def get_megatron_global_info(self):\n        return self._megatron_global_info\n"
  },
  {
    "path": "verl/single_controller/base/register_center/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/single_controller/base/register_center/ray.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ray\n\n\n@ray.remote\nclass WorkerGroupRegisterCenter:\n\n    def __init__(self, rank_zero_info):\n        self.rank_zero_info = rank_zero_info\n\n    def get_rank_zero_info(self):\n        return self.rank_zero_info\n\n\ndef create_worker_group_register_center(name, info):\n    return WorkerGroupRegisterCenter.options(name=name).remote(info)\n"
  },
  {
    "path": "verl/single_controller/base/worker.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nthe class for Worker\n\"\"\"\nimport os\nimport socket\nfrom dataclasses import dataclass\nfrom .decorator import register, Dispatch, Execute\n\n\n@dataclass\nclass DistRankInfo:\n    tp_rank: int\n    dp_rank: int\n    pp_rank: int\n\n\n@dataclass\nclass DistGlobalInfo:\n    tp_size: int\n    dp_size: int\n    pp_size: int\n\n\nclass WorkerHelper:\n\n    def _get_node_ip(self):\n\n        def get_node_ip_by_sdk():\n            if os.getenv(\"WG_BACKEND\", None) == \"ray\":\n                import ray\n                return ray._private.services.get_node_ip_address()\n            else:\n                raise NotImplementedError(\"WG_BACKEND now just support ray mode.\")\n\n        host_ipv4 = os.getenv(\"MY_HOST_IP\", None)\n        host_ipv6 = os.getenv(\"MY_HOST_IPV6\", None)\n        host_ip_by_env = host_ipv4 or host_ipv6\n        host_ip_by_sdk = get_node_ip_by_sdk()\n\n        host_ip = host_ip_by_env or host_ip_by_sdk\n        return host_ip\n\n    def _get_free_port(self):\n        with socket.socket() as sock:\n            sock.bind(('', 0))\n            return sock.getsockname()[1]\n\n    def get_availale_master_addr_port(self):\n        return self._get_node_ip(), str(self._get_free_port())\n\n    def _get_pid(self):\n        return\n\n\nclass WorkerMeta:\n    keys = [\n        \"WORLD_SIZE\", \"RANK\", \"LOCAL_WORLD_SIZE\", \"LOCAL_RANK\", \"MASTER_ADDR\", \"MASTER_PORT\", \"CUDA_VISIBLE_DEVICES\"\n    ]\n\n    def __init__(self, store) -> None:\n        self._store = store\n\n    def to_dict(self):\n        return {f\"_{key.lower()}\": self._store.get(f\"_{key.lower()}\", None) for key in WorkerMeta.keys}\n\n\n# we assume that in each WorkerGroup, there is a Master Worker\nclass Worker(WorkerHelper):\n    \"\"\"A (distributed) worker.\"\"\"\n\n    def __new__(cls, *args, **kwargs):\n        instance = super().__new__(cls)\n\n        # note that here we use int to distinguish\n        disable_worker_init = int(os.environ.get('DISABLE_WORKER_INIT', 0))\n        if disable_worker_init:\n            return instance\n\n        rank = os.environ.get(\"RANK\", None)\n        worker_group_prefix = os.environ.get(\"WG_PREFIX\", None)\n\n        # when decorator @ray.remote applies, __new__ will be called while we don't want to apply _configure_before_init\n        if None not in [rank, worker_group_prefix] and 'ActorClass(' not in cls.__name__:\n            instance._configure_before_init(f\"{worker_group_prefix}_register_center\", int(rank))\n\n        return instance\n\n    def _configure_before_init(self, register_center_name: str, rank: int):\n        assert isinstance(rank, int), f\"rank must be int, instead of {type(rank)}\"\n\n        if rank == 0:\n            master_addr, master_port = self.get_availale_master_addr_port()\n            rank_zero_info = {\n                \"MASTER_ADDR\": master_addr,\n                \"MASTER_PORT\": master_port,\n            }\n\n            if os.getenv(\"WG_BACKEND\", None) == \"ray\":\n                from verl.single_controller.base.register_center.ray import create_worker_group_register_center\n                self.register_center = create_worker_group_register_center(name=register_center_name,\n                                                                           info=rank_zero_info)\n\n            os.environ.update(rank_zero_info)\n\n    def __init__(self, cuda_visible_devices=None) -> None:\n        # construct a meta from envrionment variable. Note that the import must be inside the class because it is executed remotely\n        import os\n        world_size = int(os.environ['WORLD_SIZE'])\n        rank = int(os.environ['RANK'])\n        self._rank = rank\n        self._world_size = world_size\n\n        master_addr = os.environ[\"MASTER_ADDR\"]\n        master_port = os.environ[\"MASTER_PORT\"]\n\n        local_world_size = int(os.getenv(\"LOCAL_WORLD_SIZE\", \"1\"))\n        local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n\n        store = {\n            '_world_size': world_size,\n            '_rank': rank,\n            '_local_world_size': local_world_size,\n            '_local_rank': local_rank,\n            '_master_addr': master_addr,\n            '_master_port': master_port\n        }\n        if cuda_visible_devices is not None:\n            store['_cuda_visible_devices'] = cuda_visible_devices\n\n        meta = WorkerMeta(store=store)\n        self._configure_with_meta(meta=meta)\n\n    def _configure_with_meta(self, meta: WorkerMeta):\n        \"\"\"\n        This function should only be called inside by WorkerGroup\n        \"\"\"\n        assert isinstance(meta, WorkerMeta)\n        self.__dict__.update(meta.to_dict())  # this is hacky\n        # print(f\"__dict__: {self.__dict__}\")\n        for key in WorkerMeta.keys:\n            val = self.__dict__.get(f\"_{key.lower()}\", None)\n            if val is not None:\n                # print(f\"set {key} to {val}\")\n                os.environ[key] = str(val)\n        os.environ[\"REDIS_STORE_SERVER_HOST\"] = str(self._master_addr).replace(\"[\", \"\").replace(\n            \"]\", \"\") if self._master_addr else \"\"\n\n    def get_master_addr_port(self):\n        return self._master_addr, self._master_port\n\n    def get_cuda_visible_devices(self):\n        import os\n        cuda_visible_devices = os.environ.get(\"CUDA_VISIBLE_DEVICES\", \"not set\")\n        return cuda_visible_devices\n\n    @property\n    def world_size(self):\n        return self._world_size\n\n    @property\n    def rank(self):\n        return self._rank\n\n    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO_WITH_FUNC)\n    def execute_with_func_generator(self, func, *args, **kwargs):\n        ret_proto = func(self, *args, **kwargs)\n        return ret_proto\n\n    @register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.RANK_ZERO)\n    def execute_func_rank_zero(self, func, *args, **kwargs):\n        result = func(*args, **kwargs)\n        return result\n"
  },
  {
    "path": "verl/single_controller/base/worker_group.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nthe class of WorkerGroup\n\"\"\"\nimport logging\nimport threading\nimport signal\nimport time\nfrom typing import List, Any, Callable, Dict\n\nfrom .decorator import MAGIC_ATTR, Dispatch, get_predefined_dispatch_fn, get_predefined_execute_fn\n\n\nclass ResourcePool:\n    \"\"\"The resource pool with meta info such as world_size.\"\"\"\n\n    def __init__(self, process_on_nodes=None, max_collocate_count: int = 10, n_gpus_per_node=8) -> None:\n        if process_on_nodes is None:\n            process_on_nodes = []\n        self._store = process_on_nodes\n        self.max_collocate_count = max_collocate_count\n        self.n_gpus_per_node = n_gpus_per_node  # this is left for future huawei GPU that contains 16 GPUs per node\n\n    def add_node(self, process_count):\n        self._store.append(process_count)\n\n    @property\n    def world_size(self):\n        return sum(self._store)\n\n    def __call__(self) -> Any:\n        return self._store\n\n    @property\n    def store(self):\n        return self._store\n\n    def local_world_size_list(self) -> List[int]:\n        nested_local_world_size_list = [\n            [local_world_size for _ in range(local_world_size)] for local_world_size in self._store\n        ]\n        return [item for row in nested_local_world_size_list for item in row]\n\n    def local_rank_list(self) -> List[int]:\n        nested_local_rank_list = [[i for i in range(local_world_size)] for local_world_size in self._store]\n        return [item for row in nested_local_rank_list for item in row]\n\n\nclass ClassWithInitArgs:\n    \"\"\"\n    This class stores a class constructor and the args/kwargs to construct the class.\n    It is used to instantiate the remote class.\n    \"\"\"\n\n    def __init__(self, cls, *args, **kwargs) -> None:\n        self.cls = cls\n        self.args = args\n        self.kwargs = kwargs\n\n    # def add_arg(self, arg):\n    #     self.args += (arg,)\n\n    # def add_kwarg(self, key, value):\n    #     self.kwargs[key] = value\n\n    def __call__(self) -> Any:\n        return self.cls(*self.args, **self.kwargs)\n\n\ndef check_workers_alive(workers: List, is_alive: Callable, gap_time: float = 1) -> None:\n    import time\n    while True:\n        for worker in workers:\n            if not is_alive(worker):\n                logging.warning(f\"worker {worker} is not alive\" + \" sending signal to main thread\")\n                signal.raise_signal(signal.SIGABRT)\n        time.sleep(gap_time)\n\n\nclass WorkerGroup:\n    \"\"\"A group of workers\"\"\"\n\n    def __init__(self, resource_pool: ResourcePool, **kwargs) -> None:\n        self._is_init_with_detached_workers = True if resource_pool is None else False\n\n        if resource_pool is not None:\n            # handle the case when WorkGroup is attached to an existing one\n            self._procecss_dispatch_config = resource_pool()\n        else:\n            self._procecss_dispatch_config = None\n\n        self._workers = []\n        self._worker_names = []\n\n        self._master_addr = None\n        self._master_port = None\n\n        self._checker_thread: threading.Thread = None\n\n    def _is_worker_alive(self, worker):\n        raise NotImplementedError(f\"WorkerGroup._is_worker_alive called, should be implemented in derived class.\")\n\n    def _block_until_all_workers_alive(self) -> None:\n        while True:\n            all_state = [self._is_worker_alive(worker) for worker in self._workers]\n            if False in all_state:\n                time.sleep(1)\n            else:\n                break\n\n    def start_worker_aliveness_check(self, every_n_seconds=1) -> None:\n        # before starting checking worker aliveness, make sure all workers are already alive\n        self._block_until_all_workers_alive()\n\n        self._checker_thread = threading.Thread(target=check_workers_alive,\n                                                args=(self._workers, self._is_worker_alive, every_n_seconds))\n        self._checker_thread.start()\n\n    @property\n    def world_size(self):\n        return len(self._workers)\n\n    # execute_all_async and execute_rank_zero_async should be implemented by RayWorkerGroup, TorchRPCWorkerGroup,\n    # MegatronWorkerGroup, XperfWorkerGroup should skip\n\n    def _bind_worker_method(self, user_defined_cls, func_generator):\n        \"\"\"\n        Bind the worker method to the WorkerGroup\n        \"\"\"\n\n        for method_name in dir(user_defined_cls):\n\n            try:\n                method = getattr(user_defined_cls, method_name)\n                assert callable(method), f\"{method_name} in {user_defined_cls} is not callable\"\n            except Exception as e:\n                # if it is a property, it will fail because Class doesn't have instance property\n                continue\n\n            if hasattr(method, MAGIC_ATTR):\n                # this method is decorated by register\n                attribute = getattr(method, MAGIC_ATTR)\n                assert isinstance(attribute, Dict), f'attribute must be a dictionary. Got {type(attribute)}'\n                assert 'dispatch_mode' in attribute, f'attribute must contain dispatch_mode in its key'\n\n                dispatch_mode = attribute['dispatch_mode']\n                execute_mode = attribute['execute_mode']\n                blocking = attribute['blocking']\n\n                # get dispatch fn\n                if isinstance(dispatch_mode, Dispatch):\n                    # get default dispatch fn\n                    fn = get_predefined_dispatch_fn(dispatch_mode=dispatch_mode)\n                    dispatch_fn = fn['dispatch_fn']\n                    collect_fn = fn['collect_fn']\n                else:\n                    assert isinstance(dispatch_mode, dict)\n                    assert 'dispatch_fn' in dispatch_mode\n                    assert 'collect_fn' in dispatch_mode\n                    dispatch_fn = dispatch_mode['dispatch_fn']\n                    collect_fn = dispatch_mode['collect_fn']\n\n                # get execute_fn_name\n                execute_mode = get_predefined_execute_fn(execute_mode=execute_mode)\n                wg_execute_fn_name = execute_mode['execute_fn_name']\n\n                # get execute_fn from string\n                try:\n                    execute_fn = getattr(self, wg_execute_fn_name)\n                    assert callable(execute_fn), 'execute_fn must be callable'\n                except Exception as e:\n                    print(f'execute_fn {wg_execute_fn_name} is invalid')\n                    raise\n\n                # bind a new method to the RayWorkerGroup\n                func = func_generator(self,\n                                      method_name,\n                                      dispatch_fn=dispatch_fn,\n                                      collect_fn=collect_fn,\n                                      execute_fn=execute_fn,\n                                      blocking=blocking)\n\n                try:\n                    setattr(self, method_name, func)\n                except Exception as e:\n                    raise ValueError(f'Fail to set method_name {method_name}')\n"
  },
  {
    "path": "verl/single_controller/ray/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .base import RayResourcePool, RayClassWithInitArgs, RayWorkerGroup, create_colocated_worker_cls"
  },
  {
    "path": "verl/single_controller/ray/base.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport time\nfrom typing import Dict, List, Any, Tuple\n\nimport ray\nfrom ray.util import list_named_actors\nfrom ray.util.placement_group import placement_group, PlacementGroup\nfrom ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy, NodeAffinitySchedulingStrategy\nfrom ray.experimental.state.api import get_actor\n\nfrom verl.single_controller.base import WorkerGroup, ResourcePool, ClassWithInitArgs, Worker\n\n__all__ = ['Worker']\n\n\ndef get_random_string(length: int) -> str:\n    import random\n    import string\n    letters_digits = string.ascii_letters + string.digits\n    return ''.join(random.choice(letters_digits) for _ in range(length))\n\n\ndef func_generator(self, method_name, dispatch_fn, collect_fn, execute_fn, blocking):\n\n    def func(*args, **kwargs):\n        args, kwargs = dispatch_fn(self, *args, **kwargs)\n        output = execute_fn(method_name, *args, **kwargs)\n        if blocking:\n            output = ray.get(output)\n        output = collect_fn(self, output)\n        return output\n\n    return func\n\n\nclass RayResourcePool(ResourcePool):\n\n    def __init__(self,\n                 process_on_nodes: List[int] = None,\n                 use_gpu: bool = True,\n                 name_prefix: str = \"\",\n                 max_colocate_count: int = 5,\n                 detached=False) -> None:\n        super().__init__(process_on_nodes, max_colocate_count)\n        self.use_gpu = use_gpu\n        # print(f\"in RayProcessDispatchConfiguration: name_prefix = {name_prefix}\")\n        self.name_prefix = name_prefix\n        self.pgs = None\n        self.detached = detached\n\n    def get_placement_groups(self, strategy=\"STRICT_PACK\", name=None):\n        if self.pgs is not None:\n            return self.pgs\n\n        pg_name_prefix = name if name else \\\n            f\"{self.name_prefix}verl_group_{'_'.join([str(count) for count in self._store])}:\"\n        # print(f\"pg_name_prefix = {pg_name_prefix}\")\n        pg_scheme = [[{\n            \"CPU\": self.max_collocate_count,\n            \"GPU\": 1\n        } if self.use_gpu else {\n            \"CPU\": self.max_collocate_count\n        } for _ in range(process_count)] for process_count in self._store]\n\n        lifetime = 'detached' if self.detached else None\n\n        pgs = [\n            placement_group(bundles=bundles, strategy=strategy, name=pg_name_prefix + str(idx), lifetime=lifetime)\n            for idx, bundles in enumerate(pg_scheme)\n        ]\n\n        ray.get([pg.ready() for pg in pgs])\n\n        self.pgs = pgs\n        return pgs\n\n\ndef extract_pg_from_exist(resource_pools: Dict[str, RayResourcePool], src_role_names: List[str],\n                          resource_pool: RayResourcePool) -> List:\n\n    src_pgs = [\n        pg for role_name, resource_pool in resource_pools.items() for pg in resource_pool.get_placement_groups()\n        if role_name in src_role_names\n    ]\n\n    sorted_src_pgs = sorted(src_pgs, key=lambda pg: pg.bundle_count, reverse=True)\n    sorted_process_on_nodes = sorted([(val, idx) for idx, val in enumerate(resource_pool.store)], reverse=True)\n\n    unsorted_pgs: List[Tuple[int, PlacementGroup]] = []\n    searching_idx = 0\n    for request_process, original_idx in sorted_process_on_nodes:\n        assert searching_idx < len(sorted_src_pgs), f\"no enough nodes for request: searching {searching_idx} th node\"\n        assert request_process <= sorted_src_pgs[searching_idx].bundle_count, \\\n            f\"requesting {request_process} processes, bundle count cannot satisfy\"\n        unsorted_pgs.append((original_idx, sorted_src_pgs[searching_idx]))\n        searching_idx += 1\n\n    return [pg for _, pg in sorted(unsorted_pgs)]\n\n\ndef merge_resource_pool(rp1: RayResourcePool, rp2: RayResourcePool) -> RayResourcePool:\n    assert rp1.use_gpu == rp2.use_gpu, 'Both RayResourcePool must either use_gpu or not'\n    assert rp1.max_collocate_count == rp2.max_collocate_count, 'Both RayResourcePool must has the same max_collocate_count'\n    assert rp1.n_gpus_per_node == rp2.n_gpus_per_node, 'Both RayResourcePool must has the same n_gpus_per_node'\n    assert rp1.detached == rp2.detached, 'Detached ResourcePool cannot be merged with non-detached ResourcePool'\n\n    new_store = rp1.store + rp2.store\n\n    merged = RayResourcePool(new_store, rp1.use_gpu, f\"{rp1.name_prefix}_{rp2.name_prefix}\")\n    merged.pgs = rp1.get_placement_groups() + rp2.get_placement_groups()\n\n    return merged\n\n\nclass RayClassWithInitArgs(ClassWithInitArgs):\n\n    def __init__(self, cls, *args, **kwargs) -> None:\n        # self._options = kwargs.pop('options', dict())\n        super().__init__(cls, *args, **kwargs)\n        self._options = {}\n        self._additional_resource = {}\n\n    def set_additional_resource(self, additional_resource):\n        self._additional_resource = additional_resource\n\n    def update_options(self, options: Dict):\n        self._options.update(options)\n\n    def __call__(self,\n                 placement_group,\n                 placement_group_bundle_idx,\n                 use_gpu: bool = True,\n                 num_gpus=1,\n                 sharing_with=None) -> Any:\n        if sharing_with is not None:\n            target_node_id = ray.get(sharing_with.get_node_id.remote())\n            cuda_visible_devices = ray.get(sharing_with.get_cuda_visible_devices.remote())\n            options = {\"scheduling_strategy\": NodeAffinitySchedulingStrategy(node_id=target_node_id, soft=False)}\n            return self.cls.options(**options).remote(*self.args,\n                                                      cuda_visible_devices=cuda_visible_devices,\n                                                      **self.kwargs)\n\n        options = {\n            \"scheduling_strategy\":\n                PlacementGroupSchedulingStrategy(placement_group=placement_group,\n                                                 placement_group_bundle_index=placement_group_bundle_idx)\n        }\n        options.update(self._options)\n\n        if use_gpu:\n            options[\"num_gpus\"] = num_gpus\n\n        if len(self._additional_resource) > 1:\n            for k, v in self._additional_resource.items():\n                options[k] = v\n\n        # print(\"cls:\", self.cls)\n        # print(\"args: \", self.args)\n        # print(\"kwargs: \", self.kwargs)\n        return self.cls.options(**options).remote(*self.args, **self.kwargs)\n\n\nclass RayWorkerGroup(WorkerGroup):\n\n    def __init__(self,\n                 resource_pool: RayResourcePool = None,\n                 ray_cls_with_init: RayClassWithInitArgs = None,\n                 bin_pack: bool = True,\n                 name_prefix: str = None,\n                 detached=False,\n                 worker_names=None,\n                 **kwargs) -> None:\n        super().__init__(resource_pool=resource_pool, **kwargs)\n        self.ray_cls_with_init = ray_cls_with_init\n        self.name_prefix = get_random_string(length=6) if name_prefix is None else name_prefix\n\n        if worker_names is not None:\n            assert self._is_init_with_detached_workers\n            self._worker_names = worker_names\n\n        if self._is_init_with_detached_workers:\n            self._init_with_detached_workers(worker_names=worker_names)\n        else:\n            self._init_with_resource_pool(resource_pool=resource_pool,\n                                          ray_cls_with_init=ray_cls_with_init,\n                                          bin_pack=bin_pack,\n                                          detached=detached)\n\n        if ray_cls_with_init is not None:\n            self._bind_worker_method(self.ray_cls_with_init.cls, func_generator)\n\n    def _is_worker_alive(self, worker: ray.actor.ActorHandle):\n        worker_state_dict = get_actor(worker._actor_id.hex())\n        return worker_state_dict.get(\"state\", \"undefined\") == \"ALIVE\" if worker_state_dict is not None else False\n\n    def _init_with_detached_workers(self, worker_names):\n        workers = [ray.get_actor(name=name) for name in worker_names]\n        self._workers = workers\n        self._world_size = len(worker_names)\n\n    def _init_with_resource_pool(self, resource_pool, ray_cls_with_init, bin_pack, detached):\n        use_gpu = resource_pool.use_gpu\n\n        strategy = \"PACK\"\n        if bin_pack:\n            strategy = \"STRICT_PACK\"\n        pgs = resource_pool.get_placement_groups(strategy=strategy)\n        world_size = resource_pool.world_size\n        self._world_size = world_size\n        # cia.add_kwarg(\"_world_size\", world_size)\n        num_gpus = 1 / resource_pool.max_collocate_count\n\n        rank = -1\n        for pg_idx, local_world_size in enumerate(resource_pool.store):\n            pg = pgs[pg_idx]\n            assert local_world_size <= pg.bundle_count, \\\n                f\"when generating for {self.name_prefix}, for the \"\n            for local_rank in range(local_world_size):\n                rank += 1\n\n                # we pass in environment variable at option so that Worker can use environment variable to set\n                env_vars = {\n                    'WORLD_SIZE': str(world_size),\n                    'RANK': str(rank),\n                    'WG_PREFIX': self.name_prefix,\n                    'WG_BACKEND': 'ray',\n                    'RAY_LOCAL_WORLD_SIZE': str(local_world_size),\n                    'RAY_LOCAL_RANK': str(local_rank),\n                }\n                if rank != 0:\n                    env_vars['MASTER_ADDR'] = self._master_addr\n                    env_vars['MASTER_PORT'] = self._master_port\n\n                import re\n                cia_name = type(ray_cls_with_init.cls).__name__\n                match = re.search(r\"ActorClass\\(([^)]+)\\)\", cia_name)  # ray.remote(Obj) -> \"ActorClass(Obj)\"\n                cia_name = match.group(1) if match else cia_name  # \"ActorClass(Obj)\" -> \"Obj\"\n                name = f\"{self.name_prefix}{cia_name}_{pg_idx}:{local_rank}\"  # e.g. Worker_2:5\n\n                ray_cls_with_init.update_options({'runtime_env': {'env_vars': env_vars}, 'name': name})\n\n                if detached:\n                    ray_cls_with_init.update_options({'lifetime': 'detached'})\n\n                # create a worker\n                worker = ray_cls_with_init(placement_group=pg,\n                                           placement_group_bundle_idx=local_rank,\n                                           use_gpu=use_gpu,\n                                           num_gpus=num_gpus)\n                self._workers.append(worker)\n                self._worker_names.append(name)\n\n                if rank == 0:\n                    register_center_actor = None\n                    for _ in range(120):\n                        if f\"{self.name_prefix}_register_center\" not in list_named_actors():\n                            time.sleep(1)\n                        else:\n                            register_center_actor = ray.get_actor(f\"{self.name_prefix}_register_center\")\n                            break\n                    assert register_center_actor is not None, f\"failed to get register_center_actor: {self.name_prefix}_register_center in {list_named_actors(all_namespaces=True)}\"\n                    rank_zero_info = ray.get(register_center_actor.get_rank_zero_info.remote())\n                    self._master_addr, self._master_port = rank_zero_info['MASTER_ADDR'], rank_zero_info['MASTER_PORT']\n                    # print(f\"rank_zero_info: {rank_zero_info}\")\n                    # print(f\"master_addr: {self._master_addr}, master_port: {self._master_port}\")\n\n    @property\n    def worker_names(self):\n        return self._worker_names\n\n    @classmethod\n    def from_detached(cls, worker_names=None, ray_cls_with_init=None):\n        worker_group = cls(resource_pool=None,\n                           ray_cls_with_init=ray_cls_with_init,\n                           name_prefix=None,\n                           worker_names=worker_names)\n        return worker_group\n\n    def spawn(self, prefix_set):\n        \"\"\"\n        spawn to a dictionary of worker groups, each with a subset of method with prefix.\n\n        \"\"\"\n\n        def _rebind_actor_methods(worker_group, actor_name):\n            \"\"\"\n            bind the method with actor_prefix to its original name\n            \"\"\"\n            prefix: str = actor_name + '_'\n            for method_name in dir(worker_group):\n                if method_name.startswith(prefix):\n                    # only valid when Python >= 3.9\n                    original_method_name = method_name.removeprefix(prefix)\n                    method = getattr(worker_group, method_name)\n                    setattr(worker_group, original_method_name, method)\n\n        new_worker_group_dict = {}\n        for prefix in prefix_set:\n            new_worker_group = self.from_detached(worker_names=self._worker_names,\n                                                  ray_cls_with_init=self.ray_cls_with_init)\n\n            _rebind_actor_methods(new_worker_group, prefix)\n            new_worker_group_dict[prefix] = new_worker_group\n        return new_worker_group_dict\n\n    def execute_rank_zero_sync(self, method_name: str, *args, **kwargs):\n        return ray.get(self.execute_rank_zero_async(method_name, *args, **kwargs))\n\n    def execute_rank_zero_async(self, method_name: str, *args, **kwargs):\n        remote_call = getattr(self._workers[0], method_name)\n        return remote_call.remote(*args, **kwargs)\n\n    def execute_rank_zero(self, method_name: str, *args, **kwargs):\n        return self.execute_rank_zero_async(method_name, *args, **kwargs)\n\n    def execute_all(self, method_name: str, *args, **kwargs):\n        return self.execute_all_async(method_name, *args, **kwargs)\n\n    def execute_all_sync(self, method_name: str, *args, **kwargs):\n        return ray.get(self.execute_all_async(method_name, *args, **kwargs))\n\n    def execute_all_async(self, method_name: str, *args, **kwargs):\n        # Here, we assume that if all arguments in args and kwargs are lists, and their lengths match len(self._workers),\n        # we'll distribute each element in these lists to the corresponding worker\n        # print(f\"execute_all_async: method {method_name}({args}, {kwargs})\")\n        length = len(self._workers)\n        if all(isinstance(arg, list) for arg in args) and all(isinstance(kwarg, list) for kwarg in kwargs.values()):\n            if all(len(arg) == length for arg in args) and all(len(kwarg) == length for kwarg in kwargs.values()):\n                # print(f\"splitting args and kwargs into {length} shards\")\n                result = []\n                for i in range(length):\n                    sliced_args = tuple(arg[i] for arg in args)\n                    sliced_kwargs = {k: v[i] for k, v in kwargs.items()}\n                    remote_call = getattr(self._workers[i], method_name)\n                    result.append(remote_call.remote(*sliced_args, **sliced_kwargs))\n                return result\n\n        return [getattr(worker, method_name).remote(*args, **kwargs) for worker in self._workers]\n\n    @property\n    def master_address(self):\n        return self._master_addr\n\n    @property\n    def master_port(self):\n        return self._master_port\n\n    @property\n    def workers(self):\n        return self._workers\n\n    @property\n    def world_size(self):\n        return self._world_size\n\n\n\"\"\"\nUtilities that enables creating workers inside the same ray.Actor, \nwith code written in separate ray.Actors.\n\"\"\"\n\nfrom unittest.mock import patch\nfrom verl.single_controller.base.decorator import MAGIC_ATTR\nimport os\n\n\ndef _bind_workers_method_to_parent(cls, key, user_defined_cls):\n    \"\"\"\n    Binds the methods of each worker to the WorkerDict. \n    Note that we only bind public methods that are decorated by register\n    \"\"\"\n    for method_name in dir(user_defined_cls):\n        try:\n            method = getattr(user_defined_cls, method_name)\n            assert callable(method), f\"{method_name} in {user_defined_cls} is not callable\"\n        except Exception as e:\n            # if it is a property, it will fail because Class doesn't have instance property\n            continue\n\n        if hasattr(method, MAGIC_ATTR):\n\n            def generate_function(name):\n\n                def func(self, *args, **kwargs):\n                    # dispatch to the actual worker\n                    return getattr(self.worker_dict[key], name)(*args, **kwargs)\n\n                return func\n\n            func = generate_function(method_name)\n            # pass MAGIC_ATTR for outer worker group\n            setattr(func, MAGIC_ATTR, getattr(method, MAGIC_ATTR))\n            try:\n                method_name_with_prefix = key + '_' + method_name\n                setattr(cls, method_name_with_prefix, func)\n                # print(f'Binding {method_name_with_prefix}')\n            except Exception as e:\n                raise ValueError(f'Fail to set method_name {method_name}')\n\n\ndef _unwrap_ray_remote(cls):\n    if hasattr(cls, '__ray_actor_class__'):\n        cls = cls.__ray_actor_class__\n    return cls\n\n\ndef create_colocated_worker_cls(class_dict: dict[str, RayClassWithInitArgs]):\n    \"\"\"\n    This function should return a class instance that delegates the calls to every \n    cls in cls_dict\n    \"\"\"\n    cls_dict = {}\n    init_args_dict = {}\n    worker_cls = None\n    for key, cls in class_dict.items():\n        if worker_cls == None:\n            worker_cls = cls.cls.__ray_actor_class__.__base__\n        else:\n            assert worker_cls == cls.cls.__ray_actor_class__.__base__, \\\n                'the worker class should be the same when share the same process'\n        cls_dict[key] = cls.cls\n        init_args_dict[key] = {'args': cls.args, 'kwargs': cls.kwargs}\n\n    assert cls_dict.keys() == init_args_dict.keys()\n\n    # TODO: create a class with customizable name\n    class WorkerDict(worker_cls):\n\n        def __init__(self):\n            super().__init__()\n            self.worker_dict = {}\n            for key, user_defined_cls in cls_dict.items():\n                user_defined_cls = _unwrap_ray_remote(user_defined_cls)\n                # directly instantiate the class without remote\n                with patch.dict(os.environ, {'DISABLE_WORKER_INIT': '1'}):\n                    self.worker_dict[key] = user_defined_cls(*init_args_dict[key].get('args', ()),\n                                                             **init_args_dict[key].get('kwargs', {}))\n\n    # now monkey-patch the methods from inner class to WorkerDict\n    for key, user_defined_cls in cls_dict.items():\n        user_defined_cls = _unwrap_ray_remote(user_defined_cls)\n        _bind_workers_method_to_parent(WorkerDict, key, user_defined_cls)\n\n    remote_cls = ray.remote(WorkerDict)\n    remote_cls = RayClassWithInitArgs(cls=remote_cls)\n    return remote_cls\n"
  },
  {
    "path": "verl/single_controller/ray/megatron.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Dict, Optional\n\nimport ray\n\nfrom .base import RayWorkerGroup, RayResourcePool, RayClassWithInitArgs\nfrom verl.single_controller.base.megatron.worker import DistRankInfo, DistGlobalInfo\nfrom verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup\n\n\n# NOTE(sgm): for open-source megatron-core\nclass NVMegatronRayWorkerGroup(RayWorkerGroup, MegatronWorkerGroup):\n    \"\"\"\n    MegatronWorkerGroup will query each worker of its megatron rank info and store it inside the WorkerGroup\n    so that the dispatcher can use it to dispatch data.\n    \"\"\"\n\n    def __init__(self, resource_pool: RayResourcePool, ray_cls_with_init: RayClassWithInitArgs, **kwargs):\n        super().__init__(resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, **kwargs)\n        self._megatron_rank_info: DistRankInfo = self.execute_all_sync(method_name='get_megatron_rank_info')\n        self._megatron_global_info: DistGlobalInfo = ray.get(\n            self.execute_rank_zero_async(method_name='get_megatron_global_info'))\n\n\nclass MegatronRayWorkerGroup(RayWorkerGroup, MegatronWorkerGroup):\n    \"\"\"\n    MegatronWorkerGroup will query each worker of its megatron rank info and store it inside the WorkerGroup\n    so that the dispatcher can use it to dispatch data.\n    \"\"\"\n\n    def __init__(self,\n                 resource_pool: RayResourcePool,\n                 ray_cls_with_init: RayClassWithInitArgs,\n                 default_megatron_kwargs: Dict = None,\n                 **kwargs):\n        super().__init__(resource_pool=resource_pool,\n                         ray_cls_with_init=ray_cls_with_init,\n                         default_megatron_kwargs=default_megatron_kwargs,\n                         **kwargs)\n        self.init_megatron(default_megatron_kwargs=default_megatron_kwargs)\n        self._megatron_rank_info: DistRankInfo = self.execute_all_sync(method_name='get_megatron_rank_info')\n        self._megatron_global_info: DistGlobalInfo = ray.get(\n            self.execute_rank_zero_async(method_name='get_megatron_global_info'))\n\n    def init_megatron(self, default_megatron_kwargs: Optional[Dict] = None):\n        # after super, we will call init of each worker\n        if not self._is_init_with_detached_workers:\n            # only init_megatron if the WorkerGroup is created from scratch\n            self.execute_all_sync(method_name='init_megatron', default_megatron_kwargs=default_megatron_kwargs)\n"
  },
  {
    "path": "verl/third_party/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/third_party/vllm/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom importlib.metadata import version, PackageNotFoundError\nfrom packaging import version as vs\n\n\ndef get_version(pkg):\n    try:\n        return version(pkg)\n    except PackageNotFoundError:\n        return None\n\n\npackage_name = 'vllm'\npackage_version = get_version(package_name)\nvllm_version = None\n\nif package_version == '0.3.1':\n    vllm_version = '0.3.1'\n    from .vllm_v_0_3_1.llm import LLM\n    from .vllm_v_0_3_1.llm import LLMEngine\n    from .vllm_v_0_3_1 import parallel_state\nelif package_version == '0.4.2':\n    vllm_version = '0.4.2'\n    from .vllm_v_0_4_2.llm import LLM\n    from .vllm_v_0_4_2.llm import LLMEngine\n    from .vllm_v_0_4_2 import parallel_state\nelif package_version == '0.5.4':\n    vllm_version = '0.5.4'\n    from .vllm_v_0_5_4.llm import LLM\n    from .vllm_v_0_5_4.llm import LLMEngine\n    from .vllm_v_0_5_4 import parallel_state\nelif package_version == '0.6.3':\n    vllm_version = '0.6.3'\n    from .vllm_v_0_6_3.llm import LLM\n    from .vllm_v_0_6_3.llm import LLMEngine\n    from .vllm_v_0_6_3 import parallel_state\nelif vs.parse(package_version) >= vs.parse('0.6.6.post2.dev252+g8027a724'):\n    # From 0.6.6.post2 on, vllm supports SPMD inference\n    # See https://github.com/vllm-project/vllm/pull/12071\n\n    from vllm import LLM\n    from vllm.distributed import parallel_state\n    from .vllm_spmd.dtensor_weight_loaders import load_dtensor_weights\nelse:\n    raise ValueError(\n        f'vllm version {package_version} not supported. Currently supported versions are 0.3.1, 0.4.2, 0.5.4, 0.6.3 and 0.7.0+'\n    )\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_spmd/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_spmd/dtensor_weight_loaders.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader\n\nfrom typing import Dict\n\nimport torch.nn as nn\nfrom torch.distributed._tensor import DTensor\nfrom vllm.model_executor.model_loader.weight_utils import default_weight_loader\nfrom vllm.model_executor.models.utils import is_pp_missing_parameter\n\n\ndef gemma_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        for param_name, shard_name, shard_id in stacked_params_mapping:\n            if shard_name not in name:\n                continue\n            stacked_name = name.replace(shard_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if stacked_name.endswith(\".bias\") and stacked_name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[stacked_name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # lm_head is not used in vllm as it is tied with embed_token.\n            # To prevent errors, skip loading lm_head.weight.\n            if \"lm_head.weight\" in name:\n                continue\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef gptbigcode_dtensor_load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"lm_head.weight\" in name:\n            continue\n        if \".attn.bias\" in name:\n            # Skip attention mask.\n            # NOTE: \"c_attn.bias\" should not be skipped.\n            continue\n        local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n        param = params_dict[name]\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef starcoder2_dtensor_load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n    ]\n\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef llama_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\".qkv_proj\", \".q_proj\", \"q\"),\n        (\".qkv_proj\", \".k_proj\", \"k\"),\n        (\".qkv_proj\", \".v_proj\", \"v\"),\n        (\".gate_up_proj\", \".gate_proj\", 0),\n        (\".gate_up_proj\", \".up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if \"rotary_emb.cos_cached\" in name or \"rotary_emb.sin_cached\" in name:\n            # Models trained using ColossalAI may include these tensors in\n            # the checkpoint. Skip them.\n            continue\n        # With tie_word_embeddings, we can skip lm_head.weight\n        # The weight might appear unnecessarily in the files if the model is\n        # processed with quantization, LoRA, fine-tuning, etc.\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight)\n\n\ndef qwen2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef qwen2vl_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n\n            if \"visual\" in name:\n                continue\n\n            name = \"language_model.\" + name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            if \"visual\" in name:\n                name = name\n            else:\n                name = \"language_model.\" + name\n\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\nfrom vllm.model_executor.layers.fused_moe import FusedMoE\n\n\ndef deepseekv2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n\n    # Params for weights, fp8 weight scales, fp8 activation scales\n    # (param_name, weight_name, expert_id, shard_id)\n    expert_params_mapping = FusedMoE.make_expert_params_mapping(\n        ckpt_gate_proj_name=\"gate_proj\",\n        ckpt_down_proj_name=\"down_proj\",\n        ckpt_up_proj_name=\"up_proj\",\n        num_experts=vllm_model.config.n_routed_experts,\n    )\n\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            # Skip non-stacked layers and experts (experts handled below).\n            if weight_name not in name:\n                continue\n            # We have mlp.experts[0].gate_proj in the checkpoint.\n            # Since we handle the experts below in expert_params_mapping,\n            # we need to skip here BEFORE we update the name, otherwise\n            # name will be updated to mlp.experts[0].gate_up_proj, which\n            # will then be updated below in expert_params_mapping\n            # for mlp.experts[0].gate_gate_up_proj, which breaks load.\n            if (\"mlp.experts.\" in name) and name not in params_dict:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n\n            if is_pp_missing_parameter(name, vllm_model):\n                continue\n\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            for mapping in expert_params_mapping:\n                param_name, weight_name, expert_id, shard_id = mapping\n                if weight_name not in name:\n                    continue\n                name = name.replace(weight_name, param_name)\n\n                if is_pp_missing_parameter(name, vllm_model):\n                    continue\n\n                param = params_dict[name]\n                local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(\n                    param,\n                    local_loaded_weight.to(dtype=param.dtype),\n                    weight_name,\n                    shard_id=shard_id,\n                    expert_id=expert_id,\n                )\n                break\n            else:\n                # Skip loading extra bias for GPTQ models.\n                if name.endswith(\".bias\") and name not in params_dict:\n                    continue\n\n                if is_pp_missing_parameter(name, vllm_model):\n                    continue\n\n                param = params_dict[name]\n                local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef gpt2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    pass\n\n\ndef redistribute_dtensor(param_name: str, loaded_weights: DTensor, parallelize_plan: Dict = None):\n    param_name = _process_parameter_names(name=param_name)\n    if parallelize_plan is not None:\n        assert (\n            param_name\n            in parallelize_plan.keys()), f\"param name: {param_name} not in parallelize_plan :{parallelize_plan.keys()}\"\n        placement = parallelize_plan[param_name]\n        local_loaded_weights = loaded_weights.redistribute(device_mesh=loaded_weights.device_mesh,\n                                                           placements=placement).to_local()\n    else:\n        local_loaded_weights = loaded_weights.full_tensor()\n    return local_loaded_weights\n\n\ndef _process_parameter_names(name):\n    # Remove '.weight' if it exists at the end of the string\n    if name.endswith(\".weight\"):\n        name = name[:-7]\n\n    # Remove 'model.layers.x.' or 'model.' prefix\n    if \"model.layers\" in name:\n        parts = name.split(\".\")\n        # Reconstruct the string without 'model.layers.x.'\n        name = \".\".join(parts[3:])  # parts[0] is 'model', parts[1] is 'layers', parts[2] is 'x'\n    elif name.startswith(\"model.\"):\n        name = name[6:]  # Remove 'model.'\n\n    return name\n\n\n__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__ = {\n    \"GPT2LMHeadModel\": gpt2_dtensor_weight_loader,\n    \"LlamaForCausalLM\": llama_dtensor_weight_loader,\n    \"LLaMAForCausalLM\": llama_dtensor_weight_loader,\n    \"MistralForCausalLM\": llama_dtensor_weight_loader,  # mistral is the same as llama in vLLM\n    \"InternLMForCausalLM\": llama_dtensor_weight_loader,\n    \"AquilaModel\": llama_dtensor_weight_loader,\n    \"AquilaForCausalLM\": llama_dtensor_weight_loader,\n    \"Phi3ForCausalLM\": llama_dtensor_weight_loader,\n    \"GemmaForCausalLM\": gemma_dtensor_weight_loader,\n    \"Gemma2ForCausalLM\": gemma_dtensor_weight_loader,\n    \"GPTBigCodeForCausalLM\": gptbigcode_dtensor_load_weights,\n    \"Starcoder2ForCausalLM\": starcoder2_dtensor_load_weights,\n    \"Qwen2ForCausalLM\": qwen2_dtensor_weight_loader,\n    \"DeepseekV2ForCausalLM\": deepseekv2_dtensor_weight_loader,\n    \"Qwen2VLForConditionalGeneration\": qwen2vl_dtensor_weight_loader,\n    \"Qwen2_5_VLForConditionalGeneration\": qwen2vl_dtensor_weight_loader,\n}\n\n\n# the actor model is .state_dict()\n# Load dtensor weights\ndef load_dtensor_weights(actor_weights: Dict, vllm_model: nn.Module):\n    weight_loader = _get_model_weight_loader(vllm_model.__class__.__name__)\n    weight_loader(actor_weights, vllm_model)\n    # NOTE(sgm) to reduce peak memory usage, we offload vllm model to cpu\n    # after init, and we need this after sync model weights for in first iter.\n    vllm_model = vllm_model.cuda()\n\n\ndef _get_model_weight_loader(arch: str):\n    if arch in __MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__:\n        return __MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__.keys()}\")\n\n\n# NOTE(sgm): we use per-parameter weight loader in each vllm sub\ndef update_dtensor_weight_loader():\n    pass\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/arg_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/arg_utils.py\nimport argparse\nimport dataclasses\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nimport torch.nn as nn\nfrom vllm.config import (CacheConfig, DeviceConfig, ModelConfig, ParallelConfig, SchedulerConfig, LoRAConfig)\nfrom transformers import PretrainedConfig\nfrom .config import ModelConfig\n\n\n@dataclass\nclass EngineArgs:\n    \"\"\"Arguments for vLLM engine.\"\"\"\n    model_hf_config: PretrainedConfig = None\n    dtype: str = 'auto'\n    kv_cache_dtype: str = 'auto'\n    seed: int = 0\n    max_model_len: Optional[int] = None\n    worker_use_ray: bool = False\n    pipeline_parallel_size: int = 1\n    tensor_parallel_size: int = 1\n    max_parallel_loading_workers: Optional[int] = None\n    block_size: int = 16\n    swap_space: int = 4  # GiB\n    gpu_memory_utilization: float = 0.90\n    max_num_batched_tokens: Optional[int] = None\n    max_num_seqs: int = 256\n    max_paddings: int = 256\n    disable_log_stats: bool = False\n    revision: Optional[str] = None\n    tokenizer_revision: Optional[str] = None\n    quantization: Optional[str] = None\n    load_format: str = 'model'\n    enforce_eager: bool = False\n    max_context_len_to_capture: int = 8192\n    disable_custom_all_reduce: bool = False\n    enable_lora: bool = False\n    max_loras: int = 1\n    max_lora_rank: int = 16\n    lora_extra_vocab_size: int = 256\n    lora_dtype = 'auto'\n    max_cpu_loras: Optional[int] = None\n    device: str = 'cuda'\n\n    @staticmethod\n    def add_cli_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n        \"\"\"Shared CLI arguments for vLLM engine.\"\"\"\n        # Model arguments\n        # TODO(shengguangming): delete the unused args\n        parser.add_argument('--model',\n                            type=str,\n                            default='facebook/opt-125m',\n                            help='name or path of the huggingface model to use')\n        parser.add_argument('--tokenizer',\n                            type=str,\n                            default=EngineArgs.tokenizer,\n                            help='name or path of the huggingface tokenizer to use')\n        parser.add_argument('--revision',\n                            type=str,\n                            default=None,\n                            help='the specific model version to use. It can be a branch '\n                            'name, a tag name, or a commit id. If unspecified, will use '\n                            'the default version.')\n        parser.add_argument('--tokenizer-revision',\n                            type=str,\n                            default=None,\n                            help='the specific tokenizer version to use. It can be a branch '\n                            'name, a tag name, or a commit id. If unspecified, will use '\n                            'the default version.')\n        parser.add_argument('--tokenizer-mode',\n                            type=str,\n                            default=EngineArgs.tokenizer_mode,\n                            choices=['auto', 'slow'],\n                            help='tokenizer mode. \"auto\" will use the fast '\n                            'tokenizer if available, and \"slow\" will '\n                            'always use the slow tokenizer.')\n        parser.add_argument('--trust-remote-code', action='store_true', help='trust remote code from huggingface')\n        parser.add_argument('--download-dir',\n                            type=str,\n                            default=EngineArgs.download_dir,\n                            help='directory to download and load the weights, '\n                            'default to the default cache dir of '\n                            'huggingface')\n        parser.add_argument('--load-format',\n                            type=str,\n                            default=EngineArgs.load_format,\n                            choices=['auto', 'pt', 'safetensors', 'npcache', 'dummy'],\n                            help='The format of the model weights to load. '\n                            '\"auto\" will try to load the weights in the safetensors format '\n                            'and fall back to the pytorch bin format if safetensors format '\n                            'is not available. '\n                            '\"pt\" will load the weights in the pytorch bin format. '\n                            '\"safetensors\" will load the weights in the safetensors format. '\n                            '\"npcache\" will load the weights in pytorch format and store '\n                            'a numpy cache to speed up the loading. '\n                            '\"dummy\" will initialize the weights with random values, '\n                            'which is mainly for profiling.')\n        parser.add_argument('--dtype',\n                            type=str,\n                            default=EngineArgs.dtype,\n                            choices=['auto', 'half', 'float16', 'bfloat16', 'float', 'float32'],\n                            help='data type for model weights and activations. '\n                            'The \"auto\" option will use FP16 precision '\n                            'for FP32 and FP16 models, and BF16 precision '\n                            'for BF16 models.')\n        parser.add_argument('--max-model-len',\n                            type=int,\n                            default=None,\n                            help='model context length. If unspecified, '\n                            'will be automatically derived from the model.')\n        # Parallel arguments\n        parser.add_argument('--worker-use-ray',\n                            action='store_true',\n                            help='use Ray for distributed serving, will be '\n                            'automatically set when using more than 1 GPU')\n        parser.add_argument('--pipeline-parallel-size',\n                            '-pp',\n                            type=int,\n                            default=EngineArgs.pipeline_parallel_size,\n                            help='number of pipeline stages')\n        parser.add_argument('--tensor-parallel-size',\n                            '-tp',\n                            type=int,\n                            default=EngineArgs.tensor_parallel_size,\n                            help='number of tensor parallel replicas')\n        # KV cache arguments\n        parser.add_argument('--block-size',\n                            type=int,\n                            default=EngineArgs.block_size,\n                            choices=[8, 16, 32],\n                            help='token block size')\n        # TODO(woosuk): Support fine-grained seeds (e.g., seed per request).\n        parser.add_argument('--seed', type=int, default=EngineArgs.seed, help='random seed')\n        parser.add_argument('--swap-space',\n                            type=int,\n                            default=EngineArgs.swap_space,\n                            help='CPU swap space size (GiB) per GPU')\n        parser.add_argument('--gpu-memory-utilization',\n                            type=float,\n                            default=EngineArgs.gpu_memory_utilization,\n                            help='the percentage of GPU memory to be used for'\n                            'the model executor')\n        parser.add_argument('--max-num-batched-tokens',\n                            type=int,\n                            default=EngineArgs.max_num_batched_tokens,\n                            help='maximum number of batched tokens per '\n                            'iteration')\n        parser.add_argument('--max-num-seqs',\n                            type=int,\n                            default=EngineArgs.max_num_seqs,\n                            help='maximum number of sequences per iteration')\n        parser.add_argument('--disable-log-stats', action='store_true', help='disable logging statistics')\n        # Quantization settings.\n        parser.add_argument('--quantization',\n                            '-q',\n                            type=str,\n                            choices=['awq', None],\n                            default=None,\n                            help='Method used to quantize the weights')\n        return parser\n\n    @classmethod\n    def from_cli_args(cls, args: argparse.Namespace) -> 'EngineArgs':\n        # Get the list of attributes of this dataclass.\n        attrs = [attr.name for attr in dataclasses.fields(cls)]\n        # Set the attributes from the parsed arguments.\n        engine_args = cls(**{attr: getattr(args, attr) for attr in attrs})\n        return engine_args\n\n    def create_engine_configs(\n        self,\n    ) -> Tuple[ModelConfig, CacheConfig, ParallelConfig, SchedulerConfig]:\n        device_config = DeviceConfig(self.device)\n        model_config = ModelConfig(self.model_hf_config, self.dtype, self.seed, self.load_format, self.revision,\n                                   self.tokenizer_revision, self.max_model_len, self.quantization, self.enforce_eager,\n                                   self.max_context_len_to_capture)\n        cache_config = CacheConfig(self.block_size, self.gpu_memory_utilization, self.swap_space, self.kv_cache_dtype,\n                                   model_config.get_sliding_window())\n        parallel_config = ParallelConfig(self.pipeline_parallel_size, self.tensor_parallel_size, self.worker_use_ray,\n                                         self.max_parallel_loading_workers, self.disable_custom_all_reduce)\n        scheduler_config = SchedulerConfig(self.max_num_batched_tokens, self.max_num_seqs, model_config.max_model_len,\n                                           self.max_paddings)\n        lora_config = LoRAConfig(max_lora_rank=self.max_lora_rank,\n                                 max_loras=self.max_loras,\n                                 lora_extra_vocab_size=self.lora_extra_vocab_size,\n                                 lora_dtype=self.lora_dtype,\n                                 max_cpu_loras=self.max_cpu_loras if self.max_cpu_loras and self.max_cpu_loras > 0 else\n                                 None) if self.enable_lora else None\n        return (model_config, cache_config, parallel_config, scheduler_config, device_config, lora_config)\n\n\n@dataclass\nclass AsyncEngineArgs(EngineArgs):\n    \"\"\"Arguments for asynchronous vLLM engine.\"\"\"\n    engine_use_ray: bool = False\n    disable_log_requests: bool = False\n    max_log_len: Optional[int] = None\n\n    @staticmethod\n    def add_cli_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n        parser = EngineArgs.add_cli_args(parser)\n        parser.add_argument('--engine-use-ray',\n                            action='store_true',\n                            help='use Ray to start the LLM engine in a '\n                            'separate process as the server process.')\n        parser.add_argument('--disable-log-requests', action='store_true', help='disable logging requests')\n        parser.add_argument('--max-log-len',\n                            type=int,\n                            default=None,\n                            help='max number of prompt characters or prompt '\n                            'ID numbers being printed in log. '\n                            'Default: unlimited.')\n        return parser\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/config.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/config.py\n\nfrom typing import Optional, Union, ClassVar\nfrom dataclasses import dataclass\nimport torch\nfrom transformers import PretrainedConfig\nfrom packaging.version import Version\n\nfrom vllm.logger import init_logger\nfrom vllm.transformers_utils.config import get_config\nfrom vllm.utils import get_cpu_memory, is_hip, get_nvcc_cuda_version\n\nlogger = init_logger(__name__)\n\n_GB = 1 << 30\n\n\nclass ModelConfig:\n    \"\"\"Configuration for the model.\n\n    Args:\n        model: Name or path of the huggingface model to use.\n        tokenizer: Name or path of the huggingface tokenizer to use.\n        tokenizer_mode: Tokenizer mode. \"auto\" will use the fast tokenizer if\n            available, and \"slow\" will always use the slow tokenizer.\n        trust_remote_code: Trust remote code (e.g., from HuggingFace) when\n            downloading the model and tokenizer.\n        download_dir: Directory to download and load the weights, default to the\n            default cache directory of huggingface.\n        load_format: The format of the model weights to load:\n            \"auto\" will try to load the weights in the safetensors format and\n                fall back to the pytorch bin format if safetensors format is\n                not available.\n            \"pt\" will load the weights in the pytorch bin format.\n            \"safetensors\" will load the weights in the safetensors format.\n            \"npcache\" will load the weights in pytorch format and store\n                a numpy cache to speed up the loading.\n            \"dummy\" will initialize the weights with random values, which is\n                mainly for profiling.\n        dtype: Data type for model weights and activations. The \"auto\" option\n            will use FP16 precision for FP32 and FP16 models, and BF16 precision\n            for BF16 models.\n        seed: Random seed for reproducibility.\n        revision: The specific model version to use. It can be a branch name,\n            a tag name, or a commit id. If unspecified, will use the default\n            version.\n        tokenizer_revision: The specific tokenizer version to use. It can be a\n            branch name, a tag name, or a commit id. If unspecified, will use\n            the default version.\n        max_model_len: Maximum length of a sequence (including prompt and\n            output). If None, will be derived from the model.\n        quantization: Quantization method that was used to quantize the model\n            weights. If None, we assume the model weights are not quantized.\n        enforce_eager: Whether to enforce eager execution. If True, we will\n            disable CUDA graph and always execute the model in eager mode.\n            If False, we will use CUDA graph and eager execution in hybrid.\n        max_context_len_to_capture: Maximum context len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode.\n    \"\"\"\n\n    def __init__(\n        self,\n        hf_config: PretrainedConfig,\n        dtype: str,\n        seed: int,\n        load_format: str = 'model',\n        revision: Optional[str] = None,\n        tokenizer_revision: Optional[str] = None,\n        max_model_len: Optional[int] = None,\n        quantization: Optional[str] = None,\n        trust_remote_code: Optional[bool] = True,\n        enforce_eager: bool = False,\n        max_context_len_to_capture: Optional[int] = None,\n    ) -> None:\n        self.model = hf_config._name_or_path\n        self.tokenizer = hf_config._name_or_path\n        self.load_format = load_format\n        self.seed = seed\n        self.revision = revision\n        self.tokenizer_revision = tokenizer_revision\n        self.quantization = quantization\n        self.trust_remote_code = trust_remote_code\n        self.enforce_eager = enforce_eager\n        self.max_context_len_to_capture = max_context_len_to_capture\n\n        # self.hf_config = get_config(model, trust_remote_code, revision)\n        self.hf_config = hf_config\n        self.dtype = _get_and_verify_dtype(self.hf_config, dtype)\n        self.max_model_len = _get_and_verify_max_len(self.hf_config, max_model_len)\n        # self._verify_load_format()\n        # self._verify_tokenizer_mode()\n        self._verify_quantization()\n        self._verify_cuda_graph()\n\n    def _verify_load_format(self) -> None:\n        load_format = self.load_format.lower()\n        if load_format not in [\"auto\", \"pt\", \"safetensors\", \"npcache\", \"dummy\", \"model\"]:\n            raise ValueError(f\"Unknown load format: {self.load_format}. Must be one of \"\n                             \"'auto', 'pt', 'safetensors', 'npcache', 'dummy' or 'model'.\")\n        self.load_format = load_format\n\n    # def _verify_tokenizer_mode(self) -> None:\n    #     tokenizer_mode = self.tokenizer_mode.lower()\n    #     if tokenizer_mode not in [\"auto\", \"slow\"]:\n    #         raise ValueError(\n    #             f\"Unknown tokenizer mode: {self.tokenizer_mode}. Must be \"\n    #             \"either 'auto' or 'slow'.\")\n    #     self.tokenizer_mode = tokenizer_mode\n\n    def _verify_quantization(self) -> None:\n        supported_quantization = [\"awq\", \"gptq\", \"squeezellm\"]\n        rocm_not_supported_quantization = [\"awq\", \"gptq\"]\n        if self.quantization is not None:\n            self.quantization = self.quantization.lower()\n\n        # Parse quantization method from the HF model config, if available.\n        hf_quant_config = getattr(self.hf_config, \"quantization_config\", None)\n        if hf_quant_config is not None:\n            hf_quant_method = str(hf_quant_config[\"quant_method\"]).lower()\n            if self.quantization is None:\n                self.quantization = hf_quant_method\n            elif self.quantization != hf_quant_method:\n                raise ValueError(\"Quantization method specified in the model config \"\n                                 f\"({hf_quant_method}) does not match the quantization \"\n                                 f\"method specified in the `quantization` argument \"\n                                 f\"({self.quantization}).\")\n\n        if self.quantization is not None:\n            if self.quantization not in supported_quantization:\n                raise ValueError(f\"Unknown quantization method: {self.quantization}. Must \"\n                                 f\"be one of {supported_quantization}.\")\n            if is_hip() and self.quantization in rocm_not_supported_quantization:\n                raise ValueError(f\"{self.quantization} quantization is currently not supported \"\n                                 f\"in ROCm.\")\n            logger.warning(f\"{self.quantization} quantization is not fully \"\n                           \"optimized yet. The speed can be slower than \"\n                           \"non-quantized models.\")\n\n    def _verify_cuda_graph(self) -> None:\n        if self.max_context_len_to_capture is None:\n            self.max_context_len_to_capture = self.max_model_len\n        self.max_context_len_to_capture = min(self.max_context_len_to_capture, self.max_model_len)\n        if (self.quantization in [\"gptq\", \"squeezellm\"] and not self.enforce_eager):\n            # Related issue: https://github.com/vllm-project/vllm/issues/2147\n            logger.warning(f\"{self.quantization} does not support CUDA graph \"\n                           \"yet. Disabling CUDA graph.\")\n            self.enforce_eager = True\n\n    def verify_with_parallel_config(\n        self,\n        parallel_config: \"ParallelConfig\",\n    ) -> None:\n        total_num_attention_heads = self.hf_config.num_attention_heads\n        tensor_parallel_size = parallel_config.tensor_parallel_size\n        if total_num_attention_heads % tensor_parallel_size != 0:\n            raise ValueError(f\"Total number of attention heads ({total_num_attention_heads})\"\n                             \" must be divisible by tensor parallel size \"\n                             f\"({tensor_parallel_size}).\")\n\n        total_num_hidden_layers = self.hf_config.num_hidden_layers\n        pipeline_parallel_size = parallel_config.pipeline_parallel_size\n        if total_num_hidden_layers % pipeline_parallel_size != 0:\n            raise ValueError(f\"Total number of hidden layers ({total_num_hidden_layers}) \"\n                             \"must be divisible by pipeline parallel size \"\n                             f\"({pipeline_parallel_size}).\")\n\n    def get_sliding_window(self) -> Optional[int]:\n        return getattr(self.hf_config, \"sliding_window\", None)\n\n    def get_vocab_size(self) -> int:\n        return self.hf_config.vocab_size\n\n    def get_hidden_size(self) -> int:\n        return self.hf_config.hidden_size\n\n    def get_head_size(self) -> int:\n        # FIXME(woosuk): This may not be true for all models.\n        return self.hf_config.hidden_size // self.hf_config.num_attention_heads\n\n    def get_total_num_kv_heads(self) -> int:\n        \"\"\"Returns the total number of KV heads.\"\"\"\n        # For GPTBigCode & Falcon:\n        # NOTE: for falcon, when new_decoder_architecture is True, the\n        # multi_query flag is ignored and we use n_head_kv for the number of\n        # KV heads.\n        falcon_model_types = [\"falcon\", \"RefinedWeb\", \"RefinedWebModel\"]\n        new_decoder_arch_falcon = (self.hf_config.model_type in falcon_model_types and\n                                   getattr(self.hf_config, \"new_decoder_architecture\", False))\n        if not new_decoder_arch_falcon and getattr(self.hf_config, \"multi_query\", False):\n            # Multi-query attention, only one KV head.\n            # Currently, tensor parallelism is not supported in this case.\n            return 1\n\n        attributes = [\n            # For Falcon:\n            \"n_head_kv\",\n            \"num_kv_heads\",\n            # For LLaMA-2:\n            \"num_key_value_heads\",\n            # For ChatGLM:\n            \"multi_query_group_num\",\n        ]\n        for attr in attributes:\n            num_kv_heads = getattr(self.hf_config, attr, None)\n            if num_kv_heads is not None:\n                return num_kv_heads\n\n        # For non-grouped-query attention models, the number of KV heads is\n        # equal to the number of attention heads.\n        return self.hf_config.num_attention_heads\n\n    def get_num_kv_heads(self, parallel_config: \"ParallelConfig\") -> int:\n        \"\"\"Returns the number of KV heads per GPU.\"\"\"\n        total_num_kv_heads = self.get_total_num_kv_heads()\n        # If tensor parallelism is used, we divide the number of KV heads by\n        # the tensor parallel size. We will replicate the KV heads in the\n        # case where the number of KV heads is smaller than the tensor\n        # parallel size so each GPU has at least one KV head.\n        return max(1, total_num_kv_heads // parallel_config.tensor_parallel_size)\n\n    def get_num_layers(self, parallel_config: \"ParallelConfig\") -> int:\n        total_num_hidden_layers = self.hf_config.num_hidden_layers\n        return total_num_hidden_layers // parallel_config.pipeline_parallel_size\n\n\nclass CacheConfig:\n    \"\"\"Configuration for the KV cache.\n\n    Args:\n        block_size: Size of a cache block in number of tokens.\n        gpu_memory_utilization: Fraction of GPU memory to use for the\n            vLLM execution.\n        swap_space: Size of the CPU swap space per GPU (in GiB).\n        cache_dtype: Data type for kv cache storage.\n    \"\"\"\n\n    def __init__(\n        self,\n        block_size: int,\n        gpu_memory_utilization: float,\n        swap_space: int,\n        cache_dtype: str,\n        sliding_window: Optional[int] = None,\n    ) -> None:\n        self.block_size = block_size\n        self.gpu_memory_utilization = gpu_memory_utilization\n        self.swap_space_bytes = swap_space * _GB\n        self.cache_dtype = cache_dtype\n        self.sliding_window = sliding_window\n        self._verify_args()\n        self._verify_cache_dtype()\n\n        # Will be set after profiling.\n        self.num_gpu_blocks = None\n        self.num_cpu_blocks = None\n\n    def _verify_args(self) -> None:\n        if self.gpu_memory_utilization > 1.0:\n            raise ValueError(\"GPU memory utilization must be less than 1.0. Got \"\n                             f\"{self.gpu_memory_utilization}.\")\n\n    def _verify_cache_dtype(self) -> None:\n        if self.cache_dtype == \"auto\":\n            pass\n        elif self.cache_dtype == \"fp8_e5m2\":\n            nvcc_cuda_version = get_nvcc_cuda_version()\n            if nvcc_cuda_version < Version(\"11.8\"):\n                raise ValueError(\"FP8 is not supported when cuda version is lower than 11.8.\")\n            device_name = torch.cuda.get_device_name()\n            if \"AMD\" in device_name:\n                raise NotImplementedError(\"FP8_E5M2 KV Cache on AMD GPU has not been supported yet.\")\n            logger.info(\"Using fp8_e5m2 data type to store kv cache. It reduces \"\n                        \"the GPU memory footprint and boosts the performance. \"\n                        \"But it may cause slight accuracy drop. \"\n                        \"Currently we only support fp8 without scaling factors and \"\n                        \"make e5m2 as a default format.\")\n        else:\n            raise ValueError(f\"Unknown kv cache dtype: {self.cache_dtype}\")\n\n    def verify_with_parallel_config(\n        self,\n        parallel_config: \"ParallelConfig\",\n    ) -> None:\n        total_cpu_memory = get_cpu_memory()\n        # FIXME(woosuk): Here, it is assumed that the GPUs in a tensor parallel\n        # group are in the same node. However, the GPUs may span multiple nodes.\n        num_gpus_per_node = parallel_config.tensor_parallel_size\n        cpu_memory_usage = self.swap_space_bytes * num_gpus_per_node\n\n        msg = (f\"{cpu_memory_usage / _GB:.2f} GiB out of \"\n               f\"the {total_cpu_memory / _GB:.2f} GiB total CPU memory is \"\n               \"allocated for the swap space.\")\n        if cpu_memory_usage > 0.7 * total_cpu_memory:\n            raise ValueError(\"Too large swap space. \" + msg)\n        elif cpu_memory_usage > 0.4 * total_cpu_memory:\n            logger.warning(\"Possibly too large swap space. \" + msg)\n\n\nclass ParallelConfig:\n    \"\"\"Configuration for the distributed execution.\n\n    Args:\n        pipeline_parallel_size: Number of pipeline parallel groups.\n        tensor_parallel_size: Number of tensor parallel groups.\n        worker_use_ray: Whether to use Ray for model workers. Will be set to\n            True if either pipeline_parallel_size or tensor_parallel_size is\n            greater than 1.\n        max_parallel_loading_workers: Maximum number of multiple batches\n            when load model sequentially. To avoid RAM OOM when using tensor\n            parallel and large models.\n        disable_custom_all_reduce: Disable the custom all-reduce kernel and\n            fall back to NCCL.\n    \"\"\"\n\n    def __init__(\n        self,\n        pipeline_parallel_size: int,\n        tensor_parallel_size: int,\n        worker_use_ray: bool,\n        max_parallel_loading_workers: Optional[int] = None,\n        disable_custom_all_reduce: bool = False,\n    ) -> None:\n        self.pipeline_parallel_size = pipeline_parallel_size\n        self.tensor_parallel_size = tensor_parallel_size\n        self.worker_use_ray = worker_use_ray\n        self.max_parallel_loading_workers = max_parallel_loading_workers\n        self.disable_custom_all_reduce = disable_custom_all_reduce\n\n        self.world_size = pipeline_parallel_size * tensor_parallel_size\n        if self.world_size > 1:\n            self.worker_use_ray = True\n        self._verify_args()\n\n    def _verify_args(self) -> None:\n        if self.pipeline_parallel_size > 1:\n            raise NotImplementedError(\"Pipeline parallelism is not supported yet.\")\n        if not self.disable_custom_all_reduce and self.world_size > 1:\n            if is_hip():\n                self.disable_custom_all_reduce = True\n                logger.info(\"Disabled the custom all-reduce kernel because it is not \"\n                            \"supported on AMD GPUs.\")\n            elif self.pipeline_parallel_size > 1:\n                self.disable_custom_all_reduce = True\n                logger.info(\"Disabled the custom all-reduce kernel because it is not \"\n                            \"supported with pipeline parallelism.\")\n\n        # FIXME(woosuk): Fix the stability issues and re-enable the custom\n        # all-reduce kernel.\n        if not self.disable_custom_all_reduce and self.world_size > 1:\n            self.disable_custom_all_reduce = True\n            logger.info(\"Custom all-reduce kernels are temporarily disabled due to \"\n                        \"stability issues. We will re-enable them once the issues are \"\n                        \"resolved.\")\n\n\nclass SchedulerConfig:\n    \"\"\"Scheduler configuration.\n\n    Args:\n        max_num_batched_tokens: Maximum number of tokens to be processed in\n            a single iteration.\n        max_num_seqs: Maximum number of sequences to be processed in a single\n            iteration.\n        max_model_len: Maximum length of a sequence (including prompt\n            and generated text).\n        max_paddings: Maximum number of paddings to be added to a batch.\n    \"\"\"\n\n    def __init__(\n        self,\n        max_num_batched_tokens: Optional[int],\n        max_num_seqs: int,\n        max_model_len: int,\n        max_paddings: int,\n    ) -> None:\n        if max_num_batched_tokens is not None:\n            self.max_num_batched_tokens = max_num_batched_tokens\n        else:\n            # If max_model_len is too short, use 2048 as the default value for\n            # higher throughput.\n            self.max_num_batched_tokens = max(max_model_len, 2048)\n        self.max_num_seqs = max_num_seqs\n        self.max_model_len = max_model_len\n        self.max_paddings = max_paddings\n        self._verify_args()\n\n    def _verify_args(self) -> None:\n        if self.max_num_batched_tokens < self.max_model_len:\n            raise ValueError(f\"max_num_batched_tokens ({self.max_num_batched_tokens}) is \"\n                             f\"smaller than max_model_len ({self.max_model_len}). \"\n                             \"This effectively limits the maximum sequence length to \"\n                             \"max_num_batched_tokens and makes vLLM reject longer \"\n                             \"sequences. Please increase max_num_batched_tokens or \"\n                             \"decrease max_model_len.\")\n        if self.max_num_batched_tokens < self.max_num_seqs:\n            raise ValueError(f\"max_num_batched_tokens ({self.max_num_batched_tokens}) must \"\n                             \"be greater than or equal to max_num_seqs \"\n                             f\"({self.max_num_seqs}).\")\n\n\nclass DeviceConfig:\n\n    def __init__(self, device: str = \"cuda\") -> None:\n        self.device = torch.device(device)\n\n\n@dataclass\nclass LoRAConfig:\n    max_lora_rank: int\n    max_loras: int\n    max_cpu_loras: Optional[int] = None\n    lora_dtype: Optional[torch.dtype] = None\n    lora_extra_vocab_size: int = 256\n    # This is a constant.\n    lora_vocab_padding_size: ClassVar[int] = 256\n\n    def __post_init__(self):\n        # Keep this in sync with csrc/punica/bgmv/bgmv_config.h\n        possible_max_ranks = (8, 16, 32, 64)\n        possible_lora_extra_vocab_size = (0, 256, 512)\n        if self.max_lora_rank not in possible_max_ranks:\n            raise ValueError(f\"max_lora_rank ({self.max_lora_rank}) must be one of \"\n                             f\"{possible_max_ranks}.\")\n        if self.lora_extra_vocab_size not in possible_lora_extra_vocab_size:\n            raise ValueError(f\"lora_extra_vocab_size ({self.lora_extra_vocab_size}) \"\n                             f\"must be one of {possible_lora_extra_vocab_size}.\")\n        if self.max_loras < 1:\n            raise ValueError(f\"max_loras ({self.max_loras}) must be >= 1.\")\n        if self.max_cpu_loras is None:\n            self.max_cpu_loras = self.max_loras\n        elif self.max_cpu_loras < self.max_loras:\n            raise ValueError(f\"max_cpu_loras ({self.max_cpu_loras}) must be >= \"\n                             f\"max_loras ({self.max_loras})\")\n\n    def verify_with_model_config(self, model_config: ModelConfig):\n        if self.lora_dtype in (None, \"auto\"):\n            self.lora_dtype = model_config.dtype\n        elif isinstance(self.lora_dtype, str):\n            self.lora_dtype = getattr(torch, self.lora_dtype)\n        if model_config.quantization is not None:\n            raise ValueError(\"LoRA is not supported with quantized models yet.\")\n\n    def verify_with_scheduler_config(self, scheduler_config: SchedulerConfig):\n        if scheduler_config.max_num_batched_tokens > 65528:\n            raise ValueError(\"Due to limitations of the custom LoRA CUDA kernel, \"\n                             \"max_num_batched_tokens must be <= 65528 when \"\n                             \"LoRA is enabled.\")\n\n\n_STR_DTYPE_TO_TORCH_DTYPE = {\n    \"half\": torch.float16,\n    \"float16\": torch.float16,\n    \"float\": torch.float32,\n    \"float32\": torch.float32,\n    \"bfloat16\": torch.bfloat16,\n}\n\n_ROCM_NOT_SUPPORTED_DTYPE = [\"float\", \"float32\"]\n\n\ndef _get_and_verify_dtype(\n    config: PretrainedConfig,\n    dtype: Union[str, torch.dtype],\n) -> torch.dtype:\n    # NOTE: getattr(config, \"torch_dtype\", torch.float32) is not correct\n    # because config.torch_dtype can be None.\n    config_dtype = getattr(config, \"torch_dtype\", None)\n    if config_dtype is None:\n        config_dtype = torch.float32\n\n    if isinstance(dtype, str):\n        dtype = dtype.lower()\n        if dtype == \"auto\":\n            if config_dtype == torch.float32:\n                # Following the common practice, we use float16 for float32\n                # models.\n                torch_dtype = torch.float16\n            else:\n                torch_dtype = config_dtype\n        else:\n            if dtype not in _STR_DTYPE_TO_TORCH_DTYPE:\n                raise ValueError(f\"Unknown dtype: {dtype}\")\n            torch_dtype = _STR_DTYPE_TO_TORCH_DTYPE[dtype]\n    elif isinstance(dtype, torch.dtype):\n        torch_dtype = dtype\n    else:\n        raise ValueError(f\"Unknown dtype: {dtype}\")\n\n    if is_hip() and torch_dtype == torch.float32:\n        rocm_supported_dtypes = [\n            k for k, v in _STR_DTYPE_TO_TORCH_DTYPE.items() if (k not in _ROCM_NOT_SUPPORTED_DTYPE)\n        ]\n        raise ValueError(f\"dtype \\'{dtype}\\' is not supported in ROCm. \"\n                         f\"Supported dtypes are {rocm_supported_dtypes}\")\n\n    # Verify the dtype.\n    if torch_dtype != config_dtype:\n        if torch_dtype == torch.float32:\n            # Upcasting to float32 is allowed.\n            pass\n        elif config_dtype == torch.float32:\n            # Downcasting from float32 to float16 or bfloat16 is allowed.\n            pass\n        else:\n            # Casting between float16 and bfloat16 is allowed with a warning.\n            logger.warning(f\"Casting {config_dtype} to {torch_dtype}.\")\n\n    return torch_dtype\n\n\ndef _get_and_verify_max_len(\n    hf_config: PretrainedConfig,\n    max_model_len: Optional[int],\n) -> int:\n    \"\"\"Get and verify the model's maximum length.\"\"\"\n    derived_max_model_len = float(\"inf\")\n    possible_keys = [\n        # OPT\n        \"max_position_embeddings\",\n        # GPT-2\n        \"n_positions\",\n        # MPT\n        \"max_seq_len\",\n        # ChatGLM2\n        \"seq_length\",\n        # Others\n        \"max_sequence_length\",\n        \"max_seq_length\",\n        \"seq_len\",\n    ]\n    for key in possible_keys:\n        max_len_key = getattr(hf_config, key, None)\n        if max_len_key is not None:\n            derived_max_model_len = min(derived_max_model_len, max_len_key)\n    if derived_max_model_len == float(\"inf\"):\n        if max_model_len is not None:\n            # If max_model_len is specified, we use it.\n            return max_model_len\n\n        default_max_len = 2048\n        logger.warning(\"The model's config.json does not contain any of the following \"\n                       \"keys to determine the original maximum length of the model: \"\n                       f\"{possible_keys}. Assuming the model's maximum length is \"\n                       f\"{default_max_len}.\")\n        derived_max_model_len = default_max_len\n\n    rope_scaling = getattr(hf_config, \"rope_scaling\", None)\n    if rope_scaling is not None:\n        assert \"factor\" in rope_scaling\n        scaling_factor = rope_scaling[\"factor\"]\n        if rope_scaling[\"type\"] == \"yarn\":\n            derived_max_model_len = rope_scaling[\"original_max_position_embeddings\"]\n        derived_max_model_len *= scaling_factor\n\n    if max_model_len is None:\n        max_model_len = derived_max_model_len\n    elif max_model_len > derived_max_model_len:\n        raise ValueError(f\"User-specified max_model_len ({max_model_len}) is greater than \"\n                         f\"the derived max_model_len ({max_len_key}={derived_max_model_len}\"\n                         \" in model's config.json). This may lead to incorrect model \"\n                         \"outputs or CUDA errors. Make sure the value is correct and \"\n                         \"within the model context size.\")\n    return int(max_model_len)\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/llm.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/llm.py\n\nfrom typing import Dict, List, Optional, Tuple, Union\n\nfrom tqdm import tqdm\nfrom transformers import PreTrainedTokenizer, PreTrainedTokenizerFast\nfrom transformers import PretrainedConfig\nimport torch.nn as nn\nfrom .arg_utils import EngineArgs\nfrom .llm_engine_sp import LLMEngine\nfrom vllm.lora.request import LoRARequest\nfrom vllm.outputs import RequestOutput\nfrom vllm.sampling_params import SamplingParams\nfrom vllm.utils import Counter\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\nfrom verl.workers.rollout.tokenizer import HybridEngineBaseTokenizer\n\n\nclass LLM:\n    \"\"\"An LLM for generating texts from given prompts and sampling parameters.\n\n    This class includes a tokenizer, a language model (possibly distributed\n    across multiple GPUs), and GPU memory space allocated for intermediate\n    states (aka KV cache). Given a batch of prompts and sampling parameters,\n    this class generates texts from the model, using an intelligent batching\n    mechanism and efficient memory management.\n\n    NOTE: This class is intended to be used for offline inference. For online\n    serving, use the `AsyncLLMEngine` class instead.\n    NOTE: For the comprehensive list of arguments, see `EngineArgs`.\n\n    Args:\n        model: A HuggingFace Transformers model instance.\n        tokenizer: A HuggingFace Transformers tokenizer instance.\n        tokenizer_mode: The tokenizer mode. \"auto\" will use the fast tokenizer\n            if available, and \"slow\" will always use the slow tokenizer.\n        trust_remote_code: Trust remote code (e.g., from HuggingFace) when\n            downloading the model and tokenizer.\n        tensor_parallel_size: The number of GPUs to use for distributed\n            execution with tensor parallelism.\n        dtype: The data type for the model weights and activations. Currently,\n            we support `float32`, `float16`, and `bfloat16`. If `auto`, we use\n            the `torch_dtype` attribute specified in the model config file.\n            However, if the `torch_dtype` in the config is `float32`, we will\n            use `float16` instead.\n        quantization: The method used to quantize the model weights. Currently,\n            we support \"awq\". If None, we assume the model weights are not\n            quantized and use `dtype` to determine the data type of the weights.\n        revision: The specific model version to use. It can be a branch name,\n            a tag name, or a commit id.\n        tokenizer_revision: The specific tokenizer version to use. It can be a\n            branch name, a tag name, or a commit id.\n        seed: The seed to initialize the random number generator for sampling.\n        gpu_memory_utilization: The ratio (between 0 and 1) of GPU memory to\n            reserve for the model weights, activations, and KV cache. Higher\n            values will increase the KV cache size and thus improve the model's\n            throughput. However, if the value is too high, it may cause out-of-\n            memory (OOM) errors.\n        swap_space: The size (GiB) of CPU memory per GPU to use as swap space.\n            This can be used for temporarily storing the states of the requests\n            when their `best_of` sampling parameters are larger than 1. If all\n            requests will have `best_of=1`, you can safely set this to 0.\n            Otherwise, too small values may cause out-of-memory (OOM) errors.\n        enforce_eager: Whether to enforce eager execution. If True, we will\n            disable CUDA graph and always execute the model in eager mode.\n            If False, we will use CUDA graph and eager execution in hybrid.\n        max_context_len_to_capture: Maximum context len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode.\n        disable_custom_all_reduce: See ParallelConfig\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast, HybridEngineBaseTokenizer],\n        model_hf_config: PretrainedConfig,\n        tokenizer_mode: str = \"auto\",\n        trust_remote_code: bool = False,\n        tensor_parallel_size: int = 1,\n        dtype: str = \"auto\",\n        quantization: Optional[str] = None,\n        revision: Optional[str] = None,\n        tokenizer_revision: Optional[str] = None,\n        seed: int = 0,\n        gpu_memory_utilization: float = 0.9,\n        swap_space: int = 4,\n        enforce_eager: bool = False,\n        max_context_len_to_capture: int = 8192,\n        disable_custom_all_reduce: bool = False,\n        **kwargs,\n    ) -> None:\n        if \"disable_log_stats\" not in kwargs:\n            kwargs[\"disable_log_stats\"] = True\n        engine_args = EngineArgs(\n            model_hf_config=model_hf_config,\n            tensor_parallel_size=tensor_parallel_size,\n            dtype=dtype,\n            quantization=quantization,\n            revision=revision,\n            tokenizer_revision=tokenizer_revision,\n            seed=seed,\n            gpu_memory_utilization=gpu_memory_utilization,\n            swap_space=swap_space,\n            enforce_eager=enforce_eager,\n            max_context_len_to_capture=max_context_len_to_capture,\n            disable_custom_all_reduce=disable_custom_all_reduce,\n            **kwargs,\n        )\n        tokenizer_cls = (PreTrainedTokenizer, PreTrainedTokenizerFast, HybridEngineBaseTokenizer)\n        if not isinstance(tokenizer, tokenizer_cls):\n            raise ValueError(\n                f\"Unexpected tokenizer type: {type(tokenizer)}. Must be\"\n                \"one of the following: PreTrainedTokenizer, PreTrainedTokenizerFast, verl.workers.rollout.HybridEngineBaseTokenizer\"\n            )\n        self.llm_engine = LLMEngine.from_engine_args(model, tokenizer, engine_args)\n        self.request_counter = Counter()\n\n    def init_cache_engine(self):\n        self.llm_engine.init_cache_engine()\n\n    def free_cache_engine(self):\n        self.llm_engine.free_cache_engine()\n\n    def get_tokenizer(self) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:\n        return self.llm_engine.tokenizer\n\n    def set_tokenizer(\n        self,\n        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],\n    ) -> None:\n        self.llm_engine.tokenizer = tokenizer\n\n    def generate(\n        self,\n        prompts: Optional[Union[str, List[str]]] = None,\n        sampling_params: Optional[SamplingParams] = None,\n        prompt_token_ids: Optional[List[List[int]]] = None,\n        prefix_pos: Optional[Union[int, List[int]]] = None,\n        use_tqdm: bool = True,\n        lora_request: Optional[LoRARequest] = None,\n    ) -> List[RequestOutput]:\n        \"\"\"Generates the completions for the input prompts.\n\n        NOTE: This class automatically batches the given prompts, considering\n        the memory constraint. For the best performance, put all of your prompts\n        into a single list and pass it to this method.\n\n        Args:\n            prompts: A list of prompts to generate completions for.\n            sampling_params: The sampling parameters for text generation. If\n                None, we use the default sampling parameters.\n            prompt_token_ids: A list of token IDs for the prompts. If None, we\n                use the tokenizer to convert the prompts to token IDs.\n            use_tqdm: Whether to use tqdm to display the progress bar.\n\n        Returns:\n            A list of `RequestOutput` objects containing the generated\n            completions in the same order as the input prompts.\n        \"\"\"\n        if prompts is None and prompt_token_ids is None:\n            raise ValueError(\"Either prompts or prompt_token_ids must be \"\n                             \"provided.\")\n        if isinstance(prompts, str):\n            # Convert a single prompt to a list.\n            prompts = [prompts]\n        if prompts is not None and prompt_token_ids is not None:\n            if len(prompts) != len(prompt_token_ids):\n                raise ValueError(\"The lengths of prompts and prompt_token_ids \"\n                                 \"must be the same.\")\n        if sampling_params is None:\n            # Use default sampling params.\n            sampling_params = SamplingParams()\n\n        # Add requests to the engine.\n        num_requests = len(prompts) if prompts is not None else len(prompt_token_ids)\n        for i in range(num_requests):\n            prompt = prompts[i] if prompts is not None else None\n            prefix_pos_i = prefix_pos[i] if prefix_pos is not None else None\n            token_ids = None if prompt_token_ids is None else prompt_token_ids[i]\n            if not isinstance(token_ids, list):\n                # NOTE(shengguangming): convert the rollout input into List[str]\n                token_ids = self._pre_process_inputs(token_ids)\n            self._add_request(prompt, sampling_params, token_ids, lora_request=lora_request, prefix_pos=prefix_pos_i)\n        return self._run_engine(use_tqdm)\n\n    def _add_request(\n        self,\n        prompt: Optional[str],\n        sampling_params: SamplingParams,\n        prompt_token_ids: Optional[List[int]],\n        lora_request: Optional[LoRARequest] = None,\n        prefix_pos: Optional[int] = None,\n    ) -> None:\n        request_id = str(next(self.request_counter))\n        self.llm_engine.add_request(request_id,\n                                    prompt,\n                                    sampling_params,\n                                    prompt_token_ids,\n                                    lora_request=lora_request,\n                                    prefix_pos=prefix_pos)\n\n    def _run_engine(self, use_tqdm: bool) -> List[RequestOutput]:\n        # Initialize tqdm.\n        if use_tqdm:\n            num_requests = self.llm_engine.get_num_unfinished_requests()\n            pbar = tqdm(total=num_requests, desc=\"Processed prompts\")\n        # Run the engine.\n        outputs: List[RequestOutput] = []\n        while self.llm_engine.has_unfinished_requests():\n            step_outputs = self.llm_engine.step()\n            for output in step_outputs:\n                if output.finished:\n                    outputs.append(output)\n                    if use_tqdm:\n                        pbar.update(1)\n        if use_tqdm:\n            pbar.close()\n        # Sort the outputs by request ID.\n        # This is necessary because some requests may be finished earlier than\n        # its previous requests.\n        outputs = sorted(outputs, key=lambda x: int(x.request_id))\n        # TODO(shengguangming): maybe we can hack the autoregressive logics without only apply post process for better performance\n        return self._post_process_outputs(outputs)\n\n    # NOTE(shengguangming): add for verl\n    # TODO(sgm): we can optimize it by making the dataloader yield List[int] without padding.\n    def _pre_process_inputs(self, prompt_token_ids: torch.Tensor) -> List[int]:\n        # remove the left padding in the prompt token_id\n        pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n        non_pad_index = torch.nonzero(prompt_token_ids != pad_token_id, as_tuple=False)[0][0]\n        token_ids = prompt_token_ids[non_pad_index:].tolist()\n        return token_ids\n\n    # NOTE(shengguangming): add for verl\n    def _post_process_outputs(self, outputs: List[RequestOutput]) -> Tuple[torch.Tensor, torch.Tensor]:\n        output_token_ids = []\n        logprobs = []\n        for output in outputs:  # List[RequestOutput]\n            output = output.outputs\n            for output in output:  # List[CompletionOutput], usually len == 1\n                output_token_ids.append(torch.tensor(output.token_ids))\n                # TODO(shengguangming): can be optimzied by rewrite the Sampler._get_logprobs() logits\n                logprobs_dicts = output.logprobs\n                if logprobs_dicts is not None:\n                    logprob = []\n                    for logprobs_dict, id in zip(logprobs_dicts, output.token_ids):\n                        logprob.append(logprobs_dict[id])\n                    logprobs.append(torch.tensor(logprob))\n\n        pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n        output_token_ids = pad_sequence(output_token_ids, batch_first=True, padding_value=pad_token_id)\n        if len(logprobs) > 0:\n            logprobs = pad_sequence(logprobs, batch_first=True, padding_value=pad_token_id)\n        return output_token_ids, logprobs\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor]) -> None:\n        self.llm_engine.sync_model_weights(actor_weights=actor_weights)\n\n    def offload_model_weights(self) -> None:\n        self.llm_engine.offload_model_weights()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/llm_engine_sp.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/llm_engine.py\n\nimport os\nimport socket\nimport time\nimport torch\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Union\n\nfrom vllm.lora.request import LoRARequest\nfrom vllm.config import (CacheConfig, DeviceConfig, ModelConfig, ParallelConfig, SchedulerConfig, LoRAConfig)\nfrom vllm.core.scheduler import Scheduler, SchedulerOutputs\nfrom vllm.logger import init_logger\nfrom vllm.outputs import RequestOutput\nfrom vllm.sampling_params import SamplingParams\nfrom vllm.sequence import (SamplerOutput, Sequence, SequenceGroup, SequenceGroupMetadata, SequenceGroupOutput,\n                           SequenceOutput, SequenceStatus)\nfrom vllm.transformers_utils.tokenizer import detokenize_incrementally\nfrom vllm.engine.metrics import StatLogger, Stats\nfrom vllm.utils import Counter\nimport torch.nn as nn\nfrom .arg_utils import EngineArgs\nfrom .tokenizer import TokenizerGroup\n\nlogger = init_logger(__name__)\n_LOCAL_LOGGING_INTERVAL_SEC = 5\n\n\nclass LLMEngine:\n    \"\"\"An LLM engine that receives requests and generates texts.\n\n    This is the main class for the vLLM engine. It receives requests\n    from clients and generates texts from the LLM. It includes a tokenizer, a\n    language model (possibly distributed across multiple GPUs), and GPU memory\n    space allocated for intermediate states (aka KV cache). This class utilizes\n    iteration-level scheduling and efficient memory management to maximize the\n    serving throughput.\n\n    The `LLM` class wraps this class for offline batched inference and the\n    `AsyncLLMEngine` class wraps this class for online serving.\n\n    NOTE: The config arguments are derived from the `EngineArgs` class. For the\n    comprehensive list of arguments, see `EngineArgs`.\n\n    Args:\n        model_config: The configuration related to the LLM model.\n        cache_config: The configuration related to the KV cache memory\n            management.\n        parallel_config: The configuration related to distributed execution.\n        scheduler_config: The configuration related to the request scheduler.\n        distributed_init_method: The initialization method for distributed\n            execution. See `torch.distributed.init_process_group` for details.\n        placement_group: Ray placement group for distributed execution.\n            Required for distributed execution.\n        log_stats: Whether to log statistics.\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        tokenizer: nn.Module,\n        model_config: ModelConfig,\n        cache_config: CacheConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        lora_config: Optional[LoRAConfig],\n        distributed_init_method: str,\n        placement_group: Optional[None],\n        log_stats: bool,\n    ) -> None:\n        logger.info(\"Initializing an LLM engine with config: \"\n                    f\"model={model_config.model!r}, \"\n                    f\"tokenizer={model_config.tokenizer!r}, \"\n                    # f\"tokenizer_mode={model_config.tokenizer_mode}, \"\n                    f\"revision={model_config.revision}, \"\n                    f\"tokenizer_revision={model_config.tokenizer_revision}, \"\n                    # f\"trust_remote_code={model_config.trust_remote_code}, \"\n                    f\"dtype={model_config.dtype}, \"\n                    f\"max_seq_len={model_config.max_model_len}, \"\n                    # f\"download_dir={model_config.download_dir!r}, \"\n                    # f\"load_format={model_config.load_format}, \"\n                    f\"disable_custom_all_reduce={parallel_config.disable_custom_all_reduce}, \"\n                    f\"tensor_parallel_size={parallel_config.tensor_parallel_size}, \"\n                    f\"quantization={model_config.quantization}, \"\n                    f\"seed={model_config.seed})\")\n        # TODO(woosuk): Print more configs in debug mode.\n\n        self.model_config = model_config  # TODO: currently is hfconfig\n        self.cache_config = cache_config\n        self.lora_config = lora_config\n        assert self.cache_config.sliding_window == getattr(self.model_config.hf_config, \"sliding_window\", None)\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.log_stats = log_stats\n        self._verify_args()\n\n        # self.model = model # should not store the model, it should be deleted\n        # TODO(shengguangming): maybe we can choose init here or from arguments\n        self._init_tokenizer(tokenizer)\n\n        self.seq_counter = Counter()\n\n        # Create the parallel GPU workers.\n        self._init_workers_sp(model, distributed_init_method)\n\n        # Profile the memory usage and initialize the cache.\n        self._init_cache_sp()\n\n        # Create the scheduler.\n        # NOTE(shengguangming): each process will have independent scheduler\n        self.scheduler = Scheduler(scheduler_config, cache_config, lora_config)\n\n        # Metric Logging.\n        if self.log_stats:\n            self.stat_logger = StatLogger(local_interval=_LOCAL_LOGGING_INTERVAL_SEC)\n\n        # Logging.\n        self.last_logging_time = 0.0\n        # List of (timestamp, num_tokens)\n        self.num_prompt_tokens: List[Tuple[float, int]] = []\n        # List of (timestamp, num_tokens)\n        self.num_generation_tokens: List[Tuple[float, int]] = []\n\n    def _init_tokenizer(self, tokenizer, **tokenizer_init_kwargs):\n        init_kwargs = dict(enable_lora=bool(self.lora_config),\n                           max_num_seqs=self.scheduler_config.max_num_seqs,\n                           max_input_length=None)\n        init_kwargs.update(tokenizer_init_kwargs)\n        self.tokenizer: TokenizerGroup = TokenizerGroup(tokenizer, **init_kwargs)\n\n    # TODO: check get_lora_tokenizer func\n    def get_tokenizer_for_seq(self, sequence: Sequence):\n        return self.tokenizer.get_lora_tokenizer(sequence.lora_request)\n\n    def _init_workers_sp(self, model, distributed_init_method: str):\n        # Lazy import the Worker to avoid importing torch.cuda/xformers\n        # before CUDA_VISIBLE_DEVICES is set in the Worker\n        from .worker import Worker  # pylint: disable=import-outside-toplevel\n\n        rank = int(os.getenv(\"RANK\"))\n\n        self.worker = Worker(\n            model,\n            self.model_config,\n            self.parallel_config,\n            self.scheduler_config,\n            self.device_config,\n            rank,\n            distributed_init_method,\n            lora_config=self.lora_config,\n            kv_cache_dtype=self.cache_config.cache_dtype,\n        )\n\n        # NOTE(shengguangming): torch.distributed.init_process_group will be called inside the init_model()\n        self.worker.init_model()\n        self.worker.load_model()\n\n    def _verify_args(self) -> None:\n        self.model_config.verify_with_parallel_config(self.parallel_config)\n        self.cache_config.verify_with_parallel_config(self.parallel_config)\n\n    def _init_cache_sp(self) -> None:\n        \"\"\"Profiles the memory usage and initializes the KV cache.\"\"\"\n        # Get the maximum number of blocks that can be allocated on GPU and CPU.\n        num_blocks = self.worker.profile_num_available_blocks(\n            block_size=self.cache_config.block_size,\n            gpu_memory_utilization=self.cache_config.gpu_memory_utilization,\n            cpu_swap_space=self.cache_config.swap_space_bytes,\n            cache_dtype=self.cache_config.cache_dtype,\n        )\n\n        # NOTE(shengguangming): Now we don't use a shared centralized controler but each process will\n        # have its own scheduler\n        num_gpu_blocks = num_blocks[0]\n        num_cpu_blocks = num_blocks[1]\n\n        # FIXME(woosuk): Change to debug log.\n        logger.info(f\"# GPU blocks: {num_gpu_blocks}, \"\n                    f\"# CPU blocks: {num_cpu_blocks}\")\n\n        if num_gpu_blocks <= 0:\n            raise ValueError(\"No available memory for the cache blocks. \"\n                             \"Try increasing `gpu_memory_utilization` when \"\n                             \"initializing the engine.\")\n\n        max_seq_len = self.cache_config.block_size * num_gpu_blocks\n        if self.model_config.max_model_len > max_seq_len:\n            raise ValueError(f\"The model's max seq len ({self.model_config.max_model_len}) \"\n                             \"is larger than the maximum number of tokens that can be \"\n                             f\"stored in KV cache ({max_seq_len}). Try increasing \"\n                             \"`gpu_memory_utilization` or decreasing `max_model_len` when \"\n                             \"initializing the engine.\")\n\n        self.cache_config.num_gpu_blocks = num_gpu_blocks\n        self.cache_config.num_cpu_blocks = num_cpu_blocks\n\n        # Initialize the cache.\n        self.worker.init_cache_engine(cache_config=self.cache_config)\n        self.worker.warm_up_model()\n\n    def init_cache_engine(self):\n        self.worker.init_cache_engine(cache_config=self.cache_config)\n\n    def free_cache_engine(self):\n        self.worker.free_cache_engine()\n\n    @classmethod\n    def from_engine_args(cls, model, tokenizer, engine_args: EngineArgs) -> \"LLMEngine\":\n        \"\"\"Creates an LLM engine from the engine arguments.\"\"\"\n        # Create the engine configs.\n        engine_configs = engine_args.create_engine_configs()\n        parallel_config = engine_configs[2]\n        # Initialize the cluster.\n        distributed_init_method, placement_group = initialize_cluster(parallel_config)\n        # Create the LLM engine.\n        engine = cls(model,\n                     tokenizer,\n                     *engine_configs,\n                     distributed_init_method,\n                     placement_group,\n                     log_stats=not engine_args.disable_log_stats)\n        return engine\n\n    def add_request(\n        self,\n        request_id: str,\n        prompt: Optional[str],\n        sampling_params: SamplingParams,\n        prompt_token_ids: Optional[List[int]] = None,\n        arrival_time: Optional[float] = None,\n        lora_request: Optional[LoRARequest] = None,\n        prefix_pos: Optional[int] = None,\n    ) -> None:\n        \"\"\"Add a request to the engine's request pool.\n\n        The request is added to the request pool and will be processed by the\n        scheduler as `engine.step()` is called. The exact scheduling policy is\n        determined by the scheduler.\n\n        Args:\n            request_id: The unique ID of the request.\n            prompt: The prompt string. Can be None if prompt_token_ids is\n                provided.\n            sampling_params: The sampling parameters for text generation.\n            prompt_token_ids: The token IDs of the prompt. If None, we\n                use the tokenizer to convert the prompts to token IDs.\n            arrival_time: The arrival time of the request. If None, we use\n                the current monotonic time.\n            prefix_pos: If not None, we use the given position as the prefix\n                position for each prompt. We will cache the prefix's KV\n                cache and reuse it for the next request with the same prefix.\n                This is an experimental feature, and may be replaced with\n                automatic prefix caching in the future.\n\n        Details:\n            - Set arrival_time to the current time if it is None.\n            - Set prompt_token_ids to the encoded prompt if it is None.\n            - Create `best_of` number of :class:`~vllm.Sequence` objects.\n            - Create a :class:`~vllm.SequenceGroup` object\n              from the list of :class:`~vllm.Sequence`.\n            - Add the :class:`~vllm.SequenceGroup` object to the scheduler.\n\n        Example:\n            >>> # initialize engine\n            >>> engine = LLMEngine.from_engine_args(engine_args)\n            >>> # set request arguments\n            >>> example_prompt = \"Who is the president of the United States?\"\n            >>> sampling_params = SamplingParams(temperature=0.0)\n            >>> request_id = 0\n            >>>\n            >>> # add the request to the engine\n            >>> engine.add_request(\n            >>>    str(request_id),\n            >>>    example_prompt,\n            >>>    SamplingParams(temperature=0.0))\n            >>> # continue the request processing\n            >>> ...\n        \"\"\"\n        if lora_request is not None and not self.lora_config:\n            raise ValueError(f\"Got lora_request {lora_request} but LoRA is \"\n                             \"not enabled!\")\n        if arrival_time is None:\n            arrival_time = time.monotonic()\n        if prompt_token_ids is None:\n            assert prompt is not None\n            prompt_token_ids = self.tokenizer.encode(prompt)\n\n        # Create the sequences.\n        block_size = self.cache_config.block_size\n        seq_id = next(self.seq_counter)\n        seq = Sequence(seq_id, prompt, prompt_token_ids, block_size, lora_request)\n\n        # Check whether the input specifies prefix\n        prefix = self.scheduler.prefix_pool.add_or_get_prefix(prompt_token_ids[:prefix_pos], lora_request.lora_int_id if\n                                                              lora_request else 0) if prefix_pos is not None else None\n\n        # Create the sequence group.\n        seq_group = SequenceGroup(request_id, [seq], sampling_params, arrival_time, lora_request, prefix)\n\n        # Add the sequence group to the scheduler.\n        self.scheduler.add_seq_group(seq_group)\n\n    def abort_request(self, request_id: Union[str, Iterable[str]]) -> None:\n        \"\"\"Aborts a request(s) with the given ID.\n\n        Args:\n            request_id: The ID(s) of the request to abort.\n\n        Details:\n            - Refer to the\n              :meth:`~vllm.core.scheduler.Scheduler.abort_seq_group`\n              from class :class:`~vllm.core.scheduler.Scheduler`.\n\n        Example:\n            >>> # initialize engine and add a request with request_id\n            >>> request_id = str(0)\n            >>> # abort the request\n            >>> engine.abort_request(request_id)\n        \"\"\"\n        self.scheduler.abort_seq_group(request_id)\n\n    def get_model_config(self) -> ModelConfig:\n        \"\"\"Gets the model configuration.\"\"\"\n        return self.model_config\n\n    def get_num_unfinished_requests(self) -> int:\n        \"\"\"Gets the number of unfinished requests.\"\"\"\n        return self.scheduler.get_num_unfinished_seq_groups()\n\n    def has_unfinished_requests(self) -> bool:\n        \"\"\"Returns True if there are unfinished requests.\"\"\"\n        return self.scheduler.has_unfinished_seqs()\n\n    def _check_beam_search_early_stopping(\n        self,\n        early_stopping: Union[bool, str],\n        sampling_params: SamplingParams,\n        best_running_seq: Sequence,\n        current_worst_seq: Sequence,\n    ) -> bool:\n        assert sampling_params.use_beam_search\n        length_penalty = sampling_params.length_penalty\n        if early_stopping is True:\n            return True\n\n        current_worst_score = (current_worst_seq.get_beam_search_score(\n            length_penalty=length_penalty, eos_token_id=self.get_tokenizer_for_seq(current_worst_seq).eos_token_id))\n        if early_stopping is False:\n            highest_attainable_score = (best_running_seq.get_beam_search_score(\n                length_penalty=length_penalty, eos_token_id=self.get_tokenizer_for_seq(best_running_seq).eos_token_id))\n        else:\n            assert early_stopping == \"never\"\n            if length_penalty > 0.0:\n                # If length_penalty > 0.0, beam search will prefer longer\n                # sequences. The highest attainable score calculation is\n                # based on the longest possible sequence length in this case.\n                max_possible_length = max(best_running_seq.get_prompt_len() + sampling_params.max_tokens,\n                                          self.scheduler_config.max_model_len)\n                highest_attainable_score = (best_running_seq.get_beam_search_score(\n                    length_penalty=length_penalty,\n                    eos_token_id=self.get_tokenizer_for_seq(best_running_seq).eos_token_id,\n                    seq_len=max_possible_length))\n            else:\n                # Otherwise, beam search will prefer shorter sequences. The\n                # highest attainable score calculation is based on the current\n                # sequence length.\n                highest_attainable_score = (best_running_seq.get_beam_search_score(\n                    length_penalty=length_penalty,\n                    eos_token_id=self.get_tokenizer_for_seq(best_running_seq).eos_token_id))\n\n    def _process_sequence_group_outputs(self, seq_group: SequenceGroup, outputs: SequenceGroupOutput) -> None:\n\n        # Process prompt logprobs\n        prompt_logprobs = outputs.prompt_logprobs\n        if prompt_logprobs is not None:\n            seq_group.prompt_logprobs = prompt_logprobs\n\n        # Process samples\n        samples = outputs.samples\n        parent_seqs = seq_group.get_seqs(status=SequenceStatus.RUNNING)\n        existing_finished_seqs = seq_group.get_finished_seqs()\n        parent_child_dict = {parent_seq.seq_id: [] for parent_seq in parent_seqs}\n        for sample in samples:\n            parent_child_dict[sample.parent_seq_id].append(sample)\n        # List of (child, parent)\n        child_seqs: List[Tuple[Sequence, Sequence]] = []\n\n        # Process the child samples for each parent sequence\n        for parent in parent_seqs:\n            child_samples: List[SequenceOutput] = parent_child_dict[parent.seq_id]\n            if len(child_samples) == 0:\n                # This parent sequence has no children samples. Remove\n                # the parent sequence from the sequence group since it will\n                # not be used in the future iterations.\n                parent.status = SequenceStatus.FINISHED_ABORTED\n                seq_group.remove(parent.seq_id)\n                self.scheduler.free_seq(parent)\n                continue\n            # Fork the parent sequence if there are multiple child samples.\n            for child_sample in child_samples[:-1]:\n                new_child_seq_id = next(self.seq_counter)\n                child = parent.fork(new_child_seq_id)\n                child.append_token_id(child_sample.output_token, child_sample.logprobs)\n                child_seqs.append((child, parent))\n            # Continue the parent sequence for the last child sample.\n            # We reuse the parent sequence here to reduce redundant memory\n            # copies, especially when using non-beam search sampling methods.\n            last_child_sample = child_samples[-1]\n            parent.append_token_id(last_child_sample.output_token, last_child_sample.logprobs)\n            child_seqs.append((parent, parent))\n\n        for seq, _ in child_seqs:\n            # self._decode_sequence(seq, seq_group.sampling_params)\n            self._check_stop(seq, seq_group.sampling_params)\n\n        # Non-beam search case\n        if not seq_group.sampling_params.use_beam_search:\n            # For newly created child sequences, add them to the sequence group\n            # and fork them in block manager if they are not finished.\n            for seq, parent in child_seqs:\n                if seq is not parent:\n                    seq_group.add(seq)\n                    if not seq.is_finished():\n                        self.scheduler.fork_seq(parent, seq)\n\n            # Free the finished and selected parent sequences' memory in block\n            # manager. Keep them in the sequence group as candidate output.\n            # NOTE: we need to fork the new sequences before freeing the\n            # old sequences.\n            for seq, parent in child_seqs:\n                if seq is parent and seq.is_finished():\n                    self.scheduler.free_seq(seq)\n            return\n\n        # Beam search case\n        # Select the child sequences to keep in the sequence group.\n        selected_child_seqs = []\n        unselected_child_seqs = []\n        beam_width = seq_group.sampling_params.best_of\n        length_penalty = seq_group.sampling_params.length_penalty\n\n        # Select the newly finished sequences with the highest scores\n        # to replace existing finished sequences.\n        # Tuple of (seq, parent, is_new)\n        existing_finished_seqs = [(seq, None, False) for seq in existing_finished_seqs]\n        new_finished_seqs = [(seq, parent, True) for seq, parent in child_seqs if seq.is_finished()]\n        all_finished_seqs = existing_finished_seqs + new_finished_seqs\n        # Sort the finished sequences by their scores.\n        all_finished_seqs.sort(key=lambda x: x[0].get_beam_search_score(\n            length_penalty=length_penalty, eos_token_id=self.get_tokenizer_for_seq(x[0]).eos_token_id),\n                               reverse=True)\n        for seq, parent, is_new in all_finished_seqs[:beam_width]:\n            if is_new:\n                # A newly generated child sequence finishes and has a high\n                # score, so we will add it into the sequence group.\n                selected_child_seqs.append((seq, parent))\n        for seq, parent, is_new in all_finished_seqs[beam_width:]:\n            if is_new:\n                # A newly generated child sequence finishes but has a low\n                # score, so we will not add it into the sequence group.\n                # Additionally, if this sequence is a continuation of a\n                # parent sequence, we will need remove the parent sequence\n                # from the sequence group.\n                unselected_child_seqs.append((seq, parent))\n            else:\n                # An existing finished sequence has a low score, so we will\n                # remove it from the sequence group.\n                seq_group.remove(seq.seq_id)\n\n        # select the top beam_width sequences from the running\n        # sequences for the next iteration to continue the beam\n        # search.\n        running_child_seqs = [(seq, parent) for seq, parent in child_seqs if not seq.is_finished()]\n        # Sort the running sequences by their scores.\n        running_child_seqs.sort(key=lambda x: x[0].get_beam_search_score(\n            length_penalty=length_penalty, eos_token_id=self.get_tokenizer_for_seq(x[0]).eos_token_id),\n                                reverse=True)\n\n        # Check if we can stop the beam search.\n        if len(running_child_seqs) == 0:\n            # No running sequences, stop the beam search.\n            stop_beam_search = True\n        elif len(all_finished_seqs) < beam_width:\n            # Not enough finished sequences, continue the beam search.\n            stop_beam_search = False\n        else:\n            # Check the early stopping criteria\n            best_running_seq = running_child_seqs[0][0]\n            current_worst_seq = all_finished_seqs[beam_width - 1][0]\n            stop_beam_search = self._check_beam_search_early_stopping(seq_group.sampling_params.early_stopping,\n                                                                      seq_group.sampling_params, best_running_seq,\n                                                                      current_worst_seq)\n\n        if stop_beam_search:\n            # Stop the beam search and remove all the running sequences from\n            # the sequence group.\n            unselected_child_seqs.extend(running_child_seqs)\n        else:\n            # Continue the beam search and select the top beam_width sequences\n            # to continue the beam search.\n            selected_child_seqs.extend(running_child_seqs[:beam_width])\n            # The remaining running sequences will not be used in the next\n            # iteration. Again, if these sequences are continuations of\n            # parent sequences, we will need to remove the parent sequences\n            # from the sequence group.\n            unselected_child_seqs.extend(running_child_seqs[beam_width:])\n\n        # For newly created child sequences, add them to the sequence group\n        # and fork them in block manager if they are not finished.\n        for seq, parent in selected_child_seqs:\n            if seq is not parent:\n                seq_group.add(seq)\n                if not seq.is_finished():\n                    self.scheduler.fork_seq(parent, seq)\n\n        # Free the finished and selected parent sequences' memory in block\n        # manager. Keep them in the sequence group as candidate output.\n        for seq, parent in selected_child_seqs:\n            if seq is parent and seq.is_finished():\n                self.scheduler.free_seq(seq)\n\n        # Remove the unselected parent sequences from the sequence group and\n        # free their memory in block manager.\n        for seq, parent in unselected_child_seqs:\n            if seq is parent:\n                # Remove the parent sequence if it is not selected for next\n                # iteration\n                seq_group.remove(seq.seq_id)\n                self.scheduler.free_seq(seq)\n\n    def _process_model_outputs(self, output: SamplerOutput, scheduler_outputs: SchedulerOutputs) -> List[RequestOutput]:\n        # Update the scheduled sequence groups with the model outputs.\n        scheduled_seq_groups = scheduler_outputs.scheduled_seq_groups\n        for seq_group, outputs in zip(scheduled_seq_groups, output):\n            self._process_sequence_group_outputs(seq_group, outputs)\n\n        # Free the finished sequence groups.\n        self.scheduler.free_finished_seq_groups()\n\n        # Create the outputs.\n        request_outputs: List[RequestOutput] = []\n        for seq_group in scheduled_seq_groups:\n            request_output = RequestOutput.from_seq_group(seq_group)\n            request_outputs.append(request_output)\n        for seq_group in scheduler_outputs.ignored_seq_groups:\n            request_output = RequestOutput.from_seq_group(seq_group)\n            request_outputs.append(request_output)\n\n        # Update prefix state, now all the uncomputed prefixes are computed.\n        for seq_group in scheduled_seq_groups:\n            if (seq_group.prefix is not None and seq_group.prefix.allocated and not seq_group.prefix.computed):\n                seq_group.prefix.computed = True\n\n        # Log stats.\n        if self.log_stats:\n            self.stat_logger.log(self._get_stats(scheduler_outputs))\n\n        return request_outputs\n\n    def step(self) -> List[RequestOutput]:\n        \"\"\"Performs one decoding iteration and returns newly generated results.\n\n        This function performs one decoding iteration of the engine. It first\n        schedules the sequences to be executed in the next iteration and the\n        token blocks to be swapped in/out/copy. Then, it executes the model\n        and updates the scheduler with the model outputs. Finally, it decodes\n        the sequences and returns the newly generated results.\n        \"\"\"\n        seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule()\n        if not scheduler_outputs.is_empty():\n            output = self.worker.execute_model(\n                        seq_group_metadata_list=seq_group_metadata_list, # TODO: check this input\n                        blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in,\n                        blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out,\n                        blocks_to_copy=scheduler_outputs.blocks_to_copy,)\n        else:\n            return [RequestOutput.from_seq_group(seq_group) for seq_group in scheduler_outputs.ignored_seq_groups]\n\n        return self._process_model_outputs(output, scheduler_outputs)\n\n    def do_log_stats(self) -> None:\n        \"\"\"Forced log when no requests active.\"\"\"\n        if self.log_stats:\n            self.stat_logger.log(self._get_stats(scheduler_outputs=None))\n\n    def _get_stats(self, scheduler_outputs: Optional[SchedulerOutputs]) -> Stats:\n        \"\"\"Get Stats to be Logged to Prometheus.\"\"\"\n        now = time.monotonic()\n\n        # KV Cache Usage in %.\n        num_total_gpu = self.cache_config.num_gpu_blocks\n        num_free_gpu = self.scheduler.block_manager.get_num_free_gpu_blocks()\n        gpu_cache_usage = 1.0 - (num_free_gpu / num_total_gpu)\n\n        num_total_cpu = self.cache_config.num_cpu_blocks\n        cpu_cache_usage = 0.\n        if num_total_cpu > 0:\n            num_free_cpu = self.scheduler.block_manager.get_num_free_cpu_blocks()\n            cpu_cache_usage = 1.0 - (num_free_cpu / num_total_cpu)\n\n        # Scheduler State\n        num_running = len(self.scheduler.running)\n        num_swapped = len(self.scheduler.swapped)\n        num_waiting = len(self.scheduler.waiting)\n\n        # Iteration stats if we have scheduler output.\n        num_prompt_tokens = 0\n        num_generation_tokens = 0\n        time_to_first_tokens = []\n        time_per_output_tokens = []\n        time_e2e_requests = []\n        if scheduler_outputs is not None:\n            prompt_run = scheduler_outputs.prompt_run\n\n            # Number of Tokens.\n            if prompt_run:\n                num_prompt_tokens = scheduler_outputs.num_batched_tokens\n            else:\n                num_generation_tokens = scheduler_outputs.num_batched_tokens\n\n            # Latency Timings.\n            time_last_iters = []\n            for seq_group in scheduler_outputs.scheduled_seq_groups:\n                # Time since last token. (n.b. updates seq_group.last_token_time)\n                time_last_iters.append(seq_group.get_last_latency(now))\n                # Time since arrival for all finished requests.\n                if seq_group.is_finished():\n                    time_e2e_requests.append(now - seq_group.arrival_time)\n\n            time_to_first_tokens = time_last_iters if prompt_run else []\n            time_per_output_tokens = [] if prompt_run else time_last_iters\n\n        return Stats(\n            now=now,\n            num_running=num_running,\n            num_swapped=num_swapped,\n            num_waiting=num_waiting,\n            gpu_cache_usage=gpu_cache_usage,\n            cpu_cache_usage=cpu_cache_usage,\n            num_prompt_tokens=num_prompt_tokens,\n            num_generation_tokens=num_generation_tokens,\n            time_to_first_tokens=time_to_first_tokens,\n            time_per_output_tokens=time_per_output_tokens,\n            time_e2e_requests=time_e2e_requests,\n        )\n\n    # TODO: we may not need to decode\n    def _decode_sequence(self, seq: Sequence, prms: SamplingParams) -> None:\n        \"\"\"Decodes the new token for a sequence.\"\"\"\n        (new_tokens, new_output_text, prefix_offset, read_offset) = detokenize_incrementally(\n            self.get_tokenizer_for_seq(seq),\n            all_input_ids=seq.get_token_ids(),\n            prev_tokens=seq.tokens,\n            prefix_offset=seq.prefix_offset,\n            read_offset=seq.read_offset,\n            skip_special_tokens=prms.skip_special_tokens,\n            spaces_between_special_tokens=prms.spaces_between_special_tokens,\n        )\n        if seq.tokens is None:\n            seq.tokens = new_tokens\n        else:\n            seq.tokens.extend(new_tokens)\n        seq.prefix_offset = prefix_offset\n        seq.read_offset = read_offset\n        seq.output_text += new_output_text\n\n    def _check_stop(self, seq: Sequence, sampling_params: SamplingParams) -> None:\n        \"\"\"Stop the finished sequences.\"\"\"\n        # for stop_str in sampling_params.stop:\n        #     if seq.output_text.endswith(stop_str):\n        #         self._finalize_sequence(seq, sampling_params, stop_str)\n        #         seq.status = SequenceStatus.FINISHED_STOPPED\n        #         return\n        # if seq.get_last_token_id() in sampling_params.stop_token_ids:\n        #     stop_str = self.get_tokenizer_for_seq(seq).convert_ids_to_tokens(seq.get_last_token_id())\n        #     self._finalize_sequence(seq, sampling_params, stop_str)\n        #     seq.status = SequenceStatus.FINISHED_STOPPED\n        #     return\n\n        # Check if the sequence has reached max_model_len.\n        if seq.get_len() > self.scheduler_config.max_model_len:\n            seq.status = SequenceStatus.FINISHED_LENGTH_CAPPED\n            return\n\n        # Check if the sequence has reached max_tokens.\n        if seq.get_output_len() == sampling_params.max_tokens:\n            seq.status = SequenceStatus.FINISHED_LENGTH_CAPPED\n            return\n\n        # Check if the sequence has generated the EOS token.\n        if ((not sampling_params.ignore_eos) and\n                seq.get_last_token_id() == self.get_tokenizer_for_seq(seq).eos_token_id):\n            seq.status = SequenceStatus.FINISHED_STOPPED\n            return\n\n    def _finalize_sequence(self, seq: Sequence, sampling_params: SamplingParams, stop_string: str) -> None:\n        if not sampling_params.include_stop_str_in_output and stop_string:\n            # Truncate the output text so that the stop string is\n            # not included in the output.\n            seq.output_text = seq.output_text[:-len(stop_string)]\n\n    def add_lora(self, lora_request: LoRARequest) -> bool:\n        assert lora_request.lora_int_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.add_lora(lora_request)\n\n    def remove_lora(self, lora_id: int) -> bool:\n        assert lora_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.remove_lora(lora_id)\n\n    def list_loras(self) -> List[int]:\n        return self.worker.list_loras()\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor]) -> None:\n        self.worker.sync_model_weights(actor_weights=actor_weights)\n\n    def offload_model_weights(self) -> None:\n        self.worker.offload_model_weights()\n\n\ndef initialize_cluster(\n    parallel_config: ParallelConfig,\n    engine_use_ray: bool = False,\n    ray_address: Optional[str] = None,\n) -> Tuple[str, Optional[None]]:\n    \"\"\"Initialize the distributed cluster probably with Ray.\n\n    Args:\n        parallel_config: The configurations for parallel execution.\n        engine_use_ray: Whether to use Ray for async engine.\n        ray_address: The address of the Ray cluster. If None, uses\n            the default Ray cluster address.\n\n    Returns:\n        A tuple of (`distributed_init_method`, `placement_group`). The\n        `distributed_init_method` is the address for initializing the\n        distributed backend. `placement_group` includes the specification\n        of the resources for each distributed worker.\n    \"\"\"\n\n    # Initialize cluster locally.\n    port = get_open_port()\n    # We need to setup the distributed init method to make sure\n    # the distributed megatron code (e.g., get world size) works correctly.\n    distributed_init_method = f\"tcp://localhost:{port}\"\n    return distributed_init_method, None\n\n\ndef get_open_port():\n    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n        s.bind((\"\", 0))\n        return s.getsockname()[1]\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/model_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader\n\"\"\"Utilities for selecting and loading models.\"\"\"\nimport contextlib\nfrom typing import Dict, Type, Union\n\nimport torch\nimport torch.nn as nn\nfrom transformers import PretrainedConfig, PreTrainedModel\nfrom megatron.core.tensor_parallel.utils import VocabUtility\n\nfrom vllm.model_executor.models import ModelRegistry\nfrom vllm.model_executor.weight_utils import (get_quant_config, initialize_dummy_weights)\n\nfrom .config import ModelConfig\nfrom vllm.config import DeviceConfig, LoRAConfig\nfrom .weight_loaders import *\nfrom vllm.model_executor.sampling_metadata import SamplingMetadata, SamplingTensors\nfrom vllm.sequence import SamplerOutput\nfrom typing import Optional\nfrom vllm.model_executor.layers.sampler import Sampler\nfrom vllm.model_executor.layers.sampler import _prune_hidden_states, _apply_logits_processors, _apply_penalties, _apply_top_k_top_p, _apply_min_p, _apply_penalties, _sample, _get_logprobs, _build_sampler_output\n\n\n@contextlib.contextmanager\ndef _set_default_torch_dtype(dtype: torch.dtype):\n    \"\"\"Sets the default torch dtype to the given dtype.\"\"\"\n    old_dtype = torch.get_default_dtype()\n    torch.set_default_dtype(dtype)\n    yield\n    torch.set_default_dtype(old_dtype)\n\n\ndef _get_model_architecture(config: PretrainedConfig) -> Type[nn.Module]:\n    architectures = getattr(config, \"architectures\", [])\n    for arch in architectures:\n        model_cls = ModelRegistry.load_model_cls(arch)\n        if model_cls is not None:\n            return model_cls\n    raise ValueError(f\"Model architectures {architectures} are not supported for now. \"\n                     f\"Supported architectures: {ModelRegistry.get_supported_archs()}\")\n\n\nfrom vllm.model_executor.layers.linear import *\nfrom vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding, ParallelLMHead\nfrom vllm.model_executor.layers.activation import ScaledActivation\n\n__LAYER_WEIGHT_LOADER_REGISTRY__ = {\n    ColumnParallelLinear: parallel_weight_loader,\n    MergedColumnParallelLinear: parallel_weight_loader,\n    QKVParallelLinear: parallel_weight_loader,\n    RowParallelLinear: parallel_weight_loader,\n    VocabParallelEmbedding: parallel_weight_loader,\n    ParallelLMHead: parallel_weight_loader\n    # \"ScaledActivation.weight_loader\": ScaledActivation, # TODO(shengguangming): latest commit in vllm fix awq for this function and add load_weights\n    # \"default_weight_loader\": default_weight_loader\n}\n\n# NOTE(gmsheng): change the weight_loader function in runtime\nfor layer_class, weight_loader in __LAYER_WEIGHT_LOADER_REGISTRY__.items():\n    layer_class.weight_loader = weight_loader\n\n__MODEL_WEIGHT_LOADER_REGISTRY__ = {\n    'GPT2LMHeadModel': gpt2_weight_loader,\n    'LlamaForCausalLM': llama_weight_loader,\n    'LLaMAForCausalLM': llama_weight_loader,\n    'MistralForCausalLM': mistral_weight_loader,\n}\n\n# FIXME(shengguangming): the vLLM vocab will pad to 64, which may incur out of bounds\n# so we need to rewrite the init function of vocab\nDEFAULT_VOCAB_PADDING_SIZE = 64\n\n\ndef vocab_init(self,\n               num_embeddings: int,\n               embedding_dim: int,\n               params_dtype: Optional[torch.dtype] = None,\n               org_num_embeddings: Optional[int] = None,\n               padding_size: int = DEFAULT_VOCAB_PADDING_SIZE):\n    super(VocabParallelEmbedding, self).__init__()\n\n    # Keep the input dimensions.\n    # TODO (pad to be divided by 4)\n    self.num_embeddings = num_embeddings\n    self.org_vocab_size = org_num_embeddings or num_embeddings\n\n    # self.num_embeddings_padded = pad_vocab_size(num_embeddings,\n    #                                             padding_size)\n    self.embedding_dim = embedding_dim\n    if params_dtype is None:\n        params_dtype = torch.get_default_dtype()\n    self.tp_size = get_tensor_model_parallel_world_size()\n    # Divide the weight matrix along the vocaburaly dimension.\n\n    self.vocab_start_index, self.vocab_end_index = (VocabUtility.vocab_range_from_global_vocab_size(\n        self.num_embeddings, get_tensor_model_parallel_rank(), self.tp_size))\n    self.num_embeddings_per_partition = (self.vocab_end_index - self.vocab_start_index)\n    self.weight = Parameter(\n        torch.empty(\n            self.num_embeddings_per_partition,\n            self.embedding_dim,\n            # device=torch.cuda.current_device(),\n            dtype=params_dtype))\n    set_weight_attrs(self.weight, {\"parallel_dim\": 0, \"weight_loader\": self.weight_loader})\n\n\nVocabParallelEmbedding.__init__ = vocab_init\n\n\ndef _get_model_weight_loader(arch: str):\n    if arch in __MODEL_WEIGHT_LOADER_REGISTRY__:\n        return __MODEL_WEIGHT_LOADER_REGISTRY__[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {ModelRegistry.get_supported_archs()}\")\n\n\ndef get_model(actor_model: Union[PreTrainedModel, Dict],\n              model_config: ModelConfig,\n              device_config: DeviceConfig,\n              lora_config: Optional[LoRAConfig] = None) -> nn.Module:\n    model_class = _get_model_architecture(model_config.hf_config)\n\n    # Get the quantization config.\n    linear_method = None\n    quant_config = None\n    if model_config.quantization is not None:\n        quant_config = get_quant_config(model_config.quantization, model_config.model, model_config.hf_config,\n                                        model_config.download_dir)\n        capability = torch.cuda.get_device_capability()\n        capability = capability[0] * 10 + capability[1]\n        if capability < quant_config.get_min_capability():\n            raise ValueError(f\"The quantization method {model_config.quantization} is not \"\n                             \"supported for the current GPU. \"\n                             f\"Minimum capability: {quant_config.get_min_capability()}. \"\n                             f\"Current capability: {capability}.\")\n        supported_dtypes = quant_config.get_supported_act_dtypes()\n        if model_config.dtype not in supported_dtypes:\n            raise ValueError(f\"{model_config.dtype} is not supported for quantization \"\n                             f\"method {model_config.quantization}. Supported dtypes: \"\n                             f\"{supported_dtypes}\")\n        linear_method = quant_config.get_linear_method()\n\n    with _set_default_torch_dtype(model_config.dtype):\n        # Create a model instance.\n        # The weights will be initialized as empty tensors.\n        # with torch.device(device_config.device):\n        # NOTE(sgm): init the model in cpu\n        model = model_class(model_config.hf_config, linear_method)\n\n        if model_config.load_format == \"dummy\":\n            model = model.cuda()\n            # NOTE(woosuk): For accurate performance evaluation, we assign\n            # random values to the weights.\n            initialize_dummy_weights(model)\n        elif model_config.load_format == 'model' or model_config.load_format == 'auto':\n            # NOTE(shengguangming) Load the weights from the actor model\n            if isinstance(actor_model, nn.Module):\n                load_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)), vllm_model=model)\n            else:\n                load_weights(actor_weights=actor_model, vllm_model=model)\n\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n    return model.eval()\n\n\n# the actor model is .state_dict()\ndef load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    weight_loader = _get_model_weight_loader(vllm_model.__class__.__name__)\n    weight_loader(actor_weights, vllm_model)\n    # NOTE(sgm) to reduce peak memory usage, we offload vllm model to cpu\n    # after init, and we need this after sync model weights for in first iter.\n    vllm_model = vllm_model.cuda()\n\n\n# FIXME(sgm): hack the Sampler function in vllm v0.3.1\n# as they use ray, the sampler result will only need to return to the driver node,\n# therefore gather is enough. However, we use SPMD instead of a central scheduler,\n# all_gather is required (aligned with v0.2.6)\ndef _get_logits(self, hidden_states: torch.Tensor, embedding: torch.Tensor,\n                embedding_bias: Optional[torch.Tensor]) -> torch.Tensor:\n    # Get the logits for the next tokens.\n    logits = torch.matmul(hidden_states, embedding.t())\n    if embedding_bias is not None:\n        logits += embedding_bias\n    logits = tensor_model_parallel_all_gather(logits)\n    # Remove paddings in vocab (if any).\n    if logits is not None:\n        logits = logits[:, :self.org_vocab_size]\n    return logits\n\n\ndef forward(\n    self,\n    embedding: torch.Tensor,\n    hidden_states: torch.Tensor,\n    sampling_metadata: SamplingMetadata,\n    embedding_bias: Optional[torch.Tensor] = None,\n) -> Optional[SamplerOutput]:\n    # Get the hidden states that we use for sampling.\n    hidden_states = _prune_hidden_states(hidden_states, sampling_metadata)\n\n    # Get the logits for the next tokens.\n    logits = self._get_logits(hidden_states, embedding, embedding_bias)\n    # save origin logprobs for sampler_output\n    origin_logprobs = torch.log_softmax(logits, dim=-1, dtype=torch.float)\n\n    # Only perform sampling in the driver worker.\n    # Note: `_get_logits` is still distributed across TP workers because\n    # the `embedding` weight is distributed across TP workers.\n    # TODO(zhuohan): Change the get_logits part to a separate stage.\n    if not sampling_metadata.perform_sampling:\n        return None\n\n    assert logits is not None\n    _, vocab_size = logits.shape\n\n    # Apply logits processors (if any).\n    logits = _apply_logits_processors(logits, sampling_metadata)\n\n    # Prepare sampling tensors with pinned memory to avoid blocking.\n    (sampling_tensors, do_penalties, do_top_p_top_k,\n     do_min_p) = SamplingTensors.from_sampling_metadata(sampling_metadata, vocab_size, logits.device, logits.dtype)\n\n    # Apply presence and frequency penalties.\n    if do_penalties:\n        logits = _apply_penalties(logits, sampling_tensors.prompt_tokens, sampling_tensors.output_tokens,\n                                  sampling_tensors.presence_penalties, sampling_tensors.frequency_penalties,\n                                  sampling_tensors.repetition_penalties)\n\n    # Apply temperature scaling.\n    # Use in-place division to avoid creating a new tensor.\n    logits.div_(sampling_tensors.temperatures.unsqueeze_(dim=1))\n\n    if do_top_p_top_k:\n        logits = _apply_top_k_top_p(logits, sampling_tensors.top_ps, sampling_tensors.top_ks)\n\n    if do_min_p:\n        logits = _apply_min_p(logits, sampling_tensors.min_ps)\n\n    # We use float32 for probabilities and log probabilities.\n    # Compute the probabilities.\n    probs = torch.softmax(logits, dim=-1, dtype=torch.float)\n    # Compute the log probabilities.\n    # Use log_softmax to ensure numerical stability.\n    logprobs = torch.log_softmax(logits, dim=-1, dtype=torch.float)\n\n    # Sample the next tokens.\n    sample_results = _sample(probs, logprobs, sampling_metadata)\n\n    # Get the logprobs query results.\n    # prompt_logprobs, sample_logprobs = _get_logprobs(\n    #     logprobs, sampling_metadata, sample_results)\n    prompt_logprobs, sample_logprobs = _get_logprobs(origin_logprobs, sampling_metadata, sample_results)\n\n    return _build_sampler_output(sample_results, sampling_metadata, prompt_logprobs, sample_logprobs)\n\n\nfrom vllm.model_executor.layers.sampler import Sampler\n\nSampler._get_logits = _get_logits\nSampler.forward = forward\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/model_runner.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/model_runner.py\n\nfrom typing import Dict, List, Optional, Tuple, Set, Union\nimport contextlib\nimport time\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom vllm.config import (DeviceConfig, ModelConfig, LoRAConfig, ParallelConfig, SchedulerConfig)\nfrom vllm.logger import init_logger\nfrom vllm.model_executor import InputMetadata, SamplingMetadata\nfrom vllm.sampling_params import SamplingParams, SamplingType\nfrom vllm.sequence import SamplerOutput, SequenceData, SequenceGroupMetadata\nfrom vllm.lora.worker_manager import LRUCacheWorkerLoRAManager\nfrom vllm.lora.layers import LoRAMapping\nfrom vllm.lora.request import LoRARequest\nfrom vllm.utils import in_wsl\nfrom vllm.worker.model_runner import ModelRunner, CUDAGraphRunner, _async_h2d\n\nfrom .model_loader import get_model\n\nlogger = init_logger(__name__)\n\nKVCache = Tuple[torch.Tensor, torch.Tensor]\n_PAD_SLOT_ID = -1\nLORA_WARMUP_RANK = 8\n# Capture graphs for batch size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.\n# NOTE: _get_graph_batch_size needs to be updated if this list is changed.\n_BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [8 * i for i in range(1, 33)]\n\n\nclass ModelRunner(ModelRunner):\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        model_config: ModelConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        lora_config: Optional[LoRAConfig],\n        kv_cache_dtype: Optional[str] = \"auto\",\n    ):\n        self.model_config = model_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.lora_config = lora_config\n\n        # model_config can be None in tests/samplers/test_sampler.py.\n        # FIXME(woosuk): This is a hack to make the tests work. Refactor this.\n        self.sliding_window = (model_config.get_sliding_window() if model_config is not None else None)\n\n        self.device_config = (device_config if device_config is not None else DeviceConfig())\n        self.device = self.device_config.device\n\n        self.model = model  # this will be replaced by get_model()\n        self.block_size = None  # Set after initial profiling.\n        self.lora_manager = None\n\n        self.graph_runners: Dict[int, CUDAGraphRunner] = {}\n        self.graph_memory_pool = None  # Set during graph capture.\n\n        self.max_context_len_to_capture = (self.model_config.max_context_len_to_capture\n                                           if self.model_config is not None else 0)\n        # When using CUDA graph, the input block tables must be padded to\n        # max_context_len_to_capture. However, creating the block table in\n        # Python can be expensive. To optimize this, we cache the block table\n        # in numpy and only copy the actual input content at every iteration.\n        # The shape of the cached block table will be\n        # (max batch size to capture, max context len to capture / block size).\n        self.graph_block_tables = None  # Set after initial profiling.\n        # cache in_wsl result\n        self.in_wsl = in_wsl()\n        self.kv_cache_dtype = kv_cache_dtype\n\n    def load_model(self) -> None:\n        self.model = get_model(actor_model=self.model,\n                               model_config=self.model_config,\n                               device_config=self.device_config,\n                               lora_config=self.lora_config)\n        vocab_size = self.model.config.vocab_size\n\n        if self.lora_config:\n            assert hasattr(\n                self.model,\n                \"supported_lora_modules\") and self.model.supported_lora_modules, \"Model does not support LoRA\"\n            assert hasattr(self.model, \"embedding_modules\"), \"Model does not have embedding_modules\"\n            assert hasattr(self.model, \"embedding_padding_modules\"), \"Model does not have embedding_padding_modules\"\n            self.lora_manager = LRUCacheWorkerLoRAManager(\n                self.scheduler_config.max_num_seqs,\n                self.scheduler_config.max_num_batched_tokens + self.scheduler_config.max_paddings, vocab_size,\n                self.lora_config, self.device, self.model.embedding_modules, self.model.embedding_padding_modules)\n            self.model = self.lora_manager.create_lora_manager(self.model)\n\n    def _prepare_sample(\n        self,\n        seq_group_metadata_list: List[SequenceGroupMetadata],\n        prompt_lens: List[int],\n        subquery_lens: Optional[List[int]],\n    ) -> SamplingMetadata:\n        seq_groups: List[Tuple[List[int], SamplingParams]] = []\n        selected_token_indices: List[int] = []\n        selected_token_start_idx = 0\n        categorized_sample_indices = {t: [] for t in SamplingType}\n        categorized_sample_indices_start_idx = 0\n\n        max_subquery_len = max(subquery_lens) if subquery_lens else 1\n        for i, seq_group_metadata in enumerate(seq_group_metadata_list):\n            seq_ids = list(seq_group_metadata.seq_data.keys())\n            sampling_params = seq_group_metadata.sampling_params\n            seq_groups.append((seq_ids, sampling_params))\n\n            if seq_group_metadata.is_prompt:\n                assert len(seq_ids) == 1\n                assert subquery_lens is not None\n                subquery_len = subquery_lens[i]\n                if sampling_params.prompt_logprobs is not None:\n                    # NOTE: prompt token positions do not need sample, skip\n                    categorized_sample_indices_start_idx += subquery_len - 1\n\n                categorized_sample_indices[sampling_params.sampling_type].append(categorized_sample_indices_start_idx)\n                categorized_sample_indices_start_idx += 1\n\n                if sampling_params.prompt_logprobs is not None:\n                    selected_token_indices.extend(\n                        range(selected_token_start_idx, selected_token_start_idx + subquery_len - 1))\n                selected_token_indices.append(selected_token_start_idx + subquery_len - 1)\n                selected_token_start_idx += max_subquery_len\n            else:\n                num_seqs = len(seq_ids)\n                selected_token_indices.extend(range(selected_token_start_idx, selected_token_start_idx + num_seqs))\n                selected_token_start_idx += num_seqs\n\n                categorized_sample_indices[sampling_params.sampling_type].extend(\n                    range(categorized_sample_indices_start_idx, categorized_sample_indices_start_idx + num_seqs))\n                categorized_sample_indices_start_idx += num_seqs\n\n        selected_token_indices = _async_h2d(selected_token_indices,\n                                            dtype=torch.long,\n                                            target_device=self.device,\n                                            pin_memory=not self.in_wsl)\n        categorized_sample_indices = {\n            t: _async_h2d(seq_ids, dtype=torch.int, target_device=self.device, pin_memory=not self.in_wsl)\n            for t, seq_ids in categorized_sample_indices.items()\n        }\n\n        seq_data: Dict[int, SequenceData] = {}\n        for seq_group_metadata in seq_group_metadata_list:\n            seq_data.update(seq_group_metadata.seq_data)\n\n        sampling_metadata = SamplingMetadata(\n            seq_groups=seq_groups,\n            seq_data=seq_data,\n            prompt_lens=prompt_lens,\n            selected_token_indices=selected_token_indices,\n            categorized_sample_indices=categorized_sample_indices,\n        )\n        return sampling_metadata\n\n    def prepare_input_tensors(\n        self,\n        seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],\n    ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, SamplingMetadata, Set[int], LoRAMapping]:\n        # NOTE: We assume that all sequences in the group are all prompts or\n        # all decodes.\n        is_prompt = seq_group_metadata_list[0].is_prompt\n        # Prepare input tensors.\n        if is_prompt:\n            (input_tokens, input_positions, input_metadata, prompt_lens, subquery_lens, lora_index_mapping,\n             lora_prompt_mapping, lora_requests) = self._prepare_prompt(seq_group_metadata_list)\n        else:\n            (input_tokens, input_positions, input_metadata, lora_index_mapping, lora_prompt_mapping,\n             lora_requests) = self._prepare_decode(seq_group_metadata_list)\n            prompt_lens = []\n            subquery_lens = None\n        sampling_metadata = self._prepare_sample(seq_group_metadata_list, prompt_lens, subquery_lens)\n        if self.lora_config:\n            flat_lora_index_mapping = [item for sublist in lora_index_mapping for item in sublist]\n            lora_mapping = LoRAMapping(\n                flat_lora_index_mapping,\n                lora_prompt_mapping,\n            )\n        else:\n            lora_mapping = None\n\n        return (input_tokens, input_positions, input_metadata, sampling_metadata, lora_requests, lora_mapping)\n\n    @torch.inference_mode()\n    def execute_model(\n        self,\n        seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],\n        kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],\n    ) -> Optional[SamplerOutput]:\n        (input_tokens, input_positions, input_metadata, sampling_metadata, lora_requests,\n         lora_mapping) = self.prepare_input_tensors(seq_group_metadata_list)\n\n        if self.lora_config:\n            self.set_active_loras(lora_requests, lora_mapping)\n\n        # Execute the model.\n        if input_metadata.use_cuda_graph:\n            graph_batch_size = input_tokens.shape[0]\n            model_executable = self.graph_runners[graph_batch_size]\n        else:\n            model_executable = self.model\n        hidden_states = model_executable(\n            input_ids=input_tokens,\n            positions=input_positions,\n            kv_caches=kv_caches,\n            input_metadata=input_metadata,\n        )\n\n        # Sample the next token.\n        output = self.model.sample(\n            hidden_states=hidden_states,\n            sampling_metadata=sampling_metadata,\n        )\n        return output\n\n    @torch.inference_mode()\n    def profile_run(self) -> None:\n        # Enable top-k sampling to reflect the accurate memory usage.\n        vocab_size = self.model_config.get_vocab_size()\n        # FIXME(sgm): this sampling params will call cumsum(), causing the\n        # deterministic cumsum throw error\n        sampling_params = SamplingParams(top_p=0.99, top_k=vocab_size - 1)\n        max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens\n        max_num_seqs = self.scheduler_config.max_num_seqs\n\n        # This represents the maximum number of different requests\n        # that will have unique loras, an therefore the max amount of memory\n        # consumption create dummy lora request copies from the lora request\n        # passed in, which contains a lora from the lora warmup path.\n        dummy_lora_requests = []\n        dummy_lora_requests_per_seq = []\n        if self.lora_config:\n            for idx in range(self.lora_config.max_loras):\n                lora_id = idx + 1\n                dummy_lora_request = LoRARequest(\n                    lora_name=f\"warmup_{lora_id}\",\n                    lora_int_id=lora_id,\n                    lora_local_path=\"/not/a/real/path\",\n                )\n                self.lora_manager.add_dummy_lora(dummy_lora_request, rank=LORA_WARMUP_RANK)\n                dummy_lora_requests.append(dummy_lora_request)\n            dummy_lora_requests_per_seq = [\n                dummy_lora_requests[idx % len(dummy_lora_requests)] for idx in range(max_num_seqs)\n            ]\n\n        # Profile memory usage with max_num_sequences sequences and the total\n        # number of tokens equal to max_num_batched_tokens.\n        seqs: List[SequenceGroupMetadata] = []\n        for group_id in range(max_num_seqs):\n            seq_len = (max_num_batched_tokens // max_num_seqs + (group_id < max_num_batched_tokens % max_num_seqs))\n            seq_data = SequenceData([0] * seq_len)\n            seq = SequenceGroupMetadata(\n                request_id=str(group_id),\n                is_prompt=True,\n                seq_data={group_id: seq_data},\n                sampling_params=sampling_params,\n                block_tables=None,\n                lora_request=dummy_lora_requests_per_seq[group_id] if dummy_lora_requests_per_seq else None,\n            )\n            seqs.append(seq)\n\n        # Run the model with the dummy inputs.\n        num_layers = self.model_config.get_num_layers(self.parallel_config)\n        kv_caches = [(None, None)] * num_layers\n        self.execute_model(seqs, kv_caches)\n        torch.cuda.synchronize()\n        return\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/parallel_state.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Adapted from\n# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py\n# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.\n\"\"\"Model and data parallel groups.\"\"\"\n\nimport torch\nimport torch.distributed\n\nimport vllm.model_executor.parallel_utils.parallel_state as ps\n\"\"\"\nThis version is strongly tied with Megatron to implement HybridEngine and weight sharing between vllm and Megatron.\n- We assume the Megatron tp+dp+pp world is already established before calling this function.\n\n\"\"\"\n\n# Tensor model parallel group that the current rank belongs to.\n_TENSOR_MODEL_PARALLEL_GROUP = None\n\n# Micro Data parallel group. Micro data parallel group is additional dp group that origins from splitting training tp\n# into infer_tp and micro_tp. By default, we use order micro_dp - tp\n_MICRO_DATA_PARALLEL_GROUP = None\n\n\ndef initialize_model_parallel_from_megatron(\n        tensor_model_parallel_size=None  # we set None for backward compatibility to set infer_tp = train_tp\n) -> None:\n    from megatron.core import parallel_state as mpu\n    from megatron.distributed import new_group\n    # Get world size and rank. Ensure some consistencies.\n    assert torch.distributed.is_initialized()\n\n    if tensor_model_parallel_size is None:\n        tensor_model_parallel_size = mpu.get_tensor_model_parallel_world_size()\n    else:\n        assert isinstance(tensor_model_parallel_size, int)\n\n    # Build the tensor model-parallel groups.\n    assert ps._TENSOR_MODEL_PARALLEL_GROUP is None, (\"tensor model parallel group is already initialized\")\n\n    assert tensor_model_parallel_size <= mpu.get_tensor_model_parallel_world_size(\n    ), 'Not implemented for infer_tp > train_tp'\n\n    global _TENSOR_MODEL_PARALLEL_GROUP\n    global _MICRO_DATA_PARALLEL_GROUP\n\n    assert mpu.get_tensor_model_parallel_world_size() % tensor_model_parallel_size == 0\n\n    micro_dp_size = mpu.get_tensor_model_parallel_world_size() // tensor_model_parallel_size\n\n    world_size: int = torch.distributed.get_world_size()\n\n    num_micro_dp_groups = world_size // micro_dp_size\n\n    rank = torch.distributed.get_rank()\n\n    # Build the micro dp groups.\n    assert _MICRO_DATA_PARALLEL_GROUP is None, (\"micro data parallel group is already initialized\")\n    for i in range(num_micro_dp_groups):\n        ranks = range(i * micro_dp_size, (i + 1) * micro_dp_size)\n        group = new_group(rank=rank, ranks=ranks, group_type='micro_dp')\n        if rank in ranks:\n            _MICRO_DATA_PARALLEL_GROUP = group\n\n    if tensor_model_parallel_size == mpu.get_tensor_model_parallel_world_size():\n        # using the same tp group as Megatron\n        ps._TENSOR_MODEL_PARALLEL_GROUP = mpu.get_tensor_model_parallel_group()\n\n        _TENSOR_MODEL_PARALLEL_GROUP = mpu.get_tensor_model_parallel_group()\n        # no _MICRO_DATA_PARALLEL_GROUP\n    else:\n        # initialize a micro_dp group and a tp group\n        # assume training tp=4, infer tp=2, then, weight is partitioned as\n        # [1], [2], [3], [4] for training and [1,2], [1,2], [3,4], [3,4] for inference\n\n        # Build the inference tp groups\n        train_tp = mpu.get_tensor_model_parallel_world_size()\n        num_tensor_model_parallel_groups_per_train_tp = train_tp // tensor_model_parallel_size\n        num_tensor_model_parallel_groups = world_size // tensor_model_parallel_size\n        assert _TENSOR_MODEL_PARALLEL_GROUP is None, (\"tensor model parallel group is already initialized\")\n        for i in range(num_tensor_model_parallel_groups // num_tensor_model_parallel_groups_per_train_tp):\n            start = train_tp * i\n            end = train_tp * (i + 1)\n            for j in range(num_tensor_model_parallel_groups_per_train_tp):\n                ranks = list(range(start, end, num_tensor_model_parallel_groups_per_train_tp))\n                for i in range(len(ranks)):\n                    ranks[i] += j\n                # group = torch.distributed.new_group(ranks)\n                group = new_group(rank=rank, ranks=ranks, group_type='infer_tp')\n                if rank in ranks:\n                    _TENSOR_MODEL_PARALLEL_GROUP = group\n                    ps._TENSOR_MODEL_PARALLEL_GROUP = _TENSOR_MODEL_PARALLEL_GROUP\n    # Build the pipeline model-parallel groups.\n    # global _PIPELINE_MODEL_PARALLEL_GROUP\n    # global _PIPELINE_GLOBAL_RANKS\n    # assert ps._PIPELINE_MODEL_PARALLEL_GROUP is None, (\"pipeline model parallel group is already initialized\")\n\n    # ps._PIPELINE_MODEL_PARALLEL_GROUP = mpu.get_pipeline_model_parallel_group()\n    # ps._PIPELINE_GLOBAL_RANKS = mpu.get_pipeline_model_parallel_ranks()\n\n\n\"\"\"\nTensor model parallel utilities\n\"\"\"\n\n\ndef get_tensor_model_parallel_group():\n    \"\"\"Get the tensor model parallel group the caller rank belongs to.\"\"\"\n    assert _TENSOR_MODEL_PARALLEL_GROUP is not None, (\"tensor model parallel group is not initialized\")\n    return _TENSOR_MODEL_PARALLEL_GROUP\n\n\ndef get_tensor_model_parallel_world_size():\n    \"\"\"Return world size for the tensor model parallel group.\"\"\"\n    return torch.distributed.get_world_size(group=get_tensor_model_parallel_group())\n\n\ndef get_tensor_model_parallel_rank():\n    \"\"\"Return my rank for the tensor model parallel group.\"\"\"\n    return torch.distributed.get_rank(group=get_tensor_model_parallel_group())\n\n\ndef get_tensor_model_parallel_src_rank():\n    \"\"\"Calculate the global rank corresponding to the first local rank\n    in the tensor model parallel group.\"\"\"\n    global_rank = torch.distributed.get_rank()\n    local_world_size = get_tensor_model_parallel_world_size()\n    return (global_rank // local_world_size) * local_world_size\n\n\n\"\"\"\nMicro Data parallel group\n\"\"\"\n\n\ndef get_micro_data_parallel_group():\n    assert _MICRO_DATA_PARALLEL_GROUP is not None\n    return _MICRO_DATA_PARALLEL_GROUP\n\n\ndef get_micro_data_parallel_world_size():\n    return torch.distributed.get_world_size(group=get_micro_data_parallel_group())\n\n\ndef get_micro_data_parallel_rank():\n    return torch.distributed.get_rank(group=get_micro_data_parallel_group())\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/tokenizer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/tokenizer_group/tokenizer_group.py\n\nfrom typing import List, Optional, Tuple, Union\n\nfrom transformers import (AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast)\n\nfrom vllm.lora.request import LoRARequest\nfrom vllm.utils import make_async, LRUCache\nfrom vllm.transformers_utils.tokenizers import *\n\n\nclass TokenizerGroup:\n    \"\"\"A group of tokenizers that can be used for LoRA adapters.\"\"\"\n\n    def __init__(self, tokenizer: PreTrainedTokenizer, enable_lora: bool, max_num_seqs: int,\n                 max_input_length: Optional[int]):\n        self.enable_lora = enable_lora\n        self.max_input_length = max_input_length\n        self.tokenizer = tokenizer\n        if enable_lora:\n            self.lora_tokenizers = LRUCache(capacity=max_num_seqs)\n        else:\n            self.lora_tokenizers = None\n\n    def encode(self,\n               prompt: str,\n               request_id: Optional[str] = None,\n               lora_request: Optional[LoRARequest] = None) -> List[int]:\n        tokenizer = self.get_lora_tokenizer(lora_request)\n        return tokenizer.encode(prompt)\n\n    async def encode_async(self,\n                           prompt: str,\n                           request_id: Optional[str] = None,\n                           lora_request: Optional[LoRARequest] = None) -> List[int]:\n        tokenizer = await self.get_lora_tokenizer_async(lora_request)\n        return tokenizer.encode(prompt)\n\n    def get_lora_tokenizer(self, lora_request: Optional[LoRARequest]) -> \"PreTrainedTokenizer\":\n        if not lora_request or not self.enable_lora:\n            return self.tokenizer\n        if lora_request.lora_int_id not in self.lora_tokenizers:\n            # TODO(sgm): the lora tokenizer is also passed, but may be different\n            tokenizer = self.tokenizer\n            # tokenizer = (get_lora_tokenizer(\n            #     lora_request, **self.tokenizer_config) or self.tokenizer)\n            self.lora_tokenizers.put(lora_request.lora_int_id, tokenizer)\n            return tokenizer\n        else:\n            return self.lora_tokenizers.get(lora_request.lora_int_id)\n\n    # FIXME(sgm): for simplicity, we assign the special token here\n    @property\n    def pad_token_id(self):\n        return self.tokenizer.pad_token_id\n\n    @property\n    def eos_token_id(self):\n        return self.tokenizer.eos_token_id\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/weight_loaders.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models\n\nfrom typing import Dict\nimport torch\nimport torch.nn as nn\n\n\n# NOTE(shengguangming): replace the origin weight loader function in the class\ndef parallel_weight_loader(self, param: torch.Tensor, loaded_weight: torch.Tensor) -> None:\n    \"\"\"Parallel Linear weight loader.\"\"\"\n    assert param.size() == loaded_weight.size(\n    ), 'the parameter size is not align with the loaded weight size, param size: {}, loaded_weight size: {}'.format(\n        param.size(), loaded_weight.size())\n    assert param.data.dtype == loaded_weight.data.dtype, \"if we want to shared weights, the data type should also be the same\"\n\n    param.data = loaded_weight.data\n\n\ndef default_weight_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:\n    \"\"\"Default weight loader.\"\"\"\n    assert param.size() == loaded_weight.size()\n    assert param.data.dtype == loaded_weight.data.dtype, \"if we want to shared weights, the data type should also be the same\"\n\n    param.data = loaded_weight.data\n\n\ndef gpt2_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"lm_head.weight\" in name:\n            # GPT-2 ties the weights of the embedding layer and the final\n            # linear layer.\n            continue\n        if \".attn.bias\" in name or \".attn.masked_bias\" in name:\n            # Skip attention mask.\n            # NOTE: \"c_attn.bias\" should not be skipped.\n            continue\n        if not name.startswith(\"transformer.\"):\n            name = \"transformer.\" + name\n        param = params_dict[name]\n        # The HF's GPT-2 implementation uses Conv1D instead of Linear.\n        # Because of this, we need to transpose the weights.\n        # Note(zhuohan): the logic below might break quantized models.\n        for conv1d_weight_name in [\"c_attn\", \"c_proj\", \"c_fc\"]:\n            if conv1d_weight_name not in name:\n                continue\n            if not name.endswith(\".weight\"):\n                continue\n            # TODO: check megatron\n            loaded_weight = loaded_weight.t()\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, loaded_weight)\n\n\ndef llama_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    prefix = '0.module.module.'\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if name[:len(prefix)] == prefix:\n            name = name[len(prefix):]\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef mistral_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    # TODO: need to implement a general way to deal with prefix\n    prefix = '0.module.module.'\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if name[:len(prefix)] == prefix:\n            name = name[len(prefix):]\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_3_1/worker.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/worker.py\n\"\"\"A GPU worker class.\"\"\"\nimport os\nimport gc\nfrom typing import Dict, List, Tuple, Optional, Union, Set\n\nimport torch\nimport torch.distributed\nimport torch.nn as nn\n\nfrom vllm.config import (CacheConfig, DeviceConfig, ModelConfig, ParallelConfig, SchedulerConfig, LoRAConfig)\nfrom vllm.model_executor import InputMetadata, set_random_seed\nfrom vllm.model_executor.parallel_utils.parallel_state import (initialize_model_parallel)\nfrom vllm.sampling_params import SamplingParams, SamplingType\nfrom vllm.sequence import SamplerOutput, SequenceData, SequenceGroupMetadata\nfrom vllm.worker.cache_engine import CacheEngine\nfrom vllm.model_executor.parallel_utils.custom_all_reduce import init_custom_ar\nfrom vllm.model_executor.parallel_utils.parallel_state import get_tensor_model_parallel_group\n\nfrom .model_runner import ModelRunner\nfrom .model_loader import load_weights\nfrom .parallel_state import initialize_model_parallel_from_megatron\nfrom vllm.lora.request import LoRARequest\n\n\nclass Worker:\n    \"\"\"A worker class that executes (a partition of) the model on a GPU.\n\n    Each worker is associated with a single GPU. The worker is responsible for\n    maintaining the KV cache and executing the model on the GPU. In case of\n    distributed inference, each worker is assigned a partition of the model.\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        model_config: ModelConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        rank: Optional[int] = None,\n        distributed_init_method: Optional[str] = None,\n        lora_config: Optional[LoRAConfig] = None,\n        kv_cache_dtype: Optional[str] = \"auto\",\n    ) -> None:\n        # self.model = model  # will be replaced in the init_model\n        self.model_config = model_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.rank = rank\n        self.distributed_init_method = distributed_init_method\n        self.lora_config = lora_config\n\n        self.model_runner = ModelRunner(\n            model,\n            model_config,\n            parallel_config,\n            scheduler_config,\n            device_config,\n            lora_config=self.lora_config,\n            kv_cache_dtype=kv_cache_dtype,\n        )\n\n        # Uninitialized cache engine. Will be initialized by\n        # self.init_cache_engine().\n        self.cache_config = None\n        self.block_size = None\n        self.sliding_window = None\n        self.cache_engine = None\n        self.cache_events = None\n        self.gpu_cache = None\n\n        # For offloading inference engine params\n        self.cpu_model = None\n\n    def init_model(self, cupy_port: Optional[int] = None):\n        # torch.distributed.all_reduce does not free the input tensor until\n        # the synchronization point. This causes the memory usage to grow\n        # as the number of all_reduce calls increases. This env var disables\n        # this behavior.\n        # Related issue:\n        # https://discuss.pytorch.org/t/cuda-allocation-lifetime-for-inputs-to-distributed-all-reduce/191573\n        os.environ[\"TORCH_NCCL_AVOID_RECORD_STREAMS\"] = \"1\"\n\n        # Env vars will be set by TORCHRUN.\n        self.rank = self.rank if self.rank is not None else int(os.getenv(\"RANK\", \"-1\"))\n        local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n        self.device = torch.device(f\"cuda:{local_rank}\")\n        if self.rank < 0:\n            raise ValueError(\"Invalid or unspecified rank.\")\n        torch.cuda.set_device(self.device)\n\n        _check_if_gpu_supports_dtype(self.model_config.dtype)\n\n        # Initialize the distributed environment.\n        # TODO: do not use cupy\n        _init_distributed_environment(self.parallel_config, self.rank, self.distributed_init_method)\n        if not self.parallel_config.disable_custom_all_reduce:\n            init_custom_ar()\n        # Initialize the model.\n        set_random_seed(self.model_config.seed)\n        # self.model = get_model(actor_model=self.model, model_config=self.model_config)\n\n    def load_model(self):\n        self.model_runner.load_model()\n\n    @torch.inference_mode()\n    def profile_num_available_blocks(\n        self,\n        block_size: int,\n        gpu_memory_utilization: float,\n        cpu_swap_space: int,\n        cache_dtype: str,\n    ) -> Tuple[int, int]:\n        # Profile the memory usage of the model and get the maximum number of\n        # cache blocks that can be allocated with the remaining free memory.\n        torch.cuda.empty_cache()\n        # torch.cuda.reset_peak_memory_stats()\n\n        # Execute a forward pass with dummy inputs to profile the memory usage\n        # of the model.\n        self.model_runner.profile_run()\n\n        # Calculate the number of blocks that can be allocated with the\n        # profiled peak memory.\n        torch.cuda.synchronize()\n        free_gpu_memory, total_gpu_memory = torch.cuda.mem_get_info()\n        peak_memory = total_gpu_memory - free_gpu_memory\n\n        cache_block_size = CacheEngine.get_cache_block_size(block_size, cache_dtype, self.model_config,\n                                                            self.parallel_config)\n        # NOTE(sgm) use the remaining memory\n        num_gpu_blocks = int((free_gpu_memory * gpu_memory_utilization) // cache_block_size)\n        # num_gpu_blocks = int((total_gpu_memory * gpu_memory_utilization - peak_memory) // cache_block_size)\n        num_cpu_blocks = int(cpu_swap_space // cache_block_size)\n        num_gpu_blocks = max(num_gpu_blocks, 0)\n        num_cpu_blocks = max(num_cpu_blocks, 0)\n        if self.model_runner.lora_manager:\n            self.model_runner.remove_all_loras()\n        gc.collect()\n        torch.cuda.empty_cache()\n        # Synchronize number of blocks with all the rank\n        num_gpu_blocks = torch.tensor([num_gpu_blocks], device='cuda')\n        num_cpu_blocks = torch.tensor([num_cpu_blocks], device='cuda')\n        torch.distributed.all_reduce(num_gpu_blocks,\n                                     op=torch.distributed.ReduceOp.MIN,\n                                     group=get_tensor_model_parallel_group())\n        torch.distributed.all_reduce(num_cpu_blocks,\n                                     op=torch.distributed.ReduceOp.MIN,\n                                     group=get_tensor_model_parallel_group())\n        num_gpu_blocks = num_gpu_blocks.item()\n        num_cpu_blocks = num_cpu_blocks.item()\n        return num_gpu_blocks, num_cpu_blocks\n\n    def init_cache_engine(self, cache_config: CacheConfig) -> None:\n        if self.cache_engine is None and self.gpu_cache is None:\n            self.cache_config = cache_config\n            self.cache_engine = CacheEngine(self.cache_config, self.model_config, self.parallel_config)\n            self.cache_events = self.cache_engine.events\n            self.gpu_cache = self.cache_engine.gpu_cache\n            self.model_runner.set_block_size(self.cache_engine.block_size)\n\n    def free_cache_engine(self):\n        # ensure `enforce_eager=True`\n        self.cache_engine = None\n        self.gpu_cache = None\n\n    def warm_up_model(self) -> None:\n        if not self.model_config.enforce_eager:\n            self.model_runner.capture_model(self.gpu_cache)\n        # Reset the seed to ensure that the random state is not affected by\n        # the model initialization and profiling.\n        set_random_seed(self.model_config.seed)\n\n    def cache_swap(\n        self,\n        blocks_to_swap_in: Dict[int, int],\n        blocks_to_swap_out: Dict[int, int],\n        blocks_to_copy: Dict[int, List[int]],\n    ) -> None:\n        # Issue cache operations.\n        issued_cache_op = False\n        if blocks_to_swap_in:\n            self.cache_engine.swap_in(blocks_to_swap_in)\n            issued_cache_op = True\n        if blocks_to_swap_out:\n            self.cache_engine.swap_out(blocks_to_swap_out)\n            issued_cache_op = True\n        if blocks_to_copy:\n            self.cache_engine.copy(blocks_to_copy)\n            issued_cache_op = True\n\n        cache_events = self.cache_events if issued_cache_op else None\n\n        # Wait for cache operations to finish.\n        # TODO(woosuk): Profile swapping overhead and optimize if needed.\n        if cache_events is not None:\n            for event in cache_events:\n                event.wait()\n\n    @torch.inference_mode()\n    def execute_model(\n        self,\n        seq_group_metadata_list: List[SequenceGroupMetadata],\n        blocks_to_swap_in: Dict[int, int],\n        blocks_to_swap_out: Dict[int, int],\n        blocks_to_copy: Dict[int, List[int]],\n    ) -> SamplerOutput:\n        num_seq_groups = len(seq_group_metadata_list)\n        self.cache_swap(blocks_to_swap_in, blocks_to_swap_out, blocks_to_copy)\n\n        # If there is no input, we don't need to execute the model.\n        if num_seq_groups == 0:\n            return {}\n        output = self.model_runner.execute_model(seq_group_metadata_list, self.gpu_cache)\n        return output\n\n        # # Prepare input tensors.\n        # # NOTE(shengguangming): currently we pad in our dataloader and unpad it in pre_process_input, j\n        # # we can just input un-padded sequence for better performance\n        # input_tokens, input_positions, input_metadata = self._prepare_inputs(seq_group_metadata_list)\n\n        # # Execute the model.\n        # output = self.model(\n        #     input_ids=input_tokens,\n        #     positions=input_positions,\n        #     kv_caches=self.gpu_cache,\n        #     input_metadata=input_metadata,\n        #     cache_events=cache_events,\n        # )\n        # return output\n\n    # assume the input is .state_dict()\n    def sync_model_weights(self, actor_weights: Dict):\n        load_weights(actor_weights, self.model_runner.model)\n\n    def offload_model_weights(self) -> None:\n        if self.cpu_model == None:\n            self.cpu_model = {}\n            for name, params in self.model_runner.model.named_parameters():\n                self.cpu_model[name] = torch.empty_like(params, device='cpu')\n                params.data = self.cpu_model[name]\n        else:\n            for name, params in self.model_runner.model.named_parameters():\n                params.data = self.cpu_model[name]\n\n    def add_lora(self, lora_request: LoRARequest) -> bool:\n        return self.model_runner.add_lora(lora_request)\n\n    def remove_lora(self, lora_id: int) -> bool:\n        return self.model_runner.remove_lora(lora_id)\n\n    def list_loras(self) -> Set[int]:\n        return self.model_runner.list_loras()\n\n\ndef _init_distributed_environment(\n    parallel_config: ParallelConfig,\n    rank: int,\n    distributed_init_method: Optional[str] = None,\n) -> None:\n    \"\"\"Initialize the distributed environment.\"\"\"\n    if torch.distributed.is_initialized():\n        print('The distributed environment has been initialized before vLLM')\n    elif not distributed_init_method:\n        raise ValueError(\"distributed_init_method must be set if torch.distributed \"\n                         \"is not already initialized\")\n    else:\n        torch.distributed.init_process_group(\n            backend=\"nccl\",\n            world_size=parallel_config.world_size,\n            rank=rank,\n            # init_method=distributed_init_method,\n        )\n\n    # A small all_reduce for warmup.\n    torch.distributed.all_reduce(torch.zeros(1).cuda())\n    # TODO (shengguangming): maybe we should also flag the megatron is initialized\n    if torch.distributed.get_world_size() > 1:\n        initialize_model_parallel_from_megatron(tensor_model_parallel_size=parallel_config.tensor_parallel_size)\n    else:\n        initialize_model_parallel()\n\n\ndef _pad_to_alignment(x: List[int], multiple_of: int, pad: int) -> List[int]:\n    return x + [pad] * ((-len(x)) % multiple_of)\n\n\ndef _pad_to_max(x: List[int], max_len: int, pad: int) -> List[int]:\n    return x + [pad] * (max_len - len(x))\n\n\ndef _check_if_gpu_supports_dtype(torch_dtype: torch.dtype):\n    # Check if the GPU supports the dtype.\n    if torch_dtype == torch.bfloat16:\n        compute_capability = torch.cuda.get_device_capability()\n        if compute_capability[0] < 8:\n            gpu_name = torch.cuda.get_device_name()\n            raise ValueError(\"Bfloat16 is only supported on GPUs with compute capability \"\n                             f\"of at least 8.0. Your {gpu_name} GPU has compute capability \"\n                             f\"{compute_capability[0]}.{compute_capability[1]}.\")\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/arg_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/arg_utils.py\n\nimport os\nimport argparse\nimport dataclasses\nfrom dataclasses import dataclass\nfrom typing import List, Optional, Union\n\nimport torch.nn as nn\n\nfrom transformers import PretrainedConfig\nfrom .config import ModelConfig, LoadConfig\n\nfrom vllm.config import (CacheConfig, DecodingConfig, DeviceConfig, EngineConfig, LoRAConfig, ParallelConfig,\n                         SchedulerConfig, SpeculativeConfig, TokenizerPoolConfig, VisionLanguageConfig)\nfrom vllm.model_executor.layers.quantization import QUANTIZATION_METHODS\nfrom vllm.utils import str_to_int_tuple\n\n\ndef nullable_str(val: str):\n    if not val or val == \"None\":\n        return None\n    return val\n\n\n@dataclass\nclass EngineArgs:\n    \"\"\"Arguments for vLLM engine.\"\"\"\n    model_hf_config: PretrainedConfig = None\n    skip_tokenizer_init: bool = False\n    served_model_name: Optional[Union[str, List[str]]] = None  # TODO\n    download_dir: Optional[str] = None\n    load_format: str = 'auto'\n    dtype: str = 'auto'\n    kv_cache_dtype: str = 'auto'\n    quantization_param_path: Optional[str] = None\n    seed: int = 0\n    max_model_len: Optional[int] = None\n    worker_use_ray: bool = False\n    pipeline_parallel_size: int = 1\n    tensor_parallel_size: int = 1\n    max_parallel_loading_workers: Optional[int] = None\n    block_size: int = 16\n    enable_prefix_caching: bool = False\n    use_v2_block_manager: bool = False\n    swap_space: int = 4  # GiB\n    gpu_memory_utilization: float = 0.90\n    max_num_batched_tokens: Optional[int] = None\n    max_num_seqs: int = 256\n    max_logprobs: int = 5  # OpenAI default value\n    disable_log_stats: bool = False\n    revision: Optional[str] = None\n    code_revision: Optional[str] = None\n    tokenizer_revision: Optional[str] = None\n    quantization: Optional[str] = None\n    enforce_eager: bool = False\n    max_context_len_to_capture: Optional[int] = None\n    max_seq_len_to_capture: int = 8192\n    disable_custom_all_reduce: bool = False\n    tokenizer_pool_size: int = 0\n    tokenizer_pool_type: str = \"ray\"\n    tokenizer_pool_extra_config: Optional[dict] = None\n    enable_lora: bool = False\n    max_loras: int = 1\n    max_lora_rank: int = 16\n    fully_sharded_loras: bool = False\n    lora_extra_vocab_size: int = 256\n    lora_dtype = 'auto'\n    max_cpu_loras: Optional[int] = None\n    device: str = 'auto'\n    ray_workers_use_nsight: bool = False\n    num_gpu_blocks_override: Optional[int] = None\n    num_lookahead_slots: int = 0\n    model_loader_extra_config: Optional[dict] = None\n\n    # Related to Vision-language models such as llava\n    image_input_type: Optional[str] = None\n    image_token_id: Optional[int] = None\n    image_input_shape: Optional[str] = None\n    image_feature_size: Optional[int] = None\n    scheduler_delay_factor: float = 0.0\n    enable_chunked_prefill: bool = False\n\n    guided_decoding_backend: str = 'outlines'\n    # Speculative decoding configuration.\n    speculative_model: Optional[str] = None\n    num_speculative_tokens: Optional[int] = None\n    speculative_max_model_len: Optional[int] = None\n    ngram_prompt_lookup_max: Optional[int] = None\n    ngram_prompt_lookup_min: Optional[int] = None\n\n    @staticmethod\n    def add_cli_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n        \"\"\"Shared CLI arguments for vLLM engine.\"\"\"\n        # Model arguments\n        # TODO(shengguangming): delete the unused args\n        parser.add_argument('--model',\n                            type=str,\n                            default='facebook/opt-125m',\n                            help='name or path of the huggingface model to use')\n        parser.add_argument('--tokenizer',\n                            type=str,\n                            default=EngineArgs.tokenizer,\n                            help='name or path of the huggingface tokenizer to use')\n        parser.add_argument('--revision',\n                            type=str,\n                            default=None,\n                            help='the specific model version to use. It can be a branch '\n                            'name, a tag name, or a commit id. If unspecified, will use '\n                            'the default version.')\n        parser.add_argument('--tokenizer-revision',\n                            type=str,\n                            default=None,\n                            help='the specific tokenizer version to use. It can be a branch '\n                            'name, a tag name, or a commit id. If unspecified, will use '\n                            'the default version.')\n        parser.add_argument('--tokenizer-mode',\n                            type=str,\n                            default=EngineArgs.tokenizer_mode,\n                            choices=['auto', 'slow'],\n                            help='tokenizer mode. \"auto\" will use the fast '\n                            'tokenizer if available, and \"slow\" will '\n                            'always use the slow tokenizer.')\n        parser.add_argument('--trust-remote-code', action='store_true', help='trust remote code from huggingface')\n        parser.add_argument('--download-dir',\n                            type=str,\n                            default=EngineArgs.download_dir,\n                            help='directory to download and load the weights, '\n                            'default to the default cache dir of '\n                            'huggingface')\n        parser.add_argument('--load-format',\n                            type=str,\n                            default=EngineArgs.load_format,\n                            choices=['auto', 'pt', 'safetensors', 'npcache', 'dummy'],\n                            help='The format of the model weights to load. '\n                            '\"auto\" will try to load the weights in the safetensors format '\n                            'and fall back to the pytorch bin format if safetensors format '\n                            'is not available. '\n                            '\"pt\" will load the weights in the pytorch bin format. '\n                            '\"safetensors\" will load the weights in the safetensors format. '\n                            '\"npcache\" will load the weights in pytorch format and store '\n                            'a numpy cache to speed up the loading. '\n                            '\"dummy\" will initialize the weights with random values, '\n                            'which is mainly for profiling.')\n        parser.add_argument('--dtype',\n                            type=str,\n                            default=EngineArgs.dtype,\n                            choices=['auto', 'half', 'float16', 'bfloat16', 'float', 'float32'],\n                            help='data type for model weights and activations. '\n                            'The \"auto\" option will use FP16 precision '\n                            'for FP32 and FP16 models, and BF16 precision '\n                            'for BF16 models.')\n        parser.add_argument('--max-model-len',\n                            type=int,\n                            default=None,\n                            help='model context length. If unspecified, '\n                            'will be automatically derived from the model.')\n        # Parallel arguments\n        parser.add_argument('--worker-use-ray',\n                            action='store_true',\n                            help='use Ray for distributed serving, will be '\n                            'automatically set when using more than 1 GPU')\n        parser.add_argument('--pipeline-parallel-size',\n                            '-pp',\n                            type=int,\n                            default=EngineArgs.pipeline_parallel_size,\n                            help='number of pipeline stages')\n        parser.add_argument('--tensor-parallel-size',\n                            '-tp',\n                            type=int,\n                            default=EngineArgs.tensor_parallel_size,\n                            help='number of tensor parallel replicas')\n        # KV cache arguments\n        parser.add_argument('--block-size',\n                            type=int,\n                            default=EngineArgs.block_size,\n                            choices=[8, 16, 32],\n                            help='token block size')\n        # TODO(woosuk): Support fine-grained seeds (e.g., seed per request).\n        parser.add_argument('--seed', type=int, default=EngineArgs.seed, help='random seed')\n        parser.add_argument('--swap-space',\n                            type=int,\n                            default=EngineArgs.swap_space,\n                            help='CPU swap space size (GiB) per GPU')\n        parser.add_argument('--gpu-memory-utilization',\n                            type=float,\n                            default=EngineArgs.gpu_memory_utilization,\n                            help='the percentage of GPU memory to be used for'\n                            'the model executor')\n        parser.add_argument('--max-num-batched-tokens',\n                            type=int,\n                            default=EngineArgs.max_num_batched_tokens,\n                            help='maximum number of batched tokens per '\n                            'iteration')\n        parser.add_argument('--max-num-seqs',\n                            type=int,\n                            default=EngineArgs.max_num_seqs,\n                            help='maximum number of sequences per iteration')\n        parser.add_argument('--disable-log-stats', action='store_true', help='disable logging statistics')\n        # Quantization settings.\n        parser.add_argument('--quantization',\n                            '-q',\n                            type=str,\n                            choices=['awq', None],\n                            default=None,\n                            help='Method used to quantize the weights')\n        return parser\n\n    @classmethod\n    def from_cli_args(cls, args: argparse.Namespace) -> 'EngineArgs':\n        # Get the list of attributes of this dataclass.\n        attrs = [attr.name for attr in dataclasses.fields(cls)]\n        # Set the attributes from the parsed arguments.\n        engine_args = cls(**{attr: getattr(args, attr) for attr in attrs})\n        return engine_args\n\n    def create_engine_config(\n        self,\n    ) -> EngineConfig:\n        device_config = DeviceConfig(self.device)\n        # NOTE(sgm): we only modify ModelConfig, other configs are import from vllm\n        model_config = ModelConfig(self.model_hf_config, self.dtype, self.seed, self.revision, self.code_revision,\n                                   self.tokenizer_revision, self.max_model_len, self.quantization,\n                                   self.quantization_param_path, self.enforce_eager, self.max_context_len_to_capture,\n                                   self.max_seq_len_to_capture, self.max_logprobs, self.skip_tokenizer_init,\n                                   self.served_model_name)\n        cache_config = CacheConfig(self.block_size, self.gpu_memory_utilization,\n                                   self.swap_space, self.kv_cache_dtype, self.num_gpu_blocks_override,\n                                   model_config.get_sliding_window(), self.enable_prefix_caching)\n        parallel_config = ParallelConfig(\n            self.pipeline_parallel_size, self.tensor_parallel_size, self.worker_use_ray,\n            self.max_parallel_loading_workers, self.disable_custom_all_reduce,\n            TokenizerPoolConfig.create_config(\n                self.tokenizer_pool_size,\n                self.tokenizer_pool_type,\n                self.tokenizer_pool_extra_config,\n            ), self.ray_workers_use_nsight)\n\n        # Use the world_size set by TORCHRUN\n        world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n        assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n        parallel_config.world_size = world_size\n\n        # TODO: spec config\n        speculative_config = SpeculativeConfig.maybe_create_spec_config(\n            target_model_config=model_config,\n            target_parallel_config=parallel_config,\n            target_dtype=self.dtype,\n            speculative_model=self.speculative_model,\n            num_speculative_tokens=self.num_speculative_tokens,\n            speculative_max_model_len=self.speculative_max_model_len,\n            enable_chunked_prefill=self.enable_chunked_prefill,\n            use_v2_block_manager=self.use_v2_block_manager,\n            ngram_prompt_lookup_max=self.ngram_prompt_lookup_max,\n            ngram_prompt_lookup_min=self.ngram_prompt_lookup_min,\n        )\n\n        scheduler_config = SchedulerConfig(\n            self.max_num_batched_tokens,\n            self.max_num_seqs,\n            model_config.max_model_len,\n            self.use_v2_block_manager,\n            num_lookahead_slots=(self.num_lookahead_slots\n                                 if speculative_config is None else speculative_config.num_lookahead_slots),\n            delay_factor=self.scheduler_delay_factor,\n            enable_chunked_prefill=self.enable_chunked_prefill,\n        )\n\n        lora_config = LoRAConfig(max_lora_rank=self.max_lora_rank,\n                                 max_loras=self.max_loras,\n                                 fully_sharded_loras=self.fully_sharded_loras,\n                                 lora_extra_vocab_size=self.lora_extra_vocab_size,\n                                 lora_dtype=self.lora_dtype,\n                                 max_cpu_loras=self.max_cpu_loras if self.max_cpu_loras and self.max_cpu_loras > 0 else\n                                 None) if self.enable_lora else None\n\n        load_config = LoadConfig(\n            load_format=self.load_format,\n            download_dir=self.download_dir,\n            model_loader_extra_config=self.model_loader_extra_config,\n        )\n\n        if self.image_input_type:\n            if (not self.image_token_id or not self.image_input_shape or not self.image_feature_size):\n                raise ValueError('Specify `image_token_id`, `image_input_shape` and '\n                                 '`image_feature_size` together with `image_input_type`.')\n            vision_language_config = VisionLanguageConfig(\n                image_input_type=VisionLanguageConfig.get_image_input_enum_type(self.image_input_type),\n                image_token_id=self.image_token_id,\n                image_input_shape=str_to_int_tuple(self.image_input_shape),\n                image_feature_size=self.image_feature_size,\n            )\n        else:\n            vision_language_config = None\n\n        decoding_config = DecodingConfig(guided_decoding_backend=self.guided_decoding_backend)\n\n        return EngineConfig(model_config=model_config,\n                            cache_config=cache_config,\n                            parallel_config=parallel_config,\n                            scheduler_config=scheduler_config,\n                            device_config=device_config,\n                            lora_config=lora_config,\n                            vision_language_config=vision_language_config,\n                            speculative_config=speculative_config,\n                            load_config=load_config,\n                            decoding_config=decoding_config)\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/config.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/config.py\n\nimport enum\nimport json\nfrom typing import List, Optional, Union\nfrom dataclasses import dataclass, field, fields\n\nfrom transformers import PretrainedConfig\n\nfrom vllm.logger import init_logger\nfrom vllm.model_executor.layers.quantization import get_quantization_config\nfrom vllm.transformers_utils.config import get_hf_text_config\nfrom vllm.utils import is_hip\n# Add for verl\nfrom vllm.config import ModelConfig, _get_and_verify_dtype, _get_and_verify_max_len\n\nGPTQMarlinConfig = get_quantization_config(\"gptq_marlin\")\n\nlogger = init_logger(__name__)\n\n_GB = 1 << 30\n\n\nclass ModelConfig(ModelConfig):\n    \"\"\"Configuration for the model.\n\n    Args:\n        model: Name or path of the huggingface model to use.\n        tokenizer: Name or path of the huggingface tokenizer to use.\n        tokenizer_mode: Tokenizer mode. \"auto\" will use the fast tokenizer if\n            available, and \"slow\" will always use the slow tokenizer.\n        trust_remote_code: Trust remote code (e.g., from HuggingFace) when\n            downloading the model and tokenizer.\n        download_dir: Directory to download and load the weights, default to the\n            default cache directory of huggingface.\n        load_format: The format of the model weights to load:\n            \"auto\" will try to load the weights in the safetensors format and\n                fall back to the pytorch bin format if safetensors format is\n                not available.\n            \"pt\" will load the weights in the pytorch bin format.\n            \"safetensors\" will load the weights in the safetensors format.\n            \"npcache\" will load the weights in pytorch format and store\n                a numpy cache to speed up the loading.\n            \"dummy\" will initialize the weights with random values, which is\n                mainly for profiling.\n        dtype: Data type for model weights and activations. The \"auto\" option\n            will use FP16 precision for FP32 and FP16 models, and BF16 precision\n            for BF16 models.\n        seed: Random seed for reproducibility.\n        revision: The specific model version to use. It can be a branch name,\n            a tag name, or a commit id. If unspecified, will use the default\n            version.\n        code_revision: The specific revision to use for the model code on\n            Hugging Face Hub. It can be a branch name, a tag name, or a\n            commit id. If unspecified, will use the default version.\n        tokenizer_revision: The specific tokenizer version to use. It can be a\n            branch name, a tag name, or a commit id. If unspecified, will use\n            the default version.\n        max_model_len: Maximum length of a sequence (including prompt and\n            output). If None, will be derived from the model.\n        quantization: Quantization method that was used to quantize the model\n            weights. If None, we assume the model weights are not quantized.\n        quantization_param_path: Path to JSON file containing scaling factors.\n            Used to load KV cache scaling factors into the model when KV cache\n            type is FP8_E4M3 on ROCm (AMD GPU). In the future these will also\n            be used to load activation and weight scaling factors when the\n            model dtype is FP8_E4M3 on ROCm.\n        enforce_eager: Whether to enforce eager execution. If True, we will\n            disable CUDA graph and always execute the model in eager mode.\n            If False, we will use CUDA graph and eager execution in hybrid.\n        max_context_len_to_capture: Maximum context len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode (DEPRECATED. Use max_seq_len_to_capture instead).\n        max_seq_len_to_capture: Maximum sequence len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode\n        skip_tokenizer_init: If true, skip initialization of tokenizer and\n            detokenizer.\n        served_model_name: The model name used in metrics tag `model_name`,\n            matches the model name exposed via the APIs. If multiple model \n            names provided, the first name will be used. If not specified, \n            the model name will be the same as `model`.\n    \"\"\"\n\n    def __init__(\n        self,\n        hf_config: PretrainedConfig,\n        dtype: str,\n        seed: int,\n        revision: Optional[str] = None,\n        code_revision: Optional[str] = None,\n        tokenizer_revision: Optional[str] = None,\n        max_model_len: Optional[int] = None,\n        quantization: Optional[str] = None,\n        quantization_param_path: Optional[str] = None,\n        enforce_eager: bool = False,\n        max_context_len_to_capture: Optional[int] = None,\n        max_seq_len_to_capture: Optional[int] = None,\n        max_logprobs: int = 5,\n        skip_tokenizer_init: bool = False,\n        served_model_name: Optional[Union[str, List[str]]] = None,\n    ) -> None:\n        self.model = hf_config._name_or_path\n        self.tokenizer = hf_config._name_or_path\n        self.seed = seed\n        self.revision = revision\n        self.code_revision = code_revision\n        self.tokenizer_revision = tokenizer_revision\n        self.quantization = quantization\n        self.quantization_param_path = quantization_param_path\n        self.enforce_eager = enforce_eager\n        self.max_context_len_to_capture = max_context_len_to_capture\n        if self.max_context_len_to_capture is not None:\n            raise ValueError(\"`max_context_len_to_capture` is deprecated. \"\n                             \"Use `max_seq_len_to_capture` instead.\")\n        self.max_seq_len_to_capture = (max_seq_len_to_capture or max_context_len_to_capture)\n        self.max_logprobs = max_logprobs\n        self.skip_tokenizer_init = skip_tokenizer_init\n\n        # self.hf_config = get_config(model, trust_remote_code, revision)\n        self.hf_config = hf_config\n        self.hf_text_config = get_hf_text_config(hf_config)\n        # TODO: for multimodal model\n        self.dtype = _get_and_verify_dtype(self.hf_config, dtype)\n        self.max_model_len = _get_and_verify_max_len(self.hf_config, max_model_len)\n        # self.served_model_name = get_served_model_name(model,\n        #                                                served_model_name)\n        # self._verify_load_format()\n        # self._verify_tokenizer_mode()\n        self._verify_quantization()\n        self._verify_cuda_graph()\n\n\nclass LoadFormat(str, enum.Enum):\n    AUTO = 'auto'\n    MEGATRON = \"megatron\"\n    HF = \"hf\"\n    DTENSOR = 'dtensor'\n    DUMMY_HF = 'dummy_hf'\n    DUMMY_MEGATRON = 'dummy_megatron'\n    DUMMY_DTENSOR = 'dummy_dtensor'\n\n\n@dataclass\nclass LoadConfig:\n    \"\"\"\n        download_dir: Directory to download and load the weights, default to the\n            default cache directory of huggingface.\n        load_format: The format of the model weights to load:\n            \"auto\" will try to load the weights in the safetensors format and\n                fall back to the pytorch bin format if safetensors format is\n                not available.\n            \"pt\" will load the weights in the pytorch bin format.\n            \"safetensors\" will load the weights in the safetensors format.\n            \"npcache\" will load the weights in pytorch format and store\n                a numpy cache to speed up the loading.\n            \"dummy\" will initialize the weights with random values, which is\n                mainly for profiling.\n            \"tensorizer\" will use CoreWeave's tensorizer library for\n                fast weight loading.\n    \"\"\"\n\n    load_format: Union[str, LoadFormat, \"BaseModelLoader\"] = LoadFormat.AUTO\n    download_dir: Optional[str] = None\n    model_loader_extra_config: Optional[Union[str, dict]] = field(default_factory=dict)\n\n    def __post_init__(self):\n        model_loader_extra_config = self.model_loader_extra_config or {}\n        if isinstance(model_loader_extra_config, str):\n            self.model_loader_extra_config = json.loads(model_loader_extra_config)\n        self._verify_load_format()\n\n    def _verify_load_format(self) -> None:\n        if not isinstance(self.load_format, str):\n            return\n\n        load_format = self.load_format.lower()\n        self.load_format = LoadFormat(load_format)\n\n        rocm_not_supported_load_format: List[str] = []\n        if is_hip() and load_format in rocm_not_supported_load_format:\n            rocm_supported_load_format = [\n                f for f in LoadFormat.__members__ if (f not in rocm_not_supported_load_format)\n            ]\n            raise ValueError(f\"load format '{load_format}' is not supported in ROCm. \"\n                             f\"Supported load formats are \"\n                             f\"{rocm_supported_load_format}\")\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/dtensor_weight_loaders.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models\n\nfrom typing import Dict, Iterable, Tuple\nimport torch\nimport torch.nn as nn\nfrom torch.distributed._tensor import DTensor, Shard, Replicate\n\nfrom vllm.model_executor.layers.linear import *\nfrom vllm.model_executor.models import ModelRegistry\nfrom vllm.model_executor.model_loader.weight_utils import default_weight_loader\n\n\ndef gemma_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        for (param_name, shard_name, shard_id) in stacked_params_mapping:\n            if shard_name not in name:\n                continue\n            stacked_name = name.replace(shard_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if stacked_name.endswith(\".bias\") and stacked_name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[stacked_name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # lm_head is not used in vllm as it is tied with embed_token.\n            # To prevent errors, skip loading lm_head.weight.\n            if \"lm_head.weight\" in name:\n                continue\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            # GemmaRMSNorm is different from Llama's in that it multiplies\n            # (1 + weight) to the output, instead of just weight.\n            if \"norm.weight\" in name:\n                local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n\n                norm_weight = local_loaded_weight + 1.0\n                param = params_dict[name]\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(param, norm_weight.to(dtype=param.dtype))\n            else:\n                local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n                param = params_dict[name]\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef gptbigcode_dtensor_load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"lm_head.weight\" in name:\n            continue\n        if \".attn.bias\" in name:\n            # Skip attention mask.\n            # NOTE: \"c_attn.bias\" should not be skipped.\n            continue\n        local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n        param = params_dict[name]\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef starcoder2_dtensor_load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n    ]\n\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n\n        for (param_name, weight_name, shard_id) in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef llama_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\".qkv_proj\", \".q_proj\", \"q\"),\n        (\".qkv_proj\", \".k_proj\", \"k\"),\n        (\".qkv_proj\", \".v_proj\", \"v\"),\n        (\".gate_up_proj\", \".gate_proj\", 0),\n        (\".gate_up_proj\", \".up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if (\"rotary_emb.cos_cached\" in name or \"rotary_emb.sin_cached\" in name):\n            # Models trained using ColossalAI may include these tensors in\n            # the checkpoint. Skip them.\n            continue\n        # With tie_word_embeddings, we can skip lm_head.weight\n        # The weight might appear unnecessarily in the files if the model is\n        # processed with quantization, LoRA, fine-tuning, etc.\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for (param_name, weight_name, shard_id) in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight)\n\n\ndef qwen2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for (param_name, weight_name, shard_id) in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef gpt2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    pass\n\n\ndef redistribute_dtensor(param_name: str, loaded_weights: DTensor, parallelize_plan: Dict = None):\n    param_name = _process_parameter_names(name=param_name)\n    if parallelize_plan is not None:\n        assert param_name in parallelize_plan.keys(), \\\n            f\"param name: {param_name} not in parallelize_plan :{parallelize_plan.keys()}\"\n        placement = parallelize_plan[param_name]\n        local_loaded_weights = loaded_weights.redistribute(device_mesh=loaded_weights.device_mesh,\n                                                           placements=placement).to_local()\n    else:\n        local_loaded_weights = loaded_weights.full_tensor()\n    return local_loaded_weights\n\n\ndef _process_parameter_names(name):\n    # Remove '.weight' if it exists at the end of the string\n    if name.endswith(\".weight\"):\n        name = name[:-7]\n\n    # Remove 'model.layers.x.' or 'model.' prefix\n    if \"model.layers\" in name:\n        parts = name.split('.')\n        # Reconstruct the string without 'model.layers.x.'\n        name = '.'.join(parts[3:])  # parts[0] is 'model', parts[1] is 'layers', parts[2] is 'x'\n    elif name.startswith(\"model.\"):\n        name = name[6:]  # Remove 'model.'\n\n    return name\n\n\n__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__ = {\n    'GPT2LMHeadModel': gpt2_dtensor_weight_loader,\n    'LlamaForCausalLM': llama_dtensor_weight_loader,\n    'LLaMAForCausalLM': llama_dtensor_weight_loader,\n    'MistralForCausalLM': llama_dtensor_weight_loader,  # mistral is the same as llama in vLLM\n    'InternLMForCausalLM': llama_dtensor_weight_loader,\n    'AquilaModel': llama_dtensor_weight_loader,\n    'AquilaForCausalLM': llama_dtensor_weight_loader,\n    'Phi3ForCausalLM': llama_dtensor_weight_loader,\n    'GemmaForCausalLM': gemma_dtensor_weight_loader,\n    'GPTBigCodeForCausalLM': gptbigcode_dtensor_load_weights,\n    'Starcoder2ForCausalLM': starcoder2_dtensor_load_weights,\n    'Qwen2ForCausalLM': qwen2_dtensor_weight_loader\n}\n\n\n# the actor model is .state_dict()\n# Load dtensor weights\ndef load_dtensor_weights(actor_weights: Dict, vllm_model: nn.Module):\n    weight_loader = _get_model_weight_loader(vllm_model.__class__.__name__)\n    weight_loader(actor_weights, vllm_model)\n    # NOTE(sgm) to reduce peak memory usage, we offload vllm model to cpu\n    # after init, and we need this after sync model weights for in first iter.\n    vllm_model = vllm_model.cuda()\n\n\ndef _get_model_weight_loader(arch: str):\n    if arch in __MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__:\n        return __MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__.keys()}\")\n\n\n# NOTE(sgm): we use per-parameter weight loader in each vllm sub\ndef update_dtensor_weight_loader():\n    pass\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/hf_weight_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models\n\nfrom typing import Dict, Union, Optional, Iterable, Tuple\n\nimport torch\nimport torch.nn as nn\n\nfrom vllm.model_executor.model_loader.utils import set_default_torch_dtype\nfrom vllm.model_executor.model_loader.weight_utils import default_weight_loader\n\n\ndef update_hf_weight_loader():\n    from vllm.model_executor.models.gemma import GemmaForCausalLM\n    GemmaForCausalLM.load_weights = gemma_load_weights\n\n\ndef gemma_load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(self.named_parameters())\n    loaded_params = set()\n    for name, loaded_weight in weights:\n        for (param_name, shard_name, shard_id) in stacked_params_mapping:\n            if shard_name not in name:\n                continue\n            name = name.replace(shard_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, loaded_weight, shard_id)\n            break\n        else:\n            # lm_head is not used in vllm as it is tied with embed_token.\n            # To prevent errors, skip loading lm_head.weight.\n            if \"lm_head.weight\" in name:\n                continue\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            # GemmaRMSNorm is different from Llama's in that it multiplies\n            # (1 + weight) to the output, instead of just weight.\n            if \"norm.weight\" in name:\n                norm_weight = loaded_weight + 1.0  # prevent inplace modify actor weights\n                param = params_dict[name]\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(param, norm_weight)\n            else:\n                param = params_dict[name]\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(param, loaded_weight)\n        loaded_params.add(name)\n    unloaded_params = params_dict.keys() - loaded_params\n    if unloaded_params:\n        raise RuntimeError(\"Some weights are not initialized from checkpoints: \"\n                           f\"{unloaded_params}\")\n\n\ndef load_hf_weights(actor_weights: Dict, vllm_model: nn.Module):\n    assert isinstance(actor_weights, Dict)\n    with set_default_torch_dtype(next(vllm_model.parameters()).dtype):  # TODO\n        vllm_model.load_weights(actor_weights.items())\n    for _, module in vllm_model.named_modules():\n        quant_method = getattr(module, \"quant_method\", None)\n        if quant_method is not None:\n            quant_method.process_weights_after_loading(module)\n        # FIXME: Remove this after Mixtral is updated\n        # to use quant_method.\n        if hasattr(module, \"process_weights_after_loading\"):\n            module.process_weights_after_loading()\n    vllm_model = vllm_model.cuda()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/llm.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/llm.py\n\nfrom typing import Dict, List, Optional, Tuple, Union\n\nfrom tqdm import tqdm\nfrom transformers import PreTrainedTokenizer, PreTrainedTokenizerFast\nfrom transformers import PretrainedConfig\nimport torch.nn as nn\nfrom .arg_utils import EngineArgs\nfrom .llm_engine_sp import LLMEngine\nfrom vllm.lora.request import LoRARequest\nfrom vllm.outputs import RequestOutput\nfrom vllm.sampling_params import SamplingParams\nfrom vllm.sequence import MultiModalData\nfrom vllm.usage.usage_lib import UsageContext\nfrom vllm.utils import Counter\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\nfrom verl.workers.rollout.tokenizer import HybridEngineBaseTokenizer\n\n\nclass LLM:\n    \"\"\"An LLM for generating texts from given prompts and sampling parameters.\n\n    This class includes a tokenizer, a language model (possibly distributed\n    across multiple GPUs), and GPU memory space allocated for intermediate\n    states (aka KV cache). Given a batch of prompts and sampling parameters,\n    this class generates texts from the model, using an intelligent batching\n    mechanism and efficient memory management.\n\n    NOTE: This class is intended to be used for offline inference. For online\n    serving, use the `AsyncLLMEngine` class instead.\n    NOTE: For the comprehensive list of arguments, see `EngineArgs`.\n\n    Args:\n        model: A HuggingFace Transformers model instance.\n        tokenizer: A HuggingFace Transformers tokenizer instance.\n        tokenizer_mode: The tokenizer mode. \"auto\" will use the fast tokenizer\n            if available, and \"slow\" will always use the slow tokenizer.\n        trust_remote_code: Trust remote code (e.g., from HuggingFace) when\n            downloading the model and tokenizer.\n        tensor_parallel_size: The number of GPUs to use for distributed\n            execution with tensor parallelism.\n        dtype: The data type for the model weights and activations. Currently,\n            we support `float32`, `float16`, and `bfloat16`. If `auto`, we use\n            the `torch_dtype` attribute specified in the model config file.\n            However, if the `torch_dtype` in the config is `float32`, we will\n            use `float16` instead.\n        quantization: The method used to quantize the model weights. Currently,\n            we support \"awq\". If None, we assume the model weights are not\n            quantized and use `dtype` to determine the data type of the weights.\n        revision: The specific model version to use. It can be a branch name,\n            a tag name, or a commit id.\n        tokenizer_revision: The specific tokenizer version to use. It can be a\n            branch name, a tag name, or a commit id.\n        seed: The seed to initialize the random number generator for sampling.\n        gpu_memory_utilization: The ratio (between 0 and 1) of GPU memory to\n            reserve for the model weights, activations, and KV cache. Higher\n            values will increase the KV cache size and thus improve the model's\n            throughput. However, if the value is too high, it may cause out-of-\n            memory (OOM) errors.\n        swap_space: The size (GiB) of CPU memory per GPU to use as swap space.\n            This can be used for temporarily storing the states of the requests\n            when their `best_of` sampling parameters are larger than 1. If all\n            requests will have `best_of=1`, you can safely set this to 0.\n            Otherwise, too small values may cause out-of-memory (OOM) errors.\n        enforce_eager: Whether to enforce eager execution. If True, we will\n            disable CUDA graph and always execute the model in eager mode.\n            If False, we will use CUDA graph and eager execution in hybrid.\n        max_context_len_to_capture: Maximum context len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode.\n        disable_custom_all_reduce: See ParallelConfig\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast, HybridEngineBaseTokenizer],\n        model_hf_config: PretrainedConfig,\n        tokenizer_mode: str = \"auto\",\n        trust_remote_code: bool = False,\n        tensor_parallel_size: int = 1,\n        dtype: str = \"auto\",\n        quantization: Optional[str] = None,\n        revision: Optional[str] = None,\n        tokenizer_revision: Optional[str] = None,\n        seed: int = 0,\n        gpu_memory_utilization: float = 0.9,\n        swap_space: int = 4,\n        enforce_eager: bool = False,\n        max_context_len_to_capture: int = None,\n        disable_custom_all_reduce: bool = False,\n        load_format = 'auto',\n        **kwargs,\n    ) -> None:\n        if \"disable_log_stats\" not in kwargs:\n            kwargs[\"disable_log_stats\"] = True\n        engine_args = EngineArgs(\n            model_hf_config=model_hf_config,\n            tensor_parallel_size=tensor_parallel_size,\n            dtype=dtype,\n            quantization=quantization,\n            revision=revision,\n            tokenizer_revision=tokenizer_revision,\n            seed=seed,\n            gpu_memory_utilization=gpu_memory_utilization,\n            swap_space=swap_space,\n            enforce_eager=enforce_eager,\n            max_context_len_to_capture=max_context_len_to_capture,\n            disable_custom_all_reduce=disable_custom_all_reduce,\n            load_format=load_format,\n            **kwargs,\n        )\n        tokenizer_cls = (PreTrainedTokenizer, PreTrainedTokenizerFast, HybridEngineBaseTokenizer)\n        if not isinstance(tokenizer, tokenizer_cls):\n            raise ValueError(\n                f\"Unexpected tokenizer type: {type(tokenizer)}. Must be\"\n                \"one of the following: PreTrainedTokenizer, PreTrainedTokenizerFast, verl.workers.rollout.HybridEngineBaseTokenizer\"\n            )\n        self.llm_engine = LLMEngine.from_engine_args(model, tokenizer, engine_args)\n        self.request_counter = Counter()\n\n    def init_cache_engine(self):\n        self.llm_engine.init_cache_engine()\n\n    def free_cache_engine(self):\n        self.llm_engine.free_cache_engine()\n\n    def get_tokenizer(self) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:\n        return self.llm_engine.tokenizer\n\n    def set_tokenizer(\n        self,\n        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],\n    ) -> None:\n        self.llm_engine.tokenizer = tokenizer\n\n    def generate(\n        self,\n        prompts: Optional[Union[str, List[str]]] = None,\n        sampling_params: Optional[Union[SamplingParams, List[SamplingParams]]] = None,\n        prompt_token_ids: Optional[List[List[int]]] = None,\n        use_tqdm: bool = True,\n        lora_request: Optional[LoRARequest] = None,\n        multi_modal_data: Optional[MultiModalData] = None,\n    ) -> List[RequestOutput]:\n        \"\"\"Generates the completions for the input prompts.\n\n        NOTE: This class automatically batches the given prompts, considering\n        the memory constraint. For the best performance, put all of your prompts\n        into a single list and pass it to this method.\n\n        Args:\n            prompts: A list of prompts to generate completions for.\n            sampling_params: The sampling parameters for text generation. If\n                None, we use the default sampling parameters. \n                When it is a single value, it is applied to every prompt. \n                When it is a list, the list must have the same length as the \n                prompts and it is paired one by one with the prompt.\n            prompt_token_ids: A list of token IDs for the prompts. If None, we\n                use the tokenizer to convert the prompts to token IDs.\n            use_tqdm: Whether to use tqdm to display the progress bar.\n            lora_request: LoRA request to use for generation, if any.\n            multi_modal_data: Multi modal data.\n\n        Returns:\n            A list of `RequestOutput` objects containing the generated\n            completions in the same order as the input prompts.\n        \"\"\"\n        if prompts is None and prompt_token_ids is None:\n            raise ValueError(\"Either prompts or prompt_token_ids must be \"\n                             \"provided.\")\n        if self.llm_engine.model_config.skip_tokenizer_init \\\n            and prompts is not None:\n            raise ValueError(\"prompts must be None if skip_tokenizer_init \"\n                             \"is True\")\n        if isinstance(prompts, str):\n            # Convert a single prompt to a list.\n            prompts = [prompts]\n        if (prompts is not None and prompt_token_ids is not None and len(prompts) != len(prompt_token_ids)):\n            raise ValueError(\"The lengths of prompts and prompt_token_ids \"\n                             \"must be the same.\")\n\n        if prompts is not None:\n            num_requests = len(prompts)\n        else:\n            assert prompt_token_ids is not None\n            num_requests = len(prompt_token_ids)\n\n        if sampling_params is None:\n            # Use default sampling params.\n            sampling_params = SamplingParams()\n\n        elif isinstance(sampling_params, list) and len(sampling_params) != num_requests:\n            raise ValueError(\"The lengths of prompts and sampling_params \"\n                             \"must be the same.\")\n        if multi_modal_data:\n            multi_modal_data.data = multi_modal_data.data.to(torch.float16)\n\n        # Add requests to the engine.\n        for i in range(num_requests):\n            prompt = prompts[i] if prompts is not None else None\n            token_ids = None if prompt_token_ids is None else prompt_token_ids[i]\n            if not isinstance(token_ids, list):\n                # NOTE(shengguangming): convert the rollout input into List[str]\n                token_ids = self._pre_process_inputs(token_ids)\n            self._add_request(\n                prompt,\n                sampling_params[i] if isinstance(sampling_params, list) else sampling_params,\n                token_ids,\n                lora_request=lora_request,\n                # Get ith image while maintaining the batch dim.\n                multi_modal_data=MultiModalData(type=multi_modal_data.type, data=multi_modal_data.data[i].unsqueeze(0))\n                if multi_modal_data else None,\n            )\n        return self._run_engine(use_tqdm)\n\n    def _add_request(\n        self,\n        prompt: Optional[str],\n        sampling_params: SamplingParams,\n        prompt_token_ids: Optional[List[int]],\n        lora_request: Optional[LoRARequest] = None,\n        multi_modal_data: Optional[MultiModalData] = None,\n    ) -> None:\n        request_id = str(next(self.request_counter))\n        self.llm_engine.add_request(request_id,\n                                    prompt,\n                                    sampling_params,\n                                    prompt_token_ids,\n                                    lora_request=lora_request,\n                                    multi_modal_data=multi_modal_data)\n\n    def _run_engine(self, use_tqdm: bool) -> List[RequestOutput]:\n        # Initialize tqdm.\n        if use_tqdm:\n            num_requests = self.llm_engine.get_num_unfinished_requests()\n            pbar = tqdm(total=num_requests, desc=\"Processed prompts\", dynamic_ncols=True)\n        # Run the engine.\n        outputs: List[RequestOutput] = []\n        while self.llm_engine.has_unfinished_requests():\n            step_outputs = self.llm_engine.step()\n            for output in step_outputs:\n                if output.finished:\n                    outputs.append(output)\n                    if use_tqdm:\n                        pbar.update(1)\n        if use_tqdm:\n            pbar.close()\n        # Sort the outputs by request ID.\n        # This is necessary because some requests may be finished earlier than\n        # its previous requests.\n        outputs = sorted(outputs, key=lambda x: int(x.request_id))\n        # TODO(shengguangming): maybe we can hack the autoregressive logics without only apply post process for better performance\n        return self._post_process_outputs(outputs)\n\n    # NOTE(shengguangming): add for verl\n    # TODO(sgm): we can optimize it by making the dataloader yield List[int] without padding.\n    def _pre_process_inputs(self, prompt_token_ids: torch.Tensor) -> List[int]:\n        # remove the left padding in the prompt token_id\n        pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n        non_pad_index = torch.nonzero(prompt_token_ids != pad_token_id, as_tuple=False)[0][0]\n        token_ids = prompt_token_ids[non_pad_index:].tolist()\n        return token_ids\n\n    # NOTE(shengguangming): add for verl\n    def _post_process_outputs(self, request_outputs: List[RequestOutput]) -> Tuple[torch.Tensor, torch.Tensor]:\n        output_token_ids = []\n        logprobs = []\n        for request_output in request_outputs:  # List[RequestOutput]\n            outputs = request_output.outputs\n            for output in outputs:  # List[CompletionOutput], usually len == 1\n                output_token_ids.append(torch.tensor(output.token_ids))\n                # TODO(shengguangming): can be optimzied by rewrite the Sampler._get_logprobs() logits\n                logprobs_dicts = output.logprobs\n                if logprobs_dicts is not None:\n                    logprob = []\n                    for logprobs_dict, id in zip(logprobs_dicts, output.token_ids):\n                        logprob.append(logprobs_dict[id].logprob)\n                    logprobs.append(torch.tensor(logprob))\n\n        pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n        output_token_ids = pad_sequence(output_token_ids, batch_first=True, padding_value=pad_token_id)\n        if len(logprobs) > 0:\n            logprobs = pad_sequence(logprobs, batch_first=True, padding_value=pad_token_id)\n        return output_token_ids, logprobs\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.llm_engine.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n    def offload_model_weights(self) -> None:\n        self.llm_engine.offload_model_weights()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/llm_engine_sp.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/llm_engine.py\n\nimport torch\nfrom typing import Dict, Optional, Union, Type\n\nimport vllm\nfrom vllm.config import (CacheConfig, DecodingConfig, DeviceConfig, LoRAConfig, ParallelConfig, SchedulerConfig,\n                         SpeculativeConfig, VisionLanguageConfig)\nfrom vllm.core.scheduler import Scheduler\nfrom vllm.engine.output_processor.interfaces import (SequenceGroupOutputProcessor)\nfrom vllm.engine.output_processor.stop_checker import StopChecker\nfrom vllm.executor.executor_base import ExecutorBase\nfrom vllm.logger import init_logger\nfrom vllm.transformers_utils.detokenizer import Detokenizer\nfrom vllm.engine.metrics import StatLogger\nfrom vllm.usage.usage_lib import (UsageContext, is_usage_stats_enabled, usage_message)\nfrom vllm.utils import Counter\nfrom vllm.engine.llm_engine import _load_generation_config_dict\nfrom vllm.engine.llm_engine import LLMEngine\n\nimport torch.nn as nn\nfrom .arg_utils import EngineArgs\nfrom .tokenizer import TokenizerGroup\nfrom .config import ModelConfig, LoadConfig\n\nlogger = init_logger(__name__)\n_LOCAL_LOGGING_INTERVAL_SEC = 5\n\n\nclass LLMEngine(LLMEngine):\n    \"\"\"An LLM engine that receives requests and generates texts.\n\n    This is the main class for the vLLM engine. It receives requests\n    from clients and generates texts from the LLM. It includes a tokenizer, a\n    language model (possibly distributed across multiple GPUs), and GPU memory\n    space allocated for intermediate states (aka KV cache). This class utilizes\n    iteration-level scheduling and efficient memory management to maximize the\n    serving throughput.\n\n    The `LLM` class wraps this class for offline batched inference and the\n    `AsyncLLMEngine` class wraps this class for online serving.\n\n    NOTE: The config arguments are derived from the `EngineArgs` class. For the\n    comprehensive list of arguments, see `EngineArgs`.\n\n    Args:\n        model: the actor model initialize outside vllm (add for verl)\n        tokenizer: the initialized tokenizer (add for verl)\n        model_config: The configuration related to the LLM model.\n        cache_config: The configuration related to the KV cache memory\n            management.\n        parallel_config: The configuration related to distributed execution.\n        scheduler_config: The configuration related to the request scheduler.\n        distributed_init_method: The initialization method for distributed\n            execution. See `torch.distributed.init_process_group` for details.\n        placement_group: Ray placement group for distributed execution.\n            Required for distributed execution.\n        log_stats: Whether to log statistics.\n    \"\"\"\n\n    def __init__(\n        self,\n        # NOTE(sgm): first two arguments are added for verl\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        tokenizer: nn.Module,\n        # NOTE(sgm): vllm original arguments\n        model_config: ModelConfig,\n        cache_config: CacheConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        vision_language_config: Optional[VisionLanguageConfig],\n        speculative_config: Optional[SpeculativeConfig],\n        decoding_config: Optional[DecodingConfig],\n        executor_class: Type[ExecutorBase],\n        log_stats: bool,\n        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,\n    ) -> None:\n        logger.info(\n            \"Initializing an LLM engine (v%s) with config: \"\n            \"model=%r, speculative_config=%r, tokenizer=%r, \"\n            \"skip_tokenizer_init=%s, tokenizer_mode=%s, revision=%s, \"\n            \"tokenizer_revision=%s, trust_remote_code=%s, dtype=%s, \"\n            \"max_seq_len=%d, download_dir=%r, load_format=%s, \"\n            \"tensor_parallel_size=%d, disable_custom_all_reduce=%s, \"\n            \"quantization=%s, enforce_eager=%s, kv_cache_dtype=%s, \"\n            \"quantization_param_path=%s, device_config=%s, \"\n            \"decoding_config=%r, seed=%d, served_model_name=%s)\",\n            vllm.__version__,\n            model_config.model,\n            speculative_config,\n            model_config.tokenizer,\n            model_config.skip_tokenizer_init,\n            # model_config.tokenizer_mode,\n            model_config.revision,\n            model_config.tokenizer_revision,\n            # model_config.trust_remote_code,\n            model_config.dtype,\n            model_config.max_model_len,\n            load_config.download_dir,\n            load_config.load_format,\n            parallel_config.tensor_parallel_size,\n            parallel_config.disable_custom_all_reduce,\n            model_config.quantization,\n            model_config.enforce_eager,\n            cache_config.cache_dtype,\n            model_config.quantization_param_path,\n            device_config.device,\n            decoding_config,\n            model_config.seed,\n            # model_config.served_model_name,\n        )\n        # TODO(woosuk): Print more configs in debug mode.\n\n        self.model_config = model_config  # TODO: currently is hfconfig\n        self.cache_config = cache_config\n        self.lora_config = lora_config\n        self.vision_language_config = vision_language_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.speculative_config = speculative_config\n        self.load_config = load_config\n        self.decoding_config = decoding_config or DecodingConfig()\n        self.log_stats = log_stats\n\n        # self.model = model # should not store the model, it should be deleted\n        # TODO(shengguangming): maybe we can choose init here or from arguments\n        if not self.model_config.skip_tokenizer_init:\n            # TODO: check tokenizer class\n            self._init_tokenizer(tokenizer)\n            self.detokenizer = Detokenizer(self.tokenizer)\n        else:\n            self.detokenizer = None\n            self.tokenizer = None\n\n        self.seq_counter = Counter()\n        # TODO: don't know what's the usage\n        self.generation_config_fields = _load_generation_config_dict(model_config)\n\n        self.model_executor = executor_class(\n            model=model, # add for spmd_gpu_executor\n            model_config=model_config,\n            cache_config=cache_config,\n            parallel_config=parallel_config,\n            scheduler_config=scheduler_config,\n            device_config=device_config,\n            lora_config=lora_config,\n            vision_language_config=vision_language_config,\n            speculative_config=speculative_config,\n            load_config=load_config,\n        )\n\n        # Profile the memory usage and initialize the cache.\n        self._initialize_kv_caches()\n\n        # If usage stat is enabled, collect relevant info.\n        if is_usage_stats_enabled():\n            from vllm.model_executor.model_loader import (get_architecture_class_name)\n            usage_message.report_usage(\n                get_architecture_class_name(model_config),\n                usage_context,\n                extra_kvs={\n                    # Common configuration\n                    \"dtype\": str(model_config.dtype),\n                    \"tensor_parallel_size\": parallel_config.tensor_parallel_size,\n                    \"block_size\": cache_config.block_size,\n                    \"gpu_memory_utilization\": cache_config.gpu_memory_utilization,\n\n                    # Quantization\n                    \"quantization\": model_config.quantization,\n                    \"kv_cache_dtype\": cache_config.cache_dtype,\n\n                    # Feature flags\n                    \"enable_lora\": bool(lora_config),\n                    \"enable_prefix_caching\": cache_config.enable_prefix_caching,\n                    \"enforce_eager\": model_config.enforce_eager,\n                    \"disable_custom_all_reduce\": parallel_config.disable_custom_all_reduce,\n                })\n\n        if self.tokenizer:\n            # Ping the tokenizer to ensure liveness if it runs in a\n            # different process.\n            self.tokenizer.ping()\n\n        # Create the scheduler.\n        # NOTE: the cache_config here have been updated with the numbers of\n        # GPU and CPU blocks, which are profiled in the distributed executor.\n        # NOTE(shengguangming): each process will have independent scheduler\n        self.scheduler = Scheduler(scheduler_config, cache_config, lora_config)\n\n        # Metric Logging.\n        if self.log_stats:\n            self.stat_logger = StatLogger(local_interval=_LOCAL_LOGGING_INTERVAL_SEC,\n                                          labels=dict(model_name=model_config.served_model_name),\n                                          max_model_len=self.model_config.max_model_len)\n            self.stat_logger.info(\"cache_config\", self.cache_config)\n\n        # Create sequence output processor, e.g. for beam search or\n        # speculative decoding.\n        self.output_processor = (SequenceGroupOutputProcessor.create_output_processor(\n            self.scheduler_config,\n            self.detokenizer,\n            self.scheduler,\n            self.seq_counter,\n            self.get_tokenizer_for_seq,\n            stop_checker=StopChecker(\n                self.scheduler_config.max_model_len,\n                self.get_tokenizer_for_seq,\n            ),\n        ))\n\n    # TODO(sgm): add for verl but we may not tokenizer in Rollout\n    def _init_tokenizer(self, tokenizer, **tokenizer_init_kwargs):\n        init_kwargs = dict(enable_lora=bool(self.lora_config),\n                           max_num_seqs=self.scheduler_config.max_num_seqs,\n                           max_input_length=None)\n        init_kwargs.update(tokenizer_init_kwargs)\n        self.tokenizer: TokenizerGroup = TokenizerGroup(tokenizer, **init_kwargs)\n\n    def init_cache_engine(self):\n        # TODO: check whether we should rebuild the CUDAGraph every iter when offload/load KVCache\n        # Re-capture CUDAGraph would be time-consuming\n        self.model_executor.init_cache_engine()\n\n    def free_cache_engine(self):\n        self.model_executor.free_cache_engine()\n\n    # NOTE(sgm): currently, we only support GPU executor\n    # The GPUExecutor remove the Ray dependency\n    @classmethod\n    def from_engine_args(\n        cls,\n        model,\n        tokenizer,\n        engine_args: EngineArgs,\n        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,\n    ) -> \"LLMEngine\":\n        \"\"\"Creates an LLM engine from the engine arguments.\"\"\"\n        # Create the engine configs.\n        engine_config = engine_args.create_engine_config()\n\n        # Initialize the cluster and specify the executor class.\n        assert engine_config.device_config.device_type == \"cuda\", \\\n            \"Currently, the vllm in verl only support running on GPU\"\n\n        if engine_config.parallel_config.world_size == 1:\n            engine_config.load_config.load_format = \"dummy_hf\"\n\n        from .spmd_gpu_executor import SPMDGPUExecutor\n        executor_class = SPMDGPUExecutor\n\n        # Create the LLM engine.\n        engine = cls(\n            model,\n            tokenizer,\n            **engine_config.to_dict(),\n            executor_class=executor_class,\n            log_stats=not engine_args.disable_log_stats,\n            usage_context=usage_context,\n        )\n        return engine\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.model_executor.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n    def offload_model_weights(self) -> None:\n        self.model_executor.offload_model_weights()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/megatron_weight_loaders.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models\n\nfrom typing import Dict\nimport torch\nimport torch.nn as nn\n\nfrom vllm.model_executor.layers.linear import *\nfrom vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding, ParallelLMHead\nfrom vllm.model_executor.layers.activation import ScaledActivation\nfrom vllm.model_executor.models import ModelRegistry\n\n\n# NOTE(shengguangming): replace the origin weight loader function in the class\ndef parallel_weight_loader(self, param: torch.Tensor, loaded_weight: torch.Tensor) -> None:\n    \"\"\"Parallel Linear weight loader.\"\"\"\n    assert param.size() == loaded_weight.size(\n    ), 'the parameter size is not align with the loaded weight size, param size: {}, loaded_weight size: {}'.format(\n        param.size(), loaded_weight.size())\n    assert param.data.dtype == loaded_weight.data.dtype, \"if we want to shared weights, the data type should also be the same\"\n\n    param.data = loaded_weight.data\n\n\ndef default_weight_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:\n    \"\"\"Default weight loader.\"\"\"\n    assert param.size() == loaded_weight.size()\n    assert param.data.dtype == loaded_weight.data.dtype, \"if we want to shared weights, the data type should also be the same\"\n\n    param.data = loaded_weight.data\n\n\ndef gpt2_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"lm_head.weight\" in name:\n            # GPT-2 ties the weights of the embedding layer and the final\n            # linear layer.\n            continue\n        if \".attn.bias\" in name or \".attn.masked_bias\" in name:\n            # Skip attention mask.\n            # NOTE: \"c_attn.bias\" should not be skipped.\n            continue\n        if not name.startswith(\"transformer.\"):\n            name = \"transformer.\" + name\n        param = params_dict[name]\n        # The HF's GPT-2 implementation uses Conv1D instead of Linear.\n        # Because of this, we need to transpose the weights.\n        # Note(zhuohan): the logic below might break quantized models.\n        for conv1d_weight_name in [\"c_attn\", \"c_proj\", \"c_fc\"]:\n            if conv1d_weight_name not in name:\n                continue\n            if not name.endswith(\".weight\"):\n                continue\n            # TODO: check megatron\n            loaded_weight = loaded_weight.t()\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_te_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv.layer_norm_weight\", \"input_layernorm.weight\"),\n        (\"self_attention.linear_qkv.layer_norm_bias\", \"input_layernorm.bias\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", 'self_attn.o_proj'),\n        ('pre_mlp_layernorm', 'post_attention_layernorm'),\n        ('mlp.linear_fc1.layer_norm_weight', 'post_attention_layernorm.weight'),\n        ('mlp.linear_fc1.layer_norm_bias', 'post_attention_layernorm.bias'),\n        ('mlp.linear_fc1', 'mlp.gate_up_proj'),\n        ('mlp.linear_fc2', 'mlp.down_proj'),\n        ('decoder.final_layernorm', 'model.norm'),\n        ('output_layer', 'lm_head'),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith('.bias') and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", 'self_attn.o_proj'),\n        (\n            'input_layernorm',\n            'input_layernorm',\n        ),\n        ('pre_mlp_layernorm', 'post_attention_layernorm'),\n        ('mlp.linear_fc1', 'mlp.gate_up_proj'),\n        ('mlp.linear_fc2', 'mlp.down_proj'),\n        ('decoder.final_layernorm', 'model.norm'),\n        ('output_layer', 'lm_head'),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith('.bias') and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef _replace_name(megatron_name, name_mapping):\n    for m_name, v_name in name_mapping:\n        if m_name not in megatron_name:\n            continue\n        if 'layers' in megatron_name:  # deal with decoder layers\n            megatron_name = megatron_name.replace('decoder', 'model')\n            megatron_name_list = megatron_name.split('.')\n            if 'layer_norm_weight' in megatron_name_list or 'layer_norm_bias' in megatron_name_list:\n                param_name_list = megatron_name_list[:3]\n                param_name_list.append(v_name)\n                param_name = '.'.join(param_name_list)\n            else:\n                param_name_list = megatron_name_list[:3]\n                weight_or_bias = megatron_name_list[-1]\n                param_name_list.append(v_name)\n                param_name_list.append(weight_or_bias)\n                param_name = '.'.join(param_name_list)\n            return param_name\n        else:\n            param_name = megatron_name.replace(m_name, v_name)\n            return param_name\n\n\ndef llama_megatron_core_te_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv.layer_norm_weight\", \"input_layernorm.weight\"),\n        (\"self_attention.linear_qkv.layer_norm_bias\", \"input_layernorm.bias\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", 'self_attn.o_proj'),\n        ('pre_mlp_layernorm', 'post_attention_layernorm'),\n        ('mlp.linear_fc1.layer_norm_weight', 'post_attention_layernorm.weight'),\n        ('mlp.linear_fc1.layer_norm_bias', 'post_attention_layernorm.bias'),\n        ('mlp.linear_fc1', 'mlp.gate_up_proj'),\n        ('mlp.linear_fc2', 'mlp.down_proj'),\n        ('decoder.final_layernorm', 'model.norm'),\n        ('output_layer', 'lm_head'),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith('.bias') and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", 'self_attn.o_proj'),\n        (\n            'input_layernorm',\n            'input_layernorm',\n        ),\n        ('pre_mlp_layernorm', 'post_attention_layernorm'),\n        ('mlp.linear_fc1', 'mlp.gate_up_proj'),\n        ('mlp.linear_fc2', 'mlp.down_proj'),\n        ('decoder.final_layernorm', 'model.norm'),\n        ('output_layer', 'lm_head'),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith('.bias') and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef _replace_name(megatron_name, name_mapping):\n    for m_name, v_name in name_mapping:\n        if m_name not in megatron_name:\n            continue\n        if 'layers' in megatron_name:  # deal with decoder layers\n            megatron_name = megatron_name.replace('decoder', 'model')\n            megatron_name_list = megatron_name.split('.')\n            if 'layer_norm_weight' in megatron_name_list or 'layer_norm_bias' in megatron_name_list:\n                param_name_list = megatron_name_list[:3]\n                param_name_list.append(v_name)\n                param_name = '.'.join(param_name_list)\n            else:\n                param_name_list = megatron_name_list[:3]\n                weight_or_bias = megatron_name_list[-1]\n                param_name_list.append(v_name)\n                param_name_list.append(weight_or_bias)\n                param_name = '.'.join(param_name_list)\n            return param_name\n        else:\n            param_name = megatron_name.replace(m_name, v_name)\n            return param_name\n\n\ndef mistral_megatron_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    # TODO: need to implement a general way to deal with prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\n__LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__ = {\n    ColumnParallelLinear: parallel_weight_loader,\n    MergedColumnParallelLinear: parallel_weight_loader,\n    QKVParallelLinear: parallel_weight_loader,\n    RowParallelLinear: parallel_weight_loader,\n    VocabParallelEmbedding: parallel_weight_loader,\n    ParallelLMHead: parallel_weight_loader\n    # \"ScaledActivation.weight_loader\": ScaledActivation, # TODO(shengguangming): latest commit in vllm fix awq for this function and add load_weights\n    # \"default_weight_loader\": default_weight_loader\n}\n\n# for layer_class, weight_loader in __LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__.items():\n#     # setattr(layer_class, 'megatron_weight_loader', weight_loader)\n#     layer_class.weight_loader = weight_loader\n\n__MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__ = {\n    'GPT2LMHeadModel': gpt2_weight_loader,\n    'LlamaForCausalLM': llama_megatron_core_te_weight_loader,  # use te backend for open-source megatron\n    'LLaMAForCausalLM': llama_megatron_core_te_weight_loader,\n    'MistralForCausalLM': mistral_megatron_weight_loader,\n}\n\n\n# the actor model is .state_dict()\n# Load megatron weights\ndef load_megatron_weights(actor_weights: Dict, vllm_model: nn.Module):\n    weight_loader = _get_model_weight_loader(vllm_model.__class__.__name__)\n    weight_loader(actor_weights, vllm_model)\n    # NOTE(sgm) to reduce peak memory usage, we offload vllm model to cpu\n    # after init, and we need this after sync model weights for in first iter.\n    vllm_model = vllm_model.cuda()\n\n\ndef _get_model_weight_loader(arch: str):\n    if arch in __MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__:\n        return __MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {ModelRegistry.get_supported_archs()}\")\n\n\ndef update_megatron_weight_loader():\n    for layer_class, weight_loader in __LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__.items():\n        layer_class.weight_loader = weight_loader\n    VocabParallelEmbedding.__init__ = vocab_init\n\n\n# FIXME(shengguangming): the vLLM vocab will pad to 64, which may incur out of bounds\n# so we need to rewrite the init function of vocab\nDEFAULT_VOCAB_PADDING_SIZE = 64\n\n\ndef vocab_init(self,\n               num_embeddings: int,\n               embedding_dim: int,\n               params_dtype: Optional[torch.dtype] = None,\n               org_num_embeddings: Optional[int] = None,\n               padding_size: int = DEFAULT_VOCAB_PADDING_SIZE):\n    super(VocabParallelEmbedding, self).__init__()\n\n    # Keep the input dimensions.\n    # TODO (pad to be divided by 4)\n    self.num_embeddings = num_embeddings\n    self.org_vocab_size = org_num_embeddings or num_embeddings\n\n    # self.num_embeddings_padded = pad_vocab_size(num_embeddings,\n    #                                             padding_size)\n    self.embedding_dim = embedding_dim\n    if params_dtype is None:\n        params_dtype = torch.get_default_dtype()\n    self.tp_size = get_tensor_model_parallel_world_size()\n    # Divide the weight matrix along the vocaburaly dimension.\n\n    # TODO: remove dependencies from megatron\n    from megatron.core.tensor_parallel.utils import VocabUtility\n    self.vocab_start_index, self.vocab_end_index = (VocabUtility.vocab_range_from_global_vocab_size(\n        self.num_embeddings, get_tensor_model_parallel_rank(), self.tp_size))\n    self.num_embeddings_per_partition = (self.vocab_end_index - self.vocab_start_index)\n    self.weight = Parameter(\n        torch.empty(\n            self.num_embeddings_per_partition,\n            self.embedding_dim,\n            # device=torch.cuda.current_device(),\n            dtype=params_dtype))\n    set_weight_attrs(self.weight, {\"parallel_dim\": 0, \"weight_loader\": self.weight_loader})\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/model_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader\n\"\"\"Utilities for selecting and loading models.\"\"\"\nfrom typing import Dict, Union, Optional, Iterable, Tuple\n\nimport torch\nimport torch.nn as nn\nfrom transformers import PreTrainedModel\n\nfrom vllm.config import (DeviceConfig, LoRAConfig, ParallelConfig, SchedulerConfig, VisionLanguageConfig)\nfrom vllm.model_executor.model_loader import BaseModelLoader\nfrom vllm.model_executor.model_loader.loader import _initialize_model\nfrom vllm.model_executor.model_loader.utils import set_default_torch_dtype\nfrom vllm.distributed.communication_op import tensor_model_parallel_all_gather\n\nfrom .config import ModelConfig, LoadFormat, LoadConfig\nfrom .megatron_weight_loaders import load_megatron_weights, update_megatron_weight_loader\nfrom .dtensor_weight_loaders import load_dtensor_weights, update_dtensor_weight_loader\nfrom .hf_weight_loader import update_hf_weight_loader\n\n\ndef get_model(actor_model: Union[PreTrainedModel, Dict], model_config: ModelConfig, load_config: LoadConfig,\n              device_config: DeviceConfig, parallel_config: ParallelConfig, scheduler_config: SchedulerConfig,\n              lora_config: Optional[LoRAConfig], vision_language_config: Optional[VisionLanguageConfig]) -> nn.Module:\n    loader = get_model_loader(load_config)\n    if load_config.load_format.startswith('dummy'):\n        return loader.load_model(model_config=model_config,\n                                 device_config=device_config,\n                                 lora_config=lora_config,\n                                 vision_language_config=vision_language_config,\n                                 parallel_config=parallel_config,\n                                 scheduler_config=scheduler_config)\n    else:\n        return loader.load_model(actor_model=actor_model,\n                                 model_config=model_config,\n                                 device_config=device_config,\n                                 lora_config=lora_config,\n                                 vision_language_config=vision_language_config,\n                                 parallel_config=parallel_config,\n                                 scheduler_config=scheduler_config)\n\n\ndef get_model_loader(load_config: LoadConfig) -> BaseModelLoader:\n    \"\"\"Get a model loader based on the load format.\"\"\"\n\n    if isinstance(load_config.load_format, type):\n        return load_config.load_format(load_config)\n\n    if load_config.load_format == LoadFormat.AUTO:\n        update_megatron_weight_loader()\n        return MegatronLoader(load_config)\n\n    # NOTE(sgm): change the weight_loader function in runtime\n    if load_config.load_format == LoadFormat.MEGATRON:\n        update_megatron_weight_loader()\n        return MegatronLoader(load_config)\n\n    if load_config.load_format == LoadFormat.HF:\n        update_hf_weight_loader()\n        return HFLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DTENSOR:\n        update_dtensor_weight_loader()\n        return DTensorLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_HF:\n        update_hf_weight_loader()\n        return DummyModelLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_MEGATRON:\n        update_megatron_weight_loader()\n        return DummyModelLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_DTENSOR:\n        update_dtensor_weight_loader()\n        return DummyModelLoader(load_config)\n\n    raise ValueError('load format not supported in verl: {}, only support {} and {}'.format(\n        load_config.load_format, LoadFormat.MEGATRON, LoadFormat.HF))\n\n\nclass DummyModelLoader(BaseModelLoader):\n    \"\"\"Model loader that will set model weights to random values.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def load_model(self, *, model_config: ModelConfig, device_config: DeviceConfig, lora_config: Optional[LoRAConfig],\n                   vision_language_config: Optional[VisionLanguageConfig], parallel_config: ParallelConfig,\n                   scheduler_config: SchedulerConfig) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, vision_language_config)\n            # NOTE(woosuk): For accurate performance evaluation, we assign\n            # random values to the weights.\n            # initialize_dummy_weights(model)\n        return model.eval()\n\n\nclass MegatronLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from partitioned megatron model.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def _get_weights_iterator(actor_model: Union[PreTrainedModel, Dict]):\n        # NOTE(shengguangming) Load the weights from the actor model\n        pass\n        # if isinstance(actor_model, nn.Module):\n        #     load_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)), vllm_model=model)\n        # else:\n        #     load_weights(actor_weights=actor_model, vllm_model=model)\n        # return actor_model\n\n    def load_model(self, actor_model: Union[PreTrainedModel,\n                                            Dict], model_config: ModelConfig, device_config: DeviceConfig,\n                   lora_config: Optional[LoRAConfig], vision_language_config: Optional[VisionLanguageConfig],\n                   parallel_config: ParallelConfig, scheduler_config: SchedulerConfig) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, vision_language_config)\n\n            # TODO(sgm): This is a hack, we need to register the load_weight() func for each model in vllm\n            if isinstance(actor_model, nn.Module):\n                load_megatron_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)),\n                                      vllm_model=model)\n            else:\n                load_megatron_weights(actor_weights=actor_model, vllm_model=model)\n\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\nclass HFLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from model's full params.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def _get_weights_iterator(self, actor_model: Union[PreTrainedModel, Dict]):\n        if isinstance(actor_model, Dict):\n            return actor_model.items()\n        elif isinstance(actor_model, nn.Module):\n            return dict(actor_model.named_parameters()).items()\n        else:\n            raise ValueError(f'actor model should be Dict or nn.Module, but get {type(actor_model)}')\n\n    def load_model(self, actor_model: Union[PreTrainedModel,\n                                            Dict], model_config: ModelConfig, device_config: DeviceConfig,\n                   lora_config: Optional[LoRAConfig], vision_language_config: Optional[VisionLanguageConfig],\n                   parallel_config: ParallelConfig, scheduler_config: SchedulerConfig) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            # with torch.device(device_config.device):\n            # NOTE(sgm): init the model in cpu\n            model = _initialize_model(model_config, self.load_config, lora_config, vision_language_config)\n            model.load_weights(self._get_weights_iterator(actor_model))\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\nclass DTensorLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from partitioned megatron model.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def _get_weights_iterator(actor_model: Union[PreTrainedModel, Dict]):\n        # NOTE(shengguangming) Load the weights from the actor model\n        pass\n        # if isinstance(actor_model, nn.Module):\n        #     load_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)), vllm_model=model)\n        # else:\n        #     load_weights(actor_weights=actor_model, vllm_model=model)\n        # return actor_model\n\n    def load_model(self, actor_model: Union[PreTrainedModel,\n                                            Dict], model_config: ModelConfig, device_config: DeviceConfig,\n                   lora_config: Optional[LoRAConfig], vision_language_config: Optional[VisionLanguageConfig],\n                   parallel_config: ParallelConfig, scheduler_config: SchedulerConfig) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, vision_language_config)\n\n            # TODO(sgm): This is a hack, we need to register the load_weight() func for each model in vllm\n            if isinstance(actor_model, nn.Module):\n                load_dtensor_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)),\n                                     vllm_model=model)\n            else:\n                load_dtensor_weights(actor_weights=actor_model, vllm_model=model)\n\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\n# FIXME(sgm): hack the _get_logits function in vllm v0.4.2\n# as they use ray, the _get_logits result will only need to return to the driver node,\n# therefore gather is enough. However, we use SPMD instead of a central scheduler,\n# all_gather is required (aligned with v0.2.6)\ndef _get_logits(self, hidden_states: torch.Tensor, embedding: torch.Tensor,\n                embedding_bias: Optional[torch.Tensor]) -> torch.Tensor:\n    # Get the logits for the next tokens.\n    logits = torch.matmul(hidden_states, embedding.t())\n    if embedding_bias is not None:\n        logits += embedding_bias\n    logits = tensor_model_parallel_all_gather(logits)\n    # Remove paddings in vocab (if any).\n    if logits is not None:\n        logits = logits[:, :self.org_vocab_size]\n    return logits\n\n\nfrom vllm.model_executor.layers.logits_processor import LogitsProcessor\n\nLogitsProcessor._get_logits = _get_logits\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/model_runner.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/model_runner.py\n\nimport torch\nimport torch.nn as nn\nfrom enum import IntEnum\nfrom typing import Dict, List, Optional, Set, Tuple, Union\n\nfrom vllm.attention import (AttentionMetadata, get_attn_backend)\nfrom vllm.config import (DeviceConfig, LoRAConfig, ParallelConfig, SchedulerConfig, VisionLanguageConfig)\nfrom vllm.logger import init_logger\nfrom vllm.lora.layers import LoRAMapping\nfrom vllm.lora.request import LoRARequest\nfrom vllm.lora.worker_manager import LRUCacheWorkerLoRAManager\nfrom vllm.model_executor import SamplingMetadata\nfrom vllm.sequence import (MultiModalData, SamplerOutput, SequenceData, SequenceGroupMetadata)\nfrom vllm.utils import (CudaMemoryProfiler, is_hip, is_pin_memory_available)\nfrom vllm.worker.model_runner import ModelRunner, CUDAGraphRunner\n\nfrom .model_loader import get_model\nfrom .config import ModelConfig, LoadConfig\n\nlogger = init_logger(__name__)\n\n\n# How batches are constructed.\nclass BatchType(IntEnum):\n    # Every batch is prefill.\n    PREFILL = 0\n    # Every batch is decode.\n    DECODE = 1\n    # Batch is a mixture of prefill and decode.\n    MIXED = 2\n\n\nclass ModelRunner(ModelRunner):\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        model_config: ModelConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        kv_cache_dtype: Optional[str] = \"auto\",\n        vision_language_config: Optional[VisionLanguageConfig] = None,\n    ):\n        self.model_config = model_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.lora_config = lora_config\n        self.load_config = load_config\n\n        # model_config can be None in tests/samplers/test_sampler.py.\n        # FIXME(woosuk): This is a hack to make the tests work. Refactor this.\n        self.sliding_window = (model_config.get_sliding_window() if model_config is not None else None)\n        self.device_config = (device_config if device_config is not None else DeviceConfig())\n        self.device = self.device_config.device\n\n        # NOTE(sgm): add for verl\n        self.model = model  # this will be replaced by get_model()\n\n        # Set after load_model.\n        self.lora_manager: LRUCacheWorkerLoRAManager = None\n\n        self.graph_runners: Dict[int, CUDAGraphRunner] = {}\n        self.graph_memory_pool: Optional[Tuple[int, int]] = None  # Set during graph capture.\n\n        self.max_seq_len_to_capture = (self.model_config.max_seq_len_to_capture if self.model_config is not None else 0)\n\n        self.pin_memory = is_pin_memory_available()\n        self.kv_cache_dtype = kv_cache_dtype\n        self.vision_language_config = vision_language_config\n\n        self.attn_backend = get_attn_backend(self.model_config.dtype if model_config is not None else None)\n\n        # Lazy initialization\n        self.block_size: int  # Set after initial profiling.\n        # When using CUDA graph, the input block tables must be padded to\n        # max_seq_len_to_capture. However, creating the block table in\n        # Python can be expensive. To optimize this, we cache the block table\n        # in numpy and only copy the actual input content at every iteration.\n        # The shape of the cached block table will be\n        # (max batch size to capture, max context len to capture / block size).\n        self.graph_block_tables: torch.Tensor  # Set after initial profiling.\n\n        # Set if the backend is flashinfer.\n        self.flashinfer_workspace_buffer: torch.Tensor\n\n    # NOTE(sgm): initialize model using the actor model\n    def load_model(self) -> None:\n        with CudaMemoryProfiler() as m:\n            self.model = get_model(actor_model=self.model,\n                                   model_config=self.model_config,\n                                   device_config=self.device_config,\n                                   lora_config=self.lora_config,\n                                   load_config=self.load_config,\n                                   parallel_config=self.parallel_config,\n                                   scheduler_config=self.scheduler_config,\n                                   vision_language_config=self.vision_language_config)\n        self.model_memory_usage = m.consumed_memory\n        logger.info(\"Loading model weights took %.4f GB\", self.model_memory_usage / float(2**30))\n\n        if self.lora_config:\n            assert hasattr(self.model, \"supported_lora_modules\") and self.model.supported_lora_modules, (\n                \"Model does not support LoRA\")\n            assert hasattr(self.model, \"embedding_modules\"), \"Model does not have embedding_modules\"\n            assert hasattr(self.model, \"embedding_padding_modules\"), \"Model does not have embedding_padding_modules\"\n            self.lora_manager = LRUCacheWorkerLoRAManager(self.scheduler_config.max_num_seqs,\n                                                          self.scheduler_config.max_num_batched_tokens, self.vocab_size,\n                                                          self.lora_config, self.device, self.model.embedding_modules,\n                                                          self.model.embedding_padding_modules)\n            self.model = self.lora_manager.create_lora_manager(self.model)\n\n        if self.kv_cache_dtype == \"fp8\" and is_hip():\n            # Currently scaled KV cache is only enabled on ROCm\n            if self.model_config.quantization_param_path is not None:\n                if callable(getattr(self.model, \"load_kv_cache_scales\", None)):\n                    self.model.load_kv_cache_scales(self.model_config.quantization_param_path)\n                else:\n                    raise RuntimeError(\n                        \"Using FP8 KV cache and scaling factors provided but \"\n                        \"model %s does not support loading scaling factors.\", self.model.__class__)\n            else:\n                logger.warning(\"Using FP8 KV cache but no scaling factors \"\n                               \"provided. Defaulting to scaling factors of 1.0. \"\n                               \"This may lead to less accurate results!\")\n        elif self.model_config.quantization_param_path is not None:\n            logger.warning(\"KV cache scaling factors provided, \"\n                           \"but the KV cache data type is not FP8. \"\n                           \"KV cache scaling factors will not be used.\")\n\n    def prepare_input_tensors(\n        self,\n        seq_group_metadata_list: List[SequenceGroupMetadata],\n    ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, SamplingMetadata, Set[LoRARequest], LoRAMapping,\n               torch.Tensor]:\n        # NOTE(sgm): all workers prepare the input in the same way\n        prefill_reqs = []\n        decode_reqs = []\n        for seq_group_meta in seq_group_metadata_list:\n            if seq_group_meta.is_prompt:\n                prefill_reqs.append(seq_group_meta)\n            else:\n                decode_reqs.append(seq_group_meta)\n\n        # Prepare input tensors.\n        (\n            input_tokens,\n            input_positions,\n            prefill_attn_metadata,\n            seq_lens,\n            query_lens,\n            lora_index_mapping,\n            lora_prompt_mapping,\n            lora_requests,\n            multi_modal_input,\n            slot_mapping,\n        ) = self._prepare_prompt(prefill_reqs)\n        (\n            decode_input_tokens,\n            decode_input_positions,\n            decode_attn_metadata,\n            decode_lora_index_mapping,\n            decode_lora_prompt_mapping,\n            decode_lora_requests,\n            decode_slot_mapping,\n        ) = self._prepare_decode(decode_reqs)\n        sampling_metadata = SamplingMetadata.prepare(seq_group_metadata_list, seq_lens, query_lens, self.device,\n                                                     self.pin_memory)\n\n        if not self.scheduler_config.chunked_prefill_enabled:\n            assert (len(prefill_reqs) and len(decode_reqs)) == 0\n\n        num_prefills = len(seq_lens)\n        num_prefill_tokens = len(input_tokens)\n        num_decode_tokens = len(decode_input_tokens)\n\n        # Coalesce tensors. Note that attn_metadata is currently not\n        # coalesced for simplicity.\n        input_tokens.extend(decode_input_tokens)\n        input_positions.extend(decode_input_positions)\n        slot_mapping.extend(decode_slot_mapping)\n        lora_index_mapping.extend(decode_lora_index_mapping)\n        lora_prompt_mapping.extend(decode_lora_prompt_mapping)\n        lora_requests.update(decode_lora_requests)\n\n        input_tokens = torch.tensor(input_tokens, dtype=torch.long, device=self.device)\n        input_positions = torch.tensor(input_positions, dtype=torch.long, device=self.device)\n        slot_mapping = torch.tensor(slot_mapping, dtype=torch.long, device=self.device)\n\n        if self.lora_config:\n            lora_mapping = LoRAMapping(\n                lora_index_mapping,\n                lora_prompt_mapping,\n            )\n        else:\n            lora_mapping = None\n\n        # Broadcast the metadata.\n        # If batch contains both prefill and decode, it sends 2 broadcasts.\n        # If it only contains 1 type, it triggers a single broadcast.\n        if (prefill_attn_metadata is not None and decode_attn_metadata is not None):\n            batch_type = BatchType.MIXED\n        elif prefill_attn_metadata is not None:\n            batch_type = BatchType.PREFILL\n        else:\n            batch_type = BatchType.DECODE\n\n        attn_metadata = AttentionMetadata(\n            num_prefills=num_prefills,\n            slot_mapping=slot_mapping,\n            num_prefill_tokens=num_prefill_tokens,\n            num_decode_tokens=num_decode_tokens,\n            prefill_metadata=prefill_attn_metadata,\n            decode_metadata=decode_attn_metadata,\n            kv_cache_dtype=self.kv_cache_dtype,\n        )\n\n        return (input_tokens, input_positions, attn_metadata, sampling_metadata, lora_requests, lora_mapping,\n                multi_modal_input)\n\n    @torch.inference_mode()\n    def execute_model(\n        self,\n        seq_group_metadata_list: List[SequenceGroupMetadata],\n        kv_caches: List[torch.Tensor],\n    ) -> Optional[SamplerOutput]:\n        (input_tokens, input_positions, attn_metadata, sampling_metadata, lora_requests, lora_mapping,\n         multi_modal_input) = self.prepare_input_tensors(seq_group_metadata_list)\n\n        if self.lora_config:\n            self.set_active_loras(lora_requests, lora_mapping)\n\n        # Currently cuda graph is only supported by the decode phase.\n        prefill_meta = attn_metadata.prefill_metadata\n        decode_meta = attn_metadata.decode_metadata\n        if prefill_meta is None and decode_meta.use_cuda_graph:\n            graph_batch_size = input_tokens.shape[0]\n            model_executable = self.graph_runners[graph_batch_size]\n        else:\n            model_executable = self.model\n        execute_model_kwargs = {\n            \"input_ids\": input_tokens,\n            \"positions\": input_positions,\n            \"kv_caches\": kv_caches,\n            \"attn_metadata\": attn_metadata,\n        }\n        if self.vision_language_config:\n            execute_model_kwargs.update({\"image_input\": multi_modal_input})\n        hidden_states = model_executable(**execute_model_kwargs)\n\n        # Compute the logits.\n        logits = self.model.compute_logits(hidden_states, sampling_metadata)\n\n        # Only perform sampling in the driver worker.\n        # if not self.is_driver_worker:\n        #     return None\n\n        # TODO(sgm): perform sampling on rank 0\n        # Sample the next token.\n        output = self.model.sample(\n            logits=logits,\n            sampling_metadata=sampling_metadata,\n        )\n\n        return output\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/parallel_state.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Adapted from\n# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py\n# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.\n\"\"\"Model and data parallel groups.\"\"\"\nimport os\nimport torch\nimport torch.distributed\nfrom typing import Optional\n\nimport vllm.distributed.parallel_state as ps\n\nimport vllm.envs as envs\nfrom vllm.logger import init_logger\n\nfrom torch.distributed.device_mesh import init_device_mesh\n\nlogger = init_logger(__name__)\n\"\"\"\nThis version is strongly tied with Megatron to implement HybridEngine and weight sharing between vllm and Megatron.\n- We assume the Megatron tp+dp+pp world is already established before calling this function.\n\n\"\"\"\n\n# Device mesh for using DTensor\n_DEVICE_MESH = None\n\n# Tensor model parallel group that the current rank belongs to.\n_TP_DEVICE_GROUP = None\n_TP_CPU_GROUP = None\n\n\n# This method is for initializing the ParallelGroup when using HybridEngine\ndef initialize_parallel_state(\n    distributed_init_method: str = \"env://\",\n    backend: str = \"nccl\",\n    tensor_model_parallel_size: int = 1,\n    num_tp_per_train_tp: int = 1,\n    pipeline_model_parallel_size: int = 1,\n):\n    # torch.distributed.all_reduce does not free the input tensor until\n    # the synchronization point. This causes the memory usage to grow\n    # as the number of all_reduce calls increases. This env var disables\n    # this behavior.\n    # Related issue:\n    # https://discuss.pytorch.org/t/cuda-allocation-lifetime-for-inputs-to-distributed-all-reduce/191573\n    os.environ[\"TORCH_NCCL_AVOID_RECORD_STREAMS\"] = \"1\"\n\n    # NOTE(sgm): Modify for verl, Env vars will be set by TORCHRUN.\n    rank = int(os.getenv(\"RANK\", \"-1\"))\n    local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n\n    # Use the world_size set by TORCHRUN\n    world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n    assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n    ps.init_distributed_environment(world_size, rank, distributed_init_method, local_rank, backend)\n    if torch.distributed.get_world_size() > 1:\n        # NOTE: build a sepearate inference group with infer tp & micro dp\n        initialize_model_parallel_for_vllm(tensor_model_parallel_size=tensor_model_parallel_size,\n                                           num_tensor_model_parallel_groups_per_train_tp=num_tp_per_train_tp)\n    else:\n        initialize_model_parallel(tensor_model_parallel_size, pipeline_model_parallel_size, backend)\n\n\ndef ensure_model_parallel_initialized(\n    tensor_model_parallel_size: int,\n    pipeline_model_parallel_size: int = 1,\n    backend: Optional[str] = None,\n) -> None:\n    \"\"\"Helper to initialize model parallel groups if they are not initialized,\n    or ensure tensor-parallel and pipeline-parallel sizes are equal to expected\n    values if the model parallel groups are initialized.\n    \"\"\"\n    # get the backend of _DEVICE_WORLD_GROUP\n    backend = backend or torch.distributed.get_backend()\n    if not model_parallel_is_initialized():\n        initialize_model_parallel(tensor_model_parallel_size, pipeline_model_parallel_size, backend)\n        return\n\n    assert (get_tensor_model_parallel_world_size() == tensor_model_parallel_size), (\n        \"tensor parallel group already initialized, but of unexpected size: \"\n        f\"{get_tensor_model_parallel_world_size()=} vs. \"\n        f\"{tensor_model_parallel_size=}\")\n    # assert (get_pipeline_model_parallel_world_size(\n    # ) == pipeline_model_parallel_size), (\n    #     \"pipeline parallel group already initialized, but of unexpected size: \"\n    #     f\"{get_pipeline_model_parallel_world_size()=} vs. \"\n    #     f\"{pipeline_model_parallel_size=}\")\n\n\ndef model_parallel_is_initialized():\n    \"\"\"Check if tensor and pipeline parallel groups are initialized.\"\"\"\n    return (ps._TP_DEVICE_GROUP is not None)\n    # and _PIPELINE_MODEL_PARALLEL_GROUP is not None)\n\n\ndef initialize_model_parallel_for_vllm(tensor_model_parallel_size: int,\n                                       num_tensor_model_parallel_groups_per_train_tp: int = 1) -> None:\n    from torch.distributed import new_group\n    # Get world size and rank. Ensure some consistencies.\n    assert torch.distributed.is_initialized()\n\n    assert isinstance(tensor_model_parallel_size, int)\n\n    # assert num_tensor_model_parallel_groups_per_train_tp == 1 and not different_tp_group\n    # assert num_tensor_model_parallel_groups_per_train_tp > 1 and different_tp_group\n\n    # Build the tensor model-parallel groups.\n    assert ps._TP_DEVICE_GROUP is None, (\"tensor model parallel group is already initialized\")\n\n    global _TP_DEVICE_GROUP\n    global _TP_CPU_GROUP\n    global _DEVICE_MESH\n\n    world_size: int = torch.distributed.get_world_size()\n\n    rank = torch.distributed.get_rank()\n\n    backend = torch.distributed.get_backend()\n\n    num_tensor_model_parallel_groups = world_size // tensor_model_parallel_size\n\n    if num_tensor_model_parallel_groups_per_train_tp == 1:\n        # if tensor_model_parallel_size == train_tensor_parallel_size:\n        # using the same tp group as Megatron/vllm\n        for i in range(num_tensor_model_parallel_groups):\n            ranks = range(i * tensor_model_parallel_size, (i + 1) * tensor_model_parallel_size)\n            group = torch.distributed.new_group(ranks, backend=backend)\n            cpu_group = torch.distributed.new_group(ranks, backend=\"gloo\")\n            if rank in ranks:\n                _TP_DEVICE_GROUP = group\n                _TP_CPU_GROUP = cpu_group\n                ps._TP_DEVICE_GROUP = group\n                ps._TP_CPU_GROUP = cpu_group\n\n        # no _MICRO_DATA_PARALLEL_GROUP\n    else:\n        # initialize a micro_dp group and a tp group\n        # assume training tp=4, infer tp=2, then, weight is partitioned as\n        # [1], [2], [3], [4] for training and [1,2], [1,2], [3,4], [3,4] for inference\n\n        # Build the inference tp groups\n        # train_tp = train_tensor_parallel_size\n        train_tp = num_tensor_model_parallel_groups_per_train_tp * tensor_model_parallel_size\n        # num_tensor_model_parallel_groups_per_train_tp = train_tp // tensor_model_parallel_size\n        assert _TP_DEVICE_GROUP is None, (\"tensor model parallel group is already initialized\")\n        for i in range(num_tensor_model_parallel_groups // num_tensor_model_parallel_groups_per_train_tp):\n            start = train_tp * i\n            end = train_tp * (i + 1)\n            for j in range(num_tensor_model_parallel_groups_per_train_tp):\n                ranks = list(range(start, end, num_tensor_model_parallel_groups_per_train_tp))\n                for i in range(len(ranks)):\n                    ranks[i] += j\n                group = torch.distributed.new_group(ranks)\n                cpu_group = torch.distributed.new_group(ranks, backend='gloo')\n                if rank in ranks:\n                    _TP_DEVICE_GROUP = group\n                    _TP_CPU_GROUP = cpu_group\n                    ps._TP_DEVICE_GROUP = _TP_DEVICE_GROUP\n                    ps._TP_CPU_GROUP = cpu_group\n\n    # Build the pipeline model-parallel groups.\n    # global _PIPELINE_MODEL_PARALLEL_GROUP\n    # global _PIPELINE_GLOBAL_RANKS\n    # assert ps._PIPELINE_MODEL_PARALLEL_GROUP is None, (\"pipeline model parallel group is already initialized\")\n\n    # ps._PIPELINE_MODEL_PARALLEL_GROUP = mpu.get_pipeline_model_parallel_group()\n    # ps._PIPELINE_GLOBAL_RANKS = mpu.get_pipeline_model_parallel_ranks()\n\n\ndef initialize_model_parallel(\n    tensor_model_parallel_size: int = 1,\n    pipeline_model_parallel_size: int = 1,\n    backend: Optional[str] = None,\n) -> None:\n    \"\"\"\n    NOTE: This method is a hack from the open-sourced version without\n    asertion of world_size = tp * pp\n    \n    Initialize model parallel groups.\n\n    Arguments:\n        tensor_model_parallel_size: number of GPUs used for tensor model\n            parallelism.\n        pipeline_model_parallel_size: number of GPUs used for pipeline model\n            parallelism.\n\n    Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we\n    use 2 GPUs to parallelize the model tensor, and 4 GPUs to parallelize\n    the model pipeline. The present function will\n    create 4 tensor model-parallel groups and 2 pipeline model-parallel groups:\n        4 tensor model-parallel groups:\n            [g0, g1], [g2, g3], [g4, g5], [g6, g7]\n        2 pipeline model-parallel groups:\n            [g0, g2, g4, g6], [g1, g3, g5, g7]\n    Note that for efficiency, the caller should make sure adjacent ranks\n    are on the same DGX box. For example if we are using 2 DGX-1 boxes\n    with a total of 16 GPUs, rank 0 to 7 belong to the first box and\n    ranks 8 to 15 belong to the second box.\n    \"\"\"\n    # Get world size and rank. Ensure some consistencies.\n    assert torch.distributed.is_initialized()\n    world_size: int = torch.distributed.get_world_size()\n    # get the backend of _DEVICE_WORLD_GROUP\n    backend = backend or torch.distributed.get_backend()\n\n    # NOTE(sgm) we don't assert world_size == tp * pp\n    # DP is not managed by vllm but by the verl WorkerGroup\n\n    num_tensor_model_parallel_groups: int = (world_size // tensor_model_parallel_size)\n    num_pipeline_model_parallel_groups: int = (world_size // pipeline_model_parallel_size)\n    rank = torch.distributed.get_rank()\n\n    # Build device mesh for TP\n    if num_tensor_model_parallel_groups > 1:\n        device_mesh = init_device_mesh(\"cuda\", (num_tensor_model_parallel_groups, tensor_model_parallel_size),\n                                       mesh_dim_names=(\"replicate\", \"tp_shard\"))\n    else:\n        device_mesh = init_device_mesh(\"cuda\", (tensor_model_parallel_size,), mesh_dim_names=[\"tp_shard\"])\n    shard_group = device_mesh.get_group(mesh_dim=\"tp_shard\")\n\n    # Build the tensor model-parallel groups.\n    global _TP_DEVICE_GROUP, _TP_CPU_GROUP\n    global _DEVICE_MESH\n    assert _TP_DEVICE_GROUP is None, (\"tensor model parallel group is already initialized\")\n    assert _DEVICE_MESH is None, (\"device mesh in vllm is already initialized\")\n\n    _DEVICE_MESH = device_mesh\n    # for i in range(num_tensor_model_parallel_groups):\n    #     ranks = range(i * tensor_model_parallel_size, (i + 1) * tensor_model_parallel_size)\n    # group = torch.distributed.new_group(ranks, backend=backend)\n    # cpu_group = torch.distributed.new_group(ranks, backend=\"gloo\")\n    # assert torch.distributed.get_process_group_ranks(shard_group) == torch.distributed.get_process_group_ranks(cpu_group)\n    # ranks = torch.distributed.get_process_group_ranks(shard_group)\n    # cpu_group = torch.distributed.new_group(ranks, backend=\"gloo\") # TODO: this will hang\n    # cpu_group = torch.distributed.new_group(, backend=\"gloo\")\n    # if rank == 0:\n    #     print(f'rank: {rank}')\n    #     print(f'ranks: {ranks}')\n    #     print(f'torch.distributed.get_process_group_ranks(shard_group): {torch.distributed.get_process_group_ranks(shard_group)}')\n    # if rank in ranks:\n    _TP_DEVICE_GROUP = shard_group\n    ps._TP_DEVICE_GROUP = _TP_DEVICE_GROUP\n    # ps._TP_CPU_GROUP = cpu_group # TODO: will hang when used with device mesh\n\n    # TODO: init using device mesh\n    # Build the pipeline model-parallel groups.\n    assert ps._PIPELINE_MODEL_PARALLEL_GROUP is None, (\"pipeline model parallel group is already initialized\")\n    for i in range(num_pipeline_model_parallel_groups):\n        ranks = range(i, world_size, num_pipeline_model_parallel_groups)\n        group = torch.distributed.new_group(ranks, backend=backend)\n        if rank in ranks:\n            ps._PIPELINE_MODEL_PARALLEL_GROUP = group\n            ps._PIPELINE_GLOBAL_RANKS = ranks\n\n\n\"\"\"\nDevice mesh utilities\n\"\"\"\n\n\ndef get_device_mesh():\n    assert _DEVICE_MESH is not None, (\"device mesh is not initialized\")\n    return _DEVICE_MESH\n\n\n\"\"\"\nTensor model parallel utilities\n\"\"\"\n\n\ndef get_tensor_model_parallel_group():\n    \"\"\"Get the tensor model parallel group the caller rank belongs to.\"\"\"\n    assert _TP_DEVICE_GROUP is not None, (\"tensor model parallel group is not initialized\")\n    return _TP_DEVICE_GROUP\n\n\ndef get_tensor_model_parallel_world_size():\n    \"\"\"Return world size for the tensor model parallel group.\"\"\"\n    return torch.distributed.get_world_size(group=get_tensor_model_parallel_group())\n\n\ndef get_tensor_model_parallel_rank():\n    \"\"\"Return my rank for the tensor model parallel group.\"\"\"\n    return torch.distributed.get_rank(group=get_tensor_model_parallel_group())\n\n\ndef get_tensor_model_parallel_src_rank():\n    \"\"\"Calculate the global rank corresponding to the first local rank\n    in the tensor model parallel group.\"\"\"\n    global_rank = torch.distributed.get_rank()\n    local_world_size = get_tensor_model_parallel_world_size()\n    return (global_rank // local_world_size) * local_world_size\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/spmd_gpu_executor.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/executor/gpu_executor.py\nimport os\nimport socket\nfrom typing import Any, Dict, List, Optional, Set, Tuple\n\nimport torch\nimport vllm.envs as envs\nfrom vllm.executor.executor_base import ExecutorBase, ExecutorAsyncBase\nfrom vllm.logger import init_logger\nfrom vllm.lora.request import LoRARequest\nfrom vllm.sequence import SamplerOutput, ExecuteModelRequest\n\nfrom vllm.config import (CacheConfig, DeviceConfig, LoRAConfig, ParallelConfig, SchedulerConfig, SpeculativeConfig,\n                         VisionLanguageConfig)\nfrom .config import ModelConfig, LoadConfig\n\nlogger = init_logger(__name__)\n\n\nclass SPMDGPUExecutor(ExecutorBase):\n    \"\"\"SPMD-based multi-GPU executor implementations.\"\"\"\n\n    def __init__(\n        self,\n        model, # pytorch model itself or its parameter dict\n        model_config: ModelConfig,\n        cache_config: CacheConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        vision_language_config: Optional[VisionLanguageConfig],\n        speculative_config: Optional[SpeculativeConfig],\n    ) -> None:\n        self.model_config = model_config\n        self.cache_config = cache_config\n        self.lora_config = lora_config\n        self.load_config = load_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.vision_language_config = vision_language_config\n        self.speculative_config = speculative_config\n\n        distributed_init_method = initialize_cluster(parallel_config)\n        self._init_executor(model, distributed_init_method)\n\n    # TODO(sgm): verl not support speculative decode now\n    def _init_executor(self, model, distributed_init_method) -> None:\n        assert (not self.speculative_config), \"Speculative decoding not yet supported for multi-GPU backend.\"\n\n        # Create the parallel worker for each GPU.\n        self._init_workers_sp(model, distributed_init_method)\n\n    def _init_workers_sp(self, model, distributed_init_method: str):\n        # Lazy import the Worker to avoid importing torch.cuda/xformers\n        # before CUDA_VISIBLE_DEVICES is set in the Worker\n        from .worker import Worker  # pylint: disable=import-outside-toplevel\n\n        rank = int(os.getenv(\"RANK\"))\n        local_rank = int(os.getenv(\"LOCAL_RANK\"))\n        print(f'local rank {local_rank}')\n\n        self.worker = Worker(\n            model,\n            self.model_config,\n            self.parallel_config,\n            self.scheduler_config,\n            self.device_config,\n            self.cache_config,\n            self.load_config,\n            local_rank,\n            rank,\n            distributed_init_method,\n            lora_config=self.lora_config,\n            vision_language_config=self.vision_language_config,\n        )\n\n        # NOTE(shengguangming): torch.distributed.init_process_group will be called inside the init_model()\n        self.worker.init_device()\n        self.worker.load_model()\n\n    def determine_num_available_blocks(self) -> Tuple[int, int]:\n        \"\"\"Determine the number of available KV blocks.\n\n        This invokes `determine_num_available_blocks` on each worker and takes\n        the min of the results, guaranteeing that the selected cache sizes are\n        compatible with all workers.\n\n        Returns:\n            - tuple[num_gpu_blocks, num_cpu_blocks]\n        \"\"\"\n        # Get the maximum number of blocks that can be allocated on GPU and CPU.\n        num_blocks = self.worker.determine_num_available_blocks()\n\n        # NOTE(shengguangming): Now we don't use a shared centralized controler but each process will\n        # have its own scheduler\n        num_gpu_blocks = num_blocks[0]\n        num_cpu_blocks = num_blocks[1]\n\n        return num_gpu_blocks, num_cpu_blocks\n\n    def initialize_cache(self, num_gpu_blocks: int, num_cpu_blocks: int) -> None:\n        \"\"\"Initialize the KV cache in all workers.\n        \"\"\"\n\n        # NOTE: We log here to avoid multiple logs when number of workers is\n        # greater than one. We could log in the engine, but not all executors\n        # have GPUs.\n        logger.info(\"# GPU blocks: %d, # CPU blocks: %d\", num_gpu_blocks, num_cpu_blocks)\n\n        self.cache_config.num_gpu_blocks = num_gpu_blocks\n        self.cache_config.num_cpu_blocks = num_cpu_blocks\n\n        if torch.distributed.get_rank() == 0:\n            print(\n                f'before init cache memory allocated: {torch.cuda.memory_allocated() / 1e9}GB, reserved: {torch.cuda.memory_reserved() / 1e9}GB'\n            )\n        self.worker.initialize_cache(num_gpu_blocks=num_gpu_blocks, num_cpu_blocks=num_cpu_blocks)\n        if torch.distributed.get_rank() == 0:\n            print(\n                f'after init cache memory allocated: {torch.cuda.memory_allocated() / 1e9}GB, reserved: {torch.cuda.memory_reserved() / 1e9}GB'\n            )\n\n    # NOTE(sgm): This will not profile & capture the model(CUDAGraph) when rebuilding KVCache\n    def init_cache_engine(self) -> None:\n        self.worker._init_cache_engine()\n\n    def free_cache_engine(self) -> None:\n        self.worker.free_cache_engine()\n\n    def execute_model(self, execute_model_req) -> List[SamplerOutput]:\n        all_outputs = self.worker.execute_model(execute_model_req=execute_model_req)\n\n        # NOTE(sgm):\n        # Each GPU in vllm under verl has its own spmd_gpu_executor, therefore all GPUs should return the outputs\n        # In vllm with ray, only the driver worker returns the sampling results.\n        return all_outputs\n\n    def add_lora(self, lora_request: LoRARequest) -> bool:\n        assert lora_request.lora_int_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.add_lora(lora_request=lora_request)\n\n    def remove_lora(self, lora_id: int) -> bool:\n        assert lora_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.remove_lora(lora_id=lora_id)\n\n    def list_loras(self) -> Set[int]:\n        return self.worker.list_loras()\n\n    def check_health(self) -> None:\n        # SPMDExecutor will always be healthy as long as\n        # it's running.\n        return\n\n    # NOTE(sgm): add for verl\n    def offload_model_weights(self) -> None:\n        self.worker.offload_model_weights()\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.worker.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n\ndef initialize_cluster(\n    parallel_config: ParallelConfig,\n    engine_use_ray: bool = False,\n    ray_address: Optional[str] = None,\n) -> Tuple[str, Optional[None]]:\n    \"\"\"Initialize the distributed cluster probably with Ray.\n\n    Args:\n        parallel_config: The configurations for parallel execution.\n\n    Returns:\n        The `distributed_init_method` is the address for initializing the\n        distributed backend.\n    \"\"\"\n\n    # Initialize cluster locally.\n    port = get_open_port()\n    # We need to setup the distributed init method to make sure\n    # the distributed megatron code (e.g., get world size) works correctly.\n    # distributed_init_method = f\"tcp://localhost:{port}\"\n    distributed_init_method = 'env://'\n    return distributed_init_method\n\n\ndef get_open_port():\n    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n        s.bind((\"\", 0))\n        return s.getsockname()[1]\n\n\n# TODO(sgm): not implemented async executor yet\nclass SPMDGPUExecutorAsync(SPMDGPUExecutor, ExecutorAsyncBase):\n\n    async def execute_model_async(self, execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:\n        \"\"\"Executes one model step on the given sequences.\"\"\"\n        raise NotImplementedError\n\n    async def check_health_async(self) -> None:\n        \"\"\"Checks if the executor is healthy. If not, it should raise an\n        exception.\"\"\"\n        self.check_health()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/tokenizer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/tokenizer_group/tokenizer_group.py\n\nfrom typing import List, Optional, Tuple, Union\n\nfrom transformers import (AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast)\n\nfrom vllm.lora.request import LoRARequest\nfrom vllm.utils import make_async, LRUCache\nfrom vllm.transformers_utils.tokenizers import *\n\n\nclass TokenizerGroup:\n    \"\"\"A group of tokenizers that can be used for LoRA adapters.\"\"\"\n\n    def __init__(self, tokenizer: PreTrainedTokenizer, enable_lora: bool, max_num_seqs: int,\n                 max_input_length: Optional[int]):\n        self.enable_lora = enable_lora\n        self.max_input_length = max_input_length\n        self.tokenizer = tokenizer\n        self.lora_tokenizers = LRUCache[PreTrainedTokenizer](capacity=max_num_seqs) if enable_lora else None\n\n    def ping(self) -> bool:\n        \"\"\"Check if the tokenizer group is alive.\"\"\"\n        return True\n\n    def get_max_input_len(self, lora_request: Optional[LoRARequest] = None) -> Optional[int]:\n        \"\"\"Get the maximum input length for the LoRA request.\"\"\"\n        return self.max_input_length\n\n    def encode(self,\n               prompt: str,\n               request_id: Optional[str] = None,\n               lora_request: Optional[LoRARequest] = None) -> List[int]:\n        tokenizer = self.get_lora_tokenizer(lora_request)\n        return tokenizer.encode(prompt)\n\n    async def encode_async(self,\n                           prompt: str,\n                           request_id: Optional[str] = None,\n                           lora_request: Optional[LoRARequest] = None) -> List[int]:\n        tokenizer = await self.get_lora_tokenizer_async(lora_request)\n        return tokenizer.encode(prompt)\n\n    def get_lora_tokenizer(self, lora_request: Optional[LoRARequest]) -> \"PreTrainedTokenizer\":\n        if not lora_request or not self.enable_lora:\n            return self.tokenizer\n        if lora_request.lora_int_id not in self.lora_tokenizers:\n            # TODO(sgm): the lora tokenizer is also passed, but may be different\n            tokenizer = self.tokenizer\n            # tokenizer = (get_lora_tokenizer(\n            #     lora_request, **self.tokenizer_config) or self.tokenizer)\n            self.lora_tokenizers.put(lora_request.lora_int_id, tokenizer)\n            return tokenizer\n        else:\n            return self.lora_tokenizers.get(lora_request.lora_int_id)\n\n    # FIXME(sgm): for simplicity, we assign the special token here\n    @property\n    def pad_token_id(self):\n        return self.tokenizer.pad_token_id\n\n    @property\n    def eos_token_id(self):\n        return self.tokenizer.eos_token_id\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_4_2/worker.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/worker.py\n\"\"\"A GPU worker class.\"\"\"\nimport os\nimport gc\nfrom typing import Dict, List, Tuple, Optional, Union\n\nimport torch\nimport torch.distributed\nimport torch.nn as nn\n\nfrom vllm.config import (CacheConfig, DeviceConfig, LoRAConfig, ParallelConfig, SchedulerConfig, VisionLanguageConfig)\nfrom vllm.model_executor import set_random_seed\nfrom vllm.sequence import SamplerOutput, ExecuteModelRequest\nfrom vllm.worker.cache_engine import CacheEngine\nfrom vllm.distributed.device_communicators import pynccl_utils\nfrom vllm.distributed.device_communicators.custom_all_reduce import (init_custom_ar)\n# TODO(sgm): check why vllm has similar file in vllm.model_executor.parallel_utils.parallel_state\nfrom vllm.distributed import get_tensor_model_parallel_cpu_group, init_distributed_environment, get_tensor_model_parallel_group\nfrom vllm.worker.worker import Worker, _check_if_gpu_supports_dtype\n\nfrom .model_runner import ModelRunner\nfrom .megatron_weight_loaders import load_megatron_weights\nfrom .hf_weight_loader import load_hf_weights\nfrom .dtensor_weight_loaders import load_dtensor_weights\nfrom .parallel_state import (ensure_model_parallel_initialized)\nfrom .config import ModelConfig, LoadConfig, LoadFormat\n\n\nclass Worker(Worker):\n    \"\"\"A worker class that executes (a partition of) the model on a GPU.\n\n    Each worker is associated with a single GPU. The worker is responsible for\n    maintaining the KV cache and executing the model on the GPU. In case of\n    distributed inference, each worker is assigned a partition of the model.\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        model_config: ModelConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        cache_config: CacheConfig,\n        load_config: LoadConfig,\n        local_rank: int,\n        rank: int,\n        distributed_init_method: str,\n        lora_config: Optional[LoRAConfig] = None,\n        vision_language_config: Optional[VisionLanguageConfig] = None,\n        is_driver_worker: bool = False,\n    ) -> None:\n        # self.model = model  # will be replaced in the init_model\n        self.model_config = model_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.cache_config = cache_config\n        self.local_rank = local_rank\n        self.rank = rank\n        self.distributed_init_method = distributed_init_method\n        self.lora_config = lora_config\n        self.load_config = load_config\n        self.is_driver_worker = is_driver_worker\n        if self.is_driver_worker:\n            assert self.rank == 0, \"The driver worker must have rank 0.\"\n\n        self.vision_language_config = vision_language_config\n        if self.vision_language_config:\n            assert not self.lora_config, (\"To be tested: vision language model with LoRA settings.\")\n\n        self.model_runner = ModelRunner(\n            model,\n            model_config,\n            parallel_config,\n            scheduler_config,\n            device_config,\n            load_config=load_config,\n            lora_config=self.lora_config,\n            kv_cache_dtype=self.cache_config.cache_dtype,\n            vision_language_config=vision_language_config,\n        )\n\n        # Uninitialized cache engine. Will be initialized by\n        # init_cache_engine.\n        self.cache_engine: CacheEngine = None\n        self.gpu_cache: List[torch.Tensor] = None\n\n        # NOTE(sgm): For offloading inference engine params\n        self.cpu_model = None\n\n    def init_device(self) -> None:\n        if self.device_config.device.type == \"cuda\":\n            # torch.distributed.all_reduce does not free the input tensor until\n            # the synchronization point. This causes the memory usage to grow\n            # as the number of all_reduce calls increases. This env var disables\n            # this behavior.\n            # Related issue:\n            # https://discuss.pytorch.org/t/cuda-allocation-lifetime-for-inputs-to-distributed-all-reduce/191573\n            os.environ[\"TORCH_NCCL_AVOID_RECORD_STREAMS\"] = \"1\"\n\n            # NOTE(sgm): Modify for verl, Env vars will be set by TORCHRUN.\n            self.rank = self.rank if self.rank is not None else int(os.getenv(\"RANK\", \"-1\"))\n            local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n            self.device = torch.device(f\"cuda:{local_rank}\")\n            if self.rank < 0:\n                raise ValueError(\"Invalid or unspecified rank.\")\n            torch.cuda.set_device(self.device)\n\n            # Use the world_size set by TORCHRUN\n            world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n            assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n            self.parallel_config.world_size = world_size\n\n            _check_if_gpu_supports_dtype(self.model_config.dtype)\n            torch.cuda.empty_cache()\n            self.init_gpu_memory = torch.cuda.mem_get_info()[0]\n        else:\n            raise RuntimeError(f\"Not support device type: {self.device_config.device}\")\n\n        # Initialize the distributed environment.\n        init_worker_distributed_environment(self.parallel_config, self.rank, self.distributed_init_method,\n                                            self.local_rank)\n        # Set random seed.\n        set_random_seed(self.model_config.seed)\n        # self.model = get_model(actor_model=self.model, model_config=self.model_config)\n\n    @torch.inference_mode()\n    def determine_num_available_blocks(self) -> Tuple[int, int]:\n        \"\"\"Profiles the peak memory usage of the model to determine how many\n        KV blocks may be allocated without OOMs.\n\n        The engine will first conduct a profiling of the existing memory usage.\n        Then, it calculate the maximum possible number of GPU and CPU blocks\n        that can be allocated with the remaining free memory.\n\n        .. tip::\n            You may limit the usage of GPU memory\n            by adjusting the `gpu_memory_utilization` parameter.\n        \"\"\"\n        # Profile the memory usage of the model and get the maximum number of\n        # cache blocks that can be allocated with the remaining free memory.\n        torch.cuda.empty_cache()\n        # torch.cuda.reset_peak_memory_stats()\n\n        # Execute a forward pass with dummy inputs to profile the memory usage\n        # of the model.\n        self.model_runner.profile_run()\n\n        # Calculate the number of blocks that can be allocated with the\n        # profiled peak memory.\n        torch.cuda.synchronize()\n        free_gpu_memory, total_gpu_memory = torch.cuda.mem_get_info()\n        peak_memory = total_gpu_memory - free_gpu_memory\n\n        assert peak_memory > 0, (\"Error in memory profiling. This happens when the GPU memory was \"\n                                 \"not properly cleaned up before initializing the vLLM instance.\")\n\n        cache_block_size = self.get_cache_block_size_bytes()\n\n        # NOTE(sgm) use the remaining memory\n        num_gpu_blocks = int((free_gpu_memory * self.cache_config.gpu_memory_utilization) // cache_block_size)\n        # num_gpu_blocks = int((total_gpu_memory * self.cache_config.gpu_memory_utilization - peak_memory) // cache_block_size)\n\n        num_cpu_blocks = int(self.cache_config.swap_space_bytes // cache_block_size)\n        num_gpu_blocks = max(num_gpu_blocks, 0)\n        num_cpu_blocks = max(num_cpu_blocks, 0)\n        if self.model_runner.lora_manager:\n            self.model_runner.remove_all_loras()\n\n        # NOTE(sgm): Add for verl, synchronize number of blocks with all the rank\n        num_gpu_blocks = torch.tensor([num_gpu_blocks], device='cuda')\n        num_cpu_blocks = torch.tensor([num_cpu_blocks], device='cuda')\n        torch.distributed.all_reduce(num_gpu_blocks,\n                                     op=torch.distributed.ReduceOp.MIN,\n                                     group=get_tensor_model_parallel_group())\n        torch.distributed.all_reduce(num_cpu_blocks,\n                                     op=torch.distributed.ReduceOp.MIN,\n                                     group=get_tensor_model_parallel_group())\n        num_gpu_blocks = num_gpu_blocks.item()\n        num_cpu_blocks = num_cpu_blocks.item()\n        gc.collect()\n        torch.cuda.empty_cache()\n        return num_gpu_blocks, num_cpu_blocks\n\n    def _init_cache_engine(self):\n        if self.cache_engine is None and self.gpu_cache is None:\n            super()._init_cache_engine()\n\n    def free_cache_engine(self):\n        # ensure `enforce_eager=True`\n        self.cache_engine = None\n        self.gpu_cache = None\n\n    @torch.inference_mode()\n    def execute_model(self, execute_model_req: Optional[ExecuteModelRequest] = None) -> List[SamplerOutput]:\n\n        if execute_model_req is None:\n            seq_group_metadata_list = None\n        else:\n            seq_group_metadata_list = execute_model_req.seq_group_metadata_list\n\n        # NOTE(sgm): each SPMD rank will have identical input\n        assert seq_group_metadata_list is not None\n        assert execute_model_req is not None\n        num_seq_groups = len(seq_group_metadata_list)\n        blocks_to_swap_in = execute_model_req.blocks_to_swap_in\n        blocks_to_swap_out = execute_model_req.blocks_to_swap_out\n        blocks_to_copy = execute_model_req.blocks_to_copy\n\n        self.cache_swap(blocks_to_swap_in, blocks_to_swap_out, blocks_to_copy)\n\n        # If there is no input, we don't need to execute the model.\n        if num_seq_groups == 0:\n            return []\n\n        output = self.model_runner.execute_model(seq_group_metadata_list, self.gpu_cache)\n\n        # Worker only supports single-step execution. Wrap the output in a list\n        # to conform to interface.\n        return [output]\n\n    # assume the input is .state_dict()\n    def sync_model_weights(self, actor_weights: Dict, load_format: str):\n        if load_format in [LoadFormat.MEGATRON, LoadFormat.AUTO]:\n            load_megatron_weights(actor_weights, self.model_runner.model)\n        elif load_format == LoadFormat.HF:\n            # full model state dict without no sharding\n            load_hf_weights(actor_weights, self.model_runner.model)\n        elif load_format == LoadFormat.DTENSOR:\n            load_dtensor_weights(actor_weights, self.model_runner.model)\n\n    def offload_model_weights(self) -> None:\n        if self.cpu_model == None:\n            self.cpu_model = {}\n            for name, params in self.model_runner.model.named_parameters():\n                self.cpu_model[name] = torch.empty_like(params, device='cpu')\n                params.data = self.cpu_model[name]\n        else:\n            for name, params in self.model_runner.model.named_parameters():\n                params.data = self.cpu_model[name]\n\n\ndef init_worker_distributed_environment(\n    parallel_config: ParallelConfig,\n    rank: int,\n    distributed_init_method: Optional[str] = \"env://\",\n    local_rank: int = -1,\n) -> None:\n    \"\"\"Initialize the distributed environment.\"\"\"\n    # NOTE(sgm) use tcp://localhost:xxxx will hang in HF setting without megatron\n    init_distributed_environment(parallel_config.world_size, rank, distributed_init_method, local_rank)\n\n    ensure_model_parallel_initialized(tensor_model_parallel_size=parallel_config.tensor_parallel_size,\n                                      pipeline_model_parallel_size=parallel_config.pipeline_parallel_size)\n\n    # TODO(sgm): check whether need this\n    # if pynccl_utils.is_initialized():\n    #     pynccl_world_size = pynccl_utils.get_world_size()\n    #     if pynccl_world_size != parallel_config.world_size:\n    #         raise RuntimeError(\n    #             \"pynccl is already initialized but the pynccl world \"\n    #             \"size does not match parallel_config.world_size \"\n    #             f\"({pynccl_world_size} vs. {parallel_config.world_size}).\")\n    # elif parallel_config.world_size > 1:\n    #     # NOTE(woosuk): We don't initialize pynccl process group when world size\n    #     # is 1.\n    #     # NOTE(kaichao): By default, pynccl is initialized for tp group.\n    #     pynccl_utils.init_process_group(\n    #         group=get_tensor_model_parallel_cpu_group())\n\n    # # Initialize a custom fast all-reduce implementation.\n    # if not parallel_config.disable_custom_all_reduce:\n    #     init_custom_ar()\n\n    # A small all_reduce for warmup.\n    torch.distributed.all_reduce(torch.zeros(1).cuda())\n    # if pynccl_utils.is_initialized():\n    #     pynccl_utils.all_reduce(torch.zeros(1).cuda())\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/arg_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/arg_utils.py\n\nimport os\nimport argparse\nimport dataclasses\nimport json\nfrom dataclasses import dataclass\nfrom typing import TYPE_CHECKING, List, Optional, Tuple, Type, Union\n\nimport torch.nn as nn\n\nfrom transformers import PretrainedConfig\nfrom .config import ModelConfig, LoadConfig\n\nfrom vllm.config import (CacheConfig, DecodingConfig, DeviceConfig, EngineConfig, LoRAConfig, MultiModalConfig,\n                         ObservabilityConfig, ParallelConfig, PromptAdapterConfig, SchedulerConfig, SpeculativeConfig,\n                         TokenizerPoolConfig)\nfrom vllm.executor.executor_base import ExecutorBase\nfrom vllm.logger import init_logger\nfrom vllm.utils import FlexibleArgumentParser\nfrom vllm.model_executor.layers.quantization import QUANTIZATION_METHODS\nfrom vllm.utils import str_to_int_tuple\n\nif TYPE_CHECKING:\n    from vllm.transformers_utils.tokenizer_group.base_tokenizer_group import (BaseTokenizerGroup)\n\nlogger = init_logger(__name__)\n\n\ndef nullable_str(val: str):\n    if not val or val == \"None\":\n        return None\n    return val\n\n\n@dataclass\nclass EngineArgs:\n    \"\"\"Arguments for vLLM engine.\"\"\"\n    model_hf_config: PretrainedConfig = None  # for verl\n    served_model_name = None  # TODO(sgm): check this\n    # tokenizer: Optional[str] = None # TODO(sgm): check this\n    skip_tokenizer_init: bool = False\n    tokenizer_mode: str = 'auto'\n    trust_remote_code: bool = False\n    download_dir: Optional[str] = None\n    load_format: str = 'auto'\n    dtype: str = 'auto'\n    kv_cache_dtype: str = 'auto'\n    quantization_param_path: Optional[str] = None\n    seed: int = 0\n    max_model_len: Optional[int] = None\n    worker_use_ray: bool = False\n    # Note: Specifying a custom executor backend by passing a class\n    # is intended for expert use only. The API may change without\n    # notice.\n    distributed_executor_backend: Optional[Union[str, Type[ExecutorBase]]] = None\n    pipeline_parallel_size: int = 1\n    tensor_parallel_size: int = 1\n    max_parallel_loading_workers: Optional[int] = None\n    block_size: int = 16\n    enable_prefix_caching: bool = False\n    disable_sliding_window: bool = False\n    use_v2_block_manager: bool = False\n    swap_space: int = 4  # GiB\n    cpu_offload_gb: int = 0  # GiB\n    gpu_memory_utilization: float = 0.90\n    max_num_batched_tokens: Optional[int] = None\n    max_num_seqs: int = 256\n    max_logprobs: int = 20  # Default value for OpenAI Chat Completions API\n    disable_log_stats: bool = False\n    revision: Optional[str] = None\n    code_revision: Optional[str] = None\n    rope_scaling: Optional[dict] = None\n    rope_theta: Optional[float] = None\n    tokenizer_revision: Optional[str] = None\n    quantization: Optional[str] = None\n    enforce_eager: bool = False\n    max_context_len_to_capture: Optional[int] = None\n    max_seq_len_to_capture: int = 8192\n    disable_custom_all_reduce: bool = False\n    tokenizer_pool_size: int = 0\n    # Note: Specifying a tokenizer pool by passing a class\n    # is intended for expert use only. The API may change without\n    # notice.\n    tokenizer_pool_type: Union[str, Type[\"BaseTokenizerGroup\"]] = \"ray\"\n    tokenizer_pool_extra_config: Optional[dict] = None\n    enable_lora: bool = False\n    max_loras: int = 1\n    max_lora_rank: int = 16\n    enable_prompt_adapter: bool = False\n    max_prompt_adapters: int = 1\n    max_prompt_adapter_token: int = 0\n    fully_sharded_loras: bool = False\n    lora_extra_vocab_size: int = 256\n    long_lora_scaling_factors: Optional[Tuple[float]] = None\n    lora_dtype: str = 'auto'\n    max_cpu_loras: Optional[int] = None\n    device: str = 'auto'\n    ray_workers_use_nsight: bool = False\n    num_gpu_blocks_override: Optional[int] = None\n    num_lookahead_slots: int = 0\n    model_loader_extra_config: Optional[dict] = None\n    ignore_patterns: Optional[Union[str, List[str]]] = None\n    preemption_mode: Optional[str] = None\n\n    scheduler_delay_factor: float = 0.0\n    enable_chunked_prefill: Optional[bool] = None\n\n    guided_decoding_backend: str = 'outlines'\n    # Speculative decoding configuration.\n    speculative_model: Optional[str] = None\n    speculative_draft_tensor_parallel_size: Optional[int] = None\n    num_speculative_tokens: Optional[int] = None\n    speculative_max_model_len: Optional[int] = None\n    speculative_disable_by_batch_size: Optional[int] = None\n    ngram_prompt_lookup_max: Optional[int] = None\n    ngram_prompt_lookup_min: Optional[int] = None\n    spec_decoding_acceptance_method: str = 'rejection_sampler'\n    typical_acceptance_sampler_posterior_threshold: Optional[float] = None\n    typical_acceptance_sampler_posterior_alpha: Optional[float] = None\n    qlora_adapter_name_or_path: Optional[str] = None\n    disable_logprobs_during_spec_decoding: Optional[bool] = None\n\n    otlp_traces_endpoint: Optional[str] = None\n\n    @staticmethod\n    def add_cli_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n        \"\"\"Shared CLI arguments for vLLM engine.\"\"\"\n        # Model arguments\n        # TODO(shengguangming): delete the unused args\n        parser.add_argument('--model',\n                            type=str,\n                            default='facebook/opt-125m',\n                            help='name or path of the huggingface model to use')\n        parser.add_argument('--tokenizer',\n                            type=str,\n                            default=EngineArgs.tokenizer,\n                            help='name or path of the huggingface tokenizer to use')\n        parser.add_argument('--revision',\n                            type=str,\n                            default=None,\n                            help='the specific model version to use. It can be a branch '\n                            'name, a tag name, or a commit id. If unspecified, will use '\n                            'the default version.')\n        parser.add_argument('--tokenizer-revision',\n                            type=str,\n                            default=None,\n                            help='the specific tokenizer version to use. It can be a branch '\n                            'name, a tag name, or a commit id. If unspecified, will use '\n                            'the default version.')\n        parser.add_argument('--tokenizer-mode',\n                            type=str,\n                            default=EngineArgs.tokenizer_mode,\n                            choices=['auto', 'slow'],\n                            help='tokenizer mode. \"auto\" will use the fast '\n                            'tokenizer if available, and \"slow\" will '\n                            'always use the slow tokenizer.')\n        parser.add_argument('--trust-remote-code', action='store_true', help='trust remote code from huggingface')\n        parser.add_argument('--download-dir',\n                            type=str,\n                            default=EngineArgs.download_dir,\n                            help='directory to download and load the weights, '\n                            'default to the default cache dir of '\n                            'huggingface')\n        parser.add_argument('--load-format',\n                            type=str,\n                            default=EngineArgs.load_format,\n                            choices=['auto', 'pt', 'safetensors', 'npcache', 'dummy'],\n                            help='The format of the model weights to load. '\n                            '\"auto\" will try to load the weights in the safetensors format '\n                            'and fall back to the pytorch bin format if safetensors format '\n                            'is not available. '\n                            '\"pt\" will load the weights in the pytorch bin format. '\n                            '\"safetensors\" will load the weights in the safetensors format. '\n                            '\"npcache\" will load the weights in pytorch format and store '\n                            'a numpy cache to speed up the loading. '\n                            '\"dummy\" will initialize the weights with random values, '\n                            'which is mainly for profiling.')\n        parser.add_argument('--dtype',\n                            type=str,\n                            default=EngineArgs.dtype,\n                            choices=['auto', 'half', 'float16', 'bfloat16', 'float', 'float32'],\n                            help='data type for model weights and activations. '\n                            'The \"auto\" option will use FP16 precision '\n                            'for FP32 and FP16 models, and BF16 precision '\n                            'for BF16 models.')\n        parser.add_argument('--max-model-len',\n                            type=int,\n                            default=None,\n                            help='model context length. If unspecified, '\n                            'will be automatically derived from the model.')\n        # Parallel arguments\n        parser.add_argument('--worker-use-ray',\n                            action='store_true',\n                            help='use Ray for distributed serving, will be '\n                            'automatically set when using more than 1 GPU')\n        parser.add_argument('--pipeline-parallel-size',\n                            '-pp',\n                            type=int,\n                            default=EngineArgs.pipeline_parallel_size,\n                            help='number of pipeline stages')\n        parser.add_argument('--tensor-parallel-size',\n                            '-tp',\n                            type=int,\n                            default=EngineArgs.tensor_parallel_size,\n                            help='number of tensor parallel replicas')\n        # KV cache arguments\n        parser.add_argument('--block-size',\n                            type=int,\n                            default=EngineArgs.block_size,\n                            choices=[8, 16, 32],\n                            help='token block size')\n        # TODO(woosuk): Support fine-grained seeds (e.g., seed per request).\n        parser.add_argument('--seed', type=int, default=EngineArgs.seed, help='random seed')\n        parser.add_argument('--swap-space',\n                            type=int,\n                            default=EngineArgs.swap_space,\n                            help='CPU swap space size (GiB) per GPU')\n        parser.add_argument('--gpu-memory-utilization',\n                            type=float,\n                            default=EngineArgs.gpu_memory_utilization,\n                            help='the percentage of GPU memory to be used for'\n                            'the model executor')\n        parser.add_argument('--max-num-batched-tokens',\n                            type=int,\n                            default=EngineArgs.max_num_batched_tokens,\n                            help='maximum number of batched tokens per '\n                            'iteration')\n        parser.add_argument('--max-num-seqs',\n                            type=int,\n                            default=EngineArgs.max_num_seqs,\n                            help='maximum number of sequences per iteration')\n        parser.add_argument('--disable-log-stats', action='store_true', help='disable logging statistics')\n        # Quantization settings.\n        parser.add_argument('--quantization',\n                            '-q',\n                            type=str,\n                            choices=['awq', None],\n                            default=None,\n                            help='Method used to quantize the weights')\n        return parser\n\n    @classmethod\n    def from_cli_args(cls, args: argparse.Namespace) -> 'EngineArgs':\n        # Get the list of attributes of this dataclass.\n        attrs = [attr.name for attr in dataclasses.fields(cls)]\n        # Set the attributes from the parsed arguments.\n        engine_args = cls(**{attr: getattr(args, attr) for attr in attrs})\n        return engine_args\n\n    def create_engine_config(\n        self,\n    ) -> EngineConfig:\n        # bitsandbytes quantization needs a specific model loader\n        # so we make sure the quant method and the load format are consistent\n        if (self.quantization == \"bitsandbytes\" or\n           self.qlora_adapter_name_or_path is not None) and \\\n           self.load_format != \"bitsandbytes\":\n            raise ValueError(\"BitsAndBytes quantization and QLoRA adapter only support \"\n                             f\"'bitsandbytes' load format, but got {self.load_format}\")\n\n        if (self.load_format == \"bitsandbytes\" or\n            self.qlora_adapter_name_or_path is not None) and \\\n            self.quantization != \"bitsandbytes\":\n            raise ValueError(\"BitsAndBytes load format and QLoRA adapter only support \"\n                             f\"'bitsandbytes' quantization, but got {self.quantization}\")\n\n        assert self.cpu_offload_gb >= 0, (\"CPU offload space must be non-negative\"\n                                          f\", but got {self.cpu_offload_gb}\")\n\n        multimodal_config = MultiModalConfig()\n        device_config = DeviceConfig(self.device)\n        # NOTE(sgm): we only modify ModelConfig, other configs are import from vllm\n        model_config = ModelConfig(hf_config=self.model_hf_config,\n                                   tokenizer_mode=self.tokenizer_mode,\n                                   trust_remote_code=self.trust_remote_code,\n                                   dtype=self.dtype,\n                                   seed=self.seed,\n                                   revision=self.revision,\n                                   code_revision=self.code_revision,\n                                   rope_scaling=self.rope_scaling,\n                                   rope_theta=self.rope_theta,\n                                   tokenizer_revision=self.tokenizer_revision,\n                                   max_model_len=self.max_model_len,\n                                   quantization=self.quantization,\n                                   quantization_param_path=self.quantization_param_path,\n                                   enforce_eager=self.enforce_eager,\n                                   max_context_len_to_capture=self.max_context_len_to_capture,\n                                   max_seq_len_to_capture=self.max_seq_len_to_capture,\n                                   max_logprobs=self.max_logprobs,\n                                   disable_sliding_window=self.disable_sliding_window,\n                                   skip_tokenizer_init=self.skip_tokenizer_init,\n                                   served_model_name=self.served_model_name,\n                                   multimodal_config=multimodal_config)\n        cache_config = CacheConfig(\n            block_size=self.block_size,\n            gpu_memory_utilization=self.gpu_memory_utilization,\n            swap_space=self.swap_space,\n            cache_dtype=self.kv_cache_dtype,\n            num_gpu_blocks_override=self.num_gpu_blocks_override,\n            sliding_window=model_config.get_sliding_window(),\n            enable_prefix_caching=self.enable_prefix_caching,\n            cpu_offload_gb=self.cpu_offload_gb,\n        )\n        parallel_config = ParallelConfig(pipeline_parallel_size=self.pipeline_parallel_size,\n                                         tensor_parallel_size=self.tensor_parallel_size,\n                                         worker_use_ray=self.worker_use_ray,\n                                         max_parallel_loading_workers=self.max_parallel_loading_workers,\n                                         disable_custom_all_reduce=self.disable_custom_all_reduce,\n                                         tokenizer_pool_config=TokenizerPoolConfig.create_config(\n                                             self.tokenizer_pool_size,\n                                             self.tokenizer_pool_type,\n                                             self.tokenizer_pool_extra_config,\n                                         ),\n                                         ray_workers_use_nsight=self.ray_workers_use_nsight,\n                                         distributed_executor_backend=self.distributed_executor_backend)\n\n        # NOTE[VERL]: Use the world_size set by TORCHRUN\n        world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n        assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n        parallel_config.world_size = world_size\n\n        max_model_len = model_config.max_model_len\n        use_long_context = max_model_len > 32768\n        if self.enable_chunked_prefill is None:\n            # If not explicitly set, enable chunked prefill by default for\n            # long context (> 32K) models. This is to avoid OOM errors in the\n            # initial memory profiling phase.\n            if use_long_context:\n                is_gpu = device_config.device_type == \"cuda\"\n                use_sliding_window = (model_config.get_sliding_window() is not None)\n                use_spec_decode = self.speculative_model is not None\n                has_seqlen_agnostic_layers = (model_config.contains_seqlen_agnostic_layers(parallel_config))\n                if (is_gpu and not use_sliding_window and not use_spec_decode and not self.enable_lora and\n                        not self.enable_prompt_adapter and not self.enable_prefix_caching and\n                        not has_seqlen_agnostic_layers):\n                    self.enable_chunked_prefill = True\n                    logger.warning(\"Chunked prefill is enabled by default for models with \"\n                                   \"max_model_len > 32K. Currently, chunked prefill might \"\n                                   \"not work with some features or models. If you \"\n                                   \"encounter any issues, please disable chunked prefill \"\n                                   \"by setting --enable-chunked-prefill=False.\")\n            if self.enable_chunked_prefill is None:\n                self.enable_chunked_prefill = False\n\n        if not self.enable_chunked_prefill and use_long_context:\n            logger.warning(\n                \"The model has a long context length (%s). This may cause OOM \"\n                \"errors during the initial memory profiling phase, or result \"\n                \"in low performance due to small KV cache space. Consider \"\n                \"setting --max-model-len to a smaller value.\", max_model_len)\n\n        # TODO: spec config\n        speculative_config = SpeculativeConfig.maybe_create_spec_config(\n            target_model_config=model_config,\n            target_parallel_config=parallel_config,\n            target_dtype=self.dtype,\n            speculative_model=self.speculative_model,\n            speculative_draft_tensor_parallel_size = \\\n                self.speculative_draft_tensor_parallel_size,\n            num_speculative_tokens=self.num_speculative_tokens,\n            speculative_disable_by_batch_size=self.\n            speculative_disable_by_batch_size,\n            speculative_max_model_len=self.speculative_max_model_len,\n            enable_chunked_prefill=self.enable_chunked_prefill,\n            use_v2_block_manager=self.use_v2_block_manager,\n            disable_log_stats=self.disable_log_stats,\n            ngram_prompt_lookup_max=self.ngram_prompt_lookup_max,\n            ngram_prompt_lookup_min=self.ngram_prompt_lookup_min,\n            draft_token_acceptance_method=\\\n                self.spec_decoding_acceptance_method,\n            typical_acceptance_sampler_posterior_threshold=self.\n            typical_acceptance_sampler_posterior_threshold,\n            typical_acceptance_sampler_posterior_alpha=self.\n            typical_acceptance_sampler_posterior_alpha,\n            disable_logprobs=self.disable_logprobs_during_spec_decoding,\n        )\n\n        scheduler_config = SchedulerConfig(\n            max_num_batched_tokens=self.max_num_batched_tokens,\n            max_num_seqs=self.max_num_seqs,\n            max_model_len=model_config.max_model_len,\n            use_v2_block_manager=self.use_v2_block_manager,\n            num_lookahead_slots=(self.num_lookahead_slots\n                                 if speculative_config is None else speculative_config.num_lookahead_slots),\n            delay_factor=self.scheduler_delay_factor,\n            enable_chunked_prefill=self.enable_chunked_prefill,\n            embedding_mode=model_config.embedding_mode,\n            preemption_mode=self.preemption_mode,\n        )\n        lora_config = LoRAConfig(max_lora_rank=self.max_lora_rank,\n                                 max_loras=self.max_loras,\n                                 fully_sharded_loras=self.fully_sharded_loras,\n                                 lora_extra_vocab_size=self.lora_extra_vocab_size,\n                                 long_lora_scaling_factors=self.long_lora_scaling_factors,\n                                 lora_dtype=self.lora_dtype,\n                                 max_cpu_loras=self.max_cpu_loras if self.max_cpu_loras and self.max_cpu_loras > 0 else\n                                 None) if self.enable_lora else None\n\n        if self.qlora_adapter_name_or_path is not None and \\\n            self.qlora_adapter_name_or_path != \"\":\n            if self.model_loader_extra_config is None:\n                self.model_loader_extra_config = {}\n            self.model_loader_extra_config[\"qlora_adapter_name_or_path\"] = self.qlora_adapter_name_or_path\n\n        load_config = LoadConfig(\n            load_format=self.load_format,\n            download_dir=self.download_dir,\n            model_loader_extra_config=self.model_loader_extra_config,\n            ignore_patterns=self.ignore_patterns,\n        )\n\n        prompt_adapter_config = PromptAdapterConfig(\n            max_prompt_adapters=self.max_prompt_adapters,\n            max_prompt_adapter_token=self.max_prompt_adapter_token) \\\n                                        if self.enable_prompt_adapter else None\n\n        decoding_config = DecodingConfig(guided_decoding_backend=self.guided_decoding_backend)\n\n        observability_config = ObservabilityConfig(otlp_traces_endpoint=self.otlp_traces_endpoint)\n\n        if (model_config.get_sliding_window() is not None and scheduler_config.chunked_prefill_enabled and\n                not scheduler_config.use_v2_block_manager):\n            raise ValueError(\"Chunked prefill is not supported with sliding window. \"\n                             \"Set --disable-sliding-window to disable sliding window.\")\n\n        return EngineConfig(\n            model_config=model_config,\n            cache_config=cache_config,\n            parallel_config=parallel_config,\n            scheduler_config=scheduler_config,\n            device_config=device_config,\n            lora_config=lora_config,\n            multimodal_config=multimodal_config,\n            speculative_config=speculative_config,\n            load_config=load_config,\n            decoding_config=decoding_config,\n            observability_config=observability_config,\n            prompt_adapter_config=prompt_adapter_config,\n        )\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/config.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/config.py\n\nimport enum\nimport json\nfrom typing import List, Optional, Union\nfrom dataclasses import dataclass, field, fields\n\nimport torch\nfrom transformers import PretrainedConfig\n\nfrom vllm.logger import init_logger\nfrom vllm.model_executor.layers.quantization import get_quantization_config\nfrom vllm.transformers_utils.config import get_hf_text_config\nfrom vllm.utils import is_hip, print_warning_once\n# Add for verl\nfrom vllm.config import ModelConfig, _get_and_verify_dtype, _get_and_verify_max_len, get_served_model_name\n\nGPTQMarlinConfig = get_quantization_config(\"gptq_marlin\")\n\nlogger = init_logger(__name__)\n\n_GB = 1 << 30\n\n\nclass ModelConfig(ModelConfig):\n    \"\"\"Configuration for the model.\n\n    Args:\n        model: Name or path of the huggingface model to use.\n        tokenizer: Name or path of the huggingface tokenizer to use.\n        tokenizer_mode: Tokenizer mode. \"auto\" will use the fast tokenizer if\n            available, and \"slow\" will always use the slow tokenizer.\n        trust_remote_code: Trust remote code (e.g., from HuggingFace) when\n            downloading the model and tokenizer.\n        download_dir: Directory to download and load the weights, default to the\n            default cache directory of huggingface.\n        load_format: The format of the model weights to load:\n            \"auto\" will try to load the weights in the safetensors format and\n                fall back to the pytorch bin format if safetensors format is\n                not available.\n            \"pt\" will load the weights in the pytorch bin format.\n            \"safetensors\" will load the weights in the safetensors format.\n            \"npcache\" will load the weights in pytorch format and store\n                a numpy cache to speed up the loading.\n            \"dummy\" will initialize the weights with random values, which is\n                mainly for profiling.\n        dtype: Data type for model weights and activations. The \"auto\" option\n            will use FP16 precision for FP32 and FP16 models, and BF16 precision\n            for BF16 models.\n        seed: Random seed for reproducibility.\n        revision: The specific model version to use. It can be a branch name,\n            a tag name, or a commit id. If unspecified, will use the default\n            version.\n        code_revision: The specific revision to use for the model code on\n            Hugging Face Hub. It can be a branch name, a tag name, or a\n            commit id. If unspecified, will use the default version.\n        tokenizer_revision: The specific tokenizer version to use. It can be a\n            branch name, a tag name, or a commit id. If unspecified, will use\n            the default version.\n        max_model_len: Maximum length of a sequence (including prompt and\n            output). If None, will be derived from the model.\n        quantization: Quantization method that was used to quantize the model\n            weights. If None, we assume the model weights are not quantized.\n        quantization_param_path: Path to JSON file containing scaling factors.\n            Used to load KV cache scaling factors into the model when KV cache\n            type is FP8_E4M3 on ROCm (AMD GPU). In the future these will also\n            be used to load activation and weight scaling factors when the\n            model dtype is FP8_E4M3 on ROCm.\n        enforce_eager: Whether to enforce eager execution. If True, we will\n            disable CUDA graph and always execute the model in eager mode.\n            If False, we will use CUDA graph and eager execution in hybrid.\n        max_context_len_to_capture: Maximum context len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode (DEPRECATED. Use max_seq_len_to_capture instead).\n        max_seq_len_to_capture: Maximum sequence len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode\n        skip_tokenizer_init: If true, skip initialization of tokenizer and\n            detokenizer.\n        served_model_name: The model name used in metrics tag `model_name`,\n            matches the model name exposed via the APIs. If multiple model \n            names provided, the first name will be used. If not specified, \n            the model name will be the same as `model`.\n    \"\"\"\n\n    def __init__(\n        self,\n        hf_config: PretrainedConfig,\n        tokenizer_mode: str,\n        trust_remote_code: bool,\n        dtype: Union[str, torch.dtype],\n        seed: int,\n        revision: Optional[str] = None,\n        code_revision: Optional[str] = None,\n        rope_scaling: Optional[dict] = None,\n        rope_theta: Optional[float] = None,\n        tokenizer_revision: Optional[str] = None,\n        max_model_len: Optional[int] = None,\n        quantization: Optional[str] = None,\n        quantization_param_path: Optional[str] = None,\n        enforce_eager: bool = False,\n        max_context_len_to_capture: Optional[int] = None,\n        max_seq_len_to_capture: Optional[int] = None,\n        max_logprobs: int = 20,\n        disable_sliding_window: bool = False,\n        skip_tokenizer_init: bool = False,\n        served_model_name: Optional[Union[str, List[str]]] = None,\n        multimodal_config: Optional[\"MultiModalConfig\"] = None,\n    ) -> None:\n        self.model = hf_config._name_or_path\n        self.tokenizer = hf_config._name_or_path\n        # NOTE(sgm): same as open-sourced\n        self.tokenizer_mode = tokenizer_mode\n        self.trust_remote_code = trust_remote_code\n        self.seed = seed\n        self.revision = revision\n        self.code_revision = code_revision\n        self.rope_scaling = rope_scaling\n        self.rope_theta = rope_theta\n        # The tokenizer version is consistent with the model version by default.\n        if tokenizer_revision is None:\n            self.tokenizer_revision = revision\n        else:\n            self.tokenizer_revision = tokenizer_revision\n        self.quantization = quantization\n        self.quantization_param_path = quantization_param_path\n        self.enforce_eager = enforce_eager\n        if max_context_len_to_capture is not None:\n            raise ValueError(\"`max_context_len_to_capture` is deprecated. \"\n                             \"Use `max_seq_len_to_capture` instead.\")\n        self.max_seq_len_to_capture = max_seq_len_to_capture\n        self.max_logprobs = max_logprobs\n        self.disable_sliding_window = disable_sliding_window\n        self.skip_tokenizer_init = skip_tokenizer_init\n\n        # self.hf_config = get_config(model, trust_remote_code, revision)\n        self.hf_config = hf_config\n        self.hf_text_config = get_hf_text_config(hf_config)\n        self.dtype = _get_and_verify_dtype(self.hf_text_config, dtype)\n        # self.served_model_name = get_served_model_name(model,\n        #                                                served_model_name)\n        # self._verify_load_format()\n        # self._verify_tokenizer_mode()\n        if (not self.disable_sliding_window and self.hf_text_config.model_type == \"gemma2\" and\n                self.hf_text_config.sliding_window is not None):\n            print_warning_once(\"Gemma 2 uses sliding window attention for every odd layer, \"\n                               \"which is currently not supported by vLLM. Disabling sliding \"\n                               \"window and capping the max length to the sliding window size \"\n                               f\"({self.hf_text_config.sliding_window}).\")\n            self.disable_sliding_window = True\n\n        self.max_model_len = _get_and_verify_max_len(hf_config=self.hf_text_config,\n                                                     max_model_len=max_model_len,\n                                                     disable_sliding_window=self.disable_sliding_window,\n                                                     sliding_window_len=self.get_hf_config_sliding_window())\n        self.served_model_name = get_served_model_name(\n            self.model,  # str\n            served_model_name)\n        self.multimodal_config = multimodal_config\n\n        if not self.skip_tokenizer_init:\n            self._verify_tokenizer_mode()\n        self._verify_embedding_mode()\n        self._verify_quantization()\n        self._verify_cuda_graph()\n\n\nclass LoadFormat(str, enum.Enum):\n    AUTO = 'auto'\n    MEGATRON = \"megatron\"\n    HF = \"hf\"\n    DTENSOR = 'dtensor'\n    DUMMY_HF = 'dummy_hf'\n    DUMMY_MEGATRON = 'dummy_megatron'\n    DUMMY_DTENSOR = 'dummy_dtensor'\n\n\n# TODO: check whether this is necessary\n@dataclass\nclass LoadConfig:\n    \"\"\"\n        download_dir: Directory to download and load the weights, default to the\n            default cache directory of huggingface.\n        load_format: The format of the model weights to load:\n            \"auto\" will try to load the weights in the safetensors format and\n                fall back to the pytorch bin format if safetensors format is\n                not available.\n            \"pt\" will load the weights in the pytorch bin format.\n            \"safetensors\" will load the weights in the safetensors format.\n            \"npcache\" will load the weights in pytorch format and store\n                a numpy cache to speed up the loading.\n            \"dummy\" will initialize the weights with random values, which is\n                mainly for profiling.\n            \"tensorizer\" will use CoreWeave's tensorizer library for\n                fast weight loading.\n            \"bitsandbytes\" will load nf4 type weights.\n        ignore_patterns: The list of patterns to ignore when loading the model.\n            Default to \"original/**/*\" to avoid repeated loading of llama's \n            checkpoints.\n            \n    \"\"\"\n\n    load_format: Union[str, LoadFormat, \"BaseModelLoader\"] = LoadFormat.AUTO\n    download_dir: Optional[str] = None\n    model_loader_extra_config: Optional[Union[str, dict]] = field(default_factory=dict)\n    ignore_patterns: Optional[Union[List[str], str]] = None\n\n    def __post_init__(self):\n        model_loader_extra_config = self.model_loader_extra_config or {}\n        if isinstance(model_loader_extra_config, str):\n            self.model_loader_extra_config = json.loads(model_loader_extra_config)\n        self._verify_load_format()\n\n        if self.ignore_patterns is not None and len(self.ignore_patterns) > 0:\n            logger.info(\"Ignoring the following patterns when downloading weights: %s\", self.ignore_patterns)\n        else:\n            self.ignore_patterns = [\"original/**/*\"]\n\n    def _verify_load_format(self) -> None:\n        if not isinstance(self.load_format, str):\n            return\n\n        load_format = self.load_format.lower()\n        self.load_format = LoadFormat(load_format)\n\n        rocm_not_supported_load_format: List[str] = []\n        if is_hip() and load_format in rocm_not_supported_load_format:\n            rocm_supported_load_format = [\n                f for f in LoadFormat.__members__ if (f not in rocm_not_supported_load_format)\n            ]\n            raise ValueError(f\"load format '{load_format}' is not supported in ROCm. \"\n                             f\"Supported load formats are \"\n                             f\"{rocm_supported_load_format}\")\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/dtensor_weight_loaders.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models\n\nfrom typing import Dict, Iterable, Tuple\nimport torch\nimport torch.nn as nn\nfrom torch.distributed._tensor import DTensor, Shard, Replicate\n\nfrom vllm.model_executor.layers.linear import *\nfrom vllm.model_executor.models import ModelRegistry\nfrom vllm.model_executor.model_loader.weight_utils import default_weight_loader\nfrom vllm.model_executor.models.utils import is_pp_missing_parameter\n\n\ndef gemma_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        for (param_name, shard_name, shard_id) in stacked_params_mapping:\n            if shard_name not in name:\n                continue\n            stacked_name = name.replace(shard_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if stacked_name.endswith(\".bias\") and stacked_name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[stacked_name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # lm_head is not used in vllm as it is tied with embed_token.\n            # To prevent errors, skip loading lm_head.weight.\n            if \"lm_head.weight\" in name:\n                continue\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef gptbigcode_dtensor_load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"lm_head.weight\" in name:\n            continue\n        if \".attn.bias\" in name:\n            # Skip attention mask.\n            # NOTE: \"c_attn.bias\" should not be skipped.\n            continue\n        local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n        param = params_dict[name]\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef starcoder2_dtensor_load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n    ]\n\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n\n        for (param_name, weight_name, shard_id) in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef llama_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\".qkv_proj\", \".q_proj\", \"q\"),\n        (\".qkv_proj\", \".k_proj\", \"k\"),\n        (\".qkv_proj\", \".v_proj\", \"v\"),\n        (\".gate_up_proj\", \".gate_proj\", 0),\n        (\".gate_up_proj\", \".up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if (\"rotary_emb.cos_cached\" in name or \"rotary_emb.sin_cached\" in name):\n            # Models trained using ColossalAI may include these tensors in\n            # the checkpoint. Skip them.\n            continue\n        # With tie_word_embeddings, we can skip lm_head.weight\n        # The weight might appear unnecessarily in the files if the model is\n        # processed with quantization, LoRA, fine-tuning, etc.\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for (param_name, weight_name, shard_id) in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight)\n\n\ndef qwen2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for (param_name, weight_name, shard_id) in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\nfrom vllm.model_executor.layers.fused_moe import FusedMoE\n\n\ndef deepseekv2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n\n    # Params for weights, fp8 weight scales, fp8 activation scales\n    # (param_name, weight_name, expert_id, shard_id)\n    expert_params_mapping = FusedMoE.make_expert_params_mapping(ckpt_gate_proj_name=\"gate_proj\",\n                                                                ckpt_down_proj_name=\"down_proj\",\n                                                                ckpt_up_proj_name=\"up_proj\",\n                                                                num_experts=vllm_model.config.n_routed_experts)\n\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        for (param_name, weight_name, shard_id) in stacked_params_mapping:\n            # Skip non-stacked layers and experts (experts handled below).\n            if weight_name not in name:\n                continue\n            # We have mlp.experts[0].gate_proj in the checkpoint.\n            # Since we handle the experts below in expert_params_mapping,\n            # we need to skip here BEFORE we update the name, otherwise\n            # name will be updated to mlp.experts[0].gate_up_proj, which\n            # will then be updated below in expert_params_mapping\n            # for mlp.experts[0].gate_gate_up_proj, which breaks load.\n            if ((\"mlp.experts.\" in name) and name not in params_dict):\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n\n            if is_pp_missing_parameter(name, vllm_model):\n                continue\n\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            for mapping in expert_params_mapping:\n                param_name, weight_name, expert_id, shard_id = mapping\n                if weight_name not in name:\n                    continue\n                name = name.replace(weight_name, param_name)\n\n                if is_pp_missing_parameter(name, vllm_model):\n                    continue\n\n                param = params_dict[name]\n                local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(param,\n                              local_loaded_weight.to(dtype=param.dtype),\n                              weight_name,\n                              shard_id=shard_id,\n                              expert_id=expert_id)\n                break\n            else:\n                # Skip loading extra bias for GPTQ models.\n                if name.endswith(\".bias\") and name not in params_dict:\n                    continue\n\n                if is_pp_missing_parameter(name, vllm_model):\n                    continue\n\n                param = params_dict[name]\n                local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef gpt2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    pass\n\n\ndef redistribute_dtensor(param_name: str, loaded_weights: DTensor, parallelize_plan: Dict = None):\n    param_name = _process_parameter_names(name=param_name)\n    if parallelize_plan is not None:\n        assert param_name in parallelize_plan.keys(), \\\n            f\"param name: {param_name} not in parallelize_plan :{parallelize_plan.keys()}\"\n        placement = parallelize_plan[param_name]\n        local_loaded_weights = loaded_weights.redistribute(device_mesh=loaded_weights.device_mesh,\n                                                           placements=placement).to_local()\n    else:\n        local_loaded_weights = loaded_weights.full_tensor()\n    return local_loaded_weights\n\n\ndef _process_parameter_names(name):\n    # Remove '.weight' if it exists at the end of the string\n    if name.endswith(\".weight\"):\n        name = name[:-7]\n\n    # Remove 'model.layers.x.' or 'model.' prefix\n    if \"model.layers\" in name:\n        parts = name.split('.')\n        # Reconstruct the string without 'model.layers.x.'\n        name = '.'.join(parts[3:])  # parts[0] is 'model', parts[1] is 'layers', parts[2] is 'x'\n    elif name.startswith(\"model.\"):\n        name = name[6:]  # Remove 'model.'\n\n    return name\n\n\n__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__ = {\n    'GPT2LMHeadModel': gpt2_dtensor_weight_loader,\n    'LlamaForCausalLM': llama_dtensor_weight_loader,\n    'LLaMAForCausalLM': llama_dtensor_weight_loader,\n    'MistralForCausalLM': llama_dtensor_weight_loader,  # mistral is the same as llama in vLLM\n    'InternLMForCausalLM': llama_dtensor_weight_loader,\n    'AquilaModel': llama_dtensor_weight_loader,\n    'AquilaForCausalLM': llama_dtensor_weight_loader,\n    'Phi3ForCausalLM': llama_dtensor_weight_loader,\n    'GemmaForCausalLM': gemma_dtensor_weight_loader,\n    'Gemma2ForCausalLM': gemma_dtensor_weight_loader,\n    'GPTBigCodeForCausalLM': gptbigcode_dtensor_load_weights,\n    'Starcoder2ForCausalLM': starcoder2_dtensor_load_weights,\n    'Qwen2ForCausalLM': qwen2_dtensor_weight_loader,\n    'DeepseekV2ForCausalLM': deepseekv2_dtensor_weight_loader\n}\n\n\n# the actor model is .state_dict()\n# Load dtensor weights\ndef load_dtensor_weights(actor_weights: Dict, vllm_model: nn.Module):\n    weight_loader = _get_model_weight_loader(vllm_model.__class__.__name__)\n    weight_loader(actor_weights, vllm_model)\n    # NOTE(sgm) to reduce peak memory usage, we offload vllm model to cpu\n    # after init, and we need this after sync model weights for in first iter.\n    vllm_model = vllm_model.cuda()\n\n\ndef _get_model_weight_loader(arch: str):\n    if arch in __MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__:\n        return __MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__.keys()}\")\n\n\n# NOTE(sgm): we use per-parameter weight loader in each vllm sub\ndef update_dtensor_weight_loader():\n    pass\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/hf_weight_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models\n\nfrom typing import Dict, Union, Optional, Iterable, Tuple\n\nimport torch\nimport torch.nn as nn\n\nfrom vllm.model_executor.model_loader.utils import set_default_torch_dtype\nfrom vllm.model_executor.model_loader.weight_utils import default_weight_loader\n\n\ndef update_hf_weight_loader():\n    print('no hf weight loader need to be updated')\n    return\n\n\ndef load_hf_weights(actor_weights: Dict, vllm_model: nn.Module):\n    assert isinstance(actor_weights, Dict)\n    with set_default_torch_dtype(next(vllm_model.parameters()).dtype):  # TODO\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in actor_weights.keys():\n            del actor_weights[\"lm_head.weight\"]\n        vllm_model.load_weights(actor_weights.items())\n    for _, module in vllm_model.named_modules():\n        quant_method = getattr(module, \"quant_method\", None)\n        if quant_method is not None:\n            quant_method.process_weights_after_loading(module)\n        # FIXME: Remove this after Mixtral is updated\n        # to use quant_method.\n        if hasattr(module, \"process_weights_after_loading\"):\n            module.process_weights_after_loading()\n    vllm_model = vllm_model.cuda()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/llm.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/llm.py\n\nfrom contextlib import contextmanager\nfrom typing import ClassVar, List, Optional, Sequence, Union, cast, overload, Dict, Tuple\n\nfrom tqdm import tqdm\nfrom transformers import PreTrainedTokenizer, PreTrainedTokenizerFast\nfrom transformers import PretrainedConfig\nimport torch.nn as nn\nfrom .arg_utils import EngineArgs\nfrom .llm_engine_sp import LLMEngine\nfrom vllm import LLM\nfrom vllm.inputs import (PromptInputs, TextPrompt, TokensPrompt, parse_and_batch_prompt)\nfrom vllm.logger import init_logger\nfrom vllm.lora.request import LoRARequest\nfrom vllm.model_executor.guided_decoding import (GuidedDecodingRequest, get_local_guided_decoding_logits_processor)\nfrom vllm.model_executor.guided_decoding.guided_fields import LLMGuidedOptions\nfrom vllm.outputs import EmbeddingRequestOutput, RequestOutput\nfrom vllm.pooling_params import PoolingParams\nfrom vllm.prompt_adapter.request import PromptAdapterRequest\nfrom vllm.sampling_params import SamplingParams\nfrom vllm.transformers_utils.tokenizer import get_cached_tokenizer\nfrom vllm.usage.usage_lib import UsageContext\nfrom vllm.utils import Counter, deprecate_kwargs\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\nfrom verl.workers.rollout.tokenizer import HybridEngineBaseTokenizer\n\n\nclass LLM(LLM):\n    \"\"\"An LLM for generating texts from given prompts and sampling parameters.\n\n    This class includes a tokenizer, a language model (possibly distributed\n    across multiple GPUs), and GPU memory space allocated for intermediate\n    states (aka KV cache). Given a batch of prompts and sampling parameters,\n    this class generates texts from the model, using an intelligent batching\n    mechanism and efficient memory management.\n\n    NOTE: This class is intended to be used for offline inference. For online\n    serving, use the `AsyncLLMEngine` class instead.\n    NOTE: For the comprehensive list of arguments, see `EngineArgs`.\n\n    Args:\n        model: A HuggingFace Transformers model instance.\n        tokenizer: A HuggingFace Transformers tokenizer instance.\n        tokenizer_mode: The tokenizer mode. \"auto\" will use the fast tokenizer\n            if available, and \"slow\" will always use the slow tokenizer.\n        trust_remote_code: Trust remote code (e.g., from HuggingFace) when\n            downloading the model and tokenizer.\n        tensor_parallel_size: The number of GPUs to use for distributed\n            execution with tensor parallelism.\n        dtype: The data type for the model weights and activations. Currently,\n            we support `float32`, `float16`, and `bfloat16`. If `auto`, we use\n            the `torch_dtype` attribute specified in the model config file.\n            However, if the `torch_dtype` in the config is `float32`, we will\n            use `float16` instead.\n        quantization: The method used to quantize the model weights. Currently,\n            we support \"awq\". If None, we assume the model weights are not\n            quantized and use `dtype` to determine the data type of the weights.\n        revision: The specific model version to use. It can be a branch name,\n            a tag name, or a commit id.\n        tokenizer_revision: The specific tokenizer version to use. It can be a\n            branch name, a tag name, or a commit id.\n        seed: The seed to initialize the random number generator for sampling.\n        gpu_memory_utilization: The ratio (between 0 and 1) of GPU memory to\n            reserve for the model weights, activations, and KV cache. Higher\n            values will increase the KV cache size and thus improve the model's\n            throughput. However, if the value is too high, it may cause out-of-\n            memory (OOM) errors.\n        swap_space: The size (GiB) of CPU memory per GPU to use as swap space.\n            This can be used for temporarily storing the states of the requests\n            when their `best_of` sampling parameters are larger than 1. If all\n            requests will have `best_of=1`, you can safely set this to 0.\n            Otherwise, too small values may cause out-of-memory (OOM) errors.\n        enforce_eager: Whether to enforce eager execution. If True, we will\n            disable CUDA graph and always execute the model in eager mode.\n            If False, we will use CUDA graph and eager execution in hybrid.\n        max_context_len_to_capture: Maximum context len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode.\n        disable_custom_all_reduce: See ParallelConfig\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast, HybridEngineBaseTokenizer],\n        model_hf_config: PretrainedConfig,\n        tokenizer_mode: str = \"auto\",\n        trust_remote_code: bool = False,\n        skip_tokenizer_init: bool = False,\n        tensor_parallel_size: int = 1,\n        dtype: str = \"auto\",\n        quantization: Optional[str] = None,\n        revision: Optional[str] = None,\n        tokenizer_revision: Optional[str] = None,\n        seed: int = 0,\n        gpu_memory_utilization: float = 0.9,\n        swap_space: int = 4,\n        cpu_offload_gb: float = 0,\n        enforce_eager: bool = False,\n        max_context_len_to_capture: Optional[int] = None,\n        max_seq_len_to_capture: int = 8192,\n        disable_custom_all_reduce: bool = False,\n        load_format = 'auto',\n        **kwargs,\n    ) -> None:\n        if \"disable_log_stats\" not in kwargs:\n            kwargs[\"disable_log_stats\"] = True\n        engine_args = EngineArgs(\n            model_hf_config=model_hf_config,\n            tensor_parallel_size=tensor_parallel_size,\n            dtype=dtype,\n            quantization=quantization,\n            revision=revision,\n            tokenizer_revision=tokenizer_revision,\n            seed=seed,\n            gpu_memory_utilization=gpu_memory_utilization,\n            swap_space=swap_space,\n            cpu_offload_gb=cpu_offload_gb,\n            enforce_eager=enforce_eager,\n            max_context_len_to_capture=max_context_len_to_capture,\n            max_seq_len_to_capture=max_seq_len_to_capture,\n            disable_custom_all_reduce=disable_custom_all_reduce,\n            load_format=load_format,\n            skip_tokenizer_init=skip_tokenizer_init,\n            **kwargs,\n        )\n        tokenizer_cls = (PreTrainedTokenizer, PreTrainedTokenizerFast, HybridEngineBaseTokenizer)\n        if not isinstance(tokenizer, tokenizer_cls):\n            raise ValueError(\n                f\"Unexpected tokenizer type: {type(tokenizer)}. Must be\"\n                \"one of the following: PreTrainedTokenizer, PreTrainedTokenizerFast, verl.workers.rollout.HybridEngineBaseTokenizer\"\n            )\n        self.llm_engine = LLMEngine.from_engine_args(model, tokenizer, engine_args)  # TODO: check usagecontext\n        self.request_counter = Counter()\n\n    def init_cache_engine(self):\n        self.llm_engine.init_cache_engine()\n\n    def free_cache_engine(self):\n        self.llm_engine.free_cache_engine()\n\n    def get_tokenizer(self) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:\n        return self.llm_engine.tokenizer\n\n    def set_tokenizer(\n        self,\n        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],\n    ) -> None:\n        self.llm_engine.tokenizer = tokenizer\n\n    def _run_engine(self, *, use_tqdm: bool) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:\n        # Initialize tqdm.\n        if use_tqdm:\n            num_requests = self.llm_engine.get_num_unfinished_requests()\n            pbar = tqdm(\n                total=num_requests,\n                desc=\"Processed prompts\",\n                dynamic_ncols=True,\n                postfix=(f\"est. speed input: {0:.2f} toks/s, \"\n                         f\"output: {0:.2f} toks/s\"),\n            )\n        # Run the engine.\n        outputs: List[Union[RequestOutput, EmbeddingRequestOutput]] = []\n        total_in_toks = 0\n        total_out_toks = 0\n        while self.llm_engine.has_unfinished_requests():\n            step_outputs = self.llm_engine.step()\n            for output in step_outputs:\n                if output.finished:\n                    outputs.append(output)\n                    if use_tqdm:\n                        if isinstance(output, RequestOutput):\n                            # Calculate tokens only for RequestOutput\n                            total_in_toks += len(output.prompt_token_ids)\n                            in_spd = total_in_toks / pbar.format_dict[\"elapsed\"]\n                            total_out_toks += sum(len(stp.token_ids) for stp in output.outputs)\n                            out_spd = total_out_toks / pbar.format_dict[\"elapsed\"]\n                            pbar.postfix = (f\"est. speed input: {in_spd:.2f} toks/s, \"\n                                            f\"output: {out_spd:.2f} toks/s\")\n                        pbar.update(1)\n        if use_tqdm:\n            pbar.close()\n        # Sort the outputs by request ID.\n        # This is necessary because some requests may be finished earlier than\n        # its previous requests.\n        outputs = sorted(outputs, key=lambda x: int(x.request_id))\n        return self._post_process_outputs(outputs)\n\n    # # NOTE(shengguangming): add for verl\n    # # TODO(sgm): we can optimize it by making the dataloader yield List[int] without padding.\n    # def _pre_process_inputs(self, prompt_token_ids: torch.Tensor) -> List[int]:\n    #     # remove the left padding in the prompt token_id\n    #     pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n    #     non_pad_index = torch.nonzero(prompt_token_ids != pad_token_id, as_tuple=False)[0][0]\n    #     token_ids = prompt_token_ids[non_pad_index:].tolist()\n    #     return token_ids\n\n    # NOTE(shengguangming): add for verl\n    def _post_process_outputs(self, request_outputs: List[RequestOutput]) -> Tuple[torch.Tensor, torch.Tensor]:\n        output_token_ids = []\n        logprobs = []\n        for request_output in request_outputs:  # List[RequestOutput]\n            outputs = request_output.outputs\n            for output in outputs:  # List[CompletionOutput], usually len == 1\n                output_token_ids.append(torch.tensor(output.token_ids))\n                # TODO(shengguangming): can be optimzied by rewrite the Sampler._get_logprobs() logits\n                logprobs_dicts = output.logprobs\n                if logprobs_dicts is not None:\n                    logprob = []\n                    for logprobs_dict, id in zip(logprobs_dicts, output.token_ids):\n                        logprob.append(logprobs_dict[id].logprob)\n                    logprobs.append(torch.tensor(logprob))\n\n        pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n        output_token_ids = pad_sequence(output_token_ids, batch_first=True, padding_value=pad_token_id)\n        if len(logprobs) > 0:\n            logprobs = pad_sequence(logprobs, batch_first=True, padding_value=pad_token_id)\n        return output_token_ids, logprobs\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.llm_engine.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n    def offload_model_weights(self) -> None:\n        self.llm_engine.offload_model_weights()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/llm_engine_sp.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/llm_engine.py\n\nimport torch\nfrom typing import Dict, Optional, Union, Type\n\nimport vllm.envs as envs\nfrom vllm.config import (CacheConfig, DecodingConfig, DeviceConfig, EngineConfig, LoRAConfig, MultiModalConfig,\n                         ObservabilityConfig, ParallelConfig, PromptAdapterConfig, SchedulerConfig, SpeculativeConfig)\nfrom vllm.core.scheduler import Scheduler\nfrom vllm.engine.output_processor.interfaces import (SequenceGroupOutputProcessor)\nfrom vllm.engine.output_processor.stop_checker import StopChecker\nfrom vllm.executor.executor_base import ExecutorBase\nfrom vllm.inputs import INPUT_REGISTRY, LLMInputs, PromptInputs\nfrom vllm.logger import init_logger\nfrom vllm.transformers_utils.detokenizer import Detokenizer\nfrom vllm.engine.metrics import (LoggingStatLogger, PrometheusStatLogger, StatLoggerBase, Stats)\nfrom vllm.tracing import (SpanAttributes, SpanKind, extract_trace_context, init_tracer)\nfrom vllm.usage.usage_lib import (UsageContext, is_usage_stats_enabled, usage_message)\nfrom vllm.utils import Counter\nfrom vllm.engine.llm_engine import _load_generation_config_dict\nfrom vllm.engine.llm_engine import LLMEngine\nfrom vllm.version import __version__ as VLLM_VERSION\n\nimport torch.nn as nn\nfrom .arg_utils import EngineArgs\nfrom .tokenizer import TokenizerGroup\nfrom .config import ModelConfig, LoadConfig\n\nlogger = init_logger(__name__)\n_LOCAL_LOGGING_INTERVAL_SEC = 5\n\n\nclass LLMEngine(LLMEngine):\n    \"\"\"An LLM engine that receives requests and generates texts.\n\n    This is the main class for the vLLM engine. It receives requests\n    from clients and generates texts from the LLM. It includes a tokenizer, a\n    language model (possibly distributed across multiple GPUs), and GPU memory\n    space allocated for intermediate states (aka KV cache). This class utilizes\n    iteration-level scheduling and efficient memory management to maximize the\n    serving throughput.\n\n    The `LLM` class wraps this class for offline batched inference and the\n    `AsyncLLMEngine` class wraps this class for online serving.\n\n    NOTE: The config arguments are derived from the `EngineArgs` class. For the\n    comprehensive list of arguments, see `EngineArgs`.\n\n    Args:\n        model: the actor model initialize outside vllm (add for verl)\n        tokenizer: the initialized tokenizer (add for verl)\n        model_config: The configuration related to the LLM model.\n        cache_config: The configuration related to the KV cache memory\n            management.\n        parallel_config: The configuration related to distributed execution.\n        scheduler_config: The configuration related to the request scheduler.\n        distributed_init_method: The initialization method for distributed\n            execution. See `torch.distributed.init_process_group` for details.\n        placement_group: Ray placement group for distributed execution.\n            Required for distributed execution.\n        log_stats: Whether to log statistics.\n    \"\"\"\n\n    def __init__(\n        self,\n        # NOTE(sgm): first two arguments are added for verl\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        tokenizer: nn.Module,\n        # NOTE(sgm): vllm original arguments\n        model_config: ModelConfig,\n        cache_config: CacheConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        multimodal_config: Optional[MultiModalConfig],\n        speculative_config: Optional[SpeculativeConfig],\n        decoding_config: Optional[DecodingConfig],\n        observability_config: Optional[ObservabilityConfig],\n        prompt_adapter_config: Optional[PromptAdapterConfig],\n        executor_class: Type[ExecutorBase],\n        log_stats: bool,\n        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,\n        stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,\n    ) -> None:\n        logger.info(\n            \"Initializing an LLM engine (v%s) with config: \"\n            \"model=%r, speculative_config=%r, tokenizer=%r, \"\n            \"skip_tokenizer_init=%s, revision=%s, \"\n            \"rope_scaling=%r, rope_theta=%r, tokenizer_revision=%s, \"\n            \"trust_remote_code=%s, dtype=%s, max_seq_len=%d, \"\n            \"download_dir=%r, load_format=%s, tensor_parallel_size=%d, \"\n            \"pipeline_parallel_size=%d, \"\n            \"disable_custom_all_reduce=%s, quantization=%s, \"\n            \"enforce_eager=%s, kv_cache_dtype=%s, \"\n            \"quantization_param_path=%s, device_config=%s, \"\n            \"decoding_config=%r, observability_config=%r, \"\n            \"seed=%d, served_model_name=%s, use_v2_block_manager=%s, \"\n            \"enable_prefix_caching=%s)\",\n            VLLM_VERSION,\n            model_config.model,\n            speculative_config,\n            model_config.tokenizer,\n            model_config.skip_tokenizer_init,\n            model_config.revision,\n            model_config.rope_scaling,\n            model_config.rope_theta,\n            model_config.tokenizer_revision,\n            model_config.trust_remote_code,\n            model_config.dtype,\n            model_config.max_model_len,\n            load_config.download_dir,\n            load_config.load_format,\n            parallel_config.tensor_parallel_size,\n            parallel_config.pipeline_parallel_size,\n            parallel_config.disable_custom_all_reduce,\n            model_config.quantization,\n            model_config.enforce_eager,\n            cache_config.cache_dtype,\n            model_config.quantization_param_path,\n            device_config.device,\n            decoding_config,\n            observability_config,\n            model_config.seed,\n            model_config.served_model_name,\n            scheduler_config.use_v2_block_manager,\n            cache_config.enable_prefix_caching,\n        )\n        # TODO(woosuk): Print more configs in debug mode.\n\n        self.model_config = model_config\n        self.cache_config = cache_config\n        self.lora_config = lora_config\n        self.multimodal_config = multimodal_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.speculative_config = speculative_config\n        self.load_config = load_config\n        self.decoding_config = decoding_config or DecodingConfig()\n        self.prompt_adapter_config = prompt_adapter_config\n        self.observability_config = observability_config or ObservabilityConfig()\n        self.log_stats = log_stats\n\n        # self.model = model # should not store the model, it should be deleted\n        # TODO(shengguangming): maybe we can choose init here or from arguments\n        if not self.model_config.skip_tokenizer_init:\n            self.tokenizer = self._init_tokenizer(tokenizer)\n            self.detokenizer = Detokenizer(self.tokenizer)\n        else:\n            self.tokenizer = None\n            self.detokenizer = None\n\n        self.seq_counter = Counter()\n        self.generation_config_fields = _load_generation_config_dict(model_config)\n\n        self.input_processor = INPUT_REGISTRY.create_input_processor(self.model_config)\n\n        self.model_executor = executor_class(\n            model=model, # add for spmd_gpu_executor\n            model_config=model_config,\n            cache_config=cache_config,\n            parallel_config=parallel_config,\n            scheduler_config=scheduler_config,\n            device_config=device_config,\n            lora_config=lora_config,\n            multimodal_config=multimodal_config,\n            speculative_config=speculative_config,\n            load_config=load_config,\n            prompt_adapter_config=prompt_adapter_config,\n        )\n\n        # Profile the memory usage and initialize the cache.\n        if not self.model_config.embedding_mode:\n            self._initialize_kv_caches()\n\n        # If usage stat is enabled, collect relevant info.\n        if is_usage_stats_enabled():\n            from vllm.model_executor.model_loader import (get_architecture_class_name)\n            usage_message.report_usage(\n                get_architecture_class_name(model_config),\n                usage_context,\n                extra_kvs={\n                    # Common configuration\n                    \"dtype\": str(model_config.dtype),\n                    \"tensor_parallel_size\": parallel_config.tensor_parallel_size,\n                    \"block_size\": cache_config.block_size,\n                    \"gpu_memory_utilization\": cache_config.gpu_memory_utilization,\n\n                    # Quantization\n                    \"quantization\": model_config.quantization,\n                    \"kv_cache_dtype\": str(cache_config.cache_dtype),\n\n                    # Feature flags\n                    \"enable_lora\": bool(lora_config),\n                    \"enable_prompt_adapter\": bool(prompt_adapter_config),\n                    \"enable_prefix_caching\": cache_config.enable_prefix_caching,\n                    \"enforce_eager\": model_config.enforce_eager,\n                    \"disable_custom_all_reduce\": parallel_config.disable_custom_all_reduce,\n                })\n\n        if self.tokenizer:\n            # Ping the tokenizer to ensure liveness if it runs in a\n            # different process.\n            self.tokenizer.ping()\n\n        # Create the scheduler.\n        # NOTE: the cache_config here have been updated with the numbers of\n        # GPU and CPU blocks, which are profiled in the distributed executor.\n        self.scheduler = [\n            Scheduler(scheduler_config, cache_config, lora_config, parallel_config.pipeline_parallel_size)\n            for _ in range(parallel_config.pipeline_parallel_size)\n        ]\n\n        # Metric Logging.\n        if self.log_stats:\n            if stat_loggers is not None:\n                self.stat_loggers = stat_loggers\n            else:\n                self.stat_loggers = {\n                    \"logging\":\n                        LoggingStatLogger(local_interval=_LOCAL_LOGGING_INTERVAL_SEC),\n                    \"prometheus\":\n                        PrometheusStatLogger(local_interval=_LOCAL_LOGGING_INTERVAL_SEC,\n                                             labels=dict(model_name=model_config.served_model_name),\n                                             max_model_len=self.model_config.max_model_len),\n                }\n                self.stat_loggers[\"prometheus\"].info(\"cache_config\", self.cache_config)\n\n        self.tracer = None\n        if self.observability_config.otlp_traces_endpoint:\n            self.tracer = init_tracer(\"vllm.llm_engine\", self.observability_config.otlp_traces_endpoint)\n\n        # Create sequence output processor, e.g. for beam search or\n        # speculative decoding.\n        self.output_processor = (SequenceGroupOutputProcessor.create_output_processor(\n            self.scheduler_config,\n            self.detokenizer,\n            self.scheduler,\n            self.seq_counter,\n            self.get_tokenizer_for_seq,\n            stop_checker=StopChecker(\n                self.scheduler_config.max_model_len,\n                self.get_tokenizer_for_seq,\n            ),\n        ))\n\n    # TODO(sgm): add for verl but we may not tokenizer in Rollout\n    def _init_tokenizer(self, tokenizer, **tokenizer_init_kwargs):\n        init_kwargs = dict(enable_lora=bool(self.lora_config),\n                           max_num_seqs=self.scheduler_config.max_num_seqs,\n                           max_input_length=None)\n        init_kwargs.update(tokenizer_init_kwargs)\n        return TokenizerGroup(tokenizer, **init_kwargs)\n\n    def init_cache_engine(self):\n        # TODO: check whether we should rebuild the CUDAGraph every iter when offload/load KVCache\n        # Re-capture CUDAGraph would be time-consuming\n        self.model_executor.init_cache_engine()\n\n    def free_cache_engine(self):\n        self.model_executor.free_cache_engine()\n\n    # NOTE(sgm): currently, we only support GPU executor\n    # The GPUExecutor remove the Ray dependency\n    @classmethod\n    def _get_executor_cls(cls, engine_config: EngineConfig) -> Type[ExecutorBase]:\n        assert engine_config.device_config.device_type == \"cuda\", \\\n            \"Currently, the vllm in verl only support running on GPU\"\n\n        if engine_config.parallel_config.world_size == 1:\n            engine_config.load_config.load_format = \"dummy_hf\"\n\n        from .spmd_gpu_executor import SPMDGPUExecutor\n        executor_class = SPMDGPUExecutor\n        return executor_class\n\n    @classmethod\n    def from_engine_args(\n        cls,\n        model,\n        tokenizer,\n        engine_args: EngineArgs,\n        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,\n        stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,\n    ) -> \"LLMEngine\":\n        \"\"\"Creates an LLM engine from the engine arguments.\"\"\"\n        # Create the engine configs.\n        engine_config = engine_args.create_engine_config()\n        executor_class = cls._get_executor_cls(engine_config)\n        # Initialize the cluster and specify the executor class.\n        assert engine_config.device_config.device_type == \"cuda\", \\\n            \"Currently, the vllm in verl only support running on GPU\"\n\n        from .spmd_gpu_executor import SPMDGPUExecutor\n        executor_class = SPMDGPUExecutor\n\n        # Create the LLM engine.\n        engine = cls(\n            model,\n            tokenizer,\n            **engine_config.to_dict(),\n            executor_class=executor_class,\n            log_stats=not engine_args.disable_log_stats,\n            usage_context=usage_context,\n            stat_loggers=stat_loggers,\n        )\n        return engine\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.model_executor.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n    def offload_model_weights(self) -> None:\n        self.model_executor.offload_model_weights()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/megatron_weight_loaders.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models\n\nfrom typing import Dict\nimport torch\nimport torch.nn as nn\n\nfrom vllm.model_executor.layers.linear import *\nfrom vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding, ParallelLMHead\nfrom vllm.model_executor.layers.activation import ScaledActivation\nfrom vllm.model_executor.models import ModelRegistry\n\n\n# NOTE(shengguangming): replace the origin weight loader function in the class\ndef parallel_weight_loader(self, param: torch.Tensor, loaded_weight: torch.Tensor) -> None:\n    \"\"\"Parallel Linear weight loader.\"\"\"\n    assert param.size() == loaded_weight.size(\n    ), 'the parameter size is not align with the loaded weight size, param size: {}, loaded_weight size: {}'.format(\n        param.size(), loaded_weight.size())\n    assert param.data.dtype == loaded_weight.data.dtype, \"if we want to shared weights, the data type should also be the same\"\n\n    param.data = loaded_weight.data\n\n\ndef default_weight_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:\n    \"\"\"Default weight loader.\"\"\"\n    assert param.size() == loaded_weight.size()\n    assert param.data.dtype == loaded_weight.data.dtype, \"if we want to shared weights, the data type should also be the same\"\n\n    param.data = loaded_weight.data\n\n\ndef gpt2_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"lm_head.weight\" in name:\n            # GPT-2 ties the weights of the embedding layer and the final\n            # linear layer.\n            continue\n        if \".attn.bias\" in name or \".attn.masked_bias\" in name:\n            # Skip attention mask.\n            # NOTE: \"c_attn.bias\" should not be skipped.\n            continue\n        if not name.startswith(\"transformer.\"):\n            name = \"transformer.\" + name\n        param = params_dict[name]\n        # The HF's GPT-2 implementation uses Conv1D instead of Linear.\n        # Because of this, we need to transpose the weights.\n        # Note(zhuohan): the logic below might break quantized models.\n        for conv1d_weight_name in [\"c_attn\", \"c_proj\", \"c_fc\"]:\n            if conv1d_weight_name not in name:\n                continue\n            if not name.endswith(\".weight\"):\n                continue\n            # TODO: check megatron\n            loaded_weight = loaded_weight.t()\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_te_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv.layer_norm_weight\", \"input_layernorm.weight\"),\n        (\"self_attention.linear_qkv.layer_norm_bias\", \"input_layernorm.bias\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", 'self_attn.o_proj'),\n        ('pre_mlp_layernorm', 'post_attention_layernorm'),\n        ('mlp.linear_fc1.layer_norm_weight', 'post_attention_layernorm.weight'),\n        ('mlp.linear_fc1.layer_norm_bias', 'post_attention_layernorm.bias'),\n        ('mlp.linear_fc1', 'mlp.gate_up_proj'),\n        ('mlp.linear_fc2', 'mlp.down_proj'),\n        ('decoder.final_layernorm', 'model.norm'),\n        ('output_layer', 'lm_head'),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith('.bias') and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", 'self_attn.o_proj'),\n        (\n            'input_layernorm',\n            'input_layernorm',\n        ),\n        ('pre_mlp_layernorm', 'post_attention_layernorm'),\n        ('mlp.linear_fc1', 'mlp.gate_up_proj'),\n        ('mlp.linear_fc2', 'mlp.down_proj'),\n        ('decoder.final_layernorm', 'model.norm'),\n        ('output_layer', 'lm_head'),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith('.bias') and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef _replace_name(megatron_name, name_mapping):\n    for m_name, v_name in name_mapping:\n        if m_name not in megatron_name:\n            continue\n        if 'layers' in megatron_name:  # deal with decoder layers\n            megatron_name = megatron_name.replace('decoder', 'model')\n            megatron_name_list = megatron_name.split('.')\n            if 'layer_norm_weight' in megatron_name_list or 'layer_norm_bias' in megatron_name_list:\n                param_name_list = megatron_name_list[:3]\n                param_name_list.append(v_name)\n                param_name = '.'.join(param_name_list)\n            else:\n                param_name_list = megatron_name_list[:3]\n                weight_or_bias = megatron_name_list[-1]\n                param_name_list.append(v_name)\n                param_name_list.append(weight_or_bias)\n                param_name = '.'.join(param_name_list)\n            return param_name\n        else:\n            param_name = megatron_name.replace(m_name, v_name)\n            return param_name\n\n\ndef llama_megatron_core_te_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv.layer_norm_weight\", \"input_layernorm.weight\"),\n        (\"self_attention.linear_qkv.layer_norm_bias\", \"input_layernorm.bias\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", 'self_attn.o_proj'),\n        ('pre_mlp_layernorm', 'post_attention_layernorm'),\n        ('mlp.linear_fc1.layer_norm_weight', 'post_attention_layernorm.weight'),\n        ('mlp.linear_fc1.layer_norm_bias', 'post_attention_layernorm.bias'),\n        ('mlp.linear_fc1', 'mlp.gate_up_proj'),\n        ('mlp.linear_fc2', 'mlp.down_proj'),\n        ('decoder.final_layernorm', 'model.norm'),\n        ('output_layer', 'lm_head'),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith('.bias') and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", 'self_attn.o_proj'),\n        (\n            'input_layernorm',\n            'input_layernorm',\n        ),\n        ('pre_mlp_layernorm', 'post_attention_layernorm'),\n        ('mlp.linear_fc1', 'mlp.gate_up_proj'),\n        ('mlp.linear_fc2', 'mlp.down_proj'),\n        ('decoder.final_layernorm', 'model.norm'),\n        ('output_layer', 'lm_head'),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith('.bias') and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef _replace_name(megatron_name, name_mapping):\n    for m_name, v_name in name_mapping:\n        if m_name not in megatron_name:\n            continue\n        if 'layers' in megatron_name:  # deal with decoder layers\n            megatron_name = megatron_name.replace('decoder', 'model')\n            megatron_name_list = megatron_name.split('.')\n            if 'layer_norm_weight' in megatron_name_list or 'layer_norm_bias' in megatron_name_list:\n                param_name_list = megatron_name_list[:3]\n                param_name_list.append(v_name)\n                param_name = '.'.join(param_name_list)\n            else:\n                param_name_list = megatron_name_list[:3]\n                weight_or_bias = megatron_name_list[-1]\n                param_name_list.append(v_name)\n                param_name_list.append(weight_or_bias)\n                param_name = '.'.join(param_name_list)\n            return param_name\n        else:\n            param_name = megatron_name.replace(m_name, v_name)\n            return param_name\n\n\ndef mistral_megatron_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    # TODO: need to implement a general way to deal with prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\n__LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__ = {\n    ColumnParallelLinear: parallel_weight_loader,\n    MergedColumnParallelLinear: parallel_weight_loader,\n    QKVParallelLinear: parallel_weight_loader,\n    RowParallelLinear: parallel_weight_loader,\n    VocabParallelEmbedding: parallel_weight_loader,\n    ParallelLMHead: parallel_weight_loader\n    # \"ScaledActivation.weight_loader\": ScaledActivation, # TODO(shengguangming): latest commit in vllm fix awq for this function and add load_weights\n    # \"default_weight_loader\": default_weight_loader\n}\n\n# for layer_class, weight_loader in __LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__.items():\n#     # setattr(layer_class, 'megatron_weight_loader', weight_loader)\n#     layer_class.weight_loader = weight_loader\n\n__MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__ = {\n    'GPT2LMHeadModel': gpt2_weight_loader,\n    'LlamaForCausalLM': llama_megatron_weight_loader,  # use te backend for open-source megatron\n    'LLaMAForCausalLM': llama_megatron_weight_loader,\n    'MistralForCausalLM': mistral_megatron_weight_loader,\n}\n\n\n# the actor model is .state_dict()\n# Load megatron weights\ndef load_megatron_weights(actor_weights: Dict, vllm_model: nn.Module):\n    weight_loader = _get_model_weight_loader(vllm_model.__class__.__name__)\n    weight_loader(actor_weights, vllm_model)\n    # NOTE(sgm) to reduce peak memory usage, we offload vllm model to cpu\n    # after init, and we need this after sync model weights for in first iter.\n    vllm_model = vllm_model.cuda()\n\n\ndef _get_model_weight_loader(arch: str):\n    if arch in __MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__:\n        return __MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {ModelRegistry.get_supported_archs()}\")\n\n\ndef update_megatron_weight_loader():\n    for layer_class, weight_loader in __LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__.items():\n        layer_class.weight_loader = weight_loader\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/model_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader\n\nfrom typing import Dict, Union, Optional, Iterable, Tuple\n\nimport torch\nimport torch.nn as nn\nfrom transformers import PreTrainedModel\n\nfrom vllm.config import (CacheConfig, DeviceConfig, LoadConfig, LoRAConfig, ModelConfig, MultiModalConfig,\n                         ParallelConfig, SchedulerConfig)\nfrom vllm.model_executor.model_loader import BaseModelLoader\nfrom vllm.model_executor.model_loader.loader import _initialize_model\nfrom vllm.model_executor.model_loader.utils import set_default_torch_dtype\nfrom vllm.distributed.communication_op import tensor_model_parallel_all_gather\n\nfrom .config import ModelConfig, LoadFormat, LoadConfig\nfrom .megatron_weight_loaders import load_megatron_weights, update_megatron_weight_loader\nfrom .dtensor_weight_loaders import load_dtensor_weights, update_dtensor_weight_loader\nfrom .hf_weight_loader import update_hf_weight_loader\n\n\ndef get_model(actor_model: Union[PreTrainedModel, Dict],\n              model_config: ModelConfig,\n              load_config: LoadConfig,\n              device_config: DeviceConfig,\n              parallel_config: ParallelConfig,\n              scheduler_config: SchedulerConfig,\n              lora_config: Optional[LoRAConfig],\n              multimodal_config: Optional[MultiModalConfig],\n              cache_config: CacheConfig = None) -> nn.Module:\n    loader = get_model_loader(load_config)\n    if load_config.load_format.startswith('dummy'):\n        return loader.load_model(model_config=model_config,\n                                 device_config=device_config,\n                                 lora_config=lora_config,\n                                 multimodal_config=multimodal_config,\n                                 parallel_config=parallel_config,\n                                 scheduler_config=scheduler_config,\n                                 cache_config=cache_config)\n    else:\n        return loader.load_model(actor_model=actor_model,\n                                 model_config=model_config,\n                                 device_config=device_config,\n                                 lora_config=lora_config,\n                                 multimodal_config=multimodal_config,\n                                 parallel_config=parallel_config,\n                                 scheduler_config=scheduler_config,\n                                 cache_config=cache_config)\n\n\ndef get_model_loader(load_config: LoadConfig) -> BaseModelLoader:\n    \"\"\"Get a model loader based on the load format.\"\"\"\n\n    if isinstance(load_config.load_format, type):\n        return load_config.load_format(load_config)\n\n    if load_config.load_format == LoadFormat.AUTO:\n        update_megatron_weight_loader()\n        return MegatronLoader(load_config)\n\n    # NOTE(sgm): change the weight_loader function in runtime\n    if load_config.load_format == LoadFormat.MEGATRON:\n        update_megatron_weight_loader()\n        return MegatronLoader(load_config)\n\n    if load_config.load_format == LoadFormat.HF:\n        update_hf_weight_loader()\n        return HFLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DTENSOR:\n        update_dtensor_weight_loader()\n        return DTensorLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_HF:\n        update_hf_weight_loader()\n        return DummyModelLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_MEGATRON:\n        update_megatron_weight_loader()\n        return DummyModelLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_DTENSOR:\n        update_dtensor_weight_loader()\n        return DummyModelLoader(load_config)\n\n    raise ValueError('load format not supported in verl: {}, only support {} and {}'.format(\n        load_config.load_format, LoadFormat.MEGATRON, LoadFormat.HF))\n\n\nclass DummyModelLoader(BaseModelLoader):\n    \"\"\"Model loader that will set model weights to random values.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def load_model(self, *, model_config: ModelConfig, device_config: DeviceConfig, lora_config: Optional[LoRAConfig],\n                   multimodal_config: Optional[MultiModalConfig], parallel_config: ParallelConfig,\n                   scheduler_config: SchedulerConfig, cache_config: CacheConfig) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, multimodal_config, cache_config,\n                                          scheduler_config)\n            # NOTE(woosuk): For accurate performance evaluation, we assign\n            # random values to the weights.\n            # initialize_dummy_weights(model)\n        return model.eval()\n\n\nclass MegatronLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from partitioned megatron model.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def _get_weights_iterator(actor_model: Union[PreTrainedModel, Dict]):\n        # NOTE(shengguangming) Load the weights from the actor model\n        pass\n        # if isinstance(actor_model, nn.Module):\n        #     load_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)), vllm_model=model)\n        # else:\n        #     load_weights(actor_weights=actor_model, vllm_model=model)\n        # return actor_model\n\n    def load_model(self, actor_model: Union[PreTrainedModel, Dict], model_config: ModelConfig,\n                   device_config: DeviceConfig, lora_config: Optional[LoRAConfig],\n                   multimodal_config: Optional[MultiModalConfig], parallel_config: ParallelConfig,\n                   scheduler_config: SchedulerConfig, cache_config: CacheConfig) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, multimodal_config, cache_config,\n                                          scheduler_config)\n\n            # TODO(sgm): This is a hack, we need to register the load_weight() func for each model in vllm\n            if isinstance(actor_model, nn.Module):\n                load_megatron_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)),\n                                      vllm_model=model)\n            else:\n                load_megatron_weights(actor_weights=actor_model, vllm_model=model)\n\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\nclass HFLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from model's full params.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def _get_weights_iterator(self, actor_model: Union[PreTrainedModel, Dict]):\n        if isinstance(actor_model, Dict):\n            return actor_model.items()\n        elif isinstance(actor_model, nn.Module):\n            return dict(actor_model.named_parameters()).items()\n        else:\n            raise ValueError(f'actor model should be Dict or nn.Module, but get {type(actor_model)}')\n\n    def load_model(self, actor_model: Union[PreTrainedModel, Dict], model_config: ModelConfig,\n                   device_config: DeviceConfig, lora_config: Optional[LoRAConfig],\n                   multimodal_config: Optional[MultiModalConfig], parallel_config: ParallelConfig,\n                   scheduler_config: SchedulerConfig, cache_config: CacheConfig) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            # with torch.device(device_config.device):\n            # NOTE(sgm): init the model in cpu\n            model = _initialize_model(model_config, self.load_config, lora_config, multimodal_config, cache_config,\n                                      scheduler_config)\n            model.load_weights(self._get_weights_iterator(actor_model))\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\nclass DTensorLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from partitioned megatron model.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def _get_weights_iterator(actor_model: Union[PreTrainedModel, Dict]):\n        # NOTE(shengguangming) Load the weights from the actor model\n        pass\n        # if isinstance(actor_model, nn.Module):\n        #     load_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)), vllm_model=model)\n        # else:\n        #     load_weights(actor_weights=actor_model, vllm_model=model)\n        # return actor_model\n\n    def load_model(self, actor_model: Union[PreTrainedModel, Dict], model_config: ModelConfig,\n                   device_config: DeviceConfig, lora_config: Optional[LoRAConfig],\n                   multimodal_config: Optional[MultiModalConfig], parallel_config: ParallelConfig,\n                   scheduler_config: SchedulerConfig, cache_config: CacheConfig) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, multimodal_config, cache_config,\n                                          scheduler_config)\n\n            # TODO(sgm): This is a hack, we need to register the load_weight() func for each model in vllm\n            if isinstance(actor_model, nn.Module):\n                load_dtensor_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)),\n                                     vllm_model=model)\n            else:\n                load_dtensor_weights(actor_weights=actor_model, vllm_model=model)\n\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\n# FIXME(sgm): hack the _get_logits function in vllm v0.4.2\n# as they use ray, the _get_logits result will only need to return to the driver node,\n# therefore gather is enough. However, we use SPMD instead of a central scheduler,\n# all_gather is required (aligned with v0.2.6)\ndef _get_logits(self, hidden_states: torch.Tensor, embedding: torch.Tensor,\n                embedding_bias: Optional[torch.Tensor]) -> torch.Tensor:\n    # Get the logits for the next tokens.\n    logits = torch.matmul(hidden_states, embedding.t())\n    if embedding_bias is not None:\n        logits += embedding_bias\n    logits = tensor_model_parallel_all_gather(logits)\n    # Remove paddings in vocab (if any).\n    if logits is not None:\n        logits = logits[:, :self.org_vocab_size]\n    return logits\n\n\nfrom vllm.model_executor.layers.logits_processor import LogitsProcessor\n\n\ndef logitsprocessor_init(self,\n                         vocab_size: int,\n                         org_vocab_size: Optional[int] = None,\n                         scale: float = 1.0,\n                         logits_as_input: bool = False,\n                         soft_cap: Optional[float] = None) -> None:\n    \"\"\"\n    Args:\n        scale: A scaling factor to apply to the logits.\n    \"\"\"\n    super(LogitsProcessor, self).__init__()\n    self.scale = scale\n    self.vocab_size = vocab_size\n    # Whether the input is logits (default is hidden states).\n    self.logits_as_input = logits_as_input\n    # original vocabulary size (without LoRA).\n    self.org_vocab_size = org_vocab_size or vocab_size\n    # Soft cap the logits. Used in Gemma 2.\n    self.soft_cap = soft_cap\n    # Whether to use gather or all-gather to gather the logits.\n    self.use_gather = False\n\n\nLogitsProcessor.__init__ = logitsprocessor_init  # use all_gather\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/model_runner.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/model_runner.py\n\nimport torch\nimport torch.nn as nn\nfrom enum import IntEnum\nfrom typing import Dict, List, Optional, Set, Tuple, Union\nimport warnings\n\nimport vllm.envs as envs\nfrom vllm.attention import (AttentionMetadata, get_attn_backend)\nfrom vllm.config import (CacheConfig, DeviceConfig, LoRAConfig, MultiModalConfig, ParallelConfig, PromptAdapterConfig,\n                         SchedulerConfig)\nfrom vllm.logger import init_logger\nfrom vllm.lora.layers import LoRAMapping\nfrom vllm.lora.request import LoRARequest\nfrom vllm.lora.worker_manager import LRUCacheWorkerLoRAManager\nfrom vllm.model_executor import SamplingMetadata\nfrom vllm.model_executor.models.interfaces import (supports_lora, supports_vision)\nfrom vllm.utils import (CudaMemoryProfiler, is_hip, is_pin_memory_available)\nfrom vllm.worker.model_runner import ModelRunner, CUDAGraphRunner\nfrom vllm.prompt_adapter.worker_manager import (LRUCacheWorkerPromptAdapterManager)\n\nfrom .model_loader import get_model\nfrom .config import ModelConfig, LoadConfig\n\nlogger = init_logger(__name__)\n\n\n# How batches are constructed.\nclass BatchType(IntEnum):\n    # Every batch is prefill.\n    PREFILL = 0\n    # Every batch is decode.\n    DECODE = 1\n    # Batch is a mixture of prefill and decode.\n    MIXED = 2\n\n\nclass ModelRunner(ModelRunner):\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # [verl] model itself or its parameter dict\n        model_config: ModelConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        cache_config: CacheConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        kv_cache_dtype: Optional[str] = \"auto\",\n        is_driver_worker: bool = False,\n        prompt_adapter_config: Optional[PromptAdapterConfig] = None,\n        multimodal_config: Optional[MultiModalConfig] = None,\n        return_hidden_states: bool = False,\n    ):\n\n        super().__init__(\n            model_config,\n            parallel_config,\n            scheduler_config,\n            device_config,\n            cache_config,\n            load_config,\n            lora_config,\n            kv_cache_dtype,\n            is_driver_worker=True,  # a hack\n            prompt_adapter_config=prompt_adapter_config,\n            multimodal_config=multimodal_config,\n            return_hidden_states=return_hidden_states)\n\n        # NOTE(sgm): add for verl\n        self.model = model  # this will be replaced by get_model()\n\n    # NOTE(sgm): initialize model using the actor model\n    def load_model(self) -> None:\n        logger.info(\"Starting to load model %s...\", self.model_config.model)\n        with CudaMemoryProfiler() as m:\n            self.model = get_model(actor_model=self.model,\n                                   model_config=self.model_config,\n                                   device_config=self.device_config,\n                                   lora_config=self.lora_config,\n                                   load_config=self.load_config,\n                                   parallel_config=self.parallel_config,\n                                   scheduler_config=self.scheduler_config,\n                                   multimodal_config=self.multimodal_config,\n                                   cache_config=self.cache_config)\n        self.model_memory_usage = m.consumed_memory\n        logger.info(\"Loading model weights took %.4f GB\", self.model_memory_usage / float(2**30))\n\n        if self.lora_config:\n            assert supports_lora(self.model), \"Model does not support LoRA\"\n            assert not supports_vision(self.model), \"To be tested: vision language model with LoRA settings.\"\n\n            self.lora_manager = LRUCacheWorkerLoRAManager(\n                self.scheduler_config.max_num_seqs,\n                self.scheduler_config.max_num_batched_tokens,\n                self.vocab_size,\n                self.lora_config,\n                self.device,\n                self.model.embedding_modules,\n                self.model.embedding_padding_modules,\n                max_position_embeddings=self.model.config.max_position_embeddings,\n            )\n            self.model = self.lora_manager.create_lora_manager(self.model)\n\n        if self.prompt_adapter_config:\n            self.prompt_adapter_manager = LRUCacheWorkerPromptAdapterManager(\n                self.scheduler_config.max_num_seqs, self.scheduler_config.max_num_batched_tokens, self.device,\n                self.prompt_adapter_config)\n            self.model = (self.prompt_adapter_manager.create_prompt_adapter_manager(self.model))\n\n        if self.kv_cache_dtype == \"fp8\" and is_hip():\n            # Currently only ROCm accepts kv-cache scaling factors\n            # via quantization_param_path and this will be deprecated\n            # in the future.\n            if self.model_config.quantization_param_path is not None:\n                if callable(getattr(self.model, \"load_kv_cache_scales\", None)):\n                    warnings.warn(\n                        \"Loading kv cache scaling factor from JSON is \"\n                        \"deprecated and will be removed. Please include \"\n                        \"kv cache scaling factors in the model checkpoint.\",\n                        FutureWarning,\n                        stacklevel=2)\n                    self.model.load_kv_cache_scales(self.model_config.quantization_param_path)\n                    logger.info(\"Loaded KV cache scaling factors from %s\", self.model_config.quantization_param_path)\n                else:\n                    raise RuntimeError(\n                        \"Using FP8 KV cache and scaling factors provided but \"\n                        \"model %s does not support loading scaling factors.\", self.model.__class__)\n            else:\n                logger.warning(\"Using FP8 KV cache but no scaling factors \"\n                               \"provided. Defaulting to scaling factors of 1.0. \"\n                               \"This may lead to less accurate results!\")\n\n        if envs.VLLM_TEST_DYNAMO_GRAPH_CAPTURE:\n            self.model = torch.compile(self.model, fullgraph=True, backend=\"eager\")\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/parallel_state.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Adapted from\n# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py\n# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.\n\"\"\"Model and data parallel groups.\"\"\"\nimport os\nimport torch\nimport torch.distributed\nfrom typing import Optional\n\nimport vllm.distributed.parallel_state as ps\nfrom vllm.distributed.parallel_state import get_pp_group, get_world_group, init_distributed_environment, init_model_parallel_group\n\nimport vllm.envs as envs\nfrom vllm.logger import init_logger\n\nfrom torch.distributed.device_mesh import init_device_mesh\n\nlogger = init_logger(__name__)\n\"\"\"\nThis version is strongly tied with Megatron to implement HybridEngine and weight sharing between vllm and Megatron.\n- We assume the Megatron tp+dp+pp world is already established before calling this function.\n\n\"\"\"\n\n# Device mesh for using DTensor\n_DEVICE_MESH = None\n\n# Tensor model parallel group that the current rank belongs to.\n_TP = None\n# Pipeline model parallel group that the current rank belongs to.\n_PP = None\n\n\n# This method is for initializing the ParallelGroup when using HybridEngine\ndef initialize_parallel_state(\n    distributed_init_method: str = \"env://\",\n    backend: str = \"nccl\",\n    tensor_model_parallel_size: int = 1,\n    num_tp_per_train_tp: int = 1,\n    pipeline_model_parallel_size: int = 1,\n):\n    # torch.distributed.all_reduce does not free the input tensor until\n    # the synchronization point. This causes the memory usage to grow\n    # as the number of all_reduce calls increases. This env var disables\n    # this behavior.\n    # Related issue:\n    # https://discuss.pytorch.org/t/cuda-allocation-lifetime-for-inputs-to-distributed-all-reduce/191573\n    os.environ[\"TORCH_NCCL_AVOID_RECORD_STREAMS\"] = \"1\"\n\n    # NOTE(sgm): Modify for verl, Env vars will be set by TORCHRUN.\n    rank = int(os.getenv(\"RANK\", \"-1\"))\n    local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n\n    # Use the world_size set by TORCHRUN\n    world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n    assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n    init_distributed_environment(world_size, rank, distributed_init_method, local_rank, backend)\n    if torch.distributed.get_world_size() > 1:\n        # NOTE: build a sepearate inference group with infer tp & micro dp\n        initialize_model_parallel_for_vllm(tensor_model_parallel_size=tensor_model_parallel_size,\n                                           num_tensor_model_parallel_groups_per_train_tp=num_tp_per_train_tp)\n    else:\n        initialize_model_parallel(tensor_model_parallel_size, pipeline_model_parallel_size, backend)\n\n\ndef ensure_model_parallel_initialized(\n    tensor_model_parallel_size: int,\n    pipeline_model_parallel_size: int = 1,\n    backend: Optional[str] = None,\n) -> None:\n    \"\"\"Helper to initialize model parallel groups if they are not initialized,\n    or ensure tensor-parallel and pipeline-parallel sizes are equal to expected\n    values if the model parallel groups are initialized.\n    \"\"\"\n    # get the backend of _DEVICE_WORLD_GROUP\n    backend = backend or torch.distributed.get_backend(get_world_group().device_group)\n    if not model_parallel_is_initialized():\n        initialize_model_parallel(tensor_model_parallel_size, pipeline_model_parallel_size, backend)\n        return\n\n    assert (get_tensor_model_parallel_world_size() == tensor_model_parallel_size), (\n        \"tensor parallel group already initialized, but of unexpected size: \"\n        f\"{get_tensor_model_parallel_world_size()=} vs. \"\n        f\"{tensor_model_parallel_size=}\")\n    pp_world_size = get_pp_group().world_size\n    assert (pp_world_size == pipeline_model_parallel_size), (\n        \"pipeline parallel group already initialized, but of unexpected size: \"\n        f\"{pp_world_size=} vs. \"\n        f\"{pipeline_model_parallel_size=}\")\n\n\n# TODO(sgm): deviate from the v0.5.4, not pp now\ndef model_parallel_is_initialized():\n    \"\"\"Check if tensor and pipeline parallel groups are initialized.\"\"\"\n    return (ps._TP is not None)\n    # and _PIPELINE_MODEL_PARALLEL_GROUP is not None)\n\n\ndef initialize_model_parallel_for_vllm(tensor_model_parallel_size: int,\n                                       num_tensor_model_parallel_groups_per_train_tp: int = 1,\n                                       pipeline_model_parallel_size: int = 1) -> None:\n    from torch.distributed import new_group\n    # Get world size and rank. Ensure some consistencies.\n    assert torch.distributed.is_initialized()\n\n    assert isinstance(tensor_model_parallel_size, int)\n\n    # assert num_tensor_model_parallel_groups_per_train_tp == 1 and not different_tp_group\n    # assert num_tensor_model_parallel_groups_per_train_tp > 1 and different_tp_group\n\n    # Build the tensor model-parallel groups.\n    assert ps._TP is None, (\"tensor model parallel group is already initialized\")\n\n    global _TP\n\n    world_size: int = torch.distributed.get_world_size()\n\n    rank = torch.distributed.get_rank()\n\n    backend = torch.distributed.get_backend()\n\n    num_tensor_model_parallel_groups = world_size // tensor_model_parallel_size\n\n    if num_tensor_model_parallel_groups_per_train_tp == 1:\n        # if tensor_model_parallel_size == train_tensor_parallel_size:\n        # using the same tp group as Megatron/vllm\n        assert _TP is None, (\"tensor model parallel group is already initialized\")\n        group_ranks = []\n        for i in range(num_tensor_model_parallel_groups):\n            ranks = range(i * tensor_model_parallel_size, (i + 1) * tensor_model_parallel_size)\n            group_ranks.append(ranks)\n        _TP = init_model_parallel_group(\n            group_ranks=group_ranks,\n            local_rank=get_world_group().local_rank,\n            backend=backend,\n            use_custom_allreduce=False,  # TODO: check why True is not work in Ray trainer\n            use_message_queue_broadcaster=True)\n        ps._TP = _TP\n        # _MICRO_DATA_PARALLEL_GROUP is move to hybrid engine\n    else:\n        # initialize a micro_dp group and a tp group\n        # assume training tp=4, infer tp=2, then, weight is partitioned as\n        # [1], [2], [3], [4] for training and [1,2], [1,2], [3,4], [3,4] for inference\n\n        # Build the inference tp groups\n        # train_tp = train_tensor_parallel_size\n        train_tp = num_tensor_model_parallel_groups_per_train_tp * tensor_model_parallel_size\n        # num_tensor_model_parallel_groups_per_train_tp = train_tp // tensor_model_parallel_size\n        assert _TP is None, (\"tensor model parallel group is already initialized\")\n        group_ranks = []\n        for i in range(num_tensor_model_parallel_groups // num_tensor_model_parallel_groups_per_train_tp):\n            start = train_tp * i\n            end = train_tp * (i + 1)\n            for j in range(num_tensor_model_parallel_groups_per_train_tp):\n                ranks = list(range(start, end, num_tensor_model_parallel_groups_per_train_tp))\n                for i in range(len(ranks)):\n                    ranks[i] += j\n                group_ranks.append(ranks)\n        _TP = init_model_parallel_group(\n            group_ranks=group_ranks,\n            local_rank=get_world_group().local_rank,\n            backend=backend,\n            use_custom_allreduce=False,  # TODO: check why True is not work in Ray trainer\n            use_message_queue_broadcaster=True)\n        ps._TP = _TP\n\n    # Build the pipeline model-parallel groups.\n    # global _PIPELINE_MODEL_PARALLEL_GROUP\n    # global _PIPELINE_GLOBAL_RANKS\n    # assert ps._PIPELINE_MODEL_PARALLEL_GROUP is None, (\"pipeline model parallel group is already initialized\")\n\n    # ps._PIPELINE_MODEL_PARALLEL_GROUP = mpu.get_pipeline_model_parallel_group()\n    # ps._PIPELINE_GLOBAL_RANKS = mpu.get_pipeline_model_parallel_ranks()\n\n    # TODO: init using device mesh (not support hybrid engine now)\n    # Build the pipeline model-parallel groups.\n    num_pipeline_model_parallel_groups: int = (world_size // pipeline_model_parallel_size)\n    global _PP\n    assert _PP is None, (\"pipeline model parallel group is already initialized\")\n    group_ranks = []\n    for i in range(num_pipeline_model_parallel_groups):\n        ranks = list(range(i, world_size, num_pipeline_model_parallel_groups))\n        group_ranks.append(ranks)\n    # pipeline parallel does not need custom allreduce\n    _PP = init_model_parallel_group(group_ranks, get_world_group().local_rank, backend, use_custom_allreduce=False)\n    ps._PP = _PP  # for verl\n\n\ndef initialize_model_parallel(\n    tensor_model_parallel_size: int = 1,\n    pipeline_model_parallel_size: int = 1,\n    backend: Optional[str] = None,\n) -> None:\n    \"\"\"\n    NOTE: This method is a hack from the open-sourced version without\n    asertion of world_size = tp * pp\n    \n    Initialize model parallel groups.\n\n    Arguments:\n        tensor_model_parallel_size: number of GPUs used for tensor model\n            parallelism.\n        pipeline_model_parallel_size: number of GPUs used for pipeline model\n            parallelism.\n\n    Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we\n    use 2 GPUs to parallelize the model tensor, and 4 GPUs to parallelize\n    the model pipeline. The present function will\n    create 4 tensor model-parallel groups and 2 pipeline model-parallel groups:\n        4 tensor model-parallel groups:\n            [g0, g1], [g2, g3], [g4, g5], [g6, g7]\n        2 pipeline model-parallel groups:\n            [g0, g2, g4, g6], [g1, g3, g5, g7]\n    Note that for efficiency, the caller should make sure adjacent ranks\n    are on the same DGX box. For example if we are using 2 DGX-1 boxes\n    with a total of 16 GPUs, rank 0 to 7 belong to the first box and\n    ranks 8 to 15 belong to the second box.\n    \"\"\"\n    # Get world size and rank. Ensure some consistencies.\n    assert torch.distributed.is_initialized()\n    world_size: int = torch.distributed.get_world_size()\n    backend = backend or torch.distributed.get_backend(ps.get_world_group().device_group)\n\n    # NOTE(sgm) we don't assert world_size == tp * pp\n    # DP is not managed by vllm but by the verl WorkerGroup\n    # if (world_size !=\n    #         tensor_model_parallel_size * pipeline_model_parallel_size):\n    #     raise RuntimeError(\n    #         f\"world_size ({world_size}) is not equal to \"\n    #         f\"tensor_model_parallel_size ({tensor_model_parallel_size}) x \"\n    #         f\"pipeline_model_parallel_size ({pipeline_model_parallel_size})\")\n\n    num_tensor_model_parallel_groups: int = (world_size // tensor_model_parallel_size)\n    rank = torch.distributed.get_rank()\n    global _TP\n    assert _TP is None, (\"tensor model parallel group is already initialized\")\n    group_ranks = []\n    for i in range(num_tensor_model_parallel_groups):\n        ranks = list(range(i * tensor_model_parallel_size, (i + 1) * tensor_model_parallel_size))\n        group_ranks.append(ranks)\n\n    # message queue broadcaster is only used in tensor model parallel group\n    _TP = init_model_parallel_group(\n        group_ranks,\n        get_world_group().local_rank,\n        backend,\n        use_custom_allreduce=False,  # TODO: check why True is not work in Ray trainer\n        use_message_queue_broadcaster=True)\n    ps._TP = _TP\n\n    # TODO: init using device mesh (not support hybrid engine now)\n    # Build the pipeline model-parallel groups.\n    num_pipeline_model_parallel_groups: int = (world_size // pipeline_model_parallel_size)\n    global _PP\n    assert _PP is None, (\"pipeline model parallel group is already initialized\")\n    group_ranks = []\n    for i in range(num_pipeline_model_parallel_groups):\n        ranks = list(range(i, world_size, num_pipeline_model_parallel_groups))\n        group_ranks.append(ranks)\n    # pipeline parallel does not need custom allreduce\n    _PP = init_model_parallel_group(group_ranks, get_world_group().local_rank, backend, use_custom_allreduce=False)\n    ps._PP = _PP  # for verl\n\n\n\"\"\"\nDevice mesh utilities\n\"\"\"\n\n\ndef get_device_mesh():\n    assert _DEVICE_MESH is not None, (\"device mesh is not initialized\")\n    return _DEVICE_MESH\n\n\n\"\"\"\nTensor model parallel utilities\n\"\"\"\n\n\ndef get_tensor_model_parallel_group():\n    \"\"\"Get the tensor model parallel group the caller rank belongs to.\"\"\"\n    assert _TP is not None, (\"tensor model parallel group is not initialized\")\n    return _TP.device_group\n\n\ndef get_tensor_model_parallel_world_size():\n    \"\"\"Return world size for the tensor model parallel group.\"\"\"\n    return torch.distributed.get_world_size(group=get_tensor_model_parallel_group())\n\n\ndef get_tensor_model_parallel_rank():\n    \"\"\"Return my rank for the tensor model parallel group.\"\"\"\n    return torch.distributed.get_rank(group=get_tensor_model_parallel_group())\n\n\ndef get_tensor_model_parallel_src_rank():\n    \"\"\"Calculate the global rank corresponding to the first local rank\n    in the tensor model parallel group.\"\"\"\n    global_rank = torch.distributed.get_rank()\n    local_world_size = get_tensor_model_parallel_world_size()\n    return (global_rank // local_world_size) * local_world_size\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/spmd_gpu_executor.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/executor/gpu_executor.py\n\nimport os\nimport socket\nfrom typing import Any, Dict, List, Optional, Set, Tuple\n\nimport torch\nimport vllm.envs as envs\nfrom vllm.executor.executor_base import ExecutorBase, ExecutorAsyncBase\nfrom vllm.logger import init_logger\nfrom vllm.lora.request import LoRARequest\nfrom vllm.sequence import SamplerOutput, ExecuteModelRequest\n\nfrom vllm.config import (CacheConfig, DeviceConfig, LoRAConfig, MultiModalConfig, ParallelConfig, PromptAdapterConfig,\n                         SchedulerConfig, SpeculativeConfig)\nfrom .config import ModelConfig, LoadConfig\n\nlogger = init_logger(__name__)\n\n\nclass SPMDGPUExecutor(ExecutorBase):\n    \"\"\"SPMD-based multi-GPU executor implementations.\"\"\"\n\n    def __init__(\n        self,\n        model, # pytorch model itself or its parameter dict\n        model_config: ModelConfig,\n        cache_config: CacheConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        multimodal_config: Optional[MultiModalConfig],\n        speculative_config: Optional[SpeculativeConfig],\n        prompt_adapter_config: Optional[PromptAdapterConfig],\n    ) -> None:\n        self.model_config = model_config\n        self.cache_config = cache_config\n        self.lora_config = lora_config\n        self.load_config = load_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.multimodal_config = multimodal_config\n        self.speculative_config = speculative_config\n        self.prompt_adapter_config = prompt_adapter_config\n\n        distributed_init_method = initialize_cluster(parallel_config)\n        self._init_executor(model, distributed_init_method)\n\n    # TODO(sgm): verl not support speculative decode now\n    def _init_executor(self, model, distributed_init_method) -> None:\n        assert (not self.speculative_config), \"Speculative decoding not yet supported for multi-GPU backend.\"\n\n        # Create the parallel worker for each GPU.\n        self._init_workers_sp(model, distributed_init_method)\n\n    def _init_workers_sp(self, model, distributed_init_method: str):\n        # Lazy import the Worker to avoid importing torch.cuda/xformers\n        # before CUDA_VISIBLE_DEVICES is set in the Worker\n        from .worker import Worker  # pylint: disable=import-outside-toplevel\n\n        rank = int(os.getenv(\"RANK\"))\n        local_rank = int(os.getenv(\"LOCAL_RANK\"))\n        print(f'local rank {local_rank}')\n\n        # see https://github.com/NVIDIA/nccl/issues/1234\n        os.environ['NCCL_CUMEM_ENABLE'] = '0'\n\n        self.worker = Worker(\n            model,\n            self.model_config,\n            self.parallel_config,\n            self.scheduler_config,\n            self.device_config,\n            self.cache_config,\n            self.load_config,\n            local_rank,\n            rank,\n            distributed_init_method,\n            lora_config=self.lora_config,\n            multimodal_config=self.multimodal_config,\n            speculative_config=None,\n            prompt_adapter_config=self.speculative_config,\n            is_driver_worker=True,\n            model_runner_cls=None,  # use the default one\n        )\n\n        # NOTE(shengguangming): torch.distributed.init_process_group will be called inside the init_model()\n        self.worker.init_device()\n        self.worker.load_model()\n\n    def determine_num_available_blocks(self) -> Tuple[int, int]:\n        \"\"\"Determine the number of available KV blocks.\n\n        This invokes `determine_num_available_blocks` on each worker and takes\n        the min of the results, guaranteeing that the selected cache sizes are\n        compatible with all workers.\n\n        Returns:\n            - tuple[num_gpu_blocks, num_cpu_blocks]\n        \"\"\"\n        # Get the maximum number of blocks that can be allocated on GPU and CPU.\n        num_blocks = self.worker.determine_num_available_blocks()\n\n        # NOTE(shengguangming): Now we don't use a shared centralized controler but each process will\n        # have its own scheduler\n        num_gpu_blocks = num_blocks[0]\n        num_cpu_blocks = num_blocks[1]\n\n        return num_gpu_blocks, num_cpu_blocks\n\n    def initialize_cache(self, num_gpu_blocks: int, num_cpu_blocks: int) -> None:\n        \"\"\"Initialize the KV cache in all workers.\n        \"\"\"\n\n        # NOTE: We log here to avoid multiple logs when number of workers is\n        # greater than one. We could log in the engine, but not all executors\n        # have GPUs.\n        logger.info(\"# GPU blocks: %d, # CPU blocks: %d\", num_gpu_blocks, num_cpu_blocks)\n\n        self.cache_config.num_gpu_blocks = num_gpu_blocks\n        self.cache_config.num_cpu_blocks = num_cpu_blocks\n\n        if torch.distributed.get_rank() == 0:\n            print(\n                f'before init cache memory allocated: {torch.cuda.memory_allocated() / 1e9}GB, reserved: {torch.cuda.memory_reserved() / 1e9}GB'\n            )\n        self.worker.initialize_cache(num_gpu_blocks=num_gpu_blocks, num_cpu_blocks=num_cpu_blocks)\n        if torch.distributed.get_rank() == 0:\n            print(\n                f'after init cache memory allocated: {torch.cuda.memory_allocated() / 1e9}GB, reserved: {torch.cuda.memory_reserved() / 1e9}GB'\n            )\n\n    # NOTE(sgm): This will not profile & capture the model(CUDAGraph) when rebuilding KVCache\n    def init_cache_engine(self) -> None:\n        self.worker._init_cache_engine()\n\n    def free_cache_engine(self) -> None:\n        self.worker.free_cache_engine()\n\n    def execute_model(self, execute_model_req) -> List[SamplerOutput]:\n        all_outputs = self.worker.execute_model(execute_model_req=execute_model_req)\n\n        # NOTE(sgm):\n        # Each GPU in vllm under verl has its own spmd_gpu_executor, therefore all GPUs should return the outputs\n        # In vllm with ray, only the driver worker returns the sampling results.\n        return all_outputs\n\n    def add_lora(self, lora_request: LoRARequest) -> bool:\n        assert lora_request.lora_int_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.add_lora(lora_request=lora_request)\n\n    def remove_lora(self, lora_id: int) -> bool:\n        assert lora_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.remove_lora(lora_id=lora_id)\n\n    def list_loras(self) -> Set[int]:\n        return self.worker.list_loras()\n\n    def check_health(self) -> None:\n        # SPMDExecutor will always be healthy as long as\n        # it's running.\n        return\n\n    # NOTE(sgm) add for verl to pass the abstract class test, not used\n    from vllm.prompt_adapter.request import PromptAdapterRequest\n\n    def add_prompt_adapter(self, prompt_adapter_request: PromptAdapterRequest) -> bool:\n        assert prompt_adapter_request.prompt_adapter_id > 0, \\\n            \"prompt_adapter_id must be greater than 0.\"\n        return self.worker.add_prompt_adapter(prompt_adapter_request)\n\n    def list_prompt_adapters(self) -> Set[int]:\n        return self.worker.list_prompt_adapters()\n\n    def pin_lora(self, lora_id: int) -> bool:\n        assert lora_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.pin_lora(lora_id)\n\n    def pin_prompt_adapter(self, prompt_adapter_id: int) -> bool:\n        assert prompt_adapter_id > 0, \\\n                \"prompt_adapter_id must be greater than 0.\"\n        return self.worker.pin_prompt_adapter(prompt_adapter_id)\n\n    def remove_prompt_adapter(self, prompt_adapter_id: int) -> bool:\n        assert prompt_adapter_id > 0, \\\n            \"prompt_adapter_id must be greater than 0.\"\n        return self.worker.remove_prompt_adapter(prompt_adapter_id)\n\n    # NOTE(sgm): add for verl\n    def offload_model_weights(self) -> None:\n        self.worker.offload_model_weights()\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.worker.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n\ndef initialize_cluster(\n    parallel_config: ParallelConfig,\n    engine_use_ray: bool = False,\n    ray_address: Optional[str] = None,\n) -> Tuple[str, Optional[None]]:\n    \"\"\"Initialize the distributed cluster probably with Ray.\n\n    Args:\n        parallel_config: The configurations for parallel execution.\n\n    Returns:\n        The `distributed_init_method` is the address for initializing the\n        distributed backend.\n    \"\"\"\n\n    # Initialize cluster locally.\n    port = get_open_port()\n    # We need to setup the distributed init method to make sure\n    # the distributed megatron code (e.g., get world size) works correctly.\n    # distributed_init_method = f\"tcp://localhost:{port}\"\n    distributed_init_method = 'env://'\n    return distributed_init_method\n\n\ndef get_open_port():\n    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n        s.bind((\"\", 0))\n        return s.getsockname()[1]\n\n\n# TODO(sgm): not implemented async executor yet\nclass SPMDGPUExecutorAsync(SPMDGPUExecutor, ExecutorAsyncBase):\n\n    async def execute_model_async(self, execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:\n        \"\"\"Executes one model step on the given sequences.\"\"\"\n        raise NotImplementedError\n\n    async def check_health_async(self) -> None:\n        \"\"\"Checks if the executor is healthy. If not, it should raise an\n        exception.\"\"\"\n        self.check_health()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/tokenizer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/tokenizer_group/tokenizer_group.py\n\nfrom typing import List, Optional, Tuple, Union\n\nfrom transformers import (AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast)\n\nfrom vllm.lora.request import LoRARequest\nfrom vllm.utils import make_async, LRUCache\nfrom vllm.transformers_utils.tokenizers import *\n\n\nclass TokenizerGroup:\n    \"\"\"A group of tokenizers that can be used for LoRA adapters.\"\"\"\n\n    def __init__(self, tokenizer: PreTrainedTokenizer, enable_lora: bool, max_num_seqs: int,\n                 max_input_length: Optional[int]):\n        self.enable_lora = enable_lora\n        self.max_input_length = max_input_length\n        self.tokenizer = tokenizer\n        self.lora_tokenizers = LRUCache[PreTrainedTokenizer](capacity=max_num_seqs) if enable_lora else None\n\n    def ping(self) -> bool:\n        \"\"\"Check if the tokenizer group is alive.\"\"\"\n        return True\n\n    def get_max_input_len(self, lora_request: Optional[LoRARequest] = None) -> Optional[int]:\n        \"\"\"Get the maximum input length for the LoRA request.\"\"\"\n        return self.max_input_length\n\n    def encode(self,\n               prompt: str,\n               request_id: Optional[str] = None,\n               lora_request: Optional[LoRARequest] = None) -> List[int]:\n        tokenizer = self.get_lora_tokenizer(lora_request)\n        return tokenizer.encode(prompt)\n\n    async def encode_async(self,\n                           prompt: str,\n                           request_id: Optional[str] = None,\n                           lora_request: Optional[LoRARequest] = None) -> List[int]:\n        tokenizer = await self.get_lora_tokenizer_async(lora_request)\n        return tokenizer.encode(prompt)\n\n    def get_lora_tokenizer(self, lora_request: Optional[LoRARequest]) -> \"PreTrainedTokenizer\":\n        if not lora_request or not self.enable_lora:\n            return self.tokenizer\n        if lora_request.lora_int_id not in self.lora_tokenizers:\n            # TODO(sgm): the lora tokenizer is also passed, but may be different\n            tokenizer = self.tokenizer\n            # tokenizer = (get_lora_tokenizer(\n            #     lora_request, **self.tokenizer_config) or self.tokenizer)\n            self.lora_tokenizers.put(lora_request.lora_int_id, tokenizer)\n            return tokenizer\n        else:\n            return self.lora_tokenizers.get(lora_request.lora_int_id)\n\n    # FIXME(sgm): for simplicity, we assign the special token here\n    @property\n    def pad_token_id(self):\n        return self.tokenizer.pad_token_id\n\n    @property\n    def eos_token_id(self):\n        return self.tokenizer.eos_token_id\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_5_4/worker.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/worker.py\n\"\"\"A GPU worker class.\"\"\"\nimport os\nimport gc\nfrom typing import Dict, List, Tuple, Optional, Union, Type\n\nimport torch\nimport torch.distributed\nimport torch.nn as nn\n\nfrom vllm.config import (CacheConfig, DeviceConfig, LoRAConfig, MultiModalConfig, ParallelConfig, PromptAdapterConfig,\n                         SchedulerConfig, SpeculativeConfig)\nfrom vllm.model_executor import set_random_seed\nfrom vllm.sequence import (ExecuteModelRequest, IntermediateTensors, SamplerOutput)\nfrom vllm.worker.cache_engine import CacheEngine\n# TODO(sgm): check why vllm has similar file in vllm.model_executor.parallel_utils.parallel_state\nfrom vllm.distributed import (init_distributed_environment, set_custom_all_reduce, get_tensor_model_parallel_group)\nfrom vllm.worker.worker_base import WorkerInput\nfrom vllm.worker.worker import Worker, _check_if_gpu_supports_dtype\nfrom vllm.worker.model_runner_base import ModelRunnerBase, ModelRunnerInputBase\nfrom vllm.worker.embedding_model_runner import EmbeddingModelRunner\nfrom vllm.worker.model_runner import GPUModelRunnerBase\nfrom .model_runner import ModelRunner\nfrom .megatron_weight_loaders import load_megatron_weights\nfrom .hf_weight_loader import load_hf_weights\nfrom .dtensor_weight_loaders import load_dtensor_weights\nfrom .parallel_state import (ensure_model_parallel_initialized)\nfrom .config import ModelConfig, LoadConfig, LoadFormat\n\n\nclass Worker(Worker):\n    \"\"\"A worker class that executes (a partition of) the model on a GPU.\n\n    Each worker is associated with a single GPU. The worker is responsible for\n    maintaining the KV cache and executing the model on the GPU. In case of\n    distributed inference, each worker is assigned a partition of the model.\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict], # model itself or its parameter dict\n        model_config: ModelConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        cache_config: CacheConfig,\n        load_config: LoadConfig,\n        local_rank: int,\n        rank: int,\n        distributed_init_method: str,\n        lora_config: Optional[LoRAConfig] = None,\n        multimodal_config: Optional[MultiModalConfig] = None,\n        speculative_config: Optional[SpeculativeConfig] = None,\n        prompt_adapter_config: Optional[PromptAdapterConfig] = None,\n        is_driver_worker: bool = False,\n        model_runner_cls: Optional[Type[GPUModelRunnerBase]] = None,\n    ) -> None:\n        # self.model = model  # will be replaced in the init_model\n        self.model_config = model_config\n        self.parallel_config = parallel_config\n        self.parallel_config.rank = rank\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.cache_config = cache_config\n        self.local_rank = local_rank\n        self.rank = rank\n        self.distributed_init_method = distributed_init_method\n        self.lora_config = lora_config\n        self.load_config = load_config\n        self.prompt_adapter_config = prompt_adapter_config\n        self.is_driver_worker = is_driver_worker  # TODO: we don't need driver\n        # if parallel_config and is_driver_worker:\n        #     assert rank % parallel_config.tensor_parallel_size == 0, \\\n        #            \"Driver worker should be rank 0 of tensor parallel group.\"\n        if self.model_config.trust_remote_code:\n            # note: lazy import to avoid importing torch before initializing\n            from vllm.utils import init_cached_hf_modules\n            init_cached_hf_modules()\n        self.multimodal_config = multimodal_config\n\n        # Return hidden states from target model if the draft model is an\n        # mlp_speculator\n        speculative_args = {} if speculative_config is None \\\n            or (speculative_config.draft_model_config.model ==\n                model_config.model) \\\n            or (speculative_config.draft_model_config.hf_config.model_type\n                not in [\"medusa\", \"mlp_speculator\"]) \\\n                    else {\"return_hidden_states\": True}\n\n        # TODO(sgm): set correct model runner class\n        ModelRunnerClass: Type[GPUModelRunnerBase] = ModelRunner\n        if model_runner_cls is not None:\n            ModelRunnerClass = model_runner_cls\n        elif self.model_config.embedding_mode:\n            ModelRunnerClass = EmbeddingModelRunner\n        self.model_runner: GPUModelRunnerBase = ModelRunnerClass(\n            model, # [VERL]: add for verl\n            model_config,\n            parallel_config,\n            scheduler_config,\n            device_config,\n            cache_config,\n            load_config=load_config,\n            lora_config=self.lora_config,\n            kv_cache_dtype=self.cache_config.cache_dtype,\n            is_driver_worker=is_driver_worker,\n            prompt_adapter_config=prompt_adapter_config,\n            multimodal_config=multimodal_config,\n            **speculative_args,\n        )\n\n        # Uninitialized cache engine. Will be initialized by\n        # initialize_cache.\n        self.cache_engine: List[CacheEngine] = None\n        # Initialize gpu_cache as embedding models don't initialize kv_caches\n        self.gpu_cache: Optional[List[List[torch.Tensor]]] = None\n\n        # NOTE(sgm): [VERL] For offloading inference engine params\n        self.cpu_model = None\n\n    def init_device(self) -> None:\n        if self.device_config.device.type == \"cuda\":\n            # torch.distributed.all_reduce does not free the input tensor until\n            # the synchronization point. This causes the memory usage to grow\n            # as the number of all_reduce calls increases. This env var disables\n            # this behavior.\n            # Related issue:\n            # https://discuss.pytorch.org/t/cuda-allocation-lifetime-for-inputs-to-distributed-all-reduce/191573\n            os.environ[\"TORCH_NCCL_AVOID_RECORD_STREAMS\"] = \"1\"\n\n            # NOTE(sgm): Modify for verl, Env vars will be set by TORCHRUN.\n            self.rank = self.rank if self.rank is not None else int(os.getenv(\"RANK\", \"-1\"))\n            local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n            self.device = torch.device(f\"cuda:{local_rank}\")\n            if self.rank < 0:\n                raise ValueError(\"Invalid or unspecified rank.\")\n            torch.cuda.set_device(self.device)\n\n            # Use the world_size set by TORCHRUN\n            world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n            assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n            self.parallel_config.world_size = world_size\n\n            _check_if_gpu_supports_dtype(self.model_config.dtype)\n            torch.cuda.empty_cache()\n            self.init_gpu_memory = torch.cuda.mem_get_info()[0]\n        else:\n            raise RuntimeError(f\"Not support device type: {self.device_config.device}\")\n\n        # Initialize the distributed environment.\n        init_worker_distributed_environment(self.parallel_config, self.rank, self.distributed_init_method,\n                                            self.local_rank)\n        # Set random seed.\n        set_random_seed(self.model_config.seed)\n        # self.model = get_model(actor_model=self.model, model_config=self.model_config)\n\n    @torch.inference_mode()\n    def determine_num_available_blocks(self) -> Tuple[int, int]:\n        \"\"\"Profiles the peak memory usage of the model to determine how many\n        KV blocks may be allocated without OOMs.\n\n        The engine will first conduct a profiling of the existing memory usage.\n        Then, it calculate the maximum possible number of GPU and CPU blocks\n        that can be allocated with the remaining free memory.\n\n        .. tip::\n            You may limit the usage of GPU memory\n            by adjusting the `gpu_memory_utilization` parameter.\n        \"\"\"\n        # Profile the memory usage of the model and get the maximum number of\n        # cache blocks that can be allocated with the remaining free memory.\n        torch.cuda.empty_cache()\n        # torch.cuda.reset_peak_memory_stats()\n\n        # Execute a forward pass with dummy inputs to profile the memory usage\n        # of the model.\n        self.model_runner.profile_run()\n\n        # Calculate the number of blocks that can be allocated with the\n        # profiled peak memory.\n        torch.cuda.synchronize()\n        free_gpu_memory, total_gpu_memory = torch.cuda.mem_get_info()\n        peak_memory = total_gpu_memory - free_gpu_memory\n\n        assert peak_memory > 0, (\"Error in memory profiling. This happens when the GPU memory was \"\n                                 \"not properly cleaned up before initializing the vLLM instance.\")\n\n        cache_block_size = self.get_cache_block_size_bytes()\n\n        # NOTE(sgm) [VERL] use the remaining memory\n        num_gpu_blocks = int((free_gpu_memory * self.cache_config.gpu_memory_utilization) // cache_block_size)\n        # num_gpu_blocks = int((total_gpu_memory * self.cache_config.gpu_memory_utilization - peak_memory) // cache_block_size)\n\n        num_cpu_blocks = int(self.cache_config.swap_space_bytes // cache_block_size)\n        num_gpu_blocks = max(num_gpu_blocks, 0)\n        num_cpu_blocks = max(num_cpu_blocks, 0)\n        if self.model_runner.lora_manager:\n            self.model_runner.remove_all_loras()\n\n        # NOTE(sgm): Add for [VERL], synchronize number of blocks with all the rank\n        num_gpu_blocks = torch.tensor([num_gpu_blocks], device='cuda')\n        num_cpu_blocks = torch.tensor([num_cpu_blocks], device='cuda')\n\n        torch.distributed.all_reduce(num_gpu_blocks,\n                                     op=torch.distributed.ReduceOp.MIN,\n                                     group=get_tensor_model_parallel_group().device_group)\n        torch.distributed.all_reduce(num_cpu_blocks,\n                                     op=torch.distributed.ReduceOp.MIN,\n                                     group=get_tensor_model_parallel_group().device_group)\n        num_gpu_blocks = num_gpu_blocks.item()\n        num_cpu_blocks = num_cpu_blocks.item()\n        gc.collect()\n        torch.cuda.empty_cache()\n        return num_gpu_blocks, num_cpu_blocks\n\n    def _init_cache_engine(self):\n        if self.cache_engine is None and self.gpu_cache is None:\n            super()._init_cache_engine()\n\n    def free_cache_engine(self):\n        # ensure `enforce_eager=True`\n        self.cache_engine = None\n        self.gpu_cache = None\n\n    # NOTE(sgm): [VERL]: adapt from _execute_model_spmd()\n    def execute_model(self,\n                      execute_model_req: ExecuteModelRequest,\n                      intermediate_tensors: Optional[IntermediateTensors] = None) -> Optional[List[SamplerOutput]]:\n        \"\"\"\n        Execute model in Single Program Multiple Data (SPMD) fashion.\n        All workers take the same request, prepare the input and\n        execute the model.\n        \"\"\"\n        assert execute_model_req is not None, (\"_execute_model_spmd() requires each worker to take in an \"\n                                               \"ExecuteModelRequest\")\n        worker_input: WorkerInput = self.prepare_worker_input(execute_model_req=execute_model_req)\n        model_input: ModelRunnerInputBase = (self.model_runner.prepare_model_input(\n            execute_model_req.seq_group_metadata_list))\n\n        # verl.worker.workerbase.WorkerBase\n        # swap cache\n        super().execute_worker(worker_input)\n\n        # If there is no input, we don't need to execute the model.\n        if worker_input.num_seq_groups == 0:\n            return []\n\n        return self.model_runner.execute_model(\n            model_input, self.kv_cache[worker_input.virtual_engine] if self.kv_cache is not None else None,\n            intermediate_tensors)\n\n    # assume the input is .state_dict()\n    def sync_model_weights(self, actor_weights: Dict, load_format: str):\n        if load_format in [LoadFormat.MEGATRON, LoadFormat.AUTO]:\n            load_megatron_weights(actor_weights, self.model_runner.model)\n        elif load_format == LoadFormat.HF:\n            # full model state dict without no sharding\n            load_hf_weights(actor_weights, self.model_runner.model)\n        elif load_format == LoadFormat.DTENSOR:\n            load_dtensor_weights(actor_weights, self.model_runner.model)\n\n    def offload_model_weights(self) -> None:\n        if self.cpu_model == None:\n            self.cpu_model = {}\n            for name, params in self.model_runner.model.named_parameters():\n                self.cpu_model[name] = torch.empty_like(params, device='cpu')\n                params.data = self.cpu_model[name]\n        else:\n            for name, params in self.model_runner.model.named_parameters():\n                params.data = self.cpu_model[name]\n\n\ndef init_worker_distributed_environment(\n    parallel_config: ParallelConfig,\n    rank: int,\n    distributed_init_method: Optional[str] = \"env://\",\n    local_rank: int = -1,\n) -> None:\n    \"\"\"Initialize the distributed environment.\"\"\"\n    set_custom_all_reduce(not parallel_config.disable_custom_all_reduce)\n\n    # NOTE(sgm) use tcp://localhost:xxxx will hang in HF setting without megatron\n    init_distributed_environment(parallel_config.world_size, rank, distributed_init_method, local_rank)\n\n    ensure_model_parallel_initialized(tensor_model_parallel_size=parallel_config.tensor_parallel_size,\n                                      pipeline_model_parallel_size=parallel_config.pipeline_parallel_size)\n\n    # TODO(sgm): check whether need this\n    # if pynccl_utils.is_initialized():\n    #     pynccl_world_size = pynccl_utils.get_world_size()\n    #     if pynccl_world_size != parallel_config.world_size:\n    #         raise RuntimeError(\n    #             \"pynccl is already initialized but the pynccl world \"\n    #             \"size does not match parallel_config.world_size \"\n    #             f\"({pynccl_world_size} vs. {parallel_config.world_size}).\")\n    # elif parallel_config.world_size > 1:\n    #     # NOTE(woosuk): We don't initialize pynccl process group when world size\n    #     # is 1.\n    #     # NOTE(kaichao): By default, pynccl is initialized for tp group.\n    #     pynccl_utils.init_process_group(\n    #         group=get_tensor_model_parallel_cpu_group())\n\n    # # Initialize a custom fast all-reduce implementation.\n    # if not parallel_config.disable_custom_all_reduce:\n    #     init_custom_ar()\n\n    # A small all_reduce for warmup.\n    torch.distributed.all_reduce(torch.zeros(1).cuda())\n    # if pynccl_utils.is_initialized():\n    #     pynccl_utils.all_reduce(torch.zeros(1).cuda())\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/arg_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/arg_utils.py\n\nimport os\nfrom dataclasses import dataclass\n\nfrom transformers import PretrainedConfig\nfrom vllm.config import EngineConfig\nfrom vllm.engine.arg_utils import EngineArgs\n\nfrom .config import LoadConfig, ModelConfig\n\n\n@dataclass\nclass EngineArgs(EngineArgs):\n    model_hf_config: PretrainedConfig = None  # for verl\n\n    def __post_init__(self):\n        pass\n\n    def create_model_config(self) -> ModelConfig:\n        return ModelConfig(\n            hf_config=self.model_hf_config,\n            tokenizer_mode=self.tokenizer_mode,\n            trust_remote_code=self.trust_remote_code,\n            dtype=self.dtype,\n            seed=self.seed,\n            revision=self.revision,\n            code_revision=self.code_revision,\n            rope_scaling=self.rope_scaling,\n            rope_theta=self.rope_theta,\n            tokenizer_revision=self.tokenizer_revision,\n            max_model_len=self.max_model_len,\n            quantization=self.quantization,\n            quantization_param_path=self.quantization_param_path,\n            enforce_eager=self.enforce_eager,\n            max_context_len_to_capture=self.max_context_len_to_capture,\n            max_seq_len_to_capture=self.max_seq_len_to_capture,\n            max_logprobs=self.max_logprobs,\n            disable_sliding_window=self.disable_sliding_window,\n            skip_tokenizer_init=self.skip_tokenizer_init,\n            served_model_name=self.served_model_name,\n            limit_mm_per_prompt=self.limit_mm_per_prompt,\n            use_async_output_proc=not self.disable_async_output_proc,\n            override_neuron_config=self.override_neuron_config,\n            config_format=self.config_format,\n            mm_processor_kwargs=self.mm_processor_kwargs,\n        )\n\n    def create_load_config(self) -> LoadConfig:\n        return LoadConfig(\n            load_format=self.load_format,\n            download_dir=self.download_dir,\n            model_loader_extra_config=self.model_loader_extra_config,\n            ignore_patterns=self.ignore_patterns,\n        )\n\n    def create_engine_config(self) -> EngineConfig:\n        engine_config = super().create_engine_config()\n\n        # NOTE[VERL]: Use the world_size set by torchrun\n        world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n        assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n        engine_config.parallel_config.world_size = world_size\n\n        return engine_config\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/config.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/config.py\n\nimport enum\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import TYPE_CHECKING, List, Optional, Union\n\nfrom transformers import PretrainedConfig\n\n# Add for verl\nfrom vllm.config import ModelConfig\nfrom vllm.logger import init_logger\nfrom vllm.utils import is_hip\n\nif TYPE_CHECKING:\n    from vllm.model_executor.model_loader.loader import BaseModelLoader\n\nlogger = init_logger(__name__)\n\n\nclass LoadFormat(str, enum.Enum):\n    AUTO = \"auto\"\n    MEGATRON = \"megatron\"\n    HF = \"hf\"\n    DTENSOR = \"dtensor\"\n    DUMMY_HF = \"dummy_hf\"\n    DUMMY_MEGATRON = \"dummy_megatron\"\n    DUMMY_DTENSOR = \"dummy_dtensor\"\n\n\nclass ModelConfig(ModelConfig):\n\n    def __init__(self, hf_config: PretrainedConfig, *args, **kwargs) -> None:\n        super().__init__(model=hf_config._name_or_path, tokenizer=hf_config._name_or_path, *args, **kwargs)\n        self.hf_config = hf_config\n\n\n@dataclass\nclass LoadConfig:\n    \"\"\"\n    download_dir: Directory to download and load the weights, default to the\n        default cache directory of huggingface.\n    load_format: The format of the model weights to load:\n        \"auto\" will try to load the weights in the safetensors format and\n            fall back to the pytorch bin format if safetensors format is\n            not available.\n        \"pt\" will load the weights in the pytorch bin format.\n        \"safetensors\" will load the weights in the safetensors format.\n        \"npcache\" will load the weights in pytorch format and store\n            a numpy cache to speed up the loading.\n        \"dummy\" will initialize the weights with random values, which is\n            mainly for profiling.\n        \"tensorizer\" will use CoreWeave's tensorizer library for\n            fast weight loading.\n        \"bitsandbytes\" will load nf4 type weights.\n    ignore_patterns: The list of patterns to ignore when loading the model.\n        Default to \"original/**/*\" to avoid repeated loading of llama's\n        checkpoints.\n\n    \"\"\"\n\n    load_format: Union[str, LoadFormat, \"BaseModelLoader\"] = LoadFormat.AUTO\n    download_dir: Optional[str] = None\n    model_loader_extra_config: Optional[Union[str, dict]] = field(default_factory=dict)\n    ignore_patterns: Optional[Union[List[str], str]] = None\n\n    def __post_init__(self):\n        model_loader_extra_config = self.model_loader_extra_config or {}\n        if isinstance(model_loader_extra_config, str):\n            self.model_loader_extra_config = json.loads(model_loader_extra_config)\n        self._verify_load_format()\n\n        if self.ignore_patterns is not None and len(self.ignore_patterns) > 0:\n            logger.info(\"Ignoring the following patterns when downloading weights: %s\", self.ignore_patterns)\n        else:\n            self.ignore_patterns = [\"original/**/*\"]\n\n    def _verify_load_format(self) -> None:\n        if not isinstance(self.load_format, str):\n            return\n\n        load_format = self.load_format.lower()\n        self.load_format = LoadFormat(load_format)\n\n        rocm_not_supported_load_format: List[str] = []\n        if is_hip() and load_format in rocm_not_supported_load_format:\n            rocm_supported_load_format = [\n                f for f in LoadFormat.__members__ if (f not in rocm_not_supported_load_format)\n            ]\n            raise ValueError(f\"load format '{load_format}' is not supported in ROCm. \"\n                             f\"Supported load formats are \"\n                             f\"{rocm_supported_load_format}\")\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/dtensor_weight_loaders.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader\n\nfrom typing import Dict\n\nimport torch.nn as nn\nfrom torch.distributed._tensor import DTensor\nfrom vllm.model_executor.model_loader.weight_utils import default_weight_loader\nfrom vllm.model_executor.models.utils import is_pp_missing_parameter\n\n\ndef gemma_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        for param_name, shard_name, shard_id in stacked_params_mapping:\n            if shard_name not in name:\n                continue\n            stacked_name = name.replace(shard_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if stacked_name.endswith(\".bias\") and stacked_name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[stacked_name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # lm_head is not used in vllm as it is tied with embed_token.\n            # To prevent errors, skip loading lm_head.weight.\n            if \"lm_head.weight\" in name:\n                continue\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef gptbigcode_dtensor_load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"lm_head.weight\" in name:\n            continue\n        if \".attn.bias\" in name:\n            # Skip attention mask.\n            # NOTE: \"c_attn.bias\" should not be skipped.\n            continue\n        local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n        param = params_dict[name]\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef starcoder2_dtensor_load_weights(actor_weights: Dict, vllm_model: nn.Module):\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n    ]\n\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef llama_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\".qkv_proj\", \".q_proj\", \"q\"),\n        (\".qkv_proj\", \".k_proj\", \"k\"),\n        (\".qkv_proj\", \".v_proj\", \"v\"),\n        (\".gate_up_proj\", \".gate_proj\", 0),\n        (\".gate_up_proj\", \".up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if \"rotary_emb.cos_cached\" in name or \"rotary_emb.sin_cached\" in name:\n            # Models trained using ColossalAI may include these tensors in\n            # the checkpoint. Skip them.\n            continue\n        # With tie_word_embeddings, we can skip lm_head.weight\n        # The weight might appear unnecessarily in the files if the model is\n        # processed with quantization, LoRA, fine-tuning, etc.\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight)\n\n\ndef qwen2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef qwen2vl_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"qkv_proj\", \"q_proj\", \"q\"),\n        (\"qkv_proj\", \"k_proj\", \"k\"),\n        (\"qkv_proj\", \"v_proj\", \"v\"),\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            if weight_name not in name:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            param = params_dict[name]\n            weight_loader = param.weight_loader\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\nfrom vllm.model_executor.layers.fused_moe import FusedMoE\n\n\ndef deepseekv2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    stacked_params_mapping = [\n        # (param_name, shard_name, shard_id)\n        (\"gate_up_proj\", \"gate_proj\", 0),\n        (\"gate_up_proj\", \"up_proj\", 1),\n    ]\n\n    # Params for weights, fp8 weight scales, fp8 activation scales\n    # (param_name, weight_name, expert_id, shard_id)\n    expert_params_mapping = FusedMoE.make_expert_params_mapping(\n        ckpt_gate_proj_name=\"gate_proj\",\n        ckpt_down_proj_name=\"down_proj\",\n        ckpt_up_proj_name=\"up_proj\",\n        num_experts=vllm_model.config.n_routed_experts,\n    )\n\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        for param_name, weight_name, shard_id in stacked_params_mapping:\n            # Skip non-stacked layers and experts (experts handled below).\n            if weight_name not in name:\n                continue\n            # We have mlp.experts[0].gate_proj in the checkpoint.\n            # Since we handle the experts below in expert_params_mapping,\n            # we need to skip here BEFORE we update the name, otherwise\n            # name will be updated to mlp.experts[0].gate_up_proj, which\n            # will then be updated below in expert_params_mapping\n            # for mlp.experts[0].gate_gate_up_proj, which breaks load.\n            if (\"mlp.experts.\" in name) and name not in params_dict:\n                continue\n            name = name.replace(weight_name, param_name)\n            # Skip loading extra bias for GPTQ models.\n            if name.endswith(\".bias\") and name not in params_dict:\n                continue\n\n            if is_pp_missing_parameter(name, vllm_model):\n                continue\n\n            param = params_dict[name]\n            local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)\n            break\n        else:\n            for mapping in expert_params_mapping:\n                param_name, weight_name, expert_id, shard_id = mapping\n                if weight_name not in name:\n                    continue\n                name = name.replace(weight_name, param_name)\n\n                if is_pp_missing_parameter(name, vllm_model):\n                    continue\n\n                param = params_dict[name]\n                local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(\n                    param,\n                    local_loaded_weight.to(dtype=param.dtype),\n                    weight_name,\n                    shard_id=shard_id,\n                    expert_id=expert_id,\n                )\n                break\n            else:\n                # Skip loading extra bias for GPTQ models.\n                if name.endswith(\".bias\") and name not in params_dict:\n                    continue\n\n                if is_pp_missing_parameter(name, vllm_model):\n                    continue\n\n                param = params_dict[name]\n                local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)\n                weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n                weight_loader(param, local_loaded_weight.to(dtype=param.dtype))\n\n\ndef gpt2_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    pass\n\n\ndef redistribute_dtensor(param_name: str, loaded_weights: DTensor, parallelize_plan: Dict = None):\n    param_name = _process_parameter_names(name=param_name)\n    if parallelize_plan is not None:\n        assert (\n            param_name\n            in parallelize_plan.keys()), f\"param name: {param_name} not in parallelize_plan :{parallelize_plan.keys()}\"\n        placement = parallelize_plan[param_name]\n        local_loaded_weights = loaded_weights.redistribute(device_mesh=loaded_weights.device_mesh,\n                                                           placements=placement).to_local()\n    else:\n        local_loaded_weights = loaded_weights.full_tensor()\n    return local_loaded_weights\n\n\ndef _process_parameter_names(name):\n    # Remove '.weight' if it exists at the end of the string\n    if name.endswith(\".weight\"):\n        name = name[:-7]\n\n    # Remove 'model.layers.x.' or 'model.' prefix\n    if \"model.layers\" in name:\n        parts = name.split(\".\")\n        # Reconstruct the string without 'model.layers.x.'\n        name = \".\".join(parts[3:])  # parts[0] is 'model', parts[1] is 'layers', parts[2] is 'x'\n    elif name.startswith(\"model.\"):\n        name = name[6:]  # Remove 'model.'\n\n    return name\n\n\n__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__ = {\n    \"GPT2LMHeadModel\": gpt2_dtensor_weight_loader,\n    \"LlamaForCausalLM\": llama_dtensor_weight_loader,\n    \"LLaMAForCausalLM\": llama_dtensor_weight_loader,\n    \"MistralForCausalLM\": llama_dtensor_weight_loader,  # mistral is the same as llama in vLLM\n    \"InternLMForCausalLM\": llama_dtensor_weight_loader,\n    \"AquilaModel\": llama_dtensor_weight_loader,\n    \"AquilaForCausalLM\": llama_dtensor_weight_loader,\n    \"Phi3ForCausalLM\": llama_dtensor_weight_loader,\n    \"GemmaForCausalLM\": gemma_dtensor_weight_loader,\n    \"Gemma2ForCausalLM\": gemma_dtensor_weight_loader,\n    \"GPTBigCodeForCausalLM\": gptbigcode_dtensor_load_weights,\n    \"Starcoder2ForCausalLM\": starcoder2_dtensor_load_weights,\n    \"Qwen2ForCausalLM\": qwen2_dtensor_weight_loader,\n    \"DeepseekV2ForCausalLM\": deepseekv2_dtensor_weight_loader,\n    \"Qwen2VLForConditionalGeneration\": qwen2vl_dtensor_weight_loader,\n}\n\n\n# the actor model is .state_dict()\n# Load dtensor weights\ndef load_dtensor_weights(actor_weights: Dict, vllm_model: nn.Module):\n    weight_loader = _get_model_weight_loader(vllm_model.__class__.__name__)\n    weight_loader(actor_weights, vllm_model)\n    # NOTE(sgm) to reduce peak memory usage, we offload vllm model to cpu\n    # after init, and we need this after sync model weights for in first iter.\n    vllm_model = vllm_model.cuda()\n\n\ndef _get_model_weight_loader(arch: str):\n    if arch in __MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__:\n        return __MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__.keys()}\")\n\n\n# NOTE(sgm): we use per-parameter weight loader in each vllm sub\ndef update_dtensor_weight_loader():\n    pass\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/hf_weight_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader\n\nfrom typing import Dict\n\nimport torch.nn as nn\nfrom vllm.model_executor.model_loader.utils import set_default_torch_dtype\n\n\ndef update_hf_weight_loader():\n    print(\"no hf weight loader need to be updated\")\n    return\n\n\ndef load_hf_weights(actor_weights: Dict, vllm_model: nn.Module):\n    assert isinstance(actor_weights, Dict)\n    with set_default_torch_dtype(next(vllm_model.parameters()).dtype):  # TODO\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in actor_weights.keys():\n            del actor_weights[\"lm_head.weight\"]\n        vllm_model.load_weights(actor_weights.items())\n    for _, module in vllm_model.named_modules():\n        quant_method = getattr(module, \"quant_method\", None)\n        if quant_method is not None:\n            quant_method.process_weights_after_loading(module)\n        # FIXME: Remove this after Mixtral is updated\n        # to use quant_method.\n        if hasattr(module, \"process_weights_after_loading\"):\n            module.process_weights_after_loading()\n    vllm_model = vllm_model.cuda()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/llm.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/llm.py\n\nfrom typing import Dict, List, Optional, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pad_sequence\nfrom transformers import PretrainedConfig, PreTrainedTokenizer, PreTrainedTokenizerFast\nfrom verl.workers.rollout.tokenizer import HybridEngineBaseTokenizer\nfrom vllm import LLM\nfrom vllm.outputs import EmbeddingRequestOutput, RequestOutput\nfrom vllm.utils import Counter\n\nfrom .arg_utils import EngineArgs\nfrom .llm_engine_sp import LLMEngine\n\n\nclass LLM(LLM):\n    \"\"\"An LLM for generating texts from given prompts and sampling parameters.\n\n    This class includes a tokenizer, a language model (possibly distributed\n    across multiple GPUs), and GPU memory space allocated for intermediate\n    states (aka KV cache). Given a batch of prompts and sampling parameters,\n    this class generates texts from the model, using an intelligent batching\n    mechanism and efficient memory management.\n\n    NOTE: This class is intended to be used for offline inference. For online\n    serving, use the `AsyncLLMEngine` class instead.\n    NOTE: For the comprehensive list of arguments, see `EngineArgs`.\n\n    Args:\n        model: A HuggingFace Transformers model instance.\n        tokenizer: A HuggingFace Transformers tokenizer instance.\n        tokenizer_mode: The tokenizer mode. \"auto\" will use the fast tokenizer\n            if available, and \"slow\" will always use the slow tokenizer.\n        trust_remote_code: Trust remote code (e.g., from HuggingFace) when\n            downloading the model and tokenizer.\n        tensor_parallel_size: The number of GPUs to use for distributed\n            execution with tensor parallelism.\n        dtype: The data type for the model weights and activations. Currently,\n            we support `float32`, `float16`, and `bfloat16`. If `auto`, we use\n            the `torch_dtype` attribute specified in the model config file.\n            However, if the `torch_dtype` in the config is `float32`, we will\n            use `float16` instead.\n        quantization: The method used to quantize the model weights. Currently,\n            we support \"awq\". If None, we assume the model weights are not\n            quantized and use `dtype` to determine the data type of the weights.\n        revision: The specific model version to use. It can be a branch name,\n            a tag name, or a commit id.\n        tokenizer_revision: The specific tokenizer version to use. It can be a\n            branch name, a tag name, or a commit id.\n        seed: The seed to initialize the random number generator for sampling.\n        gpu_memory_utilization: The ratio (between 0 and 1) of GPU memory to\n            reserve for the model weights, activations, and KV cache. Higher\n            values will increase the KV cache size and thus improve the model's\n            throughput. However, if the value is too high, it may cause out-of-\n            memory (OOM) errors.\n        swap_space: The size (GiB) of CPU memory per GPU to use as swap space.\n            This can be used for temporarily storing the states of the requests\n            when their `best_of` sampling parameters are larger than 1. If all\n            requests will have `best_of=1`, you can safely set this to 0.\n            Otherwise, too small values may cause out-of-memory (OOM) errors.\n        enforce_eager: Whether to enforce eager execution. If True, we will\n            disable CUDA graph and always execute the model in eager mode.\n            If False, we will use CUDA graph and eager execution in hybrid.\n        max_context_len_to_capture: Maximum context len covered by CUDA graphs.\n            When a sequence has context length larger than this, we fall back\n            to eager mode.\n        disable_custom_all_reduce: See ParallelConfig\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict],  # model itself or its parameter dict\n        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast, HybridEngineBaseTokenizer],\n        model_hf_config: PretrainedConfig,\n        tokenizer_mode: str = \"auto\",\n        trust_remote_code: bool = False,\n        skip_tokenizer_init: bool = False,\n        tensor_parallel_size: int = 1,\n        dtype: str = \"auto\",\n        quantization: Optional[str] = None,\n        revision: Optional[str] = None,\n        tokenizer_revision: Optional[str] = None,\n        seed: int = 0,\n        gpu_memory_utilization: float = 0.9,\n        swap_space: int = 4,\n        cpu_offload_gb: float = 0,\n        enforce_eager: bool = False,\n        max_context_len_to_capture: Optional[int] = None,\n        max_seq_len_to_capture: int = 8192,\n        disable_custom_all_reduce: bool = False,\n        load_format=\"auto\",\n        **kwargs,\n    ) -> None:\n        if \"disable_log_stats\" not in kwargs:\n            kwargs[\"disable_log_stats\"] = True\n        removed_vision_keys = (\"image_token_id\", \"image_feature_size\", \"image_input_shape\", \"image_input_type\")\n        if any(k in kwargs for k in removed_vision_keys):\n            raise TypeError(\"There is no need to pass vision-related arguments anymore.\")\n        engine_args = EngineArgs(\n            model_hf_config=model_hf_config,\n            # tokenizer=tokenizer,\n            tokenizer_mode=tokenizer_mode,\n            skip_tokenizer_init=skip_tokenizer_init,\n            trust_remote_code=trust_remote_code,\n            tensor_parallel_size=tensor_parallel_size,\n            dtype=dtype,\n            quantization=quantization,\n            revision=revision,\n            tokenizer_revision=tokenizer_revision,\n            seed=seed,\n            gpu_memory_utilization=gpu_memory_utilization,\n            swap_space=swap_space,\n            cpu_offload_gb=cpu_offload_gb,\n            enforce_eager=enforce_eager,\n            max_context_len_to_capture=max_context_len_to_capture,\n            max_seq_len_to_capture=max_seq_len_to_capture,\n            disable_custom_all_reduce=disable_custom_all_reduce,\n            load_format=load_format,\n            **kwargs,\n        )\n        tokenizer_cls = (PreTrainedTokenizer, PreTrainedTokenizerFast, HybridEngineBaseTokenizer)\n        if not isinstance(tokenizer, tokenizer_cls):\n            raise ValueError(\n                f\"Unexpected tokenizer type: {type(tokenizer)}. Must be\"\n                \"one of the following: PreTrainedTokenizer, PreTrainedTokenizerFast, verl.workers.rollout.HybridEngineBaseTokenizer\"\n            )\n        self.llm_engine = LLMEngine.from_engine_args(model, tokenizer, engine_args)  # TODO: check usagecontext\n        self.request_counter = Counter()\n\n    def init_cache_engine(self):\n        self.llm_engine.init_cache_engine()\n\n    def free_cache_engine(self):\n        self.llm_engine.free_cache_engine()\n\n    def get_tokenizer(self) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:\n        return self.llm_engine.tokenizer\n\n    def set_tokenizer(\n        self,\n        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],\n    ) -> None:\n        self.llm_engine.tokenizer = tokenizer\n\n    def _run_engine(self, *, use_tqdm: bool) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:\n        outputs = super()._run_engine(use_tqdm=use_tqdm)\n        return self._post_process_outputs(outputs)\n\n    # # NOTE(shengguangming): add for verl\n    # # TODO(sgm): we can optimize it by making the dataloader yield List[int] without padding.\n    # def _pre_process_inputs(self, prompt_token_ids: torch.Tensor) -> List[int]:\n    #     # remove the left padding in the prompt token_id\n    #     pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n    #     non_pad_index = torch.nonzero(prompt_token_ids != pad_token_id, as_tuple=False)[0][0]\n    #     token_ids = prompt_token_ids[non_pad_index:].tolist()\n    #     return token_ids\n\n    # NOTE(shengguangming): add for verl\n    def _post_process_outputs(self, request_outputs: List[RequestOutput]) -> Tuple[torch.Tensor, torch.Tensor]:\n        output_token_ids = []\n        logprobs = []\n        for request_output in request_outputs:  # List[RequestOutput]\n            outputs = request_output.outputs\n            for output in outputs:  # List[CompletionOutput], usually len == 1\n                output_token_ids.append(torch.tensor(output.token_ids))\n                # TODO(shengguangming): can be optimzied by rewrite the Sampler._get_logprobs() logits\n                logprobs_dicts = output.logprobs\n                if logprobs_dicts is not None:\n                    logprob = []\n                    for logprobs_dict, id in zip(logprobs_dicts, output.token_ids):\n                        logprob.append(logprobs_dict[id].logprob)\n                    logprobs.append(torch.tensor(logprob))\n\n        pad_token_id = (self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None\n                        else self.llm_engine.tokenizer.eos_token_id)\n        output_token_ids = pad_sequence(output_token_ids, batch_first=True, padding_value=pad_token_id)\n        if len(logprobs) > 0:\n            logprobs = pad_sequence(logprobs, batch_first=True, padding_value=pad_token_id)\n        return output_token_ids, logprobs\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.llm_engine.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n    def offload_model_weights(self) -> None:\n        self.llm_engine.offload_model_weights()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/llm_engine_sp.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/llm_engine.py\n\nfrom functools import partial\nfrom typing import Callable, Dict, Optional, Type, Union\n\nimport torch\nimport torch.nn as nn\nfrom vllm.config import (\n    CacheConfig,\n    DecodingConfig,\n    DeviceConfig,\n    EngineConfig,\n    LoadConfig,\n    LoRAConfig,\n    ModelConfig,\n    ObservabilityConfig,\n    ParallelConfig,\n    PromptAdapterConfig,\n    SchedulerConfig,\n    SpeculativeConfig,\n)\nfrom vllm.core.scheduler import Scheduler\nfrom vllm.engine.arg_utils import EngineArgs\nfrom vllm.engine.llm_engine import LLMEngine, SchedulerContext, SchedulerOutputState, _load_generation_config_dict\nfrom vllm.engine.metrics_types import StatLoggerBase\nfrom vllm.engine.output_processor.interfaces import SequenceGroupOutputProcessor\nfrom vllm.engine.output_processor.stop_checker import StopChecker\nfrom vllm.executor.executor_base import ExecutorBase\nfrom vllm.inputs import INPUT_REGISTRY, InputRegistry\nfrom vllm.inputs.preprocess import InputPreprocessor\nfrom vllm.logger import init_logger\nfrom vllm.sequence import Sequence\nfrom vllm.tracing import init_tracer\nfrom vllm.transformers_utils.detokenizer import Detokenizer\nfrom vllm.transformers_utils.tokenizer import AnyTokenizer\nfrom vllm.usage.usage_lib import UsageContext, is_usage_stats_enabled, usage_message\nfrom vllm.utils import Counter, weak_bind\nfrom vllm.version import __version__ as VLLM_VERSION\n\nfrom .arg_utils import EngineArgs\nfrom .config import LoadConfig, ModelConfig\nfrom .tokenizer import TokenizerGroup\n\nlogger = init_logger(__name__)\n_LOCAL_LOGGING_INTERVAL_SEC = 5\n\n\nclass LLMEngine(LLMEngine):\n    \"\"\"An LLM engine that receives requests and generates texts.\n\n    This is the main class for the vLLM engine. It receives requests\n    from clients and generates texts from the LLM. It includes a tokenizer, a\n    language model (possibly distributed across multiple GPUs), and GPU memory\n    space allocated for intermediate states (aka KV cache). This class utilizes\n    iteration-level scheduling and efficient memory management to maximize the\n    serving throughput.\n\n    The :class:`~vllm.LLM` class wraps this class for offline batched inference\n    and the :class:`AsyncLLMEngine` class wraps this class for online serving.\n\n    The config arguments are derived from :class:`~vllm.EngineArgs`. (See\n    :ref:`engine_args`)\n\n    Args:\n        model_config: The configuration related to the LLM model.\n        cache_config: The configuration related to the KV cache memory\n            management.\n        parallel_config: The configuration related to distributed execution.\n        scheduler_config: The configuration related to the request scheduler.\n        device_config: The configuration related to the device.\n        lora_config (Optional): The configuration related to serving multi-LoRA.\n        speculative_config (Optional): The configuration related to speculative\n            decoding.\n        executor_class: The model executor class for managing distributed\n            execution.\n        prompt_adapter_config (Optional): The configuration related to serving\n            prompt adapters.\n        log_stats: Whether to log statistics.\n        usage_context: Specified entry point, used for usage info collection.\n    \"\"\"\n\n    def __init__(\n        self,\n        # NOTE(sgm): first two arguments are added for verl\n        model: Union[nn.Module, Dict],  # model itself or its parameter dict\n        tokenizer: nn.Module,\n        # NOTE(sgm): vllm original arguments\n        model_config: ModelConfig,\n        cache_config: CacheConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        speculative_config: Optional[SpeculativeConfig],\n        decoding_config: Optional[DecodingConfig],\n        observability_config: Optional[ObservabilityConfig],\n        prompt_adapter_config: Optional[PromptAdapterConfig],\n        executor_class: Type[ExecutorBase],\n        log_stats: bool,\n        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,\n        stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,\n        input_registry: InputRegistry = INPUT_REGISTRY,\n        use_cached_outputs: bool = False,\n    ) -> None:\n        logger.info(\n            \"Initializing an LLM engine (v%s) with config: \"\n            \"model=%r, speculative_config=%r, tokenizer=%r, \"\n            \"skip_tokenizer_init=%s, tokenizer_mode=%s, revision=%s, \"\n            \"override_neuron_config=%s, \"\n            \"rope_scaling=%r, rope_theta=%r, tokenizer_revision=%s, \"\n            \"trust_remote_code=%s, dtype=%s, max_seq_len=%d, \"\n            \"download_dir=%r, load_format=%s, tensor_parallel_size=%d, \"\n            \"pipeline_parallel_size=%d, \"\n            \"disable_custom_all_reduce=%s, quantization=%s, \"\n            \"enforce_eager=%s, kv_cache_dtype=%s, \"\n            \"quantization_param_path=%s, device_config=%s, \"\n            \"decoding_config=%r, observability_config=%r, \"\n            \"seed=%d, served_model_name=%s, use_v2_block_manager=%s, \"\n            \"num_scheduler_steps=%d, chunked_prefill_enabled=%s \"\n            \"multi_step_stream_outputs=%s, enable_prefix_caching=%s, \"\n            \"use_async_output_proc=%s, use_cached_outputs=%s, \"\n            \"mm_processor_kwargs=%s)\",\n            VLLM_VERSION,\n            model_config.model,\n            speculative_config,\n            model_config.tokenizer,\n            model_config.skip_tokenizer_init,\n            model_config.tokenizer_mode,\n            model_config.revision,\n            model_config.override_neuron_config,\n            model_config.rope_scaling,\n            model_config.rope_theta,\n            model_config.tokenizer_revision,\n            model_config.trust_remote_code,\n            model_config.dtype,\n            model_config.max_model_len,\n            load_config.download_dir,\n            load_config.load_format,\n            parallel_config.tensor_parallel_size,\n            parallel_config.pipeline_parallel_size,\n            parallel_config.disable_custom_all_reduce,\n            model_config.quantization,\n            model_config.enforce_eager,\n            cache_config.cache_dtype,\n            model_config.quantization_param_path,\n            device_config.device,\n            decoding_config,\n            observability_config,\n            model_config.seed,\n            model_config.served_model_name,\n            scheduler_config.use_v2_block_manager,\n            scheduler_config.num_scheduler_steps,\n            scheduler_config.chunked_prefill_enabled,\n            scheduler_config.multi_step_stream_outputs,\n            cache_config.enable_prefix_caching,\n            model_config.use_async_output_proc,\n            use_cached_outputs,\n            model_config.mm_processor_kwargs,\n        )\n        # TODO(woosuk): Print more configs in debug mode.\n        self.model_config = model_config\n        self.cache_config = cache_config\n        self.lora_config = lora_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.speculative_config = speculative_config\n        self.load_config = load_config\n        self.decoding_config = decoding_config or DecodingConfig()\n        self.prompt_adapter_config = prompt_adapter_config\n        self.observability_config = observability_config or ObservabilityConfig()\n        self.log_stats = log_stats\n        self.use_cached_outputs = use_cached_outputs\n\n        if not self.model_config.skip_tokenizer_init:\n            self.tokenizer = self._init_tokenizer(tokenizer)\n            self.detokenizer = Detokenizer(self.tokenizer)\n            tokenizer_group = self.get_tokenizer_group()\n        else:\n            self.tokenizer = None\n            self.detokenizer = None\n            tokenizer_group = None\n\n        # Ensure that the function doesn't contain a reference to self,\n        # to avoid engine GC issues\n        def get_tokenizer_for_seq(sequence: Sequence) -> AnyTokenizer:\n            assert tokenizer_group, \"tokenizer_group cannot be None, \" \"make sure skip_tokenizer_init is False\"\n            return tokenizer_group.get_lora_tokenizer(sequence.lora_request)\n\n        self.seq_counter = Counter()\n        self.generation_config_fields = _load_generation_config_dict(model_config)\n\n        self.input_preprocessor = InputPreprocessor(model_config, self.tokenizer)\n\n        self.input_registry = input_registry\n        self.input_processor = input_registry.create_input_processor(model_config)\n\n        self.model_executor = executor_class(\n            model=model,  # add for spmd_gpu_executor\n            model_config=model_config,\n            cache_config=cache_config,\n            parallel_config=parallel_config,\n            scheduler_config=scheduler_config,\n            device_config=device_config,\n            lora_config=lora_config,\n            speculative_config=speculative_config,\n            load_config=load_config,\n            prompt_adapter_config=prompt_adapter_config,\n            observability_config=self.observability_config,\n        )\n\n        if not self.model_config.embedding_mode:\n            self._initialize_kv_caches()\n\n        # If usage stat is enabled, collect relevant info.\n        if is_usage_stats_enabled():\n            from vllm.model_executor.model_loader import get_architecture_class_name\n\n            usage_message.report_usage(\n                get_architecture_class_name(model_config),\n                usage_context,\n                extra_kvs={\n                    # Common configuration\n                    \"dtype\": str(model_config.dtype),\n                    \"tensor_parallel_size\": parallel_config.tensor_parallel_size,\n                    \"block_size\": cache_config.block_size,\n                    \"gpu_memory_utilization\": cache_config.gpu_memory_utilization,\n                    # Quantization\n                    \"quantization\": model_config.quantization,\n                    \"kv_cache_dtype\": str(cache_config.cache_dtype),\n                    # Feature flags\n                    \"enable_lora\": bool(lora_config),\n                    \"enable_prompt_adapter\": bool(prompt_adapter_config),\n                    \"enable_prefix_caching\": cache_config.enable_prefix_caching,\n                    \"enforce_eager\": model_config.enforce_eager,\n                    \"disable_custom_all_reduce\": parallel_config.disable_custom_all_reduce,\n                },\n            )\n\n        if self.tokenizer:\n            # Ping the tokenizer to ensure liveness if it runs in a\n            # different process.\n            self.tokenizer.ping()\n\n        self.cached_scheduler_outputs = [\n            SchedulerOutputState() for _ in range(self.parallel_config.pipeline_parallel_size)\n        ]\n\n        self.scheduler_contexts = [\n            SchedulerContext(multi_step_stream_outputs=self.scheduler_config.multi_step_stream_outputs)\n            for _ in range(self.parallel_config.pipeline_parallel_size)\n        ]\n\n        if model_config.use_async_output_proc:\n            process_model_outputs = weak_bind(self._process_model_outputs)\n\n            self.async_callbacks = [\n                partial(process_model_outputs, ctx=self.scheduler_contexts[v_id])\n                for v_id in range(self.parallel_config.pipeline_parallel_size)\n            ]\n        else:\n            self.async_callbacks = []\n\n        # Currently used by AsyncLLMEngine to ensure quick append\n        # of request outputs to asyncio queues\n        self.process_request_outputs_callback: Optional[Callable] = None\n\n        # Create the scheduler.\n        # NOTE: the cache_config here have been updated with the numbers of\n        # GPU and CPU blocks, which are profiled in the distributed executor.\n        self.scheduler = [\n            Scheduler(\n                scheduler_config,\n                cache_config,\n                lora_config,\n                parallel_config.pipeline_parallel_size,\n                self.async_callbacks[v_id] if model_config.use_async_output_proc else None,\n            ) for v_id in range(parallel_config.pipeline_parallel_size)\n        ]\n\n        # Metric Logging.\n        if self.log_stats:\n            if stat_loggers is not None:\n                self.stat_loggers = stat_loggers\n            else:\n                # Lazy import for prometheus multiprocessing.\n                # We need to set PROMETHEUS_MULTIPROC_DIR environment variable\n                # before prometheus_client is imported.\n                # See https://prometheus.github.io/client_python/multiprocess/\n                from vllm.engine.metrics import LoggingStatLogger, PrometheusStatLogger\n\n                self.stat_loggers = {\n                    \"logging\":\n                        LoggingStatLogger(local_interval=_LOCAL_LOGGING_INTERVAL_SEC),\n                    \"prometheus\":\n                        PrometheusStatLogger(\n                            local_interval=_LOCAL_LOGGING_INTERVAL_SEC,\n                            labels=dict(model_name=model_config.served_model_name),\n                            max_model_len=self.model_config.max_model_len,\n                        ),\n                }\n                self.stat_loggers[\"prometheus\"].info(\"cache_config\", self.cache_config)\n\n        self.tracer = None\n        if self.observability_config.otlp_traces_endpoint:\n            self.tracer = init_tracer(\"vllm.llm_engine\", self.observability_config.otlp_traces_endpoint)\n\n        # Create sequence output processor, e.g. for beam search or\n        # speculative decoding.\n        self.output_processor = SequenceGroupOutputProcessor.create_output_processor(\n            self.scheduler_config,\n            self.detokenizer,\n            self.scheduler,\n            self.seq_counter,\n            get_tokenizer_for_seq,\n            stop_checker=StopChecker(\n                self.scheduler_config.max_model_len,\n                get_tokenizer_for_seq,\n            ),\n        )\n\n    # TODO(sgm): add for verl but we may not tokenizer in Rollout\n    def _init_tokenizer(self, tokenizer, **tokenizer_init_kwargs):\n        init_kwargs = dict(enable_lora=bool(self.lora_config),\n                           max_num_seqs=self.scheduler_config.max_num_seqs,\n                           max_input_length=None)\n        init_kwargs.update(tokenizer_init_kwargs)\n        return TokenizerGroup(tokenizer, **init_kwargs)\n\n    def init_cache_engine(self):\n        # TODO: check whether we should rebuild the CUDAGraph every iter when offload/load KVCache\n        # Re-capture CUDAGraph would be time-consuming\n        self.model_executor.init_cache_engine()\n\n    def free_cache_engine(self):\n        self.model_executor.free_cache_engine()\n\n    # NOTE(sgm): currently, we only support GPU executor\n    # The GPUExecutor remove the Ray dependency\n    @classmethod\n    def _get_executor_cls(cls, engine_config: EngineConfig) -> Type[ExecutorBase]:\n        distributed_executor_backend = engine_config.parallel_config.distributed_executor_backend\n        # Initialize the cluster and specify the executor class.]\n        assert (engine_config.device_config.device_type == \"cuda\"\n               ), \"Currently, the vllm in verl only support running on GPU\"\n\n        # print('Waiting for debugger'); import os,debugpy; debugpy.listen(('localhost', 5678 + int(os.getenv('RANK', '0')))); debugpy.wait_for_client()\n        if engine_config.parallel_config.world_size == 1:\n            engine_config.load_config.load_format = \"dummy_hf\"\n\n        from .spmd_gpu_executor import SPMDGPUExecutor\n\n        executor_class = SPMDGPUExecutor\n\n        return executor_class\n\n    @classmethod\n    def from_engine_args(\n        cls,\n        model,\n        tokenizer,\n        engine_args: EngineArgs,\n        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,\n        stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,\n    ) -> \"LLMEngine\":\n        \"\"\"Creates an LLM engine from the engine arguments.\"\"\"\n        # Create the engine configs.\n        engine_config = engine_args.create_engine_config()\n        executor_class = cls._get_executor_cls(engine_config)\n        # Initialize the cluster and specify the executor class.\n        assert (engine_config.device_config.device_type == \"cuda\"\n               ), \"Currently, the vllm in verl only support running on GPU\"\n\n        from .spmd_gpu_executor import SPMDGPUExecutor\n\n        executor_class = SPMDGPUExecutor\n\n        # Create the LLM engine.\n        engine = cls(\n            model,\n            tokenizer,\n            **engine_config.to_dict(),\n            executor_class=executor_class,\n            log_stats=not engine_args.disable_log_stats,\n            usage_context=usage_context,\n            stat_loggers=stat_loggers,\n        )\n        return engine\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.model_executor.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n    def offload_model_weights(self) -> None:\n        self.model_executor.offload_model_weights()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/megatron_weight_loaders.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader\n\nfrom typing import Dict\n\nimport torch\nimport torch.nn as nn\nfrom vllm.model_executor.layers.linear import *\nfrom vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead, VocabParallelEmbedding\nfrom vllm.model_executor.models import ModelRegistry\n\n\n# NOTE(shengguangming): replace the origin weight loader function in the class\ndef parallel_weight_loader(self, param: torch.Tensor, loaded_weight: torch.Tensor) -> None:\n    \"\"\"Parallel Linear weight loader.\"\"\"\n    assert (param.size() == loaded_weight.size(\n    )), \"the parameter size is not align with the loaded weight size, param size: {}, loaded_weight size: {}\".format(\n        param.size(), loaded_weight.size())\n    assert (param.data.dtype == loaded_weight.data.dtype\n           ), \"if we want to shared weights, the data type should also be the same\"\n\n    param.data = loaded_weight.data\n\n\ndef default_weight_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:\n    \"\"\"Default weight loader.\"\"\"\n    assert param.size() == loaded_weight.size()\n    assert (param.data.dtype == loaded_weight.data.dtype\n           ), \"if we want to shared weights, the data type should also be the same\"\n\n    param.data = loaded_weight.data\n\n\ndef gpt2_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_dict = dict(vllm_model.named_parameters(remove_duplicate=False))\n    for name, loaded_weight in actor_weights.items():\n        if \"lm_head.weight\" in name:\n            # GPT-2 ties the weights of the embedding layer and the final\n            # linear layer.\n            continue\n        if \".attn.bias\" in name or \".attn.masked_bias\" in name:\n            # Skip attention mask.\n            # NOTE: \"c_attn.bias\" should not be skipped.\n            continue\n        if not name.startswith(\"transformer.\"):\n            name = \"transformer.\" + name\n        param = params_dict[name]\n        # The HF's GPT-2 implementation uses Conv1D instead of Linear.\n        # Because of this, we need to transpose the weights.\n        # Note(zhuohan): the logic below might break quantized models.\n        for conv1d_weight_name in [\"c_attn\", \"c_proj\", \"c_fc\"]:\n            if conv1d_weight_name not in name:\n                continue\n            if not name.endswith(\".weight\"):\n                continue\n            # TODO: check megatron\n            loaded_weight = loaded_weight.t()\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef qwen2_megatron_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        if vllm_model.config.tie_word_embeddings and \"lm_head.weight\" in name:\n            continue\n        param = params_dict[name]\n        weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n        weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_te_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv.layer_norm_weight\", \"input_layernorm.weight\"),\n        (\"self_attention.linear_qkv.layer_norm_bias\", \"input_layernorm.bias\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", \"self_attn.o_proj\"),\n        (\"pre_mlp_layernorm\", \"post_attention_layernorm\"),\n        (\"mlp.linear_fc1.layer_norm_weight\", \"post_attention_layernorm.weight\"),\n        (\"mlp.linear_fc1.layer_norm_bias\", \"post_attention_layernorm.bias\"),\n        (\"mlp.linear_fc1\", \"mlp.gate_up_proj\"),\n        (\"mlp.linear_fc2\", \"mlp.down_proj\"),\n        (\"decoder.final_layernorm\", \"model.norm\"),\n        (\"output_layer\", \"lm_head\"),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith(\".bias\") and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", \"self_attn.o_proj\"),\n        (\n            \"input_layernorm\",\n            \"input_layernorm\",\n        ),\n        (\"pre_mlp_layernorm\", \"post_attention_layernorm\"),\n        (\"mlp.linear_fc1\", \"mlp.gate_up_proj\"),\n        (\"mlp.linear_fc2\", \"mlp.down_proj\"),\n        (\"decoder.final_layernorm\", \"model.norm\"),\n        (\"output_layer\", \"lm_head\"),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith(\".bias\") and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef _replace_name(megatron_name, name_mapping):\n    for m_name, v_name in name_mapping:\n        if m_name not in megatron_name:\n            continue\n        if \"layers\" in megatron_name:  # deal with decoder layers\n            megatron_name = megatron_name.replace(\"decoder\", \"model\")\n            megatron_name_list = megatron_name.split(\".\")\n            if \"layer_norm_weight\" in megatron_name_list or \"layer_norm_bias\" in megatron_name_list:\n                param_name_list = megatron_name_list[:3]\n                param_name_list.append(v_name)\n                param_name = \".\".join(param_name_list)\n            else:\n                param_name_list = megatron_name_list[:3]\n                weight_or_bias = megatron_name_list[-1]\n                param_name_list.append(v_name)\n                param_name_list.append(weight_or_bias)\n                param_name = \".\".join(param_name_list)\n            return param_name\n        else:\n            param_name = megatron_name.replace(m_name, v_name)\n            return param_name\n\n\ndef llama_megatron_core_te_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv.layer_norm_weight\", \"input_layernorm.weight\"),\n        (\"self_attention.linear_qkv.layer_norm_bias\", \"input_layernorm.bias\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", \"self_attn.o_proj\"),\n        (\"pre_mlp_layernorm\", \"post_attention_layernorm\"),\n        (\"mlp.linear_fc1.layer_norm_weight\", \"post_attention_layernorm.weight\"),\n        (\"mlp.linear_fc1.layer_norm_bias\", \"post_attention_layernorm.bias\"),\n        (\"mlp.linear_fc1\", \"mlp.gate_up_proj\"),\n        (\"mlp.linear_fc2\", \"mlp.down_proj\"),\n        (\"decoder.final_layernorm\", \"model.norm\"),\n        (\"output_layer\", \"lm_head\"),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith(\".bias\") and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef llama_megatron_core_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    params_mapping = [\n        # (megatron core gpt model name, vllm model name)\n        (\"embedding.word_embeddings\", \"model.embed_tokens\"),\n        (\"self_attention.linear_qkv\", \"self_attn.qkv_proj\"),\n        (\"self_attention.linear_proj\", \"self_attn.o_proj\"),\n        (\n            \"input_layernorm\",\n            \"input_layernorm\",\n        ),\n        (\"pre_mlp_layernorm\", \"post_attention_layernorm\"),\n        (\"mlp.linear_fc1\", \"mlp.gate_up_proj\"),\n        (\"mlp.linear_fc2\", \"mlp.down_proj\"),\n        (\"decoder.final_layernorm\", \"model.norm\"),\n        (\"output_layer\", \"lm_head\"),\n    ]\n    # NOTE(shengguangming): the megatron llama may have this prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        name = _replace_name(name, params_mapping)\n        if name.endswith(\".bias\") and name not in params_dict:\n            continue\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\ndef _replace_name(megatron_name, name_mapping):\n    for m_name, v_name in name_mapping:\n        if m_name not in megatron_name:\n            continue\n        if \"layers\" in megatron_name:  # deal with decoder layers\n            megatron_name = megatron_name.replace(\"decoder\", \"model\")\n            megatron_name_list = megatron_name.split(\".\")\n            if \"layer_norm_weight\" in megatron_name_list or \"layer_norm_bias\" in megatron_name_list:\n                param_name_list = megatron_name_list[:3]\n                param_name_list.append(v_name)\n                param_name = \".\".join(param_name_list)\n            else:\n                param_name_list = megatron_name_list[:3]\n                weight_or_bias = megatron_name_list[-1]\n                param_name_list.append(v_name)\n                param_name_list.append(weight_or_bias)\n                param_name = \".\".join(param_name_list)\n            return param_name\n        else:\n            param_name = megatron_name.replace(m_name, v_name)\n            return param_name\n\n\ndef mistral_megatron_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:\n    # TODO: need to implement a general way to deal with prefix\n    params_dict = dict(vllm_model.named_parameters())\n    for name, loaded_weight in actor_weights.items():\n        if \"rotary_emb.inv_freq\" in name:\n            continue\n        else:\n            param = params_dict[name]\n            weight_loader = getattr(param, \"weight_loader\", default_weight_loader)\n            weight_loader(param, loaded_weight)\n\n\n__LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__ = {\n    ColumnParallelLinear: parallel_weight_loader,\n    MergedColumnParallelLinear: parallel_weight_loader,\n    QKVParallelLinear: parallel_weight_loader,\n    RowParallelLinear: parallel_weight_loader,\n    VocabParallelEmbedding: parallel_weight_loader,\n    ParallelLMHead: parallel_weight_loader,\n    # \"ScaledActivation.weight_loader\": ScaledActivation, # TODO(shengguangming): latest commit in vllm fix awq for this function and add load_weights\n    # \"default_weight_loader\": default_weight_loader\n}\n\n# for layer_class, weight_loader in __LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__.items():\n#     # setattr(layer_class, 'megatron_weight_loader', weight_loader)\n#     layer_class.weight_loader = weight_loader\n\n__MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__ = {\n    \"GPT2LMHeadModel\": gpt2_weight_loader,\n    \"LlamaForCausalLM\": llama_megatron_weight_loader,  # use te backend for open-source megatron\n    \"LLaMAForCausalLM\": llama_megatron_weight_loader,\n    \"MistralForCausalLM\": mistral_megatron_weight_loader,\n    'Qwen2ForCausalLM': qwen2_megatron_weight_loader,\n}\n\n\n# the actor model is .state_dict()\n# Load megatron weights\ndef load_megatron_weights(actor_weights: Dict, vllm_model: nn.Module):\n    weight_loader = _get_model_weight_loader(vllm_model.__class__.__name__)\n    weight_loader(actor_weights, vllm_model)\n    # NOTE(sgm) to reduce peak memory usage, we offload vllm model to cpu\n    # after init, and we need this after sync model weights for in first iter.\n    vllm_model = vllm_model.cuda()\n\n\ndef _get_model_weight_loader(arch: str):\n    if arch in __MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__:\n        return __MODEL_MEGATRON_WEIGHT_LOADER_REGISTRY__[arch]\n    raise ValueError(f\"Model architectures {arch} are not supported for now. \"\n                     f\"Supported architectures: {ModelRegistry.get_supported_archs()}\")\n\n\ndef update_megatron_weight_loader():\n    for layer_class, weight_loader in __LAYER_WEIGHT_MEGATRON_LOADER_REGISTRY__.items():\n        layer_class.weight_loader = weight_loader\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/model_loader.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models\n\"\"\"Utilities for selecting and loading models.\"\"\"\nfrom typing import Dict, Optional, Union\n\nimport torch\nimport torch.nn as nn\nfrom transformers import PreTrainedModel\nfrom vllm.config import CacheConfig, DeviceConfig, LoadConfig, LoRAConfig, ModelConfig, ParallelConfig, SchedulerConfig\nfrom vllm.distributed.communication_op import tensor_model_parallel_all_gather\nfrom vllm.model_executor.model_loader import BaseModelLoader\nfrom vllm.model_executor.model_loader.loader import _initialize_model\nfrom vllm.model_executor.model_loader.utils import set_default_torch_dtype\n\nfrom .config import LoadConfig, LoadFormat, ModelConfig\nfrom .dtensor_weight_loaders import load_dtensor_weights, update_dtensor_weight_loader\nfrom .hf_weight_loader import update_hf_weight_loader\nfrom .megatron_weight_loaders import load_megatron_weights, update_megatron_weight_loader\n\n\ndef get_model(\n    actor_model: Union[PreTrainedModel, Dict],\n    model_config: ModelConfig,\n    load_config: LoadConfig,\n    device_config: DeviceConfig,\n    parallel_config: ParallelConfig,\n    scheduler_config: SchedulerConfig,\n    lora_config: Optional[LoRAConfig],\n    cache_config: CacheConfig = None,\n) -> nn.Module:\n    loader = get_model_loader(load_config)\n    if load_config.load_format.startswith(\"dummy\"):\n        return loader.load_model(\n            model_config=model_config,\n            device_config=device_config,\n            lora_config=lora_config,\n            parallel_config=parallel_config,\n            scheduler_config=scheduler_config,\n            cache_config=cache_config,\n        )\n    else:\n        return loader.load_model(\n            actor_model=actor_model,\n            model_config=model_config,\n            device_config=device_config,\n            lora_config=lora_config,\n            parallel_config=parallel_config,\n            scheduler_config=scheduler_config,\n            cache_config=cache_config,\n        )\n\n\ndef get_model_loader(load_config: LoadConfig) -> BaseModelLoader:\n    \"\"\"Get a model loader based on the load format.\"\"\"\n\n    if isinstance(load_config.load_format, type):\n        return load_config.load_format(load_config)\n\n    if load_config.load_format == LoadFormat.AUTO:\n        update_megatron_weight_loader()\n        return MegatronLoader(load_config)\n\n    # NOTE(sgm): change the weight_loader function in runtime\n    if load_config.load_format == LoadFormat.MEGATRON:\n        update_megatron_weight_loader()\n        return MegatronLoader(load_config)\n\n    if load_config.load_format == LoadFormat.HF:\n        update_hf_weight_loader()\n        return HFLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DTENSOR:\n        update_dtensor_weight_loader()\n        return DTensorLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_HF:\n        update_hf_weight_loader()\n        return DummyModelLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_MEGATRON:\n        update_megatron_weight_loader()\n        return DummyModelLoader(load_config)\n\n    if load_config.load_format == LoadFormat.DUMMY_DTENSOR:\n        update_dtensor_weight_loader()\n        return DummyModelLoader(load_config)\n\n    raise ValueError(\"load format not supported in verl: {}, only support {} and {}\".format(\n        load_config.load_format, LoadFormat.MEGATRON, LoadFormat.HF))\n\n\nclass DummyModelLoader(BaseModelLoader):\n    \"\"\"Model loader that will set model weights to random values.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def download_model(self, model_config: ModelConfig) -> None:\n        pass\n\n    def load_model(\n        self,\n        *,\n        model_config: ModelConfig,\n        device_config: DeviceConfig,\n        lora_config: Optional[LoRAConfig],\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        cache_config: CacheConfig,\n    ) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, cache_config, scheduler_config)\n            # NOTE(woosuk): For accurate performance evaluation, we assign\n            # random values to the weights.\n            # initialize_dummy_weights(model)\n        return model.eval()\n\n\nclass MegatronLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from partitioned megatron model.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def download_model(self, model_config: ModelConfig) -> None:\n        pass  # Nothing to download\n\n    def _get_weights_iterator(actor_model: Union[PreTrainedModel, Dict]):\n        # NOTE(shengguangming) Load the weights from the actor model\n        pass\n        # if isinstance(actor_model, nn.Module):\n        #     load_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)), vllm_model=model)\n        # else:\n        #     load_weights(actor_weights=actor_model, vllm_model=model)\n        # return actor_model\n\n    def load_model(\n        self,\n        actor_model: Union[PreTrainedModel, Dict],\n        model_config: ModelConfig,\n        device_config: DeviceConfig,\n        lora_config: Optional[LoRAConfig],\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        cache_config: CacheConfig,\n    ) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, cache_config, scheduler_config)\n\n            # TODO(sgm): This is a hack, we need to register the load_weight() func for each model in vllm\n            if isinstance(actor_model, nn.Module):\n                load_megatron_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)),\n                                      vllm_model=model)\n            else:\n                load_megatron_weights(actor_weights=actor_model, vllm_model=model)\n\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\nclass HFLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from model's full params.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def download_model(self, model_config: ModelConfig) -> None:\n        pass  # Nothing to download\n\n    def _get_weights_iterator(self, actor_model: Union[PreTrainedModel, Dict]):\n        if isinstance(actor_model, Dict):\n            return actor_model.items()\n        elif isinstance(actor_model, nn.Module):\n            return dict(actor_model.named_parameters()).items()\n        else:\n            raise ValueError(f\"actor model should be Dict or nn.Module, but get {type(actor_model)}\")\n\n    def load_model(\n        self,\n        actor_model: Union[PreTrainedModel, Dict],\n        model_config: ModelConfig,\n        device_config: DeviceConfig,\n        lora_config: Optional[LoRAConfig],\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        cache_config: CacheConfig,\n    ) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            # with torch.device(device_config.device):\n            # NOTE(sgm): init the model in cpu\n            model = _initialize_model(model_config, self.load_config, lora_config, cache_config, scheduler_config)\n            model.load_weights(self._get_weights_iterator(actor_model))\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\nclass DTensorLoader(BaseModelLoader):\n    \"\"\"Model loader that can load the model weights from partitioned megatron model.\"\"\"\n\n    def __init__(self, load_config: LoadConfig):\n        super().__init__(load_config)\n        if load_config.model_loader_extra_config:\n            raise ValueError(f\"Model loader extra config is not supported for \"\n                             f\"load format {load_config.load_format}\")\n\n    def download_model(self, model_config: ModelConfig) -> None:\n        pass  # Nothing to download\n\n    def _get_weights_iterator(actor_model: Union[PreTrainedModel, Dict]):\n        # NOTE(shengguangming) Load the weights from the actor model\n        pass\n        # if isinstance(actor_model, nn.Module):\n        #     load_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)), vllm_model=model)\n        # else:\n        #     load_weights(actor_weights=actor_model, vllm_model=model)\n        # return actor_model\n\n    def load_model(\n        self,\n        actor_model: Union[PreTrainedModel, Dict],\n        model_config: ModelConfig,\n        device_config: DeviceConfig,\n        lora_config: Optional[LoRAConfig],\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        cache_config: CacheConfig,\n    ) -> nn.Module:\n        with set_default_torch_dtype(model_config.dtype):\n            with torch.device(device_config.device):\n                model = _initialize_model(model_config, self.load_config, lora_config, cache_config, scheduler_config)\n\n            # TODO(sgm): This is a hack, we need to register the load_weight() func for each model in vllm\n            if isinstance(actor_model, nn.Module):\n                load_dtensor_weights(actor_weights=dict(actor_model.named_parameters(remove_duplicate=False)),\n                                     vllm_model=model)\n            else:\n                load_dtensor_weights(actor_weights=actor_model, vllm_model=model)\n\n            for _, module in model.named_modules():\n                quant_method = getattr(module, \"quant_method\", None)\n                if quant_method is not None:\n                    quant_method.process_weights_after_loading(module)\n                # FIXME: Remove this after Mixtral is updated\n                # to use quant_method.\n                if hasattr(module, \"process_weights_after_loading\"):\n                    module.process_weights_after_loading()\n        # NOTE(sgm) Some weights are point to gpu, but still need this.\n        model = model.cuda()  # NOTE (zhangchi.usc1992) We need this for vllm to profile memory usage\n        return model.eval()\n\n\n# FIXME(sgm): hack the _get_logits function in vllm v0.4.2\n# as they use ray, the _get_logits result will only need to return to the driver node,\n# therefore gather is enough. However, we use SPMD instead of a central scheduler,\n# all_gather is required (aligned with v0.2.6)\ndef _get_logits(self, hidden_states: torch.Tensor, embedding: torch.Tensor,\n                embedding_bias: Optional[torch.Tensor]) -> torch.Tensor:\n    # Get the logits for the next tokens.\n    logits = torch.matmul(hidden_states, embedding.t())\n    if embedding_bias is not None:\n        logits += embedding_bias\n    logits = tensor_model_parallel_all_gather(logits)\n    # Remove paddings in vocab (if any).\n    if logits is not None:\n        logits = logits[:, :self.org_vocab_size]\n    return logits\n\n\nfrom vllm.model_executor.layers.logits_processor import LogitsProcessor\n\n\ndef logitsprocessor_init(\n    self,\n    vocab_size: int,\n    org_vocab_size: Optional[int] = None,\n    scale: float = 1.0,\n    logits_as_input: bool = False,\n    soft_cap: Optional[float] = None,\n) -> None:\n    \"\"\"\n    Args:\n        scale: A scaling factor to apply to the logits.\n    \"\"\"\n    super(LogitsProcessor, self).__init__()\n    self.scale = scale\n    self.vocab_size = vocab_size\n    # Whether the input is logits (default is hidden states).\n    self.logits_as_input = logits_as_input\n    # original vocabulary size (without LoRA).\n    self.org_vocab_size = org_vocab_size or vocab_size\n    # Soft cap the logits. Used in Gemma 2.\n    self.soft_cap = soft_cap\n    # Whether to use gather or all-gather to gather the logits.\n    self.use_gather = False\n\n\nLogitsProcessor.__init__ = logitsprocessor_init  # use all_gather\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/model_runner.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/model_runner.py\n\nimport warnings\nfrom enum import IntEnum\nfrom typing import Dict, Optional, Union\n\nimport torch\nimport torch.nn as nn\nimport vllm.envs as envs\nfrom vllm.compilation.levels import CompilationLevel\nfrom vllm.config import (\n    CacheConfig,\n    DeviceConfig,\n    LoadConfig,\n    LoRAConfig,\n    ModelConfig,\n    ObservabilityConfig,\n    ParallelConfig,\n    PromptAdapterConfig,\n    SchedulerConfig,\n)\nfrom vllm.inputs import INPUT_REGISTRY, InputRegistry\nfrom vllm.logger import init_logger\nfrom vllm.lora.worker_manager import LRUCacheWorkerLoRAManager\nfrom vllm.model_executor.models.interfaces import supports_lora\nfrom vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry\nfrom vllm.prompt_adapter.worker_manager import LRUCacheWorkerPromptAdapterManager\nfrom vllm.utils import DeviceMemoryProfiler, is_hip, supports_dynamo\nfrom vllm.worker.model_runner import ModelRunner\n\nfrom .config import LoadConfig, ModelConfig\nfrom .model_loader import get_model\n\nlogger = init_logger(__name__)\n\n\n# How batches are constructed.\nclass BatchType(IntEnum):\n    # Every batch is prefill.\n    PREFILL = 0\n    # Every batch is decode.\n    DECODE = 1\n    # Batch is a mixture of prefill and decode.\n    MIXED = 2\n\n\nclass ModelRunner(ModelRunner):\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict],  # [verl] model itself or its parameter dict\n        model_config: ModelConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        cache_config: CacheConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        kv_cache_dtype: Optional[str] = \"auto\",\n        is_driver_worker: bool = False,\n        prompt_adapter_config: Optional[PromptAdapterConfig] = None,\n        return_hidden_states: bool = False,\n        observability_config: Optional[ObservabilityConfig] = None,\n        input_registry: InputRegistry = INPUT_REGISTRY,\n        mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,\n    ):\n\n        super().__init__(\n            model_config,\n            parallel_config,\n            scheduler_config,\n            device_config,\n            cache_config,\n            load_config,\n            lora_config,\n            kv_cache_dtype,\n            is_driver_worker=True,  # a hack\n            prompt_adapter_config=prompt_adapter_config,\n            return_hidden_states=return_hidden_states,\n            observability_config=observability_config,\n            input_registry=input_registry,\n            mm_registry=mm_registry,\n        )\n\n        # NOTE(sgm): add for verl\n        self.model = model  # this will be replaced by get_model()\n\n    def load_model(self) -> None:\n        logger.info(\"Starting to load model %s...\", self.model_config.model)\n        with DeviceMemoryProfiler() as m:\n            self.model = get_model(\n                self.model,\n                model_config=self.model_config,\n                device_config=self.device_config,\n                load_config=self.load_config,\n                lora_config=self.lora_config,\n                parallel_config=self.parallel_config,\n                scheduler_config=self.scheduler_config,\n                cache_config=self.cache_config,\n            )\n\n        self.model_memory_usage = m.consumed_memory\n        logger.info(\"Loading model weights took %.4f GB\", self.model_memory_usage / float(2**30))\n\n        if self.lora_config:\n            assert supports_lora(self.model), f\"{self.model.__class__.__name__} does not support LoRA yet.\"\n\n            if supports_multimodal(self.model):\n                logger.warning(\"Regarding multimodal models, vLLM currently \"\n                               \"only supports adding LoRA to language model.\")\n            # It's necessary to distinguish between the max_position_embeddings\n            # of VLMs and LLMs.\n            if hasattr(self.model.config, \"max_position_embeddings\"):\n                max_pos_embeddings = self.model.config.max_position_embeddings\n            else:\n                max_pos_embeddings = self.model.config.text_config.max_position_embeddings\n\n            self.lora_manager = LRUCacheWorkerLoRAManager(\n                self.scheduler_config.max_num_seqs,\n                self.scheduler_config.max_num_batched_tokens,\n                self.vocab_size,\n                self.lora_config,\n                self.device,\n                self.model.embedding_modules,\n                self.model.embedding_padding_modules,\n                max_position_embeddings=max_pos_embeddings,\n            )\n            self.model = self.lora_manager.create_lora_manager(self.model)\n\n        if self.prompt_adapter_config:\n            self.prompt_adapter_manager = LRUCacheWorkerPromptAdapterManager(\n                self.scheduler_config.max_num_seqs,\n                self.scheduler_config.max_num_batched_tokens,\n                self.device,\n                self.prompt_adapter_config,\n            )\n            self.model = self.prompt_adapter_manager.create_prompt_adapter_manager(self.model)\n\n        if self.kv_cache_dtype == \"fp8\" and is_hip():\n            # Currently only ROCm accepts kv-cache scaling factors\n            # via quantization_param_path and this will be deprecated\n            # in the future.\n            if self.model_config.quantization_param_path is not None:\n                if callable(getattr(self.model, \"load_kv_cache_scales\", None)):\n                    warnings.warn(\n                        \"Loading kv cache scaling factor from JSON is \"\n                        \"deprecated and will be removed. Please include \"\n                        \"kv cache scaling factors in the model checkpoint.\",\n                        FutureWarning,\n                        stacklevel=2,\n                    )\n                    self.model.load_kv_cache_scales(self.model_config.quantization_param_path)\n                    logger.info(\"Loaded KV cache scaling factors from %s\", self.model_config.quantization_param_path)\n                else:\n                    raise RuntimeError(\n                        \"Using FP8 KV cache and scaling factors provided but \"\n                        \"model %s does not support loading scaling factors.\",\n                        self.model.__class__,\n                    )\n            else:\n                logger.warning(\"Using FP8 KV cache but no scaling factors \"\n                               \"provided. Defaulting to scaling factors of 1.0. \"\n                               \"This may lead to less accurate results!\")\n\n        if envs.VLLM_TORCH_COMPILE_LEVEL == CompilationLevel.DYNAMO_AS_IS and supports_dynamo():\n            from vllm.plugins import get_torch_compile_backend\n\n            backend = get_torch_compile_backend() or \"eager\"\n            self.model = torch.compile(self.model, fullgraph=envs.VLLM_TEST_DYNAMO_FULLGRAPH_CAPTURE, backend=backend)\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/parallel_state.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Adapted from\n# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py\n# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.\n\"\"\"Model and data parallel groups.\"\"\"\nimport os\nfrom typing import Optional\n\nimport torch\nimport torch.distributed\nimport vllm.distributed.parallel_state as ps\nfrom vllm.distributed.parallel_state import (\n    get_pp_group,\n    get_world_group,\n    init_distributed_environment,\n    init_model_parallel_group,\n)\nfrom vllm.logger import init_logger\n\nlogger = init_logger(__name__)\n\"\"\"\nThis version is strongly tied with Megatron to implement HybridEngine and weight sharing between vllm and Megatron.\n- We assume the Megatron tp+dp+pp world is already established before calling this function.\n\n\"\"\"\n\n# Device mesh for using DTensor\n_DEVICE_MESH = None\n\n# Tensor model parallel group that the current rank belongs to.\n_TP = None\n# Pipeline model parallel group that the current rank belongs to.\n_PP = None\n\n\n# This method is for initializing the ParallelGroup when using HybridEngine\ndef initialize_parallel_state(\n    distributed_init_method: str = \"env://\",\n    backend: str = \"nccl\",\n    tensor_model_parallel_size: int = 1,\n    num_tp_per_train_tp: int = 1,\n    pipeline_model_parallel_size: int = 1,\n):\n    # torch.distributed.all_reduce does not free the input tensor until\n    # the synchronization point. This causes the memory usage to grow\n    # as the number of all_reduce calls increases. This env var disables\n    # this behavior.\n    # Related issue:\n    # https://discuss.pytorch.org/t/cuda-allocation-lifetime-for-inputs-to-distributed-all-reduce/191573\n    os.environ[\"TORCH_NCCL_AVOID_RECORD_STREAMS\"] = \"1\"\n\n    # NOTE(sgm): Modify for verl, Env vars will be set by TORCHRUN.\n    rank = int(os.getenv(\"RANK\", \"-1\"))\n    local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n\n    # Use the world_size set by TORCHRUN\n    world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n    assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n    init_distributed_environment(world_size, rank, distributed_init_method, local_rank, backend)\n    if torch.distributed.get_world_size() > 1:\n        # NOTE: build a sepearate inference group with infer tp & micro dp\n        initialize_model_parallel_for_vllm(\n            tensor_model_parallel_size=tensor_model_parallel_size,\n            num_tensor_model_parallel_groups_per_train_tp=num_tp_per_train_tp,\n        )\n    else:\n        initialize_model_parallel(tensor_model_parallel_size, pipeline_model_parallel_size, backend)\n\n\ndef ensure_model_parallel_initialized(\n    tensor_model_parallel_size: int,\n    pipeline_model_parallel_size: int = 1,\n    backend: Optional[str] = None,\n) -> None:\n    \"\"\"Helper to initialize model parallel groups if they are not initialized,\n    or ensure tensor-parallel and pipeline-parallel sizes are equal to expected\n    values if the model parallel groups are initialized.\n    \"\"\"\n    # get the backend of _DEVICE_WORLD_GROUP\n    backend = backend or torch.distributed.get_backend(get_world_group().device_group)\n    if not model_parallel_is_initialized():\n        initialize_model_parallel(tensor_model_parallel_size, pipeline_model_parallel_size, backend)\n        return\n\n    assert get_tensor_model_parallel_world_size() == tensor_model_parallel_size, (\n        \"tensor parallel group already initialized, but of unexpected size: \"\n        f\"{get_tensor_model_parallel_world_size()=} vs. \"\n        f\"{tensor_model_parallel_size=}\")\n    pp_world_size = get_pp_group().world_size\n    assert pp_world_size == pipeline_model_parallel_size, (\n        \"pipeline parallel group already initialized, but of unexpected size: \"\n        f\"{pp_world_size=} vs. \"\n        f\"{pipeline_model_parallel_size=}\")\n\n\n# TODO(sgm): deviate from the v0.5.4, not pp now\ndef model_parallel_is_initialized():\n    \"\"\"Check if tensor and pipeline parallel groups are initialized.\"\"\"\n    return ps._TP is not None\n    # and _PIPELINE_MODEL_PARALLEL_GROUP is not None)\n\n\ndef initialize_model_parallel_for_vllm(\n    tensor_model_parallel_size: int,\n    num_tensor_model_parallel_groups_per_train_tp: int = 1,\n    pipeline_model_parallel_size: int = 1,\n) -> None:\n    pass\n\n    # Get world size and rank. Ensure some consistencies.\n    assert torch.distributed.is_initialized()\n\n    assert isinstance(tensor_model_parallel_size, int)\n\n    # assert num_tensor_model_parallel_groups_per_train_tp == 1 and not different_tp_group\n    # assert num_tensor_model_parallel_groups_per_train_tp > 1 and different_tp_group\n\n    # Build the tensor model-parallel groups.\n    assert ps._TP is None, \"tensor model parallel group is already initialized\"\n\n    global _TP\n\n    world_size: int = torch.distributed.get_world_size()\n\n    rank = torch.distributed.get_rank()\n\n    backend = torch.distributed.get_backend()\n\n    num_tensor_model_parallel_groups = world_size // tensor_model_parallel_size\n\n    if num_tensor_model_parallel_groups_per_train_tp == 1:\n        # if tensor_model_parallel_size == train_tensor_parallel_size:\n        # using the same tp group as Megatron/vllm\n        assert _TP is None, \"tensor model parallel group is already initialized\"\n        group_ranks = []\n        for i in range(num_tensor_model_parallel_groups):\n            ranks = range(i * tensor_model_parallel_size, (i + 1) * tensor_model_parallel_size)\n            group_ranks.append(ranks)\n        _TP = init_model_parallel_group(\n            group_ranks=group_ranks,\n            local_rank=get_world_group().local_rank,\n            backend=backend,\n            use_custom_allreduce=False,  # TODO: check why True is not work in Ray trainer\n            use_message_queue_broadcaster=True,\n        )\n        ps._TP = _TP\n        # _MICRO_DATA_PARALLEL_GROUP is move to hybrid engine\n    else:\n        # initialize a micro_dp group and a tp group\n        # assume training tp=4, infer tp=2, then, weight is partitioned as\n        # [1], [2], [3], [4] for training and [1,2], [1,2], [3,4], [3,4] for inference\n\n        # Build the inference tp groups\n        # train_tp = train_tensor_parallel_size\n        train_tp = num_tensor_model_parallel_groups_per_train_tp * tensor_model_parallel_size\n        # num_tensor_model_parallel_groups_per_train_tp = train_tp // tensor_model_parallel_size\n        assert _TP is None, \"tensor model parallel group is already initialized\"\n        group_ranks = []\n        for i in range(num_tensor_model_parallel_groups // num_tensor_model_parallel_groups_per_train_tp):\n            start = train_tp * i\n            end = train_tp * (i + 1)\n            for j in range(num_tensor_model_parallel_groups_per_train_tp):\n                ranks = list(range(start, end, num_tensor_model_parallel_groups_per_train_tp))\n                for i in range(len(ranks)):\n                    ranks[i] += j\n                group_ranks.append(ranks)\n        _TP = init_model_parallel_group(\n            group_ranks=group_ranks,\n            local_rank=get_world_group().local_rank,\n            backend=backend,\n            use_custom_allreduce=False,  # TODO: check why True is not work in Ray trainer\n            use_message_queue_broadcaster=True,\n        )\n        ps._TP = _TP\n\n    # Build the pipeline model-parallel groups.\n    # global _PIPELINE_MODEL_PARALLEL_GROUP\n    # global _PIPELINE_GLOBAL_RANKS\n    # assert ps._PIPELINE_MODEL_PARALLEL_GROUP is None, (\"pipeline model parallel group is already initialized\")\n\n    # ps._PIPELINE_MODEL_PARALLEL_GROUP = mpu.get_pipeline_model_parallel_group()\n    # ps._PIPELINE_GLOBAL_RANKS = mpu.get_pipeline_model_parallel_ranks()\n\n    # TODO: init using device mesh (not support hybrid engine now)\n    # Build the pipeline model-parallel groups.\n    num_pipeline_model_parallel_groups: int = world_size // pipeline_model_parallel_size\n    global _PP\n    assert _PP is None, \"pipeline model parallel group is already initialized\"\n    group_ranks = []\n    for i in range(num_pipeline_model_parallel_groups):\n        ranks = list(range(i, world_size, num_pipeline_model_parallel_groups))\n        group_ranks.append(ranks)\n    # pipeline parallel does not need custom allreduce\n    _PP = init_model_parallel_group(group_ranks, get_world_group().local_rank, backend, use_custom_allreduce=False)\n    ps._PP = _PP  # for verl\n\n\ndef initialize_model_parallel(\n    tensor_model_parallel_size: int = 1,\n    pipeline_model_parallel_size: int = 1,\n    backend: Optional[str] = None,\n) -> None:\n    \"\"\"\n    NOTE: This method is a hack from the open-sourced version without\n    asertion of world_size = tp * pp\n\n    Initialize model parallel groups.\n\n    Arguments:\n        tensor_model_parallel_size: number of GPUs used for tensor model\n            parallelism.\n        pipeline_model_parallel_size: number of GPUs used for pipeline model\n            parallelism.\n\n    Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we\n    use 2 GPUs to parallelize the model tensor, and 4 GPUs to parallelize\n    the model pipeline. The present function will\n    create 4 tensor model-parallel groups and 2 pipeline model-parallel groups:\n        4 tensor model-parallel groups:\n            [g0, g1], [g2, g3], [g4, g5], [g6, g7]\n        2 pipeline model-parallel groups:\n            [g0, g2, g4, g6], [g1, g3, g5, g7]\n    Note that for efficiency, the caller should make sure adjacent ranks\n    are on the same DGX box. For example if we are using 2 DGX-1 boxes\n    with a total of 16 GPUs, rank 0 to 7 belong to the first box and\n    ranks 8 to 15 belong to the second box.\n    \"\"\"\n    # Get world size and rank. Ensure some consistencies.\n    assert torch.distributed.is_initialized()\n    world_size: int = torch.distributed.get_world_size()\n    backend = backend or torch.distributed.get_backend(ps.get_world_group().device_group)\n\n    # NOTE(sgm) we don't assert world_size == tp * pp\n    # DP is not managed by vllm but by the VeRL WorkerGroup\n    # if (world_size !=\n    #         tensor_model_parallel_size * pipeline_model_parallel_size):\n    #     raise RuntimeError(\n    #         f\"world_size ({world_size}) is not equal to \"\n    #         f\"tensor_model_parallel_size ({tensor_model_parallel_size}) x \"\n    #         f\"pipeline_model_parallel_size ({pipeline_model_parallel_size})\")\n\n    num_tensor_model_parallel_groups: int = world_size // tensor_model_parallel_size\n    rank = torch.distributed.get_rank()\n    global _TP\n    assert _TP is None, \"tensor model parallel group is already initialized\"\n    group_ranks = []\n    for i in range(num_tensor_model_parallel_groups):\n        ranks = list(range(i * tensor_model_parallel_size, (i + 1) * tensor_model_parallel_size))\n        group_ranks.append(ranks)\n\n    # message queue broadcaster is only used in tensor model parallel group\n    _TP = init_model_parallel_group(\n        group_ranks,\n        get_world_group().local_rank,\n        backend,\n        use_custom_allreduce=False,  # TODO: check why True is not work in Ray trainer\n        use_message_queue_broadcaster=True,\n    )\n    ps._TP = _TP\n\n    # TODO: init using device mesh (not support hybrid engine now)\n    # Build the pipeline model-parallel groups.\n    num_pipeline_model_parallel_groups: int = world_size // pipeline_model_parallel_size\n    global _PP\n    assert _PP is None, \"pipeline model parallel group is already initialized\"\n    group_ranks = []\n    for i in range(num_pipeline_model_parallel_groups):\n        ranks = list(range(i, world_size, num_pipeline_model_parallel_groups))\n        group_ranks.append(ranks)\n    # pipeline parallel does not need custom allreduce\n    _PP = init_model_parallel_group(group_ranks, get_world_group().local_rank, backend, use_custom_allreduce=False)\n    ps._PP = _PP  # for verl\n\n\n\"\"\"\nDevice mesh utilities\n\"\"\"\n\n\ndef get_device_mesh():\n    assert _DEVICE_MESH is not None, \"device mesh is not initialized\"\n    return _DEVICE_MESH\n\n\n\"\"\"\nTensor model parallel utilities\n\"\"\"\n\n\ndef get_tensor_model_parallel_group():\n    \"\"\"Get the tensor model parallel group the caller rank belongs to.\"\"\"\n    assert _TP is not None, \"tensor model parallel group is not initialized\"\n    return _TP.device_group\n\n\ndef get_tensor_model_parallel_world_size():\n    \"\"\"Return world size for the tensor model parallel group.\"\"\"\n    return torch.distributed.get_world_size(group=get_tensor_model_parallel_group())\n\n\ndef get_tensor_model_parallel_rank():\n    \"\"\"Return my rank for the tensor model parallel group.\"\"\"\n    return torch.distributed.get_rank(group=get_tensor_model_parallel_group())\n\n\ndef get_tensor_model_parallel_src_rank():\n    \"\"\"Calculate the global rank corresponding to the first local rank\n    in the tensor model parallel group.\"\"\"\n    global_rank = torch.distributed.get_rank()\n    local_world_size = get_tensor_model_parallel_world_size()\n    return (global_rank // local_world_size) * local_world_size\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/spmd_gpu_executor.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/executor/gpu_executor.py\n\nimport os\nimport socket\nfrom typing import Dict, List, Optional, Set, Tuple\n\nimport torch\nfrom vllm.config import (\n    CacheConfig,\n    DeviceConfig,\n    LoRAConfig,\n    ObservabilityConfig,\n    ParallelConfig,\n    PromptAdapterConfig,\n    SchedulerConfig,\n    SpeculativeConfig,\n)\nfrom vllm.executor.executor_base import ExecutorAsyncBase, ExecutorBase\nfrom vllm.logger import init_logger\nfrom vllm.lora.request import LoRARequest\nfrom vllm.model_executor.layers.sampler import SamplerOutput\nfrom vllm.sequence import ExecuteModelRequest\n\nfrom .config import LoadConfig, ModelConfig\n\nlogger = init_logger(__name__)\n\n\nclass SPMDGPUExecutor(ExecutorBase):\n    \"\"\"SPMD-based multi-GPU executor implementations.\"\"\"\n\n    def __init__(\n        self,\n        model,  # pytorch model itself or its parameter dict\n        model_config: ModelConfig,\n        cache_config: CacheConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        load_config: LoadConfig,\n        lora_config: Optional[LoRAConfig],\n        speculative_config: Optional[SpeculativeConfig],\n        prompt_adapter_config: Optional[PromptAdapterConfig],\n        observability_config: Optional[ObservabilityConfig],\n    ) -> None:\n        self.model_config = model_config\n        self.cache_config = cache_config\n        self.lora_config = lora_config\n        self.load_config = load_config\n        self.parallel_config = parallel_config\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.speculative_config = speculative_config\n        self.prompt_adapter_config = prompt_adapter_config\n        self.observability_config = observability_config\n\n        distributed_init_method = initialize_cluster(parallel_config)\n        self._init_executor(model, distributed_init_method)\n\n    # TODO(sgm): verl not support speculative decode now\n    def _init_executor(self, model, distributed_init_method) -> None:\n        assert not self.speculative_config, \"Speculative decoding not yet supported for multi-GPU backend.\"\n\n        # Create the parallel worker for each GPU.\n        self._init_workers_sp(model, distributed_init_method)\n\n    def _init_workers_sp(self, model, distributed_init_method: str):\n        # Lazy import the Worker to avoid importing torch.cuda/xformers\n        # before CUDA_VISIBLE_DEVICES is set in the Worker\n        from .worker import Worker  # pylint: disable=import-outside-toplevel\n\n        rank = int(os.getenv(\"RANK\"))\n        local_rank = int(os.getenv(\"LOCAL_RANK\"))\n        print(f\"local rank {local_rank}\")\n\n        # see https://github.com/NVIDIA/nccl/issues/1234\n        os.environ[\"NCCL_CUMEM_ENABLE\"] = \"0\"\n\n        self.worker = Worker(\n            model,\n            self.model_config,\n            self.parallel_config,\n            self.scheduler_config,\n            self.device_config,\n            self.cache_config,\n            self.load_config,\n            local_rank,\n            rank,\n            distributed_init_method,\n            lora_config=self.lora_config,\n            speculative_config=None,\n            prompt_adapter_config=self.speculative_config,\n            is_driver_worker=True,\n            model_runner_cls=None,  # use the default one\n        )\n\n        # NOTE(shengguangming): torch.distributed.init_process_group will be called inside the init_model()\n        self.worker.init_device()\n        self.worker.load_model()\n\n    def determine_num_available_blocks(self) -> Tuple[int, int]:\n        \"\"\"Determine the number of available KV blocks.\n\n        This invokes `determine_num_available_blocks` on each worker and takes\n        the min of the results, guaranteeing that the selected cache sizes are\n        compatible with all workers.\n\n        Returns:\n            - tuple[num_gpu_blocks, num_cpu_blocks]\n        \"\"\"\n        # Get the maximum number of blocks that can be allocated on GPU and CPU.\n        num_blocks = self.worker.determine_num_available_blocks()\n\n        # NOTE(shengguangming): Now we don't use a shared centralized controler but each process will\n        # have its own scheduler\n        num_gpu_blocks = num_blocks[0]\n        num_cpu_blocks = num_blocks[1]\n\n        return num_gpu_blocks, num_cpu_blocks\n\n    def initialize_cache(self, num_gpu_blocks: int, num_cpu_blocks: int) -> None:\n        \"\"\"Initialize the KV cache in all workers.\"\"\"\n\n        # NOTE: We log here to avoid multiple logs when number of workers is\n        # greater than one. We could log in the engine, but not all executors\n        # have GPUs.\n        logger.info(\"# GPU blocks: %d, # CPU blocks: %d\", num_gpu_blocks, num_cpu_blocks)\n\n        self.cache_config.num_gpu_blocks = num_gpu_blocks\n        self.cache_config.num_cpu_blocks = num_cpu_blocks\n\n        if torch.distributed.get_rank() == 0:\n            print(\n                f\"before init cache memory allocated: {torch.cuda.memory_allocated() / 1e9}GB, reserved: {torch.cuda.memory_reserved() / 1e9}GB\"\n            )\n        self.worker.initialize_cache(num_gpu_blocks=num_gpu_blocks, num_cpu_blocks=num_cpu_blocks)\n        if torch.distributed.get_rank() == 0:\n            print(\n                f\"after init cache memory allocated: {torch.cuda.memory_allocated() / 1e9}GB, reserved: {torch.cuda.memory_reserved() / 1e9}GB\"\n            )\n\n    # NOTE(sgm): This will not profile & capture the model(CUDAGraph) when rebuilding KVCache\n    def init_cache_engine(self) -> None:\n        self.worker._init_cache_engine()\n\n    def free_cache_engine(self) -> None:\n        self.worker.free_cache_engine()\n\n    def execute_model(self, execute_model_req) -> List[SamplerOutput]:\n        all_outputs = self.worker.execute_model(execute_model_req=execute_model_req)\n\n        # NOTE(sgm):\n        # Each GPU in vllm under verl has its own spmd_gpu_executor, therefore all GPUs should return the outputs\n        # In vllm with ray, only the driver worker returns the sampling results.\n        return all_outputs\n\n    def add_lora(self, lora_request: LoRARequest) -> bool:\n        assert lora_request.lora_int_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.add_lora(lora_request=lora_request)\n\n    def remove_lora(self, lora_id: int) -> bool:\n        assert lora_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.remove_lora(lora_id=lora_id)\n\n    def list_loras(self) -> Set[int]:\n        return self.worker.list_loras()\n\n    def check_health(self) -> None:\n        # SPMDExecutor will always be healthy as long as\n        # it's running.\n        return\n\n    # NOTE(sgm) add for verl to pass the abstract class test, not used\n    from vllm.prompt_adapter.request import PromptAdapterRequest\n\n    def add_prompt_adapter(self, prompt_adapter_request: PromptAdapterRequest) -> bool:\n        assert prompt_adapter_request.prompt_adapter_id > 0, \"prompt_adapter_id must be greater than 0.\"\n        return self.worker.add_prompt_adapter(prompt_adapter_request)\n\n    def list_prompt_adapters(self) -> Set[int]:\n        return self.worker.list_prompt_adapters()\n\n    def pin_lora(self, lora_id: int) -> bool:\n        assert lora_id > 0, \"lora_id must be greater than 0.\"\n        return self.worker.pin_lora(lora_id)\n\n    def pin_prompt_adapter(self, prompt_adapter_id: int) -> bool:\n        assert prompt_adapter_id > 0, \"prompt_adapter_id must be greater than 0.\"\n        return self.worker.pin_prompt_adapter(prompt_adapter_id)\n\n    def remove_prompt_adapter(self, prompt_adapter_id: int) -> bool:\n        assert prompt_adapter_id > 0, \"prompt_adapter_id must be greater than 0.\"\n        return self.worker.remove_prompt_adapter(prompt_adapter_id)\n\n    # NOTE(sgm): add for verl\n    def offload_model_weights(self) -> None:\n        self.worker.offload_model_weights()\n\n    def sync_model_weights(self, actor_weights: Dict[str, torch.Tensor], load_format: str) -> None:\n        self.worker.sync_model_weights(actor_weights=actor_weights, load_format=load_format)\n\n\ndef initialize_cluster(\n    parallel_config: ParallelConfig,\n    engine_use_ray: bool = False,\n    ray_address: Optional[str] = None,\n) -> Tuple[str, Optional[None]]:\n    \"\"\"Initialize the distributed cluster probably with Ray.\n\n    Args:\n        parallel_config: The configurations for parallel execution.\n\n    Returns:\n        The `distributed_init_method` is the address for initializing the\n        distributed backend.\n    \"\"\"\n\n    # Initialize cluster locally.\n    port = get_open_port()\n    # We need to setup the distributed init method to make sure\n    # the distributed megatron code (e.g., get world size) works correctly.\n    # distributed_init_method = f\"tcp://localhost:{port}\"\n    distributed_init_method = \"env://\"\n    return distributed_init_method\n\n\ndef get_open_port():\n    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n        s.bind((\"\", 0))\n        return s.getsockname()[1]\n\n\n# TODO(sgm): not implemented async executor yet\nclass SPMDGPUExecutorAsync(SPMDGPUExecutor, ExecutorAsyncBase):\n\n    async def execute_model_async(self, execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:\n        \"\"\"Executes one model step on the given sequences.\"\"\"\n        raise NotImplementedError\n\n    async def check_health_async(self) -> None:\n        \"\"\"Checks if the executor is healthy. If not, it should raise an\n        exception.\"\"\"\n        self.check_health()\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/tokenizer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/tokenizer_group/tokenizer_group.py\n\nfrom typing import Optional\n\nfrom transformers import PreTrainedTokenizer\nfrom vllm.transformers_utils.tokenizer_group import TokenizerGroup\nfrom vllm.utils import LRUCache\n\n\nclass TokenizerGroup(TokenizerGroup):\n    \"\"\"A group of tokenizers that can be used for LoRA adapters.\"\"\"\n\n    def __init__(self, tokenizer: PreTrainedTokenizer, enable_lora: bool, max_num_seqs: int,\n                 max_input_length: Optional[int]):\n        self.enable_lora = enable_lora\n        self.max_input_length = max_input_length\n        self.tokenizer = tokenizer\n        self.lora_tokenizers = LRUCache[PreTrainedTokenizer](capacity=max_num_seqs) if enable_lora else None\n\n    # FIXME(sgm): for simplicity, we assign the special token here\n    @property\n    def pad_token_id(self):\n        return self.tokenizer.pad_token_id\n\n    @property\n    def eos_token_id(self):\n        return self.tokenizer.eos_token_id\n"
  },
  {
    "path": "verl/third_party/vllm/vllm_v_0_6_3/worker.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/worker/worker.py\n\"\"\"A GPU worker class.\"\"\"\nimport gc\nimport os\nfrom typing import Dict, List, Optional, Tuple, Type, Union\n\nimport torch\nimport torch.distributed\nimport torch.nn as nn\nfrom vllm.config import (\n    CacheConfig,\n    DeviceConfig,\n    LoRAConfig,\n    ParallelConfig,\n    PromptAdapterConfig,\n    SchedulerConfig,\n    SpeculativeConfig,\n)\n\n# TODO(sgm): check why vllm has similar file in vllm.model_executor.parallel_utils.parallel_state\nfrom vllm.distributed import get_tensor_model_parallel_group, init_distributed_environment, set_custom_all_reduce\nfrom vllm.model_executor import set_random_seed\nfrom vllm.model_executor.layers.sampler import SamplerOutput\nfrom vllm.sequence import ExecuteModelRequest, IntermediateTensors\nfrom vllm.worker.cache_engine import CacheEngine\nfrom vllm.worker.embedding_model_runner import EmbeddingModelRunner\nfrom vllm.worker.model_runner import GPUModelRunnerBase\nfrom vllm.worker.model_runner_base import ModelRunnerInputBase\nfrom vllm.worker.worker import Worker, _check_if_gpu_supports_dtype\nfrom vllm.worker.worker_base import WorkerInput\n\nfrom .config import LoadConfig, LoadFormat, ModelConfig\nfrom .dtensor_weight_loaders import load_dtensor_weights\nfrom .hf_weight_loader import load_hf_weights\nfrom .megatron_weight_loaders import load_megatron_weights\nfrom .model_runner import ModelRunner\nfrom .parallel_state import ensure_model_parallel_initialized\n\n\nclass Worker(Worker):\n    \"\"\"A worker class that executes (a partition of) the model on a GPU.\n\n    Each worker is associated with a single GPU. The worker is responsible for\n    maintaining the KV cache and executing the model on the GPU. In case of\n    distributed inference, each worker is assigned a partition of the model.\n    \"\"\"\n\n    def __init__(\n        self,\n        model: Union[nn.Module, Dict],  # model itself or its parameter dict\n        model_config: ModelConfig,\n        parallel_config: ParallelConfig,\n        scheduler_config: SchedulerConfig,\n        device_config: DeviceConfig,\n        cache_config: CacheConfig,\n        load_config: LoadConfig,\n        local_rank: int,\n        rank: int,\n        distributed_init_method: str,\n        lora_config: Optional[LoRAConfig] = None,\n        speculative_config: Optional[SpeculativeConfig] = None,\n        prompt_adapter_config: Optional[PromptAdapterConfig] = None,\n        is_driver_worker: bool = False,\n        model_runner_cls: Optional[Type[GPUModelRunnerBase]] = None,\n    ) -> None:\n        # self.model = model  # will be replaced in the init_model\n        self.model_config = model_config\n        self.parallel_config = parallel_config\n        self.parallel_config.rank = rank\n        self.scheduler_config = scheduler_config\n        self.device_config = device_config\n        self.cache_config = cache_config\n        self.local_rank = local_rank\n        self.rank = rank\n        self.distributed_init_method = distributed_init_method\n        self.lora_config = lora_config\n        self.load_config = load_config\n        self.prompt_adapter_config = prompt_adapter_config\n        self.is_driver_worker = is_driver_worker  # TODO: we don't need driver\n        # if parallel_config and is_driver_worker:\n        #     assert rank % parallel_config.tensor_parallel_size == 0, \\\n        #            \"Driver worker should be rank 0 of tensor parallel group.\"\n        if self.model_config.trust_remote_code:\n            # note: lazy import to avoid importing torch before initializing\n            from vllm.utils import init_cached_hf_modules\n\n            init_cached_hf_modules()\n\n        # Return hidden states from target model if the draft model is an\n        # mlp_speculator\n        speculative_args = (\n            {} if speculative_config is None or (speculative_config.draft_model_config.model == model_config.model) or\n            (speculative_config.draft_model_config.hf_config.model_type not in [\"medusa\", \"mlp_speculator\"]) else {\n                \"return_hidden_states\": True\n            })\n\n        # TODO(sgm): set correct model runner class\n        ModelRunnerClass: Type[GPUModelRunnerBase] = ModelRunner\n        if model_runner_cls is not None:\n            ModelRunnerClass = model_runner_cls\n        elif self.model_config.embedding_mode:\n            ModelRunnerClass = EmbeddingModelRunner\n        self.model_runner: GPUModelRunnerBase = ModelRunnerClass(\n            model,  # [VERL]: add for verl\n            model_config,\n            parallel_config,\n            scheduler_config,\n            device_config,\n            cache_config,\n            load_config=load_config,\n            lora_config=self.lora_config,\n            kv_cache_dtype=self.cache_config.cache_dtype,\n            is_driver_worker=is_driver_worker,\n            prompt_adapter_config=prompt_adapter_config,\n            **speculative_args,\n        )\n\n        # Uninitialized cache engine. Will be initialized by\n        # initialize_cache.\n        self.cache_engine: List[CacheEngine] = None\n        # Initialize gpu_cache as embedding models don't initialize kv_caches\n        self.gpu_cache: Optional[List[List[torch.Tensor]]] = None\n\n        # NOTE(sgm): [VERL] For offloading inference engine params\n        self.cpu_model = None\n\n    def init_device(self) -> None:\n        if self.device_config.device.type == \"cuda\":\n            # torch.distributed.all_reduce does not free the input tensor until\n            # the synchronization point. This causes the memory usage to grow\n            # as the number of all_reduce calls increases. This env var disables\n            # this behavior.\n            # Related issue:\n            # https://discuss.pytorch.org/t/cuda-allocation-lifetime-for-inputs-to-distributed-all-reduce/191573\n            os.environ[\"TORCH_NCCL_AVOID_RECORD_STREAMS\"] = \"1\"\n\n            # NOTE(sgm): Modify for verl, Env vars will be set by TORCHRUN.\n            self.rank = self.rank if self.rank is not None else int(os.getenv(\"RANK\", \"-1\"))\n            local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n            self.device = torch.device(f\"cuda:{local_rank}\")\n            if self.rank < 0:\n                raise ValueError(\"Invalid or unspecified rank.\")\n            torch.cuda.set_device(self.device)\n\n            # Use the world_size set by TORCHRUN\n            world_size = int(os.getenv(\"WORLD_SIZE\", \"-1\"))\n            assert world_size != -1, \"The world_size is set to -1, not initialized by TORCHRUN\"\n            self.parallel_config.world_size = world_size\n\n            _check_if_gpu_supports_dtype(self.model_config.dtype)\n            torch.cuda.empty_cache()\n            self.init_gpu_memory = torch.cuda.mem_get_info()[0]\n        else:\n            raise RuntimeError(f\"Not support device type: {self.device_config.device}\")\n\n        # Initialize the distributed environment.\n        init_worker_distributed_environment(self.parallel_config, self.rank, self.distributed_init_method,\n                                            self.local_rank)\n        # Set random seed.\n        set_random_seed(self.model_config.seed)\n        # self.model = get_model(actor_model=self.model, model_config=self.model_config)\n\n    @torch.inference_mode()\n    def determine_num_available_blocks(self) -> Tuple[int, int]:\n        \"\"\"Profiles the peak memory usage of the model to determine how many\n        KV blocks may be allocated without OOMs.\n\n        The engine will first conduct a profiling of the existing memory usage.\n        Then, it calculate the maximum possible number of GPU and CPU blocks\n        that can be allocated with the remaining free memory.\n\n        .. tip::\n            You may limit the usage of GPU memory\n            by adjusting the `gpu_memory_utilization` parameter.\n        \"\"\"\n        # Profile the memory usage of the model and get the maximum number of\n        # cache blocks that can be allocated with the remaining free memory.\n        torch.cuda.empty_cache()\n        # torch.cuda.reset_peak_memory_stats()\n\n        # Execute a forward pass with dummy inputs to profile the memory usage\n        # of the model.\n        self.model_runner.profile_run()\n\n        # Calculate the number of blocks that can be allocated with the\n        # profiled peak memory.\n        torch.cuda.synchronize()\n        free_gpu_memory, total_gpu_memory = torch.cuda.mem_get_info()\n        peak_memory = total_gpu_memory - free_gpu_memory\n\n        assert peak_memory > 0, (\"Error in memory profiling. This happens when the GPU memory was \"\n                                 \"not properly cleaned up before initializing the vLLM instance.\")\n\n        cache_block_size = self.get_cache_block_size_bytes()\n\n        # NOTE(sgm) [VERL] use the remaining memory\n        num_gpu_blocks = int((free_gpu_memory * self.cache_config.gpu_memory_utilization) // cache_block_size)\n        # num_gpu_blocks = int((total_gpu_memory * self.cache_config.gpu_memory_utilization - peak_memory) // cache_block_size)\n\n        num_cpu_blocks = int(self.cache_config.swap_space_bytes // cache_block_size)\n        num_gpu_blocks = max(num_gpu_blocks, 0)\n        num_cpu_blocks = max(num_cpu_blocks, 0)\n        if self.model_runner.lora_manager:\n            self.model_runner.remove_all_loras()\n\n        # NOTE(sgm): Add for [VERL], synchronize number of blocks with all the rank\n        num_gpu_blocks = torch.tensor([num_gpu_blocks], device=\"cuda\")\n        num_cpu_blocks = torch.tensor([num_cpu_blocks], device=\"cuda\")\n\n        torch.distributed.all_reduce(num_gpu_blocks,\n                                     op=torch.distributed.ReduceOp.MIN,\n                                     group=get_tensor_model_parallel_group().device_group)\n        torch.distributed.all_reduce(num_cpu_blocks,\n                                     op=torch.distributed.ReduceOp.MIN,\n                                     group=get_tensor_model_parallel_group().device_group)\n        num_gpu_blocks = num_gpu_blocks.item()\n        num_cpu_blocks = num_cpu_blocks.item()\n        gc.collect()\n        torch.cuda.empty_cache()\n        return num_gpu_blocks, num_cpu_blocks\n\n    def _init_cache_engine(self):\n        if self.cache_engine is None and self.gpu_cache is None:\n            super()._init_cache_engine()\n\n    def free_cache_engine(self):\n        # ensure `enforce_eager=True`\n        self.cache_engine = None\n        self.gpu_cache = None\n\n    # NOTE(sgm): [VERL]: adapt from _execute_model_spmd()\n    def execute_model(self,\n                      execute_model_req: ExecuteModelRequest,\n                      intermediate_tensors: Optional[IntermediateTensors] = None) -> Optional[List[SamplerOutput]]:\n        \"\"\"\n        Execute model in Single Program Multiple Data (SPMD) fashion.\n        All workers take the same request, prepare the input and\n        execute the model.\n        \"\"\"\n        assert execute_model_req is not None, (\"_execute_model_spmd() requires each worker to take in an \"\n                                               \"ExecuteModelRequest\")\n        worker_input: WorkerInput = self.prepare_worker_input(execute_model_req=execute_model_req)\n        model_input: ModelRunnerInputBase = self.model_runner.prepare_model_input(\n            execute_model_req.seq_group_metadata_list)\n\n        # verl.worker.workerbase.WorkerBase\n        # swap cache\n        super().execute_worker(worker_input)\n\n        # If there is no input, we don't need to execute the model.\n        if worker_input.num_seq_groups == 0:\n            return []\n\n        return self.model_runner.execute_model(\n            model_input,\n            self.kv_cache[worker_input.virtual_engine] if self.kv_cache is not None else None,\n            intermediate_tensors,\n        )\n\n    # assume the input is .state_dict()\n    def sync_model_weights(self, actor_weights: Dict, load_format: str):\n        if load_format in [LoadFormat.MEGATRON, LoadFormat.AUTO]:\n            load_megatron_weights(actor_weights, self.model_runner.model)\n        elif load_format == LoadFormat.HF:\n            # full model state dict without no sharding\n            load_hf_weights(actor_weights, self.model_runner.model)\n        elif load_format == LoadFormat.DTENSOR:\n            load_dtensor_weights(actor_weights, self.model_runner.model)\n\n    def offload_model_weights(self) -> None:\n        if self.cpu_model == None:\n            self.cpu_model = {}\n            for name, params in self.model_runner.model.named_parameters():\n                self.cpu_model[name] = torch.empty_like(params, device=\"cpu\")\n                params.data = self.cpu_model[name]\n        else:\n            for name, params in self.model_runner.model.named_parameters():\n                params.data = self.cpu_model[name]\n\n\ndef init_worker_distributed_environment(\n    parallel_config: ParallelConfig,\n    rank: int,\n    distributed_init_method: Optional[str] = \"env://\",\n    local_rank: int = -1,\n) -> None:\n    \"\"\"Initialize the distributed environment.\"\"\"\n    set_custom_all_reduce(not parallel_config.disable_custom_all_reduce)\n\n    # NOTE(sgm) use tcp://localhost:xxxx will hang in HF setting without megatron\n    init_distributed_environment(parallel_config.world_size, rank, distributed_init_method, local_rank)\n\n    ensure_model_parallel_initialized(\n        tensor_model_parallel_size=parallel_config.tensor_parallel_size,\n        pipeline_model_parallel_size=parallel_config.pipeline_parallel_size,\n    )\n\n    # TODO(sgm): check whether need this\n    # if pynccl_utils.is_initialized():\n    #     pynccl_world_size = pynccl_utils.get_world_size()\n    #     if pynccl_world_size != parallel_config.world_size:\n    #         raise RuntimeError(\n    #             \"pynccl is already initialized but the pynccl world \"\n    #             \"size does not match parallel_config.world_size \"\n    #             f\"({pynccl_world_size} vs. {parallel_config.world_size}).\")\n    # elif parallel_config.world_size > 1:\n    #     # NOTE(woosuk): We don't initialize pynccl process group when world size\n    #     # is 1.\n    #     # NOTE(kaichao): By default, pynccl is initialized for tp group.\n    #     pynccl_utils.init_process_group(\n    #         group=get_tensor_model_parallel_cpu_group())\n\n    # # Initialize a custom fast all-reduce implementation.\n    # if not parallel_config.disable_custom_all_reduce:\n    #     init_custom_ar()\n\n    # A small all_reduce for warmup.\n    torch.distributed.all_reduce(torch.zeros(1).cuda())\n    # if pynccl_utils.is_initialized():\n    #     pynccl_utils.all_reduce(torch.zeros(1).cuda())\n"
  },
  {
    "path": "verl/trainer/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/trainer/config/evaluation.yaml",
    "content": "data:\n  path: /tmp/math_Qwen2-7B-Instruct.parquet\n  prompt_key: prompt\n  response_key: responses\n  data_source_key: data_source\n  reward_model_key: reward_model"
  },
  {
    "path": "verl/trainer/config/generation.yaml",
    "content": "trainer:\n  nnodes: 1\n  n_gpus_per_node: 8\n\ndata:\n  path: ~/data/rlhf/math/test.parquet\n  prompt_key: prompt\n  n_samples: 5\n  output_path: /opt/tiger/math_Qwen2-7B-Instruct.parquet\n  batch_size: 128\n\nmodel:\n  path: ~/models/Qwen2-7B-Instruct\n  external_lib: null\nrollout:\n  name: vllm\n  temperature: 1.0\n  top_k: 50 # 0 for hf rollout, -1 for vllm rollout\n  top_p: 0.7\n  prompt_length: 1536\n  response_length: 512\n  # for vllm rollout\n  dtype: bfloat16 # should align with FSDP\n  gpu_memory_utilization: 0.5\n  ignore_eos: False\n  enforce_eager: True\n  free_cache_engine: True\n  load_format: dummy_dtensor\n  tensor_model_parallel_size: 1\n  max_num_batched_tokens: 8192\n  max_model_len: null\n  max_num_seqs: 1024\n  log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu\n  log_prob_micro_batch_size_per_gpu: 8\n  # for fire vllm rollout\n  use_fire_sampling: False # enable FIRE https://arxiv.org/abs/2410.21236\n  # for hf rollout\n  do_sample: True\n  disable_log_stats: True\n  enable_chunked_prefill: True\n  n: 1\nactor:\n  strategy: fsdp  # This is for backward-compatibility\n  ppo_mini_batch_size: 256\n  ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu\n  ppo_micro_batch_size_per_gpu: null\n  use_dynamic_bsz: False\n  ppo_max_token_len_per_gpu: 16384 # n * ${data.max_prompt_length} + ${data.max_response_length}\n  grad_clip: 1.0\n  clip_ratio: 0.2\n  entropy_coeff: 0.001\n  use_kl_loss: False # True for GRPO\n  kl_loss_coef: 0.001 # for grpo\n  kl_loss_type: low_var_kl # for grpo\n  ppo_epochs: 1\n  shuffle: False\n  ulysses_sequence_parallel_size: 1 # sp size\n  optim:\n    lr: 1e-6\n    lr_warmup_steps_ratio: 0.  # the total steps will be injected during runtime\n    min_lr_ratio: null   # only useful for warmup with cosine\n    warmup_style: constant  # select from constant/cosine\n    total_training_steps: -1  # must be override by program\n  fsdp_config:\n    wrap_policy:\n      min_num_params: 0\n    param_offload: False\n    optimizer_offload: False\n    fsdp_size: -1"
  },
  {
    "path": "verl/trainer/config/ppo_megatron_trainer.yaml",
    "content": "data:\n  tokenizer: null\n  train_files: ~/data/rlhf/gsm8k/train.parquet\n  val_files: ~/data/rlhf/gsm8k/test.parquet\n  prompt_key: prompt\n  max_prompt_length: 512\n  max_response_length: 512\n  train_batch_size: 1024\n  val_batch_size: null # DEPRECATED: Validation datasets are sent to inference engines as a whole batch, which will schedule the memory themselves\n  return_raw_input_ids: False  # This should be set to true when the tokenizer between policy and rm differs\n  return_raw_chat: False\n  shuffle: True\n\nactor_rollout_ref:\n  hybrid_engine: True\n  model:\n    path: ~/models/deepseek-llm-7b-chat\n    external_lib: null\n    override_config: {}\n    enable_gradient_checkpointing: False\n  actor:\n    strategy: megatron  # This is for backward-compatibility\n    ppo_mini_batch_size: 256\n    ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu\n    ppo_micro_batch_size_per_gpu: null\n    use_dynamic_bsz: False\n    clip_ratio: 0.2\n    entropy_coeff: 0.001\n    ppo_epochs: 1\n    shuffle: True\n    optim:\n      lr: 1e-6\n      clip_grad: 1.0\n      lr_warmup_steps_ratio: 0.  # the total steps will be injected during runtime\n      min_lr_ratio: null   # only useful for warmup with cosine\n      warmup_style: constant  # select from constant/cosine\n      total_training_steps: -1  # must be override by program\n    megatron:\n      tensor_model_parallel_size: 4\n      pipeline_model_parallel_size: 1\n      num_layers_per_virtual_pipeline_stage: null # vpp will hang. need debug.\n      sequence_parallel: True\n      seed: 1\n    load_weight: True\n  ref:\n    megatron:\n      tensor_model_parallel_size: 4\n      pipeline_model_parallel_size: 1\n      num_layers_per_virtual_pipeline_stage: null # vpp will hang. need debug.\n      sequence_parallel: True\n      seed: 1\n    load_weight: True\n    param_offload: False\n    log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu\n    log_prob_micro_batch_size_per_gpu: null\n  rollout:\n    name: vllm\n    temperature: 1.0\n    top_k: -1 # 0 for hf rollout, -1 for vllm rollout\n    top_p: 1\n    prompt_length: ${data.max_prompt_length}  # for xperf_gpt\n    response_length: ${data.max_response_length}\n    # for vllm rollout\n    dtype: bfloat16 # should align with FSDP\n    gpu_memory_utilization: 0.5\n    ignore_eos: False\n    enforce_eager: True\n    free_cache_engine: True\n    load_format: dummy_megatron\n    tensor_model_parallel_size: 2\n    max_num_batched_tokens: 8192\n    max_model_len: null\n    max_num_seqs: 1024\n    log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu\n    log_prob_micro_batch_size_per_gpu: null\n    disable_log_stats: True\n    enable_chunked_prefill: False # could get higher throughput\n    # for hf rollout\n    do_sample: True\n    layer_name_map:\n      qkv_layer_name: qkv\n      gate_proj_layer_name: gate_up\n    # number of responses (i.e. num sample times)\n    n: 1\n\ncritic:\n  strategy: megatron\n  optim:\n    lr: 1e-5\n    clip_grad: 1.0\n    lr_warmup_steps_ratio: 0.  # the total steps will be injected during runtime\n    min_lr_ratio: null   # only useful for warmup with cosine\n    warmup_style: constant  # select from constant/cosine\n    total_training_steps: -1  # must be override by program\n  model:\n    path: ~/models/deepseek-llm-7b-chat\n    tokenizer_path: ${actor_rollout_ref.model.path}\n    override_config: {}\n    external_lib: ${actor_rollout_ref.model.external_lib}\n    enable_gradient_checkpointing: False\n  megatron:\n    tensor_model_parallel_size: 4\n    pipeline_model_parallel_size: 1\n    num_layers_per_virtual_pipeline_stage: null # vpp will hang. need debug.\n    sequence_parallel: True\n    seed: 1\n  load_weight: True\n  ppo_mini_batch_size: ${actor_rollout_ref.actor.ppo_mini_batch_size}\n  ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu\n  ppo_micro_batch_size_per_gpu: null\n  use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}\n  ppo_epochs: ${actor_rollout_ref.actor.ppo_epochs}\n  shuffle: ${actor_rollout_ref.actor.shuffle}\n  cliprange_value: 0.5\n  kl_ctrl:\n    type: fixed\n    kl_coef: 0.001\n\nreward_model:\n  enable: False\n  strategy: megatron\n  megatron:\n    tensor_model_parallel_size: 4\n    pipeline_model_parallel_size: 1\n    num_layers_per_virtual_pipeline_stage: null # vpp will hang. need debug.\n    sequence_parallel: True\n    seed: 1\n  model:\n    input_tokenizer: ${actor_rollout_ref.model.path}  # set this to null if the chat template is identical\n    path: ~/models/FsfairX-LLaMA3-RM-v0.1\n    external_lib: ${actor_rollout_ref.model.external_lib}\n  load_weight: True\n  param_offload: False\n  micro_batch_size: null # will be deprecated, use micro_batch_size_per_gpu\n  micro_batch_size_per_gpu: null\n  use_dynamic_bsz: ${critic.use_dynamic_bsz}\n  max_length: null\n\nalgorithm:\n  gamma: 1.0\n  lam: 1.0\n  adv_estimator: gae\n  kl_penalty: kl  # how to estimate kl divergence\n  kl_ctrl:\n    type: fixed\n    kl_coef: 0.001\n\ntrainer:\n  total_epochs: 30\n  total_training_steps: null\n  project_name: verl_examples\n  experiment_name: gsm8k\n  logger: ['console', 'wandb']\n  val_generations_to_log_to_wandb: 0\n  nnodes: 1\n  n_gpus_per_node: 8\n  save_freq: -1\n  # auto: find the last ckpt to resume. If can't find, start from scratch\n  resume_mode: disable # or auto or resume_path if \n  resume_from_path: False\n  test_freq: 2\n  critic_warmup: 0\n  default_hdfs_dir: null\n  default_local_dir: checkpoints/${trainer.project_name}/${trainer.experiment_name}\n"
  },
  {
    "path": "verl/trainer/config/ppo_trainer.yaml",
    "content": "data:\n  tokenizer: null\n  train_files: ~/data/rlhf/gsm8k/train.parquet\n  val_files: ~/data/rlhf/gsm8k/test.parquet\n  prompt_key: prompt\n  template_type: default\n  max_prompt_length: 512\n  val_max_prompt_length: 1024\n  max_response_length: 512\n  train_batch_size: 1024\n  val_batch_size: null # DEPRECATED: Validation datasets are sent to inference engines as a whole batch, which will schedule the memory themselves\n  return_raw_input_ids: False  # This should be set to true when the tokenizer between policy and rm differs\n  return_raw_chat: False\n  shuffle: True\n  image_key: images\n  reward_type: default\n  execution_error_penalty: False\n\nactor_rollout_ref:\n  hybrid_engine: True\n  model:\n    path: ~/models/deepseek-llm-7b-chat\n    external_lib: null\n    override_config: { }\n    enable_gradient_checkpointing: True\n    use_remove_padding: False\n  actor:\n    strategy: fsdp  # This is for backward-compatibility\n    ppo_mini_batch_size: 256\n    ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu\n    ppo_micro_batch_size_per_gpu: null\n    use_dynamic_bsz: False\n    ppo_max_token_len_per_gpu: 16384 # n * ${data.max_prompt_length} + ${data.max_response_length}\n    grad_clip: 1.0\n    clip_ratio: 0.2\n    entropy_coeff: 0.001\n    use_kl_loss: False # True for GRPO\n    kl_loss_coef: 0.001 # for grpo\n    kl_loss_type: low_var_kl # for grpo\n    ppo_epochs: 1\n    shuffle: False\n    ulysses_sequence_parallel_size: 1 # sp size\n    optim:\n      lr: 1e-6\n      lr_warmup_steps_ratio: 0.  # the total steps will be injected during runtime\n      min_lr_ratio: null   # only useful for warmup with cosine\n      warmup_style: constant  # select from constant/cosine\n      total_training_steps: -1  # must be override by program\n    fsdp_config:\n      wrap_policy:\n        # transformer_layer_cls_to_wrap: None\n        min_num_params: 0\n      param_offload: False\n      optimizer_offload: False\n      fsdp_size: -1\n  ref:\n    fsdp_config:\n      param_offload: False\n      wrap_policy:\n        # transformer_layer_cls_to_wrap: None\n        min_num_params: 0\n    log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu\n    log_prob_micro_batch_size_per_gpu: null\n    log_prob_use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}\n    log_prob_max_token_len_per_gpu: ${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}\n    ulysses_sequence_parallel_size: ${actor_rollout_ref.actor.ulysses_sequence_parallel_size} # sp size\n  rollout:\n    num_llm_calls_available: 3\n    name: vllm\n    temperature: 1.0\n    top_k: -1 # 0 for hf rollout, -1 for vllm rollout\n    top_p: 1\n    use_fire_sampling: False # https://arxiv.org/abs/2410.21236\n    prompt_length: ${data.max_prompt_length}  # not use for opensource\n    response_length: ${data.max_response_length}\n    # for vllm rollout\n    dtype: bfloat16 # should align with FSDP\n    gpu_memory_utilization: 0.5\n    ignore_eos: False\n    enforce_eager: True\n    free_cache_engine: True\n    load_format: dummy_dtensor\n    tensor_model_parallel_size: 2\n    max_num_batched_tokens: 8192\n    max_model_len: null\n    max_num_seqs: 1024\n    log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu\n    log_prob_micro_batch_size_per_gpu: null\n    log_prob_use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}\n    log_prob_max_token_len_per_gpu: ${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}\n    disable_log_stats: True\n    enable_chunked_prefill: True # may get higher throughput when set to True. When activated, Please increase max_num_batched_tokens or decrease max_model_len.\n    # for hf rollout\n    do_sample: True\n    # number of responses (i.e. num sample times)\n    n: 1 # > 1 for grpo\n\ncritic:\n  strategy: fsdp\n  optim:\n    lr: 1e-5\n    lr_warmup_steps_ratio: 0.  # the total steps will be injected during runtime\n    min_lr_ratio: null   # only useful for warmup with cosine\n    warmup_style: constant  # select from constant/cosine\n    total_training_steps: -1  # must be override by program\n  model:\n    path: ~/models/deepseek-llm-7b-chat\n    tokenizer_path: ${actor_rollout_ref.model.path}\n    override_config: { }\n    external_lib: ${actor_rollout_ref.model.external_lib}\n    enable_gradient_checkpointing: True\n    use_remove_padding: False\n    fsdp_config:\n      param_offload: False\n      optimizer_offload: False\n      wrap_policy:\n        # transformer_layer_cls_to_wrap: None\n        min_num_params: 0\n      fsdp_size: -1\n  ppo_mini_batch_size: ${actor_rollout_ref.actor.ppo_mini_batch_size}\n  ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu\n  ppo_micro_batch_size_per_gpu: null\n  forward_micro_batch_size: ${critic.ppo_micro_batch_size}\n  forward_micro_batch_size_per_gpu: ${critic.ppo_micro_batch_size_per_gpu}\n  use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}\n  ppo_max_token_len_per_gpu: 32768 # (${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}) * 2\n  forward_max_token_len_per_gpu: ${critic.ppo_max_token_len_per_gpu}\n  ulysses_sequence_parallel_size: 1 # sp size\n  ppo_epochs: ${actor_rollout_ref.actor.ppo_epochs}\n  shuffle: ${actor_rollout_ref.actor.shuffle}\n  grad_clip: 1.0\n  cliprange_value: 0.5\n\nreward_model:\n  enable: False\n  strategy: fsdp\n  model:\n    input_tokenizer: ${actor_rollout_ref.model.path}  # set this to null if the chat template is identical\n    path: ~/models/FsfairX-LLaMA3-RM-v0.1\n    external_lib: ${actor_rollout_ref.model.external_lib}\n    use_remove_padding: False\n    fsdp_config:\n      min_num_params: 0\n      param_offload: False\n      fsdp_size: -1\n  micro_batch_size: null # will be deprecated, use micro_batch_size_per_gpu\n  micro_batch_size_per_gpu: null # set a number\n  max_length: null\n  ulysses_sequence_parallel_size: 1 # sp size\n  use_dynamic_bsz: ${critic.use_dynamic_bsz}\n  forward_max_token_len_per_gpu: ${critic.forward_max_token_len_per_gpu}\n  reward_manager: naive\n\nalgorithm:\n  gamma: 1.0\n  lam: 1.0\n  adv_estimator: gae\n  kl_penalty: kl  # how to estimate kl divergence\n  kl_ctrl:\n    type: fixed\n    kl_coef: 0.001\n\ntrainer:\n  total_epochs: 30\n  total_training_steps: null\n  project_name: verl_examples\n  experiment_name: gsm8k\n  logger: [ 'console', 'wandb' ]\n  val_generations_to_log_to_wandb: 0\n  nnodes: 1\n  n_gpus_per_node: 8\n  save_freq: -1\n  samples_save_path: null\n  # auto: find the last ckpt to resume. If can't find, start from scratch\n  resume_mode: auto # or auto or resume_path if \n  resume_from_path: False\n  test_freq: -1\n  critic_warmup: 0\n  default_hdfs_dir: null\n  remove_previous_ckpt_in_save: False\n  del_local_ckpt_after_load: False\n  default_local_dir: checkpoints/${trainer.project_name}/${trainer.experiment_name}\n"
  },
  {
    "path": "verl/trainer/config/sft_trainer.yaml",
    "content": "data:\n  train_batch_size: 256\n  micro_batch_size: null # will be deprecated, use micro_batch_size_per_gpu\n  micro_batch_size_per_gpu: 4  # this is also val batch size\n  train_files: ~/data/gsm8k/train.parquet\n  val_files: ~/data/gsm8k/test.parquet\n  prompt_key: question\n  response_key: answer\n  max_length: 1024\n  truncation: error\n  balance_dp_token: False\n  chat_template: null\nmodel:\n  partial_pretrain: ~/models/gemma-1.1-7b-it\n  fsdp_config:\n    wrap_policy:\n      min_num_params: 0\n    cpu_offload: False\n    offload_params: False\n  external_lib: null\n  enable_gradient_checkpointing: False\n  trust_remote_code: False\n  lora_rank: 0  # Set to positive value to enable LoRA (e.g., 32)\n  lora_alpha: 16  # LoRA scaling factor\n  target_modules: all-linear  # Target modules for LoRA adaptation\n  use_liger: False\noptim:\n  lr: 1e-5\n  betas: [0.9, 0.95]\n  weight_decay: 0.01\n  warmup_steps_ratio: 0.1\n  clip_grad: 1.0\nulysses_sequence_parallel_size: 1\nuse_remove_padding: False\ntrainer:\n  default_local_dir: /tmp/sft_model\n  default_hdfs_dir: hdfs://tmp/experiments/gsm8k/gemma-1.1-7b-it/ # change the hdfs path here\n  resume_path: null\n  project_name: gsm8k-sft\n  experiment_name: test\n  total_epochs: 4\n  total_training_steps: null\n  logger: ['console']\n  seed: 1\n\n"
  },
  {
    "path": "verl/trainer/fsdp_sft_trainer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nA lightweight one-file FSDP SFT Trainer\nTODO(zhangchi.usc1992)\n- Add calculation of mfu\n- Add validation\n\"\"\"\n\nimport os\n\nos.environ['NCCL_DEBUG'] = 'WARN'\nos.environ['TOKENIZERS_PARALLELISM'] = 'true'\n\nimport logging\nimport re\nfrom contextlib import nullcontext\nimport torch\nimport torch.distributed\nfrom torch import nn, optim\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, CPUOffload\nfrom tqdm import tqdm\nfrom transformers import AutoTokenizer, AutoModelForCausalLM, PreTrainedModel, AutoConfig\nfrom verl.utils.torch_functional import get_cosine_schedule_with_warmup\nfrom tensordict import TensorDict\nfrom torch.utils.data import DataLoader, DistributedSampler\nfrom flash_attn.bert_padding import pad_input, unpad_input, rearrange, index_first_axis\n\nfrom verl.utils.fsdp_utils import get_fsdp_wrap_policy, init_fn, get_init_weight_context_manager\nfrom verl.utils.dataset import SFTDataset\nfrom verl.utils.fs import copy_to_local\nfrom verl.utils.tracking import Tracking\nfrom verl.utils.ulysses import get_ulysses_sequence_parallel_world_size, set_ulysses_sequence_parallel_group\nfrom torch.distributed.device_mesh import DeviceMesh\n\nimport verl.utils.hdfs_io as hdfs_io\nfrom verl.utils.debug import log_gpu_memory_usage\nfrom peft import LoraConfig, TaskType, get_peft_model\n\nfrom verl.workers.sharding_manager import FSDPUlyssesShardingManager\nfrom verl.utils.ulysses import ulysses_pad_and_slice_inputs, gather_outpus_and_unpad\nfrom verl import DataProto\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv('VERL_SFT_LOGGING_LEVEL', 'WARN'))\n\n\ndef extract_step(path):\n    match = re.search(r'global_step_(\\d+)', path)\n    if match:\n        return int(match.group(1))\n    return None\n\n\ndef convert_to_regular_types(obj):\n    \"\"\"Convert Hydra configs and other special types to regular Python types.\"\"\"\n    from omegaconf import ListConfig, DictConfig\n    if isinstance(obj, (ListConfig, DictConfig)):\n        return {k: convert_to_regular_types(v) for k, v in obj.items()} if isinstance(obj, DictConfig) else list(obj)\n    elif isinstance(obj, (list, tuple)):\n        return [convert_to_regular_types(x) for x in obj]\n    elif isinstance(obj, dict):\n        return {k: convert_to_regular_types(v) for k, v in obj.items()}\n    return obj\n\n\nclass FSDPSFTTrainer(object):\n\n    def __init__(self, config, device_mesh: DeviceMesh, ulysses_device_mesh: DeviceMesh):\n        self.config = config\n        self.device_mesh = device_mesh\n        self.ulysses_device_mesh = ulysses_device_mesh\n        self.sharding_manager = FSDPUlyssesShardingManager(self.ulysses_device_mesh)\n        # build tokenizer first\n        local_model_path = copy_to_local(src=self.config.model.partial_pretrain, verbose=True)\n        from verl.utils import hf_tokenizer\n        self.tokenizer = hf_tokenizer(local_model_path, trust_remote_code=self.config.model.trust_remote_code)\n        if self.config.data.chat_template is not None:\n            raise ValueError('Apply Chat template from config is not supported yet.')\n\n        # normalize dp size\n        self._normalize_config_bsz()\n\n        # Set sequence parallel size\n        self.config.ulysses_sequence_parallel_size = getattr(self.config, 'ulysses_sequence_parallel_size', 1)\n        self.use_remove_padding = getattr(self.config, 'use_remove_padding', False)\n        if self.device_mesh.get_rank() == 0:\n            print(f'Using sequence parallel size: {self.config.ulysses_sequence_parallel_size}')\n            print(f'Using remove padding: {self.use_remove_padding}')\n\n        self._build_dataloader()\n        # build model\n        self._build_model_optimizer()\n\n        # TODO: add checkpoint manager\n        if self.device_mesh.get_rank() == 0:\n            print(self.config)\n\n    def _normalize_config_bsz(self):\n        dp_size = self.device_mesh.size(0) if not self.ulysses_device_mesh else self.ulysses_device_mesh.size(0)\n        if self.device_mesh.get_rank() == 0:\n            print(f'Normalize batch size by dp {dp_size}')\n\n        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}\"\n\n        self.config.data.train_batch_size //= dp_size\n\n        assert self.config.data.train_batch_size % self.config.data.micro_batch_size_per_gpu == 0\n\n    def _build_dataloader(self):\n        config = self.config\n        # build dataset\n        self.train_dataset = SFTDataset(parquet_files=config.data.train_files,\n                                        tokenizer=self.tokenizer,\n                                        prompt_key=config.data.prompt_key,\n                                        prompt_dict_keys=config.data.get('prompt_dict_keys', None),\n                                        response_key=config.data.response_key,\n                                        response_dict_keys=config.data.get('response_dict_keys', None),\n                                        max_length=config.data.max_length,\n                                        truncation=config.data.truncation)\n        self.val_dataset = SFTDataset(parquet_files=config.data.val_files,\n                                      tokenizer=self.tokenizer,\n                                      prompt_key=config.data.prompt_key,\n                                      prompt_dict_keys=config.data.get('prompt_dict_keys', None),\n                                      response_key=config.data.response_key,\n                                      response_dict_keys=config.data.get('response_dict_keys', None),\n                                      max_length=config.data.max_length,\n                                      truncation=config.data.truncation)\n\n        # build dataloader\n        # Use data parallel rank and size instead of global rank and world size\n\n        # If doing SP, we need to use the local rank and size\n        if self.config.ulysses_sequence_parallel_size > 1:\n            rank = self.ulysses_device_mesh.get_local_rank('dp')\n            world_size = self.ulysses_device_mesh.size(0)\n            if self.ulysses_device_mesh.get_rank() == 0:\n                print(f'Using SP rank {rank} and size {world_size} for data distribution')\n                print(f'Each SP rank gets different data, but the same data WITHIN the same rank')\n        else:\n            rank = self.device_mesh.get_rank()\n            world_size = self.device_mesh.size()\n        if self.device_mesh.get_rank() == 0:\n            print(f'Using FSDP rank {rank} and size {world_size} for data distribution')\n\n        self.train_sampler = DistributedSampler(self.train_dataset,\n                                                shuffle=True,\n                                                num_replicas=world_size,\n                                                rank=rank,\n                                                drop_last=True)\n        self.train_dataloader = DataLoader(dataset=self.train_dataset,\n                                           batch_size=config.data.train_batch_size,\n                                           sampler=self.train_sampler,\n                                           num_workers=8,\n                                           pin_memory=True,\n                                           drop_last=True)\n\n        self.val_sampler = DistributedSampler(self.val_dataset,\n                                              shuffle=False,\n                                              num_replicas=world_size,\n                                              rank=rank,\n                                              drop_last=True)\n        self.val_dataloader = DataLoader(dataset=self.val_dataset,\n                                         batch_size=config.data.micro_batch_size_per_gpu,\n                                         sampler=self.val_sampler,\n                                         num_workers=8,\n                                         pin_memory=True,\n                                         drop_last=True)\n\n    def _build_model_optimizer(self):\n        # TODO (zhangchi.usc1992):\n        # 1. support pretrain from random weights\n        # 2. support init directly from sharded weights\n        local_model_path = copy_to_local(src=self.config.model.partial_pretrain, verbose=True)\n\n        if self.config.model.get('external_lib', None) is not None:\n            # This is used to import external_lib into the huggingface systems\n            import importlib\n            importlib.import_module(self.config.model.external_lib)\n\n        log_gpu_memory_usage('Before model allocation', logger=logger)\n\n        trust_remote_code = self.config.model.trust_remote_code\n        # load config first\n        config = AutoConfig.from_pretrained(local_model_path, trust_remote_code=trust_remote_code)\n        if self.config.ulysses_sequence_parallel_size > 1:\n            assert self.use_remove_padding, \"Sequence parallel is only supported when remove_padding is enabled\"\n            from verl.models.registry import check_model_support_rmpad\n            check_model_support_rmpad(config.model_type)\n\n        if self.use_remove_padding and self.config.ulysses_sequence_parallel_size > 1:\n            from verl.models.transformers.monkey_patch import apply_monkey_patch\n            apply_monkey_patch(config, verbose=True)\n\n        # This may be very large\n        init_context = get_init_weight_context_manager(use_meta_tensor=not config.tie_word_embeddings)\n\n        with init_context():\n            self.model: PreTrainedModel = AutoModelForCausalLM.from_pretrained(local_model_path,\n                                                                               config=config,\n                                                                               torch_dtype=torch.float32,\n                                                                               attn_implementation='flash_attention_2',\n                                                                               trust_remote_code=trust_remote_code)\n\n            # Apply Liger kernel if use_liger is enabled\n            if self.config.model.get('use_liger', False):\n                from liger_kernel.transformers.monkey_patch import _apply_liger_kernel_to_instance\n                _apply_liger_kernel_to_instance(model=self.model)\n\n            if self.config.model.get('lora_rank', 0) > 0:\n                self.model.enable_input_require_grads()\n                # Convert config to regular Python types before creating PEFT model\n                lora_config = {\n                    'task_type': TaskType.CAUSAL_LM,\n                    'r': self.config.model.lora_rank,\n                    'lora_alpha': self.config.model.lora_alpha,\n                    'target_modules': convert_to_regular_types(self.config.model.target_modules),\n                    'bias': \"none\"\n                }\n                self.model = get_peft_model(self.model, LoraConfig(**lora_config))\n\n        if self.config.model.enable_gradient_checkpointing:\n            self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False})\n\n        log_gpu_memory_usage('After model allocation', logger=logger)\n\n        mixed_precision = MixedPrecision(param_dtype=torch.bfloat16,\n                                         reduce_dtype=torch.float32,\n                                         buffer_dtype=torch.float32)\n\n        auto_wrap_policy = get_fsdp_wrap_policy(self.model,\n                                                config=self.config.model.fsdp_config.wrap_policy,\n                                                is_lora=self.config.model.get('lora_rank', 0) > 0)\n        if self.device_mesh.get_rank() == 0:\n            print(auto_wrap_policy)\n\n        if not self.config.model.fsdp_config.cpu_offload:\n            cpu_offload = None\n        else:\n            cpu_offload = CPUOffload(offload_params=self.config.model.fsdp_config.offload_params)\n\n        self.fsdp_model = FSDP(module=self.model,\n                               auto_wrap_policy=auto_wrap_policy,\n                               param_init_fn=init_fn,\n                               sharding_strategy=ShardingStrategy.FULL_SHARD,\n                               mixed_precision=mixed_precision,\n                               device_mesh=self.device_mesh,\n                               sync_module_states=True,\n                               device_id=torch.cuda.current_device(),\n                               cpu_offload=cpu_offload,\n                               use_orig_params=False)\n\n        log_gpu_memory_usage('After FSDP wrapping', logger=logger)\n\n        self.optimizer = optim.AdamW(self.fsdp_model.parameters(),\n                                     lr=self.config.optim.lr,\n                                     betas=self.config.optim.betas,\n                                     weight_decay=self.config.optim.weight_decay)\n\n        log_gpu_memory_usage('After initialize optimizer', logger=logger)\n\n        self.steps_per_epoch = len(self.train_dataloader)\n        self.total_steps = self.steps_per_epoch * self.config.trainer.total_epochs\n\n        if self.device_mesh.get_rank() == 0:\n            print(\n                f'Number of steps/epoch {self.steps_per_epoch}, number of epochs {self.config.trainer.total_epochs}, total number of steps {self.total_steps}'\n            )\n\n        num_warmup_steps = int(self.total_steps * self.config.optim.warmup_steps_ratio)\n\n        self.lr_scheduler = get_cosine_schedule_with_warmup(optimizer=self.optimizer,\n                                                            num_warmup_steps=num_warmup_steps,\n                                                            num_training_steps=self.total_steps)\n\n    def _compute_loss_and_backward(self, batch, do_backward=True):\n        \"\"\"Compute loss with optional sequence parallelism and remove padding features\"\"\"\n        use_sp = self.use_remove_padding and self.config.ulysses_sequence_parallel_size > 1\n\n        # Move inputs to GPU and prepare loss mask\n        input_ids = batch['input_ids'].cuda()\n        attention_mask = batch['attention_mask'].cuda()\n        position_ids = batch['position_ids'].cuda()\n        loss_mask = batch.pop('loss_mask')[:, :-1].reshape(-1).cuda()\n        loss_fct = nn.CrossEntropyLoss(reduction='none')\n\n        # Context manager for sequence parallel if needed\n        context = self.sharding_manager if use_sp else nullcontext()\n        with context:\n            with torch.autocast(device_type='cuda', dtype=torch.bfloat16):\n                if not use_sp:\n                    # Standard forward pass without sequence parallel\n                    labels = input_ids[:, 1:].contiguous()\n                    output = self.fsdp_model(input_ids=input_ids,\n                                             attention_mask=attention_mask,\n                                             position_ids=position_ids,\n                                             use_cache=False)\n                    logits = output.logits\n\n                    shift_logits = logits[..., :-1, :].contiguous()\n                    shift_labels = labels.contiguous()\n                    # Flatten the tokens\n                    shift_logits = shift_logits.view(-1, self.model.config.vocab_size)\n                    shift_labels = shift_labels.view(-1)\n                    # Enable model parallelism\n                    shift_labels = shift_labels.to(shift_logits.device)\n                    loss = loss_fct(shift_logits, shift_labels)\n                    loss = loss * loss_mask.to(loss.device)\n                else:\n                    # IMPORTANT: We have a big assumption here, so we can shard the SAME sequence across SP ranks\n                    # i.e., each GPU has <1 sequence, and each SP group has 1 sequence\n                    # 1. All SP ranks will receive the *SAME* batch\n                    # 2. Different SP groups will receive *DIFFERENT* batches\n                    # This is implemented by the DistributedSampler\n\n                    batch_size, seqlen = input_ids.shape\n                    # Remove padding\n                    input_ids_rmpad, indices, *_ = unpad_input(input_ids.unsqueeze(-1),\n                                                               attention_mask)  # input_ids_rmpad (total_nnz, ...)\n                    input_ids_rmpad = input_ids_rmpad.transpose(0, 1)  # (1, total_nnz)\n\n                    # Unpad position_ids to align rotary\n                    position_ids_rmpad = index_first_axis(rearrange(position_ids.unsqueeze(-1), \"b s ... -> (b s) ...\"),\n                                                          indices).transpose(0, 1)\n\n                    # Pad and slice inputs for sequence parallelism\n                    input_ids_rmpad_sliced, position_ids_rmpad_padded, pad_size = ulysses_pad_and_slice_inputs(\n                        input_ids_rmpad, position_ids_rmpad, sp_size=get_ulysses_sequence_parallel_world_size())\n                    # For computing loss\n                    input_ids_rmpad_rolled = torch.roll(input_ids_rmpad, shifts=-1, dims=1)  # (1, total_nnz)\n                    input_ids_rmpad_rolled, _, _ = ulysses_pad_and_slice_inputs(\n                        input_ids_rmpad_rolled, None, get_ulysses_sequence_parallel_world_size())\n                    input_ids_rmpad_rolled = input_ids_rmpad_rolled.squeeze(0)  # ((total_nnz / sp) + pad)\n\n                    # Forward pass\n                    output = self.fsdp_model(\n                        input_ids=input_ids_rmpad_sliced,\n                        attention_mask=None,  # Not needed with flash attention varlen\n                        position_ids=position_ids_rmpad_padded,\n                        use_cache=False)\n\n                    # Compute loss locally then aggregate\n                    logits_rmpad = output.logits.squeeze(0)\n                    input_ids_rmpad_rolled = input_ids_rmpad_rolled.to(logits_rmpad.device)\n                    loss = loss_fct(logits_rmpad, input_ids_rmpad_rolled)\n                    # Gather and unpad for sequence parallelism\n                    loss = gather_outpus_and_unpad(loss, gather_dim=0, unpad_dim=0, padding_size=pad_size)\n\n                    # This is the loss collected from all ulysses ranks\n                    full_loss = pad_input(hidden_states=loss.unsqueeze(-1),\n                                          indices=indices,\n                                          batch=batch_size,\n                                          seqlen=seqlen)\n                    full_loss = full_loss.squeeze(-1)[:, :-1]  # Remove last token's loss\n                    full_loss = full_loss.reshape(-1)\n                    loss_mask = loss_mask.to(full_loss.device)\n                    loss = full_loss * loss_mask\n\n                valid_token_this_rank = torch.sum(loss_mask)\n\n                if self.config.data.balance_dp_token:\n                    torch.distributed.all_reduce(valid_token_this_rank)\n                    dp_size = self.ulysses_device_mesh.size('dp') if use_sp else torch.distributed.get_world_size()\n                else:\n                    dp_size = 1\n\n                loss = torch.sum(loss) / valid_token_this_rank * dp_size\n\n                if do_backward:\n                    loss.backward()\n                return loss\n\n    def training_step(self, batch: TensorDict):\n        self.fsdp_model.train()\n\n        log_gpu_memory_usage('Before optimizer zero_grad', logger=logger)\n\n        self.optimizer.zero_grad()\n\n        log_gpu_memory_usage('After optimizer zero_grad', logger=logger)\n\n        micro_batches = batch.split(self.config.data.micro_batch_size_per_gpu)\n        n_micro_batches = len(micro_batches)\n        step_loss = 0\n        for micro_batch in micro_batches:\n            loss = self._compute_loss_and_backward(batch=micro_batch) / n_micro_batches\n            step_loss += loss.item()\n\n        self.fsdp_model.clip_grad_norm_(max_norm=self.config.optim.clip_grad)\n\n        log_gpu_memory_usage('Before optimizer step', logger=logger)\n\n        self.optimizer.step()\n\n        log_gpu_memory_usage('After optimizer step', logger=logger)\n\n        self.lr_scheduler.step()\n\n        # reduce loss across dp ranks\n        lr = self.lr_scheduler.get_last_lr()[0]\n\n        log_gpu_memory_usage('After offload weights', logger=logger)\n\n        step_loss = torch.tensor(step_loss).cuda()\n        torch.distributed.all_reduce(step_loss, op=torch.distributed.ReduceOp.AVG)\n        return {'train/loss': step_loss.detach().item(), 'train/lr(1e-3)': lr * 1e3}\n\n    def validation_step(self, batch: TensorDict):\n        self.fsdp_model.eval()\n        with torch.no_grad():\n            loss = self._compute_loss_and_backward(batch, do_backward=False)\n            torch.distributed.all_reduce(loss, op=torch.distributed.ReduceOp.AVG)\n        return loss\n\n    def save_checkpoint(self, step):\n        # save checkpoint\n        from torch.distributed.fsdp import FullStateDictConfig, StateDictType\n        cfg = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)\n        with FSDP.state_dict_type(self.fsdp_model, StateDictType.FULL_STATE_DICT, cfg):\n            state_dict = self.fsdp_model.state_dict()\n\n        path = os.path.join(self.config.trainer.default_local_dir, f'global_step_{step}')\n        # save huggingface model\n        if self.device_mesh.get_rank() == 0:\n            os.makedirs(path, exist_ok=True)\n            self.model.save_pretrained(path, state_dict=state_dict)\n            self.tokenizer.save_pretrained(path)\n            if self.config.trainer.default_hdfs_dir:\n                hdfs_io.makedirs(self.config.trainer.default_hdfs_dir, exist_ok=True)\n                hdfs_io.copy(src=path, dst=self.config.trainer.default_hdfs_dir, dirs_exist_ok=True)\n        torch.distributed.barrier()\n\n    def fit(self):\n        rank = self.device_mesh.get_rank()\n\n        # TODO: add a unified tracking\n        if rank == 0:\n            tracking = Tracking(project_name=self.config.trainer.project_name,\n                                experiment_name=self.config.trainer.experiment_name,\n                                default_backend=self.config.trainer.logger)\n\n        global_step = 0\n        # compute the total training steps.\n        # the total training steps in SFT is mainly for early exit\n        total_training_steps = len(self.train_dataloader) * self.config.trainer.total_epochs\n\n        if self.config.trainer.total_training_steps is not None:\n            total_training_steps = self.config.trainer.total_training_steps\n\n        self.total_training_steps = total_training_steps\n        print(f'Total training steps: {self.total_training_steps}')\n\n        # TODO (zhangchi.usc1992) add back checkpoint manager. Currently, it blocks when uploading to hdfs. So very slow.\n\n        for epoch in range(self.config.trainer.total_epochs):\n            self.train_sampler.set_epoch(epoch=epoch)\n            for data in tqdm(self.train_dataloader,\n                             total=self.steps_per_epoch,\n                             desc=f\"Epoch {epoch+1}/{self.config.trainer.total_epochs}\"):\n                data = TensorDict(data, batch_size=self.config.data.train_batch_size).cuda()\n                metric = self.training_step(data)\n                if rank == 0:\n                    tracking.log(data=metric, step=global_step)\n                global_step += 1\n\n                # for early exit validation\n                if global_step >= self.total_training_steps:\n                    # Perform final validation\n                    val_losses = []\n                    for val_data in self.val_dataloader:\n                        val_data = TensorDict(val_data, batch_size=self.config.data.micro_batch_size_per_gpu).cuda()\n                        val_loss = self.validation_step(val_data)\n                        val_losses.append(val_loss)\n                    if rank == 0:\n                        avg_val_loss = torch.mean(torch.stack(val_losses))\n                        metric = {'val/loss': avg_val_loss.detach().item()}\n                        tracking.log(data=metric, step=global_step)\n                    torch.distributed.barrier()\n\n                    # Save final checkpoint\n                    self.save_checkpoint(step=global_step)\n                    return\n\n            # validation\n            val_losses = []\n            for data in self.val_dataloader:\n                data = TensorDict(data, batch_size=self.config.data.micro_batch_size_per_gpu).cuda()\n                val_loss = self.validation_step(data)\n                val_losses.append(val_loss)\n            if rank == 0:\n                val_loss = torch.mean(torch.stack(val_losses))\n                metric = {'val/loss': val_loss.detach().item()}\n                tracking.log(data=metric, step=global_step)\n            torch.distributed.barrier()\n\n            # save checkpoint\n            self.save_checkpoint(step=global_step)\n\n\nfrom verl.trainer.fsdp_sft_trainer import FSDPSFTTrainer\nimport hydra\n\nfrom torch.distributed.device_mesh import init_device_mesh\n\nfrom verl.utils.distributed import initialize_global_process_group\n\n\n@hydra.main(config_path='config', config_name='sft_trainer', version_base=None)\ndef main(config):\n    local_rank, rank, world_size = initialize_global_process_group()\n\n    device_mesh = init_device_mesh(device_type='cuda', mesh_shape=(world_size,), mesh_dim_names=('fsdp',))\n    dp_size = world_size // config.ulysses_sequence_parallel_size\n    ulysses_device_mesh = init_device_mesh(device_type='cuda',\n                                           mesh_shape=(dp_size, config.ulysses_sequence_parallel_size),\n                                           mesh_dim_names=('dp', 'sp'))\n    trainer = FSDPSFTTrainer(config=config, device_mesh=device_mesh, ulysses_device_mesh=ulysses_device_mesh)\n    trainer.fit()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "verl/trainer/main_eval.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nOffline evaluate the performance of a generated file using reward model and ground truth verifier.\nThe input is a parquet file that contains N generated sequences and (optional) the ground truth.\n\n\"\"\"\n\nimport hydra\nfrom verl.utils.fs import copy_to_local\nfrom verl.utils.reward_score import math, gsm8k\nimport pandas as pd\nimport numpy as np\n\n\ndef select_reward_fn(data_source):\n    if data_source == 'lighteval/MATH':\n        return math.compute_score\n    else:\n        raise NotImplementedError\n\n\n@hydra.main(config_path='config', config_name='evaluation', version_base=None)\ndef main(config):\n    local_path = copy_to_local(config.data.path)\n    dataset = pd.read_parquet(local_path)\n    prompts = dataset[config.data.prompt_key]\n    responses = dataset[config.data.response_key]\n    data_sources = dataset[config.data.data_source_key]\n    reward_model_data = dataset[config.data.reward_model_key]\n\n    passes = 0\n\n    total = len(dataset)\n\n    for i in range(total):\n        response_lst = responses[i]\n        data_source = data_sources[i]\n        # select reward score based on data_source\n        prompt = prompts[i]\n        reward_data = reward_model_data[i]\n        reward_fn = select_reward_fn(data_source)\n        ground_truth = reward_data['ground_truth']\n        score_lst = []\n        for r in response_lst:\n            score = reward_fn(r, ground_truth)\n            score_lst.append(score)\n\n        max_score = np.max(score_lst)\n\n        if max_score == 1:\n            passes += 1\n\n    print(f'pass@5: {passes / total}')\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "verl/trainer/main_generation.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nGenerate responses given a dataset of prompts\n\"\"\"\nimport ray\nimport numpy as np\nimport hydra\nimport os\n\nos.environ['NCCL_DEBUG'] = 'WARN'\nos.environ['TOKENIZERS_PARALLELISM'] = 'true'\n# os.environ['TORCH_COMPILE_DISABLE'] = '1'\n\nfrom verl.utils.model import compute_position_id_with_mask\n\nimport pandas as pd\n\nfrom transformers import AutoTokenizer\n\nfrom verl import DataProto\nfrom verl.utils.fs import copy_to_local\nfrom verl.workers.fsdp_workers import ActorRolloutRefWorker\nfrom verl.utils.hdfs_io import makedirs\nfrom verl.single_controller.ray import RayClassWithInitArgs, RayResourcePool, RayWorkerGroup\n\n\n@hydra.main(config_path='config', config_name='generation', version_base=None)\ndef main(config):\n    from pprint import pprint\n    from omegaconf import OmegaConf\n    pprint(OmegaConf.to_container(config, resolve=True))  # resolve=True will eval symbol values\n    OmegaConf.resolve(config)\n    local_path = copy_to_local(config.model.path)\n    from verl.utils import hf_tokenizer\n    tokenizer = hf_tokenizer(local_path)\n\n    if config.rollout.temperature == 0.:\n        assert config.data.n_samples == 1, 'When temperature=0, n_samples must be 1.'\n\n    # read dataset. Note that the dataset should directly contain chat template format (e.g., a list of dictionary)\n    dataset = pd.read_parquet(config.data.path)\n    chat_lst = dataset[config.data.prompt_key].tolist()\n\n    chat_lst = [chat.tolist() for chat in chat_lst]\n\n    tokenizer.padding_side = 'left'\n    if tokenizer.pad_token is None:\n        tokenizer.pad_token = tokenizer.eos_token\n\n    ray_cls_with_init = RayClassWithInitArgs(cls=ray.remote(ActorRolloutRefWorker), config=config, role='actor_rollout')\n    resource_pool = RayResourcePool(process_on_nodes=[config.trainer.n_gpus_per_node] * config.trainer.nnodes)\n    wg = RayWorkerGroup(resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init)\n    wg.init_model()\n\n    total_samples = len(dataset)\n    # real_batch_size = data.batch['input_ids'].shape[0]\n    config_batch_size = config.data.batch_size\n    dp_size = wg.world_size // config.rollout.tensor_model_parallel_size\n    num_batch = (total_samples // config_batch_size) + 1\n    output_lst = [[] for _ in range(config.data.n_samples)]\n\n    for batch_idx in range(num_batch):\n        print(f'[{batch_idx+1}/{num_batch}] Start to process.')\n        batch_chat_lst = chat_lst[batch_idx * config_batch_size:(batch_idx + 1) * config_batch_size]\n        inputs = tokenizer.apply_chat_template(batch_chat_lst,\n                                               add_generation_prompt=True,\n                                               padding=True,\n                                               truncation=True,\n                                               max_length=config.rollout.prompt_length,\n                                               return_tensors='pt',\n                                               return_dict=True,\n                                               tokenize=True)\n        input_ids = inputs['input_ids']\n        attention_mask = inputs['attention_mask']\n        position_ids = compute_position_id_with_mask(attention_mask)\n\n        batch_dict = {'input_ids': input_ids, 'attention_mask': attention_mask, 'position_ids': position_ids}\n\n        data = DataProto.from_dict(batch_dict)\n        real_batch_size = data.batch['input_ids'].shape[0]\n        if real_batch_size % dp_size != 0:\n            dummy_data_size = dp_size - real_batch_size % dp_size\n            dummy_data = data[:dummy_data_size]\n            data = DataProto.concat([data, dummy_data])\n            print(\n                f'dp_size {dp_size} is not divisible by real_batch_size {real_batch_size}, add {dummy_data_size} dummy data'\n            )\n\n        batch_size = data.batch['input_ids'].shape[0]\n        assert batch_size % dp_size == 0, f'batch_size {batch_size} is not divisible by dp_size {dp_size}'\n\n        print(f'[{batch_idx+1}/{num_batch}] Start to generate.')\n        # START TO GENERATE FOR n_samples TIMES\n        for i in range(config.data.n_samples):\n            output = wg.generate_sequences(data)\n            # remove dummy data\n            output = output[:real_batch_size]\n            output_text = tokenizer.batch_decode(output.batch['input_ids'][:, -config.rollout.response_length:],\n                                                 skip_special_tokens=False)\n\n            # remove the padding\n            pad_token = tokenizer.pad_token\n            output_text_unpad = []\n            for text in output_text:\n                output_text_unpad.append(text.replace(pad_token, ''))\n\n            output_lst[i].extend(output_text_unpad)\n\n    # convert output_lst from (n_samples, n_data) to (n_data, n_sampels)\n    output_lst = np.array(output_lst, dtype=object)\n    output_lst = np.transpose(output_lst, axes=(1, 0)).tolist()\n\n    # add to the data frame\n    dataset[f'responses'] = output_lst\n\n    # write to a new parquet\n    output_dir = os.path.dirname(config.data.output_path)\n    makedirs(output_dir, exist_ok=True)\n    dataset.to_parquet(config.data.output_path)\n\n    return output_text\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "verl/trainer/main_ppo.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nNote that we don't combine the main with ray_trainer as ray_trainer is used by other main.\n\"\"\"\nfrom verl.trainer.ppo.ray_trainer import RayPPOTrainer\n\nimport ray\nimport hydra\n\n\n@hydra.main(config_path='config', config_name='ppo_trainer', version_base=None)\ndef main(config):\n    run_ppo(config)\n\n\ndef run_ppo(config, compute_score=None):\n    if not ray.is_initialized():\n        # this is for local ray cluster\n        ray.init(runtime_env={'env_vars': {'TOKENIZERS_PARALLELISM': 'true', 'NCCL_DEBUG': 'WARN'}})\n\n    ray.get(main_task.remote(config, compute_score))\n\n\n@ray.remote(num_cpus=1)  # please make sure main_task is not scheduled on head\ndef main_task(config, compute_score=None):\n    from verl.utils.fs import copy_to_local\n    # print initial config\n    from pprint import pprint\n    from omegaconf import OmegaConf\n    pprint(OmegaConf.to_container(config, resolve=True))  # resolve=True will eval symbol values\n    OmegaConf.resolve(config)\n\n    # download the checkpoint from hdfs\n    local_path = copy_to_local(config.actor_rollout_ref.model.path)\n\n    # instantiate tokenizer\n    from verl.utils import hf_tokenizer, hf_processor\n    tokenizer = hf_tokenizer(local_path)\n    processor = hf_processor(local_path, use_fast=True)  # used for multimodal LLM, could be none\n\n    # define worker classes\n    if config.actor_rollout_ref.actor.strategy == 'fsdp':\n        assert config.actor_rollout_ref.actor.strategy == config.critic.strategy\n        from verl.workers.fsdp_workers import ActorRolloutRefWorker, CriticWorker\n        from verl.single_controller.ray import RayWorkerGroup\n        ray_worker_group_cls = RayWorkerGroup\n\n    elif config.actor_rollout_ref.actor.strategy == 'megatron':\n        assert config.actor_rollout_ref.actor.strategy == config.critic.strategy\n        from verl.workers.megatron_workers import ActorRolloutRefWorker, CriticWorker\n        from verl.single_controller.ray.megatron import NVMegatronRayWorkerGroup\n        ray_worker_group_cls = NVMegatronRayWorkerGroup\n\n    else:\n        raise NotImplementedError\n\n    from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role\n\n    role_worker_mapping = {\n        Role.ActorRollout: ray.remote(ActorRolloutRefWorker),\n        Role.Critic: ray.remote(CriticWorker),\n    }\n    if not (config.actor_rollout_ref.actor.kl_loss_coef==0 and config.algorithm.kl_ctrl.kl_coef==0):\n        role_worker_mapping[Role.RefPolicy] = ray.remote(ActorRolloutRefWorker)\n    else:\n        config.actor_rollout_ref.actor.use_kl_loss=False\n\n    global_pool_id = 'global_pool'\n    resource_pool_spec = {\n        global_pool_id: [config.trainer.n_gpus_per_node] * config.trainer.nnodes,\n    }\n    mapping = {\n        Role.ActorRollout: global_pool_id,\n        Role.Critic: global_pool_id,\n        Role.RefPolicy: global_pool_id,\n    }\n\n    # we should adopt a multi-source reward function here\n    # - for rule-based rm, we directly call a reward score\n    # - for model-based rm, we call a model\n    # - for code related prompt, we send to a sandbox if there are test cases\n    # - finally, we combine all the rewards together\n    # - The reward type depends on the tag of the data\n    if config.reward_model.enable:\n        if config.reward_model.strategy == 'fsdp':\n            from verl.workers.fsdp_workers import RewardModelWorker\n        elif config.reward_model.strategy == 'megatron':\n            from verl.workers.megatron_workers import RewardModelWorker\n        else:\n            raise NotImplementedError\n        role_worker_mapping[Role.RewardModel] = ray.remote(RewardModelWorker)\n        mapping[Role.RewardModel] = global_pool_id\n\n    reward_manager_name = config.reward_model.get(\"reward_manager\", \"naive\")\n    if reward_manager_name == 'naive':\n        from verl.workers.reward_manager import NaiveRewardManager\n        reward_manager_cls = NaiveRewardManager\n    elif reward_manager_name == 'prime':\n        from verl.workers.reward_manager import PrimeRewardManager\n        reward_manager_cls = PrimeRewardManager\n    else:\n        raise NotImplementedError\n    reward_fn = reward_manager_cls(config=config, tokenizer=tokenizer, num_examine=0, compute_score=compute_score)\n\n    # Note that we always use function-based RM for validation\n    val_reward_fn = reward_manager_cls(config=config, tokenizer=tokenizer, num_examine=1, compute_score=compute_score)\n\n    resource_pool_manager = ResourcePoolManager(resource_pool_spec=resource_pool_spec, mapping=mapping)\n\n    trainer = RayPPOTrainer(config=config,\n                            tokenizer=tokenizer,\n                            processor=processor,\n                            role_worker_mapping=role_worker_mapping,\n                            resource_pool_manager=resource_pool_manager,\n                            ray_worker_group_cls=ray_worker_group_cls,\n                            reward_fn=reward_fn,\n                            val_reward_fn=val_reward_fn)\n    trainer.init_workers()\n    trainer.fit()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "verl/trainer/ppo/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/trainer/ppo/core_algos.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nCore functions to implement PPO algorithms.\nThe function implemented in this file should be used by trainer with different distributed strategies to\nimplement PPO\n\"\"\"\n\nimport numpy as np\nimport torch\nfrom collections import defaultdict\n\nimport verl.utils.torch_functional as verl_F\n\n\nclass AdaptiveKLController:\n    \"\"\"\n    Adaptive KL controller described in the paper:\n    https://arxiv.org/pdf/1909.08593.pdf\n    \"\"\"\n\n    def __init__(self, init_kl_coef, target_kl, horizon):\n        self.value = init_kl_coef\n        self.target = target_kl\n        self.horizon = horizon\n\n    def update(self, current_kl, n_steps):\n        target = self.target\n        proportional_error = np.clip(current_kl / target - 1, -0.2, 0.2)\n        mult = 1 + proportional_error * n_steps / self.horizon\n        self.value *= mult\n\n\nclass FixedKLController:\n    \"\"\"Fixed KL controller.\"\"\"\n\n    def __init__(self, kl_coef):\n        self.value = kl_coef\n\n    def update(self, current_kl, n_steps):\n        pass\n\n\ndef get_kl_controller(config):\n    if config.critic.kl_ctrl.type == 'fixed':\n        kl_ctrl = FixedKLController(kl_coef=config.critic.kl_ctrl.kl_coef)\n    elif config.critic.kl_ctrl.type == 'adaptive':\n        assert config.kl_ctrl.horizon > 0, f'horizon must be larger than 0. Got {config.critic.kl_ctrl.horizon}'\n        kl_ctrl = AdaptiveKLController(init_kl_coef=config.critic.kl_ctrl.kl_coef,\n                                       target_kl=config.critic.kl_ctrl.target_kl,\n                                       horizon=config.critic.kl_ctrl.horizon)\n    else:\n        raise ValueError('Unknown kl_ctrl type')\n\n    return kl_ctrl\n\n\ndef compute_gae_advantage_return(token_level_rewards: torch.Tensor, values: torch.Tensor, eos_mask: torch.Tensor,\n                                 gamma: torch.Tensor, lam: torch.Tensor):\n    \"\"\"Adapted from https://github.com/huggingface/trl/blob/main/trl/trainer/ppo_trainer.py\n\n    Args:\n        token_level_rewards: `(torch.Tensor)`\n            shape: (bs, response_length)\n        values: `(torch.Tensor)`\n            shape: (bs, response_length)\n        eos_mask: `(torch.Tensor)`\n            shape: (bs, response_length). [EOS] mask. The token after [EOS] have mask zero.\n        gamma: `(float)`\n            discounted factor used in RL\n        lam: `(float)`\n            lambda value when computing Generalized Advantage Estimation (https://arxiv.org/abs/1506.02438)\n\n    Returns:\n        advantages: `(torch.Tensor)`\n            shape: (bs, response_length)\n        Returns: `(torch.Tensor)`\n            shape: (bs, response_length)\n\n    \"\"\"\n    with torch.no_grad():\n        lastgaelam = 0\n        advantages_reversed = []\n        gen_len = token_level_rewards.shape[-1]\n\n        for t in reversed(range(gen_len)):\n            nextvalues = values[:, t + 1] if t < gen_len - 1 else 0.0\n            delta = token_level_rewards[:, t] + gamma * nextvalues - values[:, t]\n            lastgaelam = delta + gamma * lam * lastgaelam\n            advantages_reversed.append(lastgaelam)\n        advantages = torch.stack(advantages_reversed[::-1], dim=1)\n\n        returns = advantages + values\n        advantages = verl_F.masked_whiten(advantages, eos_mask)\n    return advantages, returns\n\n\n# NOTE(sgm): this implementation only consider outcome supervision, where the reward is a scalar.\ndef compute_grpo_outcome_advantage(token_level_rewards: torch.Tensor,\n                                   eos_mask: torch.Tensor,\n                                   index: torch.Tensor,\n                                   epsilon: float = 1e-6):\n    \"\"\"\n    Compute advantage for GRPO, operating only on Outcome reward \n    (with only one scalar reward for each response).\n    Args:\n        token_level_rewards: `(torch.Tensor)`\n            shape: (bs, response_length)\n        eos_mask: `(torch.Tensor)`\n            shape: (bs, response_length)\n    \n    Returns:\n        advantages: `(torch.Tensor)`\n            shape: (bs, response_length)\n        Returns: `(torch.Tensor)`\n            shape: (bs, response_length)\n    \"\"\"\n    response_length = token_level_rewards.shape[-1]\n    scores = token_level_rewards.sum(dim=-1)\n\n    id2score = defaultdict(list)\n    id2mean = {}\n    id2std = {}\n\n    with torch.no_grad():\n        bsz = scores.shape[0]\n        for i in range(bsz):\n            id2score[index[i]].append(scores[i])\n        for idx in id2score:\n            if len(id2score[idx]) == 1:\n                id2mean[idx] = torch.tensor(0.0)\n                id2std[idx] = torch.tensor(1.0)\n            elif len(id2score[idx]) > 1:\n                id2mean[idx] = torch.mean(torch.tensor(id2score[idx]))\n                id2std[idx] = torch.std(torch.tensor([id2score[idx]]))\n            else:\n                raise ValueError(f\"no score in prompt index: {idx}\")\n        for i in range(bsz):\n            scores[i] = (scores[i] - id2mean[index[i]]) / (id2std[index[i]] + epsilon)\n        scores = scores.unsqueeze(-1).tile([1, response_length]) * eos_mask\n\n    return scores, scores\n\n\ndef compute_rloo_outcome_advantage(token_level_rewards: torch.Tensor,\n                                   eos_mask: torch.Tensor,\n                                   index: torch.Tensor,\n                                   epsilon: float = 1e-6):\n    \"\"\"\n    Compute advantage for RLOO based on https://arxiv.org/abs/2402.14740\n    Args:\n        token_level_rewards: `(torch.Tensor)`\n            shape: (bs, response_length)\n        eos_mask: `(torch.Tensor)`\n            shape: (bs, response_length)\n\n    Returns:\n        advantages: `(torch.Tensor)`\n            shape: (bs, response_length)\n        Returns: `(torch.Tensor)`\n            shape: (bs, response_length)\n    \"\"\"\n    response_length = token_level_rewards.shape[-1]\n    scores = token_level_rewards.sum(dim=-1)\n\n    id2score = defaultdict(list)\n    id2mean = {}\n\n    with torch.no_grad():\n        bsz = scores.shape[0]\n        for i in range(bsz):\n            id2score[index[i]].append(scores[i])\n        for idx in id2score:\n            if len(id2score[idx]) == 1:\n                id2mean[idx] = torch.tensor(0.0)\n            elif len(id2score[idx]) > 1:\n                id2mean[idx] = torch.mean(torch.tensor(id2score[idx]))\n            else:\n                raise ValueError(f\"no score in prompt index: {idx}\")\n        for i in range(bsz):\n            response_num = len(id2score[index[i]])\n            if response_num > 1:\n                scores[i] = scores[i] * response_num / (response_num -\n                                                        1) - id2mean[index[i]] * response_num / (response_num - 1)\n        scores = scores.unsqueeze(-1).tile([1, response_length]) * eos_mask\n\n    return scores, scores\n\n\ndef compute_reinforce_plus_plus_outcome_advantage(token_level_rewards: torch.Tensor, eos_mask: torch.Tensor,\n                                                  gamma: torch.Tensor):\n    \"\"\"\n    Compute advantage for REINFORCE++. \n    This implementation is based on the paper: https://arxiv.org/abs/2501.03262\n    Args:\n        token_level_rewards: `(torch.Tensor)`\n            shape: (bs, response_length)\n        eos_mask: `(torch.Tensor)`\n            shape: (bs, response_length)\n    \n    Returns:\n        advantages: `(torch.Tensor)`\n            shape: (bs, response_length)\n        Returns: `(torch.Tensor)`\n            shape: (bs, response_length)\n    \"\"\"\n\n    with torch.no_grad():\n        returns = torch.zeros_like(token_level_rewards)\n        running_return = 0\n\n        for t in reversed(range(token_level_rewards.shape[1])):\n            running_return = token_level_rewards[:, t] + gamma * running_return\n            returns[:, t] = running_return\n            # Reset after EOS\n            running_return = running_return * eos_mask[:, t]\n\n        advantages = verl_F.masked_whiten(returns, eos_mask)\n        advantages = advantages * eos_mask\n\n    return advantages, returns\n\n\ndef compute_remax_outcome_advantage(token_level_rewards: torch.Tensor, reward_baselines: torch.Tensor,\n                                    eos_mask: torch.Tensor):\n    \"\"\"\n    Compute advantage for ReMax, operating only on Outcome reward \n    This implementation is based on the paper: https://arxiv.org/abs/2310.10505\n\n    (with only one scalar reward for each response).\n    Args:\n        token_level_rewards: `(torch.Tensor)`\n            shape: (bs, response_length)\n        reward_baselines: `(torch.Tensor)`\n            shape: (bs,)\n        eos_mask: `(torch.Tensor)`\n            shape: (bs, response_length)\n    \n    Returns:\n        advantages: `(torch.Tensor)`\n            shape: (bs, response_length)\n        Returns: `(torch.Tensor)`\n            shape: (bs, response_length)\n    \"\"\"\n    response_length = token_level_rewards.shape[-1]\n    scores = token_level_rewards.sum(dim=-1)\n\n    with torch.no_grad():\n        returns = (token_level_rewards * eos_mask).flip(dims=[-1]).cumsum(dim=-1).flip(dims=[-1])\n        advantages = returns - reward_baselines.unsqueeze(-1).tile([1, response_length]) * eos_mask\n\n    return advantages, returns\n\n\ndef compute_rewards(token_level_scores, old_log_prob, ref_log_prob, kl_ratio):\n    kl = old_log_prob - ref_log_prob\n    return token_level_scores - kl * kl_ratio\n\n\ndef compute_policy_loss(old_log_prob, log_prob, advantages, eos_mask, cliprange):\n    \"\"\"Adapted from https://github.com/huggingface/trl/blob/main/trl/trainer/ppo_trainer.py#L1122\n\n    Args:\n        old_log_prob: `(torch.Tensor)`\n            shape: (bs, response_length)\n        log_prob: `(torch.Tensor)`\n            shape: (bs, response_length)\n        advantages: `(torch.Tensor)`\n            shape: (bs, response_length)\n        eos_mask: `(torch.Tensor)`\n            shape: (bs, response_length)\n        cliprange: (float)\n            The clip range used in PPO. See https://arxiv.org/abs/1707.06347\n\n    Returns:\n        pg_loss: `a scalar torch.Tensor`\n            policy gradient loss computed via PPO\n        pg_clipfrac: (float)\n            a float number indicating the fraction of policy gradient loss being clipped\n\n    \"\"\"\n    negative_approx_kl = log_prob - old_log_prob\n    ratio = torch.exp(negative_approx_kl)\n    ppo_kl = verl_F.masked_mean(-negative_approx_kl, eos_mask)\n\n    pg_losses = -advantages * ratio\n    pg_losses2 = -advantages * torch.clamp(ratio, 1.0 - cliprange, 1.0 + cliprange)\n\n    pg_loss = verl_F.masked_mean(torch.max(pg_losses, pg_losses2), eos_mask)\n    pg_clipfrac = verl_F.masked_mean(torch.gt(pg_losses2, pg_losses).float(), eos_mask)\n    return pg_loss, pg_clipfrac, ppo_kl\n\n\ndef compute_entropy_loss(logits, eos_mask):\n    \"\"\"Compute Categorical entropy loss\n\n    Args:\n        logits: `(torch.Tensor)`\n            shape: (bs, response_length, vocab_size)\n        eos_mask: `(torch.Tensor)`\n            shape: (bs, response_length)\n\n    Returns:\n        entropy: a scalar torch.Tensor\n\n    \"\"\"\n    # compute entropy\n    entropy = verl_F.entropy_from_logits(logits)  # (bs, response_len)\n    entropy_loss = verl_F.masked_mean(entropy, mask=eos_mask)\n    return entropy_loss\n\n\ndef compute_value_loss(vpreds, returns, values, eos_mask, cliprange_value):\n    \"\"\"Compute the value loss. Copied from https://github.com/huggingface/trl/blob/main/trl/trainer/ppo_trainer.py#L1151\n\n    Args:\n        vpreds (`torch.FloatTensor`):\n            Predicted values of the value head, shape (`batch_size`, `response_length`)\n        values (`torch.FloatTensor`):\n            Old values of value head, shape (`batch_size`, `response_length`)\n        returns: (`torch.FloatTensor`):\n            Ground truth returns, shape (`batch_size`, `response_length`)\n\n    Returns:\n        vf_loss: a scalar (`torch.FloatTensor`):\n            value function loss\n        vf_clipfrac: a float\n            The ratio of vf being clipped\n\n    \"\"\"\n    vpredclipped = verl_F.clip_by_value(vpreds, values - cliprange_value, values + cliprange_value)\n    vf_losses1 = (vpreds - returns)**2\n    vf_losses2 = (vpredclipped - returns)**2\n    vf_loss = 0.5 * verl_F.masked_mean(torch.max(vf_losses1, vf_losses2), eos_mask)\n    vf_clipfrac = verl_F.masked_mean(torch.gt(vf_losses2, vf_losses1).float(), eos_mask)\n    return vf_loss, vf_clipfrac\n\n\ndef kl_penalty(logprob: torch.FloatTensor, ref_logprob: torch.FloatTensor, kl_penalty) -> torch.FloatTensor:\n    \"\"\"Compute KL divergence given logprob and ref_logprob.\n    Copied from https://github.com/huggingface/trl/blob/main/trl/trainer/ppo_trainer.py#L1104\n\n    Args:\n        logprob:\n        ref_logprob:\n\n    Returns:\n\n    \"\"\"\n    if kl_penalty == \"kl\":\n        return logprob - ref_logprob\n\n    if kl_penalty == \"abs\":\n        return (logprob - ref_logprob).abs()\n\n    if kl_penalty == \"mse\":\n        return 0.5 * (logprob - ref_logprob).square()\n\n    # J. Schulman. Approximating kl divergence, 2020.\n    # # URL http://joschu.net/blog/kl-approx.html.\n    if kl_penalty == 'low_var_kl':\n        kl = ref_logprob - logprob\n        ratio = torch.exp(kl)\n        kld = (ratio - kl - 1).contiguous()\n        return torch.clamp(kld, min=-10, max=10)\n\n    if kl_penalty == \"full\":\n        # so, here logprob and ref_logprob should contain the logits for every token in vocabulary\n        raise NotImplementedError\n\n    raise NotImplementedError\n"
  },
  {
    "path": "verl/trainer/ppo/ray_trainer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nFSDP PPO Trainer with Ray-based single controller.\nThis trainer supports model-agonistic model initialization with huggingface\n\"\"\"\n\nimport os\nimport uuid\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom pprint import pprint\nfrom typing import Type, Dict\nfrom copy import deepcopy\nimport json\n\nimport numpy as np\nfrom codetiming import Timer\nfrom omegaconf import OmegaConf, open_dict\nfrom verl import DataProto\nfrom verl.protocol import pad_dataproto_to_divisor, unpad_dataproto\nfrom verl.single_controller.base import Worker\nfrom verl.single_controller.ray import RayResourcePool, RayWorkerGroup, RayClassWithInitArgs\nfrom verl.single_controller.ray.base import create_colocated_worker_cls\nfrom verl.trainer.ppo import core_algos\nfrom verl.utils.seqlen_balancing import get_seqlen_balanced_partitions, log_seqlen_unbalance\nfrom verl.utils.checkpoint.checkpoint_manager import find_latest_ckpt_path\nfrom verl.utils.dataset.rl_dataset import RLHFDataset, collate_fn\nfrom torch.utils.data import RandomSampler, SequentialSampler\nfrom torchdata.stateful_dataloader import StatefulDataLoader\n\nWorkerType = Type[Worker]\n\n\nclass Role(Enum):\n    \"\"\"\n    To create more roles dynamically, you can subclass Role and add new members\n    \"\"\"\n    Actor = 0\n    Rollout = 1\n    ActorRollout = 2\n    Critic = 3\n    RefPolicy = 4\n    RewardModel = 5\n    ActorRolloutRef = 6\n\n\nclass AdvantageEstimator(str, Enum):\n    \"\"\"\n    Using an enumeration class to avoid spelling errors in adv_estimator\n    \"\"\"\n    GAE = 'gae'\n    GRPO = 'grpo'\n    REINFORCE_PLUS_PLUS = 'reinforce_plus_plus'\n    REMAX = 'remax'\n    RLOO = 'rloo'\n\n\n@dataclass\nclass ResourcePoolManager:\n    \"\"\"\n    Define a resource pool specification. Resource pool will be initialized first.\n    Mapping\n    \"\"\"\n    resource_pool_spec: dict[str, list[int]]\n    mapping: dict[Role, str]\n    resource_pool_dict: dict[str, RayResourcePool] = field(default_factory=dict)\n\n    def create_resource_pool(self):\n        for resource_pool_name, process_on_nodes in self.resource_pool_spec.items():\n            # max_colocate_count means the number of WorkerGroups (i.e. processes) in each RayResourcePool\n            # For FSDP backend, we recommend using max_colocate_count=1 that merge all WorkerGroups into one.\n            # For Megatron backend, we recommend using max_colocate_count>1 that can utilize different WorkerGroup for differnt models\n            resource_pool = RayResourcePool(process_on_nodes=process_on_nodes,\n                                            use_gpu=True,\n                                            max_colocate_count=1,\n                                            name_prefix=resource_pool_name)\n            self.resource_pool_dict[resource_pool_name] = resource_pool\n\n    def get_resource_pool(self, role: Role) -> RayResourcePool:\n        \"\"\"Get the resource pool of the worker_cls\"\"\"\n        return self.resource_pool_dict[self.mapping[role]]\n\n\nimport torch\nfrom verl.utils.torch_functional import masked_mean\n\n\ndef apply_kl_penalty(data: DataProto, kl_ctrl: core_algos.AdaptiveKLController, kl_penalty='kl'):\n    responses = data.batch['responses']\n    response_length = responses.size(1)\n    token_level_scores = data.batch['token_level_scores']\n    batch_size = data.batch.batch_size[0]\n    attention_mask = data.batch['attention_mask']\n    response_mask = attention_mask[:, -response_length:]\n\n    # compute kl between ref_policy and current policy\n    if 'ref_log_prob' in data.batch.keys():\n        kld = core_algos.kl_penalty(data.batch['old_log_probs'], data.batch['ref_log_prob'],\n                                    kl_penalty=kl_penalty)  # (batch_size, response_length)\n        kld = kld * response_mask\n        beta = kl_ctrl.value\n    else:\n        beta = 0\n        kld = torch.zeros_like(response_mask, dtype=torch.float32)\n\n    token_level_rewards = token_level_scores - beta * kld\n\n    current_kl = masked_mean(kld, mask=response_mask, axis=-1)  # average over sequence\n    current_kl = torch.mean(current_kl, dim=0).item()\n\n    # according to https://github.com/huggingface/trl/blob/951ca1841f29114b969b57b26c7d3e80a39f75a0/trl/trainer/ppo_trainer.py#L837\n    kl_ctrl.update(current_kl=current_kl, n_steps=batch_size)\n    data.batch['token_level_rewards'] = token_level_rewards\n\n    metrics = {'critic/kl': current_kl, 'critic/kl_coeff': beta}\n\n    return data, metrics\n\n\ndef compute_advantage(data: DataProto, adv_estimator, gamma=1.0, lam=1.0, num_repeat=1):\n    # prepare response group\n    # TODO: add other ways to estimate advantages\n    if adv_estimator == AdvantageEstimator.GAE:\n        values = data.batch['values']\n        responses = data.batch['responses']\n        response_length = responses.size(-1)\n        attention_mask = data.batch['attention_mask']\n        response_mask = attention_mask[:, -response_length:]\n        token_level_rewards = data.batch['token_level_rewards']\n        advantages, returns = core_algos.compute_gae_advantage_return(token_level_rewards=token_level_rewards,\n                                                                      values=values,\n                                                                      eos_mask=response_mask,\n                                                                      gamma=gamma,\n                                                                      lam=lam)\n        data.batch['advantages'] = advantages\n        data.batch['returns'] = returns\n    elif adv_estimator == AdvantageEstimator.GRPO:\n        token_level_rewards = data.batch['token_level_rewards']\n        index = data.non_tensor_batch['uid']\n        responses = data.batch['responses']\n        response_length = responses.size(-1)\n        attention_mask = data.batch['attention_mask']\n        response_mask = attention_mask[:, -response_length:]\n        advantages, returns = core_algos.compute_grpo_outcome_advantage(token_level_rewards=token_level_rewards,\n                                                                        eos_mask=response_mask,\n                                                                        index=index)\n        data.batch['advantages'] = advantages\n        data.batch['returns'] = returns\n    elif adv_estimator == AdvantageEstimator.REINFORCE_PLUS_PLUS:\n        token_level_rewards = data.batch['token_level_rewards']\n        responses = data.batch['responses']\n        response_length = responses.size(-1)\n        attention_mask = data.batch['attention_mask']\n        response_mask = attention_mask[:, -response_length:]\n        advantages, returns = core_algos.compute_reinforce_plus_plus_outcome_advantage(\n            token_level_rewards=token_level_rewards, eos_mask=response_mask, gamma=gamma)\n        data.batch['advantages'] = advantages\n        data.batch['returns'] = returns\n    elif adv_estimator == AdvantageEstimator.REMAX:\n        token_level_rewards = data.batch['token_level_rewards']\n        index = data.non_tensor_batch['uid']\n        responses = data.batch['responses']\n        response_length = responses.size(-1)\n        attention_mask = data.batch['attention_mask']\n        response_mask = attention_mask[:, -response_length:]\n\n        reward_baselines = data.batch['reward_baselines']\n\n        advantages, returns = core_algos.compute_remax_outcome_advantage(token_level_rewards=token_level_rewards,\n                                                                         reward_baselines=reward_baselines,\n                                                                         eos_mask=response_mask)\n\n        data.batch['advantages'] = advantages\n        data.batch['returns'] = returns\n    elif adv_estimator == AdvantageEstimator.RLOO:\n        token_level_rewards = data.batch['token_level_rewards']\n        index = data.non_tensor_batch['uid']\n        responses = data.batch['responses']\n        response_length = responses.size(-1)\n        attention_mask = data.batch['attention_mask']\n        response_mask = attention_mask[:, -response_length:]\n        advantages, returns = core_algos.compute_rloo_outcome_advantage(token_level_rewards=token_level_rewards,\n                                                                        eos_mask=response_mask,\n                                                                        index=index)\n        data.batch['advantages'] = advantages\n        data.batch['returns'] = returns\n    else:\n        raise NotImplementedError\n    return data\n\n\ndef reduce_metrics(metrics: dict):\n    for key, val in metrics.items():\n        metrics[key] = np.mean(val)\n    return metrics\n\n\ndef _compute_response_info(batch):\n    response_length = batch.batch['responses'].shape[-1]\n\n    prompt_mask = batch.batch['attention_mask'][:, :-response_length]\n    response_mask = batch.batch['attention_mask'][:, -response_length:]\n\n    prompt_length = prompt_mask.sum(-1).float()\n    response_length = response_mask.sum(-1).float()  # (batch_size,)\n\n    return dict(\n        response_mask=response_mask,\n        prompt_length=prompt_length,\n        response_length=response_length,\n    )\n\n\ndef compute_data_metrics(batch, use_critic=True):\n    # TODO: add response length\n    sequence_score = batch.batch['token_level_scores'].sum(-1)\n    sequence_reward = batch.batch['token_level_rewards'].sum(-1)\n\n    advantages = batch.batch['advantages']\n    returns = batch.batch['returns']\n\n    max_response_length = batch.batch['responses'].shape[-1]\n\n    prompt_mask = batch.batch['attention_mask'][:, :-max_response_length].bool()\n    response_mask = batch.batch['attention_mask'][:, -max_response_length:].bool()\n\n    max_prompt_length = prompt_mask.size(-1)\n\n    response_info = _compute_response_info(batch)\n    prompt_length = response_info['prompt_length']\n    response_length = response_info['response_length']\n\n    valid_adv = torch.masked_select(advantages, response_mask)\n    valid_returns = torch.masked_select(returns, response_mask)\n\n    if use_critic:\n        values = batch.batch['values']\n        valid_values = torch.masked_select(values, response_mask)\n        return_diff_var = torch.var(valid_returns - valid_values)\n        return_var = torch.var(valid_returns)\n\n    metrics = {\n        # score\n        'critic/score/mean':\n            torch.mean(sequence_score).detach().item(),\n        'critic/score/max':\n            torch.max(sequence_score).detach().item(),\n        'critic/score/min':\n            torch.min(sequence_score).detach().item(),\n        # reward\n        'critic/rewards/mean':\n            torch.mean(sequence_reward).detach().item(),\n        'critic/rewards/max':\n            torch.max(sequence_reward).detach().item(),\n        'critic/rewards/min':\n            torch.min(sequence_reward).detach().item(),\n        # adv\n        'critic/advantages/mean':\n            torch.mean(valid_adv).detach().item(),\n        'critic/advantages/max':\n            torch.max(valid_adv).detach().item(),\n        'critic/advantages/min':\n            torch.min(valid_adv).detach().item(),\n        # returns\n        'critic/returns/mean':\n            torch.mean(valid_returns).detach().item(),\n        'critic/returns/max':\n            torch.max(valid_returns).detach().item(),\n        'critic/returns/min':\n            torch.min(valid_returns).detach().item(),\n        **({\n            # values\n            'critic/values/mean': torch.mean(valid_values).detach().item(),\n            'critic/values/max': torch.max(valid_values).detach().item(),\n            'critic/values/min': torch.min(valid_values).detach().item(),\n            # vf explained var\n            'critic/vf_explained_var': (1.0 - return_diff_var / (return_var + 1e-5)).detach().item(),\n        } if use_critic else {}),\n\n        # response length\n        'response_length/mean':\n            torch.mean(response_length).detach().item(),\n        'response_length/max':\n            torch.max(response_length).detach().item(),\n        'response_length/min':\n            torch.min(response_length).detach().item(),\n        'response_length/clip_ratio':\n            torch.mean(torch.eq(response_length, max_response_length).float()).detach().item(),\n        # prompt length\n        'prompt_length/mean':\n            torch.mean(prompt_length).detach().item(),\n        'prompt_length/max':\n            torch.max(prompt_length).detach().item(),\n        'prompt_length/min':\n            torch.min(prompt_length).detach().item(),\n        'prompt_length/clip_ratio':\n            torch.mean(torch.eq(prompt_length, max_prompt_length).float()).detach().item(),\n    }\n    return metrics\n\n\ndef compute_timing_metrics(batch, timing_raw):\n    response_info = _compute_response_info(batch)\n    num_prompt_tokens = torch.sum(response_info['prompt_length']).item()\n    num_response_tokens = torch.sum(response_info['response_length']).item()\n    num_overall_tokens = num_prompt_tokens + num_response_tokens\n\n    num_tokens_of_section = {\n        'gen': num_response_tokens,\n        **{\n            name: num_overall_tokens for name in ['ref', 'values', 'adv', 'update_critic', 'update_actor']\n        },\n    }\n\n    return {\n        **{\n            f'timing_s/{name}': value for name, value in timing_raw.items()\n        },\n        **{\n            f'timing_per_token_ms/{name}': timing_raw[name] * 1000 / num_tokens_of_section[name] for name in set(num_tokens_of_section.keys(\n            )) & set(timing_raw.keys())\n        },\n    }\n\n\n@contextmanager\ndef _timer(name: str, timing_raw: Dict[str, float]):\n    with Timer(name=name, logger=None) as timer:\n        yield\n    timing_raw[name] = timer.last\n\n\nclass RayPPOTrainer(object):\n    \"\"\"\n    Note that this trainer runs on the driver process on a single CPU/GPU node.\n    \"\"\"\n\n    # TODO: support each role have individual ray_worker_group_cls,\n    # i.e., support different backend of different role\n    def __init__(self,\n                 config,\n                 tokenizer,\n                 role_worker_mapping: dict[Role, WorkerType],\n                 resource_pool_manager: ResourcePoolManager,\n                 ray_worker_group_cls: RayWorkerGroup = RayWorkerGroup,\n                 processor=None,\n                 reward_fn=None,\n                 val_reward_fn=None):\n\n        # assert torch.cuda.is_available(), 'cuda must be available on driver'\n\n        self.tokenizer = tokenizer\n        self.processor = processor\n        self.config = config\n        self.reward_fn = reward_fn\n        self.val_reward_fn = val_reward_fn\n\n        self.hybrid_engine = config.actor_rollout_ref.hybrid_engine\n        assert self.hybrid_engine, 'Currently, only support hybrid engine'\n\n        if self.hybrid_engine:\n            assert Role.ActorRollout in role_worker_mapping, f'{role_worker_mapping.keys()=}'\n\n        self.role_worker_mapping = role_worker_mapping\n        self.resource_pool_manager = resource_pool_manager\n        self.use_reference_policy = Role.RefPolicy in role_worker_mapping\n        self.use_rm = Role.RewardModel in role_worker_mapping\n        self.ray_worker_group_cls = ray_worker_group_cls\n\n        # define KL control\n        if self.use_reference_policy:\n            if config.algorithm.kl_ctrl.type == 'fixed':\n                self.kl_ctrl = core_algos.FixedKLController(kl_coef=config.algorithm.kl_ctrl.kl_coef)\n            elif config.algorithm.kl_ctrl.type == 'adaptive':\n                assert config.algorithm.kl_ctrl.horizon > 0, f'horizon must be larger than 0. Got {config.critic.kl_ctrl.horizon}'\n                self.kl_ctrl = core_algos.AdaptiveKLController(init_kl_coef=config.algorithm.kl_ctrl.kl_coef,\n                                                               target_kl=config.algorithm.kl_ctrl.target_kl,\n                                                               horizon=config.algorithm.kl_ctrl.horizon)\n            else:\n                raise NotImplementedError\n        else:\n            self.kl_ctrl = core_algos.FixedKLController(kl_coef=0.)\n\n        if self.config.algorithm.adv_estimator == AdvantageEstimator.GAE:\n            self.use_critic = True\n        elif self.config.algorithm.adv_estimator in [\n                AdvantageEstimator.GRPO, AdvantageEstimator.REINFORCE_PLUS_PLUS, AdvantageEstimator.REMAX,\n                AdvantageEstimator.RLOO\n        ]:\n            self.use_critic = False\n        else:\n            raise NotImplementedError\n\n        self._validate_config()\n        self._create_dataloader()\n\n    def _validate_config(self):\n        config = self.config\n        # number of GPUs total\n        n_gpus = config.trainer.n_gpus_per_node * config.trainer.nnodes\n\n        # 1. Check total batch size for data correctness\n        real_train_batch_size = config.data.train_batch_size * config.actor_rollout_ref.rollout.n\n        assert real_train_batch_size % n_gpus == 0, \\\n            f\"real_train_batch_size ({real_train_batch_size}) must be divisible by total n_gpus ({n_gpus}).\"\n\n        # A helper function to check \"micro_batch_size\" vs \"micro_batch_size_per_gpu\"\n        # We throw an error if the user sets both. The new convention is \"..._micro_batch_size_per_gpu\".\n        def check_mutually_exclusive(mbs, mbs_per_gpu, name: str):\n            if mbs is None and mbs_per_gpu is None:\n                raise ValueError(f\"[{name}] Please set at least one of '{name}.micro_batch_size' or \"\n                                 f\"'{name}.micro_batch_size_per_gpu'.\")\n\n            if mbs is not None and mbs_per_gpu is not None:\n                raise ValueError(f\"[{name}] You have set both '{name}.micro_batch_size' AND \"\n                                 f\"'{name}.micro_batch_size_per_gpu'. Please remove '{name}.micro_batch_size' \"\n                                 f\"because only '*_micro_batch_size_per_gpu' is supported (the former is deprecated).\")\n\n        if not config.actor_rollout_ref.actor.use_dynamic_bsz:\n            # actor: ppo_micro_batch_size vs. ppo_micro_batch_size_per_gpu\n            check_mutually_exclusive(config.actor_rollout_ref.actor.ppo_micro_batch_size,\n                                     config.actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu,\n                                     \"actor_rollout_ref.actor\")\n\n            # reference: log_prob_micro_batch_size vs. log_prob_micro_batch_size_per_gpu\n            check_mutually_exclusive(config.actor_rollout_ref.ref.log_prob_micro_batch_size,\n                                     config.actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu,\n                                     \"actor_rollout_ref.ref\")\n\n            #  The rollout section also has log_prob_micro_batch_size vs. log_prob_micro_batch_size_per_gpu\n            check_mutually_exclusive(config.actor_rollout_ref.rollout.log_prob_micro_batch_size,\n                                     config.actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu,\n                                     \"actor_rollout_ref.rollout\")\n\n        if self.use_critic and not config.critic.use_dynamic_bsz:\n            # Check for critic micro-batch size conflicts\n            check_mutually_exclusive(config.critic.ppo_micro_batch_size, config.critic.ppo_micro_batch_size_per_gpu,\n                                     \"critic\")\n\n        # Check for reward model micro-batch size conflicts\n        if config.reward_model.enable and not config.reward_model.use_dynamic_bsz:\n            check_mutually_exclusive(config.reward_model.micro_batch_size, config.reward_model.micro_batch_size_per_gpu,\n                                     \"reward_model\")\n\n        # Actor\n        # if NOT dynamic_bsz, we must ensure:\n        #    ppo_mini_batch_size is divisible by ppo_micro_batch_size\n        #    ppo_micro_batch_size * sequence_parallel_size >= n_gpus\n        if not config.actor_rollout_ref.actor.use_dynamic_bsz:\n            sp_size = config.actor_rollout_ref.actor.get('ulysses_sequence_parallel_size', 1)\n            if config.actor_rollout_ref.actor.ppo_micro_batch_size is not None:\n                assert config.actor_rollout_ref.actor.ppo_mini_batch_size % config.actor_rollout_ref.actor.ppo_micro_batch_size == 0\n                assert config.actor_rollout_ref.actor.ppo_micro_batch_size * sp_size >= n_gpus\n\n        # critic\n        if self.use_critic and not config.critic.use_dynamic_bsz:\n            sp_size = config.critic.get('ulysses_sequence_parallel_size', 1)\n            if config.critic.ppo_micro_batch_size is not None:\n                assert config.critic.ppo_mini_batch_size % config.critic.ppo_micro_batch_size == 0\n                assert config.critic.ppo_micro_batch_size * sp_size >= n_gpus\n\n        # Check if use_remove_padding is enabled when using sequence parallelism for fsdp\n        if config.actor_rollout_ref.actor.strategy == 'fsdp':\n            if config.actor_rollout_ref.actor.get('ulysses_sequence_parallel_size', 1) > 1 or \\\n                    config.actor_rollout_ref.ref.get('ulysses_sequence_parallel_size', 1) > 1:\n                assert config.actor_rollout_ref.model.use_remove_padding, \\\n                    \"When using sequence parallelism for actor/ref policy, you must enable `use_remove_padding`.\"\n\n        if self.use_critic and config.critic.strategy == 'fsdp':\n            if config.critic.get('ulysses_sequence_parallel_size', 1) > 1:\n                assert config.critic.model.use_remove_padding, \\\n                    \"When using sequence parallelism for critic, you must enable `use_remove_padding`.\"\n\n        if config.data.get('val_batch_size', None) is not None:\n            print(\n                f\"WARNING: val_batch_size is deprecated. Validation datasets are sent to inference engines as a whole batch, which will schedule the memory themselves.\"\n            )\n\n        print(\"[validate_config] All configuration checks passed successfully!\")\n\n    def _create_dataloader(self):\n        # TODO: we have to make sure the batch size is divisible by the dp size\n        self.train_dataset = RLHFDataset(parquet_files=self.config.data.train_files,\n                                         tokenizer=self.tokenizer,\n                                         processor=self.processor,\n                                         prompt_key=self.config.data.prompt_key,\n                                         image_key=self.config.data.get('image_key', 'images'),\n                                         max_prompt_length=self.config.data.max_prompt_length,\n                                         filter_prompts=True,\n                                         return_raw_chat=self.config.data.get('return_raw_chat', False),\n                                         truncation='error',\n                                         template_type=self.config.data.template_type)\n        # use sampler for better ckpt resume\n        if self.config.data.shuffle:\n            train_dataloader_generator = torch.Generator()\n            train_dataloader_generator.manual_seed(self.config.data.get('seed', 1))\n            sampler = RandomSampler(data_source=self.train_dataset, generator=train_dataloader_generator)\n        else:\n            sampler = SequentialSampler(data_source=self.train_dataset)\n\n        self.train_dataloader = StatefulDataLoader(dataset=self.train_dataset,\n                                                   batch_size=self.config.data.train_batch_size,\n                                                   num_workers=8,\n                                                   drop_last=True,\n                                                   collate_fn=collate_fn,\n                                                   sampler=sampler)\n\n        self.val_dataset = RLHFDataset(parquet_files=self.config.data.val_files,\n                                       tokenizer=self.tokenizer,\n                                       processor=self.processor,\n                                       prompt_key=self.config.data.prompt_key,\n                                       image_key=self.config.data.get('image_key', 'images'),\n                                       max_prompt_length=self.config.data.val_max_prompt_length,\n                                       filter_prompts=True,\n                                       return_raw_chat=self.config.data.get('return_raw_chat', False),\n                                       truncation='error',\n                                       template_type=self.config.data.template_type)\n        self.val_dataloader = StatefulDataLoader(\n            dataset=self.val_dataset,\n            # Validation datasets are sent to inference engines as a whole batch,\n            # which will schedule the memory themselves.\n            batch_size=len(self.val_dataset),\n            num_workers=8,\n            shuffle=False,\n            drop_last=False,\n            collate_fn=collate_fn)\n\n        assert len(self.train_dataloader) >= 1\n        assert len(\n            self.val_dataloader\n        ) == 1, \"Validation dataloader must have a single batch, which inference engines will schedule the memory themselves.\"\n\n        print(f'Size of train dataloader: {len(self.train_dataloader)}')\n\n        # inject total_training_steps to actor/critic optim_config. This is hacky.\n        total_training_steps = len(self.train_dataloader) * self.config.trainer.total_epochs\n\n        if self.config.trainer.total_training_steps is not None:\n            total_training_steps = self.config.trainer.total_training_steps\n\n        self.total_training_steps = total_training_steps\n        print(f'Total training steps: {self.total_training_steps}')\n\n        OmegaConf.set_struct(self.config, True)\n        with open_dict(self.config):\n            self.config.actor_rollout_ref.actor.optim.total_training_steps = total_training_steps\n            self.config.critic.optim.total_training_steps = total_training_steps\n\n    def _maybe_log_val_generations_to_wandb(self, inputs, outputs, scores):\n        \"\"\"Log a table of validation samples to wandb\"\"\"\n\n        generations_to_log = self.config.trainer.val_generations_to_log_to_wandb\n\n        if generations_to_log == 0:\n            return\n\n        if generations_to_log > 0 and 'wandb' not in self.config.trainer.logger:\n            print(\n                'WARNING: `val_generations_to_log_to_wandb` is set to a positive value, but no wandb logger is found. ')\n            return\n\n        import wandb\n        import numpy as np\n\n        # Create tuples of (input, output, score) and sort by input text\n        samples = list(zip(inputs, outputs, scores))\n        samples.sort(key=lambda x: x[0])  # Sort by input text\n\n        # Use fixed random seed for deterministic shuffling\n        rng = np.random.RandomState(42)\n        rng.shuffle(samples)\n\n        # Take first N samples after shuffling\n        samples = samples[:generations_to_log]\n\n        # Create column names for all samples\n        columns = [\"step\"] + sum([[f\"input_{i+1}\", f\"output_{i+1}\", f\"score_{i+1}\"] for i in range(len(samples))], [])\n\n        if not hasattr(self, 'validation_table'):\n            # Initialize the table on first call\n            self.validation_table = wandb.Table(columns=columns)\n\n        # Create a new table with same columns and existing data\n        # Workaround for https://github.com/wandb/wandb/issues/2981#issuecomment-1997445737\n        new_table = wandb.Table(columns=columns, data=self.validation_table.data)\n\n        # Add new row with all data\n        row_data = []\n        row_data.append(self.global_steps)\n        for sample in samples:\n            row_data.extend(sample)\n\n        new_table.add_data(*row_data)\n\n        # Update reference and log\n        wandb.log({\"val/generations\": new_table}, step=self.global_steps)\n        self.validation_table = new_table\n\n    def _validate(self):\n        reward_tensor_lst = []\n        data_source_lst = []\n\n        # Lists to collect samples for the table\n        sample_inputs = []\n        sample_outputs = []\n        sample_scores = []\n        sample_lengths = []\n        for test_data in self.val_dataloader:\n            test_batch = DataProto.from_single_dict(test_data)\n\n            # we only do validation on rule-based rm\n            if self.config.reward_model.enable and test_batch[0].non_tensor_batch['reward_model']['style'] == 'model':\n                return {}\n\n            # Store original inputs\n            input_ids = test_batch.batch['input_ids']\n            input_texts = [self.tokenizer.decode(ids, skip_special_tokens=True) for ids in input_ids]\n            sample_inputs.extend(input_texts)\n\n            if 'multi_modal_inputs' in test_batch.non_tensor_batch.keys():\n                test_gen_batch = test_batch.pop(\n                    batch_keys=['input_ids', 'attention_mask', 'position_ids'],\n                    non_tensor_batch_keys=['raw_prompt_ids', 'multi_modal_data', 'multi_modal_inputs'],\n                )\n            else:\n                test_gen_batch = test_batch.pop(\n                    batch_keys=['input_ids', 'attention_mask', 'position_ids'],\n                    non_tensor_batch_keys=['raw_prompt_ids'],\n                )\n\n            test_gen_batch.meta_info = {\n                'eos_token_id': self.tokenizer.eos_token_id,\n                'pad_token_id': self.tokenizer.pad_token_id,\n                'recompute_log_prob': False,\n                'do_sample': False,\n                'validate': True,\n            }\n\n            # pad to be divisible by dp_size\n            test_gen_batch_padded, pad_size = pad_dataproto_to_divisor(test_gen_batch, self.actor_rollout_wg.world_size)\n            test_output_gen_batch_padded = self.actor_rollout_wg.generate_sequences(test_gen_batch_padded)\n            # unpad\n            test_output_gen_batch = unpad_dataproto(test_output_gen_batch_padded, pad_size=pad_size)\n            print('validation generation end')\n\n            # Store generated outputs\n            output_ids = test_output_gen_batch.batch['responses']\n            output_texts = [self.tokenizer.decode(ids, skip_special_tokens=True) for ids in output_ids]\n            sample_outputs.extend(output_texts)\n            sample_lengths.extend((~torch.isin(output_ids, torch.tensor(self.tokenizer.pad_token_id, device=output_ids.device))).sum(-1).tolist())\n\n            test_batch = test_batch.union(test_output_gen_batch)\n\n            # evaluate using reward_function\n            reward_tensor = self.val_reward_fn(test_batch)\n            reward_tensor = torch.where((reward_tensor == -1.0) | (reward_tensor == -0.5), torch.tensor(0.0), reward_tensor) \n            test_batch.batch['token_level_scores']=reward_tensor\n            self._save_samples(test_batch, \"test\")\n\n            # Store scores\n            scores = reward_tensor.sum(-1).cpu().tolist()\n            sample_scores.extend(scores)\n\n            reward_tensor_lst.append(reward_tensor)\n            data_source_lst.append(test_batch.non_tensor_batch.get('data_source', ['unknown'] * reward_tensor.shape[0]))\n\n        self._maybe_log_val_generations_to_wandb(inputs=sample_inputs, outputs=sample_outputs, scores=sample_scores)\n\n        reward_tensor = torch.cat(reward_tensor_lst, dim=0).sum(-1).cpu()  # (batch_size,)\n        data_sources = np.concatenate(data_source_lst, axis=0)\n\n        # evaluate test_score based on data source\n        data_source_reward = {}\n        data_source_length = {}\n        for i in range(reward_tensor.shape[0]):\n            data_source = data_sources[i]\n            if data_source not in data_source_reward:\n                data_source_reward[data_source] = []\n                data_source_length[data_source] = []\n            data_source_reward[data_source].append(reward_tensor[i].item())\n            data_source_length[data_source].append(sample_lengths[i])\n\n        metric_dict = {}\n        average_acc=[]\n        for data_source, rewards in data_source_reward.items():\n            metric_dict[f'val/test_score/{data_source}'] = np.mean(rewards)\n            average_acc.append(np.mean(rewards))\n        metric_dict[f'val/test_score/avg_acc'] = np.mean(average_acc)\n\n        for data_source, lengths in data_source_length.items():\n            metric_dict[f'val_response_length/test_length/{data_source}'] = np.mean(lengths)\n            rewards=data_source_reward[data_source]\n            if np.mean(rewards)==0: continue\n            metric_dict[f'val_response_length/test_length_correct/{data_source}'] = sum([lengths[i] for i in range(len(lengths)) if rewards[i]==1.0])/sum(rewards)\n\n        return metric_dict\n    \n    def _save_samples(self, batch: DataProto, split: str):\n        prompts, response, token_level_scores=batch.batch['prompts'], batch.batch['responses'], batch.batch['token_level_scores']\n        sources=batch.non_tensor_batch['data_source']\n        prompts=self.tokenizer.batch_decode(prompts, skip_special_tokens=True)\n        response=self.tokenizer.batch_decode(response, skip_special_tokens=True)\n        rewards=[]\n        for row in token_level_scores:\n            non_zero_indices = torch.nonzero(row, as_tuple=True)[0]\n            if len(non_zero_indices) > 0: rewards.append( row[non_zero_indices[-1]].item() )\n            else: rewards.append(0.0)\n        data=[]\n        for idx in range(len(prompts)):\n            data.append({\n                'prompt': prompts[idx],\n                'response': response[idx],\n                'reward': rewards[idx],\n                'source': sources[idx],\n            })\n        os.makedirs(os.path.join(self.config.trainer.samples_save_path, split), exist_ok=True)\n        with open(os.path.join(self.config.trainer.samples_save_path, split, f\"step_{self.global_steps}.json\"), 'a+', encoding='utf-8') as f:\n            json.dump(data, f, ensure_ascii=False, indent=4)\n\n    def init_workers(self):\n        \"\"\"Init resource pool and worker group\"\"\"\n        self.resource_pool_manager.create_resource_pool()\n\n        self.resource_pool_to_cls = {pool: {} for pool in self.resource_pool_manager.resource_pool_dict.values()}\n\n        # create actor and rollout\n        if self.hybrid_engine:\n            resource_pool = self.resource_pool_manager.get_resource_pool(Role.ActorRollout)\n            actor_rollout_cls = RayClassWithInitArgs(cls=self.role_worker_mapping[Role.ActorRollout],\n                                                     config=self.config.actor_rollout_ref,\n                                                     role='actor_rollout')\n            self.resource_pool_to_cls[resource_pool]['actor_rollout'] = actor_rollout_cls\n        else:\n            raise NotImplementedError\n\n        # create critic\n        if self.use_critic:\n            resource_pool = self.resource_pool_manager.get_resource_pool(Role.Critic)\n            critic_cls = RayClassWithInitArgs(cls=self.role_worker_mapping[Role.Critic], config=self.config.critic)\n            self.resource_pool_to_cls[resource_pool]['critic'] = critic_cls\n\n        # create reference policy if needed\n        if self.use_reference_policy:\n            resource_pool = self.resource_pool_manager.get_resource_pool(Role.RefPolicy)\n            ref_policy_cls = RayClassWithInitArgs(self.role_worker_mapping[Role.RefPolicy],\n                                                  config=self.config.actor_rollout_ref,\n                                                  role='ref')\n            self.resource_pool_to_cls[resource_pool]['ref'] = ref_policy_cls\n\n        # create a reward model if reward_fn is None\n        if self.use_rm:\n            # we create a RM here\n            resource_pool = self.resource_pool_manager.get_resource_pool(Role.RewardModel)\n            rm_cls = RayClassWithInitArgs(self.role_worker_mapping[Role.RewardModel], config=self.config.reward_model)\n            self.resource_pool_to_cls[resource_pool]['rm'] = rm_cls\n\n        # initialize WorkerGroup\n        # NOTE: if you want to use a different resource pool for each role, which can support different parallel size,\n        # you should not use `create_colocated_worker_cls`. Instead, directly pass different resource pool to different worker groups.\n        # See https://github.com/volcengine/verl/blob/master/examples/ray/tutorial.ipynb for more information.\n        all_wg = {}\n        self.wg_dicts = []\n        for resource_pool, class_dict in self.resource_pool_to_cls.items():\n            worker_dict_cls = create_colocated_worker_cls(class_dict=class_dict)\n            wg_dict = self.ray_worker_group_cls(resource_pool=resource_pool, ray_cls_with_init=worker_dict_cls)\n            spawn_wg = wg_dict.spawn(prefix_set=class_dict.keys())\n            all_wg.update(spawn_wg)\n            # keep the referece of WorkerDict to support ray >= 2.31. Ref: https://github.com/ray-project/ray/pull/45699\n            self.wg_dicts.append(wg_dict)\n\n        if self.use_critic:\n            self.critic_wg = all_wg['critic']\n            self.critic_wg.init_model()\n\n        if self.use_reference_policy:\n            self.ref_policy_wg = all_wg['ref']\n            self.ref_policy_wg.init_model()\n\n        if self.use_rm:\n            self.rm_wg = all_wg['rm']\n            self.rm_wg.init_model()\n\n        # we should create rollout at the end so that vllm can have a better estimation of kv cache memory\n        self.actor_rollout_wg = all_wg['actor_rollout']\n        self.actor_rollout_wg.init_model()\n\n    def _save_checkpoint(self):\n        # path: given_path + `/global_step_{global_steps}` + `/actor`\n        local_global_step_folder = os.path.join(self.config.trainer.default_local_dir,\n                                                f'global_step_{self.global_steps}')\n        actor_local_path = os.path.join(local_global_step_folder, 'actor')\n\n        actor_remote_path = None if self.config.trainer.default_hdfs_dir is None else os.path.join(\n            self.config.trainer.default_hdfs_dir, f'global_step_{self.global_steps}', 'actor')\n        self.actor_rollout_wg.save_checkpoint(actor_local_path,\n                                              actor_remote_path,\n                                              self.global_steps,\n                                              remove_previous_ckpt=self.config.trainer.remove_previous_ckpt_in_save)\n\n        if self.use_critic:\n            critic_local_path = os.path.join(local_global_step_folder, 'critic')\n            critic_remote_path = None if self.config.trainer.default_hdfs_dir is None else os.path.join(\n                self.config.trainer.default_hdfs_dir, f'global_step_{self.global_steps}', 'critic')\n            self.critic_wg.save_checkpoint(critic_local_path,\n                                           critic_remote_path,\n                                           self.global_steps,\n                                           remove_previous_ckpt=self.config.trainer.remove_previous_ckpt_in_save)\n\n        # save dataloader\n        dataloader_local_path = os.path.join(local_global_step_folder, 'data.pt')\n        dataloader_state_dict = self.train_dataloader.state_dict()\n        torch.save(dataloader_state_dict, dataloader_local_path)\n\n        # latest checkpointed iteration tracker (for atomic usage)\n        local_latest_checkpointed_iteration = os.path.join(self.config.trainer.default_local_dir,\n                                                           'latest_checkpointed_iteration.txt')\n        with open(local_latest_checkpointed_iteration, 'w') as f:\n            f.write(str(self.global_steps))\n\n    def _load_checkpoint(self):\n        if self.config.trainer.resume_mode == 'disable':\n            return 0\n\n        # load from hdfs\n        if self.config.trainer.default_hdfs_dir is not None:\n            NotImplementedError('load from hdfs is not implemented yet')\n        else:\n            checkpoint_folder = self.config.trainer.default_local_dir  # TODO: check path\n            if not os.path.isabs(checkpoint_folder):\n                working_dir = os.getcwd()\n                checkpoint_folder = os.path.join(working_dir, checkpoint_folder)\n            global_step_folder = find_latest_ckpt_path(checkpoint_folder)  # None if no latest\n\n        # find global_step_folder\n        if self.config.trainer.resume_mode == 'auto':\n            if global_step_folder is None:\n                print('Training from scratch')\n                return 0\n        else:\n            if not (self.config.trainer.resume_from_path and global_step_folder is not None):\n                assert isinstance(self.config.trainer.resume_mode, str), \"resume ckpt must be str type\"\n                assert 'global_step_' in self.config.trainer.resume_mode, \"resume ckpt must specify the global_steps\"\n                global_step_folder = self.config.trainer.resume_mode\n                if not os.path.isabs(global_step_folder):\n                    working_dir = os.getcwd()\n                    global_step_folder = os.path.join(working_dir, global_step_folder)\n        print(f'Load from checkpoint folder: {global_step_folder}')\n        # set global step\n        self.global_steps = int(global_step_folder.split('global_step_')[-1])\n\n        print(f'Setting global step to {self.global_steps}')\n        print(f'Resuming from {global_step_folder}')\n\n        actor_path = os.path.join(global_step_folder, 'actor')\n        critic_path = os.path.join(global_step_folder, 'critic')\n        # load actor\n        self.actor_rollout_wg.load_checkpoint(actor_path,\n                                              del_local_after_load=self.config.trainer.del_local_ckpt_after_load)\n        # load critic\n        if self.use_critic:\n            self.critic_wg.load_checkpoint(critic_path,\n                                           del_local_after_load=self.config.trainer.del_local_ckpt_after_load)\n\n        # load dataloader,\n        # TODO: from remote not implemented yet\n        dataloader_local_path = os.path.join(global_step_folder, 'data.pt')\n        if os.path.exists(dataloader_local_path):\n            dataloader_state_dict = torch.load(dataloader_local_path)\n            self.train_dataloader.load_state_dict(dataloader_state_dict)\n        else:\n            print(f\"Warning: No dataloader state found at {dataloader_local_path}, will start from scratch\")\n\n    def _balance_batch(self, batch: DataProto, metrics, logging_prefix='global_seqlen'):\n        \"\"\"Reorder the data on single controller such that each dp rank gets similar total tokens\"\"\"\n        attention_mask = batch.batch['attention_mask']\n        batch_size = attention_mask.shape[0]\n        global_seqlen_lst = batch.batch['attention_mask'].view(batch_size, -1).sum(-1).tolist()  # (train_batch_size,)\n        world_size = self.actor_rollout_wg.world_size\n        global_partition_lst = get_seqlen_balanced_partitions(global_seqlen_lst,\n                                                              k_partitions=world_size,\n                                                              equal_size=True)\n        # reorder based on index. The data will be automatically equally partitioned by dispatch function\n        global_idx = torch.tensor([j for partition in global_partition_lst for j in partition])\n        batch.reorder(global_idx)\n        global_balance_stats = log_seqlen_unbalance(seqlen_list=global_seqlen_lst,\n                                                    partitions=global_partition_lst,\n                                                    prefix=logging_prefix)\n        metrics.update(global_balance_stats)\n\n    def fit(self):\n        \"\"\"\n        The training loop of PPO.\n        The driver process only need to call the compute functions of the worker group through RPC to construct the PPO dataflow.\n        The light-weight advantage computation is done on the driver process.\n        \"\"\"\n        from verl.utils.tracking import Tracking\n        from omegaconf import OmegaConf\n\n        logger = Tracking(project_name=self.config.trainer.project_name,\n                          experiment_name=self.config.trainer.experiment_name,\n                          default_backend=self.config.trainer.logger,\n                          config=OmegaConf.to_container(self.config, resolve=True))\n\n        self.global_steps = 0\n\n        # load checkpoint before doing anything\n        self._load_checkpoint()\n\n        # perform validation before training\n        # currently, we only support validation using the reward_function.\n        if self.val_reward_fn is not None and self.config.trainer.get('val_before_train', True):\n            val_metrics = self._validate()\n            pprint(f'Initial validation metrics: {val_metrics}')\n            logger.log(data=val_metrics, step=self.global_steps)\n            if self.config.trainer.get('val_only', False):\n                return\n\n        # we start from step 1\n        self.global_steps += 1\n\n        for epoch in range(self.config.trainer.total_epochs):\n            for batch_dict in self.train_dataloader:\n                metrics = {}\n                timing_raw = {}\n\n                batch: DataProto = DataProto.from_single_dict(batch_dict)\n\n                # pop those keys for generation\n                if 'multi_modal_inputs' in batch.non_tensor_batch.keys():\n                    gen_batch = batch.pop(\n                        batch_keys=['input_ids', 'attention_mask', 'position_ids'],\n                        non_tensor_batch_keys=['raw_prompt_ids', 'multi_modal_data', 'multi_modal_inputs'],\n                    )\n                else:\n                    gen_batch = batch.pop(\n                        batch_keys=['input_ids', 'attention_mask', 'position_ids'],\n                        non_tensor_batch_keys=['raw_prompt_ids'],\n                    )\n\n                with _timer('step', timing_raw):\n                    # generate a batch\n                    with _timer('gen', timing_raw):\n                        gen_batch_output = self.actor_rollout_wg.generate_sequences(gen_batch)\n\n                    if self.config.algorithm.adv_estimator == AdvantageEstimator.REMAX:\n                        with _timer('gen_max', timing_raw):\n                            gen_baseline_batch = deepcopy(gen_batch)\n                            gen_baseline_batch.meta_info['do_sample'] = False\n                            gen_baseline_output = self.actor_rollout_wg.generate_sequences(gen_baseline_batch)\n\n                            batch = batch.union(gen_baseline_output)\n                            reward_baseline_tensor = self.reward_fn(batch)\n                            reward_baseline_tensor = reward_baseline_tensor.sum(dim=-1)\n\n                            batch.pop(batch_keys=list(gen_baseline_output.batch.keys()))\n\n                            batch.batch['reward_baselines'] = reward_baseline_tensor\n\n                            del gen_baseline_batch, gen_baseline_output\n\n                    batch.non_tensor_batch['uid'] = np.array([str(uuid.uuid4()) for _ in range(len(batch.batch))],\n                                                             dtype=object)\n                    # repeat to align with repeated responses in rollout\n                    batch = batch.repeat(repeat_times=self.config.actor_rollout_ref.rollout.n, interleave=True)\n                    batch = batch.union(gen_batch_output)\n\n                    # balance the number of valid tokens on each dp rank.\n                    # Note that this breaks the order of data inside the batch.\n                    # Please take care when you implement group based adv computation such as GRPO and rloo\n                    self._balance_batch(batch, metrics=metrics)\n\n                    # compute global_valid tokens\n                    batch.meta_info['global_token_num'] = torch.sum(batch.batch['attention_mask'], dim=-1).tolist()\n\n                    # recompute old_log_probs\n                    with _timer('old_log_prob', timing_raw):\n                        old_log_prob = self.actor_rollout_wg.compute_log_prob(batch)\n                        batch = batch.union(old_log_prob)\n\n                    if self.use_reference_policy:\n                        # compute reference log_prob\n                        with _timer('ref', timing_raw):\n                            ref_log_prob = self.ref_policy_wg.compute_ref_log_prob(batch)\n                            batch = batch.union(ref_log_prob)\n\n                    # compute values\n                    if self.use_critic:\n                        with _timer('values', timing_raw):\n                            values = self.critic_wg.compute_values(batch)\n                            batch = batch.union(values)\n\n                    with _timer('adv', timing_raw):\n                        # compute scores. Support both model and function-based.\n                        # We first compute the scores using reward model. Then, we call reward_fn to combine\n                        # the results from reward model and rule-based results.\n                        if self.use_rm:\n                            # we first compute reward model score\n                            reward_tensor = self.rm_wg.compute_rm_score(batch)\n                            batch = batch.union(reward_tensor)\n\n                        # we combine with rule-based rm\n                        reward_tensor = self.reward_fn(batch)\n                        batch.batch['token_level_scores'] = reward_tensor\n\n                        # compute rewards. apply_kl_penalty if available\n                        if not self.config.actor_rollout_ref.actor.get('use_kl_loss', False):\n                            batch, kl_metrics = apply_kl_penalty(batch,\n                                                                 kl_ctrl=self.kl_ctrl,\n                                                                 kl_penalty=self.config.algorithm.kl_penalty)\n                            metrics.update(kl_metrics)\n                        else:\n                            batch.batch['token_level_rewards'] = batch.batch['token_level_scores']\n\n                        # compute advantages, executed on the driver process\n                        batch = compute_advantage(batch,\n                                                  adv_estimator=self.config.algorithm.adv_estimator,\n                                                  gamma=self.config.algorithm.gamma,\n                                                  lam=self.config.algorithm.lam,\n                                                  num_repeat=self.config.actor_rollout_ref.rollout.n)\n\n                    # update critic\n                    if self.use_critic:\n                        with _timer('update_critic', timing_raw):\n                            critic_output = self.critic_wg.update_critic(batch)\n                        critic_output_metrics = reduce_metrics(critic_output.meta_info['metrics'])\n                        metrics.update(critic_output_metrics)\n\n                    # implement critic warmup\n                    if self.config.trainer.critic_warmup <= self.global_steps:\n                        # update actor\n                        with _timer('update_actor', timing_raw):\n                            actor_output = self.actor_rollout_wg.update_actor(batch)\n                        actor_output_metrics = reduce_metrics(actor_output.meta_info['metrics'])\n                        metrics.update(actor_output_metrics)\n\n                    # validate\n                    if self.val_reward_fn is not None and self.config.trainer.test_freq > 0 and \\\n                        self.global_steps % self.config.trainer.test_freq == 0:\n                        with _timer('testing', timing_raw):\n                            val_metrics: dict = self._validate()\n                        metrics.update(val_metrics)\n\n                    if self.config.trainer.save_freq > 0 and \\\n                            self.global_steps % self.config.trainer.save_freq == 0:\n                        with _timer('save_checkpoint', timing_raw):\n                            self._save_checkpoint()\n\n                # collect metrics\n                self._save_samples(batch, split=\"train\")\n                metrics.update(compute_data_metrics(batch=batch, use_critic=self.use_critic))\n                metrics.update(compute_timing_metrics(batch=batch, timing_raw=timing_raw))\n\n                # TODO: make a canonical logger that supports various backend\n                logger.log(data=metrics, step=self.global_steps)\n\n                self.global_steps += 1\n\n                if self.global_steps >= self.total_training_steps:\n\n                    # perform validation after training\n                    if self.val_reward_fn is not None:\n                        val_metrics = self._validate()\n                        pprint(f'Final validation metrics: {val_metrics}')\n                        logger.log(data=val_metrics, step=self.global_steps)\n                    if self.config.trainer.save_freq > 0 and \\\n                            (self.global_steps - 1) % self.config.trainer.save_freq != 0:\n                        with _timer('save_checkpoint', timing_raw):\n                            self._save_checkpoint()\n                    return\n"
  },
  {
    "path": "verl/trainer/runtime_env.yaml",
    "content": "working_dir: ./\nexcludes: [\"/.git/\"]\nenv_vars:\n  TORCH_NCCL_AVOID_RECORD_STREAMS: \"1\"\n  VLLM_ATTENTION_BACKEND: \"XFORMERS\""
  },
  {
    "path": "verl/utils/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom . import tokenizer\nfrom .tokenizer import hf_tokenizer, hf_processor\n\n__all__ = tokenizer.__all__"
  },
  {
    "path": "verl/utils/checkpoint/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License."
  },
  {
    "path": "verl/utils/checkpoint/checkpoint_manager.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nimport shutil\nfrom filelock import FileLock\nimport tempfile\nfrom typing import Union\nimport torch\nimport torch.distributed\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType\nfrom transformers import PreTrainedTokenizer, ProcessorMixin\nimport numpy as np\nimport random\n\n\nclass BaseCheckpointManager:\n    \"\"\"\n    A checkpoint manager that saves and loads\n    - model\n    - optimizer\n    - lr_scheduler\n    - extra_states\n    in a SPMD way.\n\n    We save\n    - sharded model states and optimizer states\n    - full lr_scheduler states\n    - huggingface tokenizer and config for ckpt merge\n    \"\"\"\n\n    def __init__(self, model: FSDP, optimizer: torch.optim.Optimizer,\n                 lr_scheduler: torch.optim.lr_scheduler.LRScheduler, processing_class: Union[PreTrainedTokenizer,\n                                                                                             ProcessorMixin]):\n        self.previous_global_step = None\n        self.previous_save_local_path = None\n\n        self.model = model\n        self.optimizer = optimizer\n        self.lr_scheduler = lr_scheduler\n        self.processing_class = processing_class\n\n        assert isinstance(self.model, FSDP)\n        self.rank = torch.distributed.get_rank()\n        self.world_size = torch.distributed.get_world_size()\n\n    def load_checkpoint(self, *args, **kwargs):\n        raise NotImplementedError\n\n    def save_checkpoint(self, *args, **kwargs):\n        raise NotImplementedError\n\n    def remove_previous_save_local_path(self):\n        if not self.previous_save_local_path:\n            return\n\n        abs_path = os.path.abspath(self.previous_save_local_path)\n        print(f'Checkpoint manager remove previous save local path: {abs_path}')\n        if not os.path.exists(abs_path):\n            return\n\n        # remove previous local_path\n        shutil.rmtree(abs_path, ignore_errors=True)\n\n    @staticmethod\n    def local_mkdir(path):\n        if not os.path.isabs(path):\n            working_dir = os.getcwd()\n            path = os.path.join(working_dir, path)\n\n        # Using hash value of path as lock file name to avoid long file name\n        lock_filename = f\"ckpt_{hash(path) & 0xFFFFFFFF:08x}.lock\"\n        lock_path = os.path.join(tempfile.gettempdir(), lock_filename)\n\n        try:\n            with FileLock(lock_path, timeout=60):  # Add timeout\n                # make a new dir\n                os.makedirs(path, exist_ok=True)\n        except Exception as e:\n            print(f\"Warning: Failed to acquire lock for {path}: {e}\")\n            # Even if the lock is not acquired, try to create the directory\n            os.makedirs(path, exist_ok=True)\n\n        return path\n\n    @staticmethod\n    def get_rng_state():\n        rng_state = {\n            'cpu': torch.get_rng_state(),\n            'cuda': torch.cuda.get_rng_state(),\n            'numpy': np.random.get_state(),\n            'random': random.getstate(),\n        }\n        return rng_state\n\n    @staticmethod\n    def load_rng_state(rng_state):\n        torch.set_rng_state(rng_state['cpu'])\n        torch.cuda.set_rng_state(rng_state['cuda'])\n        np.random.set_state(rng_state['numpy'])\n        random.setstate(rng_state['random'])\n\n\ndef find_latest_ckpt_path(path, directory_format=\"global_step_{}\"):\n    if path is None:\n        return None\n\n    tracker_file = get_checkpoint_tracker_filename(path)\n    if not os.path.exists(tracker_file):\n        print(\"Checkpoint tracker file does not exist: %s\", tracker_file)\n        return None\n\n    with open(tracker_file, \"rb\") as f:\n        iteration = int(f.read().decode())\n    ckpt_path = os.path.join(path, directory_format.format(iteration))\n    if not os.path.exists(ckpt_path):\n        print(\"Checkpoint does not exist: %s\", ckpt_path)\n        return None\n\n    print(\"Found checkpoint: %s\", ckpt_path)\n    return ckpt_path\n\n\ndef get_checkpoint_tracker_filename(root_path: str):\n    \"\"\"\n    Tracker file rescords the latest chckpoint during training to restart from.\n    \"\"\"\n    return os.path.join(root_path, \"latest_checkpointed_iteration.txt\")\n"
  },
  {
    "path": "verl/utils/checkpoint/fsdp_checkpoint_manager.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ray\nimport os\n\nimport warnings\nfrom typing import Union\nimport torch\nimport torch.distributed\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType\nfrom torch.distributed.fsdp import ShardedStateDictConfig, ShardedOptimStateDictConfig\n\nfrom verl.utils.fs import copy_to_local, is_non_local\n\nfrom transformers import PreTrainedTokenizer, ProcessorMixin\n\nfrom .checkpoint_manager import BaseCheckpointManager\n\n\nclass FSDPCheckpointManager(BaseCheckpointManager):\n    \"\"\"\n    A checkpoint manager that saves and loads\n    - model\n    - optimizer\n    - lr_scheduler\n    - extra_states\n    in a SPMD way.\n\n    We save \n    - sharded model states and optimizer states\n    - full lr_scheduler states\n    - huggingface tokenizer/processor and config for ckpt merge\n    \"\"\"\n\n    def __init__(self,\n                 model: FSDP,\n                 optimizer: torch.optim.Optimizer,\n                 lr_scheduler: torch.optim.lr_scheduler.LRScheduler,\n                 processing_class: Union[PreTrainedTokenizer, ProcessorMixin] = None,\n                 **kwargs):\n\n        if processing_class is None:\n            assert \"tokenizer\" in kwargs, \"tokenizer or processor must be provided\"\n            warnings.warn(\"`tokenizer` is deprecated. use `processing_class` instead.\", DeprecationWarning)\n            processing_class = kwargs.pop(\"tokenizer\")\n\n        super().__init__(model, optimizer, lr_scheduler, processing_class)\n\n    def load_checkpoint(self, path=None, del_local_after_load=False, *args, **kwargs):\n        if path is None:\n            return\n\n        # every rank download its own checkpoint\n        remote_model_path = os.path.join(path, f'model_world_size_{self.world_size}_rank_{self.rank}.pt')\n        remote_optim_path = os.path.join(path, f'optim_world_size_{self.world_size}_rank_{self.rank}.pt')\n        remote_extra_state_path = os.path.join(path, f'extra_state_world_size_{self.world_size}_rank_{self.rank}.pt')\n        print(\n            f'[rank-{self.rank}]: Loading from {remote_model_path} and {remote_optim_path} and {remote_extra_state_path}'\n        )\n        local_model_path = copy_to_local(remote_model_path)\n        local_optim_path = copy_to_local(remote_optim_path)\n        local_extra_state_path = copy_to_local(remote_extra_state_path)\n\n        model_state_dict = torch.load(local_model_path)\n        optimizer_state_dict = torch.load(local_optim_path)\n        extra_state_dict = torch.load(local_extra_state_path)\n\n        if del_local_after_load:\n            try:\n                os.remove(local_model_path) if is_non_local(local_model_path) else None\n                os.remove(local_optim_path) if is_non_local(local_optim_path) else None\n                os.remove(local_extra_state_path) if is_non_local(local_extra_state_path) else None\n            except Exception as e:\n                print(\n                    f'[rank-{self.rank}]: remove local resume ckpt file after loading failed, exception {e} will be ignored'\n                )\n\n        lr_scheduler_state_dict = extra_state_dict['lr_scheduler']\n\n        state_dict_cfg = ShardedStateDictConfig(offload_to_cpu=True)\n        optim_cfg = ShardedOptimStateDictConfig(offload_to_cpu=True)\n        with FSDP.state_dict_type(self.model, StateDictType.SHARDED_STATE_DICT, state_dict_cfg, optim_cfg):\n            self.model.load_state_dict(model_state_dict)\n            if self.optimizer is not None:\n                self.optimizer.load_state_dict(optimizer_state_dict)\n        # recover random state\n        if 'rng' in extra_state_dict:\n            # 'rng' may not exist for backward compatibility\n            self.load_rng_state(extra_state_dict['rng'])\n\n        if self.lr_scheduler is not None:\n            self.lr_scheduler.load_state_dict(lr_scheduler_state_dict)\n\n    def save_checkpoint(self, local_path: str, global_step: int, remove_previous_ckpt=False, *args, **kwargs):\n        # record the previous global step\n        self.previous_global_step = global_step\n\n        # remove previous local_path\n        # TODO: shall we remove previous ckpt every save?\n        if remove_previous_ckpt:\n            self.remove_previous_save_local_path()\n        local_path = self.local_mkdir(local_path)\n        torch.distributed.barrier()\n\n        # every rank will save its own model and optim shard\n        state_dict_cfg = ShardedStateDictConfig(offload_to_cpu=True)\n        optim_cfg = ShardedOptimStateDictConfig(offload_to_cpu=True)\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            with FSDP.state_dict_type(self.model, StateDictType.SHARDED_STATE_DICT, state_dict_cfg, optim_cfg):\n                model_state_dict = self.model.state_dict()\n                if self.optimizer is not None:\n                    optimizer_state_dict = self.optimizer.state_dict()\n                else:\n                    optimizer_state_dict = None\n                if self.lr_scheduler is not None:\n                    lr_scheduler_state_dict = self.lr_scheduler.state_dict()\n                else:\n                    lr_scheduler_state_dict = None\n\n                extra_state_dict = {\n                    'lr_scheduler': lr_scheduler_state_dict,\n                    'rng': self.get_rng_state(),\n                }\n                model_path = os.path.join(local_path, f'model_world_size_{self.world_size}_rank_{self.rank}.pt')\n                optim_path = os.path.join(local_path, f'optim_world_size_{self.world_size}_rank_{self.rank}.pt')\n                extra_path = os.path.join(local_path, f'extra_state_world_size_{self.world_size}_rank_{self.rank}.pt')\n\n                print(f'[rank-{self.rank}]: Saving model to {os.path.abspath(model_path)}')\n                print(f'[rank-{self.rank}]: Saving checkpoint to {os.path.abspath(model_path)}')\n                print(f'[rank-{self.rank}]: Saving extra_state to {os.path.abspath(extra_path)}')\n                torch.save(model_state_dict, model_path)\n                torch.save(optimizer_state_dict, optim_path)  # TODO: address optimizer is None\n                torch.save(extra_state_dict, extra_path)\n\n        # wait for everyone to dump to local\n        torch.distributed.barrier()\n\n        if self.rank == 0:\n            hf_local_path = os.path.join(local_path, 'huggingface')\n            os.makedirs(hf_local_path, exist_ok=True)\n            self.model._fsdp_wrapped_module.config.save_pretrained(hf_local_path)\n            self.processing_class.save_pretrained(hf_local_path)\n\n        torch.distributed.barrier()\n\n        self.previous_save_local_path = local_path\n"
  },
  {
    "path": "verl/utils/config.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Dict\n\nfrom omegaconf import DictConfig\n\n\ndef update_dict_with_config(dictionary: Dict, config: DictConfig):\n    for key in dictionary:\n        if hasattr(config, key):\n            dictionary[key] = getattr(config, key)\n"
  },
  {
    "path": "verl/utils/dataset/README.md",
    "content": "# Dataset Format\n## RLHF dataset\nWe combine all the data sources into a single parquet files. We directly organize the prompt into the chat format so that multi-turn chats can be easily incorporated. In the prompt, we may add instruction following texts to guide the model output the answers in a particular format so that we can extract the answers.\n\nMath problems\n```json\n{\n    \"data_source\": \"openai/gsm8k\",\n    \"prompt\": [{\"role\": \"user\", \"content\": \"Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May? Let's think step by step and output the final answer after \\\"####\\\"\"}],\n    \"ability\": \"math\",\n    \"reward_model\": {\n        \"style\": \"rule\",\n        \"ground_truth\": [\"72\"]\n    },\n}\n```\n"
  },
  {
    "path": "verl/utils/dataset/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .rl_dataset import RLHFDataset\nfrom .rm_dataset import RMDataset\nfrom .sft_dataset import SFTDataset\n"
  },
  {
    "path": "verl/utils/dataset/rl_dataset.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom omegaconf import ListConfig\nimport os\nfrom typing import List, Union, Optional\nimport copy\nimport pandas as pd\nfrom collections import defaultdict\n\nimport torch\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom transformers import PreTrainedTokenizer, ProcessorMixin\n\nfrom verl.utils.model import compute_position_id_with_mask\nimport verl.utils.torch_functional as verl_F\n\ntir_base_0307='''A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. User: Please integrate natural language reasoning with programs to solve the problem above, and put your final answer within \\\\boxed{}.\\n[PROMPT]\\nAssistant:\n'''\n\ntir_base_0309='''A conversation between User and Assistant. The user asks a question, and the Assistant solves it.\\nUser: Please integrate natural language reasoning with programs to solve the problem above, and put your final answer within \\\\boxed{}.\\n[PROMPT]\\nAssistant:\n'''\n\ndef collate_fn(data_list: list[dict]) -> dict:\n    tensors = defaultdict(list)\n    non_tensors = defaultdict(list)\n\n    for data in data_list:\n        for key, val in data.items():\n            if isinstance(val, torch.Tensor):\n                tensors[key].append(val)\n            else:\n                non_tensors[key].append(val)\n\n    for key, val in tensors.items():\n        tensors[key] = torch.stack(val, dim=0)\n\n    for key, val in non_tensors.items():\n        non_tensors[key] = np.array(val, dtype=object)\n\n    return {**tensors, **non_tensors}\n\n\ndef process_image(image: dict, max_pixels: int = 2048 * 2048, min_pixels: int = 512 * 512):\n    import math\n    from io import BytesIO\n    from PIL import Image\n\n    if isinstance(image, dict):\n        image = Image.open(BytesIO(image['bytes']))\n\n    if (image.width * image.height) > max_pixels:\n        resize_factor = math.sqrt(max_pixels / (image.width * image.height))\n        width, height = int(image.width * resize_factor), int(image.height * resize_factor)\n        image = image.resize((width, height))\n\n    if (image.width * image.height) < min_pixels:\n        resize_factor = math.sqrt(min_pixels / (image.width * image.height))\n        width, height = int(image.width * resize_factor), int(image.height * resize_factor)\n        image = image.resize((width, height))\n\n    if image.mode != 'RGB':\n        image = image.convert('RGB')\n\n    return image\n\n\nclass RLHFDataset(Dataset):\n    \"\"\"\n    We assume the dataset contains a column that contains prompts and other information\n    \"\"\"\n\n    def __init__(self,\n                 parquet_files: Union[str, List[str]],\n                 tokenizer: PreTrainedTokenizer,\n                 processor: Optional[ProcessorMixin] = None,\n                 prompt_key='prompt',\n                 image_key='images',\n                 max_prompt_length=1024,\n                 filter_prompts=True,\n                 cache_dir='~/.cache/verl/rlhf',\n                 chat_template_func=None,\n                 return_raw_chat=False,\n                 truncation='error',\n                 template_type='default'):\n        if not isinstance(parquet_files, (List, ListConfig)):\n            parquet_files = [parquet_files]\n\n        self.parquet_files = copy.deepcopy(parquet_files)\n        self.original_parquet_files = copy.deepcopy(parquet_files)  # use for resume\n        self.cache_dir = os.path.expanduser(cache_dir)\n        self.tokenizer = tokenizer\n        self.processor = processor\n\n        self.prompt_key = prompt_key\n        self.image_key = image_key\n        self.max_prompt_length = max_prompt_length\n        self.filter_prompts = filter_prompts\n\n        self.return_raw_chat = return_raw_chat\n        self.chat_template_func = chat_template_func\n        self.truncation = truncation\n        self.template_type = template_type\n\n        # whether to store the dataset in state_dict()\n        # default not store\n        self.serialize_dataset = False\n        self._download()\n        self._read_files_and_tokenize()\n\n    def _download(self, use_origin_parquet=False):\n        from verl.utils.fs import copy_to_local\n        parquet_files = self.parquet_files if not use_origin_parquet else self.original_parquet_files\n        for i, parquet_file in enumerate(parquet_files):\n            self.parquet_files[i] = copy_to_local(src=parquet_file, cache_dir=self.cache_dir)\n\n    def _read_files_and_tokenize(self):\n        dataframes = []\n        for parquet_file in self.parquet_files:\n            # read parquet files and cache\n            dataframe = pd.read_parquet(parquet_file)\n            dataframes.append(dataframe)\n        self.dataframe = pd.concat(dataframes)\n\n        print(f'original dataset len: {len(self.dataframe)}')\n\n        # filter out too long prompts\n        tokenizer = self.tokenizer\n        prompt_key = self.prompt_key\n        if self.template_type==\"default\":\n            self.dataframe = self.dataframe[self.dataframe.apply(lambda doc: len(\n            tokenizer.apply_chat_template(doc[prompt_key], add_generation_prompt=True)) <= self.max_prompt_length,\n                                                             axis=1)]\n        elif self.template_type==\"tir_base_0307\":\n            self.dataframe = self.dataframe[self.dataframe.apply(lambda doc: len(tokenizer.encode(tir_base_0307.replace(\"[PROMPT]\", doc[prompt_key][1]['content']))) <= self.max_prompt_length-10, axis=1)]\n        elif self.template_type==\"tir_base_0309\":\n            self.dataframe = self.dataframe[self.dataframe.apply(lambda doc: len(tokenizer.encode(tir_base_0309.replace(\"[PROMPT]\", doc[prompt_key][1]['content']))) <= self.max_prompt_length-10, axis=1)]\n\n        print(f'filter dataset len: {len(self.dataframe)}')\n\n    def resume_dataset_state(self):\n        self.serialize_dataset = False if hasattr(self, 'original_parquet_files') else True\n        # resume dataframe if not it's serialized in data.pt\n        if not self.serialize_dataset:\n            self._download(use_origin_parquet=True)  # download and resume from original parquet files\n            self._read_files_and_tokenize()\n        else:\n            print(r'old dataloader ckpt file is used, please train from scratch for better ckpt performance')\n\n    def __len__(self):\n        return len(self.dataframe)\n\n    def __getitem__(self, item):\n        \"\"\"\n        Note that we also return the raw_input_ids so that it can be combined with other chat template\n        \"\"\"\n        row_dict: dict = self.dataframe.iloc[item].to_dict()\n\n        chat = row_dict.pop(self.prompt_key)\n\n        if self.template_type==\"default\":\n            prompt_with_chat_template = self.tokenizer.apply_chat_template(chat, add_generation_prompt=True, tokenize=False)\n        elif self.template_type==\"tir_base_0307\":\n            prompt_with_chat_template = tir_base_0307.replace(\"[PROMPT]\", chat[1]['content'])\n        elif self.template_type==\"tir_base_0309\":\n            prompt_with_chat_template = tir_base_0309.replace(\"[PROMPT]\", chat[1]['content'])\n\n        if self.image_key in row_dict:  # expand image token\n            raw_prompt = prompt_with_chat_template.replace('<image>', '<|vision_start|><|image_pad|><|vision_end|>')\n            row_dict['multi_modal_data'] = {'image': [process_image(image) for image in row_dict.pop(self.image_key)]}\n            image_inputs = self.processor.image_processor(row_dict['multi_modal_data']['image'], return_tensors='pt')\n            image_grid_thw = image_inputs['image_grid_thw']\n            row_dict['multi_modal_inputs'] = {key: val for key, val in image_inputs.items()}\n\n            if image_grid_thw is not None:\n                merge_length = self.processor.image_processor.merge_size**2\n                index = 0\n                while '<image>' in prompt_with_chat_template:\n                    prompt_with_chat_template = prompt_with_chat_template.replace(\n                        '<image>',\n                        '<|vision_start|>' + '<|placeholder|>' * (image_grid_thw[index].prod() // merge_length) +\n                        '<|vision_end|>',\n                        1,\n                    )\n                    index += 1\n\n                prompt_with_chat_template = prompt_with_chat_template.replace('<|placeholder|>',\n                                                                              self.processor.image_token)\n        else:\n            raw_prompt = prompt_with_chat_template\n\n        input_ids, attention_mask = verl_F.tokenize_and_postprocess_data(prompt=prompt_with_chat_template,\n                                                                         tokenizer=self.tokenizer,\n                                                                         max_length=self.max_prompt_length,\n                                                                         pad_token_id=self.tokenizer.pad_token_id,\n                                                                         left_pad=True,\n                                                                         truncation=self.truncation)\n\n        if self.image_key in row_dict:\n            from verl.models.transformers.qwen2_vl import get_rope_index\n\n            position_ids = get_rope_index(\n                self.processor,\n                input_ids=input_ids[0],\n                image_grid_thw=image_grid_thw,\n                attention_mask=attention_mask[0],\n            )  # (3, seq_len)\n        else:\n            position_ids = compute_position_id_with_mask(attention_mask)\n\n        row_dict['input_ids'] = input_ids[0]\n        row_dict['attention_mask'] = attention_mask[0]\n        row_dict['position_ids'] = position_ids[0]\n        row_dict['raw_prompt_ids'] = self.tokenizer.encode(raw_prompt, add_special_tokens=False)\n\n        # encode prompts without chat template\n        if self.return_raw_chat:\n            row_dict['raw_prompt'] = chat.tolist()\n\n        # add index for each prompt\n        index = row_dict.get(\"extra_info\", {}).get(\"index\", 0)\n        row_dict[\"index\"] = index\n\n        return row_dict\n\n    def __getstate__(self):\n        if not self.serialize_dataset:\n            state = self.__dict__.copy()\n\n            if 'dataframe' in state:\n                del state['dataframe']\n            return state\n        return self.__dict__.copy()\n"
  },
  {
    "path": "verl/utils/dataset/rm_dataset.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom typing import List, Union\n\nimport pandas as pd\n\nimport torch\nfrom torch.utils.data import Dataset\nfrom transformers import AutoTokenizer\n\nfrom verl.utils import hf_tokenizer\n\n\ndef download_files_distributed(download_fn):\n    import torch.distributed\n    if torch.distributed.is_initialized():\n        if torch.distributed.get_rank() == 0:\n            # download files\n            download_fn()\n\n        torch.distributed.barrier()\n    else:\n        # download anyway\n        download_fn()\n\n\nclass RMDataset(Dataset):\n\n    def __init__(self,\n                 parquet_files: Union[str, List[str]],\n                 tokenizer,\n                 prompt_key='prompt',\n                 chosen_key='chosen',\n                 rejected_key='rejected',\n                 max_length=1024,\n                 add_eos=True,\n                 cache_dir='~/.cache/verl/rm'):\n        if not isinstance(parquet_files, List):\n            parquet_files = [parquet_files]\n\n        self.parquet_files = parquet_files\n        self.cache_dir = os.path.expanduser(cache_dir)\n        if isinstance(tokenizer, str):\n            tokenizer = hf_tokenizer(tokenizer)\n        self.tokenizer = tokenizer\n\n        self.prompt_key = prompt_key\n        self.chosen_key = chosen_key\n        self.rejected_key = rejected_key\n\n        self.add_eos = add_eos\n        self.max_length = max_length\n\n        self._download()\n        self._read_files_and_tokenize()\n\n    def _download(self):\n\n        def _download_files():\n            from verl.utils.fs import copy, is_non_local\n            os.makedirs(self.cache_dir, exist_ok=True)\n            assert os.path.exists(self.cache_dir)\n            for i, parquet_file in enumerate(self.parquet_files):\n                if is_non_local(parquet_file):\n                    dst = os.path.join(self.cache_dir, os.path.basename(parquet_file))\n                    if not os.path.exists(dst):\n                        copy(src=parquet_file, dst=dst)\n                    self.parquet_files[i] = dst\n\n        download_files_distributed(_download_files)\n\n    def _read_files_and_tokenize(self):\n        dataframes = []\n        for parquet_file in self.parquet_files:\n            # read parquet files and cache\n            dataframe = pd.read_parquet(parquet_file)\n            dataframes.append(dataframe)\n        self.dataframe = pd.concat(dataframes)\n        self.prompts = self.dataframe[self.prompt_key].tolist()\n        self.chosen_responses = self.dataframe[self.chosen_key].tolist()\n        self.rejected_responses = self.dataframe[self.rejected_key].tolist()\n\n    def __len__(self):\n        return len(self.prompts)\n\n    def _pad_to_length(self, input_ids, attention_mask):\n        curr_length = input_ids.shape[-1]\n\n        if curr_length < self.max_length:\n            input_ids = torch.cat(\n                (input_ids, torch.zeros(size=(self.max_length - curr_length,), dtype=input_ids.dtype)), dim=-1)\n            attention_mask = torch.cat(\n                (attention_mask, torch.zeros(size=(self.max_length - curr_length,), dtype=attention_mask.dtype)),\n                dim=-1)\n        elif curr_length > self.max_length:\n            input_ids = input_ids[:self.max_length]\n            attention_mask = attention_mask[:self.max_length]\n\n        return input_ids, attention_mask\n\n    def __getitem__(self, item):\n        prompt = self.prompts[item]\n        chosen_response = self.chosen_responses[item]\n        rejected_response = self.rejected_responses[item]\n\n        prompt_ids = self.tokenizer(prompt, return_tensors='pt')['input_ids'][0]\n        chosen_response_ids = self.tokenizer(chosen_response, return_tensors='pt')['input_ids'][0]\n        rejected_response_ids = self.tokenizer(rejected_response, return_tensors='pt')['input_ids'][0]\n\n        if self.add_eos:\n            chosen_response_ids = torch.cat((chosen_response_ids, torch.tensor([self.tokenizer.eos_token_id])), dim=-1)\n            rejected_response_ids = torch.cat((rejected_response_ids, torch.tensor([self.tokenizer.eos_token_id])),\n                                              dim=-1)\n\n        chosen_input_ids = torch.cat((prompt_ids, chosen_response_ids), dim=-1)\n        chosen_attention_mask = torch.ones_like(chosen_input_ids)\n\n        rejected_input_ids = torch.cat((prompt_ids, rejected_response_ids), dim=-1)\n        rejected_attention_mask = torch.ones_like(rejected_input_ids)\n\n        chosen_input_ids, chosen_attention_mask = self._pad_to_length(chosen_input_ids, chosen_attention_mask)\n        rejected_input_ids, rejected_attention_mask = self._pad_to_length(rejected_input_ids, rejected_attention_mask)\n\n        input_ids = torch.stack((chosen_input_ids, rejected_input_ids), dim=0)\n        attention_mask = torch.stack((rejected_input_ids, rejected_attention_mask), dim=0)\n\n        return {\n            'input_ids': input_ids,\n            'attention_mask': attention_mask,\n        }"
  },
  {
    "path": "verl/utils/dataset/sft_dataset.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nSFT dataset\n- We assume user pass a single parquet file.\n- We load all the data into the memory.\nEach parquet file contains\n\"\"\"\n\nfrom typing import List, Union\n\nimport pandas as pd\n\nimport torch\nfrom torch.utils.data import Dataset\nfrom transformers import AutoTokenizer, PreTrainedTokenizer\n\nfrom verl.utils.fs import copy_to_local\nfrom verl.utils.model import compute_position_id_with_mask\nfrom verl.utils import hf_tokenizer\n\n\nclass SFTDataset(Dataset):\n    \"\"\"\n    This is an in-memory SFTDataset\n    \"\"\"\n\n    def __init__(self,\n                 parquet_files: Union[str, List[str]],\n                 tokenizer,\n                 prompt_key='prompt',\n                 prompt_dict_keys=None,\n                 response_key='response',\n                 response_dict_keys=None,\n                 max_length=1024,\n                 truncation='error'):\n        assert truncation in ['error', 'left', 'right']\n        self.truncation = truncation\n\n        if not isinstance(parquet_files, List):\n            parquet_files = [parquet_files]\n\n        self.parquet_files = parquet_files\n        if isinstance(tokenizer, str):\n            tokenizer = hf_tokenizer(tokenizer)\n        self.tokenizer: PreTrainedTokenizer = tokenizer\n\n        self.prompt_key = prompt_key if isinstance(prompt_key, (tuple, list)) else [prompt_key]\n        self.response_key = response_key if isinstance(response_key, (tuple, list)) else [response_key]\n        self.prompt_dict_keys = [] if not prompt_dict_keys else prompt_dict_keys\n        self.response_dict_keys = [] if not response_dict_keys else response_dict_keys\n\n        self.max_length = max_length\n\n        self._download()\n        self._read_files_and_tokenize()\n\n    def _download(self):\n        for i, parquet_file in enumerate(self.parquet_files):\n            self.parquet_files[i] = copy_to_local(parquet_file, verbose=True)\n\n    def _read_files_and_tokenize(self):\n\n        def series_to_item(ls):\n            import pandas, numpy\n            while isinstance(ls, (pandas.core.series.Series, numpy.ndarray)) and len(ls) == 1:\n                ls = ls[0]\n            return ls\n\n        dataframes = []\n        for parquet_file in self.parquet_files:\n            # read parquet files and cache\n            dataframe = pd.read_parquet(parquet_file)\n            dataframes.append(dataframe)\n        self.dataframe = pd.concat(dataframes)\n        self.prompts = self.dataframe[self.prompt_key]\n        for key in self.prompt_dict_keys:\n            # type(x): pandas.core.series.Series\n            # type(x[0]): numpy.ndarray\n            # type(x[0][0]): dict\n            try:\n                self.prompts = self.prompts.apply(lambda x: series_to_item(x)[key], axis=1)\n            except Exception:\n                print(f'self.prompts={self.prompts}')\n                raise\n        self.prompts = self.prompts.tolist()\n        self.responses = self.dataframe[self.response_key]\n        for key in self.response_dict_keys:\n            try:\n                self.responses = self.responses.apply(lambda x: series_to_item(x)[key], axis=1)\n            except Exception:\n                print(f'self.responses={self.responses}')\n                raise\n        self.responses = self.responses.tolist()\n\n    def __len__(self):\n        return len(self.prompts)\n\n    def __getitem__(self, item):\n        tokenizer = self.tokenizer\n\n        prompt = self.prompts[item]\n        response = self.responses[item]\n\n        # apply chat template\n        prompt_chat = [{'role': 'user', 'content': prompt}]\n\n        # string\n        prompt_chat_str = tokenizer.apply_chat_template(prompt_chat, add_generation_prompt=True, tokenize=False)\n        response_chat_str = response + tokenizer.eos_token\n\n        # tokenize\n        prompt_ids_output = tokenizer(prompt_chat_str, return_tensors='pt', add_special_tokens=False)\n        prompt_ids = prompt_ids_output['input_ids'][0]\n        prompt_attention_mask = prompt_ids_output['attention_mask'][0]\n\n        response_ids_output = tokenizer(response_chat_str, return_tensors='pt', add_special_tokens=False)\n        response_ids = response_ids_output['input_ids'][0]\n        response_attention_mask = response_ids_output['attention_mask'][0]\n\n        prompt_length = prompt_ids.shape[0]\n        response_length = response_ids.shape[0]\n\n        input_ids = torch.cat((prompt_ids, response_ids), dim=-1)\n        attention_mask = torch.cat((prompt_attention_mask, response_attention_mask), dim=-1)\n\n        # padding to max length\n        sequence_length = input_ids.shape[0]\n        if sequence_length < self.max_length:\n            padded_input_ids = torch.ones(size=(self.max_length - sequence_length,),\n                                          dtype=input_ids.dtype) * self.tokenizer.pad_token_id\n            padded_attention_mask = torch.zeros(size=(self.max_length - sequence_length,), dtype=attention_mask.dtype)\n\n            input_ids = torch.cat((input_ids, padded_input_ids))\n            attention_mask = torch.cat((attention_mask, padded_attention_mask))\n        elif sequence_length > self.max_length:\n            if self.truncation == 'left':\n                # actually, left truncation may not be reasonable\n                input_ids = input_ids[-self.max_length:]\n                attention_mask = attention_mask[-self.max_length:]\n            elif self.truncation == 'right':\n                input_ids = input_ids[:self.max_length]\n                attention_mask = attention_mask[:self.max_length]\n            elif self.truncation == 'error':\n                raise NotImplementedError(f'{sequence_length=} is larger than {self.max_length=}')\n            else:\n                raise NotImplementedError(f'Unknown truncation method {self.truncation}')\n\n        position_ids = compute_position_id_with_mask(attention_mask)\n\n        loss_mask = attention_mask.clone()\n        if prompt_length > 1:\n            # mask out prompt for SFT.\n            loss_mask[:min(prompt_length, loss_mask.size(0)) - 1] = 0\n        # mask out the last token in response\n        loss_mask[min(prompt_length + response_length, loss_mask.size(0)) - 1] = 0\n\n        return {\n            'input_ids': input_ids,\n            'attention_mask': attention_mask,\n            'position_ids': position_ids,\n            'loss_mask': loss_mask\n        }\n"
  },
  {
    "path": "verl/utils/debug/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .performance import log_gpu_memory_usage"
  },
  {
    "path": "verl/utils/debug/performance.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport torch.distributed as dist\nimport logging\n\n\ndef log_gpu_memory_usage(head: str, logger: logging.Logger = None, level=logging.DEBUG, rank: int = 0):\n    if (not dist.is_initialized()) or (rank is None) or (dist.get_rank() == rank):\n        memory_allocated = torch.cuda.memory_allocated() / 1024**3\n        memory_reserved = torch.cuda.memory_reserved() / 1024**3\n\n        message = f'{head}, memory allocated (GB): {memory_allocated}, memory reserved (GB): {memory_reserved}'\n\n        if logger is None:\n            print(message)\n        else:\n            logger.log(msg=message, level=level)\n"
  },
  {
    "path": "verl/utils/debug/trajectory_tracker.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nTrajectory tracker can be inserted into code to save the intermediate results.\nThe results will be dump to hdfs for offline comparison.\nEach process will have a client that first move all the tensors to CPU\n\"\"\"\n\nfrom verl.utils.hdfs_io import makedirs, copy\nimport torch\nimport os\nimport ray\nimport io\nimport tempfile\n\nfrom collections import deque\n\nremote_copy = ray.remote(copy)\n\n\n@ray.remote\ndef save_to_hdfs(data: io.BytesIO, name, hdfs_dir, verbose):\n    filename = name + '.pth'\n    with tempfile.TemporaryDirectory() as tmpdirname:\n        local_filepath = os.path.join(tmpdirname, filename)\n        with open(local_filepath, 'wb') as f:\n            f.write(data.getbuffer())\n        # upload to hdfs\n\n        if verbose:\n            print(f'Saving {local_filepath} to {hdfs_dir}')\n        try:\n            copy(local_filepath, hdfs_dir)\n        except Exception as e:\n            print(e)\n\n\n@ray.remote\nclass TrajectoryTracker():\n\n    def __init__(self, hdfs_dir, verbose) -> None:\n        self.hdfs_dir = hdfs_dir\n        makedirs(hdfs_dir)\n        self.verbose = verbose\n\n        self.handle = deque()\n\n    def dump(self, data: io.BytesIO, name):\n        # get a temp file and write to it\n        self.handle.append(save_to_hdfs.remote(data, name, self.hdfs_dir, self.verbose))\n\n    def wait_for_hdfs(self):\n        while len(self.handle) != 0:\n            future = self.handle.popleft()\n            ray.get(future)\n\n\ndef dump_data(data, name):\n    enable = os.getenv('VERL_ENABLE_TRACKER', '0') == '1'\n    if not enable:\n        return\n    buffer = io.BytesIO()\n    torch.save(data, buffer)\n    tracker = get_trajectory_tracker()\n    ray.get(tracker.dump.remote(buffer, name))\n\n\ndef get_trajectory_tracker():\n    hdfs_dir = os.getenv('VERL_TRACKER_HDFS_DIR', default=None)\n    verbose = os.getenv('VERL_TRACKER_VERBOSE', default='0') == '1'\n    assert hdfs_dir is not None\n    tracker = TrajectoryTracker.options(name=\"global_tracker\", get_if_exists=True,\n                                        lifetime=\"detached\").remote(hdfs_dir, verbose)\n    return tracker\n\n\nif __name__ == '__main__':\n    # testing\n    os.environ['VERL_ENABLE_TRACKER'] = '1'\n    os.environ['VERL_TRACKER_HDFS_DIR'] = '~/debug/test'\n\n    @ray.remote\n    def process(iter):\n        data = {'obs': torch.randn(10, 20)}\n        dump_data(data, f'process_{iter}_obs')\n\n    ray.init()\n\n    output_lst = []\n\n    for i in range(10):\n        output_lst.append(process.remote(i))\n\n    out = ray.get(output_lst)\n\n    tracker = get_trajectory_tracker()\n    ray.get(tracker.wait_for_hdfs.remote())\n"
  },
  {
    "path": "verl/utils/distributed.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utilities for distributed training.\"\"\"\nimport os\n\n\ndef initialize_global_process_group(timeout_second=36000):\n    import torch.distributed\n    from datetime import timedelta\n    torch.distributed.init_process_group('nccl', timeout=timedelta(seconds=timeout_second))\n    local_rank = int(os.environ[\"LOCAL_RANK\"])\n    rank = int(os.environ[\"RANK\"])\n    world_size = int(os.environ[\"WORLD_SIZE\"])\n\n    if torch.distributed.is_initialized():\n        torch.cuda.set_device(local_rank)\n    return local_rank, rank, world_size\n"
  },
  {
    "path": "verl/utils/flops_counter.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nfrom transformers import PretrainedConfig\n\nVALID_CONFIG_TYPE = {\"llama\", \"qwen2\", \"qwen2_vl\", \"qwen2_5_vl\"}\n\n\ndef get_device_flops(unit=\"T\"):\n\n    def unit_convert(number, level):\n        units = [\"B\", \"K\", \"M\", \"G\", \"T\", \"P\"]\n        if number <= 0:\n            return number\n        ptr = 0\n        while ptr < len(units) and units[ptr] != level:\n            number /= 1000\n            ptr += 1\n        return number\n\n    device_name = torch.cuda.get_device_name()\n    flops = float(\"inf\")  # INF flops for unkown gpu type\n    if \"H100\" in device_name or \"H800\" in device_name:\n        flops = 989e12\n    elif \"A100\" in device_name or \"A800\" in device_name:\n        flops = 312e12\n    elif \"L40\" in device_name:\n        flops = 181.05e12\n    elif \"L20\" in device_name:\n        flops = 119.5e12\n    elif \"H20\" in device_name:\n        flops = 148e12\n    elif \"910B\" in device_name:\n        flops = 354e12\n    flops_unit = unit_convert(flops, unit)\n    return flops_unit\n\n\nclass FlopsCounter:\n    \"\"\"\n    Used to count mfu during training loop\n\n    Example:\n        flops_counter = FlopsCounter(config)\n        flops_achieved, flops_promised = flops_counter.estimate_flops(tokens_list, delta_time)\n\n    \"\"\"\n\n    def __init__(self, config: PretrainedConfig):\n        if not config.model_type in VALID_CONFIG_TYPE:\n            print(f\"Only support config type of {VALID_CONFIG_TYPE}, but got {self.config.model_type}. \"\n                  f\"MFU will always be zero.\")\n\n        self.estimate_func = {\n            'qwen2': self._estimate_qwen2_flops,\n            'llama': self._estimate_qwen2_flops,\n            'qwen2_vl': self._estimate_qwen2_flops,\n            'qwen2_5_vl': self._estimate_qwen2_flops\n        }\n        self.config = config\n\n    def _estimate_unknown_flops(self, tokens_sum, batch_seqlens, delta_time):\n        return 0\n\n    def _estimate_qwen2_flops(self, tokens_sum, batch_seqlens, delta_time):\n        hidden_size = self.config.hidden_size\n        vocab_size = self.config.vocab_size\n        num_hidden_layers = self.config.num_hidden_layers\n        num_key_value_heads = self.config.num_key_value_heads\n        num_attention_heads = self.config.num_attention_heads\n        intermediate_size = self.config.intermediate_size\n\n        head_dim = hidden_size // num_attention_heads\n        q_size = num_attention_heads * head_dim\n        k_size = num_key_value_heads * head_dim\n        v_size = num_key_value_heads * head_dim\n\n        # non-attn per layer parm\n        # Qwen2/LLama use SwiGelu, gate, having up and down linear layer in mlp\n        mlp_N = hidden_size * intermediate_size * 3\n        attn_linear_N = hidden_size * (q_size + k_size + v_size + num_attention_heads * head_dim)\n        emd_and_lm_head_N = vocab_size * hidden_size * 2\n        # non-attn all_layer parm\n        dense_N = (mlp_N + attn_linear_N) * num_hidden_layers + emd_and_lm_head_N\n        # non-attn all_layer & all_token fwd & bwd flops\n        dense_N_flops = 6 * dense_N * tokens_sum\n\n        # attn all_layer & all_token fwd & bwd flops\n        seqlen_square_sum = 0\n        for seqlen in batch_seqlens:\n            seqlen_square_sum += seqlen * seqlen\n        attn_qkv_flops = 12 * seqlen_square_sum * head_dim * num_attention_heads * num_hidden_layers\n\n        # all_layer & all_token fwd & bwd flops\n        flops_all_token = dense_N_flops + attn_qkv_flops\n        flops_achieved = flops_all_token * (1.0 / delta_time) / 1e12\n        return flops_achieved\n\n    def estimate_flops(self, batch_seqlens, delta_time):\n        \"\"\"\n        Estimate the FLOPS based on the number of valid tokens in the current batch and the time taken.\n\n        Args:\n            batch_seqlens (List[int]): A list where each element represents the number of valid tokens in the current batch.\n            delta_time (float): The time taken to process the batch, in seconds.\n\n        Returns:\n            estimated_flops (float): The estimated FLOPS based on the input tokens and time.\n            promised_flops (float): The expected FLOPS of the current device.\n        \"\"\"\n        tokens_sum = sum(batch_seqlens)\n        func = self.estimate_func.get(self.config.model_type, self._estimate_unknown_flops)\n        estimated_flops = func(tokens_sum, batch_seqlens, delta_time)\n        promised_flops = get_device_flops()\n        return estimated_flops, promised_flops\n"
  },
  {
    "path": "verl/utils/fs.py",
    "content": "#!/usr/bin/env python\n# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# -*- coding: utf-8 -*-\n\"\"\"File-system agnostic IO APIs\"\"\"\nimport os\nimport tempfile\nimport hashlib\n\ntry:\n    from hdfs_io import copy, makedirs, exists  # for internal use only\nexcept ImportError:\n    from .hdfs_io import copy, makedirs, exists\n\n__all__ = [\"copy\", \"exists\", \"makedirs\"]\n\n_HDFS_PREFIX = \"hdfs://\"\n\n\ndef is_non_local(path):\n    return path.startswith(_HDFS_PREFIX)\n\n\ndef md5_encode(path: str) -> str:\n    return hashlib.md5(path.encode()).hexdigest()\n\n\ndef get_local_temp_path(hdfs_path: str, cache_dir: str) -> str:\n    \"\"\"Return a local temp path that joins cache_dir and basename of hdfs_path\n\n    Args:\n        hdfs_path:\n        cache_dir:\n\n    Returns:\n\n    \"\"\"\n    # make a base64 encoding of hdfs_path to avoid directory conflict\n    encoded_hdfs_path = md5_encode(hdfs_path)\n    temp_dir = os.path.join(cache_dir, encoded_hdfs_path)\n    os.makedirs(temp_dir, exist_ok=True)\n    dst = os.path.join(temp_dir, os.path.basename(hdfs_path))\n    return dst\n\n\ndef copy_to_local(src: str, cache_dir=None, filelock='.file.lock', verbose=False) -> str:\n    \"\"\"Copy src from hdfs to local if src is on hdfs or directly return src.\n    If cache_dir is None, we will use the default cache dir of the system. Note that this may cause conflicts if\n    the src name is the same between calls\n\n    Args:\n        src (str): a HDFS path of a local path\n\n    Returns:\n        a local path of the copied file\n    \"\"\"\n    return copy_local_path_from_hdfs(src, cache_dir, filelock, verbose)\n\n\ndef copy_local_path_from_hdfs(src: str, cache_dir=None, filelock='.file.lock', verbose=False) -> str:\n    \"\"\"Deprecated. Please use copy_to_local instead.\"\"\"\n    from filelock import FileLock\n\n    assert src[-1] != '/', f'Make sure the last char in src is not / because it will cause error. Got {src}'\n\n    if is_non_local(src):\n        # download from hdfs to local\n        if cache_dir is None:\n            # get a temp folder\n            cache_dir = tempfile.gettempdir()\n        os.makedirs(cache_dir, exist_ok=True)\n        assert os.path.exists(cache_dir)\n        local_path = get_local_temp_path(src, cache_dir)\n        # get a specific lock\n        filelock = md5_encode(src) + '.lock'\n        lock_file = os.path.join(cache_dir, filelock)\n        with FileLock(lock_file=lock_file):\n            if not os.path.exists(local_path):\n                if verbose:\n                    print(f'Copy from {src} to {local_path}')\n                copy(src, local_path)\n        return local_path\n    else:\n        return src\n"
  },
  {
    "path": "verl/utils/fsdp_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Dict\nimport functools\nimport json\nimport math\nimport itertools\nimport os\nfrom contextlib import contextmanager\nfrom torch.distributed.fsdp.wrap import size_based_auto_wrap_policy, transformer_auto_wrap_policy\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP\nfrom torch.distributed.fsdp._runtime_utils import _lazy_init\nfrom transformers.trainer_pt_utils import get_module_class_from_name\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\n\n\ndef init_fn(x: torch.nn.Module):\n    if not torch.distributed.get_rank() == 0:\n        x = x.to_empty(device=torch.cuda.current_device(), recurse=False)\n        torch.cuda.empty_cache()\n    return x\n\n\ndef get_init_weight_context_manager(use_meta_tensor=True):\n    from accelerate import init_empty_weights\n    cpu_init_weights = lambda: torch.device('cpu')\n    if use_meta_tensor:\n        init_context = init_empty_weights if torch.distributed.get_rank() != 0 else cpu_init_weights\n    else:\n        init_context = cpu_init_weights\n    return init_context\n\n\n# Copyright 2020-present the HuggingFace Inc. team.\n# Adapted from https://github.com/huggingface/transformers/src/transformers/trainer.py\ndef get_fsdp_wrap_policy(module, config=None, is_lora=False):\n    \"\"\"Get FSDP wrap policy for the module.\n    \n    Args:\n        module: The module to get wrap policy for\n        config: Configuration for wrap policy\n        is_lora: Whether to enable lambda policy for LoRA modules\n    \"\"\"\n    if config is None:\n        config = {}\n\n    if config.get('disable', False):\n        return None\n\n    default_transformer_cls_names_to_wrap = getattr(module, \"_no_split_modules\", None)\n    fsdp_transformer_layer_cls_to_wrap = config.get(\"transformer_layer_cls_to_wrap\",\n                                                    default_transformer_cls_names_to_wrap)\n    min_num_params = config.get('min_num_params', 0)\n    auto_wrap_policy = None\n\n    policies = []\n\n    from torch.distributed.fsdp.wrap import _or_policy, lambda_auto_wrap_policy, transformer_auto_wrap_policy\n\n    # Add lambda policy for LoRA modules if is_lora is True\n    if is_lora:\n\n        def lambda_policy_fn(module):\n            if (len(list(module.named_children())) == 0 and getattr(module, \"weight\", None) is not None and\n                    module.weight.requires_grad):\n                return True\n            return False\n\n        lambda_policy = functools.partial(lambda_auto_wrap_policy, lambda_fn=lambda_policy_fn)\n        policies.append(lambda_policy)\n\n    if min_num_params > 0:\n        size_policy = functools.partial(size_based_auto_wrap_policy, min_num_params=min_num_params)\n        policies.append(size_policy)\n    elif fsdp_transformer_layer_cls_to_wrap is not None:\n        transformer_cls_to_wrap = set()\n        for layer_class in fsdp_transformer_layer_cls_to_wrap:\n            transformer_cls = get_module_class_from_name(module, layer_class)\n            if transformer_cls is None:\n                raise Exception(\"Could not find the transformer layer class to wrap in the model.\")\n            else:\n                transformer_cls_to_wrap.add(transformer_cls)\n\n        transformer_policy = functools.partial(\n            transformer_auto_wrap_policy,\n            transformer_layer_cls=transformer_cls_to_wrap,\n        )\n        policies.append(transformer_policy)\n\n    if len(policies) > 0:\n        auto_wrap_policy = functools.partial(_or_policy, policies=policies)\n\n    return auto_wrap_policy\n\n\n@torch.no_grad()\ndef offload_fsdp_model_to_cpu(model: FSDP, empty_cache: bool = True):\n    assert isinstance(model, FSDP)\n    # lazy init FSDP model\n    _lazy_init(model, model)\n    assert model._is_root, f\"Only support root model offloading to CPU\"\n    for handle in model._all_handles:\n        if handle._offload_params:\n            continue\n        flat_param = handle.flat_param\n        assert flat_param.data.data_ptr() == flat_param._local_shard.data_ptr() and \\\n            id(flat_param.data) != id(flat_param._local_shard) and \\\n            flat_param.data.size() == flat_param._local_shard.size()\n        handle.flat_param_to(torch.device(\"cpu\"), non_blocking=True)\n        # the following still keeps id(._local_shard) != id(.data)\n        flat_param._local_shard = flat_param.data\n        assert id(flat_param._local_shard) != id(flat_param.data)\n    if empty_cache:\n        torch.cuda.empty_cache()\n\n\n@torch.no_grad()\ndef load_fsdp_model_to_gpu(model: FSDP):\n    assert isinstance(model, FSDP)\n    # lazy init FSDP model\n    _lazy_init(model, model)\n    assert model._is_root, f\"Only support root model loading to GPU\"\n    device_id = torch.cuda.current_device()\n    for handle in model._all_handles:\n        if handle._offload_params:\n            continue\n        flat_param = handle.flat_param\n        handle.flat_param_to(torch.device(f\"cuda:{device_id}\"), non_blocking=True)\n        # the following still keeps id(._local_shard) != id(.data)\n        flat_param._local_shard = flat_param.data\n\n\n@torch.no_grad()\ndef offload_fsdp_optimizer(optimizer):\n    if not optimizer.state:\n        return\n    for param_group in optimizer.param_groups:\n        for param in param_group['params']:\n            state = optimizer.state[param]\n            for key, value in state.items():\n                if isinstance(value, torch.Tensor):\n                    state[key] = value.to(\"cpu\", non_blocking=True)\n\n\n@torch.no_grad()\ndef load_fsdp_optimizer(optimizer, device_id):\n    if not optimizer.state:\n        return\n    for param_group in optimizer.param_groups:\n        for param in param_group['params']:\n            state = optimizer.state[param]\n            for key, value in state.items():\n                if isinstance(value, torch.Tensor):\n                    state[key] = value.to(device_id, non_blocking=True)\n\n\n@contextmanager\ndef meta_device_init():\n    \"\"\"\n    Create model parameters with meta device.\n\n    Note buffers in model will still be initialized in default device (e.g., CPU),\n    since the buffers can be non-persistent and filled with expected values that can\n    NOT be captured in meta device.\n    \"\"\"\n    device = torch.device(\"meta\")\n    old_register_parameter = nn.Module.register_parameter\n    registered = set()\n\n    def register_empty_parameter(module, name, param):\n        old_register_parameter(module, name, param)\n        # we will skip register shared parameters as it\n        # is already registered previously\n        if param is not None and param not in registered:\n            param_cls = type(module._parameters[name])\n            kwargs = module._parameters[name].__dict__\n            kwargs[\"requires_grad\"] = param.requires_grad\n            module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)\n            registered.add(module._parameters[name])\n\n    try:\n        nn.Module.register_parameter = register_empty_parameter\n        yield\n    finally:\n        registered.clear()\n        nn.Module.register_parameter = old_register_parameter\n\n\ndef parallel_load_safetensors(filepath):\n    \"\"\"\n    Parallel load safetensors from huggingface checkpoint\n\n    Huggingface checkpoint contains:\n\n    - config.json: a json file for model configuration\n    - model.safetensor.index.json: a json file for safetensors (parameters & buffers) index\n    - model-000x-of-ooxx.safetensors: a binary file for safetensors (parameters & buffers) chunks\n\n    Or (when model is small),\n\n    - model.safetensors: a binary file for all parameters and buffers\n\n    Each rank will own a part of model chunks and load them directly into GPU memory.\n    \"\"\"\n    from safetensors.torch import load_file\n\n    safetensors2param = {}\n\n    index_file = os.path.join(filepath, \"model.safetensors.index.json\")\n    if os.path.exists(index_file):\n        index = json.load(open(index_file, \"rb\"))\n        for param_name, filename in index[\"weight_map\"].items():\n            safetensors2param.setdefault(filename, []).append(param_name)\n    else:\n        # in this case, the model is small and we can load it all at once\n        param_file = os.path.join(filepath, \"model.safetensors\")\n        assert os.path.exists(param_file), f\"Cannot find {param_file}\"\n        states = load_file(param_file)\n        for param_name in states:\n            safetensors2param.setdefault(\"model.safetensors\", []).append(param_name)\n        del states\n\n    total_files = len(safetensors2param)\n    ckpt_chunks = sorted(safetensors2param.keys())\n    world_size = dist.get_world_size()\n    size = int(math.ceil(total_files / world_size))\n    ckpt_chunks = [ckpt_chunks[rank * size:rank * size + size] for rank in range(world_size)]\n\n    shard_states = {}\n    device = torch.cuda.current_device()\n    for rank, files in enumerate(ckpt_chunks):\n        if rank == dist.get_rank():\n            for file in files:\n                file = os.path.join(filepath, file)\n                states = load_file(file, device=device)\n                # print(f\"rank {rank} loading {file}...\")\n                shard_states.update(states)\n        else:\n            for file in files:\n                for param_name in safetensors2param[file]:\n                    shard_states[param_name] = rank\n    return shard_states\n\n\ndef parallel_init_module_fn(module: torch.nn.Module, shard_states: Dict[str, torch.nn.Parameter]):\n    \"\"\"\n    Generate a function to initialize sub-modules in the `module` with `shard_states`\n    from huggingface checkpoint.\n\n    Args:\n        module (torch.nn.Module): the global module to be initialized\n        shard_states (Dict[str, torch.nn.Parameter]): the shard states from huggingface checkpoint\n\n    Returns:\n        init_fn (Callable): a function to initialize sub-modules in the `module` with `shard_states`\n    \"\"\"\n\n    state2fqn = {}\n    for name, state in itertools.chain(module.named_parameters(remove_duplicate=False),\n                                       module.named_buffers(remove_duplicate=False)):\n        state2fqn.setdefault(state, []).append(name)\n    # remove standalone parameters and buffers\n    shared = {s for s, names in state2fqn.items() if len(names) > 1}\n    materialized_states = {}\n\n    @torch.no_grad()\n    def create_and_sync_state(param_name, state, is_param):\n        assert param_name in shard_states, f\"{param_name} not loaded\"\n        device = torch.cuda.current_device()\n        if is_param:\n            param = torch.nn.Parameter(torch.empty_like(state.data, device=device), requires_grad=state.requires_grad)\n        else:  # buffer\n            param = torch.empty_like(state.data, device=device)\n        loaded = shard_states[param_name]\n        if isinstance(loaded, (torch.nn.Parameter, torch.Tensor)):\n            # NOTE: loaded.dtype can be different with param.dtype\n            param.data.copy_(loaded.data)\n            dist.broadcast(param.data, src=dist.get_rank())\n        else:\n            assert isinstance(loaded, int)  # the rank that holds the state\n            dist.broadcast(param.data, src=loaded)\n        shard_states.pop(param_name)\n        del loaded\n        return param\n\n    def init_fn(sub_mod: torch.nn.Module, recurse: bool = True):\n        param_and_buffers = tuple(sub_mod.named_parameters(recurse=False)) + tuple(sub_mod.named_buffers(recurse=False))\n        # param_and_buffers = sorted(sub_mod.named_parameters(recurse=False), key=lambda x: x[0])\n        for name, state in param_and_buffers:\n            if not state.is_meta:\n                continue\n            is_param = name in sub_mod._parameters\n            fqn = state2fqn[state].pop(0)\n            # non-persistent buffers will not be saved in state dict, we can safely skip it\n            if (not is_param) and fqn not in shard_states:\n                if state.is_meta:\n                    raise RuntimeError(\n                        f\"find a non-persistent buffer ({fqn}) initiated with device meta. \"\n                        \"Such buffer is not saved in checkpoint and user should guarantee to init in CPU / GPU device.\")\n                continue\n            # for shared parameter, we get it from the first time it is created\n            if state in shared:\n                if state not in materialized_states:\n                    materialized_states[state] = create_and_sync_state(fqn, state, is_param)\n                else:\n                    if fqn in shard_states:\n                        shard_states.pop(fqn)\n                materialize_state = materialized_states[state]\n            # for not shared parameter, we create it directly\n            else:\n                materialize_state = create_and_sync_state(fqn, state, is_param)\n            if is_param:\n                sub_mod._parameters[name] = materialize_state\n            else:\n                sub_mod._buffers[name] = materialize_state\n        if recurse:\n            for module in sub_mod.children():\n                init_fn(module, recurse=True)\n\n        # for debug\n        # if len(shard_states) == 0: print(\"clear\")\n        return sub_mod\n\n    return init_fn\n"
  },
  {
    "path": "verl/utils/hdfs_io.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport shutil\nimport logging\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv('VERL_SFT_LOGGING_LEVEL', 'WARN'))\n\n_HDFS_PREFIX = \"hdfs://\"\n\n_HDFS_BIN_PATH = shutil.which('hdfs')\n\n\ndef exists(path: str, **kwargs) -> bool:\n    r\"\"\"Works like os.path.exists() but supports hdfs.\n\n    Test whether a path exists. Returns False for broken symbolic links.\n\n    Args:\n        path (str): path to test\n\n    Returns:\n        bool: True if the path exists, False otherwise\n    \"\"\"\n    if _is_non_local(path):\n        return _exists(path, **kwargs)\n    return os.path.exists(path)\n\n\ndef _exists(file_path: str):\n    \"\"\" hdfs capable to check whether a file_path is exists \"\"\"\n    if file_path.startswith(\"hdfs\"):\n        return _run_cmd(_hdfs_cmd(f\"-test -e {file_path}\")) == 0\n    return os.path.exists(file_path)\n\n\ndef makedirs(name, mode=0o777, exist_ok=False, **kwargs) -> None:\n    r\"\"\"Works like os.makedirs() but supports hdfs.\n\n    Super-mkdir; create a leaf directory and all intermediate ones.  Works like\n    mkdir, except that any intermediate path segment (not just the rightmost)\n    will be created if it does not exist. If the target directory already\n    exists, raise an OSError if exist_ok is False. Otherwise no exception is\n    raised.  This is recursive.\n\n    Args:\n        name (str): directory to create\n        mode (int): file mode bits\n        exist_ok (bool): if True, do not raise an exception if the directory already exists\n        kwargs: keyword arguments for hdfs\n\n    \"\"\"\n    if _is_non_local(name):\n        # TODO(haibin.lin):\n        # - handle OSError for hdfs(?)\n        # - support exist_ok for hdfs(?)\n        _mkdir(name, **kwargs)\n    else:\n        os.makedirs(name, mode=mode, exist_ok=exist_ok)\n\n\ndef _mkdir(file_path: str) -> bool:\n    \"\"\"hdfs mkdir\"\"\"\n    if file_path.startswith(\"hdfs\"):\n        _run_cmd(_hdfs_cmd(f\"-mkdir -p {file_path}\"))\n    else:\n        os.makedirs(file_path, exist_ok=True)\n    return True\n\n\ndef copy(src: str, dst: str, **kwargs) -> bool:\n    r\"\"\"Works like shutil.copy() for file, and shutil.copytree for dir, and supports hdfs.\n\n    Copy data and mode bits (\"cp src dst\"). Return the file's destination.\n    The destination may be a directory.\n    If source and destination are the same file, a SameFileError will be\n    raised.\n\n    Arg:\n        src (str): source file path\n        dst (str): destination file path\n        kwargs: keyword arguments for hdfs copy\n\n    Returns:\n        str: destination file path\n\n    \"\"\"\n    if _is_non_local(src) or _is_non_local(dst):\n        # TODO(haibin.lin):\n        # - handle SameFileError for hdfs files(?)\n        # - return file destination for hdfs files\n        return _copy(src, dst)\n    else:\n        if os.path.isdir(src):\n            return shutil.copytree(src, dst, **kwargs)\n        else:\n            return shutil.copy(src, dst, **kwargs)\n\n\ndef _copy(from_path: str, to_path: str, timeout: int = None) -> bool:\n    if to_path.startswith(\"hdfs\"):\n        if from_path.startswith(\"hdfs\"):\n            returncode = _run_cmd(_hdfs_cmd(f\"-cp -f {from_path} {to_path}\"), timeout=timeout)\n        else:\n            returncode = _run_cmd(_hdfs_cmd(f\"-put -f {from_path} {to_path}\"), timeout=timeout)\n    else:\n        if from_path.startswith(\"hdfs\"):\n            returncode = _run_cmd(_hdfs_cmd(f\"-get \\\n                {from_path} {to_path}\"), timeout=timeout)\n        else:\n            try:\n                shutil.copy(from_path, to_path)\n                returncode = 0\n            except shutil.SameFileError:\n                returncode = 0\n            except Exception as e:\n                logger.warning(f\"copy {from_path} {to_path} failed: {e}\")\n                returncode = -1\n    return returncode == 0\n\n\ndef _run_cmd(cmd: str, timeout=None):\n    return os.system(cmd)\n\n\ndef _hdfs_cmd(cmd: str) -> str:\n    return f\"{_HDFS_BIN_PATH} dfs {cmd}\"\n\n\ndef _is_non_local(path: str):\n    return path.startswith(_HDFS_PREFIX)\n"
  },
  {
    "path": "verl/utils/import_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nUtilities to check if packages are available.\nWe assume package availability won't change during runtime.\n\"\"\"\n\nfrom functools import cache\nfrom typing import List\n\n\n@cache\ndef is_megatron_core_available():\n    try:\n        from megatron.core import parallel_state as mpu\n        return True\n    except ImportError:\n        return False\n\n\n@cache\ndef is_vllm_available():\n    try:\n        import vllm\n        return True\n    except ImportError:\n        return False\n\n\ndef import_external_libs(external_libs=None):\n    if external_libs is None:\n        return\n    if not isinstance(external_libs, List):\n        external_libs = [external_libs]\n    import importlib\n    for external_lib in external_libs:\n        importlib.import_module(external_lib)\n"
  },
  {
    "path": "verl/utils/logger/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/utils/logger/aggregate_logger.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nA Ray logger will receive logging info from different processes.\n\"\"\"\nimport numbers\nfrom typing import Dict\n\n\ndef concat_dict_to_str(dict: Dict, step):\n    output = [f'step:{step}']\n    for k, v in dict.items():\n        if isinstance(v, numbers.Number):\n            output.append(f'{k}:{v:.3f}')\n    output_str = ' - '.join(output)\n    return output_str\n\n\nclass LocalLogger:\n\n    def __init__(self, remote_logger=None, enable_wandb=False, print_to_console=False):\n        self.print_to_console = print_to_console\n        if print_to_console:\n            print('Using LocalLogger is deprecated. The constructor API will change ')\n\n    def flush(self):\n        pass\n\n    def log(self, data, step):\n        if self.print_to_console:\n            print(concat_dict_to_str(data, step=step), flush=True)"
  },
  {
    "path": "verl/utils/logging_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\n\n\ndef set_basic_config(level):\n    \"\"\"\n    This function sets the global logging format and level. It will be called when import verl\n    \"\"\"\n    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=level)\n"
  },
  {
    "path": "verl/utils/megatron/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/utils/megatron/memory.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\n\n\nclass MemoryBuffer:\n\n    def __init__(self, numel, numel_padded, dtype):\n        self.numel = numel\n        self.numel_padded = numel_padded\n        self.dtype = dtype\n        self.data = torch.zeros(self.numel_padded,\n                                dtype=self.dtype,\n                                device=torch.cuda.current_device(),\n                                requires_grad=False)\n\n    def zero(self):\n        \"\"\"Reset the buffer to zero.\"\"\"\n        self.data.zero_()\n\n    def get(self, shape, start_index):\n        \"\"\"Return a tensor with the input `shape` as a view into the\n        1-D data starting at `start_index`.\"\"\"\n        end_index = start_index + shape.numel()\n        assert end_index <= self.numel, \\\n            'requested tensor is out of the buffer range.'\n        buffer_tensor = self.data[start_index:end_index]\n        buffer_tensor = buffer_tensor.view(shape)\n        return buffer_tensor\n"
  },
  {
    "path": "verl/utils/megatron/optimizer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport importlib\nfrom packaging.version import Version\n\nfrom apex.optimizers import FusedAdam as Adam\nfrom apex.optimizers import FusedSGD as SGD\n\nfrom megatron.core.optimizer import OptimizerConfig\n\nfrom megatron.core.optimizer import get_megatron_optimizer as get_megatron_optimizer_native\n\n\ndef get_megatron_optimizer(\n        model,\n        config: OptimizerConfig,\n        no_weight_decay_cond=None,\n        scale_lr_cond=None,\n        lr_mult=1.0,\n        check_for_nan_in_loss_and_grad=False,\n        overlap_param_gather=False  # add for verl\n):\n    # Base optimizer.\n    return get_megatron_optimizer_native(config=config,\n                                         model_chunks=model,\n                                         no_weight_decay_cond=no_weight_decay_cond,\n                                         scale_lr_cond=scale_lr_cond,\n                                         lr_mult=lr_mult)\n"
  },
  {
    "path": "verl/utils/megatron/pipeline_parallel.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nfrom megatron.core import parallel_state as mpu\n\nfrom .sequence_parallel import pad_to_sequence_parallel\n\n\ndef compute_transformers_input_shapes(batches, meta_info):\n    from flash_attn.bert_padding import unpad_input  # flash 2 is a must for Megatron\n    # pre-compute input shapes for each micro-batch at each pp stage\n    input_shapes = []\n    for model_inputs in batches:\n        input_ids = model_inputs['input_ids']\n        attention_mask = model_inputs['attention_mask']\n        input_ids_rmpad = unpad_input(input_ids.unsqueeze(dim=-1), attention_mask)[0]  # (total_nnz, 1)\n        if meta_info['sequence_parallel']:\n            input_ids_rmpad = pad_to_sequence_parallel(input_ids_rmpad)\n            # compute shapes for model_inputs\n            input_shapes.append(\n                torch.Size([\n                    input_ids_rmpad.shape[0] // mpu.get_tensor_model_parallel_world_size(), 1, meta_info['hidden_size']\n                ]))\n        else:\n            # compute shapes for model_inputs\n            input_shapes.append(torch.Size([input_ids_rmpad.shape[0], 1, meta_info['hidden_size']]))\n    return input_shapes\n\n\ndef make_batch_generator(batches, vpp_size):\n    if vpp_size > 1:\n        # has vpp\n        batch_generator = [batches] * vpp_size  # number of vpp chunks\n        batch_generator = [iter(b) for b in batch_generator]\n    else:\n        # no vpp\n        batch_generator = iter(batches)\n    return batch_generator\n"
  },
  {
    "path": "verl/utils/megatron/sequence_parallel.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport torch.nn.functional as F\nfrom megatron.core import parallel_state as mpu\n\n\ndef mark_parameter_as_sequence_parallel(parameter):\n    setattr(parameter, 'sequence_parallel', True)\n\n\ndef is_sequence_parallel_param(param):\n    return hasattr(param, 'sequence_parallel') and param.sequence_parallel\n\n\ndef pad_to_sequence_parallel(unpad_tokens: torch.Tensor):\n    \"\"\"pad the tokens such that the total length is a multiple of sp world size\n\n    Args:\n        unpad_tokens: (total_nnz, ...). Tokens after removing padding\n\n    Returns:\n\n    \"\"\"\n    total_nnz = unpad_tokens.shape[0]\n    sp_world_size = mpu.get_tensor_model_parallel_world_size()\n\n    if total_nnz % sp_world_size == 0:\n        pad_size = 0\n    else:\n        pad_size = sp_world_size - total_nnz % sp_world_size\n\n    if pad_size > 0:\n        if unpad_tokens.ndim == 1:\n            unpad_tokens = F.pad(unpad_tokens, (0, pad_size))\n        elif unpad_tokens.ndim == 2:\n            unpad_tokens = F.pad(unpad_tokens, (0, 0, 0, pad_size))\n        else:\n            raise NotImplementedError(f'Padding dim {unpad_tokens.ndim()} is not supported')\n\n    return unpad_tokens\n"
  },
  {
    "path": "verl/utils/megatron/tensor_parallel.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nUtilities for using tensor_parallel in megatron\n\"\"\"\nfrom typing import Dict\nimport torch\nfrom torch.nn import init\nimport torch.distributed as dist\nfrom megatron.core import ModelParallelConfig\nfrom megatron.core import parallel_state as mpu, tensor_parallel\nimport verl.utils.torch_functional as verl_F\n\n\ndef update_kwargs_with_config(dictionary: Dict, config: ModelParallelConfig):\n    dictionary['config'] = config\n    return dictionary\n\n\ndef get_default_kwargs_for_model_parallel_config():\n    model_parallel_config_kwargs = {\n        'params_dtype': torch.float32,\n        'use_cpu_initialization': False,\n        'perform_initialization': True,\n        'gradient_accumulation_fusion': False,\n        'sequence_parallel': False,\n    }\n    return model_parallel_config_kwargs\n\n\ndef get_default_model_parallel_config():\n    return ModelParallelConfig(**get_default_kwargs_for_model_parallel_config())\n\n\ndef get_common_default_kwargs_for_parallel_linear():\n    default_model_parallel_config = get_default_model_parallel_config()\n    common_default_kwargs = {\n        'init_method': init.xavier_normal_,\n        'stride': 1,\n        'keep_master_weight_for_test': False,\n        'config': default_model_parallel_config,\n    }\n    return common_default_kwargs\n\n\ndef get_default_kwargs_for_column_parallel_linear():\n    model_parallel_config_kwargs = get_default_kwargs_for_model_parallel_config()\n    column_parallel_config_kwargs = {\n        'async_tensor_model_parallel_allreduce': False,\n    }\n    model_parallel_config_kwargs.update(column_parallel_config_kwargs)\n    column_default_kwargs = {\n        'config': ModelParallelConfig(**model_parallel_config_kwargs),\n    }\n    common_default_kwargs = get_common_default_kwargs_for_parallel_linear()\n    common_default_kwargs.update(column_default_kwargs)\n    return common_default_kwargs\n\n\ndef get_default_kwargs_for_row_parallel_linear():\n    common_default_kwargs = get_common_default_kwargs_for_parallel_linear()\n    return common_default_kwargs\n\n\ndef get_default_kwargs_for_parallel_embedding():\n    model_parallel_config_kwargs = get_default_kwargs_for_model_parallel_config()\n    embedding_default_kwargs = {\n        'init_method': init.xavier_normal_,\n        'config': ModelParallelConfig(**model_parallel_config_kwargs),\n    }\n    return embedding_default_kwargs\n\n\ndef is_tensor_parallel_param(param):\n    return (hasattr(param, 'tensor_model_parallel') and param.tensor_model_parallel)\n\n\ndef get_tensor_parallel_partition_dim(param):\n    assert is_tensor_parallel_param(param)\n    return param.partition_dim\n\n\ndef get_tensor_parallel_partition_stride(param):\n    assert is_tensor_parallel_param(param)\n    return param.partition_stride\n\n\nclass _VocabParallelEntropy(torch.autograd.Function):\n\n    @staticmethod\n    def forward(ctx, vocab_parallel_logits: torch.Tensor) -> torch.Tensor:\n        logits_max = vocab_parallel_logits.max(dim=-1, keepdim=True).values\n        dist.all_reduce(logits_max, op=dist.ReduceOp.MAX, group=mpu.get_tensor_model_parallel_group())\n        normalized_vocab_parallel_logits = vocab_parallel_logits - logits_max\n        normalized_exp_logits = normalized_vocab_parallel_logits.exp()\n        normalized_sum_exp_logits = normalized_exp_logits.sum(dim=-1, keepdim=True)\n        dist.all_reduce(normalized_sum_exp_logits, group=mpu.get_tensor_model_parallel_group())\n        softmax_logits = normalized_exp_logits / normalized_sum_exp_logits\n        sum_softmax_times_logits = (softmax_logits * vocab_parallel_logits).sum(dim=-1, keepdim=True)\n        dist.all_reduce(sum_softmax_times_logits, group=mpu.get_tensor_model_parallel_group())\n        entropy = logits_max + normalized_sum_exp_logits.log() - sum_softmax_times_logits\n        ctx.save_for_backward(vocab_parallel_logits, softmax_logits, sum_softmax_times_logits)\n        return entropy.squeeze(dim=-1)\n\n    @staticmethod\n    def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:\n        vocab_parallel_logits, softmax_logits, sum_softmax_times_logits = ctx.saved_tensors\n        grad_input = grad_output.unsqueeze(dim=-1) * softmax_logits * (sum_softmax_times_logits - vocab_parallel_logits)\n        return grad_input\n\n\ndef vocab_parallel_entropy(vocab_parallel_logits: torch.Tensor) -> torch.Tensor:\n    \"\"\"Compute entropy when the logits are sharded in tp ranks\n    \n    Args:\n        vocab_parallel_logits: (total_nnz, vocab_size // tp_size)\n\n    Returns: (total_nnz,)\n        \n    \"\"\"\n    return _VocabParallelEntropy.apply(vocab_parallel_logits)\n\n\ndef vocab_parallel_log_probs_from_logits(logits, labels):\n    \"\"\"TODO(zhangchi.usc1992): We may change the implementation later\"\"\"\n    return -tensor_parallel.vocab_parallel_cross_entropy(vocab_parallel_logits=logits, target=labels)\n\n\ndef vocab_parallel_log_probs_from_logits_response_rmpad(input_ids, attention_mask, logits_rmpad, response_length):\n    \"\"\"Similar to log_probs_from_logits_response_rmpad, but the logits_rmpad is now spliited across tensor parallel region.\n    This will further reduce the peak memory usage during training\n\n    Args:\n        input_ids: [batch_size, seqlen]\n        attention_mask: [batch_size, seqlen]\n        logits_rmpad: [total_nnz, vocab_size // tp_size]\n        response_length: int\n\n    \"\"\"\n    from flash_attn.bert_padding import pad_input, unpad_input\n\n    batch_size, seqlen = input_ids.shape\n    input_ids_rmpad, indices, *_ = unpad_input(input_ids.unsqueeze(-1), attention_mask=attention_mask)\n    input_ids_rmpad = input_ids_rmpad.squeeze(-1)\n    input_ids_rmpad_rolled = torch.roll(input_ids_rmpad, shifts=-1, dims=0)\n    full_log_probs_rmpad = vocab_parallel_log_probs_from_logits(logits=logits_rmpad,\n                                                                labels=input_ids_rmpad_rolled)  # (total_nnz,)\n    full_output = pad_input(hidden_states=full_log_probs_rmpad.unsqueeze(-1),\n                            indices=indices,\n                            batch=batch_size,\n                            seqlen=seqlen)\n    output = full_output.squeeze(-1)[:, -response_length - 1:-1]  # [batch_size, response_length]\n    return output\n\n\ndef vocab_parallel_compute_entropy_loss(logits, eos_mask):\n    \"\"\"Compute Categorical entropy loss\n\n    Args:\n        logits: `(torch.Tensor)`\n            shape: (bs, response_length, vocab_size)\n        eos_mask: `(torch.Tensor)`\n            shape: (bs, response_length)\n\n    Returns:\n        entropy: a scalar torch.Tensor\n\n    \"\"\"\n    # compute entropy\n    entropy = vocab_parallel_entropy(logits)\n    entropy_loss = verl_F.masked_mean(entropy, mask=eos_mask)\n    return entropy_loss\n"
  },
  {
    "path": "verl/utils/megatron_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Pretrain utilities.\"\"\"\nimport importlib\nfrom packaging.version import Version\nfrom typing import Any, Dict\nimport time\nfrom omegaconf import DictConfig\nfrom verl.utils.torch_dtypes import PrecisionType\nfrom verl.utils.memory_buffer import build_memory_reference_from_module\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom megatron.core import mpu, tensor_parallel\nfrom megatron.core.utils import get_attr_wrapped_model\nfrom megatron.core.transformer import TransformerConfig\nfrom megatron.core.transformer.module import Float16Module\nfrom megatron.core.distributed import DistributedDataParallelConfig\nfrom megatron.core.distributed import DistributedDataParallel as DDP\nfrom megatron.core.enums import ModelType\nfrom megatron.core import ModelParallelConfig\nfrom megatron.core.optimizer import OptimizerConfig\n\n\ndef get_model_config(model):\n    return get_attr_wrapped_model(model, 'megatron_config', allow_none=False)\n\n\ndef get_model(model_provider_func, model_type=ModelType.encoder_or_decoder, wrap_with_ddp=True):\n    \"\"\"Build the model.\"\"\"\n    # Build model.\n    if mpu.get_pipeline_model_parallel_world_size() > 1 and \\\n       mpu.get_virtual_pipeline_model_parallel_world_size() is not None:\n        assert model_type != ModelType.encoder_and_decoder, \\\n            \"Interleaved schedule not supported for model with both encoder and decoder\"\n        model = []\n        for i in range(mpu.get_virtual_pipeline_model_parallel_world_size()):\n            mpu.set_virtual_pipeline_model_parallel_rank(i)\n            # Set pre_process and post_process only after virtual rank is set.\n            pre_process = mpu.is_pipeline_first_stage()\n            post_process = mpu.is_pipeline_last_stage()\n            this_model = model_provider_func(pre_process=pre_process, post_process=post_process)\n            this_model.model_type = model_type\n            model.append(this_model)\n    else:\n        pre_process = mpu.is_pipeline_first_stage()\n        post_process = mpu.is_pipeline_last_stage()\n        add_encoder = True\n        add_decoder = True\n        if model_type == ModelType.encoder_and_decoder:\n            if mpu.get_pipeline_model_parallel_world_size() > 1:\n                assert mpu.get_pipeline_model_parallel_split_rank() is not None, \\\n                    \"Split rank needs to be specified for model with both encoder and decoder\"\n                rank = mpu.get_pipeline_model_parallel_rank()\n                split_rank = mpu.get_pipeline_model_parallel_split_rank()\n                world_size = mpu.get_pipeline_model_parallel_world_size()\n                pre_process = rank == 0 or rank == split_rank\n                post_process = (rank == (split_rank - 1)) or (rank == (world_size - 1))\n                add_encoder = mpu.is_pipeline_stage_before_split()\n                add_decoder = mpu.is_pipeline_stage_after_split()\n            model = model_provider_func(pre_process=pre_process,\n                                        post_process=post_process,\n                                        add_encoder=add_encoder,\n                                        add_decoder=add_decoder)\n        else:\n            model = model_provider_func(pre_process=pre_process, post_process=post_process)\n        model.model_type = model_type\n\n    if not isinstance(model, list):\n        model = [model]\n\n    # Set tensor model parallel attributes if not set.\n    # Only parameters that are already tensor model parallel have these\n    # attributes set for them. We should make sure the default attributes\n    # are set for all params so the optimizer can use them.\n    for model_module in model:\n        for param in model_module.parameters():\n            tensor_parallel.set_defaults_if_not_set_tensor_model_parallel_attributes(param)\n\n    # Print number of parameters.\n    if mpu.get_data_parallel_rank() == 0:\n        print(' > number of parameters on (tensor, pipeline) '\n              'model parallel rank ({}, {}): {}'.format(\n                  mpu.get_tensor_model_parallel_rank(), mpu.get_pipeline_model_parallel_rank(),\n                  sum([sum([p.nelement() for p in model_module.parameters()]) for model_module in model])),\n              flush=True)\n\n    # GPU allocation.\n    for model_module in model:\n        model_module.cuda(torch.cuda.current_device())\n\n    # Fp16 conversion.\n    config: ModelParallelConfig = get_model_config(model[0])\n    config.fp8 = None\n    tfconfig: TransformerConfig = convert_config(model[0].config, config)\n    if config.fp16 or config.bf16:  # the ModelParallelConfig in GPTModel\n        model = [Float16Module(config, model_module) for model_module in model]\n\n    if wrap_with_ddp:\n        ddp_models = []\n        for model_chunk_idx, model_chunk in enumerate(model):\n            ddp_model = DDP(\n                config=tfconfig,\n                module=model_chunk,\n                disable_bucketing=(model_chunk_idx > 0),\n                ddp_config=DistributedDataParallelConfig(\n                    overlap_grad_reduce=False,\n                    use_distributed_optimizer=True,\n                    grad_reduce_in_fp32=True,  # [old] accumulate_allreduce_grads_in_fp32=True,\n                ))\n            ddp_models.append(ddp_model)\n        model = ddp_models\n        # # Broadcast params from data parallel src rank to other data parallel ranks.\n        # # if args.data_parallel_random_init:\n        for model_module in model:\n            model_module.broadcast_params()\n    return model\n\n\nALL_MODULE_WRAPPER_CLASSNAMES = (DDP, Float16Module)\n\n\ndef unwrap_model(model, module_instances=ALL_MODULE_WRAPPER_CLASSNAMES):\n    return_list = True\n    if not isinstance(model, list):\n        model = [model]\n        return_list = False\n    unwrapped_model = []\n    for model_module in model:\n        while isinstance(model_module, module_instances):\n            model_module = model_module.module\n        unwrapped_model.append(model_module)\n    if not return_list:\n        return unwrapped_model[0]\n    return unwrapped_model\n\n\nfrom transformers import PretrainedConfig\n\n\ndef convert_config(hf_config: PretrainedConfig, megatron_config) -> TransformerConfig:\n    print(f'megatron config {megatron_config}')\n    dt = PrecisionType.to_dtype(megatron_config.params_dtype)\n    print(f'pipeline_dtype=megatron_config {dt}')\n    transformer_config = TransformerConfig(\n        num_layers=hf_config.num_hidden_layers,\n        hidden_size=hf_config.hidden_size,\n        num_attention_heads=hf_config.num_attention_heads,\n        num_query_groups=hf_config.num_key_value_heads,\n        ffn_hidden_size=hf_config.intermediate_size,\n        #    max_position_embeddings=hf_config.max_position_embeddings,\n        activation_func=F.silu,\n        normalization='RMSNorm',\n        #    rotary_percent=False, # default,\n        gated_linear_unit=True,  # for llama\n        use_cpu_initialization=True,\n        apply_residual_connection_post_layernorm=False,  # check what's this mean\n        add_bias_linear=False,\n        tensor_model_parallel_size=mpu.get_tensor_model_parallel_world_size(),\n        pipeline_model_parallel_size=mpu.get_pipeline_model_parallel_world_size(),\n        virtual_pipeline_model_parallel_size=mpu.get_virtual_pipeline_model_parallel_world_size(),\n        pipeline_dtype=dt,\n        params_dtype=dt,\n        sequence_parallel=True,\n        variable_seq_lengths=True,\n        masked_softmax_fusion=True,\n        moe_token_dispatcher_type=\"alltoall\",\n        bf16=dt is torch.bfloat16)\n    if torch.distributed.get_rank() == 0:\n        print(f'tensor_parallel_size={transformer_config.tensor_model_parallel_size} \\n \\\n                pipeline_model_parallel_size={transformer_config.pipeline_model_parallel_size} \\n \\\n                virtual_pipeline_model_parallel_size={transformer_config.virtual_pipeline_model_parallel_size} \\n \\\n                pipeline_dtype={transformer_config.pipeline_dtype} \\n \\\n                params_dtype={transformer_config.params_dtype} \\n \\\n                sequence_parallel={transformer_config.sequence_parallel} \\n \\\n                variable_seq_lengths={transformer_config.variable_seq_lengths} \\n \\\n                masked_softmax_fusion={transformer_config.masked_softmax_fusion} \\n ')\n\n    return transformer_config\n\n\ndef init_megatron_optim_config(optim_config: Dict) -> OptimizerConfig:\n    config = OptimizerConfig(\n        optimizer='adam',\n        lr=optim_config.get('lr'),\n        clip_grad=optim_config.get('clip_grad'),\n        weight_decay=1e-2,\n        bf16=True,\n        params_dtype=torch.bfloat16,\n        use_distributed_optimizer=True,\n    )\n    return config\n\n\ndef init_model_parallel_config(config: DictConfig) -> ModelParallelConfig:\n    # TODO(sgm): check how to disable megatron timers\n    timers = None\n    return ModelParallelConfig(tensor_model_parallel_size=config.get('tensor_model_parallel_size'),\n                               pipeline_model_parallel_size=config.get('pipeline_model_parallel_size'),\n                               virtual_pipeline_model_parallel_size=config.get('virtual_pipeline_model_parallel_size'),\n                               sequence_parallel=config.get('sequence_parallel'),\n                               params_dtype=PrecisionType.to_dtype(config.get('param_dtype')),\n                               pipeline_dtype=PrecisionType.to_dtype(config.get('param_dtype')),\n                               bf16=True,\n                               fp16=False,\n                               timers=timers)\n\n\ndef offload_megatron_param_and_grad(module_list: nn.ModuleList, offload_grad=False, hybrid_engine=None):\n    if hybrid_engine is not None:\n        pp_rank = mpu.get_pipeline_model_parallel_rank()\n        for buffer in hybrid_engine.memory_buffers[pp_rank].values():\n            buffer.data = buffer.data.to('cpu', non_blocking=True)\n        build_memory_reference_from_module(module_list, hybrid_engine.memory_buffers[pp_rank], maintain_weight=True)\n    else:\n        for module in module_list:\n            for _, param in module.named_parameters():\n                param.data = param.data.to('cpu', non_blocking=True)\n                if offload_grad and param.grad is not None:\n                    param.grad = param.grad.to(\"cpu\", non_blocking=True)\n    torch.cuda.empty_cache()\n\n\ndef load_megatron_param_and_grad(module_list: nn.ModuleList, device_id, load_grad=False, hybrid_engine=None):\n    if hybrid_engine is not None:\n        pp_rank = mpu.get_pipeline_model_parallel_rank()\n        for buffer in hybrid_engine.memory_buffers[pp_rank].values():\n            buffer.data = buffer.data.to(device_id, non_blocking=True)\n        build_memory_reference_from_module(module_list, hybrid_engine.memory_buffers[pp_rank], maintain_weight=True)\n    else:\n        for module in module_list:\n            for _, param in module.named_parameters():\n                param.data = param.data.to(device_id, non_blocking=True)\n                if load_grad and param.grad is not None:\n                    param.grad = param.grad.to(device_id, non_blocking=True)\n    torch.cuda.empty_cache()\n"
  },
  {
    "path": "verl/utils/memory_buffer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThis file contains utilities to manipulate torch memory buffers\n\"\"\"\n\nfrom typing import Dict, List, Optional\n\nimport torch\nfrom torch import nn\n\n\nclass MemoryBuffer:\n    \"\"\"\n    A memory buffer is a contiguous torch tensor that may combine multiple tensors sharing with the underlying\n    memory. It must have a unique type to support this behavior.\n    \"\"\"\n\n    def __init__(self, numel: int, numel_padded: int, dtype: torch.dtype, source: Optional[torch.Tensor] = None):\n        self.numel = numel\n        self.numel_padded = numel_padded\n        self.dtype = dtype\n        if source is not None:\n            self.data = source\n        else:\n            self.data = torch.zeros(self.numel_padded, dtype=self.dtype, device='cuda', requires_grad=False)\n\n    def zero(self):\n        \"\"\"Reset the buffer to zero.\"\"\"\n        self.data.zero_()\n\n    def get(self, shape, start_index):\n        \"\"\"Return a tensor with the input `shape` as a view into the\n        1-D data starting at `start_index`.\"\"\"\n        end_index = start_index + shape.numel()\n        assert end_index <= self.numel, \\\n            'requested tensor is out of the buffer range.'\n        buffer_tensor = self.data[start_index:end_index]\n        buffer_tensor = buffer_tensor.view(shape)\n        return buffer_tensor\n\n\ndef calc_padded_numel(shape: torch.Size, dtype: torch.dtype):\n    \"\"\"for cuda memory alignment, make sure alignment by 128-bits\"\"\"\n    align_numel = 128 // torch.finfo(dtype).bits\n    numel = shape.numel()\n    return (numel + align_numel - 1) // align_numel * align_numel\n\n\ndef get_weight_buffer_meta_from_module(module: nn.Module) -> Dict[str, Dict]:\n    \"\"\"\n    Return a dictionary containing name to a shape and dtype.\n    \"\"\"\n    weight_buffer_meta = {}\n    for name, param in sorted(module.named_parameters()):\n        weight_buffer_meta[name] = {'shape': param.shape, 'dtype': param.dtype}\n    return weight_buffer_meta\n\n\ndef build_memory_buffer(weight_buffer_meta: Dict[str, Dict]) -> Dict[torch.dtype, MemoryBuffer]:\n    \"\"\"Build the memory buffer given weight_buffer_meta\n\n    Args:\n        weight_buffer_meta: contains mapping from name to a dictionary containing shape and dtype of the tensors\n\n    Returns: a large memory buffer for each dtype that can hold all the tensors\n\n    \"\"\"\n    memory_buffers = {}\n    total_numel_map = {}  # map from dtype to the total numel\n    for name, meta_info in sorted(weight_buffer_meta.items()):\n        shape = meta_info['shape']\n        dtype = meta_info['dtype']\n\n        assert isinstance(shape, torch.Size)\n        assert isinstance(dtype, torch.dtype)\n\n        if dtype not in total_numel_map:\n            total_numel_map[dtype] = 0\n\n        total_numel_map[dtype] += calc_padded_numel(shape, dtype)\n\n    for dtype, total_numel in total_numel_map.items():\n        memory_buffers[dtype] = MemoryBuffer(total_numel, total_numel, dtype)\n\n    return memory_buffers\n\n\ndef build_memory_reference_from_module(module: torch.nn.Module,\n                                       memory_buffers: Dict[torch.dtype, MemoryBuffer],\n                                       maintain_weight=True):\n    start_index = {}\n    for dtype in memory_buffers.keys():\n        start_index[dtype] = 0\n    for name, param in sorted(module.named_parameters()):\n        memory_buffer = memory_buffers[param.dtype]\n        buffer = memory_buffer.get(shape=param.shape, start_index=start_index[param.dtype])\n        # need to increment start_index\n        start_index[param.dtype] += calc_padded_numel(param.shape, dtype)\n        if maintain_weight:\n            buffer.copy_(param.data)\n        param.data = buffer\n\n\ndef build_memory_reference(weight_buffer_meta: Dict[str, Dict], memory_buffers: Dict[torch.dtype, MemoryBuffer]):\n    \"\"\"Build the memory references. The memory buffers are built using the build_memory_buffer API.\n    This API will allocate a weight buffer pointer to the memory buffer according to the weight_buffer_meta.\n\n    Args:\n        weight_buffer_meta:\n        memory_buffers:\n\n    Returns:\n\n    \"\"\"\n    start_idx = {}\n    weight_buffers = {}\n    for dtype in memory_buffers.keys():\n        start_idx[dtype] = 0\n\n    for name, meta_info in sorted(weight_buffer_meta.items()):\n        shape = meta_info['shape']\n        dtype = meta_info['dtype']\n\n        buffer = memory_buffers[dtype].get(shape, start_index=start_idx[dtype])\n        start_idx[dtype] += calc_padded_numel(shape, dtype)\n        weight_buffers[name] = buffer\n\n    return weight_buffers\n\n\nclass MemoryBufferModuleWrapper:\n    \"\"\"\n    Note that we do not design MemoryBufferModuleWrapper as an nn.Module due to\n    - It will change the checkpoint name\n    \"\"\"\n\n    def __init__(self, module: nn.Module):\n        super().__init__()\n        self.module = module\n        self.weight_buffer_meta = get_weight_buffer_meta_from_module(self.module)\n        self.memory_buffers = build_memory_buffer(self.weight_buffer_meta)\n        build_memory_reference_from_module(self.module, self.memory_buffers)\n\n    def get_memory_buffers(self):\n        return self.memory_buffers\n\n    def get_weight_buffer_meta(self):\n        return self.weight_buffer_meta\n\n\nclass MegatronMemoryBufferForRollout(object):\n    \"\"\"\n    We assume that\n    - inference engine has tp + dp\n    - actor has tp + pp + dp\n    - the tp between inference engine and actor should be the same\n    - memory_buffers: contains a list of memory_buffers, each is a dict from dtype to MemoryBuffer\n    - weight_buffers: contains a list of weight_buffers, each is a dict from name to param\n    - named_parameters: a dict from name to parameter that normalizes the names from pp and vpp. Note that\n        the named_parameters may not be directly compatible with inference engine. User has to take care of\n        this part such as the layout mismatches. (e.g. qkv transpose)\n    - Note that weight_buffer, named_parameters and memory_buffers share the same underlying GPU memory.\n    - When doing weight sync, the data is transfer via memory buffers\n    \"\"\"\n\n    def __init__(self, transform_memory_param_fn):\n        self._memory_buffers = []\n        self._weight_buffers = []\n        self._named_parameters = {}\n        self.transform_memory_param_fn = transform_memory_param_fn\n\n    def initialize_weight_buffer(self, weight_buffer_meta_pp: List[Dict[str, Dict]]):\n        \"\"\"\n        Initialize the weight buffer. The weight buffer is obtained according to the actor. We will construct\n        a large buffer for each dtype in the weight_buffer.\n\n        Args:\n            weight_buffer_meta: contains pp models, each pp models contains a dictionary of mapping from\n\n        Returns: None\n\n        \"\"\"\n        self.weight_buffer_meta_pp = weight_buffer_meta_pp\n\n        for weight_buffer_meta in self.weight_buffer_meta_pp:\n            memory_buffer = build_memory_buffer(weight_buffer_meta)\n            self._memory_buffers.append(memory_buffer)\n            self._weight_buffers.append(None)\n\n    def build_memory_reference(self):\n        for i, weight_buffer_meta in enumerate(self.weight_buffer_meta_pp):\n            self._weight_buffers[i] = build_memory_reference(weight_buffer_meta, self._memory_buffers[i])\n        self._named_parameters = self.transform_memory_param_fn(self._weight_buffers)\n\n    @property\n    def named_parameters(self):\n        return self._named_parameters\n\n    @property\n    def weight_buffers(self):\n        return self._weight_buffers\n\n    @property\n    def memory_buffers(self):\n        return self._memory_buffers\n"
  },
  {
    "path": "verl/utils/model.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nUtilities to create common models from huggingface\n\"\"\"\nimport os\nimport warnings\nfrom typing import Dict, Type, Optional\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom transformers import AutoConfig, AutoModelForCausalLM, PretrainedConfig, MistralForSequenceClassification, GenerationConfig\nfrom verl.models.registry import ModelRegistry\n\n\nclass LambdaLayer(nn.Module):\n\n    def __init__(self, fn):\n        super().__init__()\n        self.fn = fn\n\n    def forward(self, *args, **kwargs):\n        return self.fn(*args, **kwargs)\n\n\ndef squeeze(x):\n    return torch.squeeze(x, dim=-1)\n\n\ndef update_model_config(module_config, override_config_kwargs):\n    for key, val in override_config_kwargs.items():\n        setattr(module_config, key, val)\n\n\ndef get_huggingface_actor_config(model_name: str, override_config_kwargs=None, trust_remote_code=False) -> Dict:\n    if override_config_kwargs is None:\n        override_config_kwargs = {}\n    assert isinstance(override_config_kwargs, Dict), \\\n        f'override_config_kwargs must be a dict, got {type(override_config_kwargs)}'\n    module_config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code)\n    update_model_config(module_config, override_config_kwargs)\n\n    return module_config\n\n\ndef get_generation_config(\n    model: str,\n    trust_remote_code: bool = False,\n) -> Optional[GenerationConfig]:\n    try:\n        return GenerationConfig.from_pretrained(model)\n    except OSError:  # Not found\n        try:\n            config = get_huggingface_actor_config(\n                model,\n                trust_remote_code=trust_remote_code,\n            )\n            return GenerationConfig.from_model_config(config)\n        except OSError:  # Not found\n            return None\n\n\ndef create_huggingface_actor(model_name: str, override_config_kwargs=None, automodel_kwargs=None) -> nn.Module:\n    \"\"\"\n\n    Args:\n        model_name:\n        override_config_kwargs:\n\n    Returns:\n\n    \"\"\"\n    if override_config_kwargs is None:\n        override_config_kwargs = {}\n    if automodel_kwargs is None:\n        automodel_kwargs = {}\n    assert isinstance(override_config_kwargs, Dict), \\\n        f'override_config_kwargs must be a dict, got {type(override_config_kwargs)}'\n    module_config = get_huggingface_actor_config(model_name,\n                                                 override_config_kwargs,\n                                                 trust_remote_code=automodel_kwargs.get('trust_remote_code', False))\n    module: nn.Module = AutoModelForCausalLM.from_config(module_config, **automodel_kwargs)\n    return module\n\n\ndef create_huggingface_critic(model_name: str, override_config_kwargs=None, automodel_kwargs=None) -> nn.Module:\n    \"\"\"\n\n    Args:\n        model_name:\n        override_config_kwargs:\n\n    Returns:\n\n    \"\"\"\n    critic_module: nn.Module = create_huggingface_actor(model_name,\n                                                        override_config_kwargs=override_config_kwargs,\n                                                        automodel_kwargs=automodel_kwargs)\n    if automodel_kwargs is None:\n        automodel_kwargs = {}\n    torch_dtype = automodel_kwargs.get('torch_dtype', torch.float32)\n    critic_module.lm_head = nn.Sequential(nn.Linear(critic_module.config.hidden_size, 1, dtype=torch_dtype),\n                                          LambdaLayer(fn=squeeze))\n    return critic_module\n\n\ndef get_model_size(model: nn.Module, scale='auto'):\n    n_params = sum(p.numel() for p in model.parameters())\n\n    if scale == 'auto':\n        if n_params > 1e9:\n            scale = 'B'\n        elif n_params > 1e6:\n            scale = 'M'\n        elif n_params > 1e3:\n            scale = 'K'\n        else:\n            scale = ''\n\n    if scale == 'B':\n        n_params = n_params / 1e9\n    elif scale == 'M':\n        n_params = n_params / 1e6\n    elif scale == 'K':\n        n_params = n_params / 1e3\n    elif scale == '':\n        pass\n    else:\n        raise NotImplemented(f'Unknown scale {scale}')\n\n    return n_params, scale\n\n\ndef print_model_size(model: nn.Module, name: str = None):\n    n_params, scale = get_model_size(model, scale='auto')\n    if name is None:\n        name = model.__class__.__name__\n    print(f'{name} contains {n_params:.2f}{scale} parameters')\n\n\ndef create_random_mask(input_ids: torch.Tensor,\n                       max_ratio_of_valid_token: float,\n                       max_ratio_of_left_padding: float,\n                       min_ratio_of_valid_token: float = 0):\n    \"\"\"Create a random mask given input_ids. Support left padding and right padding.\n    Process:\n    - Sample valid token length\n    - Sample left_padding length\n    - Generate padding\n\n    Args:\n        input_ids:\n            shape (batch_size, seq_len)\n\n    Returns:\n\n    \"\"\"\n    assert max_ratio_of_valid_token > 0 and max_ratio_of_valid_token <= 1.\n    assert max_ratio_of_left_padding >= 0 and max_ratio_of_left_padding < 1.\n    assert min_ratio_of_valid_token <= max_ratio_of_valid_token\n\n    batch_size, sequence_length = input_ids.shape\n    max_num_valid_tokens = int(sequence_length * max_ratio_of_valid_token)\n    min_num_valid_tokens = max(1, int(sequence_length * min_ratio_of_valid_token))\n    max_left_padding = int(sequence_length * max_ratio_of_left_padding)\n    assert max_num_valid_tokens + max_left_padding <= sequence_length\n    assert max_num_valid_tokens > 0 and max_ratio_of_valid_token <= sequence_length\n    masks = torch.ones_like(input_ids, dtype=torch.int64)\n    # TODO: we can make this faster\n    for i in range(batch_size):\n        num_left_padding = np.random.randint(low=0, high=max_left_padding + 1, dtype=np.int64)\n        num_valid = np.random.randint(low=min_num_valid_tokens, high=max_num_valid_tokens + 1, dtype=np.int64)\n\n        for index in range(num_left_padding):\n            masks[i, index] = 0\n\n        for index in range(num_left_padding + num_valid, sequence_length):\n            masks[i, index] = 0\n    return masks\n\n\ndef compute_position_id_with_mask(mask):\n    return torch.clip(torch.cumsum(mask, dim=-1) - 1, min=0, max=None)\n\n\ndef normalize_pp_vpp_params(params, num_hidden_layers, layer_name='layers'):\n    \"\"\"\n    Normalize the pp vpp params into a complete named parameters. \n    This is useful when gather parameters from pp ranks and passed to a model without pp\n\n    params: List[List[Dict[str, param]]]\n        params contains a list of pp, with a list of vpp named_parameters in each vpp chunk.\n    output: Dict[str, param]\n\n    \"\"\"\n\n    def normalize_model_name(name, pp_rank, vpp_rank, pp_size, vpp_size, num_layers):\n        \"\"\"\n        Transform the model name in each model_chunk in each pp stage into the name in inference engine\n        \"\"\"\n        if vpp_size > 1:\n            # print(f'try to bind vpp params to inference engine...')\n            layers_per_pp = num_layers // pp_size\n            layers_per_vpp = layers_per_pp // vpp_size\n            pp_offset = layers_per_vpp * pp_rank\n            vpp_offset = (layers_per_vpp * pp_size) * vpp_rank\n            layer_offset = pp_offset + vpp_offset\n        else:\n            layers_per_pp = num_layers // pp_size\n            layer_offset = layers_per_pp * pp_rank\n\n        if layer_name in name:  # belong to an intermediate layer\n            split_name = name.split('.')\n            # find the num next to split_name\n            for i, name in enumerate(split_name):\n                if name == layer_name:\n                    break\n            layer_num_idx = i + 1\n            # check the name\n            assert len(split_name) >= layer_num_idx + 1, f'split_name = {split_name}'\n            assert split_name[layer_num_idx].isdigit(), f'split_name = {split_name}'\n            # increment layer_num_idx by layer_offset\n            split_name[layer_num_idx] = str(int(split_name[layer_num_idx]) + layer_offset)\n            name = '.'.join(split_name)  # weight name in inference_tp_model\n        return name\n\n    pp_size = len(params)\n    normalized_name_to_param = {}\n    for pp_rank in range(len(params)):\n        vpp_size = len(params[pp_rank])\n        for vpp_rank in range(vpp_size):\n            for name, param in params[pp_rank][vpp_rank].items():\n                normalized_name = normalize_model_name(name, pp_rank, vpp_rank, pp_size, vpp_size, num_hidden_layers)\n                normalized_name_to_param[normalized_name] = param\n\n    return normalized_name_to_param\n\n\ndef get_parallel_model_from_config(config,\n                                   megatron_config,\n                                   pre_process=None,\n                                   post_process=None,\n                                   share_embeddings_and_output_weights=False,\n                                   value=False):\n    from megatron.core import ModelParallelConfig\n    assert isinstance(megatron_config, ModelParallelConfig)\n    model_class = _get_parallel_model_architecture_from_config(config, value)\n\n    model = model_class(config,\n                        megatron_config,\n                        pre_process=pre_process,\n                        post_process=post_process,\n                        share_embeddings_and_output_weights=share_embeddings_and_output_weights)\n    return model\n\n\ndef _get_parallel_model_architecture_from_config(config: PretrainedConfig, value=False) -> Type[nn.Module]:\n    architectures = getattr(config, \"architectures\", [])\n    for arch in architectures:\n        model_cls = ModelRegistry.load_model_cls(arch, value)\n        if model_cls is not None:\n            return model_cls\n    raise ValueError(f\"Model architectures {architectures} are not supported for now. \"\n                     f\"Supported architectures: {ModelRegistry.get_supported_archs()}\")\n\n\ndef load_megatron_model_weights(config,\n                                model_config,\n                                parallel_model,\n                                params_dtype,\n                                is_value_model=False,\n                                local_cache_path='~/.cache/verl/rlhf'):\n    assert hasattr(model_config, \"architectures\"), \"architectures cannot be empty when load weight!\"\n    architectures = getattr(model_config, \"architectures\", [])\n    local_cache_path = os.path.expanduser(local_cache_path)\n\n    if config.model.path.startswith(\"hdfs:\"):\n        from verl.utils.fs import copy_to_local\n        print(f'start download from {config.model.path}')\n        local_model_path = copy_to_local(src=config.model.path, cache_dir=local_cache_path)\n        print('finish download')\n    else:\n        print(f\"load from local dir {config.model.path}\")\n        local_model_path = config.model.path\n\n    # TODO: to find a better way to load mistral7b-rm lm_head\n    if 'mistral7b-rm' in config.model.path:\n        model = MistralForSequenceClassification.from_pretrained(local_model_path)  # use score head instead of lm_head\n        state_dict = model.state_dict()\n        state_dict['lm_head.weight'] = state_dict['score.weight']\n        state_dict['model.embed_tokens.weight'] = state_dict[\n            'model.embed_tokens.weight'][:32000]  # workaround, 32001 -> 32000\n        is_value_model = True\n    else:\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n        model = AutoModelForCausalLM.from_pretrained(local_model_path)\n        state_dict = model.state_dict()\n\n    from verl.models.weight_loader_registry import get_weight_loader\n    print(f'before weight loader: architectures = {architectures}...')\n    for arch in architectures:\n        print(f'call weight loader arch = {arch}, model config = {model.config}')\n        weight_loader = get_weight_loader(arch)\n        weight_loader(state_dict=state_dict,\n                      wrapped_models=parallel_model,\n                      config=model.config,\n                      params_dtype=params_dtype,\n                      is_value_model=is_value_model)\n\n\n# pad input_ids_rmpad, cu_seqlens and max_seqlen_in_batch to be divisible by tp\ndef pad_packed_inputs(unpad_tokens: torch.Tensor, cu_seqlens, max_seqlen_in_batch, size):\n    \"\"\"pad the tokens such that the total length is a multiple of size.\n    This function is useful when applying sequence parallel and context parallel\n\n    Args:\n        unpad_tokens: (total_nnz, ...). Tokens after removing padding\n        cu_seqlens: (total_nnz + 1,)\n        max_seqlen_in_batch: int\n\n    Returns:\n\n    \"\"\"\n    F = nn.functional\n\n    total_nnz = unpad_tokens.shape[0]\n\n    if total_nnz % size == 0:\n        pad_size = 0\n    else:\n        pad_size = size - total_nnz % size\n\n    # we assume adding a new data in the batch with seqlen pad_size\n    if pad_size > 0:\n        if unpad_tokens.ndim == 1:\n            unpad_tokens = F.pad(unpad_tokens, (0, pad_size))\n        elif unpad_tokens.ndim == 2:\n            unpad_tokens = F.pad(unpad_tokens, (0, 0, 0, pad_size))\n        else:\n            raise NotImplementedError(f'Padding dim {unpad_tokens.ndim()} is not supported')\n\n        cu_seqlens = F.pad(cu_seqlens, (0, 1), value=pad_size + cu_seqlens[-1])\n        max_seqlen_in_batch = max(max_seqlen_in_batch, pad_size)\n\n    return unpad_tokens, cu_seqlens, max_seqlen_in_batch\n"
  },
  {
    "path": "verl/utils/py_functional.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nContain small python utility functions\n\"\"\"\n\nfrom typing import Dict\nfrom types import SimpleNamespace\n\n\ndef union_two_dict(dict1: Dict, dict2: Dict):\n    \"\"\"Union two dict. Will throw an error if there is an item not the same object with the same key.\n\n    Args:\n        dict1:\n        dict2:\n\n    Returns:\n\n    \"\"\"\n    for key, val in dict2.items():\n        if key in dict1:\n            assert dict2[key] == dict1[key], \\\n                f'{key} in meta_dict1 and meta_dict2 are not the same object'\n        dict1[key] = val\n\n    return dict1\n\n\ndef append_to_dict(data: Dict, new_data: Dict):\n    for key, val in new_data.items():\n        if key not in data:\n            data[key] = []\n        data[key].append(val)\n\n\nclass NestedNamespace(SimpleNamespace):\n\n    def __init__(self, dictionary, **kwargs):\n        super().__init__(**kwargs)\n        for key, value in dictionary.items():\n            if isinstance(value, dict):\n                self.__setattr__(key, NestedNamespace(value))\n            else:\n                self.__setattr__(key, value)\n"
  },
  {
    "path": "verl/utils/ray_utils.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nContains commonly used utilities for ray\n\"\"\"\n\nimport ray\n\nimport concurrent.futures\n\n\ndef parallel_put(data_list, max_workers=None):\n\n    def put_data(index, data):\n        return index, ray.put(data)\n\n    if max_workers is None:\n        max_workers = min(len(data_list), 16)\n\n    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:\n        data_list_f = [executor.submit(put_data, i, data) for i, data in enumerate(data_list)]\n        res_lst = []\n        for future in concurrent.futures.as_completed(data_list_f):\n            res_lst.append(future.result())\n\n        # reorder based on index\n        output = [None for _ in range(len(data_list))]\n        for res in res_lst:\n            index, data_ref = res\n            output[index] = data_ref\n\n    return output\n"
  },
  {
    "path": "verl/utils/rendezvous/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/utils/rendezvous/ray_backend.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport time\n\nfrom cupy.cuda.nccl import NcclCommunicator, get_unique_id\n\nimport ray\nfrom ray.util import list_named_actors\n\n\n@ray.remote\nclass NCCLIDStore:\n\n    def __init__(self, nccl_id):\n        self._nccl_id = nccl_id\n\n    def get(self):\n        return self._nccl_id\n\n\ndef get_nccl_id_store_by_name(name):\n    all_actors = list_named_actors(all_namespaces=True)\n    matched_actors = [actor for actor in all_actors if actor.get(\"name\", None) == name]\n    if len(matched_actors) == 1:\n        actor = matched_actors[0]\n        return ray.get_actor(**actor)\n    elif len(matched_actors) > 1:\n        logging.warning(f\"multiple actors with same name found: {matched_actors}\")\n    elif len(matched_actors) == 0:\n        logging.info(f\"failed to get any actor named {name}\")\n    return None\n\n\ndef create_nccl_communicator_in_ray(rank: int,\n                                    world_size: int,\n                                    group_name: str,\n                                    max_retries: int = 100,\n                                    interval_s: int = 5):\n    if rank == 0:\n        nccl_id = get_unique_id()\n        nccl_id_store = NCCLIDStore.options(name=group_name).remote(nccl_id)\n\n        assert ray.get(nccl_id_store.get.remote()) == nccl_id\n        communicator = NcclCommunicator(\n            ndev=world_size,\n            commId=nccl_id,\n            rank=0,\n        )\n        return communicator\n    else:\n        for i in range(max_retries):\n            nccl_id_store = get_nccl_id_store_by_name(group_name)\n            if nccl_id_store is not None:\n                logging.info(f\"nccl_id_store {group_name} got\")\n                nccl_id = ray.get(nccl_id_store.get.remote())\n                logging.info(f\"nccl id for {group_name} got: {nccl_id}\")\n                communicator = NcclCommunicator(\n                    ndev=world_size,\n                    commId=nccl_id,\n                    rank=rank,\n                )\n                return communicator\n            logging.info(f\"failed to get nccl_id for {i+1} time, sleep for {interval_s} seconds\")\n            time.sleep(interval_s)\n"
  },
  {
    "path": "verl/utils/reward_score/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# from . import gsm8k, math, prime_math, prime_code\n\n\ndef _default_compute_score(data_source, solution_str, ground_truth, extra_info=None, reward_type=None):\n    if data_source == 'openai/gsm8k':\n        from . import gsm8k\n        res = gsm8k.compute_score(solution_str, ground_truth)\n    elif data_source in ['lighteval/MATH', 'DigitalLearningGmbH/MATH-lighteval']:\n        from . import math\n        res = math.compute_score(solution_str, ground_truth)\n    elif data_source in [\n            'numina_aops_forum', 'numina_synthetic_math', 'numina_amc_aime', 'numina_synthetic_amc', 'numina_cn_k12',\n            'numina_olympiads'\n    ]:\n        from . import prime_math\n        res = prime_math.compute_score(solution_str, ground_truth)\n    elif data_source in ['codecontests', 'apps', 'codeforces', 'taco']:\n        from . import prime_code\n        res = prime_code.compute_score(solution_str, ground_truth, continuous=True)\n    elif data_source in ['hiyouga/geometry3k']:\n        from . import geo3k\n        res = geo3k.compute_score(solution_str, ground_truth)\n    else:\n        from . import math_verifier\n        res = math_verifier.compute_score(solution_str, ground_truth, reward_type)\n\n    if isinstance(res, (int, float, bool)):\n        return float(res)\n    else:\n        return float(res[0])\n"
  },
  {
    "path": "verl/utils/reward_score/eval.py",
    "content": "import os\nimport json\nimport jsonlines\nimport re\nimport copy\n\nPATTERNS=[\n    r\"(?i)Answer\\s*:\\s*([^\\n]+)\",\n    r\"\\\\boxed\\{((?:[^{}]|\\\\{|\\\\}|(?:\\{(?:[^{}]|\\\\{|\\\\}|(?:\\{(?:[^{}]|\\\\{|\\\\}|(?:\\{[^{}]*\\}))*\\}))*\\}))*\\})\",\n]\ndef extract_pattern(pred: str, pattern: str):\n    match = re.findall(pattern, pred)\n    # 从pred中extract出一个answerlist，代表所有可能的answer\n    if match:\n        extracted_answer = match[-1]\n        if pattern==r\"\\\\boxed\\{((?:[^{}]|\\\\{|\\\\}|(?:\\{(?:[^{}]|\\\\{|\\\\}|(?:\\{(?:[^{}]|\\\\{|\\\\}|(?:\\{[^{}]*\\}))*\\}))*\\}))*\\})\": extracted_answer=extracted_answer[:-1]\n        return extracted_answer.strip(\"*\").strip().strip(\"*\")\n    else:\n        return \"\"\n\nSPLIT=[\n    \"####\"\n    \"\\n\",\n    \"Answer:\",\n]\ndef extract_split(pred: str, split: str):\n    '''\n    最后一个换行符之后的部分\n    '''\n    pred=pred.split(split)[-1]\n    return pred.strip(\"*\").strip().strip(\"*\")\n\n\ndef expansion(answer_list: str):\n    org_answer_list=copy.deepcopy(answer_list)\n    for answer in org_answer_list:\n        if \"=\" in answer:\n            answer_list.append(answer.split(\"=\")[-1])\n        for choice in [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"]:\n            if f\"({choice.upper()})\" in answer.upper() or f\"{choice.upper()}:\" in answer.upper() or f\"{choice.upper()}. \" in answer.upper(): \n                answer_list.append(f\"{choice.upper()}\")\n                break\n    for answer in org_answer_list:\n        pattern = r'^(\\d+(\\.\\d+)?)\\s+[a-zA-Z]+(?:\\s+[a-zA-Z]+)*$'\n        if bool(re.match(pattern, answer)): answer_list.append(answer.split(\" \")[0])\n    for answer in org_answer_list:\n        if \"\\\\in\" in answer:\n            answer_list.append(answer.split(\"\\\\in\")[-1].strip())\n        if \"\\u2208\" in answer:\n            answer_list.append(answer.split(\"\\u2208\")[-1].strip())\n    return answer_list\n\ndef extract(pred: str):\n    answer_list=[]\n    answer_list.append(pred.split(\"####\")[-1].strip())\n\n    for split in SPLIT:\n        answer_list.append(extract_split(copy.deepcopy(pred), split=split))\n    for pattern in PATTERNS:\n        answer_list.append(extract_pattern(copy.deepcopy(pred), pattern=pattern))\n    answer_list=expansion(answer_list)\n    return answer_list\n\n\n\nimport re\n\n\nSUBSTITUTIONS = [\n    (\"an \", \"\"),\n    # (\"a \", \"\"),\n    (\".$\", \"$\"),\n    (\"\\\\$\", \"\"),\n    (r\"\\ \", \"\"),\n    (\" \", \"\"),\n    (\"mbox\", \"text\"),\n    (\",\\\\text{and}\", \",\"),\n    (\"\\\\text{and}\", \",\"),\n    (\"\\\\text{m}\", \"\\\\text{}\"),\n    (\"\\\\left\", \"\"),\n    (\"\\\\right\", \"\"),\n    (\"∶\", \":\"),\n    (\"，\", \",\"),\n    (\"$\",  \"\"),\n    (\"\\\\approx\", \"=\"),\n    (\"\\\\simeq\", \"=\"),\n    (\"\\\\sim\", \"=\"),\n    (\"^\\\\prime\", \"'\"),\n    (\"^{\\\\prime}\", \"'\"),\n    (\"\\\\dfrac\", \"\\\\frac\"),\n    (\"\\\\tfrac\", \"\\\\frac\"),\n    (\"^\\\\circ\", \"\"),\n    (\"%\", \"\"),\n    (\"\\u221a\", \"\\\\sqrt\"),\n    (\"\\u221e\", \"\\\\infty\"),\n    (\"\\u222a\", \"\\\\cup\"),\n]\n\nREMOVED_EXPRESSIONS = [\n    \"square\",\n    \"ways\",\n    \"integers\",\n    \"dollars\",\n    \"mph\",\n    \"inches\",\n    # \"ft\", #this is dangerous, infty, left will be damaged!\n    \"hours\",\n    \"km\",\n    \"units\",\n    \"\\\\ldots\",\n    \"sue\",\n    \"points\",\n    \"feet\",\n    \"minutes\",\n    \"digits\",\n    \"cents\",\n    \"degrees\",\n    \"cm\",\n    \"gm\",\n    \"pounds\",\n    \"meters\",\n    \"meals\",\n    \"edges\",\n    \"students\",\n    \"childrentickets\",\n    \"multiples\",\n    \"\\\\text{s}\",\n    \"\\\\text{.}\",\n    \"\\\\text{\\ns}\",\n    \"\\\\text{}^2\",\n    \"\\\\text{}^3\",\n    \"\\\\text{\\n}\",\n    \"\\\\text{}\",\n    r\"\\mathrm{th}\",\n    r\"^\\circ\",\n    r\"^{\\circ}\",\n    r\"\\;\",\n    r\",\\!\",\n    \"{,}\",\n    '\"',\n    \"\\\\dots\",\n]\n\n\n\ndef normalize_final_answer(final_answer: str) -> str:\n    \"\"\"\n    Normalize a final answer to a quantitative reasoning question.\n    Copied character for character from appendix D of Lewkowycz et al. (2022)\n    \"\"\"\n    # final_answer = final_answer.split(\"=\")[-1]\n    final_answer=final_answer.strip()\n    if final_answer[:2]==\"\\\\(\" or final_answer[:2]=='\\\\[':\n        final_answer=final_answer[2:]\n    if final_answer[-2:]=='\\\\)' or final_answer[-2:]=='\\\\]':\n        final_answer=final_answer[:-2]\n    \n    for before, after in SUBSTITUTIONS:\n        final_answer = final_answer.replace(before, after)\n    for expr in REMOVED_EXPRESSIONS:\n        final_answer = final_answer.replace(expr, \"\")\n    # Extract answer that is in LaTeX math, is bold,\n    # is surrounded by a box, etc.\n    final_answer = re.sub(r\"(.*?)(\\$)(.*?)(\\$)(.*)\", \"$\\\\3$\", final_answer)\n    final_answer = re.sub(r\"(\\\\text\\{)(.*?)(\\})\", \"\\\\2\", final_answer)\n    final_answer = re.sub(r\"(\\\\textbf\\{)(.*?)(\\})\", \"\\\\2\", final_answer)\n    final_answer = re.sub(r\"(\\\\overline\\{)(.*?)(\\})\", \"\\\\2\", final_answer)\n    final_answer = re.sub(r\"(\\\\boxed\\{)(.*)(\\})\", \"\\\\2\", final_answer)\n    # Normalize shorthand TeX:\n    #  \\fracab -> \\frac{a}{b}\n    #  \\frac{abc}{bef} -> \\frac{abc}{bef}\n    #  \\fracabc -> \\frac{a}{b}c\n    #  \\sqrta -> \\sqrt{a}\n    #  \\sqrtab -> sqrt{a}b\n    final_answer = re.sub(r\"(frac)([^{])(.)\", \"frac{\\\\2}{\\\\3}\", final_answer)\n    final_answer = re.sub(r\"(sqrt)([^{])\", \"sqrt{\\\\2}\", final_answer)\n    final_answer = final_answer.replace(\"$\", \"\")\n    # Normalize 100,000 -> 100000\n    if final_answer.replace(\",\", \"\").isdigit():\n        final_answer = final_answer.replace(\",\", \"\")\n    if final_answer[:2]==\"\\\\(\" or final_answer[:2]=='\\\\[':\n        final_answer=final_answer[2:]\n    if final_answer[-2:]=='\\\\)' or final_answer[-2:]=='\\\\]':\n        final_answer=final_answer[:-2]\n    return final_answer.strip()\n\n\"\"\"\nThis logic is largely copied from the Hendrycks' MATH release (math_equivalence), and borrowed from:\n- https://github.com/microsoft/ProphetNet/tree/master/CRITIC\n- https://github.com/openai/prm800k\n- https://github.com/microsoft/ToRA/blob/main/src/eval/grader.py\n- https://github.com/deepseek-ai/DeepSeek-Math/blob/main/evaluation/eval/eval_utils.py\n\"\"\"\n\nimport re\nimport regex\nimport multiprocessing\nfrom math import isclose\nfrom typing import Union\nfrom collections import defaultdict\n\nfrom sympy import simplify, N\nfrom sympy.parsing.sympy_parser import parse_expr\nfrom sympy.parsing.latex import parse_latex\n# from latex2sympy2 import latex2sympy\n\n# from .parser import choice_answer_clean, strip_string\n# from parser import choice_answer_clean\n\n\ndef choice_answer_clean(pred: str):\n    pred = pred.strip(\"\\n\").rstrip(\".\").rstrip(\"/\").strip(\" \").lstrip(\":\")\n    # Clean the answer based on the dataset\n    tmp = re.findall(r\"\\b(A|B|C|D|E)\\b\", pred.upper())\n    if tmp:\n        pred = tmp\n    else:\n        pred = [pred.strip().strip(\".\")]\n    pred = pred[-1]\n    # Remove the period at the end, again!\n    pred = pred.rstrip(\".\").rstrip(\"/\")\n    return pred\n\n\ndef parse_digits(num):\n    num = regex.sub(\",\", \"\", str(num))\n    try:\n        return float(num)\n    except:\n        if num.endswith(\"%\"):\n            num = num[:-1]\n            if num.endswith(\"\\\\\"):\n                num = num[:-1]\n            try:\n                return float(num) / 100\n            except:\n                pass\n    return None\n\n\ndef is_digit(num):\n    # paired with parse_digits\n    return parse_digits(num) is not None\n\n\ndef str_to_pmatrix(input_str):\n    input_str = input_str.strip()\n    matrix_str = re.findall(r\"\\{.*,.*\\}\", input_str)\n    pmatrix_list = []\n\n    for m in matrix_str:\n        m = m.strip(\"{}\")\n        pmatrix = r\"\\begin{pmatrix}\" + m.replace(\",\", \"\\\\\") + r\"\\end{pmatrix}\"\n        pmatrix_list.append(pmatrix)\n\n    return \", \".join(pmatrix_list)\n\n\ndef math_equal(\n    prediction: Union[bool, float, str],\n    reference: Union[float, str],\n    include_percentage: bool = True,\n    is_close: bool = True,\n    timeout: bool = False,\n) -> bool:\n    \"\"\"\n    Exact match of math if and only if:\n    1. numerical equal: both can convert to float and are equal\n    2. symbolic equal: both can convert to sympy expression and are equal\n    \"\"\"\n    # print(\"Judge:\", prediction, reference)\n    if prediction is None or reference is None:\n        return False\n    if str(prediction.strip().lower()) == str(reference.strip().lower()):\n        return True\n    if (\n        reference in [\"A\", \"B\", \"C\", \"D\", \"E\"]\n        and choice_answer_clean(prediction) == reference\n    ):\n        return True\n\n    try:  # 1. numerical equal\n        if is_digit(prediction) and is_digit(reference):\n            prediction = parse_digits(prediction)\n            reference = parse_digits(reference)\n            # number questions\n            if include_percentage:\n                gt_result = [reference / 100, reference, reference * 100]\n            else:\n                gt_result = [reference]\n            for item in gt_result:\n                try:\n                    if is_close:\n                        if numeric_equal(prediction, item):\n                            return True\n                    else:\n                        if item == prediction:\n                            return True\n                except Exception:\n                    continue\n            return False\n    except:\n        pass\n\n    if not prediction and prediction not in [0, False]:\n        return False\n    \n    # 2. symbolic equal\n    reference = str(reference).strip()\n    prediction = str(prediction).strip()\n\n    ## pmatrix (amps)\n    if \"pmatrix\" in prediction and not \"pmatrix\" in reference:\n        reference = str_to_pmatrix(reference)\n\n    ## deal with [], (), {}\n    pred_str, ref_str = prediction, reference\n    if (\n        prediction.startswith(\"[\")\n        and prediction.endswith(\"]\")\n        and not reference.startswith(\"(\")\n    ) or (\n        prediction.startswith(\"(\")\n        and prediction.endswith(\")\")\n        and not reference.startswith(\"[\")\n    ):\n        pred_str = pred_str.strip(\"[]()\")\n        ref_str = ref_str.strip(\"[]()\")\n    for s in [\"{\", \"}\", \"(\", \")\"]:\n        ref_str = ref_str.replace(s, \"\")\n        pred_str = pred_str.replace(s, \"\")\n    if pred_str.lower() == ref_str.lower():\n        return True\n\n    ## [a, b] vs. [c, d], return a==c and b==d\n    if (\n        regex.match(r\"(\\(|\\[).+(\\)|\\])\", prediction) is not None\n        and regex.match(r\"(\\(|\\[).+(\\)|\\])\", reference) is not None\n    ):\n        pred_parts = prediction[1:-1].split(\",\")\n        ref_parts = reference[1:-1].split(\",\")\n        if len(pred_parts) == len(ref_parts):\n            if all(\n                [\n                    math_equal(\n                        pred_parts[i], ref_parts[i], include_percentage, is_close\n                    )\n                    for i in range(len(pred_parts))\n                ]\n            ):\n                return True\n    if (\n        (\n            prediction.startswith(\"\\\\begin{pmatrix}\")\n            or prediction.startswith(\"\\\\begin{bmatrix}\")\n        )\n        and (\n            prediction.endswith(\"\\\\end{pmatrix}\")\n            or prediction.endswith(\"\\\\end{bmatrix}\")\n        )\n        and (\n            reference.startswith(\"\\\\begin{pmatrix}\")\n            or reference.startswith(\"\\\\begin{bmatrix}\")\n        )\n        and (\n            reference.endswith(\"\\\\end{pmatrix}\") or reference.endswith(\"\\\\end{bmatrix}\")\n        )\n    ):\n        pred_lines = [\n            line.strip()\n            for line in prediction[\n                len(\"\\\\begin{pmatrix}\") : -len(\"\\\\end{pmatrix}\")\n            ].split(\"\\\\\\\\\")\n            if line.strip()\n        ]\n        ref_lines = [\n            line.strip()\n            for line in reference[\n                len(\"\\\\begin{pmatrix}\") : -len(\"\\\\end{pmatrix}\")\n            ].split(\"\\\\\\\\\")\n            if line.strip()\n        ]\n        matched = True\n        if len(pred_lines) == len(ref_lines):\n            for pred_line, ref_line in zip(pred_lines, ref_lines):\n                pred_parts = pred_line.split(\"&\")\n                ref_parts = ref_line.split(\"&\")\n                if len(pred_parts) == len(ref_parts):\n                    if not all(\n                        [\n                            math_equal(\n                                pred_parts[i],\n                                ref_parts[i],\n                                include_percentage,\n                                is_close,\n                            )\n                            for i in range(len(pred_parts))\n                        ]\n                    ):\n                        matched = False\n                        break\n                else:\n                    matched = False\n                if not matched:\n                    break\n        else:\n            matched = False\n        if matched:\n            return True\n\n    if prediction.count(\"=\") == 1 and reference.count(\"=\") == 1:\n        pred = prediction.split(\"=\")\n        pred = f\"{pred[0].strip()} - ({pred[1].strip()})\"\n        ref = reference.split(\"=\")\n        ref = f\"{ref[0].strip()} - ({ref[1].strip()})\"\n        if symbolic_equal(pred, ref) or symbolic_equal(f\"-({pred})\", ref):\n            return True\n    elif (\n        prediction.count(\"=\") == 1\n        and len(prediction.split(\"=\")[0].strip()) <= 2\n        and \"=\" not in reference\n    ):\n        if math_equal(\n            prediction.split(\"=\")[1], reference, include_percentage, is_close\n        ):\n            return True\n    elif (\n        reference.count(\"=\") == 1\n        and len(reference.split(\"=\")[0].strip()) <= 2\n        and \"=\" not in prediction\n    ):\n        if math_equal(\n            prediction, reference.split(\"=\")[1], include_percentage, is_close\n        ):\n            return True\n\n    # symbolic equal with sympy\n    if timeout:\n        if call_with_timeout(symbolic_equal_process, prediction, reference):\n            return True\n    else:\n        if symbolic_equal(prediction, reference):\n            return True\n    # symbolic == numeric\n    try:\n        prediction=float(N(parse_latex(prediction)))\n        if abs(prediction-float(reference))<=1e-8: True\n    except:\n        pass\n    try:\n        reference=float(N(parse_latex(reference)))\n        if abs(prediction-reference)<=1e-8: return True\n    except:\n        pass\n    return False\n\n\ndef math_equal_process(param):\n    return math_equal(param[-2], param[-1])\n\n\ndef numeric_equal(prediction: float, reference: float):\n    # prediction = round(prediction, len(str(reference).split(\".\")[-1]))\n    return isclose(reference, prediction, rel_tol=1e-4)\n\n\ndef symbolic_equal(a, b):\n    def _parse(s):\n        for f in [parse_latex, parse_expr]:\n            try:\n                return f(s.replace(\"\\\\\\\\\", \"\\\\\"))\n            except:\n                try:\n                    return f(s)\n                except:\n                    pass\n        return s\n\n    a = _parse(a)\n    b = _parse(b)\n    # direct equal\n    try:\n        if str(a) == str(b) or a == b:\n            return True\n    except:\n        pass\n\n    # simplify equal\n    try:\n        if a.equals(b) or simplify(a - b) == 0:\n            return True\n    except:\n        pass\n\n    # equation equal\n    try:\n        if (abs(a.lhs - a.rhs)).equals(abs(b.lhs - b.rhs)):\n            return True\n    except:\n        pass\n\n    try:\n        if numeric_equal(float(N(a)), float(N(b))):\n            return True\n    except:\n        pass\n\n    # matrix\n    try:\n        # if a and b are matrix\n        if a.shape == b.shape:\n            _a = a.applyfunc(lambda x: round(x, 3))\n            _b = b.applyfunc(lambda x: round(x, 3))\n            if _a.equals(_b):\n                return True\n    except:\n        pass\n\n    return False\n\n\ndef symbolic_equal_process(a, b, output_queue):\n    result = symbolic_equal(a, b)\n    output_queue.put(result)\n\n\ndef call_with_timeout(func, *args, timeout=1, **kwargs):\n    output_queue = multiprocessing.Queue()\n    process_args = args + (output_queue,)\n    process = multiprocessing.Process(target=func, args=process_args, kwargs=kwargs)\n    process.start()\n    process.join(timeout)\n\n    if process.is_alive():\n        process.terminate()\n        process.join()\n        return False\n\n    return output_queue.get()\n\ndef process_answer_list(answer_list):\n    answer_list = list(set(answer_list))\n    if \"\" in answer_list: answer_list.remove(\"\")\n    return answer_list\n\n\nimport os\nimport json\nimport jsonlines\nimport copy\nfrom tqdm import tqdm \nimport pandas as pd\nfrom multiprocessing import Pool\nfrom functools import partial\nfrom datetime import datetime\n# api\n\n\ndef is_equal(pred, gt):\n    pred=normalize_final_answer(pred)\n    gt=normalize_final_answer(gt)\n    return math_equal(pred, gt)\n\n\ndef exact_match_eval(pred, gt):\n    gt=normalize_final_answer(gt)\n\n    answer_list=extract(pred)\n    normalized_answer_list=[]\n    for answer in copy.deepcopy(answer_list):\n        normalized_answer_list.append(normalize_final_answer(answer))\n    normalized_answer_list=process_answer_list(normalized_answer_list)\n\n    for answer in normalized_answer_list:\n        if math_equal(gt, answer):\n            return normalized_answer_list, True\n    return normalized_answer_list, False\n\n"
  },
  {
    "path": "verl/utils/reward_score/geo3k.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport re\nfrom mathruler.grader import extract_boxed_content, grade_answer\n\n\ndef format_reward(predict_str: str) -> float:\n    pattern = re.compile(r'<think>.*</think>.*\\\\boxed\\{.*\\}.*', re.DOTALL)\n    match_result = re.fullmatch(pattern, predict_str)\n    return 1.0 if match_result else 0.0\n\n\ndef acc_reward(predict_str: str, ground_truth: str) -> float:\n    answer = extract_boxed_content(predict_str)\n    return 1.0 if grade_answer(answer, ground_truth) else 0.0\n\n\ndef compute_score(predict_str: str, ground_truth: str) -> float:\n    return 0.9 * acc_reward(predict_str, ground_truth) + 0.1 * format_reward(predict_str)\n"
  },
  {
    "path": "verl/utils/reward_score/gsm8k.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport re\n\n\ndef extract_solution(solution_str, method='strict'):\n    assert method in ['strict', 'flexible']\n\n    if method == 'strict':\n        # this also tests the formatting of the model\n        solution = re.search(\"#### (\\\\-?[0-9\\\\.\\\\,]+)\", solution_str)\n        if solution is None:\n            final_answer = None\n        else:\n            final_answer = solution.group(0)\n            final_answer = final_answer.split('#### ')[1].replace(',', '').replace('$', '')\n    elif method == 'flexible':\n        answer = re.findall(\"(\\\\-?[0-9\\\\.\\\\,]+)\", solution_str)\n        final_answer = None\n        if len(answer) == 0:\n            # no reward is there is no answer\n            pass\n        else:\n            invalid_str = ['', '.']\n            # find the last number that is not '.'\n            for final_answer in reversed(answer):\n                if final_answer not in invalid_str:\n                    break\n    return final_answer\n\n\ndef compute_score(solution_str, ground_truth, method='strict', format_score=0., score=1.):\n    \"\"\"The scoring function for GSM8k.\n\n    Reference: Trung, Luong, et al. \"Reft: Reasoning with reinforced fine-tuning.\" Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers). 2024.\n\n    Args:\n        solution_str: the solution text\n        ground_truth: the ground truth\n        method: the method to extract the solution, choices are 'strict' and 'flexible'\n        format_score: the score for the format\n        score: the score for the correct answer\n    \"\"\"\n    answer = extract_solution(solution_str=solution_str, method=method)\n    if answer is None:\n        return 0\n    else:\n        if answer == ground_truth:\n            return score\n        else:\n            return format_score"
  },
  {
    "path": "verl/utils/reward_score/math.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/hendrycks_math/utils.py\n\n\ndef compute_score(solution_str, ground_truth) -> float:\n    retval = 0.\n    try:\n        string_in_last_boxed = last_boxed_only_string(solution_str)\n        if string_in_last_boxed is not None:\n            answer = remove_boxed(string_in_last_boxed)\n            if is_equiv(answer, ground_truth):\n                retval = 1.\n    except Exception as e:\n        print(e)\n\n    return retval\n\n\n# string normalization from https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_math.py\ndef is_equiv(str1, str2, verbose=False):\n    if str1 is None and str2 is None:\n        print(\"WARNING: Both None\")\n        return True\n    if str1 is None or str2 is None:\n        return False\n\n    try:\n        ss1 = strip_string(str1)\n        ss2 = strip_string(str2)\n        if verbose:\n            print(ss1, ss2)\n        return ss1 == ss2\n    except Exception:\n        return str1 == str2\n\n\ndef remove_boxed(s):\n    if \"\\\\boxed \" in s:\n        left = \"\\\\boxed \"\n        assert s[:len(left)] == left\n        return s[len(left):]\n\n    left = \"\\\\boxed{\"\n\n    assert s[:len(left)] == left\n    assert s[-1] == \"}\"\n\n    return s[len(left):-1]\n\n\ndef last_boxed_only_string(string):\n    idx = string.rfind(\"\\\\boxed\")\n    if \"\\\\boxed \" in string:\n        return \"\\\\boxed \" + string.split(\"\\\\boxed \")[-1].split(\"$\")[0]\n    if idx < 0:\n        idx = string.rfind(\"\\\\fbox\")\n        if idx < 0:\n            return None\n\n    i = idx\n    right_brace_idx = None\n    num_left_braces_open = 0\n    while i < len(string):\n        if string[i] == \"{\":\n            num_left_braces_open += 1\n        if string[i] == \"}\":\n            num_left_braces_open -= 1\n            if num_left_braces_open == 0:\n                right_brace_idx = i\n                break\n        i += 1\n\n    if right_brace_idx is None:\n        retval = None\n    else:\n        retval = string[idx:right_brace_idx + 1]\n\n    return retval\n\n\ndef fix_fracs(string):\n    substrs = string.split(\"\\\\frac\")\n    new_str = substrs[0]\n    if len(substrs) > 1:\n        substrs = substrs[1:]\n        for substr in substrs:\n            new_str += \"\\\\frac\"\n            if substr[0] == \"{\":\n                new_str += substr\n            else:\n                try:\n                    assert len(substr) >= 2\n                except AssertionError:\n                    return string\n                a = substr[0]\n                b = substr[1]\n                if b != \"{\":\n                    if len(substr) > 2:\n                        post_substr = substr[2:]\n                        new_str += \"{\" + a + \"}{\" + b + \"}\" + post_substr\n                    else:\n                        new_str += \"{\" + a + \"}{\" + b + \"}\"\n                else:\n                    if len(substr) > 2:\n                        post_substr = substr[2:]\n                        new_str += \"{\" + a + \"}\" + b + post_substr\n                    else:\n                        new_str += \"{\" + a + \"}\" + b\n    string = new_str\n    return string\n\n\ndef fix_a_slash_b(string):\n    if len(string.split(\"/\")) != 2:\n        return string\n    a = string.split(\"/\")[0]\n    b = string.split(\"/\")[1]\n    try:\n        a = int(a)\n        b = int(b)\n        assert string == \"{}/{}\".format(a, b)\n        new_string = \"\\\\frac{\" + str(a) + \"}{\" + str(b) + \"}\"\n        return new_string\n    except AssertionError:\n        return string\n\n\ndef remove_right_units(string):\n    # \"\\\\text{ \" only ever occurs (at least in the val set) when describing units\n    if \"\\\\text{ \" in string:\n        splits = string.split(\"\\\\text{ \")\n        assert len(splits) == 2\n        return splits[0]\n    else:\n        return string\n\n\ndef fix_sqrt(string):\n    if \"\\\\sqrt\" not in string:\n        return string\n    splits = string.split(\"\\\\sqrt\")\n    new_string = splits[0]\n    for split in splits[1:]:\n        if split[0] != \"{\":\n            a = split[0]\n            new_substr = \"\\\\sqrt{\" + a + \"}\" + split[1:]\n        else:\n            new_substr = \"\\\\sqrt\" + split\n        new_string += new_substr\n    return new_string\n\n\ndef strip_string(string):\n    # linebreaks\n    string = string.replace(\"\\n\", \"\")\n\n    # remove inverse spaces\n    string = string.replace(\"\\\\!\", \"\")\n\n    # replace \\\\ with \\\n    string = string.replace(\"\\\\\\\\\", \"\\\\\")\n\n    # replace tfrac and dfrac with frac\n    string = string.replace(\"tfrac\", \"frac\")\n    string = string.replace(\"dfrac\", \"frac\")\n\n    # remove \\left and \\right\n    string = string.replace(\"\\\\left\", \"\")\n    string = string.replace(\"\\\\right\", \"\")\n\n    # Remove circ (degrees)\n    string = string.replace(\"^{\\\\circ}\", \"\")\n    string = string.replace(\"^\\\\circ\", \"\")\n\n    # remove dollar signs\n    string = string.replace(\"\\\\$\", \"\")\n\n    # remove units (on the right)\n    string = remove_right_units(string)\n\n    # remove percentage\n    string = string.replace(\"\\\\%\", \"\")\n    string = string.replace(\"\\%\", \"\")  # noqa: W605\n\n    # \" 0.\" equivalent to \" .\" and \"{0.\" equivalent to \"{.\" Alternatively, add \"0\" if \".\" is the start of the string\n    string = string.replace(\" .\", \" 0.\")\n    string = string.replace(\"{.\", \"{0.\")\n    # if empty, return empty string\n    if len(string) == 0:\n        return string\n    if string[0] == \".\":\n        string = \"0\" + string\n\n    # to consider: get rid of e.g. \"k = \" or \"q = \" at beginning\n    if len(string.split(\"=\")) == 2:\n        if len(string.split(\"=\")[0]) <= 2:\n            string = string.split(\"=\")[1]\n\n    # fix sqrt3 --> sqrt{3}\n    string = fix_sqrt(string)\n\n    # remove spaces\n    string = string.replace(\" \", \"\")\n\n    # \\frac1b or \\frac12 --> \\frac{1}{b} and \\frac{1}{2}, etc. Even works with \\frac1{72} (but not \\frac{72}1). Also does a/b --> \\\\frac{a}{b}\n    string = fix_fracs(string)\n\n    # manually change 0.5 --> \\frac{1}{2}\n    if string == \"0.5\":\n        string = \"\\\\frac{1}{2}\"\n\n    # NOTE: X/Y changed to \\frac{X}{Y} in dataset, but in simple cases fix in case the model output is X/Y\n    string = fix_a_slash_b(string)\n\n    return string\n"
  },
  {
    "path": "verl/utils/reward_score/math_verifier.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/hendrycks_math/utils.py\nimport signal\nimport re\nfrom contextlib import contextmanager\nimport importlib.util\nfrom verl.utils.reward_score.eval import normalize_final_answer\nfrom math_verify import parse, verify\nclass TimeoutException(Exception):\n    pass\n\n@contextmanager\ndef timeout(seconds):\n    def signal_handler(signum, frame):\n        raise TimeoutException(\"Timed out!\")\n    signal.signal(signal.SIGALRM, signal_handler)\n    signal.alarm(seconds)\n    try:\n        yield\n    finally:\n        signal.alarm(0)\n\ntimeout_seconds=2\nchinese_pattern = re.compile(r'[\\u4e00-\\u9fff]')\nenglish_pattern = re.compile(r'[a-zA-Z]')\nboxed_pattern = re.compile(r\"\\\\boxed\\{((?:[^{}]|\\\\{|\\\\}|(?:\\{(?:[^{}]|\\\\{|\\\\}|(?:\\{(?:[^{}]|\\\\{|\\\\}|(?:\\{[^{}]*\\}))*\\}))*\\}))*\\})\")\nvalid_char_pattern = re.compile(r'[a-zA-Z0-9\\s\\.,!?\"\\'\\(\\)\\{\\}\\[\\]_\\-+=<>/@#$%^&*\\\\|:;~`\\u2200-\\u22FF]')\nrepeat_pattern = re.compile(r'(.{5,}?)\\1{4,}')\n\ndef check_mixed_languages(text):\n    chinese_chars = len(chinese_pattern.findall(text))\n    english_chars = len(english_pattern.findall(text))\n    return chinese_chars >= 20 and english_chars >= 20\n\ndef undesired_format(text):\n    if \"<|endoftext|>\" not in text: return True\n    else: return False\n\n\ndef check_garbled_characters(text):\n    valid_chars = valid_char_pattern.sub('', text)\n    if not text: \n        return False\n    invalid_ratio = len(valid_chars) / len(text)\n    return invalid_ratio > 0.3\n\ndef has_repeated_patterns(text):\n    return bool(repeat_pattern.search(text))\n    \ndef correctness_score_default(response, gt):\n    matches = boxed_pattern.findall(response)\n    if not matches: return -1.0\n    pred = matches[-1][:-1]\n    return 1.0 if is_equiv(pred, gt) else -1.0\n\n\ndef correctness_score_v2(response, gt):\n    matches = boxed_pattern.findall(response)\n    if not matches: return -1.0\n    pred = matches[-1][:-1]\n    return 1.0 if is_equiv(pred, gt) else -0.5\n\ndef compute_score(solution_str, ground_truth, reward_type) -> float:      \n    if reward_type=='default':\n        try:     \n            # if undesired_format(solution_str): return -1.0\n            return correctness_score_default(solution_str, ground_truth)            \n        except TimeoutException:\n            return -1.0\n        except Exception as e:\n            return -1.0\n    elif reward_type==\"v2.wformat\":\n        try:\n            return correctness_score_v2(solution_str, ground_truth)\n        except TimeoutException:\n            return -1.0\n        except Exception as e:\n            return -1.0\n    else:\n        try:     \n            # if undesired_format(solution_str): return -1.0\n            return correctness_score_default(solution_str, ground_truth)            \n        except TimeoutException:\n            return -1.0\n        except Exception as e:\n            return -1.0\n\n\n\n\n# string normalization from https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_math.py\ndef is_equiv(str1, str2, verbose=False):\n    if str1 is None and str2 is None:\n        print(\"WARNING: Both None\")\n        return True\n    if str1 is None or str2 is None:\n        return False\n    if str1.strip().lower() == str2.strip().lower(): return True\n    try:\n        str1=normalize_final_answer(str1)\n        str2=normalize_final_answer(str2)\n        str1=parse(str1)\n        str2=parse(str2)\n        return verify(str1, str2)\n    except:\n        pass\n\n    try:\n        ss1 = strip_string(str1)\n        ss2 = strip_string(str2)\n        if verbose:\n            print(ss1, ss2)\n        return ss1==ss2\n    except Exception:\n        return str1 == str2\n\n\ndef remove_boxed(s):\n    if \"\\\\boxed \" in s:\n        left = \"\\\\boxed \"\n        assert s[:len(left)] == left\n        return s[len(left):]\n\n    left = \"\\\\boxed{\"\n\n    assert s[:len(left)] == left\n    assert s[-1] == \"}\"\n\n    return s[len(left):-1]\n\n\ndef last_boxed_only_string(string):\n    idx = string.rfind(\"\\\\boxed\")\n    if \"\\\\boxed \" in string:\n        return \"\\\\boxed \" + string.split(\"\\\\boxed \")[-1].split(\"$\")[0]\n    if idx < 0:\n        idx = string.rfind(\"\\\\fbox\")\n        if idx < 0:\n            return None\n\n    i = idx\n    right_brace_idx = None\n    num_left_braces_open = 0\n    while i < len(string):\n        if string[i] == \"{\":\n            num_left_braces_open += 1\n        if string[i] == \"}\":\n            num_left_braces_open -= 1\n            if num_left_braces_open == 0:\n                right_brace_idx = i\n                break\n        i += 1\n\n    if right_brace_idx is None:\n        retval = None\n    else:\n        retval = string[idx:right_brace_idx + 1]\n\n    return retval\n\n\ndef fix_fracs(string):\n    substrs = string.split(\"\\\\frac\")\n    new_str = substrs[0]\n    if len(substrs) > 1:\n        substrs = substrs[1:]\n        for substr in substrs:\n            new_str += \"\\\\frac\"\n            if substr[0] == \"{\":\n                new_str += substr\n            else:\n                try:\n                    assert len(substr) >= 2\n                except AssertionError:\n                    return string\n                a = substr[0]\n                b = substr[1]\n                if b != \"{\":\n                    if len(substr) > 2:\n                        post_substr = substr[2:]\n                        new_str += \"{\" + a + \"}{\" + b + \"}\" + post_substr\n                    else:\n                        new_str += \"{\" + a + \"}{\" + b + \"}\"\n                else:\n                    if len(substr) > 2:\n                        post_substr = substr[2:]\n                        new_str += \"{\" + a + \"}\" + b + post_substr\n                    else:\n                        new_str += \"{\" + a + \"}\" + b\n    string = new_str\n    return string\n\n\ndef fix_a_slash_b(string):\n    if len(string.split(\"/\")) != 2:\n        return string\n    a = string.split(\"/\")[0]\n    b = string.split(\"/\")[1]\n    try:\n        a = int(a)\n        b = int(b)\n        assert string == \"{}/{}\".format(a, b)\n        new_string = \"\\\\frac{\" + str(a) + \"}{\" + str(b) + \"}\"\n        return new_string\n    except AssertionError:\n        return string\n\n\ndef remove_right_units(string):\n    # \"\\\\text{ \" only ever occurs (at least in the val set) when describing units\n    if \"\\\\text{ \" in string:\n        splits = string.split(\"\\\\text{ \")\n        assert len(splits) == 2\n        return splits[0]\n    else:\n        return string\n\n\ndef fix_sqrt(string):\n    if \"\\\\sqrt\" not in string:\n        return string\n    splits = string.split(\"\\\\sqrt\")\n    new_string = splits[0]\n    for split in splits[1:]:\n        if split[0] != \"{\":\n            a = split[0]\n            new_substr = \"\\\\sqrt{\" + a + \"}\" + split[1:]\n        else:\n            new_substr = \"\\\\sqrt\" + split\n        new_string += new_substr\n    return new_string\n\n\ndef strip_string(string):\n    # linebreaks\n    string = string.replace(\"\\n\", \"\")\n\n    # remove inverse spaces\n    string = string.replace(\"\\\\!\", \"\")\n\n    # replace \\\\ with \\\n    string = string.replace(\"\\\\\\\\\", \"\\\\\")\n\n    # replace tfrac and dfrac with frac\n    string = string.replace(\"tfrac\", \"frac\")\n    string = string.replace(\"dfrac\", \"frac\")\n\n    # remove \\left and \\right\n    string = string.replace(\"\\\\left\", \"\")\n    string = string.replace(\"\\\\right\", \"\")\n\n    # Remove circ (degrees)\n    string = string.replace(\"^{\\\\circ}\", \"\")\n    string = string.replace(\"^\\\\circ\", \"\")\n\n    # remove dollar signs\n    string = string.replace(\"\\\\$\", \"\")\n\n    # remove units (on the right)\n    string = remove_right_units(string)\n\n    # remove percentage\n    string = string.replace(\"\\\\%\", \"\")\n    string = string.replace(\"\\%\", \"\")  # noqa: W605\n\n    # \" 0.\" equivalent to \" .\" and \"{0.\" equivalent to \"{.\" Alternatively, add \"0\" if \".\" is the start of the string\n    string = string.replace(\" .\", \" 0.\")\n    string = string.replace(\"{.\", \"{0.\")\n    # if empty, return empty string\n    if len(string) == 0:\n        return string\n    if string[0] == \".\":\n        string = \"0\" + string\n\n    # to consider: get rid of e.g. \"k = \" or \"q = \" at beginning\n    if len(string.split(\"=\")) == 2:\n        if len(string.split(\"=\")[0]) <= 2:\n            string = string.split(\"=\")[1]\n\n    # fix sqrt3 --> sqrt{3}\n    string = fix_sqrt(string)\n\n    # remove spaces\n    string = string.replace(\" \", \"\")\n\n    # \\frac1b or \\frac12 --> \\frac{1}{b} and \\frac{1}{2}, etc. Even works with \\frac1{72} (but not \\frac{72}1). Also does a/b --> \\\\frac{a}{b}\n    string = fix_fracs(string)\n\n    # manually change 0.5 --> \\frac{1}{2}\n    if string == \"0.5\":\n        string = \"\\\\frac{1}{2}\"\n\n    # NOTE: X/Y changed to \\frac{X}{Y} in dataset, but in simple cases fix in case the model output is X/Y\n    string = fix_a_slash_b(string)\n\n    return string\n\n\nif __name__ == \"__main__\":\n    response=\"To determine which digit appears in the 534th place after the decimal point in the decimal representation of $\\\\frac{5}{13}$, we need to first find the repeating decimal sequence of $\\\\frac{5}{13}$. \\n\\nLet's start by calculating the decimal representation of $\\\\frac{5}{13}$.\\n```python\\nfrom decimal import Decimal, getcontext\\r\\n\\r\\n# Set the precision high enough to see the repeating pattern clearly\\r\\ngetcontext().prec = 1000\\r\\n\\r\\n# Calculate the decimal representation of 5/13\\r\\ndecimal_rep = Decimal(5) / Decimal(13)\\r\\nprint(str(decimal_rep))\\n```\\n```output\\n0.3846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846153846\\n```\\nThe decimal representation of $\\\\frac{5}{13}$ is $0.\\\\overline{384615}$. This means the repeating sequence is \\\"384615\\\" and it has a length of 6 digits.\\n\\nTo find the digit in the 534th place after the decimal point, we need to determine the position within the repeating sequence. Since the sequence repeats every 6 digits, we can find the position by calculating the remainder when 534 is divided by 6.\\n\\nLet's calculate this.\\n```python\\n# Length of the repeating sequence\\r\\nrepeating_sequence = \\\"384615\\\"\\r\\nsequence_length = len(repeating_sequence)\\r\\n\\r\\n# Find the position within the repeating sequence\\r\\nposition = (534 - 1) % sequence_length  # -1 because indexing starts from 0\\r\\n\\r\\n# Get the digit at that position\\r\\ndigit_in_534th_place = repeating_sequence[position]\\r\\nprint(digit_in_534th_place)\\n```\\n```output\\n6\\n```\\nThe digit in the 534th place after the decimal point in the decimal representation of $\\\\frac{5}{13}$ is $\\\\boxed{6}$. <|endoftext|>\"\n    answer=\"6\"\n    res=compute_score(response, answer)\n    print(res)"
  },
  {
    "path": "verl/utils/reward_score/prime_code/__init__.py",
    "content": "# Copyright 2024 PRIME team and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .utils import check_correctness as apps_check_correctness\nimport json\nimport re\nimport traceback\n\n\ndef compute_score(completion, test_cases, continuous=False):\n    # try to get code solution from completion. if the completion is pure code, this will not take effect.\n    solution = completion.split('```python')[-1].split('```')[0]\n    try:\n        try:\n            if not isinstance(test_cases, dict):\n                test_cases = json.loads(test_cases)\n        except Exception as e:\n            print(f\"Error:{e}\")\n\n        # Complete check on all in-out pairs first. If there is no failure, per-sample test can be skipped.\n        try:\n            res, metadata = apps_check_correctness(in_outs=test_cases, generation=solution, timeout=5, debug=False)\n            metadata = dict(enumerate(metadata))[0]\n            success = all(map(lambda x: x == True, res))\n            if success:\n                return success, metadata\n        except Exception as e:\n            pass\n\n        test_cases_list = []\n        inputs = test_cases[\"inputs\"]\n        outputs = test_cases[\"outputs\"]\n        for i in range(len(inputs)):\n            test_cases_list.append({\"inputs\": [inputs[i]], \"outputs\": [outputs[i]]})\n\n        if continuous:\n            # per sample test: if continuous score is needed, test first 10 samples regardless of failures\n            # do not test all samples cuz some problems have enormous test cases\n            metadata_list = []\n            res_list = []\n            for test_case_id, test_case in enumerate(test_cases_list):\n                res, metadata = apps_check_correctness(in_outs=test_case, generation=solution, timeout=5, debug=False)\n                try:\n                    metadata = dict(enumerate(metadata))[0]  # metadata can be empty occasionally\n                except Exception as e:\n                    metadata = {}\n                metadata[\"test_case\"] = {}\n                metadata[\"test_case\"][\"input\"] = str(test_case[\"inputs\"][0])\n                metadata[\"test_case\"][\"output\"] = str(test_case[\"outputs\"][0])\n                metadata[\"test_case\"][\"res\"] = str(res)\n                metadata_list.append(metadata)\n                res_list.extend(res)\n\n                if test_case_id >= 9:\n                    break\n            res_count = len(res_list) if len(res_list) > 0 else 1\n            success = sum(map(lambda x: x == True, res_list)) / res_count\n    except Exception as e:\n        traceback.print_exc(10)\n        success = False\n        metadata_list = None\n    return success, metadata_list\n"
  },
  {
    "path": "verl/utils/reward_score/prime_code/testing_util.py",
    "content": "# Copyright 2024 PRIME team and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nimport json\nimport sys\nimport faulthandler\nimport platform\n\n# used for debugging to time steps\nfrom datetime import datetime\n\n# to run the solution files we're using a timing based approach\nimport signal\n\nimport numpy as np\n\n# for capturing the stdout\nfrom io import StringIO\n\n# used for testing the code that reads from input\nfrom unittest.mock import patch, mock_open\n\nfrom pyext import RuntimeModule\n\nfrom enum import Enum\n\nimport traceback\n\n\ndef truncatefn(s, length=300):\n    assert isinstance(s, str)\n    if len(s) <= length:\n        return s\n\n    return s[:length // 2] + \"...(truncated) ...\" + s[-length // 2:]\n\n\nclass CODE_TYPE(Enum):\n    call_based = 0\n    standard_input = 1\n\n\n# stuff for setting up signal timer\nclass TimeoutException(Exception):\n    pass\n\n\ndef timeout_handler(signum, frame):\n    print(\"alarm went off\")\n    return\n    # raise TimeoutException # this is an unhandled exception. just return None is OK\n\n\nsignal.signal(signal.SIGALRM, timeout_handler)\n\n# timeout = 6  # seconds\n\n\n# used to capture stdout as a list\n# from https://stackoverflow.com/a/16571630/6416660\n# alternative use redirect_stdout() from contextlib\nclass Capturing(list):\n\n    def __enter__(self):\n        self._stdout = sys.stdout\n        sys.stdout = self._stringio = StringIO()\n        # Make closing the StringIO a no-op\n        self._stringio.close = lambda x: 1\n        return self\n\n    def __exit__(self, *args):\n        self.append(self._stringio.getvalue())\n        del self._stringio  # free up some memory\n        sys.stdout = self._stdout\n\n\ndef only_int_check(val):\n    return isinstance(val, int)\n\n\ndef string_int_check(val):\n    return isinstance(val, str) and val.isdigit()\n\n\ndef combined_int_check(val):\n    return only_int_check(val) or string_int_check(val)\n\n\ndef clean_traceback(error_traceback):\n    file_start = error_traceback.find('File \\\"<string>\\\"')\n    # print(file_start)\n    error_traceback = \"Traceback (most recent call last):\\n  \" + error_traceback[file_start:]\n    return error_traceback\n\n\ndef run_test(in_outs, test=None, debug=False, timeout=15):\n    \"\"\"\n    if test(generated_code) is not None it'll try to run the code.\n    otherwise it'll just return an input and output pair.\n    \"\"\"\n    # Disable functionalities that can make destructive changes to the test.\n    reliability_guard()\n\n    if debug:\n        print(f\"start = {datetime.now().time()}\")\n\n    if in_outs:\n        if in_outs.get(\"fn_name\") is None:\n            which_type = CODE_TYPE.standard_input  # Standard input\n            method_name = None\n        else:\n            which_type = CODE_TYPE.call_based  # Call-based\n            method_name = in_outs[\"fn_name\"]\n\n    if debug:\n        print(f\"loaded input_output = {datetime.now().time()}\")\n\n    if test is None:\n        assert False, \"should not happen: test code is none\"\n        return in_outs, {\"error\": \"no test code provided\"}\n    elif test is not None:\n        results = []\n        sol = \"from string import *\\nfrom re import *\\nfrom datetime import *\\nfrom collections import *\\nfrom heapq import *\\nfrom bisect import *\\nfrom copy import *\\nfrom math import *\\nfrom random import *\\nfrom statistics import *\\nfrom itertools import *\\nfrom functools import *\\nfrom operator import *\\nfrom io import *\\nfrom sys import *\\nfrom json import *\\nfrom builtins import *\\nfrom typing import *\\nimport string\\nimport re\\nimport datetime\\nimport collections\\nimport heapq\\nimport bisect\\nimport copy\\nimport math\\nimport random\\nimport statistics\\nimport itertools\\nimport functools\\nimport operator\\nimport io\\nimport sys\\nimport json\\nsys.setrecursionlimit(6*10**5)\\n\"\n        if debug:\n            print(f\"loading test code = {datetime.now().time()}\")\n\n        if which_type == CODE_TYPE.call_based:\n\n            sol += test\n            if debug:\n                print(f\"sol = {sol}\")\n            signal.alarm(timeout)\n            try:\n                tmp_sol = RuntimeModule.from_string(\"tmp_sol\", \"\", sol)\n                if \"class Solution\" not in test:\n                    tmp = tmp_sol\n                else:\n                    tmp = tmp_sol.Solution()\n                signal.alarm(0)\n            except Exception as e:\n                signal.alarm(0)\n                error_traceback = traceback.format_exc()\n                if debug:\n                    print(f\"type 0 compilation error = {e}\")\n                results.append(-2)\n                return results, {\n                    \"error\": repr(e),\n                    # \"error_code\": -1,\n                    # \"error_message\": \"Compilation Error\",\n                    \"traceback\": clean_traceback(error_traceback),\n                }\n            signal.alarm(0)\n\n        elif which_type == CODE_TYPE.standard_input:\n            # sol\n            # if code has if __name__ == \"__main__\": then remove it\n            try:\n                astree = ast.parse(test)\n                last_block = astree.body[-1]\n                if isinstance(last_block, ast.If):\n                    condition = last_block.test\n                    if ast.unparse(condition).strip() == \"__name__ == '__main__'\":\n                        test = (ast.unparse(astree.body[:-1]) + \"\\n\" + ast.unparse(last_block.body))\n            except:\n                pass\n\n            tmp_test = test.split(\"\\n\")\n\n            new_test = []\n            for x in tmp_test:\n                if (not x.startswith(\"from \")) and (not x.startswith(\"import \")):\n                    new_test.append(\"\\t\" + x + \"\\n\")\n                else:\n                    new_test.append(x + \"\\n\")\n            tmp_test = new_test\n\n            new_test = \"\"\n            started = False\n            for i in tmp_test:\n                if i.startswith(\"\\t\") and not started:\n                    new_test += \"stdin = sys.stdin\\nstdout = sys.stdout\\n\"\n                    new_test += \"def code():\\n\"\n                    new_test += i\n                    started = True\n                elif started and ((i.startswith(\"from \")) or (i.startswith(\"import \"))):\n                    new_test += \"\\t\" + i\n                else:\n                    new_test += i\n            tmp_test = new_test\n\n            sol += tmp_test\n            if debug:\n                print(f\"sol = {sol}\")\n            method_name = \"code\"\n            signal.alarm(timeout)\n            try:\n                tmp_sol = RuntimeModule.from_string(\"tmp_sol\", \"\", sol)\n                tmp = tmp_sol\n                signal.alarm(0)\n            except Exception as e:\n                signal.alarm(0)\n                error_traceback = traceback.format_exc()\n                if debug:\n                    print(f\"type 1 compilation error = {e}\")\n                results.append(-2)\n                return results, {\n                    \"error\": repr(e),\n                    # \"error_code\": -1,\n                    # \"error_message\": \"Compilation Error\",\n                    \"traceback\": clean_traceback(error_traceback),\n                }\n            signal.alarm(0)\n        if debug:\n            print(f\"get method = {datetime.now().time()}\")\n\n        try:\n            method = getattr(tmp, method_name)  # get_attr second arg must be str\n        except:\n            signal.alarm(0)\n            error_traceback = traceback.format_exc()\n            e = sys.exc_info()\n            print(f\"unable to get function error = {e}\")\n            results.append(-2)\n            return results, {\n                \"error\": repr(e),\n                # \"error_code\": -1,\n                # \"error_message\": \"Unable to extract code\",\n                \"traceback\": clean_traceback(error_traceback),\n            }\n\n        for index, inputs in enumerate(in_outs[\"inputs\"]):\n            raw_inputs = inputs\n            raw_outputs = in_outs[\"outputs\"][index]\n            if which_type == CODE_TYPE.call_based:\n                inputs = [json.loads(line) for line in inputs.split(\"\\n\")]\n                in_outs[\"outputs\"][index] = json.loads(in_outs[\"outputs\"][index])\n\n                truncate_line_size = 300 // (raw_inputs.count(\"\\n\") + 1)\n                raw_inputs = \"\\n\".join(\n                    [truncatefn(line, truncate_line_size) for line in raw_inputs.strip().split(\"\\n\")])\n                raw_outputs = truncatefn(raw_outputs, 200)\n            else:\n                raw_inputs = truncatefn(raw_inputs)\n                raw_outputs = truncatefn(raw_outputs, 200)\n            # JSON forces dictionaries to have string keys; this undoes this (assuming a singleton list)\n            try:\n                if isinstance(inputs[0], dict):\n                    inputs = [{int(k): v for k, v in inputs[0].items()}]\n            except:\n                True\n            try:\n                if isinstance(in_outs[\"outputs\"][index], dict):\n                    in_outs[\"outputs\"][index] = [{int(k): v for k, v in in_outs[\"outputs\"][index].items()}]\n            except:\n                True\n            try:\n                if isinstance(in_outs[\"outputs\"][index][0], dict):\n                    in_outs[\"outputs\"][index] = [{int(k): v for k, v in in_outs[\"outputs\"][index][0].items()}]\n            except:\n                True\n\n            if debug:\n                print(\n                    f\"time: {datetime.now().time()} testing index = {index}  inputs = {inputs}, {type(inputs)}. type = {which_type}\"\n                )\n            if which_type == CODE_TYPE.call_based:  # Call-based\n                signal.alarm(timeout)\n                faulthandler.enable()\n                try:\n                    output = method(*inputs)\n                    raw_true_output = output\n\n                    raw_true_output_copy = json.dumps(output)\n                    raw_true_output_copy = truncatefn(raw_true_output_copy, 200)\n\n                    # ground truth sequences are not tuples\n                    if isinstance(output, tuple):\n                        output = list(output)\n\n                    tmp_result = output == in_outs[\"outputs\"][index]\n                    if (isinstance(in_outs[\"outputs\"][index], list) and in_outs[\"outputs\"][index]):\n                        tmp_result = tmp_result or (output == in_outs[\"outputs\"][index][0])\n\n                    # ground truth sequences are not tuples\n                    try:\n                        if isinstance(output[0], tuple):\n                            tmp_result = tmp_result or ([list(x) for x in output] == in_outs[\"outputs\"][index][0])\n                    except:\n                        True\n                    results.append(tmp_result)\n                    if tmp_result != True:\n                        return results, {\n                            \"output\": raw_true_output_copy,\n                            \"expected\": raw_outputs,\n                            \"inputs\": raw_inputs,\n                            # \"error_code\": -2,\n                            \"error_message\": \"Wrong Answer\",\n                        }\n                    # reset the alarm\n                    signal.alarm(0)\n                except Exception as e:\n                    signal.alarm(0)\n                    error_traceback = traceback.format_exc()\n                    faulthandler.disable()\n                    if debug:\n                        print(f\"Standard input runtime error or time limit exceeded error = {e}\")\n                    results.append(-1)\n                    if \"timeoutexception\" in repr(e).lower():\n                        return results, {\n                            \"error\": repr(e),\n                            # \"error_code\": -3,\n                            # \"error_message\": \"Time Limit Exceeded\",\n                            # \"inputs\": raw_inputs,\n                            # \"expected\": raw_outputs,\n                            \"traceback\": clean_traceback(error_traceback),\n                        }\n                    else:\n                        return results, {\n                            \"error\": repr(e),\n                            # \"error_code\": -4,\n                            # \"error_message\": \"Runtime Error\",\n                            # \"inputs\": raw_inputs,\n                            # \"expected\": raw_outputs,\n                            \"traceback\": clean_traceback(error_traceback),\n                        }\n                faulthandler.disable()\n                signal.alarm(0)\n                if debug:\n                    print(\n                        f\"outputs = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs}, {type(inputs)}, {output == [in_outs['outputs'][index]]}\"\n                    )\n            elif which_type == CODE_TYPE.standard_input:  # Standard input\n                faulthandler.enable()\n                passed = False\n\n                if isinstance(inputs, list):\n                    inputs = \"\\n\".join(inputs)\n                if isinstance(in_outs[\"outputs\"][index], list):\n                    in_outs[\"outputs\"][index] = \"\\n\".join(in_outs[\"outputs\"][index])\n\n                signal.alarm(timeout)\n                with Capturing() as output:\n                    try:\n                        call_method(method, inputs)\n                        # reset the alarm\n                        signal.alarm(0)\n                        passed = True\n                    except Exception as e:\n                        # runtime error or took too long\n                        signal.alarm(0)\n                        error_traceback = traceback.format_exc()\n                        print(f\"Call-based runtime error or time limit exceeded error = {repr(e)}{e}\")\n                        results.append(-1)\n                        if \"timeoutexception\" in repr(e).lower():\n                            return results, {\n                                \"error\": repr(e),\n                                # \"error_code\": -3,\n                                # \"error_message\": \"Time Limit Exceeded\",\n                                # \"inputs\": raw_inputs,\n                                # \"expected\": raw_outputs,\n                                \"traceback\": clean_traceback(error_traceback),\n                            }\n                        else:\n                            return results, {\n                                \"error\": repr(e),\n                                # \"error_code\": -4,\n                                # \"error_message\": \"Runtime Error\",\n                                # \"inputs\": raw_inputs,\n                                # \"expected\": raw_outputs,\n                                \"traceback\": clean_traceback(error_traceback),\n                            }\n                    signal.alarm(0)\n                raw_true_output = output[0]\n                raw_true_output_copy = truncatefn(raw_true_output, 200)\n                output = raw_true_output.splitlines()\n                if not passed:\n                    if debug:\n                        nl = \"\\n\"\n                        if not isinstance(inputs, list):\n                            print(\n                                f\"not passed output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs.replace(nl,' new-line ')}, {type(inputs)}, {output == [in_outs['outputs'][index]]}\"\n                            )\n                        else:\n                            print(\n                                f\"not passed output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs}, {type(inputs)}, {output == [in_outs['outputs'][index]]}\"\n                            )\n                    continue\n\n                if passed and debug:\n                    print(f\"==> output = {output}, test outputs = {in_outs['outputs'][index]}\")\n\n                if custom_compare_(output, in_outs[\"outputs\"][index]):\n                    tmp_result = True\n                    results.append(tmp_result)\n                    continue\n\n                # ground truth sequences are expressed as lists not tuples\n                if isinstance(output, tuple):\n                    output = list(output)\n\n                tmp_result = False\n                try:\n                    tmp_result = output == [in_outs[\"outputs\"][index]]\n                    if isinstance(in_outs[\"outputs\"][index], list):\n                        tmp_result = tmp_result or (output == in_outs[\"outputs\"][index])\n                        if isinstance(output[0], str):\n                            tmp_result = tmp_result or ([e.strip() for e in output] == in_outs[\"outputs\"][index])\n                except Exception as e:\n                    if debug:\n                        print(f\"Failed check1 exception = {e}\")\n                    pass\n\n                if tmp_result == True:\n                    results.append(tmp_result)\n                    continue\n\n                # try one more time without \\n\n                if isinstance(in_outs[\"outputs\"][index], list):\n                    for tmp_index, i in enumerate(in_outs[\"outputs\"][index]):\n                        in_outs[\"outputs\"][index][tmp_index] = i.split(\"\\n\")\n                        in_outs[\"outputs\"][index][tmp_index] = [\n                            x.strip() for x in in_outs[\"outputs\"][index][tmp_index] if x\n                        ]\n                else:\n                    in_outs[\"outputs\"][index] = in_outs[\"outputs\"][index].split(\"\\n\")\n                    in_outs[\"outputs\"][index] = list(filter(len, in_outs[\"outputs\"][index]))\n                    in_outs[\"outputs\"][index] = list(map(lambda x: x.strip(), in_outs[\"outputs\"][index]))\n\n                try:\n                    tmp_result = output == [in_outs[\"outputs\"][index]]\n                    if isinstance(in_outs[\"outputs\"][index], list):\n                        tmp_result = tmp_result or (output == in_outs[\"outputs\"][index])\n                except Exception as e:\n                    if debug:\n                        print(f\"Failed check2 exception = {e}\")\n                    pass\n\n                if tmp_result == True:\n                    results.append(tmp_result)\n                    continue\n\n                # try by converting the output into a split up list too\n                if isinstance(output, list):\n                    output = list(filter(len, output))\n\n                if debug:\n                    nl = \"\\n\"\n                    if not isinstance(inputs, list):\n                        print(\n                            f\"@1 output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs.replace(nl,' new-line ')}, {type(inputs)}, {output == [in_outs['outputs'][index]]} {tmp_result=}\"\n                        )\n                    else:\n                        print(\n                            f\"@1 output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs}, {type(inputs)}, {output == [in_outs['outputs'][index]]} {tmp_result=}\"\n                        )\n\n                if tmp_result == True:\n                    results.append(tmp_result)\n                    continue\n\n                if debug:\n                    print(f\"{tmp_result=} @a\")\n\n                try:\n                    tmp_result = output == [in_outs[\"outputs\"][index]]\n                    if isinstance(in_outs[\"outputs\"][index], list):\n                        tmp_result = tmp_result or (output == in_outs[\"outputs\"][index])\n                except Exception as e:\n                    if debug:\n                        print(f\"Failed check3 exception = {e}\")\n                    pass\n\n                if debug:\n                    print(f\"{tmp_result=} @b\")\n\n                try:\n                    all_ints = all(\n                        combined_int_check(e1) and combined_int_check(e2)\n                        for e1, e2 in zip(output, in_outs[\"outputs\"][index]))\n                    if not all_ints:\n                        if debug:\n                            print([\n                                combined_int_check(e1) and combined_int_check(e2)\n                                for e1, e2 in zip(output, in_outs[\"outputs\"][index])\n                            ])\n                        output_float = [float(e) for e in output]\n                        gt_float = [float(e) for e in in_outs[\"outputs\"][index]]\n                        tmp_result = tmp_result or ((len(output_float) == len(gt_float)) and\n                                                    np.allclose(output_float, gt_float))\n                except Exception as e:\n                    pass\n\n                if debug:\n                    print(f\"{tmp_result=} @c\")\n\n                try:\n                    if isinstance(output[0], list):\n                        all_ints = all(\n                            combined_int_check(e1) and combined_int_check(e2)\n                            for e1, e2 in zip(output[0], in_outs[\"outputs\"][index]))\n                        if not all_ints:\n                            output_float = [float(e) for e in output[0]]\n                            gt_float = [float(e) for e in in_outs[\"outputs\"][index][0]]\n                            tmp_result = tmp_result or ((len(output_float) == len(gt_float)) and\n                                                        np.allclose(output_float, gt_float))\n                except Exception as e:\n                    pass\n\n                if tmp_result == True:\n                    results.append(tmp_result)\n                    continue\n\n                if debug:\n                    print(f\"{tmp_result=} @d\")\n                # try by converting the stuff into split up list\n                if isinstance(in_outs[\"outputs\"][index], list):\n                    for tmp_index, i in enumerate(in_outs[\"outputs\"][index]):\n                        in_outs[\"outputs\"][index][tmp_index] = set(i.split())\n                else:\n                    in_outs[\"outputs\"][index] = set(in_outs[\"outputs\"][index].split())\n\n                if debug:\n                    print(f\"{tmp_result=} @e\")\n\n                try:\n                    tmp_result = output == in_outs[\"outputs\"][index]\n                except Exception as e:\n                    if debug:\n                        print(f\"Failed check4 exception = {e}\")\n                    continue\n\n                if tmp_result == True:\n                    results.append(tmp_result)\n                    continue\n\n                if debug:\n                    print(f\"{tmp_result=} @f\")\n\n                # try by converting the output into a split up list too\n                if isinstance(output, list):\n                    for tmp_index, i in enumerate(output):\n                        output[tmp_index] = i.split()\n                    output = list(filter(len, output))\n                    for tmp_index, i in enumerate(output):\n                        output[tmp_index] = set(i)\n                else:\n                    output = output.split()\n                    output = list(filter(len, output))\n                    output = set(output)\n\n                if debug:\n                    print(f\"{tmp_result=} @g\")\n\n                if tmp_result == True and debug:\n                    print(\"PASSED\")\n\n                results.append(tmp_result)\n                if tmp_result != True:\n                    return results, {\n                        \"output\": raw_true_output_copy,\n                        \"expected\": raw_outputs,\n                        \"inputs\": raw_inputs,\n                        # \"error_code\": -2,\n                        \"error_message\": \"Wrong Answer\",\n                    }\n\n                if debug:\n                    nl = \"\\n\"\n                    if not isinstance(inputs, list):\n                        print(\n                            f\"@2 output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs.replace(nl,' new-line ')}, {type(inputs)}, {output == [in_outs['outputs'][index]]}\"\n                        )\n                    else:\n                        print(\n                            f\"@2 output = {output}, test outputs = {in_outs['outputs'][index]}, inputs = {inputs}, {type(inputs)}, {output == [in_outs['outputs'][index]]}\"\n                        )\n\n                    print(f\"results = {results}\")\n\n    return results, {}\n\n\ndef custom_compare_(output, ground_truth):\n\n    if isinstance(output, list):\n        output_1 = \"\\n\".join(output)\n        if stripped_string_compare(output_1, ground_truth):\n            return True\n\n    if isinstance(output, list):\n        output_2 = [o.lstrip().rstrip() for o in output]\n        output_2 = \"\\n\".join(output_2)\n        if stripped_string_compare(output_2, ground_truth):\n            return True\n\n    return False\n\n\ndef stripped_string_compare(s1, s2):\n    s1 = s1.lstrip().rstrip()\n    s2 = s2.lstrip().rstrip()\n    return s1 == s2\n\n\ndef call_method(method, inputs):\n\n    if isinstance(inputs, list):\n        inputs = \"\\n\".join(inputs)\n\n    inputs_line_iterator = iter(inputs.split(\"\\n\"))\n\n    # sys.setrecursionlimit(10000)\n\n    # @patch('builtins.input', side_effect=inputs.split(\"\\n\"))\n    @patch(\"builtins.open\", mock_open(read_data=inputs))\n    @patch(\"sys.stdin\", StringIO(inputs))\n    @patch(\"sys.stdin.readline\", lambda *args: next(inputs_line_iterator))\n    @patch(\"sys.stdin.readlines\", lambda *args: inputs.split(\"\\n\"))\n    @patch(\"sys.stdin.read\", lambda *args: inputs)\n    # @patch('sys.stdout.write', print)\n    def _inner_call_method(_method):\n        try:\n            return _method()\n        except SystemExit as e:\n            pass\n        finally:\n            pass\n\n    return _inner_call_method(method)\n\n\ndef reliability_guard(maximum_memory_bytes=None):\n    \"\"\"\n    This disables various destructive functions and prevents the generated code\n    from interfering with the test (e.g. fork bomb, killing other processes,\n    removing filesystem files, etc.)\n    WARNING\n    This function is NOT a security sandbox. Untrusted code, including, model-\n    generated code, should not be blindly executed outside of one. See the\n    Codex paper for more information about OpenAI's code sandbox, and proceed\n    with caution.\n    \"\"\"\n\n    if maximum_memory_bytes is not None:\n        import resource\n\n        resource.setrlimit(resource.RLIMIT_AS, (maximum_memory_bytes, maximum_memory_bytes))\n        resource.setrlimit(resource.RLIMIT_DATA, (maximum_memory_bytes, maximum_memory_bytes))\n        if not platform.uname().system == \"Darwin\":\n            resource.setrlimit(resource.RLIMIT_STACK, (maximum_memory_bytes, maximum_memory_bytes))\n\n    faulthandler.disable()\n\n    import builtins\n\n    builtins.exit = None\n    builtins.quit = None\n\n    import os\n\n    os.environ[\"OMP_NUM_THREADS\"] = \"1\"\n\n    os.kill = None\n    os.system = None  # 防止干扰repl评测\n    os.putenv = None\n    os.remove = None\n    os.removedirs = None\n    os.rmdir = None\n    os.fchdir = None\n    os.setuid = None\n    os.fork = None\n    os.forkpty = None\n    os.killpg = None\n    os.rename = None\n    os.renames = None\n    os.truncate = None\n    os.replace = None\n    os.unlink = None\n    os.fchmod = None\n    os.fchown = None\n    os.chmod = None\n    os.chown = None\n    os.chroot = None\n    os.fchdir = None\n    os.lchflags = None\n    os.lchmod = None\n    os.lchown = None\n    os.getcwd = None\n    os.chdir = None\n\n    import shutil\n\n    shutil.rmtree = None\n    shutil.move = None\n    shutil.chown = None\n\n    import subprocess\n\n    subprocess.Popen = None  # type: ignore\n\n    __builtins__[\"help\"] = None\n\n    import sys\n\n    sys.modules[\"ipdb\"] = None\n    sys.modules[\"joblib\"] = None\n    sys.modules[\"resource\"] = None\n    sys.modules[\"psutil\"] = None\n    sys.modules[\"tkinter\"] = None\n"
  },
  {
    "path": "verl/utils/reward_score/prime_code/utils.py",
    "content": "# Copyright 2024 PRIME team and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Borrowed from: https://huggingface.co/spaces/codeparrot/apps_metric/blob/main/utils.py\n\nimport multiprocessing\nfrom typing import Dict, Optional\nfrom datasets import load_dataset\nfrom .testing_util import run_test\nimport traceback\nimport os, sys\n\n\ndef _temp_run(sample, generation, debug, result, metadata_list, timeout):\n    with open(os.devnull, 'w') as devnull:\n        sys.stdout = devnull\n        sys.stderr = devnull\n        try:\n            res, metadata = run_test(in_outs=sample, test=generation, debug=debug, timeout=timeout)\n            result.append(res)\n            metadata_list.append(metadata)\n        except Exception as e:\n            # print(e) # some tracebacks are extremely long.\n            traceback.print_exc(10)\n            result.append([-1 for i in range(len(sample['inputs']))])\n            metadata_list.append({})\n\n\ndef check_correctness(in_outs: Optional[dict], generation, timeout=10, debug=True):\n    \"\"\"Check correctness of code generation with a global timeout.\n    The global timeout is to catch some extreme/rare cases not handled by the timeouts\n    inside `run_test`\"\"\"\n\n    manager = multiprocessing.Manager()\n    result = manager.list()\n    metadata_list = manager.list()\n    p = multiprocessing.Process(target=_temp_run, args=(in_outs, generation, debug, result, metadata_list, timeout))\n    p.start()\n    p.join(timeout=timeout + 1)\n    if p.is_alive():\n        p.kill()\n        # p.terminate()\n    if not result:\n        # consider that all tests failed\n        result = [[-1 for i in range(len(in_outs[\"inputs\"]))]]\n        if debug:\n            print(f\"global timeout\")\n    return result[0], metadata_list\n"
  },
  {
    "path": "verl/utils/reward_score/prime_math/__init__.py",
    "content": "# Copyright 2024 PRIME team and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nAnswer checker API that uses sympy to simplify expressions and check for equality.\n\nCall grade_answer(given_answer: str, ground_truth: str).\n\nFROM: https://github.com/openai/prm800k/blob/main/prm800k/grading/grader.py\n\"\"\"\nimport re\nimport sympy\nfrom pylatexenc import latex2text\nfrom sympy.parsing import sympy_parser\n\nfrom . import math_normalize\nfrom .grader import math_equal\n\n# import math_normalize\n# from grader import math_equal\n\n# sympy might hang -- we don't care about trying to be lenient in these cases\nBAD_SUBSTRINGS = [\"^{\", \"^(\"]\nBAD_REGEXES = [\"\\^[0-9]+\\^\", \"\\^[0-9][0-9]+\"]\nTUPLE_CHARS = \"()[]\"\n\n\ndef _sympy_parse(expr: str):\n    \"\"\"Parses an expression with sympy.\"\"\"\n    py_expr = expr.replace(\"^\", \"**\")\n    return sympy_parser.parse_expr(\n        py_expr,\n        transformations=(sympy_parser.standard_transformations + (sympy_parser.implicit_multiplication_application,)),\n    )\n\n\ndef _parse_latex(expr: str) -> str:\n    \"\"\"Attempts to parse latex to an expression sympy can read.\"\"\"\n    expr = expr.replace(\"\\\\tfrac\", \"\\\\frac\")\n    expr = expr.replace(\"\\\\dfrac\", \"\\\\frac\")\n    expr = expr.replace(\"\\\\frac\", \" \\\\frac\")  # Play nice with mixed numbers.\n    expr = latex2text.LatexNodes2Text().latex_to_text(expr)\n\n    # Replace the specific characters that this parser uses.\n    expr = expr.replace(\"√\", \"sqrt\")\n    expr = expr.replace(\"π\", \"pi\")\n    expr = expr.replace(\"∞\", \"inf\")\n    expr = expr.replace(\"∪\", \"U\")\n    expr = expr.replace(\"·\", \"*\")\n    expr = expr.replace(\"×\", \"*\")\n\n    return expr.strip()\n\n\ndef _is_float(num: str) -> bool:\n    try:\n        float(num)\n        return True\n    except ValueError:\n        return False\n\n\ndef _is_int(x: float) -> bool:\n    try:\n        return abs(x - int(round(x))) <= 1e-7\n    except:\n        return False\n\n\ndef _is_frac(expr: str) -> bool:\n    return bool(re.search(r\"^-?[0-9]+.?/0*[1-9][0-9]*.?$\", expr))\n\n\ndef _str_is_int(x: str) -> bool:\n    try:\n        x = _strip_properly_formatted_commas(x)\n        x = float(x)\n        return abs(x - int(round(x))) <= 1e-7\n    except:\n        return False\n\n\ndef _str_to_int(x: str) -> bool:\n    x = x.replace(\",\", \"\")\n    x = float(x)\n    return int(x)\n\n\ndef _inject_implicit_mixed_number(step: str):\n    \"\"\"\n    Automatically make a mixed number evalable\n    e.g. 7 3/4 => 7+3/4\n    \"\"\"\n    p1 = re.compile(\"([0-9]) +([0-9])\")\n    step = p1.sub(\"\\\\1+\\\\2\", step)  ## implicit mults\n    return step\n\n\ndef _strip_properly_formatted_commas(expr: str):\n    # We want to be careful because we don't want to strip tuple commas\n    p1 = re.compile(\"(\\d)(,)(\\d\\d\\d)($|\\D)\")\n    while True:\n        next_expr = p1.sub(\"\\\\1\\\\3\\\\4\", expr)\n        if next_expr == expr:\n            break\n        expr = next_expr\n    return next_expr\n\n\ndef _normalize(expr: str) -> str:\n    \"\"\"Normalize answer expressions.\"\"\"\n    if expr is None:\n        return None\n\n    # Remove enclosing `\\text{}`.\n    m = re.search(\"^\\\\\\\\text\\{(?P<text>.+?)\\}$\", expr)\n    if m is not None:\n        expr = m.group(\"text\")\n\n    expr = expr.replace(\"\\\\%\", \"%\")\n    expr = expr.replace(\"\\\\$\", \"$\")\n    expr = expr.replace(\"$\", \"\")\n    expr = expr.replace(\"%\", \"\")\n    expr = expr.replace(\" or \", \" , \")\n    expr = expr.replace(\" and \", \" , \")\n\n    expr = expr.replace(\"million\", \"*10^6\")\n    expr = expr.replace(\"billion\", \"*10^9\")\n    expr = expr.replace(\"trillion\", \"*10^12\")\n\n    for unit in [\n            \"degree\",\n            \"cm\",\n            \"centimeter\",\n            \"meter\",\n            \"mile\",\n            \"second\",\n            \"minute\",\n            \"hour\",\n            \"day\",\n            \"week\",\n            \"month\",\n            \"year\",\n            \"foot\",\n            \"feet\",\n            \"inch\",\n            \"yard\",\n            \"liter\",\n    ]:\n        expr = re.sub(f\"{unit}(es)?(s)? *(\\^[0-9]+)?\", \"\", expr)\n    expr = re.sub(f\"\\^ *\\\\\\\\circ\", \"\", expr)\n\n    if len(expr) > 0 and expr[0] == \"{\" and expr[-1] == \"}\":\n        expr = expr[1:-1]\n\n    expr = re.sub(\",\\\\\\\\! *\", \"\", expr)\n    if _is_float(expr) and _is_int(float(expr)):\n        expr = str(int(round(float(expr))))\n    if \"\\\\\" in expr:\n        try:\n            expr = _parse_latex(expr)\n        except:\n            pass\n\n    # edge case with mixed numbers and negative signs\n    expr = re.sub(\"- *\", \"-\", expr)\n\n    expr = _inject_implicit_mixed_number(expr)\n\n    # don't be case sensitive for text answers\n    expr = expr.lower()\n\n    if _str_is_int(expr):\n        expr = str(_str_to_int(expr))\n\n    return expr\n\n\ndef count_unknown_letters_in_expr(expr: str):\n    expr = expr.replace(\"sqrt\", \"\")\n    expr = expr.replace(\"frac\", \"\")\n    letters_in_expr = set([x for x in expr if x.isalpha()])\n    return len(letters_in_expr)\n\n\ndef should_allow_eval(expr: str):\n    # we don't want to try parsing unknown text or functions of more than two variables\n    if count_unknown_letters_in_expr(expr) > 2:\n        return False\n\n    for bad_string in BAD_SUBSTRINGS:\n        if bad_string in expr:\n            return False\n\n    for bad_regex in BAD_REGEXES:\n        if re.search(bad_regex, expr) is not None:\n            return False\n\n    return True\n\n\ndef are_equal_under_sympy(ground_truth_normalized: str, given_normalized: str):\n    are_equal = False\n    try:\n        expr = f\"({ground_truth_normalized})-({given_normalized})\"\n        if should_allow_eval(expr):\n            sympy_diff = _sympy_parse(expr)\n            simplified = sympy.simplify(sympy_diff)\n            if simplified == 0:\n                are_equal = True\n    except:\n        pass\n    return are_equal\n\n\ndef split_tuple(expr: str):\n    \"\"\"\n    Split the elements in a tuple/interval, while handling well-formatted commas in large numbers\n    \"\"\"\n    expr = _strip_properly_formatted_commas(expr)\n    if len(expr) == 0:\n        return []\n    if (len(expr) > 2 and expr[0] in TUPLE_CHARS and expr[-1] in TUPLE_CHARS and\n            all([ch not in expr[1:-1] for ch in TUPLE_CHARS])):\n        elems = [elem.strip() for elem in expr[1:-1].split(\",\")]\n    else:\n        elems = [expr]\n    return elems\n\n\ndef grade_answer(given_answer: str, ground_truth: str) -> bool:\n    \"\"\"\n    The answer will be considered correct if:\n    (a) it normalizes to the same string as the ground truth answer\n    OR\n    (b) sympy can simplify the difference between the expressions to 0\n    \"\"\"\n    if given_answer is None:\n        return False\n\n    ground_truth_normalized_mathd = math_normalize.normalize_answer(ground_truth)\n    given_answer_normalized_mathd = math_normalize.normalize_answer(given_answer)\n\n    # be at least as lenient as mathd\n    if ground_truth_normalized_mathd == given_answer_normalized_mathd:\n        return True\n\n    ground_truth_normalized = _normalize(ground_truth)\n    given_normalized = _normalize(given_answer)\n\n    if ground_truth_normalized is None:\n        return False\n\n    if ground_truth_normalized == given_normalized:\n        return True\n\n    if len(given_normalized) == 0:\n        return False\n\n    ground_truth_elems = split_tuple(ground_truth_normalized)\n    given_elems = split_tuple(given_normalized)\n\n    if len(ground_truth_elems) > 1 and (ground_truth_normalized[0] != given_normalized[0] or\n                                        ground_truth_normalized[-1] != given_normalized[-1]):\n        is_correct = False\n    elif len(ground_truth_elems) != len(given_elems):\n        is_correct = False\n    else:\n        for ground_truth_elem, given_elem in zip(ground_truth_elems, given_elems):\n            if _is_frac(ground_truth_elem) and _is_frac(given_elem):\n                # if fractions aren't reduced, then shouldn't be marked as correct\n                # so, we don't want to allow sympy.simplify in this case\n                is_correct = ground_truth_elem == given_elem\n            elif _str_is_int(ground_truth_elem) != _str_is_int(given_elem):\n                # if the ground truth answer is an integer, we require the given answer to be a strict match (no sympy.simplify)\n                is_correct = False\n            else:\n                is_correct = are_equal_under_sympy(ground_truth_elem, given_elem)\n            if not is_correct:\n                break\n\n    return is_correct\n\n\ndef remove_boxed(s):\n    left = \"\\\\boxed{\"\n    try:\n        assert s[:len(left)] == left\n        assert s[-1] == \"}\"\n        return s[len(left):-1]\n    except:\n        return None\n\n\ndef _last_boxed_only_string(string):\n    idx = string.rfind(\"\\\\boxed\")\n    if idx < 0:\n        idx = string.rfind(\"\\\\fbox\")\n        if idx < 0:\n            return None\n\n    i = idx\n    left_brace_idx = None\n    right_brace_idx = None\n    num_left_braces_open = 0\n    while i < len(string):\n        if string[i] == \"{\":\n            num_left_braces_open += 1\n            if left_brace_idx is None:\n                left_brace_idx = i\n        elif string[i] == \"}\":\n            num_left_braces_open -= 1\n            if num_left_braces_open == 0:\n                right_brace_idx = i\n                break\n\n        i += 1\n\n    if left_brace_idx is None or right_brace_idx is None:\n        return None\n\n    return string[left_brace_idx + 1:right_brace_idx].strip()\n\n\ndef match_answer(response):\n    is_matched = False\n    for ans_marker in ['answer:', \"answer is\", \"answers are\"]:\n        ans_idx = response.lower().rfind(ans_marker)\n        if ans_idx != -1:\n            is_matched = True\n            response = response[ans_idx + len(ans_marker):].strip()\n            if response.endswith(\"\\n\"):\n                response = response[:-2]\n\n    for ans_marker in [\"is answer\", \"is the answer\", \"are answers\", \"are the answers\"]:\n        ans_idx = response.lower().rfind(ans_marker)\n        if ans_idx != -1:\n            is_matched = True\n            response = response[:ans_idx].strip()\n            if response.endswith(\"\\n\"):\n                response = response[:-2]\n\n    # Find boxed\n    ans_boxed = _last_boxed_only_string(response)\n    if ans_boxed:\n        is_matched = True\n        response = ans_boxed\n\n    if \". \" in response:\n        dot_idx = response.lower().rfind(\". \")\n        if dot_idx != -1:\n            response = response[:dot_idx].strip()\n\n    for ans_marker in ['be ', \"is \", \"are \", \"=\", \": \", \"get \", 'be\\n', \"is\\n\", \"are\\n\", \":\\n\", \"get\\n\"]:\n        ans_idx = response.lower().rfind(ans_marker)\n        if ans_idx != -1:\n            is_matched = True\n            response = response[ans_idx + len(ans_marker):].strip()\n            if response.endswith(\"\\n\"):\n                response = response[:-2]\n\n    is_matched = is_matched if any([c.isdigit() for c in response]) else False  # answer must have a digit\n    # Grade\n    return is_matched, response\n\n\nimport math\n\n\ndef compute_score(model_output: str, ground_truth: str) -> bool:\n    model_output = str(model_output)\n    ground_truth = str(ground_truth)\n\n    is_matched, extracted_model_output = match_answer(model_output)\n    format_correctness = \"Step 2:\" in model_output and \"\\\\box\" in model_output\n\n    # grade simple algebra questions. if succeeded, return; otherwise, proceed to more complex grading\n    if grade_answer(extracted_model_output, ground_truth):\n        return True, True, extracted_model_output\n\n    try:\n        if \"\\pi\" in extracted_model_output or \"\\pi\" in ground_truth:\n            equivs = []\n            for pi in [math.pi, 3.14]:\n                equivs.append(math_equal(extracted_model_output, ground_truth, timeout=True, pi=pi))\n            is_correct = any(equivs)\n        else:\n            is_correct = math_equal(extracted_model_output, ground_truth, timeout=True)\n    except:\n        is_correct = False\n\n    return is_correct, format_correctness, extracted_model_output\n"
  },
  {
    "path": "verl/utils/reward_score/prime_math/grader.py",
    "content": "# Copyright (c) 2024, NVIDIA CORPORATION.  All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Copyright (c) Microsoft Corporation.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE\n\n# Copyright (c) 2023 OpenAI\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Copyright (c) 2021 Dan Hendrycks\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Copyright 2024 PRIME team and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThis logic is largely copied from the Hendrycks' MATH release (math_equivalence), and borrowed from:\n- https://github.com/microsoft/ToRA/blob/main/src/eval/grader.py\n- https://github.com/microsoft/ProphetNet/tree/master/CRITIC\n- https://github.com/openai/prm800k\n\"\"\"\n\nimport contextlib\nimport re\nimport signal\nimport math\nfrom math import isclose\nfrom typing import Union\n\nfrom sympy import N, simplify\nfrom sympy.parsing.latex import parse_latex\nfrom sympy.parsing.sympy_parser import parse_expr\n\n\ndef is_digit(s):\n    try:\n        if \"{,}\" in str(s):\n            num = float(str(s).replace(\"{,}\", \"\"))\n            return True, num\n\n        num = float(str(s).replace(\",\", \"\"))\n        return True, num\n    except ValueError:\n        return False, None\n\n\ndef normalize(answer, pi) -> str:\n    # checking if answer is $<number> and removing $ in that case to compare\n    if isinstance(answer, str) and bool(re.match(r'\\$\\d+(\\.\\d+)?', answer)):\n        return answer[1:]\n\n    # checking if answer is <number>% or <number>\\\\% and removing %\n    if isinstance(answer, str) and (bool(re.match(r'^\\d+(\\.\\d+)?%$', answer)) or\n                                    bool(re.match(r'^\\d+(\\.\\d+)?\\\\%$', answer))):\n        return answer.replace(\"\\\\%\", \"\").replace(\"%\", \"\")\n\n    # handle base\n    answer = handle_base(answer)\n\n    # handle pi\n    answer = handle_pi(answer, pi)\n\n    return answer\n\n\ndef handle_base(x) -> str:\n    if isinstance(x, str) and \"_\" in x:\n        # Due to base\n        x = x.split(\"_\")[0]\n        x = float(x)\n        return int(x)\n    return x\n\n\ndef handle_pi(string, pi):\n    if isinstance(string, str) and \"\\pi\" in string:\n        # Find the first occurrence of \"\\pi\"\n        idx = string.find(\"\\pi\")\n\n        # Iterate over the string and find all occurrences of \"\\pi\" with a valid previous character\n        while idx != -1:\n\n            if idx > 0 and string[idx - 1].isdigit():\n                # Replace \"\\pi\" with \"*math.pi\" if the previous character is a digit\n                string = string[:idx] + f\"*{pi}\" + string[idx + 3:]\n            else:\n                # Replace \"\\pi\" with \"1*math.pi\" if the previous character is not a digit\n                string = string[:idx] + f\"1*{pi}\" + string[idx + 3:]\n\n            # Find the next occurrence of \"\\pi\"\n            idx = string.find(\"\\pi\", idx + 1)\n\n        # Evaluate the expression using eval() function\n        try:\n            string = eval(string)\n        except:\n            pass\n\n    return string\n\n\ndef math_equal(prediction: Union[bool, float, str],\n               reference: Union[float, str],\n               include_percentage: bool = True,\n               tolerance: float = 1e-4,\n               timeout: float = 10.0,\n               pi: float = math.pi) -> bool:\n    \"\"\"\n    Exact match of math if and only if:\n    1. numerical equal: both can convert to float and are equal\n    2. symbolic equal: both can convert to sympy expression and are equal\n    \"\"\"\n\n    prediction = normalize(prediction, pi)\n    reference = normalize(reference, pi)\n\n    if isinstance(prediction, str) and len(prediction) > 1000:  # handling weird corner-cases\n        prediction = prediction[:1000]\n\n    # 0. string comparison\n    if isinstance(prediction, str) and isinstance(reference, str):\n        if prediction.strip().lower() == reference.strip().lower():\n            return True\n        if prediction.replace(\" \", \"\") == reference.replace(\" \", \"\"):\n            return True\n\n    try:  # 1. numerical equal\n        if is_digit(prediction)[0] and is_digit(reference)[0]:\n            prediction = is_digit(prediction)[1]\n            reference = is_digit(reference)[1]\n            # number questions\n            if include_percentage:\n                gt_result = [reference / 100, reference, reference * 100]\n            else:\n                gt_result = [reference]\n            for item in gt_result:\n                try:\n                    if isclose(item, prediction, rel_tol=tolerance):\n                        return True\n                except Exception:\n                    continue\n            return False\n    except Exception:\n        pass\n\n    if not prediction and prediction not in [0, False]:\n        return False\n\n    # 2. symbolic equal\n    reference = str(reference).strip()\n    prediction = str(prediction).strip()\n\n    ## deal with [], (), {}\n    prediction = format_intervals(prediction)\n\n    pred_str, ref_str = prediction, reference\n    if (prediction.startswith(\"[\") and prediction.endswith(\"]\") and\n            not reference.startswith(\"(\")) or (prediction.startswith(\"(\") and prediction.endswith(\")\") and\n                                               not reference.startswith(\"[\")):\n        pred_str = pred_str.strip(\"[]()\")\n        ref_str = ref_str.strip(\"[]()\")\n    for s in [\"{\", \"}\", \"(\", \")\"]:\n        ref_str = ref_str.replace(s, \"\")\n        pred_str = pred_str.replace(s, \"\")\n    if pred_str == ref_str:\n        return True\n\n    ## [a, b] vs. [c, d], return a==c and b==d\n    if (prediction and reference and prediction[0] in \"([\" and prediction[-1] in \")]\" and\n            prediction[0] == reference[0] and prediction[-1] == reference[-1]):\n        pred_parts = prediction[1:-1].split(\",\")\n        ref_parts = reference[1:-1].split(\",\")\n        if len(pred_parts) == len(ref_parts):\n            if all([\n                    math_equal(pred_pt, ref_pt, include_percentage, tolerance)\n                    for pred_pt, ref_pt in zip(pred_parts, ref_parts)\n            ]):\n                return True\n\n    if \",\" in prediction and \",\" in reference:\n        pred_parts = [item.strip() for item in prediction.split(\",\")]\n        ref_parts = [item.strip() for item in reference.split(\",\")]\n\n        if len(pred_parts) == len(ref_parts):\n            if all([\n                    math_equal(pred_parts[i], ref_parts[i], include_percentage, tolerance)\n                    for i in range(len(pred_parts))\n            ]):\n                return True\n            else:\n                return False\n\n    # if we have point == tuple of values\n    if prediction.startswith(\"Point\") and reference[0] == \"(\" and reference[-1] == \")\":\n        pred_parts = prediction[prediction.find(\"(\") + 1:-1].split(\",\")\n        ref_parts = reference[1:-1].split(\",\")\n        if len(pred_parts) == len(ref_parts):\n            if all([\n                    math_equal(pred_pt, ref_pt, include_percentage, tolerance)\n                    for pred_pt, ref_pt in zip(pred_parts, ref_parts)\n            ]):\n                return True\n\n    # if reference is a matrix\n    if \"\\begin{pmatrix}\" in reference and prediction.startswith(\"Matrix\"):\n        try:\n            pred_matrix = parse_expr(prediction)\n            ref_matrix_items = reference.split()[1:-1:2]\n            if len(pred_matrix) == len(ref_matrix_items):\n                if all([\n                        math_equal(pred, ref, include_percentage, tolerance)\n                        for ref, pred in zip(ref_matrix_items, pred_matrix)\n                ]):\n                    return True\n        except Exception:\n            pass\n    elif \"\\begin{pmatrix}\" in reference and prediction.startswith(\"[\") and prediction.endswith(\"]\"):\n        if isinstance(eval(prediction), list):\n            try:\n                pred_matrix = eval(prediction)\n                # ref_matrix_items = reference.split()[1:-1:2]\n                ref_matrix_items = reference.lstrip(\"\\\\begin{pmatrix}\").lstrip(\"\\begin{pmatrix}\").rstrip(\n                    \"\\\\end{pmatrix}\").rstrip(\"\\end{pmatrix}\")\n                ref_matrix_items = ref_matrix_items.split(\"\\\\\")\n                ref_matrix_items = [row.split(\"&\") if \"&\" in row else row for row in ref_matrix_items]\n                if len(pred_matrix) == len(ref_matrix_items):\n                    if all([\n                            math_equal(pred, ref, include_percentage, tolerance)\n                            for ref, pred in zip(ref_matrix_items, pred_matrix)\n                    ]):\n                        return True\n            except Exception:\n                pass\n\n    return symbolic_equal(prediction, reference, tolerance, timeout)\n\n\ndef symbolic_equal(a, b, tolerance, timeout=10.0):\n\n    def _parse(s):\n        for f in [parse_expr, parse_latex]:\n            try:\n                with time_limit(timeout):\n                    return f(s)\n            except Exception:\n                pass\n        return s\n\n    a = _parse(a)\n    b = _parse(b)\n\n    try:\n        with time_limit(timeout):\n            if simplify(a - b) == 0:\n                return True\n    except Exception:\n        pass\n\n    try:\n        with time_limit(timeout):\n            if isclose(N(a), N(b), rel_tol=tolerance):\n                return True\n    except Exception:\n        pass\n    return False\n\n\nclass TimeoutException(Exception):\n    pass\n\n\n@contextlib.contextmanager\ndef time_limit(seconds: float):\n\n    def signal_handler(signum, frame):\n        raise TimeoutException(\"Timed out!\")\n\n    signal.setitimer(signal.ITIMER_REAL, seconds)\n    signal.signal(signal.SIGALRM, signal_handler)\n    try:\n        yield\n    finally:\n        signal.setitimer(signal.ITIMER_REAL, 0)\n\n\ndef format_intervals(prediction):\n    patterns = {\n        \"Interval(\": r\"^Interval\\((.*)\\)$\",\n        \"Interval.Ropen(\": r\"^Interval\\.Ropen\\((.*)\\)$\",\n        \"Interval.Lopen(\": r\"^Interval\\.Lopen\\((.*)\\)$\",\n        \"Interval.open(\": r\"^Interval\\.open\\((.*)\\)$\",\n    }\n\n    for key, pattern in patterns.items():\n        match = re.match(pattern, prediction)\n        if match:\n            inner_content = match.group(1)\n\n            if key == \"Interval(\":  # Intarval(a, b) == [a, b]\n                return f\"[{inner_content}]\"\n            elif key == \"Interval.Ropen(\":  # Intarval.Ropen(a, b) == [a, b)\n                return f\"[{inner_content})\"\n            elif key == \"Interval.Lopen(\":  # Intarval.Lopen(a, b) == (a, b]\n                return f\"({inner_content}]\"\n            elif key == \"Interval.open(\":  # Intarval.open(a, b) == (a, b)\n                return f\"({inner_content})\"\n\n    return prediction\n"
  },
  {
    "path": "verl/utils/reward_score/prime_math/math_normalize.py",
    "content": "# Copyright 2024 PRIME team and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Copyright (c) 2021 Dan Hendrycks\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis logic is largely copied from the Hendrycks' MATH release (math_equivalence).\n\nFrom: https://github.com/openai/prm800k/blob/main/prm800k/grading/math_normalize.py\n\"\"\"\nimport re\nfrom typing import Optional\n\n\ndef normalize_answer(answer: Optional[str]) -> Optional[str]:\n    if answer is None:\n        return None\n    answer = answer.strip()\n    try:\n        # Remove enclosing `\\text{}`.\n        m = re.search(\"^\\\\\\\\text\\{(?P<text>.+?)\\}$\", answer)\n        if m is not None:\n            answer = m.group(\"text\").strip()\n        return _strip_string(answer)\n    except:\n        return answer\n\n\ndef _fix_fracs(string):\n    substrs = string.split(\"\\\\frac\")\n    new_str = substrs[0]\n    if len(substrs) > 1:\n        substrs = substrs[1:]\n        for substr in substrs:\n            new_str += \"\\\\frac\"\n            if substr[0] == \"{\":\n                new_str += substr\n            else:\n                try:\n                    assert len(substr) >= 2\n                except:\n                    return string\n                a = substr[0]\n                b = substr[1]\n                if b != \"{\":\n                    if len(substr) > 2:\n                        post_substr = substr[2:]\n                        new_str += \"{\" + a + \"}{\" + b + \"}\" + post_substr\n                    else:\n                        new_str += \"{\" + a + \"}{\" + b + \"}\"\n                else:\n                    if len(substr) > 2:\n                        post_substr = substr[2:]\n                        new_str += \"{\" + a + \"}\" + b + post_substr\n                    else:\n                        new_str += \"{\" + a + \"}\" + b\n    string = new_str\n    return string\n\n\ndef _fix_a_slash_b(string):\n    if len(string.split(\"/\")) != 2:\n        return string\n    a = string.split(\"/\")[0]\n    b = string.split(\"/\")[1]\n    try:\n        a = int(a)\n        b = int(b)\n        assert string == \"{}/{}\".format(a, b)\n        new_string = \"\\\\frac{\" + str(a) + \"}{\" + str(b) + \"}\"\n        return new_string\n    except:\n        return string\n\n\ndef _remove_right_units(string):\n    # \"\\\\text{ \" only ever occurs (at least in the val set) when describing units\n    if \"\\\\text{ \" in string:\n        splits = string.split(\"\\\\text{ \")\n        assert len(splits) == 2\n        return splits[0]\n    else:\n        return string\n\n\ndef _fix_sqrt(string):\n    if \"\\\\sqrt\" not in string:\n        return string\n    splits = string.split(\"\\\\sqrt\")\n    new_string = splits[0]\n    for split in splits[1:]:\n        if split[0] != \"{\":\n            a = split[0]\n            new_substr = \"\\\\sqrt{\" + a + \"}\" + split[1:]\n        else:\n            new_substr = \"\\\\sqrt\" + split\n        new_string += new_substr\n    return new_string\n\n\ndef _strip_string(string):\n    # linebreaks\n    string = string.replace(\"\\n\", \"\")\n\n    # remove inverse spaces\n    string = string.replace(\"\\\\!\", \"\")\n\n    # replace \\\\ with \\\n    string = string.replace(\"\\\\\\\\\", \"\\\\\")\n\n    # replace tfrac and dfrac with frac\n    string = string.replace(\"tfrac\", \"frac\")\n    string = string.replace(\"dfrac\", \"frac\")\n\n    # remove \\left and \\right\n    string = string.replace(\"\\\\left\", \"\")\n    string = string.replace(\"\\\\right\", \"\")\n\n    # Remove circ (degrees)\n    string = string.replace(\"^{\\\\circ}\", \"\")\n    string = string.replace(\"^\\\\circ\", \"\")\n\n    # remove dollar signs\n    string = string.replace(\"\\\\$\", \"\")\n\n    # remove units (on the right)\n    string = _remove_right_units(string)\n\n    # remove percentage\n    string = string.replace(\"\\\\%\", \"\")\n    string = string.replace(\"\\%\", \"\")\n\n    # \" 0.\" equivalent to \" .\" and \"{0.\" equivalent to \"{.\" Alternatively, add \"0\" if \".\" is the start of the string\n    string = string.replace(\" .\", \" 0.\")\n    string = string.replace(\"{.\", \"{0.\")\n    # if empty, return empty string\n    if len(string) == 0:\n        return string\n    if string[0] == \".\":\n        string = \"0\" + string\n\n    # to consider: get rid of e.g. \"k = \" or \"q = \" at beginning\n    if len(string.split(\"=\")) == 2:\n        if len(string.split(\"=\")[0]) <= 2:\n            string = string.split(\"=\")[1]\n\n    # fix sqrt3 --> sqrt{3}\n    string = _fix_sqrt(string)\n\n    # remove spaces\n    string = string.replace(\" \", \"\")\n\n    # \\frac1b or \\frac12 --> \\frac{1}{b} and \\frac{1}{2}, etc. Even works with \\frac1{72} (but not \\frac{72}1). Also does a/b --> \\\\frac{a}{b}\n    string = _fix_fracs(string)\n\n    # manually change 0.5 --> \\frac{1}{2}\n    if string == \"0.5\":\n        string = \"\\\\frac{1}{2}\"\n\n    # NOTE: X/Y changed to \\frac{X}{Y} in dataset, but in simple cases fix in case the model output is X/Y\n    string = _fix_a_slash_b(string)\n\n    return string"
  },
  {
    "path": "verl/utils/seqlen_balancing.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import List, Tuple, Callable\nimport heapq\n\nimport torch\nfrom torch import distributed as dist\n\nfrom tensordict import TensorDict\nimport copy\n\n\ndef karmarkar_karp(seqlen_list: List[int], k_partitions: int, equal_size: bool):\n    # see: https://en.wikipedia.org/wiki/Largest_differencing_method\n    class Set:\n\n        def __init__(self) -> None:\n            self.sum = 0\n            self.items = []\n\n        def add(self, idx: int, val: int):\n            self.items.append((idx, val))\n            self.sum += val\n\n        def merge(self, other):\n            for idx, val in other.items:\n                self.items.append((idx, val))\n                self.sum += val\n\n        def __lt__(self, other):\n            if self.sum != other.sum:\n                return self.sum < other.sum\n            if len(self.items) != len(other.items):\n                return len(self.items) < len(other.items)\n            return self.items < other.items\n\n    class State:\n\n        def __init__(self, items: List[Tuple[int, int]], k: int) -> None:\n            self.k = k\n            # sets should always be decreasing order\n            self.sets = [Set() for _ in range(k)]\n            assert len(items) in [1, k], f\"{len(items)} not in [1, {k}]\"\n            for i, (idx, seqlen) in enumerate(items):\n                self.sets[i].add(idx=idx, val=seqlen)\n            self.sets = sorted(self.sets, reverse=True)\n\n        def spread(self):\n            return self.sets[0].sum - self.sets[-1].sum\n\n        def get_partitions(self):\n            partitions = []\n            for i in range(len(self.sets)):\n                cur_partition = []\n                for idx, _ in self.sets[i].items:\n                    cur_partition.append(idx)\n                partitions.append(cur_partition)\n            return partitions\n\n        def merge(self, other):\n            for i in range(self.k):\n                self.sets[i].merge(other.sets[self.k - 1 - i])\n            self.sets = sorted(self.sets, reverse=True)\n\n        @property\n        def spread(self) -> int:\n            return self.sets[0].sum - self.sets[-1].sum\n\n        def __lt__(self, other):\n            # least heap, let the state with largest spread to be popped first,\n            # if the spread is the same, let the state who has the largest set\n            # to be popped first.\n            if self.spread != other.spread:\n                return self.spread > other.spread\n            return self.sets[0] > other.sets[0]\n\n        def __repr__(self) -> str:\n            repr_str = \"[\"\n            for i in range(self.k):\n                if i > 0:\n                    repr_str += \",\"\n                repr_str += \"{\"\n                for j, (_, seqlen) in enumerate(self.sets[i].items):\n                    if j > 0:\n                        repr_str += \",\"\n                    repr_str += str(seqlen)\n                repr_str += \"}\"\n            repr_str += \"]\"\n            return repr_str\n\n    sorted_seqlen_list = sorted([(seqlen, i) for i, seqlen in enumerate(seqlen_list)])\n    states_pq = []\n    if equal_size:\n        assert len(seqlen_list) % k_partitions == 0, f\"{len(seqlen_list)} % {k_partitions} != 0\"\n        for offset in range(0, len(sorted_seqlen_list), k_partitions):\n            items = []\n            for i in range(k_partitions):\n                seqlen, idx = sorted_seqlen_list[offset + i]\n                items.append((idx, seqlen))\n            heapq.heappush(states_pq, State(items=items, k=k_partitions))\n    else:\n        for seqlen, idx in sorted_seqlen_list:\n            heapq.heappush(states_pq, State(items=[(idx, seqlen)], k=k_partitions))\n\n    while len(states_pq) > 1:\n        state0 = heapq.heappop(states_pq)\n        state1 = heapq.heappop(states_pq)\n        # merge states\n        state0.merge(state1)\n        heapq.heappush(states_pq, state0)\n\n    final_state = states_pq[0]\n    partitions = final_state.get_partitions()\n    if equal_size:\n        for i, partition in enumerate(partitions):\n            assert len(partition) * \\\n                k_partitions == len(seqlen_list), f\"{len(partition)} * {k_partitions} != {len(seqlen_list)}\"\n    return partitions\n\n\ndef greedy_partition(seqlen_list: List[int], k_partitions: int, equal_size: bool):\n    bias = sum(seqlen_list) + 1 if equal_size else 0\n    sorted_seqlen = [(seqlen + bias, i) for i, seqlen in enumerate(seqlen_list)]\n    partitions = [[] for _ in range(k_partitions)]\n    partition_sums = [0 for _ in range(k_partitions)]\n    for seqlen, i in sorted_seqlen:\n        min_idx = None\n        for j in range(k_partitions):\n            if min_idx is None or partition_sums[j] < partition_sums[min_idx]:\n                min_idx = j\n        partitions[min_idx].append(i)\n        partition_sums[min_idx] += seqlen\n    if equal_size:\n        for i, partition in enumerate(partitions):\n            assert len(partition) * \\\n                k_partitions == len(seqlen_list), f\"{len(partition)} * {k_partitions} != {len(seqlen_list)}\"\n    return partitions\n\n\ndef get_seqlen_balanced_partitions(seqlen_list: List[int], k_partitions: int, equal_size: bool):\n    \"\"\" get order of seq lengths to make partitions balanced, this is\n        used in balacing sum of seqlength across dp ranks and microbatches\n    Parameters:\n        seqlen_list (List[int]):\n            seq lengths of each items\n        k_partitions (int):\n            resulting number of partitions\n        equal_size (bool):\n            if True, number of items in each partitions must be equal.\n            if False, only consider balancing the sum, each partition can have\n            variable number of items\n    Returns:\n        partitions (List[List[int]]):\n            return k_partitions list containing the index of items.\n    \"\"\"\n    assert len(seqlen_list) >= k_partitions, f\"number of items:[{len(seqlen_list)}] < k_partitions:[{k_partitions}]\"\n\n    def _check_and_sort_partitions(partitions):\n        assert len(partitions) == k_partitions, f\"{len(partitions)} != {k_partitions}\"\n        seen_idx = set()\n        sorted_partitions = [None] * k_partitions\n        for i, partition in enumerate(partitions):\n            assert len(partition) > 0, f\"the {i}-th partition is empty\"\n            for idx in partition:\n                seen_idx.add(idx)\n            sorted_partitions[i] = sorted(partition)\n        assert seen_idx == set(range(len(seqlen_list)))\n        return sorted_partitions\n\n    partitions = karmarkar_karp(seqlen_list=seqlen_list, k_partitions=k_partitions, equal_size=equal_size)\n    return _check_and_sort_partitions(partitions)\n\n\ndef log_seqlen_unbalance(seqlen_list: List[int], partitions: List[List[int]], prefix):\n    # add some metrics of seqlen sum on dp ranks\n    k_partition = len(partitions)\n    # assert len(seqlen_list) % k_partition == 0\n    batch_size = len(seqlen_list) // k_partition\n    min_sum_seqlen = None\n    max_sum_seqlen = None\n    total_sum_seqlen = 0\n    for offset in range(0, len(seqlen_list), batch_size):\n        cur_sum_seqlen = sum(seqlen_list[offset:offset + batch_size])\n        if min_sum_seqlen is None or cur_sum_seqlen < min_sum_seqlen:\n            min_sum_seqlen = cur_sum_seqlen\n        if max_sum_seqlen is None or cur_sum_seqlen > max_sum_seqlen:\n            max_sum_seqlen = cur_sum_seqlen\n        total_sum_seqlen += cur_sum_seqlen\n\n    balanced_sum_seqlen_list = []\n    for partition in partitions:\n        cur_sum_seqlen_balanced = sum([seqlen_list[i] for i in partition])\n        balanced_sum_seqlen_list.append(cur_sum_seqlen_balanced)\n    # print(\"balanced_sum_seqlen_list: \", balanced_sum_seqlen_list)\n    min_sum_seqlen_balanced = min(balanced_sum_seqlen_list)\n    max_sum_seqlen_balanced = max(balanced_sum_seqlen_list)\n\n    return {\n        f'{prefix}/min': min_sum_seqlen,\n        f'{prefix}/max': max_sum_seqlen,\n        f'{prefix}/minmax_diff': max_sum_seqlen - min_sum_seqlen,\n        f'{prefix}/balanced_min': min_sum_seqlen_balanced,\n        f'{prefix}/balanced_max': max_sum_seqlen_balanced,\n        f'{prefix}/mean': total_sum_seqlen / len(partitions)\n    }\n\n\ndef ceildiv(a, b):\n    return -(a // -b)\n\n\ndef rearrange_micro_batches(batch: TensorDict, max_token_len, dp_group=None):\n    \"\"\"Split the batch into a list of micro_batches, where the max_token_len is smaller than max_token_len\n    and the number of valid tokens in each micro batch is well balanced.\n    \"\"\"\n    # this is per local micro_bsz\n    max_seq_len = batch['attention_mask'].shape[-1]\n    assert max_token_len >= max_seq_len, \\\n        f'max_token_len must be greater than the sequence length. Got {max_token_len=} and {max_seq_len=}'\n\n    seq_len_effective: torch.Tensor = batch['attention_mask'].sum(dim=1)\n    total_seqlen = seq_len_effective.sum().item()\n    num_micro_batches = ceildiv(total_seqlen, max_token_len)\n    if dist.is_initialized():\n        num_micro_batches = torch.tensor([num_micro_batches], device='cuda')\n        dist.all_reduce(num_micro_batches, op=dist.ReduceOp.MAX, group=dp_group)\n        num_micro_batches = num_micro_batches.cpu().item()\n\n    seq_len_effective = seq_len_effective.tolist()\n    assert num_micro_batches <= len(seq_len_effective)\n\n    micro_bsz_idx = get_seqlen_balanced_partitions(seq_len_effective, num_micro_batches, equal_size=False)\n\n    micro_batches = []\n\n    for partition in micro_bsz_idx:\n        curr_micro_batch = []\n        for idx in partition:\n            curr_micro_batch.append(batch[idx:idx + 1])\n        curr_micro_batch = torch.cat(curr_micro_batch)\n\n        micro_batches.append(curr_micro_batch)\n\n    return micro_batches, micro_bsz_idx\n\n\ndef get_reverse_idx(idx_map):\n    reverse_idx_map = copy.deepcopy(idx_map)\n\n    for i, idx in enumerate(idx_map):\n        reverse_idx_map[idx] = i\n\n    return reverse_idx_map\n"
  },
  {
    "path": "verl/utils/tokenizer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utils for tokenization.\"\"\"\nimport warnings\n\n__all__ = ['hf_tokenizer', 'hf_processor']\n\n\ndef set_pad_token_id(tokenizer):\n    \"\"\"Set pad_token_id to eos_token_id if it is None.\n\n    Args:\n        tokenizer (transformers.PreTrainedTokenizer): The tokenizer to be set.\n\n    \"\"\"\n    if tokenizer.pad_token_id is None:\n        tokenizer.pad_token_id = tokenizer.eos_token_id\n        warnings.warn(f'tokenizer.pad_token_id is None. Now set to {tokenizer.eos_token_id}')\n    if tokenizer.pad_token is None:\n        tokenizer.pad_token = tokenizer.eos_token\n        warnings.warn(f'tokenizer.pad_token is None. Now set to {tokenizer.eos_token}')\n\n\ndef hf_tokenizer(name_or_path, correct_pad_token=True, correct_gemma2=True, **kwargs):\n    \"\"\"Create a huggingface pretrained tokenizer which correctness handles eos and pad tokens.\n\n    Args:\n\n        name (str): The name of the tokenizer.\n        correct_pad_token (bool): Whether to correct the pad token id.\n        correct_gemma2 (bool): Whether to correct the gemma2 tokenizer.\n\n    Returns:\n\n        transformers.PreTrainedTokenizer: The pretrained tokenizer.\n\n    \"\"\"\n    from transformers import AutoTokenizer\n    if correct_gemma2 and isinstance(name_or_path, str) and 'gemma-2-2b-it' in name_or_path:\n        # the EOS token in gemma2 is ambiguious, which may worsen RL performance.\n        # https://huggingface.co/google/gemma-2-2b-it/commit/17a01657f5c87135bcdd0ec7abb4b2dece04408a\n        warnings.warn('Found gemma-2-2b-it tokenizer. Set eos_token and eos_token_id to <end_of_turn> and 107.')\n        kwargs['eos_token'] = '<end_of_turn>'\n        kwargs['eos_token_id'] = 107\n    tokenizer = AutoTokenizer.from_pretrained(name_or_path, **kwargs)\n    if correct_pad_token:\n        set_pad_token_id(tokenizer)\n    return tokenizer\n\n\ndef hf_processor(name_or_path, **kwargs):\n    \"\"\"Create a huggingface processor to process multimodal data.\n\n    Args:\n        name_or_path (str): The name of the processor.\n\n    Returns:\n        transformers.ProcessorMixin: The pretrained processor.\n    \"\"\"\n    from transformers import AutoProcessor\n    try:\n        processor = AutoProcessor.from_pretrained(name_or_path, **kwargs)\n    except Exception:\n        processor = None\n    # Avoid load tokenizer, see:\n    # https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/auto/processing_auto.py#L344\n    if processor is not None and \"Processor\" not in processor.__class__.__name__:\n        processor = None\n    return processor\n"
  },
  {
    "path": "verl/utils/torch_dtypes.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nAdapted from Cruise.\n\"\"\"\n\nimport torch\n\nfrom typing import Union\n\nHALF_LIST = [16, \"16\", \"fp16\", \"float16\", torch.float16]\nFLOAT_LIST = [32, \"32\", \"fp32\", \"float32\", torch.float32]\nBFLOAT_LIST = [\"bf16\", \"bfloat16\", torch.bfloat16]\n\n\nclass PrecisionType(object):\n    \"\"\"Type of precision used.\n\n    >>> PrecisionType.HALF == 16\n    True\n    >>> PrecisionType.HALF in (16, \"16\")\n    True\n    \"\"\"\n\n    HALF = \"16\"\n    FLOAT = \"32\"\n    FULL = \"64\"\n    BFLOAT = \"bf16\"\n    MIXED = \"mixed\"\n\n    @staticmethod\n    def supported_type(precision: Union[str, int]) -> bool:\n        return any(x == precision for x in PrecisionType)\n\n    @staticmethod\n    def supported_types() -> list[str]:\n        return [x.value for x in PrecisionType]\n\n    @staticmethod\n    def is_fp16(precision):\n        return precision in HALF_LIST\n\n    @staticmethod\n    def is_fp32(precision):\n        return precision in FLOAT_LIST\n\n    @staticmethod\n    def is_bf16(precision):\n        return precision in BFLOAT_LIST\n\n    @staticmethod\n    def to_dtype(precision):\n        if precision in HALF_LIST:\n            return torch.float16\n        elif precision in FLOAT_LIST:\n            return torch.float32\n        elif precision in BFLOAT_LIST:\n            return torch.bfloat16\n        else:\n            raise RuntimeError(f\"unexpected precision: {precision}\")\n\n    @staticmethod\n    def to_str(precision):\n        if precision == torch.float16:\n            return 'fp16'\n        elif precision == torch.float32:\n            return 'fp32'\n        elif precision == torch.bfloat16:\n            return 'bf16'\n        else:\n            raise RuntimeError(f\"unexpected precision: {precision}\")\n"
  },
  {
    "path": "verl/utils/torch_functional.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nContain small torch utilities\n\"\"\"\n\nfrom typing import Dict, Union, List, Optional\n\nimport torch\nimport torch.distributed\nimport torch.nn.functional as F\nfrom tensordict import TensorDict\nfrom torch import nn\n\ntry:\n    from flash_attn.ops.triton.cross_entropy import cross_entropy_loss\n    FLAH_ATTN_CROSS_ENTROPY_LOSS_AVAILABLE = True\nexcept ImportError:\n    FLAH_ATTN_CROSS_ENTROPY_LOSS_AVAILABLE = False\n\n\ndef gather_from_labels(data, label):\n    \"\"\"Gather the label from data. The value in label should be [0, vocab_size)\n\n    Args:\n        data: (..., vocab_size)\n        label (torch.IntTensor) : (...,)\n\n    Returns:\n\n    \"\"\"\n\n    output = torch.gather(data, -1, label.unsqueeze(-1)).squeeze(-1)\n    return output\n\n\ndef logprobs_from_logits(logits, labels):\n    \"\"\"\n    See: https://github.com/pytorch/pytorch/issues/563#issuecomment-330103591\n    \"\"\"\n    if FLAH_ATTN_CROSS_ENTROPY_LOSS_AVAILABLE:\n        batch_dim = logits.shape[:-1]\n        last_dim = logits.shape[-1]\n        logits = logits.reshape(-1, last_dim)\n        labels = labels.reshape(-1)\n        output = logprobs_from_logits_flash_attn(logits, labels)\n        output = output.view(*batch_dim)\n    else:\n        output = logprobs_from_logits_v2(logits, labels)\n    return output\n\n\ndef logprobs_from_logits_flash_attn(logits, labels):\n    output = cross_entropy_loss(logits, labels)\n    assert isinstance(\n        output, tuple), \"please make sure flash-attn>=2.4.3 where cross_entropy_loss returns Tuple[losses, z_losses].\"\n    return -output[0]\n\n\ndef logprobs_from_logits_naive(logits, labels):\n    logp = F.log_softmax(logits, dim=-1)\n    logpy = gather_from_labels(logp, labels)\n    return logpy\n\n\ndef logprobs_from_logits_v2(logits: torch.FloatTensor, labels):\n    \"\"\"\n    A memory efficient implementation of logprobs_from_logits\n    \"\"\"\n    if logits.dtype in [torch.float32, torch.float64]:\n        logits_labels = torch.gather(logits, dim=-1, index=labels.unsqueeze(-1)).squeeze(-1)\n        # loop to reduce peak mem consumption\n        logsumexp_values = torch.stack([torch.logsumexp(l, dim=-1) for l in logits])\n        logprobs_labels = logits_labels - logsumexp_values  # log_softmax(x_i) = x_i - logsumexp(x)\n    else:\n        # logsumexp approach is unstable with bfloat16, fall back to slightly less efficent approach\n        logprobs_labels = []\n        for row_logits, row_labels in zip(logits, labels):  # loop to reduce peak mem consumption\n            row_logprobs = F.log_softmax(row_logits, dim=-1)\n            row_logprobs_labels = row_logprobs.gather(dim=-1, index=row_labels.unsqueeze(-1)).squeeze(-1)\n            logprobs_labels.append(row_logprobs_labels)\n        logprobs_labels = torch.stack(logprobs_labels)\n    return logprobs_labels\n\n\ndef clip_by_value(x, tensor_min, tensor_max):\n    \"\"\"\n    Tensor extenstion to torch.clamp\n    https://github.com/pytorch/pytorch/issues/2793#issuecomment-428784713\n    \"\"\"\n    clipped = torch.max(torch.min(x, tensor_max), tensor_min)\n    return clipped\n\n\ndef entropy_from_logits(logits: torch.Tensor):\n    \"\"\"Calculate entropy from logits.\"\"\"\n    pd = torch.nn.functional.softmax(logits, dim=-1)\n    entropy = torch.logsumexp(logits, dim=-1) - torch.sum(pd * logits, dim=-1)\n    return entropy\n\n\ndef masked_sum(values, mask, axis=None):\n    \"\"\"Compute mean of tensor with a masked values.\"\"\"\n    return (values * mask).sum(axis=axis)\n\n\ndef masked_mean(values, mask, axis=None):\n    \"\"\"Compute mean of tensor with a masked values.\"\"\"\n    return (values * mask).sum(axis=axis) / mask.sum(axis=axis)\n\n\ndef masked_var(values, mask, unbiased=True):\n    \"\"\"Compute variance of tensor with masked values.\"\"\"\n    mean = masked_mean(values, mask)\n    centered_values = values - mean\n    variance = masked_mean(centered_values**2, mask)\n    if unbiased:\n        mask_sum = mask.sum()\n        if mask_sum == 0:\n            raise ValueError(\"At least one element in the mask has to be 1.\")\n        # note that if mask_sum == 1, then there is a division by zero issue\n        # to avoid it you just need to use a larger minibatch_size\n        if mask_sum == 1:\n            raise ValueError(\"The sum of the mask is one, which can cause a division by zero.\")\n        bessel_correction = mask_sum / (mask_sum - 1)\n        variance = variance * bessel_correction\n    return variance\n\n\ndef masked_whiten(values, mask, shift_mean=True):\n    \"\"\"Whiten values with masked values.\"\"\"\n    mean, var = masked_mean(values, mask), masked_var(values, mask)\n    whitened = (values - mean) * torch.rsqrt(var + 1e-8)\n    if not shift_mean:\n        whitened += mean\n    return whitened\n\n\ndef get_eos_mask(response_id: torch.Tensor, eos_token: Union[int, List[int]] = 2, dtype=torch.int64):\n    '''\n    end of sentence token can be int or list: 1 or [1, 2]\n    e.g. eos_token=1\n    response_id: [0, 0, 2, 42, 3, 5, 1, 0, 0]\n    eos_mask:     [1, 1, 1, 1,  1, 1, 1, 0, 0]\n    '''\n    if isinstance(eos_token, int):\n        eos_token = [eos_token]\n\n    eos_mask = torch.zeros_like(response_id, dtype=torch.bool)\n    for token in eos_token:\n        eos_mask |= response_id.eq(token)\n\n    eos_mask = eos_mask.long()\n    eos_mask = (torch.cumsum(eos_mask, dim=1) - eos_mask).bool()\n    eos_mask = torch.logical_not(eos_mask).to(dtype)\n    return eos_mask\n\n\ndef compute_grad_norm(model: nn.Module):\n    total_grad_square = 0\n    total_params = 0\n    for param in model.parameters():\n        if param.grad is not None:\n            total_grad_square += torch.sum(torch.square(param.grad.detach())).item()\n    return total_grad_square\n\n\ndef broadcast_dict_tensor(tensors: Union[Dict[str, torch.Tensor], TensorDict], src, group):\n    \"\"\"\n    TODO: optimize this. Technically, we only need one broadcast\n    \"\"\"\n\n    for key in tensors.sorted_keys:\n        torch.distributed.broadcast(tensors[key], src=src, group=group, async_op=False)\n\n\ndef allgather_dict_tensors(tensors: Union[Dict[str, torch.Tensor], TensorDict], size, group, dim=0):\n    \"\"\"\n    TODO: optimize this.\n    - We can use async ops\n    - We can use only one allgather\n    Args:\n        tensors:\n        size:\n        group:\n\n    Returns:\n\n    \"\"\"\n    if isinstance(tensors, TensorDict):\n        is_tensor_dict = True\n        tensors_as_dict = tensors.to_dict()\n    else:\n        tensors_as_dict = tensors\n        is_tensor_dict = False\n\n    output = {}\n    sorted_keys = sorted(tensors_as_dict.keys())\n    for key in sorted_keys:\n        val = tensors_as_dict[key]\n        output[key] = [torch.empty_like(val) for _ in range(size)]\n        torch.distributed.all_gather(output[key], val, group=group, async_op=False)\n        output[key] = torch.cat(output[key], dim=dim)\n\n    if is_tensor_dict:\n        output = TensorDict(source=output, batch_size=tensors.batch_size[0] * size)\n\n    return output\n\n\ndef split_dict_tensor_into_batches(tensors: TensorDict, batch_size) -> List[TensorDict]:\n    assert tensors.batch_size[0] % batch_size == 0, \\\n        f'input data batch size: {tensors.batch_size[0]}, split batch size: {batch_size}'\n    return tensors.split(batch_size)\n\n\ndef pad_2d_list_to_length(response, pad_token_id, max_length=None):\n    \"\"\"\n    pad a 2D list (e.g. responses, logprobs) to a 2D tensor.\n    \"\"\"\n    response_length = max(len(sub_list) for sub_list in response)\n    if max_length is not None and max_length > response_length:\n        target_length = max_length\n    else:\n        target_length = response_length\n    padded_response = [tuple(sub_list) + (pad_token_id,) * (target_length - len(sub_list)) for sub_list in response]\n    tensor = torch.tensor(padded_response)\n    return tensor\n\n\ndef pad_sequence_to_length(tensors, max_seq_len, pad_token_id, left_pad=False):\n    \"\"\"\n    pad a 2D tensors (e.g. responses, logprobs) in the last dim to max_seq_length.\n    input shape: [bs, seq_length]\n    output shape: [bs, max_seq_length]\n    (0, max_seq_len - tensors.shape[-1]) means right pad to max_seq_length and no left pad\n    \"\"\"\n    if tensors.shape[-1] >= max_seq_len:\n        return tensors\n    pad_tuple = (max_seq_len - tensors.shape[-1], 0) if left_pad else (0, max_seq_len - tensors.shape[-1])\n    return F.pad(tensors, pad_tuple, 'constant', pad_token_id)\n\n\nfrom transformers import PreTrainedTokenizer\n\n\ndef tokenize_and_postprocess_data(prompt: str,\n                                  tokenizer: PreTrainedTokenizer,\n                                  max_length: int,\n                                  pad_token_id: int,\n                                  left_pad=True,\n                                  truncation='error'):\n    \"\"\"\n    input_data is the output from tokenizer.\n    \"\"\"\n    assert truncation in ['left', 'right', 'error']\n\n    input_data = tokenizer(prompt, return_tensors='pt', add_special_tokens=False)\n\n    input_ids = input_data['input_ids']\n    attention_mask = input_data['attention_mask']\n\n    assert input_ids.ndim == 2\n\n    sequence_length = input_ids.shape[-1]\n    if sequence_length < max_length:\n        input_ids = pad_sequence_to_length(input_ids,\n                                           max_seq_len=max_length,\n                                           pad_token_id=pad_token_id,\n                                           left_pad=left_pad)\n        attention_mask = pad_sequence_to_length(attention_mask,\n                                                max_seq_len=max_length,\n                                                pad_token_id=0,\n                                                left_pad=left_pad)\n    elif sequence_length > max_length:\n        if truncation == 'left':\n            # actually, left truncation may not be reasonable\n            input_ids = input_ids[:, -max_length:]\n            attention_mask = attention_mask[:, -max_length:]\n        elif truncation == 'right':\n            input_ids = input_ids[:, :max_length]\n            attention_mask = attention_mask[:, :max_length]\n        elif truncation == 'error':\n            raise NotImplementedError(f'{sequence_length=} is larger than {max_length=}')\n        else:\n            raise NotImplementedError(f'Unknown truncation method {truncation}')\n\n    return input_ids, attention_mask\n\n\ndef remove_pad_token(input_ids: torch.Tensor, attention_mask: torch.Tensor):\n    \"\"\" Remove the pad token.\n\n    Args:\n        input_ids shape: [bs, seq_length]\n        attention_mask shape: [bs, seq_length]\n    Returns:\n        no_padding_batch(List[List[int]]): contains the rmpad token ids per query.\n    \"\"\"\n    no_padding_batch = []\n    for ids, mask in zip(input_ids, attention_mask):\n        no_padding_batch.append((ids[len(ids) - mask.sum():]).cpu().numpy().tolist())\n    return no_padding_batch\n\n\ndef log_probs_from_logits_response(input_ids, logits, response_length):\n    \"\"\"Compute the response log_probs from full logits. Note that logits = model(input_ids)\n\n    Args:\n        input_ids: [batch_size, seqlen]\n        logits: [batch_size, seqlen, vocab_size]\n\n    Returns:\n        response_log_prob:\n    \"\"\"\n    response_logits = logits[:, -response_length - 1:-1]\n    response = input_ids[:, -response_length:]\n    response_log_prob = logprobs_from_logits(logits=response_logits, labels=response)\n    return response_log_prob\n\n\ndef log_probs_from_logits_response_rmpad(input_ids, attention_mask, logits_rmpad, response_length):\n    \"\"\"Compute the log_probs from logits with rmpad logits and pad input. Note that\n    logits_rmpad = model(input_ids_rmpad). For each sentences, there is a shift between\n    logits and input_ids.\n    The reason for this function to is to compute logprobs_from_logits in rmpad mode because it is memory-intensive\n    for large vocab_size\n\n    Args:\n        input_ids: [batch_size, seqlen]\n        attention_mask: [batch_size, seqlen]\n        logits_rmpad: [total_nnz, vocab_size]\n        response_length: int\n    \"\"\"\n    from flash_attn.bert_padding import pad_input, unpad_input\n\n    batch_size, seqlen = input_ids.shape\n    input_ids_rmpad, indices, *_ = unpad_input(input_ids.unsqueeze(-1), attention_mask=attention_mask)\n    input_ids_rmpad = input_ids_rmpad.squeeze(-1)\n    input_ids_rmpad_rolled = torch.roll(input_ids_rmpad, shifts=-1, dims=0)\n    full_log_probs_rmpad = logprobs_from_logits(logits=logits_rmpad, labels=input_ids_rmpad_rolled)  # (total_nnz,)\n    full_output = pad_input(hidden_states=full_log_probs_rmpad.unsqueeze(-1),\n                            indices=indices,\n                            batch=batch_size,\n                            seqlen=seqlen)\n    output = full_output.squeeze(-1)[:, -response_length - 1:-1]  # [batch_size, response_length]\n    return output\n\n\ndef log_probs_from_logits_all_rmpad(input_ids_rmpad, logits_rmpad, indices, batch_size, seqlen, response_length):\n    \"\"\"Compute the log_probs from logits with rmpad input_ids and logits. Note that\n    logits_rmpad = model(input_ids_rmpad). For each sentences, there is a shift between\n    logits and input_ids.\n    The reason for this function to is to compute logprobs_from_logits in rmpad mode because it is memory-intensive\n    for large vocab_size\n\n    Args:\n        input_ids_rmpad: [1, total_nnz]\n        logits_rmpad: [total_nnz, vocab_size]\n        indices: [total_nnz]\n        batch_size: int\n        seqlen: int\n        response_length: int\n    \"\"\"\n    from flash_attn.bert_padding import pad_input\n    input_ids_rmpad = input_ids_rmpad.transpose(0, 1)  # transpose back to [total_nnz, 1]\n    input_ids_rmpad = input_ids_rmpad.squeeze(-1)\n    input_ids_rmpad_rolled = torch.roll(input_ids_rmpad, shifts=-1, dims=0)\n    full_log_probs_rmpad = logprobs_from_logits(logits=logits_rmpad, labels=input_ids_rmpad_rolled)  # (total_nnz,)\n    full_output = pad_input(hidden_states=full_log_probs_rmpad.unsqueeze(-1),\n                            indices=indices,\n                            batch=batch_size,\n                            seqlen=seqlen)\n    output = full_output.squeeze(-1)[:, -response_length - 1:-1]  # [batch_size, response_length]\n    return output\n\n\nfrom transformers.generation.logits_process import (TemperatureLogitsWarper, TopKLogitsWarper, TopPLogitsWarper)\n\n\ndef post_process_logits(input_ids, logits, temperature, top_k, top_p):\n    if temperature != 1.:\n        logits = logits.div_(temperature)  # inplace operation to avoid OOM\n    # TODO: add them back\n    # if top_k is not None and top_k > 0:\n    #     logits = TopKLogitsWarper(top_k=top_k)(input_ids, logits)\n    # if top_p is not None and top_p < 1.0 and top_p > 0.0:\n    #     logits = TopPLogitsWarper(top_p=top_p)(input_ids, logits)\n    return logits\n\n\n\"\"\"\nOptimizer related\n\"\"\"\n\nfrom torch.optim import Optimizer\nfrom torch.optim.lr_scheduler import LambdaLR\nimport math\n\n\ndef get_cosine_schedule_with_warmup(\n    optimizer: Optimizer,\n    num_warmup_steps: int,\n    num_training_steps: int,\n    min_lr_ratio: float = 0.0,\n    num_cycles: float = 0.5,\n    last_epoch: int = -1,\n):\n    \"\"\"\n    Create a schedule with a learning rate that decreases following the values of the cosine function between the\n    initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the\n    initial lr set in the optimizer.\n    Args:\n        optimizer (:class:`~torch.optim.Optimizer`):\n            The optimizer for which to schedule the learning rate.\n        num_warmup_steps (:obj:`int`):\n            The number of steps for the warmup phase.\n        num_training_steps (:obj:`int`):\n            The total number of training steps.\n        min_lr_ratio (:obj:`float`, `optional`, defaults to 0.0):\n            The minimum lr ratio w.r.t the maximum.\n        num_cycles (:obj:`float`, `optional`, defaults to 0.5):\n            The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0\n            following a half-cosine).\n        last_epoch (:obj:`int`, `optional`, defaults to -1):\n            The index of the last epoch when resuming training.\n    Return:\n        :obj:`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.\n    \"\"\"\n    assert min_lr_ratio >= 0 and min_lr_ratio <= 1.\n    coef = (1 - min_lr_ratio) * 0.5\n    intercept = (1 + min_lr_ratio) * 0.5\n\n    def lr_lambda(current_step):\n        if current_step < num_warmup_steps:\n            return float(current_step) / float(max(1, num_warmup_steps))\n        progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))\n        x = math.cos(math.pi * float(num_cycles) * 2.0 * progress)\n        return max(0.0, x * coef + intercept)\n\n    return LambdaLR(optimizer, lr_lambda, last_epoch)\n\n\ndef get_constant_schedule_with_warmup(\n    optimizer: Optimizer,\n    num_warmup_steps: int,\n    last_epoch: int = -1,\n):\n\n    def lr_lambda(current_step):\n        return min(1, float(current_step) / float(max(1, num_warmup_steps)))\n\n    return LambdaLR(optimizer, lr_lambda, last_epoch)\n\n\ndef prepare_decoder_attention_mask(attention_mask, input_shape, inputs_embeds):\n    # create causal mask\n    # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n    combined_attention_mask = None\n    if input_shape[-1] > 1:\n        combined_attention_mask = _make_causal_mask(\n            input_shape,\n            inputs_embeds.dtype,\n            device=inputs_embeds.device,\n        )\n\n    if attention_mask is not None:\n        # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n        expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype,\n                                          tgt_len=input_shape[-1]).to(inputs_embeds.device)\n        combined_attention_mask = (expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask +\n                                   combined_attention_mask)\n\n    return combined_attention_mask\n\n\n# Copied from transformers.models.bart.modeling_bart._make_causal_mask\ndef _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device):\n    \"\"\"\n    Make causal mask used for bi-directional self-attention.\n    \"\"\"\n    bsz, tgt_len = input_ids_shape\n    mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)\n    mask_cond = torch.arange(mask.size(-1), device=device)\n    mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)\n    mask = mask.to(dtype)\n    return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len)\n\n\n# Copied from transformers.models.bart.modeling_bart._expand_mask\ndef _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):\n    \"\"\"\n    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.\n    \"\"\"\n    bsz, src_len = mask.size()\n    tgt_len = tgt_len if tgt_len is not None else src_len\n\n    expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)\n\n    inverted_mask = 1.0 - expanded_mask\n\n    return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)\n\n\ndef get_unpad_data(attention_mask):\n    seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)\n    indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()\n    max_seqlen_in_batch = seqlens_in_batch.max().item()\n    cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))\n    return (\n        indices,\n        cu_seqlens,\n        max_seqlen_in_batch,\n    )\n"
  },
  {
    "path": "verl/utils/tracking.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nA unified tracking interface that supports logging data to different backend\n\"\"\"\nimport dataclasses\nfrom enum import Enum\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import List, Union, Dict, Any\n\n\nclass Tracking(object):\n    supported_backend = [\"wandb\", \"mlflow\", \"swanlab\", \"vemlp_wandb\", \"tensorboard\", \"console\"]\n\n    def __init__(self, project_name, experiment_name, default_backend: Union[str, List[str]] = 'console', config=None):\n        if isinstance(default_backend, str):\n            default_backend = [default_backend]\n        for backend in default_backend:\n            if backend == 'tracking':\n                import warnings\n                warnings.warn(\"`tracking` logger is deprecated. use `wandb` instead.\", DeprecationWarning)\n            else:\n                assert backend in self.supported_backend, f'{backend} is not supported'\n\n        self.logger = {}\n\n        if 'tracking' in default_backend or 'wandb' in default_backend:\n            import wandb\n            wandb.init(project=project_name, name=experiment_name, config=config)\n            self.logger['wandb'] = wandb\n\n        if 'mlflow' in default_backend:\n            import mlflow\n            mlflow.start_run(run_name=experiment_name)\n            mlflow.log_params(_compute_mlflow_params_from_objects(config))\n            self.logger['mlflow'] = _MlflowLoggingAdapter()\n\n        if \"swanlab\" in default_backend:\n            import swanlab\n            import os\n\n            SWANLAB_API_KEY = os.environ.get(\"SWANLAB_API_KEY\", None)\n            SWANLAB_LOG_DIR = os.environ.get(\"SWANLAB_LOG_DIR\", \"swanlog\")\n            SWANLAB_MODE = os.environ.get(\"SWANLAB_MODE\", \"cloud\")\n            if SWANLAB_API_KEY:\n                swanlab.login(SWANLAB_API_KEY)  # NOTE: previous login information will be overwritten\n            swanlab.init(project=project_name,\n                         experiment_name=experiment_name,\n                         config=config,\n                         logdir=SWANLAB_LOG_DIR,\n                         mode=SWANLAB_MODE)\n            self.logger[\"swanlab\"] = swanlab\n\n        if 'vemlp_wandb' in default_backend:\n            import os\n            import volcengine_ml_platform\n            from volcengine_ml_platform import wandb as vemlp_wandb\n            volcengine_ml_platform.init(\n                ak=os.environ[\"VOLC_ACCESS_KEY_ID\"],\n                sk=os.environ[\"VOLC_SECRET_ACCESS_KEY\"],\n                region=os.environ[\"MLP_TRACKING_REGION\"],\n            )\n\n            vemlp_wandb.init(\n                project=project_name,\n                name=experiment_name,\n                config=config,\n                sync_tensorboard=True,\n            )\n            self.logger['vemlp_wandb'] = vemlp_wandb\n\n        if 'tensorboard' in default_backend:\n            self.logger['tensorboard'] = _TensorboardAdapter()\n\n        if 'console' in default_backend:\n            from verl.utils.logger.aggregate_logger import LocalLogger\n            self.console_logger = LocalLogger(print_to_console=True)\n            self.logger['console'] = self.console_logger\n\n    def log(self, data, step, backend=None):\n        for default_backend, logger_instance in self.logger.items():\n            if backend is None or default_backend in backend:\n                logger_instance.log(data=data, step=step)\n\n    def __del__(self):\n        if 'wandb' in self.logger:\n            self.logger['wandb'].finish(exit_code=0)\n        if 'swanlab' in self.logger:\n            self.logger['swanlab'].finish()\n        if 'vemlp_wandb' in self.logger:\n            self.logger['vemlp_wandb'].finish(exit_code=0)\n        if 'tensorboard' in self.logger:\n            self.logger['tensorboard'].finish()\n\n\nclass _TensorboardAdapter:\n\n    def __init__(self):\n        from torch.utils.tensorboard import SummaryWriter\n        import os\n        tensorboard_dir = os.environ.get(\"TENSORBOARD_DIR\", \"tensorboard_log\")\n        os.makedirs(tensorboard_dir, exist_ok=True)\n        print(f\"Saving tensorboard log to {tensorboard_dir}.\")\n        self.writer = SummaryWriter(tensorboard_dir)\n\n    def log(self, data, step):\n        for key in data:\n            self.writer.add_scalar(key, data[key], step)\n\n    def finish(self):\n        self.writer.close()\n\n\nclass _MlflowLoggingAdapter:\n\n    def log(self, data, step):\n        import mlflow\n        mlflow.log_metrics(metrics=data, step=step)\n\n\ndef _compute_mlflow_params_from_objects(params) -> Dict[str, Any]:\n    if params is None:\n        return {}\n\n    return _flatten_dict(_transform_params_to_json_serializable(params, convert_list_to_dict=True), sep='/')\n\n\ndef _transform_params_to_json_serializable(x, convert_list_to_dict: bool):\n    _transform = partial(_transform_params_to_json_serializable, convert_list_to_dict=convert_list_to_dict)\n\n    if dataclasses.is_dataclass(x):\n        return _transform(dataclasses.asdict(x))\n    if isinstance(x, dict):\n        return {k: _transform(v) for k, v in x.items()}\n    if isinstance(x, list):\n        if convert_list_to_dict:\n            return {'list_len': len(x)} | {f'{i}': _transform(v) for i, v in enumerate(x)}\n        else:\n            return [_transform(v) for v in x]\n    if isinstance(x, Path):\n        return str(x)\n    if isinstance(x, Enum):\n        return x.value\n\n    return x\n\n\ndef _flatten_dict(raw: Dict[str, Any], *, sep: str) -> Dict[str, Any]:\n    import pandas as pd\n    ans = pd.json_normalize(raw, sep=sep).to_dict(orient='records')[0]\n    assert isinstance(ans, dict)\n    return ans\n"
  },
  {
    "path": "verl/utils/ulysses.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nUtilities for DeepSpeed Ulysses Sequence Parallelism.\nDeepSpeed Ulysses Paper: https://arxiv.org/abs/2309.14509\nInspired from: https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/sequence/layer.py\n\"\"\"\nfrom typing import Any, Optional, List, Tuple\n\nimport torch\nfrom torch import Tensor\nimport torch.distributed as dist\nfrom torch.distributed import ProcessGroup\n\n_ULYSSES_SEQUENCE_PARALLEL_GROUP = None\n\n\ndef set_ulysses_sequence_parallel_group(group: dist.ProcessGroup):\n    \"\"\"\n    Set ulysses sequence parallel process group.\n    \"\"\"\n    global _ULYSSES_SEQUENCE_PARALLEL_GROUP\n    _ULYSSES_SEQUENCE_PARALLEL_GROUP = group\n\n\ndef get_ulysses_sequence_parallel_group() -> Optional[dist.ProcessGroup]:\n    \"\"\"\n    Get ulysses sequence parallel process group.\n    \"\"\"\n    global _ULYSSES_SEQUENCE_PARALLEL_GROUP\n    return _ULYSSES_SEQUENCE_PARALLEL_GROUP\n\n\ndef get_ulysses_sequence_parallel_world_size(group: ProcessGroup = None) -> int:\n    \"\"\"\n    Get ulysses sequence parallel world size.\n    \"\"\"\n    group = get_ulysses_sequence_parallel_group() if group is None else group\n    return dist.get_world_size(group) if group else 1\n\n\ndef get_ulysses_sequence_parallel_rank(group: ProcessGroup = None) -> int:\n    \"\"\"\n    Get ulysses sequence parallel rank.\n    \"\"\"\n    group = get_ulysses_sequence_parallel_group() if group is None else group\n    return dist.get_rank(group) if group else 0\n\n\ndef gather_seq_scatter_heads(\n    x: Tensor,\n    seq_dim: int,\n    head_dim: int,\n    unpadded_dim_size: int = 0,\n    group: ProcessGroup = None,\n) -> Tensor:\n    \"\"\"\n    A func to sync embedding input with alltoall in sequence parallel\n    gather sequence dimension and scatter head dim:\n    e.g. seq_dim: 1, head_dim: 2\n    [bsz, seq/n, h, ...] -> [bsz, seq, h/n, ...]\n    \"\"\"\n    group = get_ulysses_sequence_parallel_group() if group is None else group\n    if not group:\n        return x\n    sp_world = get_ulysses_sequence_parallel_world_size(group)\n    x = SeqAllToAll.apply(group, x, head_dim, seq_dim)\n    if unpadded_dim_size and unpadded_dim_size % sp_world != 0:\n        padding_size = x.size(seq_dim) - unpadded_dim_size\n        x = _unpad_tensor(x, seq_dim, padding_size)\n    return x\n\n\ndef gather_heads_scatter_seq(x: Tensor, head_dim: int, seq_dim: int, group: ProcessGroup = None) -> Tensor:\n    \"\"\"\n    A func to sync attention result with alltoall in sequence parallel\n    gather head dimension and scatter seq dim:\n    e.g. seq_dim: 1, head_dim: 2\n    [bsz, seq, h/n, ...] -> [bsz, seq/n, h, ...]\n    \"\"\"\n    group = get_ulysses_sequence_parallel_group() if group is None else group\n    if not group:\n        return x\n    dim_size = x.size(seq_dim)\n    sp_world = get_ulysses_sequence_parallel_world_size(group)\n    if dim_size % sp_world != 0:\n        padding_size = sp_world - (dim_size % sp_world)\n        x = _pad_tensor(x, seq_dim, padding_size)\n    return SeqAllToAll.apply(group, x, seq_dim, head_dim, False)\n\n\ndef _pad_tensor(x: Tensor, dim: int, padding_size: int) -> Tensor:\n    shape = list(x.shape)\n    shape[dim] = padding_size\n    pad = torch.zeros(shape, dtype=x.dtype, device=x.device)\n    return torch.cat([x, pad], dim=dim)\n\n\ndef _unpad_tensor(x: Tensor, dim: int, padding_size: int) -> Tensor:\n    slc = [slice(None)] * len(x.shape)\n    slc[dim] = slice(0, -padding_size)\n    return x[slc]\n\n\ndef slice_input_tensor(x: Tensor, dim: int, padding: bool = True, group: ProcessGroup = None) -> Tensor:\n    group = get_ulysses_sequence_parallel_group() if group is None else group\n    sp_world_size = dist.get_world_size(group)\n    sp_rank = get_ulysses_sequence_parallel_rank()\n    dim_size = x.size(dim)\n    # pad before slice\n    if padding and dim_size % sp_world_size:\n        padding_size = sp_world_size - (dim_size % sp_world_size)\n        x = _pad_tensor(x, dim, padding_size)\n    # slice the input tensor\n    parts = x.size(dim) // sp_world_size\n    slc = [slice(None)] * len(x.shape)\n    slc[dim] = slice(sp_rank * parts, (sp_rank + 1) * parts)\n    return x[slc].contiguous()\n\n\ndef all_to_all_tensor(\n    local_input: Tensor,\n    scatter_dim: int,\n    gather_dim: int,\n    group: Optional[dist.ProcessGroup] = None,\n    async_op: bool = False,\n):\n    group = get_ulysses_sequence_parallel_group() if group is None else group\n    seq_world_size = dist.get_world_size(group)\n    input_list = [t.contiguous() for t in torch.tensor_split(local_input, seq_world_size, scatter_dim)]\n    output_list = [torch.empty_like(input_list[0]) for _ in range(seq_world_size)]\n    comm = dist.all_to_all(output_list, input_list, group=group, async_op=async_op)\n    if async_op:\n\n        def wait():\n            comm.wait()\n            return torch.cat(output_list, dim=gather_dim).contiguous()\n\n        return wait\n    return torch.cat(output_list, dim=gather_dim).contiguous()\n\n\ndef all_gather_tensor(local_tensor: Tensor, group: Optional[dist.ProcessGroup] = None, async_op: bool = False):\n    group = get_ulysses_sequence_parallel_group() if group is None else group\n    sp_world_size = dist.get_world_size(group=group)\n    output_shape = list(local_tensor.shape)\n    output_shape[0] = output_shape[0] * sp_world_size\n    output = torch.empty(output_shape, dtype=local_tensor.dtype, device=local_tensor.device)\n    dist.all_gather_into_tensor(output, local_tensor, group=group, async_op=async_op)\n    return output\n\n\nclass SeqAllToAll(torch.autograd.Function):\n\n    @staticmethod\n    def forward(\n        ctx: Any,\n        group: dist.ProcessGroup,\n        local_input: Tensor,\n        scatter_dim: int,\n        gather_dim: int,\n        async_op: bool = False,\n    ) -> Tensor:\n        ctx.group = group\n        ctx.scatter_dim = scatter_dim\n        ctx.gather_dim = gather_dim\n        ctx.async_op = async_op\n        return all_to_all_tensor(local_input, scatter_dim, gather_dim, group, async_op)\n\n    @staticmethod\n    def backward(ctx: Any, *grad_output: Tensor) -> Tuple[None, Tensor, None, None]:\n        if ctx.async_op:\n            input_t = torch.cat(grad_output[1:], dim=ctx.gather_dim).contiguous()\n        else:\n            input_t = grad_output[0]\n        return (\n            None,\n            all_to_all_tensor(input_t, ctx.gather_dim, ctx.scatter_dim, ctx.group, False),\n            None,\n            None,\n            None,\n            None,\n        )\n\n\nclass Gather(torch.autograd.Function):\n\n    @staticmethod\n    def forward(ctx: Any,\n                group: dist.ProcessGroup,\n                local_tensor: Tensor,\n                gather_dim: int,\n                grad_scaler: bool = True,\n                async_op=False) -> Tensor:\n        ctx.group = group\n        ctx.gather_dim = gather_dim\n        ctx.grad_scaler = grad_scaler\n        ctx.async_op = async_op\n\n        sp_world_size = dist.get_world_size(group=group)\n        ctx.sp_world_size = sp_world_size\n\n        sp_rank = dist.get_rank(group=group)\n        ctx.sp_rank = sp_rank\n\n        local_shape = list(local_tensor.size())\n        split_size = local_shape[0]\n        part_size = local_shape[gather_dim]  # store original size\n        ctx.part_size = part_size\n\n        output = all_gather_tensor(local_tensor, group, async_op)\n        return torch.cat(output.split(split_size, dim=0), dim=gather_dim)\n\n    @staticmethod\n    def backward(ctx: Any, grad_output: Tensor) -> Any:\n        if ctx.grad_scaler:\n            grad_output = grad_output * ctx.sp_world_size\n        return (None, grad_output.split(ctx.part_size,\n                                        dim=ctx.gather_dim)[ctx.sp_rank].contiguous(), None, None, None, None)\n\n\ndef gather_outpus_and_unpad(x: Tensor,\n                            gather_dim: int,\n                            unpad_dim: int = None,\n                            padding_size: int = 0,\n                            grad_scaler: bool = True,\n                            group: Optional[dist.ProcessGroup] = None):\n    group = get_ulysses_sequence_parallel_group() if group is None else group\n    sp_size = get_ulysses_sequence_parallel_world_size()\n    if group == None:\n        return x\n    x = Gather.apply(group, x, gather_dim, grad_scaler)\n    if unpad_dim is not None:\n        assert isinstance(padding_size, int), 'padding size is not given or is not an integer'\n        if padding_size == 0:\n            return x\n        x = _unpad_tensor(x, unpad_dim, padding_size)\n    return x\n\n\ndef ulysses_pad_and_slice_inputs(input_ids_rmpad: torch.Tensor,\n                                 position_ids_rmpad: Optional[torch.Tensor] = None,\n                                 sp_size: int = 1):\n    \"\"\"\n    Pad and slice input_ids to be divisible by sp_size\n    Pad position_ids to be divisible by sp_size.\n\n    Note both input_ids_rmpad and position_ids_rmpad will be padded,\n    but only input_ids will be sliced.\n\n    The is the utility of pre-forward for ulysses sequence parallelism\n\n    Args:\n        input_ids_rmpad: shape of [bsz, seqlen]\n        position_ids_rmpad: shape of [bsz, seqlen], where bsz must be 1\n        sp_size (int): ulysses sequence parallelism size\n\n    Returns:\n        torch.Tensor: padded and sliced input_ids\n        torch.Tensor: padded and sliced position_ids\n        int: pad size \n    \"\"\"\n    if position_ids_rmpad is not None:\n        assert position_ids_rmpad.size(0) == 1\n        assert input_ids_rmpad.size(1) == position_ids_rmpad.size(1)\n    if sp_size <= 1:\n        return input_ids_rmpad, position_ids_rmpad, 0\n    _, total_seq_len = input_ids_rmpad.shape\n    pad_size = (sp_size - total_seq_len % sp_size) % sp_size\n    if pad_size > 0:\n        input_ids_rmpad = torch.nn.functional.pad(input_ids_rmpad, (0, pad_size), value=0)\n        if position_ids_rmpad is not None:\n            pad_pos_ids = torch.arange(pad_size, device=position_ids_rmpad.device).unsqueeze(0)\n            position_ids_rmpad = torch.cat((position_ids_rmpad, pad_pos_ids), dim=-1)\n    # we don't need to slice position ids\n    input_ids_rmpad = slice_input_tensor(input_ids_rmpad, dim=1, padding=False)\n    return input_ids_rmpad, position_ids_rmpad, pad_size\n"
  },
  {
    "path": "verl/version/version",
    "content": "0.2.0.dev\n"
  },
  {
    "path": "verl/workers/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"
  },
  {
    "path": "verl/workers/actor/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .base import BasePPOActor\nfrom .dp_actor import DataParallelPPOActor\n\n__all__ = [\"BasePPOActor\", \"DataParallelPPOActor\"]\n"
  },
  {
    "path": "verl/workers/actor/base.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe base class for Actor\n\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import Iterable, Dict\n\nfrom verl import DataProto\nimport torch\n\n__all__ = ['BasePPOActor']\n\n\nclass BasePPOActor(ABC):\n\n    def __init__(self, config):\n        \"\"\"The base class for PPO actor\n\n        Args:\n            config (DictConfig): a config passed to the PPOActor. We expect the type to be\n                DictConfig (https://omegaconf.readthedocs.io/), but it can be any namedtuple in general.\n        \"\"\"\n        super().__init__()\n        self.config = config\n\n    @abstractmethod\n    def compute_log_prob(self, data: DataProto) -> torch.Tensor:\n        \"\"\"Compute logits given a batch of data.\n\n        Args:\n            data (DataProto): a batch of data represented by DataProto. It must contain key ```input_ids```,\n                ```attention_mask``` and ```position_ids```.\n\n        Returns:\n            DataProto: a DataProto containing the key ```log_probs```\n\n\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def update_policy(self, data: DataProto) -> Dict:\n        \"\"\"Update the policy with an iterator of DataProto\n\n        Args:\n            data (DataProto): an iterator over the DataProto that returns by\n                ```make_minibatch_iterator```\n\n        Returns:\n            Dict: a dictionary contains anything. Typically, it contains the statistics during updating the model\n            such as ```loss```, ```grad_norm```, etc,.\n\n        \"\"\"\n        pass\n"
  },
  {
    "path": "verl/workers/actor/dp_actor.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nSingle Process Actor\n\"\"\"\n\nimport itertools\nfrom typing import Iterable, Tuple\n\nimport torch\nfrom torch import nn\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP\n\nfrom verl import DataProto\nfrom verl.trainer.ppo import core_algos\nfrom verl.workers.actor import BasePPOActor\nfrom verl.utils.py_functional import append_to_dict\nfrom verl.utils.torch_functional import logprobs_from_logits, masked_mean\nfrom verl.utils.ulysses import ulysses_pad_and_slice_inputs, gather_outpus_and_unpad\nfrom verl.utils.seqlen_balancing import rearrange_micro_batches, get_reverse_idx\nimport verl.utils.torch_functional as verl_F\n\nfrom flash_attn.bert_padding import pad_input, unpad_input, rearrange, index_first_axis\n\n__all__ = ['DataParallelPPOActor']\n\n\nclass DataParallelPPOActor(BasePPOActor):\n\n    def __init__(\n        self,\n        config,\n        actor_module: nn.Module,\n        actor_optimizer: torch.optim.Optimizer = None,\n    ):\n        \"\"\"When optimizer is None, it is Reference Policy\"\"\"\n        super().__init__(config)\n        self.actor_module = actor_module\n        self.actor_optimizer = actor_optimizer\n        self.use_remove_padding = self.config.get('use_remove_padding', False)\n        print(f'Actor use_remove_padding={self.use_remove_padding}')\n        self.ulysses_sequence_parallel_size = self.config.ulysses_sequence_parallel_size\n        self.use_ulysses_sp = self.ulysses_sequence_parallel_size > 1\n\n        self.compute_entropy_from_logits = torch.compile(verl_F.entropy_from_logits, dynamic=True)\n\n    def _forward_micro_batch(self, micro_batch, temperature) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Returns: \n            entropy: # (bs, response_len)\n            log_probs: # (bs, response_len)\n        \"\"\"\n        response_length = micro_batch['responses'].size(-1)\n        multi_modal_inputs = {}\n        if 'multi_modal_inputs' in micro_batch:\n            for key in micro_batch['multi_modal_inputs'][0].keys():\n                multi_modal_inputs[key] = torch.cat([inputs[key] for inputs in micro_batch['multi_modal_inputs']],\n                                                    dim=0)\n\n        with torch.autocast(device_type='cuda', dtype=torch.bfloat16):\n            input_ids = micro_batch['input_ids']\n            batch_size, seqlen = input_ids.shape\n            attention_mask = micro_batch['attention_mask']\n            position_ids = micro_batch['position_ids']\n            if position_ids.dim() == 3:  # qwen2vl mrope\n                position_ids = position_ids.transpose(0, 1)  # (bsz, 3, seqlen) -> (3, bsz, seqlen)\n\n            if self.use_remove_padding:\n                input_ids_rmpad, indices, *_ = unpad_input(input_ids.unsqueeze(-1),\n                                                           attention_mask)  # input_ids_rmpad (total_nnz, ...)\n                input_ids_rmpad = input_ids_rmpad.transpose(0, 1)  # (1, total_nnz)\n\n                # unpad the position_ids to align the rotary\n                if position_ids.dim() == 3:\n                    position_ids_rmpad = index_first_axis(rearrange(position_ids, \"c b s ... -> (b s) c ...\"),\n                                                          indices).transpose(0, 1).unsqueeze(\n                                                              1)  # (3, bsz, seqlen) -> (3, 1, bsz * seqlen)\n                else:\n                    position_ids_rmpad = index_first_axis(rearrange(position_ids.unsqueeze(-1), \"b s ... -> (b s) ...\"),\n                                                          indices).transpose(0, 1)\n\n                # for compute the log_prob\n                input_ids_rmpad_rolled = torch.roll(input_ids_rmpad, shifts=-1, dims=1)  # (1, total_nnz)\n\n                # pad and slice the inputs if sp > 1\n                if self.use_ulysses_sp:\n                    input_ids_rmpad, position_ids_rmpad, pad_size = ulysses_pad_and_slice_inputs(input_ids_rmpad, \\\n                                                                                                position_ids_rmpad, \\\n                                                                                                sp_size=self.ulysses_sequence_parallel_size)\n                    input_ids_rmpad_rolled, _, _ = ulysses_pad_and_slice_inputs(input_ids_rmpad_rolled, None,\n                                                                                self.ulysses_sequence_parallel_size)\n\n                input_ids_rmpad_rolled = input_ids_rmpad_rolled.squeeze(0)  # ((total_nnz / sp) + pad)\n\n                # only pass input_ids and position_ids to enable flash_attn_varlen\n                output = self.actor_module(input_ids=input_ids_rmpad,\n                                           attention_mask=None,\n                                           position_ids=position_ids_rmpad,\n                                           **multi_modal_inputs,\n                                           use_cache=False)  # prevent model thinks we are generating\n                logits_rmpad = output.logits.squeeze(0)  # (total_nnz, vocab_size)\n\n                logits_rmpad.div_(temperature)\n\n                # compute entropy\n                entropy_rmpad = self.compute_entropy_from_logits(logits_rmpad)  # ((total_nnz / sp) + pad)\n\n                # if use_sp: ((total_nnz / sp) + pad) ; if not use_sp: (batch, seqlen)\n                log_probs = logprobs_from_logits(logits=logits_rmpad, labels=input_ids_rmpad_rolled)\n\n                # gather log_prob if sp > 1\n                if self.use_ulysses_sp:\n                    # gather and unpad for the ulysses sp\n                    log_probs = gather_outpus_and_unpad(log_probs, gather_dim=0, unpad_dim=0, padding_size=pad_size)\n                    entropy_rmpad = gather_outpus_and_unpad(entropy_rmpad,\n                                                            gather_dim=0,\n                                                            unpad_dim=0,\n                                                            padding_size=pad_size)\n                # pad back to (bsz, seqlen)\n                full_entropy = pad_input(hidden_states=entropy_rmpad.unsqueeze(-1),\n                                         indices=indices,\n                                         batch=batch_size,\n                                         seqlen=seqlen)\n                full_log_probs = pad_input(hidden_states=log_probs.unsqueeze(-1),\n                                           indices=indices,\n                                           batch=batch_size,\n                                           seqlen=seqlen)\n\n                # only return response part:\n                entropy = full_entropy.squeeze(-1)[:, -response_length - 1:-1]  # (bsz, response_length)\n                log_probs = full_log_probs.squeeze(-1)[:, -response_length - 1:-1]  # (bsz, response_length)\n\n            else:  # not using rmpad and no ulysses sp\n                output = self.actor_module(input_ids=input_ids,\n                                           attention_mask=attention_mask,\n                                           position_ids=position_ids,\n                                           **multi_modal_inputs,\n                                           use_cache=False)  # prevent model thinks we are generating\n                logits = output.logits\n                logits.div_(temperature)\n                logits = logits[:, -response_length - 1:-1, :]  # (bsz, response_length, vocab_size)\n                log_probs = logprobs_from_logits(logits, micro_batch['responses'])\n                entropy = verl_F.entropy_from_logits(logits)  # (bsz, response_length)\n\n            return entropy, log_probs\n\n    def _optimizer_step(self):\n        assert self.config.grad_clip is not None\n\n        if isinstance(self.actor_module, FSDP):\n            grad_norm = self.actor_module.clip_grad_norm_(max_norm=self.config.grad_clip)\n        else:\n            grad_norm = torch.nn.utils.clip_grad_norm_(self.actor_module.parameters(), max_norm=self.config.grad_clip)\n        self.actor_optimizer.step()\n        return grad_norm\n\n    def compute_log_prob(self, data: DataProto) -> torch.Tensor:\n        \"\"\"Compute the log probability of the responses given input_ids, attention_mask and position_ids\n\n        Args:\n            data (DataProto): a DataProto containing keys\n\n                ``input_ids``: tensor of shape [batch_size, sequence_length]. torch.int64. Note that input_ids is the\n                concatenation of prompt and response. Note that ``sequence_length = prompt_length + response_length``.\n\n                ``attention_mask``: tensor of shape [batch_size, sequence_length]. torch.int64.\n\n                ``position_ids``: tensor of shape [batch_size, sequence_length]. torch.int64.\n\n                ``responses``:  tensor of shape [batch_size, response_length]. torch.int64.\n\n        Returns:\n            torch.Tensor: the log_prob tensor\n        \"\"\"\n        # set to eval\n        self.actor_module.eval()\n\n        micro_batch_size = data.meta_info['micro_batch_size']\n        temperature = data.meta_info['temperature']  # temperature must be in the data.meta_info to avoid slient error\n        use_dynamic_bsz = data.meta_info['use_dynamic_bsz']\n\n        select_keys = ['responses', 'input_ids', 'attention_mask', 'position_ids']\n        batch = data.select(batch_keys=select_keys).batch\n        has_multi_modal_inputs = 'multi_modal_inputs' in data.non_tensor_batch.keys()\n\n        if has_multi_modal_inputs:\n            num_micro_batches = data.batch.batch_size[0] // micro_batch_size\n            non_tensor_select_keys = ['multi_modal_inputs']\n            micro_batches = data.select(select_keys, non_tensor_select_keys).chunk(num_micro_batches)\n        elif use_dynamic_bsz:\n            # split using dynamic bsz\n            max_token_len = data.meta_info['max_token_len'] * self.ulysses_sequence_parallel_size\n            micro_batches, indices = rearrange_micro_batches(batch=batch, max_token_len=max_token_len)\n        else:\n            micro_batches = batch.split(micro_batch_size)\n\n        log_probs_lst = []\n        for micro_batch in micro_batches:\n            if isinstance(micro_batch, DataProto):\n                micro_batch = {**micro_batch.batch, **micro_batch.non_tensor_batch}\n\n            with torch.no_grad():\n                _, log_probs = self._forward_micro_batch(micro_batch, temperature=temperature)\n            log_probs_lst.append(log_probs)\n        log_probs = torch.concat(log_probs_lst, dim=0)\n\n        if use_dynamic_bsz:\n            indices = list(itertools.chain.from_iterable(indices))\n            assert len(indices) == log_probs.size(0), f\"{len(indices)} vs. {log_probs.size()}\"\n            revert_indices = torch.tensor(get_reverse_idx(indices), dtype=torch.long)\n            log_probs = log_probs[revert_indices]\n\n        return log_probs\n\n    def update_policy(self, data: DataProto):\n        # make sure we are in training mode\n        self.actor_module.train()\n\n        temperature = data.meta_info['temperature']  # temperature must be in the data.meta_info to avoid slient error\n\n        select_keys = ['responses', 'input_ids', 'attention_mask', 'tool_output_masks', 'position_ids', 'old_log_probs', 'advantages']\n        if self.config.use_kl_loss:\n            select_keys.append('ref_log_prob')\n        batch = data.select(batch_keys=select_keys).batch\n        has_multi_modal_inputs = 'multi_modal_inputs' in data.non_tensor_batch.keys()\n\n        # Split to make minibatch iterator for updating the actor\n        # See PPO paper for details. https://arxiv.org/abs/1707.06347\n        if has_multi_modal_inputs:\n            num_mini_batches = data.batch.batch_size[0] // self.config.ppo_mini_batch_size\n            non_tensor_select_keys = ['multi_modal_inputs']\n            dataloader = data.select(select_keys, non_tensor_select_keys).chunk(num_mini_batches)\n        else:\n            dataloader = batch.split(self.config.ppo_mini_batch_size)\n\n        metrics = {}\n        for epoch in range(self.config.ppo_epochs):\n            for batch_idx, data in enumerate(dataloader):\n                # split batch into micro_batches\n                mini_batch = data\n                if has_multi_modal_inputs:\n                    self.gradient_accumulation = self.config.ppo_mini_batch_size // self.config.ppo_micro_batch_size_per_gpu\n                    num_micro_batches = mini_batch.batch.batch_size[0] // self.config.ppo_micro_batch_size_per_gpu\n                    micro_batches = data.select(select_keys, non_tensor_select_keys).chunk(num_micro_batches)\n                elif self.config.use_dynamic_bsz:\n                    max_token_len = self.config.ppo_max_token_len_per_gpu * self.ulysses_sequence_parallel_size\n                    micro_batches, _ = rearrange_micro_batches(batch=mini_batch, max_token_len=max_token_len)\n                else:\n                    self.gradient_accumulation = self.config.ppo_mini_batch_size // self.config.ppo_micro_batch_size_per_gpu\n                    # split batch into micro_batches\n                    micro_batches = mini_batch.split(self.config.ppo_micro_batch_size_per_gpu)\n\n                self.actor_optimizer.zero_grad()\n\n                for data in micro_batches:\n                    if isinstance(data, DataProto):\n                        data = {**data.batch.cuda(), **data.non_tensor_batch}\n                    else:\n                        data = data.cuda()  # actor device is cpu when using offload\n\n                    responses = data['responses']\n                    response_length = responses.size(1)\n                    attention_mask = data['attention_mask']\n                    tool_output_masks = data['tool_output_masks'] if 'tool_output_masks' in data else None\n                    response_mask = attention_mask[:, -response_length:]\n                    response_mask = response_mask & tool_output_masks\n                    old_log_prob = data['old_log_probs']\n                    advantages = data['advantages']\n\n                    clip_ratio = self.config.clip_ratio\n                    entropy_coeff = self.config.entropy_coeff\n\n                    # all return: (bsz, response_length)\n                    entropy, log_prob = self._forward_micro_batch(micro_batch=data, temperature=temperature)\n\n                    pg_loss, pg_clipfrac, ppo_kl = core_algos.compute_policy_loss(old_log_prob=old_log_prob,\n                                                                                  log_prob=log_prob,\n                                                                                  advantages=advantages,\n                                                                                  eos_mask=response_mask,\n                                                                                  cliprange=clip_ratio)\n                    # compute entropy loss from entropy\n                    entropy_loss = verl_F.masked_mean(entropy, response_mask)\n\n                    # compute policy loss\n                    policy_loss = pg_loss - entropy_loss * entropy_coeff\n\n                    if self.config.use_kl_loss:\n                        ref_log_prob = data['ref_log_prob']\n                        # compute kl loss\n                        kld = core_algos.kl_penalty(logprob=log_prob,\n                                                    ref_logprob=ref_log_prob,\n                                                    kl_penalty=self.config.kl_loss_type)\n                        kl_loss = masked_mean(kld, response_mask)\n\n                        policy_loss = policy_loss + kl_loss * self.config.kl_loss_coef\n                        metrics['actor/kl_loss'] = kl_loss.detach().item()\n                        metrics['actor/kl_coef'] = self.config.kl_loss_coef\n\n                    if self.config.use_dynamic_bsz:\n                        # relative to the dynamic bsz\n                        loss = policy_loss * (len(data) / self.config.ppo_mini_batch_size)\n                    else:\n                        loss = policy_loss / self.gradient_accumulation\n                    loss.backward()\n\n                    data = {\n                        'actor/entropy_loss': entropy_loss.detach().item(),\n                        'actor/pg_loss': pg_loss.detach().item(),\n                        'actor/pg_clipfrac': pg_clipfrac.detach().item(),\n                        'actor/ppo_kl': ppo_kl.detach().item(),\n                    }\n                    append_to_dict(metrics, data)\n\n                grad_norm = self._optimizer_step()\n                data = {'actor/grad_norm': grad_norm.detach().item()}\n            append_to_dict(metrics, data)\n        self.actor_optimizer.zero_grad()\n        return metrics\n"
  },
  {
    "path": "verl/workers/actor/megatron_actor.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nMegatron Actor.\nIn megatron actor, the differences are:\n1. We only make minibatch\n\nNote that our model doesn't have to be `MegatronModule` because we don't share embedding in the last layer\n\"\"\"\n\nimport importlib\nfrom functools import partial\nfrom packaging.version import Version\nfrom typing import Iterable, Dict\n\nimport torch\nfrom torch import nn\nimport torch.distributed\n# from megatron import get_args\nfrom megatron.core.optimizer import OptimizerConfig\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core import ModelParallelConfig\nfrom verl.utils.megatron_utils import get_model_config\nfrom megatron.core.pipeline_parallel import get_forward_backward_func\n\nfrom megatron.core.distributed import finalize_model_grads\n# from megatron.core.optimizer import DistributedOptimizer\n\nfrom megatron.core.optimizer import DistributedOptimizer\n\nfrom omegaconf import OmegaConf\nfrom verl.utils.megatron.tensor_parallel import vocab_parallel_compute_entropy_loss, vocab_parallel_log_probs_from_logits\nfrom verl.utils.megatron.pipeline_parallel import (compute_transformers_input_shapes, make_batch_generator)\nfrom verl import DataProto\nfrom verl.trainer.ppo import core_algos\nfrom verl.workers.actor import BasePPOActor\nfrom verl.utils.py_functional import append_to_dict\nfrom verl.utils.torch_functional import logprobs_from_logits, broadcast_dict_tensor, split_dict_tensor_into_batches\n\n__all__ = ['MegatronPPOActor']\n\n\nclass MegatronPPOActor(BasePPOActor):\n\n    def __init__(self, config, model_config, megatron_config: ModelParallelConfig, actor_module: nn.ModuleList,\n                 actor_optimizer: DistributedOptimizer, actor_optimizer_config: OptimizerConfig):\n        \"\"\"MeagtronPPOActor class. This class implements the simple PPO logics when the model is built with Megatron.\n\n        Args:\n            config (OmegaConf): the basic config that contains the hyper-parameters of PPO Actor. It must contain\n\n                ``ppo_micro_batch_size_per_gpu``: micro batch size when updating ppo.\n\n                ``ppo_mini_batch_size``: minibatch size when updating ppo using the batch data.\n\n                ``ppo_epochs``: number of epochs to update the actor using the batch data.\n\n                ``shuffle``: whether to shuffle the data after each ppo epoch.\n\n                ``clip_ratio``: clip ratio of the ppo algorithm. See https://arxiv.org/abs/1707.06347.\n\n                ``entropy_coeff``: entropy coefficient of the PPO loss. See https://arxiv.org/abs/1707.06347.\n            model_config (OmegaConf): model configuration. It must contains ``model_config.vocab_size`` and\n                ``model_config.hidden_size``\n            megatron_config (OmegaConf): megatron configuration. It must contains\n\n                ``sequence_parallel_enabled``: whether the sequence parallel is enabled.\n\n                ``param_dtype``: the dtype of the parameters.\n\n                ``virtual_pipeline_model_parallel_size``: virtual pipeline model parallel size. a.k.a number of chunks in each pp stage.\n            actor_module (nn.ModuleList): actor module is a ModuleList that contains a list of nn.Module in this pp stage.\n                each nn.Module in this rank holds a vpp module chunk. See https://arxiv.org/pdf/2104.04473.pdf for more details.\n                The actor module has some constraints to follow in order to use the updating logics implemented here\n\n                1. It must implement unpad_input before any computation and pad_input after all the computation. Remove padding is an\n                optimization that removes the padding tokens. See unpad_input and pad_input function in flash-attn\n                (https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/bert_padding.py).\n\n                2. Each pp stage must return the hidden state with the same shape [total_nnz, 1, hidden_size],\n                where total_nnz is the number of valid tokens in this batch. If sequence parallel is enabled, the size\n                of the hidden state is [total_nnz // tp, 1, hidden_size].\n            actor_optimizer (DistributedOptimizer): currently, we only support DistributedOptimizer in Megatron. It implements\n                zero1 optimizer that shards the optimizer state across dp ranks.\n\n        >>> def megatron_actor_model_provider(pre_process, post_process):\n        >>>     vpp_rank = mpu.get_virtual_pipeline_model_parallel_rank()\n        >>>     parallel_model = ParallelMistralForCausalLMRmPadPP(config=actor_model_config,\n        >>>                                                        megatron_config=megatron_config,\n        >>>                                                        pre_process=pre_process,\n        >>>                                                        post_process=post_process).cuda()\n        >>>     return parallel_model\n        >>> from megatron.training import get_model\n        >>> from megatron.optimizer import get_megatron_optimizer\n        >>> actor_module = get_model(megatron_actor_model_provider, wrap_with_ddp=True)\n        >>> actor_module = nn.ModuleList(actor_module)\n        >>> actor_optimizer = get_megatron_optimizer(actor_module)\n        >>> actor = MegatronPPOActor(config=config,\n        >>>                          model_config=actor_model_config,\n        >>>                          megatron_config=megatron_config,\n        >>>                          actor_module=actor_module,\n        >>>                          actor_optimizer=actor_optimizer)\n        \"\"\"\n        super().__init__(config)\n        self._validate_config(config)\n        self.model_config = model_config\n        self.megatron_config = megatron_config\n        # self.megatron_args = get_args()\n        self.actor_module = actor_module\n        self.actor_optimizer: DistributedOptimizer = actor_optimizer\n        self.actor_optimizer_config = actor_optimizer_config\n\n        self.optimizer_step_args = OmegaConf.create({\n            'skip_grad': None,\n            'overlap_dp_param_comm': False,\n            'overlap_dp_grad_comm': False,\n            'gradient_accumulation_steps': 1,\n            'sequence_parallel': self.megatron_config.sequence_parallel,\n            'DDP_impl': 'local',\n            'layernorm_allreduce_bucket_threshold': 0,\n            'pipeline_model_parallel_split_rank': None,\n            'reduce_grads_use_alltoall': False\n        })\n\n        config = get_model_config(self.actor_module[0])\n        config.finalize_model_grads_func = finalize_model_grads\n\n    def _validate_config(self, config) -> None:\n        \"\"\"Validate config options not implemented for Megatron backend\"\"\"\n        assert config.get('ulysses_sequence_parallel_size', 1) == 1\n\n    def compute_log_prob(self, data: DataProto) -> torch.Tensor:\n        \"\"\"Compute the log probability of the responses given input_ids, attention_mask and position_ids\n\n        Args:\n            data (DataProto): a DataProto containing keys\n\n                ``input_ids``: tensor of shape [batch_size, sequence_length]. torch.int64. Note that input_ids is the\n                concatenation of prompt and response. Note that ``sequence_length = prompt_length + response_length``.\n\n                ``attention_mask``: tensor of shape [batch_size, sequence_length]. torch.int64.\n\n                ``position_ids``: tensor of shape [batch_size, sequence_length]. torch.int64.\n\n                ``responses``:  tensor of shape [batch_size, response_length]. torch.int64.\n\n        Returns:\n            DataProto: torch.Tensor: the log_prob tensor\n        \"\"\"\n        data.batch = data.batch.contiguous()\n\n        def compute_logprobs_fn(output, data):\n            response = data['responses']\n            response_length = response.size(1)\n            logits = output['logits']\n            logits = logits[:, -response_length - 1:-1].contiguous()\n            log_probs = vocab_parallel_log_probs_from_logits(logits, response)\n            return {'log_probs': log_probs}\n\n        # We make recompute_old_log_prob by default here.\n        # TODO (zhangchi.usc1992): actually, this function should only return log_prob and this logic should be handled by user outside\n        recompute_old_log_prob = self.config.get('recompute_old_log_prob', True)\n\n        if recompute_old_log_prob or 'old_log_probs' not in data.batch.keys():\n            select_keys = ['responses', 'input_ids', 'attention_mask', 'position_ids']\n            batch = data.select(batch_keys=select_keys).batch\n            input_ids = batch['input_ids']\n            batch_size = input_ids.size(0)\n            response = batch['responses']\n            response_length = response.size(1)\n            with torch.no_grad():\n                output = self.forward_backward_batch(data, forward_only=True, post_process_fn=compute_logprobs_fn)\n                if mpu.is_pipeline_last_stage(ignore_virtual=True):\n                    # only on last rank. It should be on every tp rank\n                    log_probs = torch.cat([o['log_probs'] for o in output], dim=0)  # (bs, seq_size)\n                    log_probs = log_probs.to(torch.float32)\n                else:\n                    log_probs = torch.empty(size=(batch_size, response_length),\n                                            dtype=torch.float32,\n                                            device=input_ids.device)\n\n                # broadcast across pp ranks\n                torch.distributed.broadcast(tensor=log_probs,\n                                            src=mpu.get_pipeline_model_parallel_last_rank(),\n                                            group=mpu.get_pipeline_model_parallel_group(),\n                                            async_op=False)\n\n        # add empty cache after each compute\n        torch.cuda.empty_cache()\n\n        return log_probs\n\n    def make_minibatch_iterator(self, data: DataProto) -> Iterable[DataProto]:\n        \"\"\"Make minibatch iterator for updating the actor\n\n        Args:\n            data (DataProto): a DataProto containing keys\n\n                ``input_ids``: tensor of shape [batch_size, sequence_length]. torch.int64, where ``sequence_length = prompt_length + response_length``\n\n                ``attention_mask``: tensor of shape [batch_size, sequence_length]. torch.int64\n\n                ``position_ids``: tensor of shape [batch_size, sequence_length]. torch.int64\n\n                ``responses``: tensor of shape [batch_size, response_length]. torch.int64. Note that responses = input_ids[:, -response_length:]\n\n                ``old_log_probs``: tensor of shape [batch_size, response_length]. torch.float32. The log probability of responses.\n\n                ``advantages``: tensor of shape [batch_size, response_length]. torch.float32. The advantages of responses.\n                See PPO paper for details. https://arxiv.org/abs/1707.06347\n\n        Returns:\n\n        \"\"\"\n        select_keys = ['responses', 'input_ids', 'attention_mask', 'position_ids', 'old_log_probs', 'advantages']\n        data = data.select(batch_keys=select_keys)\n        return data.make_iterator(mini_batch_size=self.config.ppo_mini_batch_size,\n                                  epochs=self.config.ppo_epochs,\n                                  dataloader_kwargs={'shuffle': self.config.shuffle})\n\n    def forward_backward_batch(self, data: DataProto, forward_only=False, post_process_fn=None):\n        \"\"\"\n        We assume:\n        - The model takes input: (input_ids, attention_mask, position_ids). No rmpad for the input\n        - The communication shape is (total_nnz_pad_to_sp // tp_size, 1, hidden_size) if sequence parallel is enabled\n        \"\"\"\n        # broadcast from last pp rank to all other pp ranks\n        # TODO: actually, we just need to control the sampling order.\n        broadcast_dict_tensor(data.batch,\n                              src=mpu.get_pipeline_model_parallel_last_rank(),\n                              group=mpu.get_pipeline_model_parallel_group())\n        # split into micro-batches\n        data.batch['attention_mask'] = data.batch['attention_mask'].to(bool)\n\n        if data.meta_info.get('micro_batch_size', None) is not None:\n            batch_size = data.meta_info['micro_batch_size']\n        else:\n            batch_size = self.config.ppo_micro_batch_size_per_gpu\n        batches = split_dict_tensor_into_batches(data.batch, batch_size=batch_size)\n        # compute input shapes for pp stages\n        input_shapes = compute_transformers_input_shapes(\n            batches,\n            meta_info={\n                'sequence_parallel': self.megatron_config.sequence_parallel,\n                'hidden_size': self.model_config.hidden_size\n            })\n        n_micro_batch = len(batches)\n        seq_len = batches[0]['input_ids'].shape[1]\n\n        forward_backward_func = get_forward_backward_func()\n\n        def loss_func(output, data, meta_info):\n            if forward_only:\n                if post_process_fn is None:\n                    return 1.0, {'logits': output.logits}\n                else:\n                    return 1.0, post_process_fn(output, data)\n\n            responses = data['responses']\n            response_length = responses.size(1)\n            attention_mask = data['attention_mask']\n            response_mask = attention_mask[:, -response_length:]\n            old_log_prob = data['old_log_probs']\n            advantages = data['advantages']\n\n            clip_ratio = meta_info['clip_ratio']\n            entropy_coeff = meta_info['entropy_coeff']\n\n            # compute policy loss\n            logits = output.logits\n            logits = logits[:, -response_length - 1:-1].contiguous()\n            logits_back = logits.clone()\n            log_prob = vocab_parallel_log_probs_from_logits(logits, responses)\n            logits = logits_back\n            pg_loss, pg_clipfrac, ppo_kl = core_algos.compute_policy_loss(old_log_prob=old_log_prob,\n                                                                          log_prob=log_prob,\n                                                                          advantages=advantages,\n                                                                          eos_mask=response_mask,\n                                                                          cliprange=clip_ratio)\n            entropy_loss = vocab_parallel_compute_entropy_loss(logits, eos_mask=response_mask)\n            policy_loss = pg_loss - entropy_loss * entropy_coeff\n            # return loss and stats\n            stats = {\n                'actor/entropy_loss': entropy_loss.detach().item(),\n                'actor/pg_loss': pg_loss.detach().item(),\n                'actor/pg_clipfrac': pg_clipfrac.detach().item(),\n                'actor/ppo_kl': ppo_kl.detach().item()\n            }\n            return policy_loss, stats\n\n        def forward_step(batch_iter, model):\n            batch = next(batch_iter)\n            input_ids = batch['input_ids']\n            attention_mask = batch['attention_mask']\n            position_ids = batch['position_ids']\n            output = model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids)\n            if forward_only:\n                meta_info = None\n            else:\n                meta_info = {'clip_ratio': self.config.clip_ratio, 'entropy_coeff': self.config.entropy_coeff}\n            return output, partial(loss_func, data=batch, meta_info=meta_info)\n\n        # batch should be a list of batches inside micro-batches\n        batch_generator = make_batch_generator(batches, vpp_size=len(self.actor_module))\n\n        # TODO: we may use the new schedule instead\n        # for flash-attn: (seq_len, batch_size, hidden_size) = (mbs*seq_len, 1, hidden_size)\n        if mpu.get_pipeline_model_parallel_world_size() > 1:\n            losses_reduced = forward_backward_func(\n                forward_step_func=forward_step,\n                data_iterator=batch_generator,\n                model=self.actor_module,\n                num_microbatches=n_micro_batch,\n                seq_length=batch_size * seq_len,  # no use when input_shapes was set\n                micro_batch_size=1,  # no use when input_shapes was set\n                forward_only=forward_only,\n            )\n        else:\n            losses_reduced = forward_backward_func(\n                forward_step_func=forward_step,\n                data_iterator=batch_generator,\n                model=self.actor_module,\n                num_microbatches=n_micro_batch,\n                seq_length=batch_size * seq_len,  # in use for pp = 1\n                micro_batch_size=1,  # in use for pp = 1\n                forward_only=forward_only,\n            )\n        # loss_reduces contains the stats returned from loss_func\n        return losses_reduced\n\n    def update_policy(self, dataloader: Iterable[DataProto]) -> Dict:\n        \"\"\"Update the policy with an iterator of DataProto\n\n        Args:\n            dataloader (Iterable[DataProto]): an iterator over the DataProto that returns by ``make_minibatch_iterator``\n                The keys of each data batch is described in the make_minibatch_iterator.\n\n        Returns:\n            Dict: a dictionary containing the statistics. Note that the statistics are only valid in the last pp stage\n            and users have to combine the output in each dp rank manually.\n\n        \"\"\"\n        metrics = {}\n        for data in dataloader:\n            # data = data.batch.to(self.actor_module.device)\n            self.actor_optimizer.zero_grad()\n            # use use_contiguous_buffers_in_local_ddp and no overlap_dp_param_comm\n            for chunk in self.actor_module:\n                # if use distributed optimizer, zero grad buffer will be handled by optimizer\n                chunk.zero_grad_buffer()\n\n            metric_micro_batch = self.forward_backward_batch(data)\n            for metric in metric_micro_batch:\n                append_to_dict(metrics, metric)  # append the metric from this micro-batch to global metrics.\n\n            update_successful, grad_norm, num_zeros_in_grad = self.actor_optimizer.step()\n\n            if update_successful:\n                # allgather already execute in optimizer.step in new megatron\n                pass\n            else:\n                raise NotImplementedError\n\n        # add empty cache after each compute\n        torch.cuda.empty_cache()\n\n        return metrics\n"
  },
  {
    "path": "verl/workers/critic/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .base import BasePPOCritic\nfrom .dp_critic import DataParallelPPOCritic\n\n__all__ = [\"BasePPOCritic\", \"DataParallelPPOCritic\"]\n"
  },
  {
    "path": "verl/workers/critic/base.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nBase class for a critic\n\"\"\"\nfrom abc import ABC, abstractmethod\n\nimport torch\n\nfrom verl import DataProto\n\n__all__ = ['BasePPOCritic']\n\n\nclass BasePPOCritic(ABC):\n\n    def __init__(self, config):\n        super().__init__()\n        self.config = config\n\n    @abstractmethod\n    def compute_values(self, data: DataProto) -> torch.Tensor:\n        \"\"\"Compute values\"\"\"\n        pass\n\n    @abstractmethod\n    def update_critic(self, data: DataProto):\n        \"\"\"Update the critic\"\"\"\n        pass\n"
  },
  {
    "path": "verl/workers/critic/dp_critic.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nImplement a multiprocess PPOCritic\n\"\"\"\nimport itertools\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed\nfrom torch import nn, optim\n\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP\n\nfrom verl import DataProto\nfrom verl.trainer.ppo import core_algos\nfrom verl.workers.critic import BasePPOCritic\nfrom verl.utils.py_functional import append_to_dict\nfrom verl.utils.torch_functional import masked_mean\nfrom verl.utils.ulysses import ulysses_pad_and_slice_inputs, gather_outpus_and_unpad\nfrom verl.utils.seqlen_balancing import rearrange_micro_batches, get_reverse_idx\n\nfrom flash_attn.bert_padding import pad_input, unpad_input, rearrange, index_first_axis\n\n__all__ = ['DataParallelPPOCritic']\n\n\nclass DataParallelPPOCritic(BasePPOCritic):\n\n    def __init__(self, config, critic_module: nn.Module, critic_optimizer: optim.Optimizer):\n        super().__init__(config=config)\n        self.critic_module = critic_module\n        self.critic_optimizer = critic_optimizer\n        self.use_remove_padding = self.config.model.get('use_remove_padding', False)\n        print(f'Critic use_remove_padding={self.use_remove_padding}')\n\n        self.ulysses_sequence_parallel_size = self.config.get('ulysses_sequence_parallel_size', 1)\n\n    def _forward_micro_batch(self, micro_batch):\n        response_length = micro_batch['responses'].size(-1)\n        multi_modal_inputs = {}\n        if 'multi_modal_inputs' in micro_batch:\n            for key in micro_batch['multi_modal_inputs'][0].keys():\n                multi_modal_inputs[key] = torch.cat([inputs[key] for inputs in micro_batch['multi_modal_inputs']],\n                                                    dim=0)\n\n        with torch.autocast(device_type='cuda', dtype=torch.bfloat16):\n            input_ids = micro_batch['input_ids']\n            batch, seqlen = input_ids.shape\n            attention_mask = micro_batch['attention_mask']\n            position_ids = micro_batch['position_ids']\n            if position_ids.dim() == 3:  # qwen2vl mrope\n                position_ids = position_ids.transpose(0, 1)\n\n            if self.use_remove_padding:\n                input_ids_rmpad, indices, *_ = unpad_input(input_ids.unsqueeze(-1),\n                                                           attention_mask)  # input_ids_rmpad (total_nnz, ...)\n                input_ids_rmpad = input_ids_rmpad.transpose(0, 1)  # (1, total_nnz)\n\n                # unpad the position_ids to align the rotary\n                if position_ids.dim() == 3:\n                    position_ids_rmpad = index_first_axis(rearrange(position_ids, \"c b s ... -> (b s) c ...\"),\n                                                          indices).transpose(0, 1).unsqueeze(\n                                                              1)  # (3, bsz, seqlen) -> (3, 1, bsz * seqlen)\n                else:\n                    position_ids_rmpad = index_first_axis(rearrange(position_ids.unsqueeze(-1), \"b s ... -> (b s) ...\"),\n                                                          indices).transpose(0, 1)\n\n                # pad and slice the inputs if sp > 1\n                if self.ulysses_sequence_parallel_size > 1:\n                    input_ids_rmpad, position_ids_rmpad, pad_size = ulysses_pad_and_slice_inputs(input_ids_rmpad, \\\n                                                                                                position_ids_rmpad, \\\n                                                                                                sp_size=self.ulysses_sequence_parallel_size)\n\n                # only pass input_ids and position_ids to enable flash_attn_varlen\n                output = self.critic_module(input_ids=input_ids_rmpad,\n                                            attention_mask=None,\n                                            position_ids=position_ids_rmpad,\n                                            **multi_modal_inputs,\n                                            use_cache=False)  # prevent model thinks we are generating\n                values_rmpad = output.logits\n                values_rmpad = values_rmpad.squeeze(0)  # (total_nnz)\n\n                # gather output if sp > 1\n                if self.ulysses_sequence_parallel_size > 1:\n                    values_rmpad = gather_outpus_and_unpad(values_rmpad,\n                                                           gather_dim=0,\n                                                           unpad_dim=0,\n                                                           padding_size=pad_size)\n\n                # pad it back\n                values = pad_input(values_rmpad, indices=indices, batch=batch, seqlen=seqlen).squeeze(-1)\n                values = values[:, -response_length - 1:-1]\n            else:\n                output = self.critic_module(input_ids=input_ids,\n                                            attention_mask=attention_mask,\n                                            position_ids=position_ids,\n                                            **multi_modal_inputs,\n                                            use_cache=False)  # prevent model thinks we are generating\n                values = output.logits\n                values = values[:, -response_length - 1:-1].squeeze(-1)\n            return values\n\n    def _optimizer_step(self):\n        assert self.config.grad_clip is not None\n\n        if isinstance(self.critic_module, FSDP):\n            grad_norm = self.critic_module.clip_grad_norm_(self.config.grad_clip)\n        else:\n            grad_norm = torch.nn.utils.clip_grad_norm_(self.critic_module.parameters(), max_norm=self.config.grad_clip)\n        self.critic_optimizer.step()\n        return grad_norm\n\n    def compute_values(self, data: DataProto) -> torch.Tensor:\n        self.critic_module.eval()\n        micro_batch_size = data.meta_info['micro_batch_size']\n        select_keys = ['responses', 'input_ids', 'attention_mask', 'position_ids']\n        batch = data.select(batch_keys=select_keys).batch\n        use_dynamic_bsz = data.meta_info['use_dynamic_bsz']\n        has_multi_modal_inputs = 'multi_modal_inputs' in data.non_tensor_batch.keys()\n\n        if has_multi_modal_inputs:\n            num_micro_batches = data.batch.batch_size[0] // micro_batch_size\n            non_tensor_select_keys = ['multi_modal_inputs']\n            micro_batches = data.select(select_keys, non_tensor_select_keys).chunk(num_micro_batches)\n        elif use_dynamic_bsz:\n            # split using dynamic bsz\n            max_token_len = data.meta_info['max_token_len'] * self.ulysses_sequence_parallel_size\n            micro_batches, indices = rearrange_micro_batches(batch=batch, max_token_len=max_token_len)\n        else:\n            micro_batches = batch.split(micro_batch_size)\n\n        values_lst = []\n        for micro_batch in micro_batches:\n            if isinstance(micro_batch, DataProto):\n                micro_batch = {**micro_batch.batch, **micro_batch.non_tensor_batch}\n\n            with torch.no_grad():\n                values = self._forward_micro_batch(micro_batch)\n            values_lst.append(values)\n        values = torch.concat(values_lst, dim=0)\n        responses = data.batch['responses']\n        attention_mask = data.batch['attention_mask']\n        response_length = responses.size(1)\n        values = values * attention_mask[:, -response_length - 1:-1]\n\n        if use_dynamic_bsz:\n            indices = list(itertools.chain.from_iterable(indices))\n            assert len(indices) == values.size(0), f\"{len(indices)} vs. {values.size()}\"\n            revert_indices = torch.tensor(get_reverse_idx(indices), dtype=torch.long)\n            values = values[revert_indices]\n\n        return values\n\n    def update_critic(self, data: DataProto):\n        # make sure we are in training mode\n        self.critic_module.train()\n        metrics = {}\n\n        select_keys = ['input_ids', 'responses', 'attention_mask', 'position_ids', 'values', 'returns']\n        batch = data.select(batch_keys=select_keys).batch\n        has_multi_modal_inputs = 'multi_modal_inputs' in data.non_tensor_batch.keys()\n\n        # Split to make minibatch iterator for updating the actor\n        # See PPO paper for details. https://arxiv.org/abs/1707.06347\n        if has_multi_modal_inputs:\n            num_mini_batches = data.batch.batch_size[0] // self.config.ppo_mini_batch_size\n            non_tensor_select_keys = ['multi_modal_inputs']\n            dataloader = data.select(select_keys, non_tensor_select_keys).chunk(num_mini_batches)\n        else:\n            dataloader = batch.split(self.config.ppo_mini_batch_size)\n\n        for epoch in range(self.config.ppo_epochs):\n            for batch_idx, data in enumerate(dataloader):\n                # split batch into micro_batches\n                mini_batch = data\n                if has_multi_modal_inputs:\n                    num_micro_batches = mini_batch.batch.batch_size[0] // self.config.ppo_micro_batch_size_per_gpu\n                    micro_batches = data.select(select_keys, non_tensor_select_keys).chunk(num_micro_batches)\n                elif self.config.use_dynamic_bsz:\n                    max_token_len = self.config.ppo_max_token_len_per_gpu * self.ulysses_sequence_parallel_size\n                    micro_batches, _ = rearrange_micro_batches(batch=mini_batch, max_token_len=max_token_len)\n                else:\n                    micro_batches = mini_batch.split(self.config.ppo_micro_batch_size_per_gpu)\n                    self.gradient_accumulation = self.config.ppo_mini_batch_size // self.config.ppo_micro_batch_size_per_gpu\n\n                self.critic_optimizer.zero_grad()\n\n                for data in micro_batches:\n                    if isinstance(data, DataProto):\n                        data = {**data.batch.cuda(), **data.non_tensor_batch}\n                    else:\n                        data = data.cuda()  # critic device is cpu when using offload\n\n                    input_ids = data['input_ids']\n                    responses = data['responses']\n                    attention_mask = data['attention_mask']\n                    position_ids = data['position_ids']\n                    values = data['values']\n                    returns = data['returns']\n                    response_length = responses.size(1)\n\n                    eos_mask = attention_mask[:, -response_length - 1:-1]\n\n                    vpreds = self._forward_micro_batch(data)\n\n                    # assert not torch.any(torch.isnan(vpreds)).item()\n\n                    vf_loss, vf_clipfrac = core_algos.compute_value_loss(vpreds=vpreds,\n                                                                         values=values,\n                                                                         returns=returns,\n                                                                         eos_mask=eos_mask,\n                                                                         cliprange_value=self.config.cliprange_value)\n                    if self.config.use_dynamic_bsz:\n                        # relative to the dynamic bsz\n                        loss = vf_loss * (len(data) / self.config.ppo_mini_batch_size)\n                    else:\n                        loss = vf_loss / self.gradient_accumulation\n\n                    loss.backward()\n\n                    data = {\n                        'critic/vf_loss': vf_loss.detach().item(),\n                        'critic/vf_clipfrac': vf_clipfrac.detach().item(),\n                        'critic/vpred_mean': masked_mean(vpreds, eos_mask).detach().item(),\n                    }\n\n                    append_to_dict(metrics, data)\n\n                grad_norm = self._optimizer_step()\n                data = {'critic/grad_norm': grad_norm.detach().item()}\n                append_to_dict(metrics, data)\n        self.critic_optimizer.zero_grad()\n        return metrics\n"
  },
  {
    "path": "verl/workers/critic/megatron_critic.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nImplement a multiprocess PPOCritic\n\"\"\"\n\nimport importlib\nfrom functools import partial\nfrom packaging.version import Version\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed\nfrom omegaconf import OmegaConf\nfrom torch import nn\n\nfrom verl import DataProto\nfrom verl.trainer.ppo import core_algos\nfrom verl.workers.critic import BasePPOCritic\nfrom verl.utils.megatron.pipeline_parallel import (compute_transformers_input_shapes, make_batch_generator)\nfrom verl.utils.py_functional import append_to_dict\nfrom verl.utils.torch_dtypes import PrecisionType\nfrom verl.utils.torch_functional import masked_mean, broadcast_dict_tensor, split_dict_tensor_into_batches\nfrom verl.utils.megatron import sequence_parallel as sp_utils\nfrom megatron.core.optimizer import OptimizerConfig\n\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core.pipeline_parallel import get_forward_backward_func\nfrom megatron.core.optimizer import DistributedOptimizer\n\n\nclass MegatronPPOCritic(BasePPOCritic):\n\n    def __init__(self, config, model_config, megatron_config, critic_module: nn.ModuleList,\n                 critic_optimizer: DistributedOptimizer, critic_optimizer_config: OptimizerConfig):\n        super().__init__(config=config)\n        self._validate_config(config)\n        self.model_config = model_config\n        self.megatron_config = megatron_config\n\n        self.critic_module = critic_module\n        self.critic_optimizer = critic_optimizer\n        self.critic_optimizer_config = critic_optimizer_config\n\n        # we create a separate nametuple for optimizer step so that global args won't affect it.\n        self.optimizer_step_args = OmegaConf.create({\n            'skip_grad': None,\n            'overlap_dp_param_comm': False,\n            'overlap_dp_grad_comm': False,\n            'gradient_accumulation_steps': 1,\n            'sequence_parallel': self.megatron_config.sequence_parallel,\n            'DDP_impl': 'local',\n            'layernorm_allreduce_bucket_threshold': 0,\n            'pipeline_model_parallel_split_rank': None,\n            'reduce_grads_use_alltoall': False\n        })\n\n        if self.config.kl_ctrl.type == 'fixed':\n            self.kl_ctrl = core_algos.FixedKLController(kl_coef=self.config.kl_ctrl.kl_coef)\n        elif self.config.kl_ctrl.type == 'adaptive':\n            assert self.config.kl_ctrl.horizon > 0, f'horizon must be larger than 0. Got {self.config.kl_ctrl.horizon}'\n            self.kl_ctrl = core_algos.AdaptiveKLController(init_kl_coef=self.config.kl_ctrl.kl_coef,\n                                                           target_kl=self.config.kl_ctrl.target_kl,\n                                                           horizon=self.config.kl_ctrl.horizon)\n        else:\n            raise NotImplementedError\n\n    def _validate_config(self, config) -> None:\n        \"\"\"Validate config options not implemented for Megatron backend\"\"\"\n        assert config.get('ulysses_sequence_parallel_size', 1) == 1\n\n    def compute_values(self, data: DataProto) -> DataProto:\n        # data.batch = data.batch.to(self.critic_module.module.device)\n        responses = data.batch['responses']\n        attention_mask = data.batch['attention_mask']\n        response_length = responses.size(1)\n        with torch.no_grad():\n            output = self.forward_backward_batch(data=data, forward_only=True)\n            if mpu.is_pipeline_last_stage(ignore_virtual=True):\n                # only on last rank. It should be on every tp rank\n                values = torch.cat([o['vpreds'] for o in output], dim=0)  # (bs, seq_size, vocal_size)\n                values = values.to(torch.float32)\n            else:\n                values = torch.empty_like(attention_mask, dtype=torch.float32)\n\n            # each tp ranks should contain the same value\n            values = values * attention_mask\n            values = values[:, -response_length - 1:-1]\n            values = values.contiguous()\n\n            # sync among pp ranks\n            torch.distributed.broadcast(tensor=values,\n                                        src=mpu.get_pipeline_model_parallel_last_rank(),\n                                        group=mpu.get_pipeline_model_parallel_group())\n\n        # add empty cache after each compute\n        torch.cuda.empty_cache()\n\n        return values\n\n    def make_minibatch_iterator(self, data: DataProto) -> Iterable[DataProto]:\n        select_keys = ['input_ids', 'responses', 'attention_mask', 'position_ids', 'values', 'returns']\n        data = data.select(batch_keys=select_keys)\n        return data.make_iterator(mini_batch_size=self.config.ppo_mini_batch_size,\n                                  epochs=self.config.ppo_epochs,\n                                  dataloader_kwargs={'shuffle': self.config.shuffle})\n\n    def forward_backward_batch(self, data: DataProto, forward_only=False):\n        # broadcast from last pp rank to all other pp ranks\n        data.batch = data.batch.contiguous()\n        broadcast_dict_tensor(data.batch,\n                              src=mpu.get_pipeline_model_parallel_last_rank(),\n                              group=mpu.get_pipeline_model_parallel_group())\n        # split into micro-batches\n        data.batch['attention_mask'] = data.batch['attention_mask'].to(bool)\n        batches = split_dict_tensor_into_batches(data.batch, batch_size=self.config.ppo_micro_batch_size_per_gpu)\n        n_micro_batch = len(batches)\n        seq_len = batches[0]['input_ids'].shape[1]\n\n        # compute input shapes for pp stages\n        input_shapes = compute_transformers_input_shapes(\n            batches,\n            meta_info={\n                'sequence_parallel': self.megatron_config.sequence_parallel,\n                'hidden_size': self.model_config.hidden_size\n            })\n\n        forward_backward_func = get_forward_backward_func()\n\n        def loss_func(output, data, meta_info):\n            if forward_only:\n                return 1.0, {'vpreds': output.logits}\n\n            responses = data['responses']\n            attention_mask = data['attention_mask']\n            values = data['values']\n            returns = data['returns']\n            response_length = responses.size(1)\n\n            eos_mask = attention_mask[:, -response_length:]\n\n            cliprange_value = self.config.cliprange_value\n\n            vpreds = output.logits  # (bs, sequence_length)\n            vpreds = vpreds[:, -response_length - 1:-1]\n\n            vf_loss, vf_clipfrac = core_algos.compute_value_loss(vpreds=vpreds,\n                                                                 values=values,\n                                                                 returns=returns,\n                                                                 eos_mask=eos_mask,\n                                                                 cliprange_value=cliprange_value)\n            stats = {\n                'critic/vf_loss': vf_loss.detach().item(),\n                'critic/vf_clipfrac': vf_clipfrac.detach().item(),\n                'critic/vpred_mean': masked_mean(vpreds, eos_mask).detach().item(),\n            }\n\n            return vf_loss, stats\n\n        def forward_step(batch_iter, model):\n            batch = next(batch_iter)\n            input_ids = batch['input_ids']\n            attention_mask = batch['attention_mask']\n            position_ids = batch['position_ids']\n            output = model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids)\n            return output, partial(loss_func, data=batch, meta_info={})\n\n        # batch should be a list of batches inside micro-batches\n        batch_generator = make_batch_generator(batches, vpp_size=len(self.critic_module))\n\n        # TODO: we may use the new schedule instead\n        # for flash-attn: (seq_len, batch_size, hidden_size) = (mbs*seq_len, 1, hidden_size)\n        if mpu.get_pipeline_model_parallel_world_size() > 1:\n            losses_reduced = forward_backward_func(\n                forward_step_func=forward_step,\n                data_iterator=batch_generator,\n                model=self.critic_module,\n                num_microbatches=n_micro_batch,\n                seq_length=self.config.ppo_micro_batch_size_per_gpu * seq_len,  # no use when input_shapes was set\n                micro_batch_size=1,  # no use when input_shapes was set\n                forward_only=forward_only,\n            )\n        else:\n            losses_reduced = forward_backward_func(\n                forward_step_func=forward_step,\n                data_iterator=batch_generator,\n                model=self.critic_module,\n                num_microbatches=n_micro_batch,\n                seq_length=self.config.ppo_micro_batch_size_per_gpu * seq_len,  # in use for pp = 1\n                micro_batch_size=1,  # in use for pp = 1\n                forward_only=forward_only,\n            )\n        # loss_reduces contains the stats returned from loss_func\n        return losses_reduced\n\n    def update_critic(self, dataloader: Iterable[DataProto]):\n        metrics = {}\n\n        for data in dataloader:\n            # data = data.batch.to(self.critic_module.device)\n            self.critic_optimizer.zero_grad()\n            # use use_contiguous_buffers_in_local_ddp and no overlap_dp_param_comm\n            for chunk in self.critic_module:\n                chunk.zero_grad_buffer()\n\n            metric_micro_batch = self.forward_backward_batch(data)\n\n            update_successful, grad_norm, num_zeros_in_grad = self.critic_optimizer.step()\n\n            if update_successful:\n                # allgather already execute in optimizer.step in new megatron\n                pass\n            else:\n                raise NotImplementedError\n\n            for metric in metric_micro_batch:\n                append_to_dict(metrics, metric)  # append the metric from this micro-batch to global metrics.\n\n        # add empty cache after each compute\n        torch.cuda.empty_cache()\n        return metrics\n"
  },
  {
    "path": "verl/workers/fsdp_workers.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe main entry point to run the PPO algorithm\n\"\"\"\n\nimport logging\nimport os\nimport warnings\n\nimport torch\nimport torch.distributed\nfrom torch.distributed.device_mesh import init_device_mesh\nimport verl.utils.torch_functional as verl_F\nfrom omegaconf import DictConfig, open_dict\nfrom verl import DataProto\nfrom verl.single_controller.base import Worker\nfrom verl.single_controller.base.decorator import register, Dispatch\nfrom verl.utils import hf_tokenizer, hf_processor\nfrom verl.utils.debug import log_gpu_memory_usage\nfrom verl.utils.fs import copy_to_local\nfrom verl.utils.fsdp_utils import get_fsdp_wrap_policy, init_fn, get_init_weight_context_manager\nfrom verl.utils.fsdp_utils import offload_fsdp_optimizer, offload_fsdp_model_to_cpu, load_fsdp_optimizer, \\\n    load_fsdp_model_to_gpu\nfrom verl.utils.import_utils import import_external_libs\nfrom verl.utils.model import compute_position_id_with_mask\nfrom verl.utils.flops_counter import FlopsCounter\nfrom verl.utils.checkpoint.fsdp_checkpoint_manager import FSDPCheckpointManager\nfrom verl.workers.sharding_manager.fsdp_ulysses import FSDPUlyssesShardingManager\n\nfrom codetiming import Timer\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv('VERL_PPO_LOGGING_LEVEL', 'WARN'))\n\n\ndef create_device_mesh(world_size, fsdp_size):\n    if fsdp_size < 0 or fsdp_size >= world_size:\n        device_mesh = init_device_mesh('cuda', mesh_shape=(world_size,), mesh_dim_names=['fsdp'])\n    else:\n        raise ValueError(\n            'HSDP is not supported yet because it produces incorrect results for now. Please set fsdp_size=-1')\n        assert world_size % fsdp_size == 0\n        device_mesh = init_device_mesh('cuda',\n                                       mesh_shape=(world_size // fsdp_size, fsdp_size),\n                                       mesh_dim_names=['ddp', 'fsdp'])\n    return device_mesh\n\n\ndef get_sharding_strategy(device_mesh):\n    from torch.distributed.fsdp import ShardingStrategy\n    if device_mesh.ndim == 1:\n        sharding_strategy = ShardingStrategy.FULL_SHARD\n    elif device_mesh.ndim == 2:\n        sharding_strategy = ShardingStrategy.HYBRID_SHARD\n    else:\n        raise NotImplementedError(f\"Get device mesh ndim={device_mesh.ndim}, but only support 1 or 2\")\n    return sharding_strategy\n\n\nclass ActorRolloutRefWorker(Worker):\n    \"\"\"\n    This worker can be instantiated as a standalone actor or a standalone rollout or a standalone reference policy\n    or a hybrid engine based on the config.rollout\n    \"\"\"\n\n    def __init__(self, config: DictConfig, role: str):\n        super().__init__()\n        self.config = config\n        import torch.distributed\n        if not torch.distributed.is_initialized():\n            torch.distributed.init_process_group(backend=\"nccl\")\n\n        # build device mesh for FSDP\n        world_size = torch.distributed.get_world_size()\n        # TODO(sgm): support FSDP hybrid shard for larger model\n        self.device_mesh = create_device_mesh(world_size=world_size, fsdp_size=self.config.actor.fsdp_config.fsdp_size)\n\n        # build device mesh for Ulysses Sequence Parallel\n        self.ulysses_device_mesh = None\n        self.ulysses_sequence_parallel_size = self.config.actor.get('ulysses_sequence_parallel_size', 1)\n        dp = world_size // self.ulysses_sequence_parallel_size\n        if self.ulysses_sequence_parallel_size > 1:\n            self.ulysses_device_mesh = init_device_mesh('cuda',\n                                                        mesh_shape=(dp, self.ulysses_sequence_parallel_size),\n                                                        mesh_dim_names=['dp', 'sp'])\n\n        self.ulysses_sharding_manager = FSDPUlyssesShardingManager(self.ulysses_device_mesh)\n\n        self.role = role\n        assert self.role in ['actor', 'rollout', 'ref', 'actor_rollout', 'actor_rollout_ref']\n\n        self._is_actor = self.role in ['actor', 'actor_rollout', 'actor_rollout_ref']\n        self._is_rollout = self.role in ['rollout', 'actor_rollout', 'actor_rollout_ref']\n        self._is_ref = self.role in ['ref', 'actor_rollout_ref']\n\n        self._is_offload_param = False\n        self._is_offload_optimizer = False\n        if self._is_actor:\n            self._is_offload_param = self.config.actor.fsdp_config.get('param_offload', False)\n            self._is_offload_optimizer = self.config.actor.fsdp_config.get('optimizer_offload', False)\n        elif self._is_ref:\n            # TODO: it seems that manual offload is slowly than FSDP offload\n            self._is_offload_param = self.config.ref.fsdp_config.get('param_offload', False)\n\n        # normalize config\n        if self._is_actor:\n            self.config.actor.ppo_mini_batch_size *= self.config.rollout.n\n            self.config.actor.ppo_mini_batch_size //= (self.device_mesh.shape[0] // self.ulysses_sequence_parallel_size)\n            # micro bsz\n            if self.config.actor.ppo_micro_batch_size is not None:\n                self.config.actor.ppo_micro_batch_size //= (self.device_mesh.shape[0] //\n                                                            self.ulysses_sequence_parallel_size)\n                self.config.actor.ppo_micro_batch_size_per_gpu = self.config.actor.ppo_micro_batch_size\n                assert self.config.actor.ppo_mini_batch_size % self.config.actor.ppo_micro_batch_size_per_gpu == 0, \\\n                    f'normalized ppo_mini_batch_size {self.config.actor.ppo_mini_batch_size} should be divisible by ppo_micro_batch_size_per_gpu {self.config.actor.ppo_micro_batch_size_per_gpu}'\n                assert self.config.actor.ppo_mini_batch_size // self.config.actor.ppo_micro_batch_size_per_gpu > 0, \\\n                    f'normalized ppo_mini_batch_size {self.config.actor.ppo_mini_batch_size} should be larger than ppo_micro_batch_size_per_gpu {self.config.actor.ppo_micro_batch_size_per_gpu}'\n\n        # normalize rollout config\n        if self._is_rollout and self.config.rollout.log_prob_micro_batch_size is not None:\n            self.config.rollout.log_prob_micro_batch_size //= (self.device_mesh.shape[0] //\n                                                               self.ulysses_sequence_parallel_size)\n            self.config.rollout.log_prob_micro_batch_size_per_gpu = self.config.rollout.log_prob_micro_batch_size\n        # normalize ref config\n        if self._is_ref and self.config.ref.log_prob_micro_batch_size is not None:\n            self.config.ref.log_prob_micro_batch_size //= (self.device_mesh.shape[0] //\n                                                           self.ulysses_sequence_parallel_size)\n            self.config.ref.log_prob_micro_batch_size_per_gpu = self.config.ref.log_prob_micro_batch_size\n\n    def _build_model_optimizer(self,\n                               model_path,\n                               fsdp_config,\n                               optim_config,\n                               override_model_config,\n                               use_remove_padding=False,\n                               enable_gradient_checkpointing=False,\n                               trust_remote_code=False,\n                               use_liger=False,\n                               role='actor'):\n        from verl.utils.model import print_model_size, update_model_config, get_generation_config\n        from verl.utils.torch_dtypes import PrecisionType\n        from transformers import AutoModelForCausalLM, AutoConfig, AutoModelForVision2Seq\n        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, ShardingStrategy, MixedPrecision, CPUOffload\n        from torch import optim\n\n        assert role in ['actor', 'ref']\n\n        log_gpu_memory_usage('Before init from HF AutoModel', logger=logger)\n        local_path = copy_to_local(model_path)\n\n        # note that we have to create model in fp32. Otherwise, the optimizer is in bf16, which is incorrect\n        # TODO(zhangchi.usc1992): 1. support create from random initialized model. 2. Support init with FSDP directly\n        self.tokenizer = hf_tokenizer(local_path, trust_remote_code=trust_remote_code)\n        self.processor = hf_processor(local_path, trust_remote_code=trust_remote_code)\n\n        torch_dtype = fsdp_config.get('model_dtype', None)\n        if torch_dtype is None:\n            torch_dtype = torch.float32 if self._is_actor else torch.bfloat16\n        else:\n            torch_dtype = PrecisionType.to_dtype(torch_dtype)\n\n        # override model kwargs\n        actor_model_config = AutoConfig.from_pretrained(local_path, trust_remote_code=trust_remote_code)\n\n        self.generation_config = get_generation_config(local_path, trust_remote_code=trust_remote_code)\n\n        if use_remove_padding:\n            from verl.models.registry import check_model_support_rmpad\n            check_model_support_rmpad(actor_model_config.model_type)\n\n        if use_remove_padding and self.ulysses_sequence_parallel_size > 1:\n            from verl.models.transformers.monkey_patch import apply_monkey_patch\n            apply_monkey_patch(actor_model_config, verbose=True)\n\n        override_config_kwargs = {\n            'bos_token_id': self.tokenizer.bos_token_id,\n            'eos_token_id': self.tokenizer.eos_token_id,\n            'pad_token_id': self.tokenizer.pad_token_id,\n        }\n        override_config_kwargs.update(override_model_config)\n        update_model_config(actor_model_config, override_config_kwargs=override_config_kwargs)\n        if self.rank == 0:\n            print(f'Model config after override: {actor_model_config}')\n\n        # NOTE(fix me): tie_word_embedding causes meta_tensor init to hang\n        init_context = get_init_weight_context_manager(use_meta_tensor=not actor_model_config.tie_word_embeddings)\n\n        with init_context(), warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            if type(actor_model_config) in AutoModelForVision2Seq._model_mapping.keys():\n                actor_module_class = AutoModelForVision2Seq\n            else:\n                actor_module_class = AutoModelForCausalLM\n\n            actor_module = actor_module_class.from_pretrained(pretrained_model_name_or_path=local_path,\n                                                              torch_dtype=torch_dtype,\n                                                              config=actor_model_config,\n                                                              attn_implementation='flash_attention_2',\n                                                              trust_remote_code=trust_remote_code)\n            # Apply Liger kernel to the model if use_liger is set to True\n            if use_liger:\n                from liger_kernel.transformers.monkey_patch import _apply_liger_kernel_to_instance\n                _apply_liger_kernel_to_instance(model=actor_module)\n\n            # some parameters may not in torch_dtype. TODO(zhangchi.usc1992) remove this after we switch to fsdp2\n            actor_module.to(torch_dtype)\n\n            if enable_gradient_checkpointing:\n                actor_module.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False})\n        torch.distributed.barrier()\n\n        if self.rank == 0:\n            print_model_size(actor_module)\n\n        log_gpu_memory_usage('After init from HF AutoModel', logger=logger)\n\n        # We wrap FSDP for rollout as well\n        mixed_precision_config = fsdp_config.get('mixed_precision', None)\n        if mixed_precision_config is not None:\n            param_dtype = PrecisionType.to_dtype(mixed_precision_config.get('param_dtype', 'bf16'))\n            reduce_dtype = PrecisionType.to_dtype(mixed_precision_config.get('reduce_dtype', 'fp32'))\n            buffer_dtype = PrecisionType.to_dtype(mixed_precision_config.get('buffer_dtype', 'fp32'))\n        else:\n            param_dtype = torch.bfloat16\n            reduce_dtype = torch.float32\n            buffer_dtype = torch.float32\n\n        mixed_precision = MixedPrecision(param_dtype=param_dtype, reduce_dtype=reduce_dtype, buffer_dtype=buffer_dtype)\n\n        auto_wrap_policy = get_fsdp_wrap_policy(module=actor_module, config=fsdp_config.get('wrap_policy', None))\n\n        if self._is_rollout and self.config.rollout.name == 'hf':\n            # TODO(zhangchi.usc1992, shengguangming) fix me. Current, auto_wrap_policy causes HFRollout to hang in Gemma\n            auto_wrap_policy = None\n\n        print(f'wrap_policy: {auto_wrap_policy}')\n\n        fsdp_mesh = self.device_mesh\n        sharding_strategy = get_sharding_strategy(fsdp_mesh)\n\n        # TODO: add transformer policy\n        # We force reference policy to use CPUOffload to save memory.\n        # We force turn off CPUOffload for actor because it causes incorrect results when using grad accumulation\n        cpu_offload = None if role == 'actor' else CPUOffload(offload_params=True)\n        actor_module_fsdp = FSDP(\n            actor_module,\n            cpu_offload=cpu_offload,\n            param_init_fn=init_fn,\n            use_orig_params=False,\n            auto_wrap_policy=auto_wrap_policy,\n            device_id=torch.cuda.current_device(),\n            sharding_strategy=sharding_strategy,  # zero3\n            mixed_precision=mixed_precision,\n            sync_module_states=True,\n            device_mesh=self.device_mesh,\n            forward_prefetch=False)\n\n        log_gpu_memory_usage('After Actor FSDP init', logger=logger)\n\n        # TODO: add more optimizer args into config\n        if role == 'actor':\n            from verl.utils.torch_functional import get_constant_schedule_with_warmup\n            actor_optimizer = optim.AdamW(actor_module_fsdp.parameters(),\n                                          lr=optim_config.lr,\n                                          betas=optim_config.get('betas', (0.9, 0.999)),\n                                          weight_decay=optim_config.get('weight_decay', 1e-2))\n\n            total_steps = optim_config.get('total_training_steps', 0)\n            num_warmup_steps_ratio = optim_config.get('lr_warmup_steps_ratio', 0.)\n            num_warmup_steps = int(num_warmup_steps_ratio * total_steps)\n\n            print(f'Total steps: {total_steps}, num_warmup_steps: {num_warmup_steps}')\n\n            actor_lr_scheduler = get_constant_schedule_with_warmup(optimizer=actor_optimizer,\n                                                                   num_warmup_steps=num_warmup_steps)\n        else:\n            actor_optimizer = None\n            actor_lr_scheduler = None\n\n        log_gpu_memory_usage('After actor optimizer init', logger=logger)\n\n        return actor_module_fsdp, actor_optimizer, actor_lr_scheduler, actor_model_config\n\n    def _build_rollout(self):\n        from torch.distributed.device_mesh import init_device_mesh\n        # TODO(sgm): support FSDP hybrid shard for larger model\n        infer_tp = self.config.rollout.tensor_model_parallel_size\n        dp = self.world_size // infer_tp\n        assert self.world_size % infer_tp == 0, f'rollout world_size: {self.world_size} is not divisible by infer_tp: {infer_tp}'\n        rollout_device_mesh = init_device_mesh('cuda', mesh_shape=(dp, infer_tp), mesh_dim_names=['dp', 'infer_tp'])\n\n        if self.config.rollout.name == 'hf':\n            from verl.workers.rollout import HFRollout\n            from verl.workers.sharding_manager import BaseShardingManager\n            rollout = HFRollout(module=self.actor_module_fsdp, config=self.config.rollout)\n            rollout_sharding_manager = BaseShardingManager()\n            # TODO: a sharding manager that do nothing?\n        elif self.config.rollout.name == 'vllm':\n            if self.config.rollout.use_fire_sampling:\n                from verl.workers.rollout.vllm_rollout import FIREvLLMRollout as vLLMRollout\n                from verl.workers.rollout.vllm_rollout import vllm_mode\n            else:\n                from verl.workers.rollout.vllm_rollout import vLLMRollout, vllm_mode\n            from verl.workers.sharding_manager import FSDPVLLMShardingManager\n            log_gpu_memory_usage('Before building vllm rollout', logger=None)\n            local_path = copy_to_local(self.config.model.path)\n            if vllm_mode == 'customized':\n                rollout = vLLMRollout(actor_module=self.actor_module_fsdp,\n                                      config=self.config.rollout,\n                                      tokenizer=self.tokenizer,\n                                      model_hf_config=self.actor_model_config)\n            elif vllm_mode == 'spmd':\n                rollout = vLLMRollout(model_path=local_path,\n                                      config=self.config.rollout,\n                                      tokenizer=self.tokenizer,\n                                      model_hf_config=self.actor_model_config,\n                                      device_mesh=rollout_device_mesh)\n            else:\n                raise NotImplementedError(\"vllm_mode must be 'customized' or 'spmd'\")\n            log_gpu_memory_usage('After building vllm rollout', logger=None)\n            if torch.distributed.get_world_size() == 1:\n                self.config.rollout.load_format = 'dummy_hf'\n            rollout_sharding_manager = FSDPVLLMShardingManager(module=self.actor_module_fsdp,\n                                                               inference_engine=rollout.inference_engine,\n                                                               model_config=self.actor_model_config,\n                                                               full_params='hf' in self.config.rollout.load_format,\n                                                               device_mesh=rollout_device_mesh)\n            log_gpu_memory_usage('After building sharding manager', logger=None)\n\n        return rollout, rollout_sharding_manager\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def init_model(self):\n        from verl.workers.actor import DataParallelPPOActor\n        # This is used to import external_lib into the huggingface systems\n        import_external_libs(self.config.model.get('external_lib', None))\n\n        from omegaconf import OmegaConf\n        override_model_config = OmegaConf.to_container(self.config.model.get('override_config', OmegaConf.create()))\n\n        use_remove_padding = self.config.model.get('use_remove_padding', False)\n\n        if self._is_actor or self._is_rollout:\n            # we need the model for actor and rollout\n            if self._is_actor:\n                optim_config = self.config.actor.optim\n                fsdp_config = self.config.actor.fsdp_config\n            else:\n                optim_config = None\n                fsdp_config = OmegaConf.create()\n            self.actor_module_fsdp, self.actor_optimizer, self.actor_lr_scheduler, self.actor_model_config = self._build_model_optimizer(\n                model_path=self.config.model.path,\n                fsdp_config=fsdp_config,\n                optim_config=optim_config,\n                override_model_config=override_model_config,\n                use_remove_padding=use_remove_padding,\n                enable_gradient_checkpointing=self.config.model.get('enable_gradient_checkpointing', False),\n                trust_remote_code=self.config.model.get('trust_remote_code', False),\n                use_liger=self.config.model.get('use_liger', False),\n                role='actor')\n\n            # get the original unwrapped module\n            self.actor_module = self.actor_module_fsdp._fsdp_wrapped_module\n\n            if self._is_offload_optimizer:\n                offload_fsdp_optimizer(optimizer=self.actor_optimizer)\n                log_gpu_memory_usage('After offload actor optimizer during init', logger=logger)\n        # load from checkpoint\n        if self._is_actor:\n            OmegaConf.set_struct(self.config.actor, True)\n            with open_dict(self.config.actor):\n                self.config.actor.use_remove_padding = use_remove_padding\n            self.actor = DataParallelPPOActor(config=self.config.actor,\n                                              actor_module=self.actor_module_fsdp,\n                                              actor_optimizer=self.actor_optimizer)\n\n        if self._is_rollout:\n            self.rollout, self.rollout_sharding_manager = self._build_rollout()\n\n        if self._is_ref:\n            self.ref_module_fsdp = self._build_model_optimizer(model_path=self.config.model.path,\n                                                               fsdp_config=self.config.ref.fsdp_config,\n                                                               optim_config=None,\n                                                               override_model_config=override_model_config,\n                                                               use_remove_padding=use_remove_padding,\n                                                               trust_remote_code=self.config.model.get(\n                                                                   'trust_remote_code', False),\n                                                               use_liger=self.config.model.get('use_liger', False),\n                                                               role='ref')[0]\n            OmegaConf.set_struct(self.config.ref, True)\n            with open_dict(self.config.ref):\n                self.config.ref.use_remove_padding = use_remove_padding\n            self.ref_policy = DataParallelPPOActor(config=self.config.ref, actor_module=self.ref_module_fsdp)\n\n        if self._is_actor:\n            self.flops_counter = FlopsCounter(self.actor_model_config)\n            self.checkpoint_manager = FSDPCheckpointManager(\n                model=self.actor_module_fsdp,\n                optimizer=self.actor.actor_optimizer,\n                lr_scheduler=self.actor_lr_scheduler,\n                processing_class=self.processor if self.processor is not None else self.tokenizer)\n\n        torch.cuda.empty_cache()\n\n    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)\n    def update_actor(self, data: DataProto):\n        data = data.to('cuda')\n\n        assert self._is_actor\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.actor_module_fsdp)\n        if self._is_offload_optimizer:\n            load_fsdp_optimizer(optimizer=self.actor_optimizer, device_id=torch.cuda.current_device())\n\n        data.batch = data.batch.cuda()\n\n        log_gpu_memory_usage('Before update policy', logger=logger)\n\n        with self.ulysses_sharding_manager:\n            data = self.ulysses_sharding_manager.preprocess_data(data=data)\n            # perform training\n            with Timer(name='update_policy', logger=None) as timer:\n                metrics = self.actor.update_policy(data=data)\n            delta_time = timer.last\n            global_num_tokens = data.meta_info['global_token_num']\n            estimated_flops, promised_flops = self.flops_counter.estimate_flops(global_num_tokens, delta_time)\n            metrics['mfu/actor'] = estimated_flops * self.config.actor.ppo_epochs / promised_flops / self.world_size\n\n            self.actor_lr_scheduler.step()\n            lr = self.actor_lr_scheduler.get_last_lr()[0]\n            metrics['actor/lr'] = lr\n\n            log_gpu_memory_usage('After update policy', logger=logger)\n\n            # TODO: here, we should return all metrics\n            output = DataProto(meta_info={'metrics': metrics})\n\n            output = self.ulysses_sharding_manager.postprocess_data(data=output)\n            output = output.to('cpu')\n\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.actor_module_fsdp)\n        if self._is_offload_optimizer:\n            offload_fsdp_optimizer(optimizer=self.actor_optimizer)\n        torch.cuda.empty_cache()\n        return output\n\n    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)\n    def generate_sequences(self, prompts: DataProto):\n        prompts = prompts.to('cuda')\n\n        assert self._is_rollout\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.actor_module_fsdp)\n\n        prompts.batch = prompts.batch.cuda()\n        meta_info = {\n            'eos_token_id':\n                self.generation_config.eos_token_id\n                if self.generation_config is not None else self.tokenizer.eos_token_id,\n            'pad_token_id':\n                self.generation_config.pad_token_id\n                if self.generation_config is not None else self.tokenizer.pad_token_id,\n        }\n        prompts.meta_info.update(meta_info)\n        with self.rollout_sharding_manager:\n\n            # after parameters sync with rollout, offload actor model to CPU\n            if self._is_offload_param:\n                offload_fsdp_model_to_cpu(self.actor_module_fsdp)\n            if self._is_offload_optimizer:\n                offload_fsdp_optimizer(optimizer=self.actor_optimizer)\n\n            log_gpu_memory_usage('After entering rollout sharding manager', logger=logger)\n\n            prompts = self.rollout_sharding_manager.preprocess_data(prompts)\n            output = self.rollout.generate_sequences(prompts=prompts)\n\n            log_gpu_memory_usage('After rollout generation', logger=logger)\n\n            output = self.rollout_sharding_manager.postprocess_data(output)\n\n        output = output.to('cpu')\n\n        # clear kv cache\n        torch.cuda.empty_cache()\n        log_gpu_memory_usage('After recompute log prob', logger=logger)\n        return output\n\n    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)\n    def compute_log_prob(self, data: DataProto):\n        assert self._is_actor\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.actor_module_fsdp)\n        data = data.to('cuda')\n        # we should always recompute old_log_probs when it is HybridEngine\n        data.meta_info['micro_batch_size'] = self.config.rollout.log_prob_micro_batch_size_per_gpu\n        data.meta_info['max_token_len'] = self.config.rollout.log_prob_max_token_len_per_gpu\n        data.meta_info['use_dynamic_bsz'] = self.config.rollout.log_prob_use_dynamic_bsz\n        data.meta_info['temperature'] = self.config.rollout.temperature\n        # perform recompute log_prob\n        with self.ulysses_sharding_manager:\n            data = self.ulysses_sharding_manager.preprocess_data(data)\n            output = self.actor.compute_log_prob(data=data)\n            output = DataProto.from_dict(tensors={'old_log_probs': output},\n                                         meta_info={'temperature': self.config.rollout.temperature})\n            output = self.ulysses_sharding_manager.postprocess_data(output)\n\n        output = output.to('cpu')\n\n        # https://pytorch.org/docs/stable/notes/fsdp.html#fsdp-notes\n        # unshard the root FSDP module\n        if self.world_size > 1:\n            self.actor.actor_module._handle.reshard(True)\n\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.actor_module_fsdp)\n\n        # clear kv cache\n        torch.cuda.empty_cache()\n        log_gpu_memory_usage('After compute_log_prob', logger=logger)\n        return output\n\n    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)\n    def compute_ref_log_prob(self, data: DataProto):\n        assert self._is_ref\n\n        data = data.to('cuda')\n\n        micro_batch_size = self.config.ref.log_prob_micro_batch_size_per_gpu\n        data.meta_info['micro_batch_size'] = micro_batch_size\n        data.meta_info['temperature'] = self.config.rollout.temperature\n        data.meta_info['max_token_len'] = self.config.ref.log_prob_max_token_len_per_gpu\n        data.meta_info['use_dynamic_bsz'] = self.config.ref.log_prob_use_dynamic_bsz\n        with self.ulysses_sharding_manager:\n            data = self.ulysses_sharding_manager.preprocess_data(data)\n            output = self.ref_policy.compute_log_prob(data=data)\n            output = DataProto.from_dict(tensors={'ref_log_prob': output})\n            output = self.ulysses_sharding_manager.postprocess_data(output)\n\n        output = output.to('cpu')\n\n        # https://pytorch.org/docs/stable/notes/fsdp.html#fsdp-notes\n        # unshard the root FSDP module\n        if self.world_size > 1:\n            self.ref_policy.actor_module._handle.reshard(True)\n\n        torch.cuda.empty_cache()\n        return output\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def save_checkpoint(self, local_path, hdfs_path=None, global_step=0, remove_previous_ckpt=False):\n        # only support save and load ckpt for actor\n        assert self._is_actor\n        import torch\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.actor_module_fsdp)\n\n        self.checkpoint_manager.save_checkpoint(local_path=local_path,\n                                                hdfs_path=hdfs_path,\n                                                global_step=global_step,\n                                                remove_previous_ckpt=remove_previous_ckpt)\n\n        torch.distributed.barrier()\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.actor_module_fsdp)\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def load_checkpoint(self, path, del_local_after_load=False):\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.actor_module_fsdp)\n\n        self.checkpoint_manager.load_checkpoint(path=path, del_local_after_load=del_local_after_load)\n\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.actor_module_fsdp)\n\n        if self._is_offload_optimizer:\n            offload_fsdp_optimizer(self.actor_optimizer)\n\n\nclass CriticWorker(Worker):\n\n    def __init__(self, config):\n        super().__init__()\n        import torch.distributed\n        if not torch.distributed.is_initialized():\n            torch.distributed.init_process_group(backend=\"nccl\")\n        self.config = config\n\n        # build device mesh for Ulysses Sequence Parallel\n        world_size = torch.distributed.get_world_size()\n        from torch.distributed.device_mesh import init_device_mesh\n\n        fsdp_size = self.config.model.fsdp_config.fsdp_size\n        self.device_mesh = create_device_mesh(world_size=world_size, fsdp_size=fsdp_size)\n\n        self.ulysses_device_mesh = None\n        self.ulysses_sequence_parallel_size = self.config.get('ulysses_sequence_parallel_size', 1)\n        dp = world_size // self.ulysses_sequence_parallel_size\n        if self.ulysses_sequence_parallel_size > 1:\n            self.ulysses_device_mesh = init_device_mesh('cuda',\n                                                        mesh_shape=(dp, self.ulysses_sequence_parallel_size),\n                                                        mesh_dim_names=['dp', 'sp'])\n\n        self.ulysses_sharding_manager = FSDPUlyssesShardingManager(self.ulysses_device_mesh)\n\n        # set FSDP offload params\n        self._is_offload_param = self.config.model.fsdp_config.param_offload\n        self._is_offload_optimizer = self.config.model.fsdp_config.optimizer_offload\n\n        # normalize config\n        self.config.ppo_mini_batch_size //= (torch.distributed.get_world_size() // self.ulysses_sequence_parallel_size)\n        if self.config.ppo_micro_batch_size is not None:\n            self.config.ppo_micro_batch_size //= (torch.distributed.get_world_size() //\n                                                  self.ulysses_sequence_parallel_size)\n            self.config.forward_micro_batch_size //= (torch.distributed.get_world_size() //\n                                                      self.ulysses_sequence_parallel_size)\n            self.config.ppo_micro_batch_size_per_gpu = self.config.ppo_micro_batch_size\n            self.config.forward_micro_batch_size_per_gpu = self.config.forward_micro_batch_size\n            assert self.config.ppo_mini_batch_size % self.config.ppo_micro_batch_size_per_gpu == 0, \\\n                f'normalized ppo_mini_batch_size {self.config.ppo_mini_batch_size} should be divisible by ppo_micro_batch_size_per_gpu {self.config.ppo_micro_batch_size_per_gpu}'\n            assert self.config.ppo_mini_batch_size // self.config.ppo_micro_batch_size_per_gpu > 0, \\\n                f'normalized ppo_mini_batch_size {self.config.ppo_mini_batch_size} should be larger than ppo_micro_batch_size_per_gpu {self.config.ppo_micro_batch_size_per_gpu}'\n\n    def _build_critic_model_optimizer(self, config):\n        # the following line is necessary\n        from verl.utils.model import LambdaLayer, print_model_size, squeeze\n        from verl.utils.torch_dtypes import PrecisionType\n        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, ShardingStrategy, MixedPrecision\n        from torch import optim\n\n        local_path = copy_to_local(config.model.path)\n        # note that the tokenizer between actor and critic may be different. So override tokenizer info with actor info\n        # using random initialized model from any architecture. May not be the same as Actor.\n\n        tokenizer_path = copy_to_local(config.model.tokenizer_path)\n        self.tokenizer = hf_tokenizer(tokenizer_path, trust_remote_code=config.model.get('trust_remote_code', False))\n        self.processor = hf_processor(tokenizer_path, trust_remote_code=config.model.get('trust_remote_code', False))\n\n        from omegaconf import OmegaConf\n        override_config = OmegaConf.to_container(self.config.model.get('override_config', OmegaConf.create()))\n        override_config_kwargs = {\n            'bos_token_id': self.tokenizer.bos_token_id,\n            'eos_token_id': self.tokenizer.eos_token_id,\n            'pad_token_id': self.tokenizer.pad_token_id,\n        }\n        override_config_kwargs.update(override_config)\n        if self.rank == 0:\n            print(f'Critic overriding config {override_config_kwargs}')\n\n        torch_dtype = self.config.model.fsdp_config.get('model_dtype', 'fp32')\n        torch_dtype = PrecisionType.to_dtype(torch_dtype)\n\n        from transformers import AutoConfig, AutoModelForTokenClassification\n        from torch import nn\n\n        trust_remote_code = False\n        critic_model_config = AutoConfig.from_pretrained(local_path, trust_remote_code=trust_remote_code)\n        critic_model_config.num_labels = 1\n\n        use_remove_padding = config.model.get('use_remove_padding', False)\n        if use_remove_padding:\n            from verl.models.registry import check_model_support_rmpad\n            check_model_support_rmpad(critic_model_config.model_type)\n\n        if use_remove_padding and self.ulysses_sequence_parallel_size > 1:\n            from verl.models.transformers.monkey_patch import apply_monkey_patch\n            apply_monkey_patch(critic_model_config, verbose=True)\n\n        init_context = get_init_weight_context_manager()\n        with init_context(), warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            setattr(critic_model_config, 'classifier_dropout', 0.)\n            setattr(critic_model_config, 'hidden_dropout', '0')\n            critic_module = AutoModelForTokenClassification.from_pretrained(pretrained_model_name_or_path=local_path,\n                                                                            torch_dtype=torch_dtype,\n                                                                            config=critic_model_config,\n                                                                            attn_implementation='flash_attention_2',\n                                                                            trust_remote_code=trust_remote_code)\n\n            # some parameters may not in torch_dtype\n            critic_module.to(torch_dtype)\n\n            if config.model.get('enable_gradient_checkpointing', False):\n                critic_module.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False})\n        if self.rank == 0:\n            print_model_size(critic_module)\n\n        self.critic_model_config = critic_model_config\n\n        fsdp_config = self.config.model.fsdp_config\n        mixed_precision_config = fsdp_config.get('mixed_precision', None)\n        if mixed_precision_config is not None:\n            param_dtype = PrecisionType.to_dtype(mixed_precision_config.get('param_dtype', 'bf16'))\n            reduce_dtype = PrecisionType.to_dtype(mixed_precision_config.get('reduce_dtype', 'fp32'))\n            buffer_dtype = PrecisionType.to_dtype(mixed_precision_config.get('buffer_dtype', 'fp32'))\n        else:\n            param_dtype = torch.bfloat16\n            reduce_dtype = torch.float32\n            buffer_dtype = torch.float32\n\n        mixed_precision = MixedPrecision(param_dtype=param_dtype, reduce_dtype=reduce_dtype, buffer_dtype=buffer_dtype)\n\n        auto_wrap_policy = get_fsdp_wrap_policy(module=critic_module, config=self.config.model.fsdp_config.wrap_policy)\n\n        log_gpu_memory_usage('Before critic FSDP', logger=None)\n\n        fsdp_mesh = self.device_mesh\n        sharding_strategy = get_sharding_strategy(fsdp_mesh)\n\n        # Note: We force turn off CPUOffload for critic because it causes incorrect results when using grad accumulation\n        critic_module = FSDP(critic_module,\n                             param_init_fn=init_fn,\n                             use_orig_params=False,\n                             auto_wrap_policy=auto_wrap_policy,\n                             device_id=torch.cuda.current_device(),\n                             sharding_strategy=sharding_strategy,\n                             mixed_precision=mixed_precision,\n                             sync_module_states=True,\n                             forward_prefetch=False,\n                             device_mesh=self.device_mesh,\n                             cpu_offload=None)\n\n        log_gpu_memory_usage('After critic FSDP', logger=None)\n\n        critic_optimizer = optim.AdamW(critic_module.parameters(),\n                                       lr=config.optim.lr,\n                                       betas=config.optim.get('betas', (0.9, 0.999)),\n                                       weight_decay=config.optim.get('weight_decay', 1e-2))\n\n        total_steps = config.optim.get('total_training_steps', 0)\n        num_warmup_steps_ratio = config.optim.get('lr_warmup_steps_ratio', 0.)\n        num_warmup_steps = int(num_warmup_steps_ratio * total_steps)\n\n        print(f'Total steps: {total_steps}, num_warmup_steps: {num_warmup_steps}')\n\n        from verl.utils.torch_functional import get_constant_schedule_with_warmup\n        critic_lr_scheduler = get_constant_schedule_with_warmup(optimizer=critic_optimizer,\n                                                                num_warmup_steps=num_warmup_steps)\n\n        return critic_module, critic_optimizer, critic_lr_scheduler\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def init_model(self):\n        # This is used to import external_lib into the huggingface systems\n        import_external_libs(self.config.model.get('external_lib', None))\n\n        from verl.workers.critic import DataParallelPPOCritic\n        self.critic_module, self.critic_optimizer, self.critic_lr_scheduler = self._build_critic_model_optimizer(\n            self.config)\n\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.critic_module)\n        if self._is_offload_optimizer:\n            offload_fsdp_optimizer(optimizer=self.critic_optimizer)\n\n        self.critic = DataParallelPPOCritic(config=self.config,\n                                            critic_module=self.critic_module,\n                                            critic_optimizer=self.critic_optimizer)\n\n        self.flops_counter = FlopsCounter(self.critic_model_config)\n        self.checkpoint_manager = FSDPCheckpointManager(\n            model=self.critic_module,\n            optimizer=self.critic_optimizer,\n            lr_scheduler=self.critic_lr_scheduler,\n            processing_class=self.processor if self.processor is not None else self.tokenizer)\n\n        torch.cuda.empty_cache()\n\n    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)\n    def compute_values(self, data: DataProto):\n        data = data.to('cuda')\n\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.critic_module)\n        micro_batch_size = self.config.forward_micro_batch_size_per_gpu\n        data.meta_info['micro_batch_size'] = micro_batch_size\n        data.meta_info['max_token_len'] = self.config.forward_max_token_len_per_gpu\n        data.meta_info['use_dynamic_bsz'] = self.config.use_dynamic_bsz\n        # perform forward computation\n        with self.ulysses_sharding_manager:\n            data = self.ulysses_sharding_manager.preprocess_data(data=data)\n            values = self.critic.compute_values(data=data)\n            output = DataProto.from_dict(tensors={'values': values})\n            output = self.ulysses_sharding_manager.postprocess_data(data=output)\n\n        output = output.to('cpu')\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.critic_module)\n        return output\n\n    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)\n    def update_critic(self, data: DataProto):\n        data = data.to('cuda')\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.critic_module)\n        if self._is_offload_optimizer:\n            load_fsdp_optimizer(optimizer=self.critic_optimizer, device_id=torch.cuda.current_device())\n\n        # perform forward computation\n        with self.ulysses_sharding_manager:\n            data = self.ulysses_sharding_manager.preprocess_data(data=data)\n\n            with Timer(name='update_critic', logger=None) as timer:\n                metrics = self.critic.update_critic(data=data)\n            delta_time = timer.last\n\n            global_num_tokens = data.meta_info['global_token_num']\n            estimated_flops, promised_flops = self.flops_counter.estimate_flops(global_num_tokens, delta_time)\n            metrics['mfu/critic'] = estimated_flops * self.config.ppo_epochs / promised_flops / self.world_size\n\n            self.critic_lr_scheduler.step()\n            lr = self.critic_lr_scheduler.get_last_lr()[0]\n            metrics['critic/lr'] = lr\n\n            output = DataProto(batch=None, meta_info={'metrics': metrics})\n            output = self.ulysses_sharding_manager.postprocess_data(data=output)\n\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.critic_module)\n        if self._is_offload_optimizer:\n            offload_fsdp_optimizer(optimizer=self.critic_optimizer)\n        torch.cuda.empty_cache()\n        output = output.to('cpu')\n        return output\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def save_checkpoint(self, local_path, hdfs_path=None, global_step=0, remove_previous_ckpt=False):\n        import torch\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.critic_module)\n\n        self.checkpoint_manager.save_checkpoint(local_path=local_path,\n                                                hdfs_path=hdfs_path,\n                                                global_step=global_step,\n                                                remove_previous_ckpt=remove_previous_ckpt)\n\n        torch.distributed.barrier()\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.critic_module)\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def load_checkpoint(self, path, del_local_after_load=True):\n        import torch\n        if self._is_offload_param:\n            load_fsdp_model_to_gpu(self.critic_module)\n\n        self.checkpoint_manager.load_checkpoint(path=path, del_local_after_load=del_local_after_load)\n\n        torch.distributed.barrier()\n        if self._is_offload_param:\n            offload_fsdp_model_to_cpu(self.critic_module)\n\n        if self._is_offload_optimizer:\n            offload_fsdp_optimizer(self.critic_optimizer)\n\n\n# TODO(sgm): we may need to extract it to dp_reward_model.py\nclass RewardModelWorker(Worker):\n    \"\"\"\n    Note that we only implement the reward model that is subclass of AutoModelForTokenClassification.\n    \"\"\"\n\n    def __init__(self, config):\n        super().__init__()\n        import torch.distributed\n        if not torch.distributed.is_initialized():\n            torch.distributed.init_process_group(backend=\"nccl\")\n        self.config = config\n\n        # build device mesh for Ulysses Sequence Parallel\n        world_size = torch.distributed.get_world_size()\n        from torch.distributed.device_mesh import init_device_mesh\n\n        fsdp_size = self.config.model.fsdp_config.fsdp_size\n        self.device_mesh = create_device_mesh(world_size=world_size, fsdp_size=fsdp_size)\n\n        self.ulysses_device_mesh = None\n        self.ulysses_sequence_parallel_size = self.config.get('ulysses_sequence_parallel_size', 1)\n        dp = world_size // self.ulysses_sequence_parallel_size\n        if self.ulysses_sequence_parallel_size > 1:\n            self.ulysses_device_mesh = init_device_mesh('cuda',\n                                                        mesh_shape=(dp, self.ulysses_sequence_parallel_size),\n                                                        mesh_dim_names=['dp', 'sp'])\n\n        self.ulysses_sharding_manager = FSDPUlyssesShardingManager(self.ulysses_device_mesh)\n\n        self.use_remove_padding = self.config.model.get('use_remove_padding', False)\n\n        # normalize config\n        if self.config.micro_batch_size is not None:\n            self.config.micro_batch_size //= torch.distributed.get_world_size()\n            self.config.micro_batch_size_per_gpu = self.config.micro_batch_size\n\n    def _build_model(self, config):\n        # the following line is necessary\n        from transformers import AutoModelForTokenClassification, AutoConfig\n        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, ShardingStrategy, CPUOffload\n\n        # download the checkpoint from hdfs\n        local_path = copy_to_local(config.model.path)\n\n        if self.config.model.input_tokenizer is None:\n            self._do_switch_chat_template = False\n        else:\n            self._do_switch_chat_template = True\n            input_tokenizer_local_path = copy_to_local(config.model.input_tokenizer)\n            self.input_tokenizer = hf_tokenizer(input_tokenizer_local_path,\n                                                trust_remote_code=config.model.get('trust_remote_code', False))\n            self.tokenizer = hf_tokenizer(local_path, trust_remote_code=config.model.get('trust_remote_code', False))\n\n        trust_remote_code = config.model.get('trust_remote_code', False)\n        model_config = AutoConfig.from_pretrained(local_path, trust_remote_code=trust_remote_code)\n        model_config.num_labels = 1\n\n        use_remove_padding = config.model.get('use_remove_padding', False)\n        if use_remove_padding:\n            from verl.models.registry import check_model_support_rmpad\n            check_model_support_rmpad(model_config.model_type)\n\n        if use_remove_padding and self.ulysses_sequence_parallel_size > 1:\n            from verl.models.transformers.monkey_patch import apply_monkey_patch\n            apply_monkey_patch(model_config, verbose=True)\n\n        # note that we have to create model in fp32. Otherwise, the optimizer is in bf16, which is incorrect\n        init_context = get_init_weight_context_manager(use_meta_tensor=not model_config.tie_word_embeddings)\n\n        with init_context(), warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            setattr(model_config, 'classifier_dropout', 0.)\n            reward_module = AutoModelForTokenClassification.from_pretrained(pretrained_model_name_or_path=local_path,\n                                                                            config=model_config,\n                                                                            torch_dtype=torch.bfloat16,\n                                                                            attn_implementation='flash_attention_2',\n                                                                            trust_remote_code=trust_remote_code)\n            reward_module.to(torch.bfloat16)\n        auto_wrap_policy = get_fsdp_wrap_policy(module=reward_module, config=self.config.model.fsdp_config)\n\n        fsdp_mesh = self.device_mesh\n        sharding_strategy = get_sharding_strategy(fsdp_mesh)\n\n        reward_module = FSDP(\n            reward_module,\n            param_init_fn=init_fn,\n            use_orig_params=False,\n            auto_wrap_policy=auto_wrap_policy,\n            device_id=torch.cuda.current_device(),\n            sharding_strategy=sharding_strategy,  # zero3\n            sync_module_states=True,\n            cpu_offload=CPUOffload(offload_params=True),\n            forward_prefetch=False,\n            device_mesh=self.device_mesh)\n\n        return reward_module\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def init_model(self):\n        # This is used to import external_lib into the huggingface systems\n        import_external_libs(self.config.model.get('external_lib', None))\n        self.reward_module = self._build_model(config=self.config)\n        torch.cuda.empty_cache()\n\n    def _forward_micro_batch(self, micro_batch):\n        from flash_attn.bert_padding import pad_input, unpad_input, index_first_axis, rearrange\n        from verl.utils.ulysses import ulysses_pad_and_slice_inputs, gather_outpus_and_unpad\n\n        with torch.no_grad(), torch.autocast(device_type='cuda', dtype=torch.bfloat16):\n            input_ids = micro_batch['input_ids']\n            batch_size, seqlen = input_ids.shape\n            attention_mask = micro_batch['attention_mask']\n            position_ids = micro_batch['position_ids']\n\n            if self.use_remove_padding:\n                input_ids_rmpad, indices, *_ = unpad_input(input_ids.unsqueeze(-1),\n                                                           attention_mask)  # input_ids_rmpad (total_nnz, ...)\n                input_ids_rmpad = input_ids_rmpad.transpose(0, 1)  # (1, total_nnz)\n\n                # unpad the position_ids to align the rotary\n                position_ids_rmpad = index_first_axis(rearrange(position_ids.unsqueeze(-1), \"b s ... -> (b s) ...\"),\n                                                      indices).transpose(0, 1)\n\n                # pad and slice the inputs if sp > 1\n                if self.ulysses_sequence_parallel_size > 1:\n                    input_ids_rmpad, position_ids_rmpad, pad_size = ulysses_pad_and_slice_inputs(input_ids_rmpad, \\\n                                                                                                position_ids_rmpad, \\\n                                                                                                sp_size=self.ulysses_sequence_parallel_size)\n\n                # only pass input_ids and position_ids to enable flash_attn_varlen\n                output = self.reward_module(input_ids=input_ids_rmpad,\n                                            attention_mask=None,\n                                            position_ids=position_ids_rmpad,\n                                            use_cache=False)  # prevent model thinks we are generating\n                reward_rmpad = output.logits\n                reward_rmpad = reward_rmpad.squeeze(0)  # (total_nnz)\n\n                # gather output if sp > 1\n                if self.ulysses_sequence_parallel_size > 1:\n                    reward_rmpad = gather_outpus_and_unpad(reward_rmpad,\n                                                           gather_dim=0,\n                                                           unpad_dim=0,\n                                                           padding_size=pad_size)\n\n                # pad it back\n                rm_score = pad_input(reward_rmpad, indices=indices, batch=batch_size, seqlen=seqlen).squeeze(-1)\n            else:\n                output = self.reward_module(input_ids=input_ids,\n                                            attention_mask=attention_mask,\n                                            position_ids=position_ids)\n                rm_score = output.logits  # (batch_size, seq_len, 1)\n                rm_score = rm_score.squeeze(-1)\n\n            # extract the result of the last valid token\n            eos_mask_idx = torch.argmax(position_ids * attention_mask, dim=-1)  # (bsz,)\n            rm_score = rm_score[torch.arange(batch_size), eos_mask_idx]\n            return rm_score\n\n    def _expand_to_token_level(self, data: DataProto, scores: torch.Tensor):\n        batch_size = data.batch.batch_size[0]\n        # expand as token_level_reward\n        attention_mask = data.batch['attention_mask']\n        position_ids = data.batch['position_ids']\n        response_length = data.batch['responses'].shape[-1]\n        eos_mask_idx = torch.argmax(position_ids * attention_mask, dim=-1)  # (bsz,)\n        token_level_scores = torch.zeros_like(attention_mask, dtype=scores.dtype)  # (bsz, seqlen)\n        token_level_scores[torch.arange(batch_size), eos_mask_idx] = scores\n\n        # select the response part\n        token_level_scores = token_level_scores[:, -response_length:]\n\n        return token_level_scores\n\n    def _switch_chat_template(self, data: DataProto):\n        src_max_length = data.batch['attention_mask'].shape[-1]\n\n        src_tokenizer = self.input_tokenizer\n        target_tokenizer = self.tokenizer\n\n        rm_input_ids = []\n        rm_attention_mask = []\n\n        for i in range(data.batch.batch_size[0]):\n            # extract raw prompt\n            chat: list = data.non_tensor_batch['raw_prompt'][i].tolist()\n\n            # extract response\n            response_ids = data.batch['responses'][i]\n            response_length = response_ids.shape[-1]\n            valid_response_length = data.batch['attention_mask'][i][-response_length:].sum()\n            valid_response_ids = response_ids[:valid_response_length]\n\n            # decode\n            response = src_tokenizer.decode(valid_response_ids)\n            # remove bos and eos\n            response = response.replace(src_tokenizer.eos_token, '')\n\n            chat.append({'role': 'assistant', 'content': response})\n\n            prompt_with_chat_template = target_tokenizer.apply_chat_template(chat,\n                                                                             add_generation_prompt=False,\n                                                                             tokenize=False)\n            if self.rank == 0 and i == 0:\n                # for debugging purpose\n                print(f'Switch template. chat: {prompt_with_chat_template}')\n\n            # the maximum length is actually determined by the reward model itself\n            max_length = self.config.get('max_length', src_max_length)\n            if max_length is None:\n                max_length = src_max_length\n            input_ids, attention_mask = verl_F.tokenize_and_postprocess_data(\n                prompt=prompt_with_chat_template,\n                tokenizer=target_tokenizer,\n                max_length=max_length,\n                pad_token_id=target_tokenizer.pad_token_id,\n                left_pad=False,  # right padding\n                truncation=self.config.get('truncation', 'right'))  # truncate from the right\n\n            rm_input_ids.append(input_ids)\n            rm_attention_mask.append(attention_mask)\n\n        rm_input_ids = torch.cat(rm_input_ids, dim=0)\n        rm_attention_mask = torch.cat(rm_attention_mask, dim=0)\n\n        rm_position_ids = compute_position_id_with_mask(rm_attention_mask)\n\n        rm_inputs = {'input_ids': rm_input_ids, 'attention_mask': rm_attention_mask, 'position_ids': rm_position_ids}\n\n        return DataProto.from_dict(rm_inputs)\n\n    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)\n    def compute_rm_score(self, data: DataProto):\n        import itertools\n        from verl.utils.seqlen_balancing import rearrange_micro_batches, get_reverse_idx\n        data = data.to('cuda')\n        if self._do_switch_chat_template:\n            rm_data = self._switch_chat_template(data)\n\n        rm_data.batch = rm_data.batch.cuda()\n\n        # perform forward computation\n        with self.ulysses_sharding_manager:\n            rm_data = self.ulysses_sharding_manager.preprocess_data(data=rm_data)\n            data = self.ulysses_sharding_manager.preprocess_data(data=data)\n\n            use_dynamic_bsz = self.config.use_dynamic_bsz\n            if use_dynamic_bsz:\n                max_token_len = self.config.forward_max_token_len_per_gpu * self.ulysses_sequence_parallel_size\n                micro_batches, indices = rearrange_micro_batches(batch=rm_data.batch, max_token_len=max_token_len)\n            else:\n                micro_batches = rm_data.batch.split(self.config.micro_batch_size_per_gpu)\n            output = []\n            for micro_batch in micro_batches:\n                rm_score = self._forward_micro_batch(micro_batch)\n                output.append(rm_score)\n            scores = torch.cat(output, dim=0)  # (batch_size)\n\n            if use_dynamic_bsz:\n                indices = list(itertools.chain.from_iterable(indices))\n                assert len(indices) == scores.size(0), f\"{len(indices)} vs. {scores.size()}\"\n                revert_indices = torch.tensor(get_reverse_idx(indices), dtype=torch.long)\n                scores = scores[revert_indices]\n\n            token_level_scores = self._expand_to_token_level(data, scores)\n            # Note that this is only the scores, may not be the final rewards used to train RL\n            output = DataProto.from_dict(tensors={'rm_scores': token_level_scores})\n            output = self.ulysses_sharding_manager.postprocess_data(data=output)\n\n        # https://pytorch.org/docs/stable/notes/fsdp.html#fsdp-notes\n        # unshard the root FSDP module\n        self.reward_module._handle.reshard(True)\n\n        output = output.to('cpu')\n        torch.cuda.empty_cache()\n        return output\n"
  },
  {
    "path": "verl/workers/megatron_workers.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe main entry point to run the PPO algorithm\n\"\"\"\n\nimport os\nimport logging\nimport ray\nimport torch\nimport torch.distributed\nimport torch.nn as nn\nfrom omegaconf import DictConfig\nfrom verl.single_controller.base.megatron.worker import MegatronWorker\nfrom verl.workers.actor.megatron_actor import MegatronPPOActor\nfrom verl.workers.critic.megatron_critic import MegatronPPOCritic\nfrom verl.workers.sharding_manager import AllGatherPPModel\nfrom verl.workers.reward_model.megatron.reward_model import MegatronRewardModel\n\nfrom verl.single_controller.base.decorator import register, Dispatch\nfrom verl import DataProto\nfrom verl.utils.fs import copy_to_local\nfrom verl.utils.debug import log_gpu_memory_usage\nfrom verl.utils.model import load_megatron_model_weights\nfrom verl.utils.flops_counter import FlopsCounter\nfrom verl.utils.megatron_utils import init_model_parallel_config\nfrom verl.utils.megatron_utils import offload_megatron_param_and_grad, load_megatron_param_and_grad\nfrom verl.utils import hf_tokenizer\n\nfrom codetiming import Timer\n\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core import ModelParallelConfig\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv('VERL_PPO_LOGGING_LEVEL', 'WARN'))\n\n\ndef set_random_seed(seed):\n    import torch\n    import numpy as np\n    import random\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n    if torch.cuda.device_count() > 0:\n        from megatron.core import tensor_parallel\n        tensor_parallel.model_parallel_cuda_manual_seed(seed)\n    # FIXME: torch cumsum not support deterministic (used in vllm sampler),\n    # https://github.com/pytorch/pytorch/issues/89492\n    # torch.use_deterministic_algorithms(True, warn_only=True)\n    # os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'\n\n\nclass ActorRolloutRefWorker(MegatronWorker):\n    \"\"\"\n    This worker can be instantiated as a standalone actor or a standalone rollout or a standalone reference policy\n    or a hybrid engine based on the config.rollout\n    \"\"\"\n\n    def __init__(self, config: DictConfig, role: str):\n        super().__init__()\n        self.config = config\n\n        # NOTE(sgm): We utilize colocate WorkerGroup by default.\n        # As a result, Workers for different model share the same process.\n        # Therefore, we only require one distribute initialization.\n        # To utilize different parallel startegy in different models:\n        # 1, users should disable WorkerDict; 2.assign different ResourcePool to different models,\n        # 3. and apply the following patch in ray==2.10, https://github.com/ray-project/ray/pull/44385\n        if not torch.distributed.is_initialized():\n            rank = int(os.environ['LOCAL_RANK'])\n            torch.distributed.init_process_group(backend=\"nccl\")\n            torch.cuda.set_device(rank)\n\n            if self.config.actor.megatron.sequence_parallel:\n                os.environ['CUDA_DEVICE_MAX_CONNECTIONS'] = '1'\n            mpu.initialize_model_parallel(\n                tensor_model_parallel_size=self.config.actor.megatron.tensor_model_parallel_size,\n                pipeline_model_parallel_size=self.config.actor.megatron.pipeline_model_parallel_size,\n                virtual_pipeline_model_parallel_size=None,\n                pipeline_model_parallel_split_rank=None,\n                use_sharp=False,\n                context_parallel_size=1,\n                expert_model_parallel_size=1,\n                nccl_communicator_config_path=None,\n            )\n\n        set_random_seed(seed=self.config.actor.megatron.seed)\n\n        self.role = role\n        assert self.role in ['actor', 'rollout', 'ref', 'actor_rollout', 'actor_rollout_ref']\n\n        self._is_actor = self.role in ['actor', 'actor_rollout', 'actor_rollout_ref']\n        self._is_rollout = self.role in ['rollout', 'actor_rollout', 'actor_rollout_ref']\n        self._is_ref = self.role in ['ref', 'actor_rollout_ref']\n\n        # TODO(sgm): Currently, we only support reference model param offload\n        # will support other offload later\n        self._is_offload_param = False\n        self._is_offload_grad = False\n        self._is_offload_optimizer = False\n\n        # normalize config\n        if self._is_actor and self._is_rollout:\n            self.config.actor.ppo_mini_batch_size *= self.config.rollout.n\n            self.config.actor.ppo_mini_batch_size //= mpu.get_data_parallel_world_size()\n            if self.config.actor.get('ppo_micro_batch_size', None):\n                self.config.actor.ppo_micro_batch_size //= mpu.get_data_parallel_world_size()\n                self.config.rollout.log_prob_micro_batch_size //= mpu.get_data_parallel_world_size()\n                self.config.actor.ppo_micro_batch_size_per_gpu = self.config.actor.ppo_micro_batch_size\n                self.config.rollout.log_prob_micro_batch_size_per_gpu = self.config.rollout.log_prob_micro_batch_size\n\n            self._is_offload_param = self.config.actor.get('param_offload', False)\n            self._is_offload_grad = self.config.actor.get('grad_offload', False)\n            self._is_offload_optimizer = self.config.actor.get('optimizer_offload', False)\n        elif self._is_ref:\n            if self.config.ref.get('ppo_micro_batch_size', None):\n                self.config.ref.log_prob_micro_batch_size //= mpu.get_data_parallel_world_size()\n                self.config.ref.ppo_micro_batch_size_per_gpu = self.config.ref.ppo_micro_batch_size\n            self._is_offload_param = self.config.ref.get('param_offload', False)\n\n    def _build_model_optimizer(self,\n                               model_path,\n                               megatron_config: ModelParallelConfig,\n                               optim_config,\n                               override_model_config,\n                               enable_gradient_checkpointing=False):\n        from verl.utils.megatron.optimizer import get_megatron_optimizer\n        from megatron.core.models.gpt.gpt_model import ModelType\n        from verl.utils.model import print_model_size, update_model_config, get_generation_config\n        from verl.utils.megatron_utils import get_model, init_megatron_optim_config\n        from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig, GenerationConfig\n\n        # Step 1: initialize the tokenizer\n        local_path = copy_to_local(model_path)\n        self.tokenizer = hf_tokenizer(local_path)\n\n        # Step 2: get the actor_model_config\n        actor_model_config = AutoConfig.from_pretrained(local_path)\n\n        self.generation_config = get_generation_config(local_path)\n\n        override_config_kwargs = {\n            'bos_token_id': self.tokenizer.bos_token_id,\n            'eos_token_id': self.tokenizer.eos_token_id,\n            'pad_token_id': self.tokenizer.pad_token_id,\n        }\n        override_config_kwargs.update(override_model_config)\n        update_model_config(actor_model_config, override_config_kwargs=override_config_kwargs)\n\n        if self.rank == 0:\n            print(f'Model config after override: {actor_model_config}')\n\n        def megatron_actor_model_provider(pre_process, post_process):\n            from verl.utils.model import get_parallel_model_from_config\n            # vpp is not supported yet because it will hang for some reason. Need debugging\n            vpp_rank = mpu.get_virtual_pipeline_model_parallel_rank()  # this will be set inside get_model\n            # this_megatron_config = copy.deepcopy(megatron_config)\n            # this_megatron_config.virtual_pipeline_model_parallel_rank = vpp_rank\n            share_embeddings_and_output_weights = getattr(actor_model_config, \"tie_word_embeddings\", False)\n            parallel_model = get_parallel_model_from_config(\n                config=actor_model_config,\n                megatron_config=megatron_config,\n                pre_process=pre_process,\n                post_process=post_process,\n                share_embeddings_and_output_weights=share_embeddings_and_output_weights,\n                value=False)\n            parallel_model.cuda()\n            return parallel_model\n\n        # Step 3: initialize the megatron model\n        if self._is_actor and self._is_rollout:\n            # Initialize the 3D HybridEngine\n            hybrid_engine = AllGatherPPModel(model_provider=megatron_actor_model_provider)\n            # Fetch the model at current rank\n            actor_module = hybrid_engine.this_rank_models\n            if isinstance(actor_module, nn.ModuleList):\n                actor_module = [actor_module[0]]\n            if self.config.actor.load_weight:\n                load_megatron_model_weights(self.config,\n                                            actor_model_config,\n                                            actor_module,\n                                            params_dtype=megatron_config.params_dtype,\n                                            is_value_model=False)\n\n            if self.rank == 0:\n                print_model_size(actor_module[0])\n            log_gpu_memory_usage('After AllGatherPPModel init', logger=logger)\n        elif self._is_ref:\n            print(f'self.config.ref.load_weight: {self.config.ref.load_weight}')\n            ref_module = get_model(model_provider_func=megatron_actor_model_provider,\n                                   model_type=ModelType.encoder_or_decoder,\n                                   wrap_with_ddp=False)\n            # ref_module = nn.ModuleList(ref_module)\n\n            if self.config.ref.load_weight:  # should align with the actor:\n                assert self.config.actor.load_weight == self.config.ref.load_weight\n                print(f'load ref weight start')\n                load_megatron_model_weights(self.config,\n                                            actor_model_config,\n                                            ref_module,\n                                            params_dtype=megatron_config.params_dtype,\n                                            is_value_model=False)\n            log_gpu_memory_usage('After ref module init', logger=logger)\n            return ref_module, actor_model_config\n\n        # TODO: add more optimizer args into config\n        if self._is_actor:\n            optim_config = init_megatron_optim_config(optim_config)\n            actor_optimizer = get_megatron_optimizer(model=actor_module, config=optim_config)\n        else:\n            optim_config = None\n            actor_optimizer = None\n\n        log_gpu_memory_usage('After actor optimizer init', logger=logger)\n\n        return actor_module, hybrid_engine, actor_optimizer, actor_model_config, optim_config\n\n    def _build_rollout(self):\n        if self.config.rollout.name == 'vllm':\n            from verl.workers.rollout.vllm_rollout import vLLMRollout, vllm_mode\n            from verl.workers.sharding_manager import MegatronVLLMShardingManager\n            from verl.utils.model import normalize_pp_vpp_params\n\n            # NOTE(sgm): If the QKV and gate_up projection layer are concate together in actor,\n            # we will reorganize their weight format when resharding from actor to rollout.\n            layer_name_mapping = {\n                \"qkv_layer_name\":\n                    self.config.rollout.layer_name_map.get(\"qkv_layer_name\", \"qkv\"),\n                \"gate_proj_layer_name\":\n                    self.config.rollout.layer_name_map.get(\"gate_proj_layer_name\", \"linear_fc1.weight\"),\n            }\n\n            # reshard the weight partition from actor to rollout to initialize the rollout class\n            # create a new cuda space for parameters not in this pp rank\n            self.hybrid_engine.load_params_to_cuda()\n            # broadcast the parameters from pp rank to other ranks\n            self.hybrid_engine.allgather_params()\n            # obtain name to parameters in pp/vpp\n            params = self.hybrid_engine.get_all_params()\n            # update the param name for the\n            params = normalize_pp_vpp_params(params=params,\n                                             num_hidden_layers=self.actor_model_config.num_hidden_layers,\n                                             layer_name='layers')\n            assert vllm_mode == 'customized', \"Support for vllm>=0.7 for Megatron-LM backend has not been implemented yet.\"\n            rollout = vLLMRollout(actor_module=params,\n                                  config=self.config.rollout,\n                                  tokenizer=self.tokenizer,\n                                  model_hf_config=self.actor_model_config,\n                                  train_tp=mpu.get_tensor_model_parallel_world_size())\n            log_gpu_memory_usage('After building vllm rollout', logger=logger)\n\n            # perform weight resharding between actor and rollout\n            sharding_manager = MegatronVLLMShardingManager(module=self.hybrid_engine,\n                                                           inference_engine=rollout.inference_engine,\n                                                           model_config=self.actor_model_config,\n                                                           layer_name_mapping=layer_name_mapping)\n            log_gpu_memory_usage('After building sharding manager', logger=logger)\n        else:\n            NotImplementedError('Only vllmRollout is supported with Megatron now')\n\n        return rollout, sharding_manager\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def init_model(self):\n        if self.config.model.get('external_lib', None) is not None:\n            # This is used to import external_lib into the huggingface systems\n            import importlib\n            importlib.import_module(self.config.model.external_lib)\n\n        from omegaconf import OmegaConf\n        from verl.utils.torch_dtypes import PrecisionType\n        override_model_config = OmegaConf.to_container(self.config.model.get('override_config', OmegaConf.create()))\n        torch_dtype = torch.bfloat16\n\n        megatron_config = OmegaConf.create({\n            'sequence_parallel': self.config.actor.megatron.get('sequence_parallel', True),\n            'param_dtype': PrecisionType.to_str(torch_dtype),\n            'tensor_model_parallel_size': mpu.get_tensor_model_parallel_world_size(),\n            'pipeline_model_parallel_rank': mpu.get_pipeline_model_parallel_rank(),\n            'pipeline_model_parallel_size': mpu.get_pipeline_model_parallel_world_size(),\n            'virtual_pipeline_model_parallel_rank': mpu.get_virtual_pipeline_model_parallel_rank(),\n            'virtual_pipeline_model_parallel_size': mpu.get_virtual_pipeline_model_parallel_world_size()\n        })\n\n        megatron_config = init_model_parallel_config(megatron_config)\n\n        if self._is_actor or self._is_rollout:\n            # we need the model for actor and rollout\n            if self._is_actor:\n                optim_config = self.config.actor.optim\n            else:\n                optim_config = None\n            self.actor_module, self.hybrid_engine, self.actor_optimizer, \\\n            self.actor_model_config, self.actor_optim_config = self._build_model_optimizer(\n                model_path=self.config.model.path,\n                megatron_config=megatron_config,\n                optim_config=optim_config,\n                override_model_config=override_model_config,\n            )\n\n        if self._is_actor:\n            self.actor = MegatronPPOActor(config=self.config.actor,\n                                          model_config=self.actor_model_config,\n                                          megatron_config=megatron_config,\n                                          actor_module=self.actor_module,\n                                          actor_optimizer=self.actor_optimizer,\n                                          actor_optimizer_config=self.actor_optim_config)\n\n        if self._is_rollout:\n            self.rollout, self.sharding_manager = self._build_rollout()\n\n        if self._is_ref:\n            self.ref_module, self.ref_model_config = self._build_model_optimizer(\n                model_path=self.config.model.path,\n                megatron_config=megatron_config,\n                optim_config=None,\n                override_model_config=override_model_config,\n            )\n            self.ref_policy = MegatronPPOActor(config=self.config.ref,\n                                               model_config=self.ref_model_config,\n                                               megatron_config=megatron_config,\n                                               actor_module=self.ref_module,\n                                               actor_optimizer=None,\n                                               actor_optimizer_config=None)\n\n        if self._is_actor:\n            self.flops_counter = FlopsCounter(self.actor_model_config)\n\n        torch.cuda.empty_cache()\n\n    @register(dispatch_mode=Dispatch.MEGATRON_COMPUTE_PROTO)\n    def update_actor(self, data: DataProto):\n        assert self._is_actor\n\n        data.batch = data.batch.cuda()\n\n        log_gpu_memory_usage('Before update policy', logger=logger)\n\n        dataloader = self.actor.make_minibatch_iterator(data=data)\n        with Timer(name='update_policy', logger=None) as timer:\n            metrics = self.actor.update_policy(dataloader=dataloader)\n        delta_time = timer.last\n        global_num_tokens = data.meta_info['global_token_num']\n        estimated_flops, promised_flops = self.flops_counter.estimate_flops(global_num_tokens, delta_time)\n        metrics['mfu/actor'] = estimated_flops * self.config.actor.ppo_epochs / promised_flops / self.world_size\n\n        log_gpu_memory_usage('After update policy', logger=logger)\n\n        # TODO: here, we should return all metrics\n        output = DataProto(meta_info={'metrics': metrics})\n        output = output.to('cpu')\n        torch.cuda.empty_cache()\n        return output\n\n    @register(dispatch_mode=Dispatch.MEGATRON_PP_AS_DP_PROTO)\n    def generate_sequences(self, prompts: DataProto):\n        assert self._is_rollout\n\n        prompts.batch = prompts.batch.cuda()\n        meta_info = {\n            'eos_token_id':\n                self.generation_config.eos_token_id\n                if self.generation_config is not None else self.tokenizer.eos_token_id,\n            'pad_token_id':\n                self.generation_config.pad_token_id\n                if self.generation_config is not None else self.tokenizer.pad_token_id,\n        }\n        prompts.meta_info.update(meta_info)\n        with self.sharding_manager:\n            log_gpu_memory_usage('After entering sharding manager', logger=logger)\n\n            prompts = self.sharding_manager.preprocess_data(prompts)\n            output = self.rollout.generate_sequences(prompts=prompts)\n\n            log_gpu_memory_usage('After rollout generation', logger=logger)\n\n            output = self.sharding_manager.postprocess_data(output)\n\n        output = output.to('cpu')\n        # clear kv cache\n        torch.cuda.empty_cache()\n        log_gpu_memory_usage('After recompute log prob', logger=logger)\n        return output\n\n    @register(dispatch_mode=Dispatch.MEGATRON_COMPUTE_PROTO)\n    def compute_ref_log_prob(self, data: DataProto):\n        data = data.to('cuda')\n\n        assert self._is_ref\n        if self._is_offload_param:\n            load_megatron_param_and_grad(self.ref_module, torch.cuda.current_device(), self._is_offload_grad)\n\n        micro_batch_size = self.config.rollout.log_prob_micro_batch_size_per_gpu\n        data.meta_info['micro_batch_size'] = micro_batch_size\n        data.meta_info['temperature'] = self.config.rollout.temperature\n        output = self.ref_policy.compute_log_prob(data=data)\n        output = DataProto.from_dict(tensors={'ref_log_prob': output})\n        output = output.to('cpu')\n        if self._is_offload_param:\n            offload_megatron_param_and_grad(self.ref_module, self._is_offload_grad)\n        torch.cuda.empty_cache()\n        return output\n\n    @register(dispatch_mode=Dispatch.MEGATRON_COMPUTE_PROTO)\n    def compute_log_prob(self, data: DataProto):\n        assert self._is_actor\n        data = data.to('cuda')\n        output = data\n        # we should always recompute old_log_probs when it is HybridEngine\n        output.meta_info['micro_batch_size'] = self.config.rollout.log_prob_micro_batch_size_per_gpu\n        output.meta_info['temperature'] = self.config.rollout.temperature\n        old_log_probs = self.actor.compute_log_prob(data=output)\n        output.batch['old_log_probs'] = old_log_probs\n        output = output.to('cpu')\n        # clear kv cache\n        torch.cuda.empty_cache()\n        log_gpu_memory_usage('After recompute log prob', logger=logger)\n        return output\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def load_checkpoint(self, checkpoint_path, **kwargs):\n        pass\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def load_pretrained_model(self, checkpoint_path, **kwargs):\n        pass\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def save_checkpoint(self, checkpoint_path, **kwargs):\n        assert self._is_actor\n        pass\n\n\nclass CriticWorker(MegatronWorker):\n\n    def __init__(self, config):\n        super().__init__()\n        self.config = config\n\n        # NOTE(sgm): We utilize colocate WorkerGroup by default.\n        # As a result, Workers for different model share the same process.\n        # Therefore, we only require one distribute initialization.\n        # To utilize different parallel startegy in different models:\n        # 1, users should disable WorkerDict; 2.assign different ResourcePool to different models,\n        # 3. and apply the following patch in ray==2.10, https://github.com/ray-project/ray/pull/44385\n        if not torch.distributed.is_initialized():\n            rank = int(os.environ['LOCAL_RANK'])\n            torch.distributed.init_process_group(backend=\"nccl\")\n            torch.cuda.set_device(rank)\n\n            if self.config.megatron.sequence_parallel:\n                os.environ['CUDA_DEVICE_MAX_CONNECTIONS'] = '1'\n            mpu.initialize_model_parallel(\n                tensor_model_parallel_size=self.config.megatron.tensor_model_parallel_size,\n                pipeline_model_parallel_size=self.config.megatron.pipeline_model_parallel_size,\n                virtual_pipeline_model_parallel_size=None,\n                pipeline_model_parallel_split_rank=None,\n                use_sharp=False,\n                context_parallel_size=1,\n                expert_model_parallel_size=1,\n                nccl_communicator_config_path=None,\n            )\n\n        set_random_seed(seed=self.config.megatron.seed)\n\n        # normalize config\n        self.config.ppo_mini_batch_size //= mpu.get_data_parallel_world_size()\n        if self.config.get('ppo_micro_batch_size', None):\n            self.config.ppo_micro_batch_size //= mpu.get_data_parallel_world_size()\n            self.config.ppo_micro_batch_size_per_gpu = self.config.ppo_micro_batch_size\n\n        # TODO(sgm): support critic model offload\n\n    def _build_critic_model_optimizer(self,\n                                      model_path,\n                                      megatron_config: ModelParallelConfig,\n                                      optim_config,\n                                      override_model_config,\n                                      enable_gradient_checkpointing=False):\n        from megatron.core.models.gpt.gpt_model import ModelType\n        from verl.utils.model import print_model_size, update_model_config\n        from verl.utils.megatron.optimizer import get_megatron_optimizer\n        from verl.utils.megatron_utils import get_model, init_megatron_optim_config, init_model_parallel_config\n        from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig\n\n        # Step 1: initialize the tokenizer\n        local_path = copy_to_local(model_path)\n        self.tokenizer = hf_tokenizer(local_path)\n\n        # Step 2: get the actor_model_config\n        critic_model_config = AutoConfig.from_pretrained(local_path)\n\n        override_config_kwargs = {\n            'bos_token_id': self.tokenizer.bos_token_id,\n            'eos_token_id': self.tokenizer.eos_token_id,\n            'pad_token_id': self.tokenizer.pad_token_id,\n        }\n        override_config_kwargs.update(override_model_config)\n        update_model_config(critic_model_config, override_config_kwargs=override_config_kwargs)\n\n        if self.rank == 0:\n            print(f'Model config after override: {critic_model_config}')\n\n        def megatron_critic_model_provider(pre_process, post_process):\n            from verl.utils.model import get_parallel_model_from_config\n            # TODO: support vpp here\n            # vpp_rank = mpu.get_virtual_pipeline_model_parallel_rank()  # this will be set inside get_model\n            # this_megatron_config = copy.deepcopy(megatron_config)\n            # this_megatron_config.virtual_pipeline_model_parallel_rank = vpp_rank\n            parallel_model = get_parallel_model_from_config(config=critic_model_config,\n                                                            megatron_config=megatron_config,\n                                                            pre_process=pre_process,\n                                                            post_process=post_process,\n                                                            share_embeddings_and_output_weights=False,\n                                                            value=True)\n            parallel_model.cuda()\n            return parallel_model\n\n        # Step 3: initialize the megatron model\n        critic_module = get_model(model_provider_func=megatron_critic_model_provider,\n                                  model_type=ModelType.encoder_or_decoder,\n                                  wrap_with_ddp=True)\n        # note that here critic_module will be a list to be compatible with the construction of interleaved pp (vpp).\n        # but here, we do not use pp (vpp) yet. For simplicity, we remove the list\n        # critic_module = nn.ModuleList(critic_module)\n\n        if self.config.load_weight:\n            load_megatron_model_weights(self.config,\n                                        critic_model_config,\n                                        critic_module,\n                                        params_dtype=megatron_config.params_dtype,\n                                        is_value_model=True)\n        if self.rank == 0:\n            print_model_size(critic_module[0])\n\n        # TODO: add more optimizer args into config\n        optim_config = init_megatron_optim_config(optim_config)\n        critic_optimizer = get_megatron_optimizer(model=critic_module, config=optim_config)\n        torch.cuda.empty_cache()\n        return critic_module, critic_optimizer, critic_model_config, optim_config\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def init_model(self):\n        # create critic\n        from omegaconf import OmegaConf\n        from verl.utils.torch_dtypes import PrecisionType\n\n        if self.config.model.get('external_lib', None) is not None:\n            # This is used to import external_lib into the huggingface systems\n            import importlib\n            importlib.import_module(self.config.model.external_lib)\n        override_model_config = OmegaConf.to_container(self.config.model.get('override_config', OmegaConf.create()))\n        torch_dtype = torch.bfloat16\n\n        megatron_config = OmegaConf.create({\n            'sequence_parallel': self.config.megatron.get('sequence_parallel', True),\n            'param_dtype': PrecisionType.to_str(torch_dtype),\n            'tensor_model_parallel_size': mpu.get_tensor_model_parallel_world_size(),\n            'pipeline_model_parallel_rank': mpu.get_pipeline_model_parallel_rank(),\n            'pipeline_model_parallel_size': mpu.get_pipeline_model_parallel_world_size(),\n            'virtual_pipeline_model_parallel_rank': mpu.get_virtual_pipeline_model_parallel_rank(),\n            'virtual_pipeline_model_parallel_size': mpu.get_virtual_pipeline_model_parallel_world_size()\n        })\n\n        megatron_config = init_model_parallel_config(megatron_config)\n\n        critic_module, critic_optimizer, critic_model_config, critic_optimizer_config = self._build_critic_model_optimizer(\n            model_path=self.config.model.path,\n            megatron_config=megatron_config,\n            optim_config=self.config.optim,\n            override_model_config=override_model_config)\n        self.critic = MegatronPPOCritic(config=self.config,\n                                        model_config=critic_model_config,\n                                        megatron_config=megatron_config,\n                                        critic_module=critic_module,\n                                        critic_optimizer=critic_optimizer,\n                                        critic_optimizer_config=critic_optimizer_config)\n        self.flops_counter = FlopsCounter(critic_model_config)\n\n    @register(dispatch_mode=Dispatch.MEGATRON_COMPUTE_PROTO)\n    def compute_values(self, data: DataProto):\n        data = data.to('cuda')\n        values = self.critic.compute_values(data=data)\n        output = DataProto.from_dict(tensors={'values': values})\n        output = output.to('cpu')\n        return output\n\n    @register(dispatch_mode=Dispatch.MEGATRON_COMPUTE_PROTO)\n    def update_critic(self, data: DataProto):\n        data = data.to('cuda')\n        dataloader = self.critic.make_minibatch_iterator(data)\n        with Timer(name='update_critic', logger=None) as timer:\n            metrics = self.critic.update_critic(dataloader=dataloader)\n        delta_time = timer.last\n        global_num_tokens = data.meta_info['global_token_num']\n        estimated_flops, promised_flops = self.flops_counter.estimate_flops(global_num_tokens, delta_time)\n        metrics['mfu/critic'] = estimated_flops * self.config.ppo_epochs / promised_flops / self.world_size\n        output = DataProto(batch=None, meta_info={'metrics': metrics})\n        output = output.to('cpu')\n        return output\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def load_checkpoint(self, checkpoint_path, **kwargs):\n        pass\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def save_checkpoint(self, checkpoint_path, **kwargs):\n        pass\n\n\nclass RewardModelWorker(MegatronWorker):\n    \"\"\"\n    Note that we only implement the reward model that is subclass of AutoModelForSequenceClassification.\n    \"\"\"\n\n    def __init__(self, config):\n        super().__init__()\n        self.config = config\n\n        # NOTE(sgm): We utilize colocate WorkerGroup by default.\n        # As a result, Workers for different model share the same process.\n        # Therefore, we only require one distribute initialization.\n        # To utilize different parallel startegy in different models:\n        # 1, users should disable WorkerDict; 2.assign different ResourcePool to different models,\n        # 3. and apply the following patch in ray==2.10, https://github.com/ray-project/ray/pull/44385\n        if not torch.distributed.is_initialized():\n            rank = int(os.environ['LOCAL_RANK'])\n            torch.distributed.init_process_group(backend=\"nccl\")\n            torch.cuda.set_device(rank)\n\n            if self.config.megatron.sequence_parallel:\n                os.environ['CUDA_DEVICE_MAX_CONNECTIONS'] = '1'\n            mpu.initialize_model_parallel(\n                tensor_model_parallel_size=self.config.megatron.tensor_model_parallel_size,\n                pipeline_model_parallel_size=self.config.megatron.pipeline_model_parallel_size,\n                virtual_pipeline_model_parallel_size=None,\n                pipeline_model_parallel_split_rank=None,\n                use_sharp=False,\n                context_parallel_size=1,\n                expert_model_parallel_size=1,\n                nccl_communicator_config_path=None,\n            )\n\n        set_random_seed(seed=self.config.megatron.seed)\n\n        # normalize config\n        if self.config.micro_batch_size is not None:\n            self.config.micro_batch_size //= mpu.get_data_parallel_world_size()\n            self.config.micro_batch_size_per_gpu = self.config.micro_batch_size\n\n    def _build_rm_model(self, model_path, megatron_config: ModelParallelConfig, override_model_config):\n        from megatron.core.models.gpt.gpt_model import ModelType\n        from verl.utils.model import print_model_size, update_model_config\n        from verl.utils.megatron_utils import get_model\n        from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig\n\n        # Step 1: initialize the tokenizer\n        local_path = copy_to_local(model_path)\n        self.tokenizer = hf_tokenizer(local_path)\n\n        # Step 2: get the actor_model_config\n        rm_model_config = AutoConfig.from_pretrained(local_path)\n\n        override_config_kwargs = {\n            'bos_token_id': self.tokenizer.bos_token_id,\n            'eos_token_id': self.tokenizer.eos_token_id,\n            'pad_token_id': self.tokenizer.pad_token_id,\n        }\n        override_config_kwargs.update(override_model_config)\n        update_model_config(rm_model_config, override_config_kwargs=override_config_kwargs)\n\n        if self.rank == 0:\n            print(f'Model config after override: {rm_model_config}')\n\n        def megatron_rm_model_provider(pre_process, post_process):\n            from verl.utils.model import get_parallel_model_from_config\n            # vpp is not supported yet because it will hang for some reason. Need debugging\n            vpp_rank = mpu.get_virtual_pipeline_model_parallel_rank()  # this will be set inside get_model\n            # this_megatron_config = copy.deepcopy(megatron_config)\n            # this_megatron_config.virtual_pipeline_model_parallel_rank = vpp_rank\n            parallel_model = get_parallel_model_from_config(config=rm_model_config,\n                                                            megatron_config=megatron_config,\n                                                            pre_process=pre_process,\n                                                            post_process=post_process,\n                                                            share_embeddings_and_output_weights=False,\n                                                            value=True)\n            parallel_model.cuda()\n            return parallel_model\n\n        # Step 3: initialize the megatron model\n        reward_model = get_model(model_provider_func=megatron_rm_model_provider,\n                                 model_type=ModelType.encoder_or_decoder,\n                                 wrap_with_ddp=False)\n        # note that here critic_module will be a list to be compatible with the construction of interleaved pp (vpp).\n        # but here, we do not use pp (vpp) yet. For simplicity, we remove the list\n        # reward_model = nn.ModuleList(reward_model)\n\n        if self.config.load_weight:\n            load_megatron_model_weights(self.config,\n                                        rm_model_config,\n                                        reward_model,\n                                        params_dtype=megatron_config.params_dtype,\n                                        is_value_model=True)\n\n        # TODO: add more optimizer args into config\n        torch.cuda.empty_cache()\n        return reward_model, rm_model_config\n\n    @register(dispatch_mode=Dispatch.ONE_TO_ALL)\n    def init_model(self):\n        # create critic\n        from omegaconf import OmegaConf\n        from verl.utils.torch_dtypes import PrecisionType\n        from transformers import AutoTokenizer\n\n        if self.config.model.get('external_lib', None) is not None:\n            # This is used to import external_lib into the huggingface systems\n            import importlib\n            importlib.import_module(self.config.model.external_lib)\n        override_model_config = OmegaConf.to_container(self.config.model.get('override_config', OmegaConf.create()))\n\n        sft_tokenizer_local_path = copy_to_local(self.config.model.input_tokenizer)\n        sft_tokenizer = hf_tokenizer(sft_tokenizer_local_path)\n        rm_tokenizer_path = self.config.model.get('rm_tokenizer', None)\n        rm_tokenizer = None\n        if rm_tokenizer_path is not None:\n            rm_tokenizer_local_path = copy_to_local(rm_tokenizer_path)\n            rm_tokenizer = hf_tokenizer(rm_tokenizer_local_path)\n\n        torch_dtype = torch.bfloat16\n\n        megatron_config = OmegaConf.create({\n            'sequence_parallel': self.config.megatron.get('sequence_parallel', True),\n            'param_dtype': PrecisionType.to_str(torch_dtype),\n            'tensor_model_parallel_size': mpu.get_tensor_model_parallel_world_size(),\n            'pipeline_model_parallel_rank': mpu.get_pipeline_model_parallel_rank(),\n            'pipeline_model_parallel_size': mpu.get_pipeline_model_parallel_world_size(),\n            'virtual_pipeline_model_parallel_rank': mpu.get_virtual_pipeline_model_parallel_rank(),\n            'virtual_pipeline_model_parallel_size': mpu.get_virtual_pipeline_model_parallel_world_size()\n        })\n\n        megatron_config = init_model_parallel_config(megatron_config)\n\n        reward_model_module, reward_model_config = self._build_rm_model(\n            model_path=self.config.model.path,\n            megatron_config=megatron_config,\n            override_model_config=override_model_config,\n        )\n        # FIXME(sgm): reward model param offload is implemented in MegatronRewardModel\n        # should be implemented in workers\n        self.rm = MegatronRewardModel(config=self.config,\n                                      reward_model_module=reward_model_module,\n                                      model_config=reward_model_config,\n                                      megatron_config=megatron_config,\n                                      sft_tokenizer=sft_tokenizer,\n                                      rm_tokenizer=rm_tokenizer)\n\n    # TODO: reward model use itself tokenizer instead of sft tokenizer\n    # the input_ids, responses, attention_mask and position_ids may be different!\n    @register(dispatch_mode=Dispatch.MEGATRON_COMPUTE_PROTO)\n    def compute_rm_score(self, data: DataProto):\n        data.batch = data.batch.cuda()\n        output = self.rm.compute_reward(data)\n        output = output.to('cpu')\n        return output\n"
  },
  {
    "path": "verl/workers/reward_manager/__init__.py",
    "content": "# Copyright 2024 PRIME team and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .naive import NaiveRewardManager\nfrom .prime import PrimeRewardManager"
  },
  {
    "path": "verl/workers/reward_manager/naive.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom verl import DataProto\nfrom verl.utils.reward_score import _default_compute_score\nimport torch\n\n\nclass NaiveRewardManager:\n    \"\"\"The reward manager.\n    \"\"\"\n\n    def __init__(self, config, tokenizer, num_examine, compute_score=None) -> None:\n        self.tokenizer = tokenizer\n        self.num_examine = num_examine  # the number of batches of decoded responses to print to the console\n        self.compute_score = compute_score or _default_compute_score\n        self.config = config\n\n    def __call__(self, data: DataProto):\n        \"\"\"We will expand this function gradually based on the available datasets\"\"\"\n\n        # If there is rm score, we directly return rm score. Otherwise, we compute via rm_score_fn\n        if 'rm_scores' in data.batch.keys():\n            return data.batch['rm_scores']\n\n        reward_tensor = torch.zeros_like(data.batch['responses'], dtype=torch.float32)\n\n        already_print_data_sources = {}\n\n        for i in range(len(data)):\n            data_item = data[i]  # DataProtoItem\n\n            prompt_ids = data_item.batch['prompts']\n\n            prompt_length = prompt_ids.shape[-1]\n\n            valid_prompt_length = data_item.batch['attention_mask'][:prompt_length].sum()\n            valid_prompt_ids = prompt_ids[-valid_prompt_length:]\n\n            response_ids = data_item.batch['responses']\n            valid_response_length = data_item.batch['attention_mask'][prompt_length:].sum()\n            valid_response_ids = response_ids[:valid_response_length]\n\n            # decode\n            prompt_str = self.tokenizer.decode(valid_prompt_ids)\n            response_str = self.tokenizer.decode(valid_response_ids)\n\n            ground_truth = data_item.non_tensor_batch['reward_model']['ground_truth']\n\n            data_source = data_item.non_tensor_batch['data_source']\n\n            extra_info = data_item.non_tensor_batch.get('extra_info', None)\n\n            score = self.compute_score(\n                data_source=data_source,\n                solution_str=response_str,\n                ground_truth=ground_truth,\n                extra_info=extra_info,\n                reward_type=self.config.data.reward_type\n            )\n            if self.config.data.execution_error_penalty and data_item.batch['execution_passes'].item()==0:\n                score-=0.5\n            reward_tensor[i, valid_response_length - 1] = score\n\n            if data_source not in already_print_data_sources:\n                already_print_data_sources[data_source] = 0\n\n            if already_print_data_sources[data_source] < self.num_examine:\n                already_print_data_sources[data_source] += 1\n                # print(\"[prompt]\", prompt_str)\n                # print(\"[response]\", response_str)\n                # print(\"[ground_truth]\", ground_truth)\n                # print(\"[score]\", score)\n\n        return reward_tensor\n"
  },
  {
    "path": "verl/workers/reward_manager/prime.py",
    "content": "# Copyright 2024 PRIME team and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport asyncio\nfrom concurrent.futures import ProcessPoolExecutor\nfrom functools import partial\n\nimport torch\n\nfrom verl import DataProto\nfrom verl.utils.reward_score import _default_compute_score\n\n\nasync def single_compute_score(evaluation_func, completion, reference, task, task_extra_info, executor, timeout=300.):\n    loop = asyncio.get_running_loop()\n    try:\n        # Ensure process_completion is called properly\n        tasks = [\n            asyncio.wait_for(\n                loop.run_in_executor(\n                    executor,\n                    partial(evaluation_func, task, completion, reference, task_extra_info)  # Ensure synchronous\n                ),\n                timeout=timeout)\n        ]\n        return await asyncio.gather(*tasks)\n    except asyncio.TimeoutError:\n        print(f\"Timeout occurred for completion: {completion}\")\n        return None  # Default value for timed-out rows\n    except Exception as e:\n        print(f\"Error processing completion: {completion[:10]}, Error: {e}\")\n        return None  # Default value for failed rows\n\n\nasync def parallel_compute_score_async(evaluation_func,\n                                       completions,\n                                       references,\n                                       tasks,\n                                       extra_info=None,\n                                       num_processes=64):\n    scores = []\n    with ProcessPoolExecutor(max_workers=num_processes) as executor:\n        if extra_info is None:\n            extra_info = [None] * len(tasks)\n        # Create tasks for all rows\n        tasks_async = [\n            single_compute_score(evaluation_func, completion, reference, task, task_extra_info, executor, timeout=300.)\n            for completion, reference, task, task_extra_info in zip(completions, references, tasks, extra_info)\n        ]\n        # to prevent very occasional starvation caused by some anomalous programs ( like infinite loop ), the exceptions in async programs will instantly halt the evaluation, and all summoned processes will be killed.\n        try:\n            results = await asyncio.gather(*tasks_async, return_exceptions=False)\n        except:\n            for pid, proc in executor._processes.items():\n                try:\n                    proc.kill()\n                except Exception as kill_err:\n                    print('shut down failed: ' + str(kill_err))\n            raise\n\n    # Process results\n    for result, completion, reference, task in zip(results, completions, references, tasks):\n        if isinstance(result, Exception) or result is None:\n            # Handle failed or timed-out tasks\n            scores.append(0.0)\n        elif isinstance(result[0], (int, float, bool)):\n            scores.append(float(result[0]))\n        else:\n            scores.append(float(result[0][0]))\n    return scores\n\n\nclass PrimeRewardManager:\n    \"\"\"\n    The Reward Manager used in https://github.com/PRIME-RL/PRIME\n    \"\"\"\n\n    def __init__(self, tokenizer, num_examine, compute_score=None) -> None:\n        self.tokenizer = tokenizer\n        self.num_examine = num_examine  # the number of batches of decoded responses to print to the console\n        self.compute_score = compute_score or _default_compute_score\n\n    def __call__(self, data: DataProto):\n        \"\"\"We will expand this function gradually based on the available datasets\"\"\"\n\n        # If there is rm score, we directly return rm score. Otherwise, we compute via rm_score_fn\n        if 'rm_scores' in data.batch.keys():\n            return data.batch['rm_scores']\n\n        reward_tensor = torch.zeros_like(data.batch['responses'], dtype=torch.float32)\n\n        already_print_data_sources = {}\n\n        # batched scoring\n        prompt_ids = data.batch['prompts']\n        prompt_length = prompt_ids.shape[-1]\n\n        response_ids = data.batch['responses']\n        valid_response_length = data.batch['attention_mask'][:, prompt_length:].sum(dim=-1)\n        response_str = self.tokenizer.batch_decode(response_ids, skip_special_tokens=True)\n        ground_truth = [data_item.non_tensor_batch['reward_model']['ground_truth'] for data_item in data]\n        data_sources = data.non_tensor_batch['data_source']\n        extra_info = data.non_tensor_batch.get('extra_info', [None] * len(data_sources))\n\n        assert len(response_str) == len(ground_truth) == len(data_sources) == len(extra_info)\n        try:\n            scores = asyncio.run(\n                parallel_compute_score_async(self.compute_score,\n                                             response_str,\n                                             ground_truth,\n                                             data_sources,\n                                             extra_info,\n                                             num_processes=64))\n        except asyncio.TimeoutError as e:\n            print('Global timeout in reward computing! Setting all as 0.')\n            scores = [0. for _ in range(len(response_str))]\n        except Exception as e:\n            print(f\"Unexpected error in batched reward computing. Setting all as 0.: {e}\")\n            scores = [0. for _ in range(len(response_str))]\n\n        for i in range(len(data)):\n            data_source = data_sources[i]\n            reward_tensor[i, valid_response_length[i].item() - 1] = scores[i]\n\n            if data_source not in already_print_data_sources:\n                already_print_data_sources[data_source] = 0\n\n            if already_print_data_sources[data_source] < self.num_examine:\n                already_print_data_sources[data_source] += 1\n                print(\"[response]\", response_str[i])\n\n        return reward_tensor\n"
  },
  {
    "path": "verl/workers/reward_model/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .base import BasePPORewardModel\n"
  },
  {
    "path": "verl/workers/reward_model/base.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe base class for reward model\n\"\"\"\n\nfrom abc import ABC, abstractmethod\n\nfrom verl import DataProto\n\n\nclass BasePPORewardModel(ABC):\n\n    def __init__(self, config):\n        self.config = config\n\n    @abstractmethod\n    def compute_reward(self, data: DataProto) -> DataProto:\n        \"\"\"Computing reward given input_ids. The transformers should output a tensor with shape\n           [batch_size, sequence_length], and the value at [EOS] mask should be gathered.\n\n        Args:\n            data: must contain keys \"input_ids\", \"attention_mask\" and \"position_ids\".\n                - input_ids: [batch_size, sequence_length]\n                - attention_mask: [batch_size, sequence_length]\n                - position_ids: [batch_size, sequence_length]\n\n        Returns: a data pass protocol containing \"reward\". Only the [EOS] position contains the reward.\n            Other position should have zero reward. Note that this may change in the future if we use\n            dense reward. So, we leave the interface for general case.\n            - reward: [batch_size, sequence_length].\n\n        \"\"\"\n        pass\n"
  },
  {
    "path": "verl/workers/reward_model/megatron/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .reward_model import MegatronRewardModel\n"
  },
  {
    "path": "verl/workers/reward_model/megatron/reward_model.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nMegatron Reward Model.\n\"\"\"\n\nfrom tensordict import TensorDict\nfrom verl import DataProto\nimport torch\nimport torch.distributed\n\nfrom verl.utils.torch_functional import pad_sequence_to_length\nfrom verl.utils.megatron.pipeline_parallel import (compute_transformers_input_shapes, make_batch_generator)\nfrom verl import DataProto\nfrom verl.utils.torch_functional import broadcast_dict_tensor, split_dict_tensor_into_batches\nfrom verl.workers.reward_model.base import BasePPORewardModel\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core.pipeline_parallel import get_forward_backward_func\n\n\nclass MegatronRewardModel(BasePPORewardModel):\n\n    def __init__(self,\n                 config,\n                 model_config,\n                 reward_model_module: torch.nn.ModuleList,\n                 megatron_config,\n                 sft_tokenizer=None,\n                 rm_tokenizer=None):\n        self.config = config\n        self.reward_model_module = reward_model_module\n        self.megatron_config = megatron_config\n        self.model_config = model_config\n        self.device = 'cuda'\n        self.sft_tokenizer = sft_tokenizer\n        self.rm_tokenizer = rm_tokenizer\n        self.use_different_tokenizer = rm_tokenizer is not None\n\n        if self.config.param_offload:\n            self.offload_params_to_cpu()\n\n    def re_encode_by_rm_tokenizer(self, data: DataProto) -> DataProto:\n        assert self.use_different_tokenizer, 're-encode need rm tokenizer not be None!'\n        # need to use rm tokenizer to re-generate input_ids, attention_mask and position_ids\n        # 1. remove pad for each sequence\n        # 2. decode by sft_tokenizer, remove sft system prompts\n        # 3. encode by rm_tokenizer with rm system prompts, get rm_input_ids\n        # 4. generate attention_mask and position_ids\n        input_ids = data.batch['input_ids']  # (bs, seq_len)\n        attention_mask = data.batch['attention_mask']\n        position_ids = data.batch['position_ids']\n        ori_values = {'input_ids': input_ids, 'attention_mask': attention_mask, 'position_ids': position_ids}\n        ori_bs, ori_seqlen = input_ids.size(0), input_ids.size(1)\n        input_ids_for_rm = []\n        attention_mask_for_rm = []\n        position_ids_for_rm = []\n        print_decode = True\n        ori_seqlen = ori_seqlen + 128\n        for id, mask in zip(input_ids, attention_mask):\n            # 1. remove pad for each sequence\n            non_zero_indices = torch.nonzero(mask).view(-1)\n            begin_pos, end_pos = non_zero_indices[0].item(), non_zero_indices[-1].item()\n            valid_id = id[begin_pos:end_pos + 1]\n            # 2. decode by sft_tokenizer, remove sft system prompts\n            decode_result = self.sft_tokenizer.decode(valid_id)\n            # workaround\n            decode_with_rm_chat = decode_result.replace(\"<|user|>\\n\", \"[INST] \").replace(\n                \"</s>\\n<|assistant|>\\n\", \" [/INST]\").replace(\"</s> \\n<|assistant|>\\n\", \" [/INST]\") + \"</s>\"\n            if print_decode and torch.distributed.get_rank() == 0:\n                # only print first decode result\n                print(f'device {torch.cuda.current_device()}: sft decode result:\\n{decode_result}\\n \\\n                        \\ndevice {torch.cuda.current_device()}: sft decode result with rm chat template:\\n{decode_with_rm_chat}\\n\\n'\n                     )\n                print_decode = False\n            # 3. encode by rm_tokenizer\n            rm_input_ids = self.rm_tokenizer(decode_with_rm_chat,\n                                             return_tensors='pt')['input_ids'][0].to(input_ids.device)\n            # 4. generate attention_mask and position_ids\n            rm_attention_mask = torch.ones_like(rm_input_ids, device=input_ids.device)\n            cur_seqlen = rm_input_ids.shape[-1]\n            # NOTE(gh): the later reward compute will process the shape (bs, seqlen_pad_128)\n            if cur_seqlen > ori_seqlen:\n                print(f'warninig: rm encode seqlen {cur_seqlen} > sft encode seqlen {ori_seqlen}')\n                rm_input_ids = rm_input_ids[:ori_seqlen]\n                rm_attention_mask = rm_attention_mask[:ori_seqlen]\n            else:\n                # right padding\n                rm_input_ids = pad_sequence_to_length(rm_input_ids, ori_seqlen, self.rm_tokenizer.pad_token_id)\n                rm_attention_mask = pad_sequence_to_length(rm_attention_mask, ori_seqlen, 0)\n            rm_position_ids = torch.arange(0, ori_seqlen, device=input_ids.device)\n            input_ids_for_rm.append(torch.unsqueeze(rm_input_ids, dim=0))\n            attention_mask_for_rm.append(torch.unsqueeze(rm_attention_mask, dim=0))\n            position_ids_for_rm.append(torch.unsqueeze(rm_position_ids, dim=0))\n        input_ids_for_rm = torch.cat(input_ids_for_rm, dim=0)\n        attention_mask_for_rm = torch.cat(attention_mask_for_rm, dim=0)\n        position_ids_for_rm = torch.cat(position_ids_for_rm, dim=0)\n\n        # (bs, seqlen) will not change, but input_ids, attention_mask and position_ids will change\n        # NOTE(gh): need to replace into origin values after compute reward!\n        data.batch['input_ids'] = input_ids_for_rm\n        data.batch['attention_mask'] = attention_mask_for_rm\n        data.batch['position_ids'] = position_ids_for_rm\n\n        return data, ori_values\n\n    @torch.no_grad()\n    def compute_reward(self, data: DataProto) -> DataProto:\n        if self.config.param_offload:\n            self.load_params_to_cuda()\n\n        if self.use_different_tokenizer:\n            data, ori_values = self.re_encode_by_rm_tokenizer(data)\n\n        input_ids = data.batch['input_ids']  # (bs, seq_len')\n        attention_mask = data.batch['attention_mask']\n        position_ids = data.batch['position_ids']\n\n        responses = data.batch['responses']\n        batch_size = responses.size(0)\n        response_length = responses.size(1)\n\n        with torch.no_grad():\n            output = self.forward_batch(data)\n            if mpu.is_pipeline_last_stage(ignore_virtual=True):\n                logits = torch.cat([o['logits'] for o in output], dim=0)\n            else:\n                logits = torch.empty(\n                    (input_ids.shape[0], input_ids.shape[1]),\n                    dtype=torch.bfloat16,  # TODO(sgm): check why is bfloat16\n                    device=input_ids.device)\n            # broadcast across pp ranks\n            torch.distributed.broadcast(tensor=logits,\n                                        src=mpu.get_pipeline_model_parallel_last_rank(),\n                                        group=mpu.get_pipeline_model_parallel_group(),\n                                        async_op=False)\n\n        # (bs, seqlen', hidden_size) -> (bs, seqlen', 1) -> (bs, seqlen')\n        token_level_rewards = logits\n        # find the last token reward\n        ends = attention_mask.cumsum(dim=-1).argmax(dim=-1).view(-1, 1)  # (bs, 1)\n        rewards = torch.gather(token_level_rewards, dim=1, index=ends)  # (bs, 1)\n\n        if self.use_different_tokenizer:\n            data.batch.update(ori_values)\n            input_ids = ori_values['input_ids']\n            attention_mask = ori_values['attention_mask']\n            position_ids = ori_values['position_ids']\n\n        token_level_rewards = rewards.expand(attention_mask.shape[0], attention_mask.shape[1])  # (bs, ori_seqlen)\n\n        # assign last valid token reward to ori position\n        eos_mask_idx = torch.argmax(position_ids * attention_mask, dim=-1)  # (bs,)\n        eos_mask = torch.zeros_like(attention_mask)\n        eos_mask[torch.arange(batch_size), eos_mask_idx] = 1.\n\n        token_level_rewards = token_level_rewards * eos_mask\n        token_level_rewards = token_level_rewards[:, -response_length:]\n\n        if self.config.param_offload:\n            self.offload_params_to_cpu()\n        else:\n            # add empty cache after each compute\n            torch.cuda.empty_cache()\n\n        batch = TensorDict({'rm_scores': token_level_rewards}, batch_size=input_ids.shape[0])\n\n        return DataProto(batch=batch)\n\n    def forward_batch(self, data: DataProto):\n        \"\"\"\n        We assume:\n        - The model takes input: (input_ids, attention_mask, position_ids). No rmpad for the input\n        - The communication shape is (total_nnz_pad_to_sp // tp_size, 1, hidden_size) if sequence parallel is enabled\n        \"\"\"\n        # broadcast from last pp rank to all other pp ranks\n        # TODO: actually, we just need to control the sampling order.\n        data.batch = data.batch.contiguous()\n        broadcast_dict_tensor(data.batch,\n                              src=mpu.get_pipeline_model_parallel_last_rank(),\n                              group=mpu.get_pipeline_model_parallel_group())\n\n        # split into micro-batches\n        if self.config is not None and 'ppo_micro_batch_size_per_gpu' in self.config:\n            infer_batch_size = self.config.ppo_micro_batch_size_per_gpu\n        else:\n            infer_batch_size = data.batch.batch_size[0]\n\n        data.batch['attention_mask'] = data.batch['attention_mask'].to(bool)\n        batches = split_dict_tensor_into_batches(data.batch, batch_size=infer_batch_size)\n        n_micro_batch = len(batches)\n        seq_len = batches[0]['input_ids'].shape[1]\n\n        # compute input shapes for pp stages\n        input_shapes = compute_transformers_input_shapes(\n            batches,\n            meta_info={\n                'sequence_parallel': self.megatron_config.sequence_parallel,\n                'hidden_size': self.model_config.hidden_size\n            })\n        # compute input shapes for pp stages\n        forward_backward_func = get_forward_backward_func()\n\n        def loss_func(output):\n            return 1., {'logits': output.logits}\n\n        def forward_step(batch_iter, model):\n            batch = next(batch_iter)\n            input_ids = batch['input_ids']\n            attention_mask = batch['attention_mask']\n            position_ids = batch['position_ids']\n            output = model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids)\n            return output, loss_func\n\n        # batch should be a list of batches inside micro-batches\n        batch_generator = make_batch_generator(batches, vpp_size=len(self.reward_model_module))\n\n        # TODO: we may use the new schedule instead\n        # for flash-attn: (seq_len, batch_size, hidden_size) = (mbs*seq_len, 1, hidden_size)\n        if mpu.get_pipeline_model_parallel_world_size() > 1:\n            losses_reduced = forward_backward_func(\n                forward_step_func=forward_step,\n                data_iterator=batch_generator,\n                model=self.reward_model_module,\n                num_microbatches=n_micro_batch,\n                seq_length=infer_batch_size * seq_len,  # no use when input_shapes was set\n                micro_batch_size=1,  # no use when input_shapes was set\n                forward_only=True,\n            )\n        else:\n            losses_reduced = forward_backward_func(\n                forward_step_func=forward_step,\n                data_iterator=batch_generator,\n                model=self.reward_model_module,\n                num_microbatches=n_micro_batch,\n                seq_length=infer_batch_size * seq_len,  # in use for pp = 1\n                micro_batch_size=1,  # in use for pp = 1\n                forward_only=True,\n            )\n        # loss_reduces contains the stats returned from loss_func\n\n        return losses_reduced\n\n    def offload_params_to_cpu(self):\n        if self.device == 'cuda':\n            for reward_model_module in self.reward_model_module:\n                for name, param in reward_model_module.named_parameters():\n                    param.data = param.data.to('cpu', non_blocking=True)\n            self.device = 'cpu'\n            torch.cuda.empty_cache()\n\n    def load_params_to_cuda(self):\n        if self.device == 'cpu':\n            for reward_model_module in self.reward_model_module:\n                for name, param in reward_model_module.named_parameters():\n                    param.data = param.data.to(torch.cuda.current_device(), non_blocking=True)\n            self.device = 'cuda'\n"
  },
  {
    "path": "verl/workers/rollout/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .base import BaseRollout\nfrom .naive import NaiveRollout\nfrom .hf_rollout import HFRollout\n\n__all__ = [\"BaseRollout\", \"NaiveRollout\", \"HFRollout\"]\n"
  },
  {
    "path": "verl/workers/rollout/base.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom abc import ABC, abstractmethod\nfrom typing import Iterable, Union\n\nfrom verl import DataProto\n\n__all__ = ['BaseRollout']\n\n\nclass BaseRollout(ABC):\n\n    def __init__(self):\n        \"\"\"\n\n        Args:\n            dataloader: an Iterable of TensorDict that consistently generates prompts. Note that the dataloader\n            should handle when the training stops.\n        \"\"\"\n        super().__init__()\n\n    @abstractmethod\n    def generate_sequences(self, prompts: DataProto) -> DataProto:\n        \"\"\"Generate sequences\"\"\"\n        pass\n"
  },
  {
    "path": "verl/workers/rollout/hf_rollout.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nRollout with huggingface models.\nTODO: refactor this class. Currently, it will hang when using FSDP HybridShard. We should actually create a single GPU model.\nThen, get full state_dict and bind the state_dict to the single GPU model. Then, use the single GPU model to perform generation.\n\"\"\"\nimport contextlib\nimport torch\nimport torch.distributed\nfrom tensordict import TensorDict\nfrom torch import nn\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP\n\nfrom verl import DataProto\nfrom verl.utils.torch_functional import get_eos_mask\nfrom .base import BaseRollout\n\nfrom transformers import GenerationConfig\n\n__all__ = ['HFRollout']\n\n\nclass HFRollout(BaseRollout):\n\n    def __init__(self, module: nn.Module, config):\n        super().__init__()\n        self.config = config\n        self.module = module\n\n    def generate_sequences(self, prompts: DataProto) -> DataProto:\n        batch_size = prompts.batch.batch_size[0]\n        num_chunks = max(batch_size // self.config.get('micro_batch_size', batch_size), 1)\n        batch_prompts = prompts.chunk(chunks=num_chunks)\n        output = [self._generate_minibatch(p) for p in batch_prompts]\n        output = DataProto.concat(output)\n        return output\n\n    @torch.no_grad()\n    def _generate_minibatch(self, prompts: DataProto) -> DataProto:\n        idx = prompts.batch['input_ids']  # (bs, prompt_length)\n        attention_mask = prompts.batch['attention_mask']  # left-padded attention_mask\n        position_ids = prompts.batch['position_ids']\n\n        # used to construct attention_mask\n        eos_token_id = prompts.meta_info['eos_token_id']\n        pad_token_id = prompts.meta_info['pad_token_id']\n\n        batch_size = idx.size(0)\n        prompt_length = idx.size(1)\n\n        self.module.eval()\n        param_ctx = contextlib.nullcontext()\n\n        # make sampling args can be overriden by inputs\n        do_sample = prompts.meta_info.get('do_sample', self.config.do_sample)\n        response_length = prompts.meta_info.get('response_length', self.config.response_length)\n        top_p = prompts.meta_info.get('top_p', self.config.get('top_p', 1.0))\n        top_k = prompts.meta_info.get('top_k', self.config.get('top_k', 0))\n\n        if top_k is None:\n            top_k = 0\n        top_k = max(0, top_k)  # to be compatible with vllm\n\n        temperature = prompts.meta_info.get('temperature', self.config.temperature)\n\n        generation_config = GenerationConfig(temperature=temperature, top_p=top_p, top_k=top_k)\n\n        if isinstance(self.module, FSDP):\n            # recurse need to set to False according to https://github.com/pytorch/pytorch/issues/100069\n            param_ctx = FSDP.summon_full_params(self.module, writeback=False, recurse=False)\n        with param_ctx:\n            with torch.autocast(device_type='cuda', dtype=torch.bfloat16):\n                output = self.module.generate(\n                    input_ids=idx,\n                    attention_mask=attention_mask,\n                    do_sample=do_sample,\n                    max_new_tokens=response_length,\n                    # max_length=max_length,\n                    eos_token_id=eos_token_id,\n                    pad_token_id=pad_token_id,\n                    generation_config=generation_config,\n                    # renormalize_logits=True,\n                    output_scores=False,  # this is potentially very large\n                    return_dict_in_generate=True,\n                    use_cache=True)\n        # TODO: filter out the seq with no answers like ds-chat\n        seq = output.sequences\n\n        # huggingface generate will stop generating when all the batch reaches [EOS].\n        # We have to pad to response_length\n        sequence_length = prompt_length + self.config.response_length\n        delta_length = sequence_length - seq.shape[1]\n\n        if delta_length > 0:\n            delta_tokens = torch.ones(size=(batch_size, delta_length), device=seq.device, dtype=seq.dtype)\n            delta_tokens = pad_token_id * delta_tokens\n            seq = torch.cat((seq, delta_tokens), dim=1)\n\n        assert seq.shape[1] == sequence_length\n\n        prompt = seq[:, :prompt_length]  # (bs, prompt_length)\n        response = seq[:, prompt_length:]  # (bs, response_length)\n\n        response_length = response.size(1)\n        delta_position_id = torch.arange(1, response_length + 1, device=position_ids.device)\n        delta_position_id = delta_position_id.unsqueeze(0).repeat(batch_size, 1)\n\n        response_position_ids = position_ids[:, -1:] + delta_position_id\n        position_ids = torch.cat([position_ids, response_position_ids], dim=-1)\n\n        response_attention_mask = get_eos_mask(response_id=response, eos_token=eos_token_id, dtype=attention_mask.dtype)\n        attention_mask = torch.cat((attention_mask, response_attention_mask), dim=-1)\n\n        batch = TensorDict(\n            {\n                'prompts': prompt,\n                'responses': response,\n                'input_ids': seq,\n                'attention_mask': attention_mask,\n                'position_ids': position_ids\n            },\n            batch_size=batch_size)\n\n        # empty cache before compute old_log_prob\n        torch.cuda.empty_cache()\n\n        self.module.train()\n        return DataProto(batch=batch)\n"
  },
  {
    "path": "verl/workers/rollout/naive/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .naive_rollout import NaiveRollout\n"
  },
  {
    "path": "verl/workers/rollout/naive/naive_rollout.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nIn single GPU rollout, the sequences are generated directly by sampling from the model.\nThe output will contain\n1. output_ids\n2. attention_masks (left padding)\n3. eos_masks\n4. log_probs\n\"\"\"\nfrom typing import Iterable, Union\n\nimport torch\nimport torch.nn.functional as F\nfrom tensordict import TensorDict\nfrom torch import nn\n\nfrom verl import DataProto\nfrom verl.utils.torch_functional import logprobs_from_logits\nfrom ..base import BaseRollout\n\n__all__ = ['NaiveRollout']\n\n\nclass NaiveRollout(BaseRollout):\n\n    def __init__(self, module: nn.Module, config):\n        \"\"\"A naive rollout. It requires the module to be compatible with huggingface APIs. That is:\n        The module should define __call__ to receive input_ids, attention_mask and position_ids.\n        It outputs a structure that contains logits field.\n\n        Args:\n            module: module here follows huggingface APIs\n            config: DictConfig\n        \"\"\"\n        super().__init__()\n        self.config = config\n        self.module = module\n\n    @torch.no_grad()\n    def generate_sequences(self, prompts: DataProto) -> DataProto:\n        \"\"\"Generate sequences\"\"\"\n        idx = prompts.batch['input_ids']  # (bs, prompt_length)\n        attention_mask = prompts.batch['attention_mask']  # left-padded attention_mask\n        position_ids = prompts.batch['position_ids']\n\n        # used to construct attention_mask\n        eos_token_id = prompts.meta_info['eos_token_id']\n        if isinstance(eos_token, int):\n            eos_token = [eos_token]\n\n        batch_size = idx.size(0)\n        prompt_length = idx.size(1)\n\n        self.module.eval()\n\n        prev_attention_mask = torch.ones(size=(batch_size, 1), dtype=attention_mask.dtype, device=attention_mask.device)\n\n        logits_lst = []\n        for _ in range(self.config.response_length):\n            # if the sequence context is growing too long we must crop it at block_size\n            # idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]\n            idx_cond = idx\n            # forward the model to get the logits for the index in the sequence\n            # we use huggingface APIs here\n            output = self.module(input_ids=idx_cond, attention_mask=attention_mask, position_ids=position_ids)\n            logits = output.logits\n            # pluck the logits at the final step and scale by desired temperature\n            logits = logits[:, -1, :] / self.config.temperature  # (bs, vocab_size)\n            # optionally crop the logits to only the top k options\n            if self.config.top_k is not None:\n                v, _ = torch.topk(logits, min(self.config.top_k, logits.size(-1)))\n                logits[logits < v[:, [-1]]] = -float('Inf')\n            # apply softmax to convert logits to (normalized) probabilities\n            probs = F.softmax(logits, dim=-1)\n            # sample from the distribution\n            if self.config.do_sample:\n                idx_next = torch.multinomial(probs, num_samples=1)\n            else:\n                idx_next = torch.argmax(probs, dim=-1, keepdim=True)\n\n            attention_mask = torch.cat((attention_mask, prev_attention_mask), dim=-1)\n\n            for token_id in eos_token_id:\n                prev_attention_mask = torch.logical_and(idx_next != token_id, prev_attention_mask.bool())\n            prev_attention_mask.to(attention_mask.dtype)\n\n            position_ids = torch.cat((position_ids, position_ids[:, -1:] + 1), dim=-1)\n\n            # append sampled index to the running sequence and continue\n            idx = torch.cat((idx, idx_next), dim=1)\n            logits_lst.append(logits)\n\n        logits = torch.stack(logits_lst, dim=1)  # (bs, response_length, vocab_size)\n        prompts = idx[:, :prompt_length]  # (bs, prompt_length)\n        response = idx[:, prompt_length:]  # (bs, response_length)\n        log_probs = logprobs_from_logits(logits=logits, labels=response)\n        batch = TensorDict(\n            {\n                'input_ids': prompts,\n                'responses': response,\n                'sequences': idx,\n                'old_log_probs': log_probs,\n                'attention_mask': attention_mask,\n                'position_ids': position_ids,\n            },\n            batch_size=batch_size)\n\n        self.module.train()\n\n        return DataProto(batch=batch)\n"
  },
  {
    "path": "verl/workers/rollout/tokenizer.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe base tokenizer class, required for any hybrid engine based rollout or inference with vLLM.\n\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import Dict, List, Union\n\n__all__ = ['HybridEngineBaseTokenizer']\n\n\nclass HybridEngineBaseTokenizer(ABC):\n    \"\"\"the tokenizer property and function name should align with HF's to meet vllm requirement\"\"\"\n\n    @property\n    @abstractmethod\n    def vocab_size(self):\n        \"\"\"\n        `int`: Size of the base vocabulary (without the added tokens).\n        \"\"\"\n        pass\n\n    @property\n    @abstractmethod\n    def pad_token_id(self):\n        \"\"\"\n        `Optional[int]`: Id of the padding token in the vocabulary. Returns `None` if the token has not been set.\n        \"\"\"\n        pass\n\n    @property\n    @abstractmethod\n    def eos_token_id(self):\n        \"\"\"\n        `Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been\n        set.\n        \"\"\"\n        pass\n\n    @property\n    @abstractmethod\n    def all_special_ids(self) -> List[int]:\n        \"\"\"\n        `List[int]`: List the ids of the special tokens(`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes.\n        \"\"\"\n        pass\n\n    @property\n    @abstractmethod\n    def all_special_tokens(self) -> List[str]:\n        \"\"\"\n        `List[str]`: A list of the unique special tokens (`'<unk>'`, `'<cls>'`, ..., etc.).\n\n        Convert tokens of `tokenizers.AddedToken` type to string.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def encode(self, text):\n        \"\"\"\n        Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary.\n\n        Args:\n            text (`str`, `List[str]` or `List[int]`):\n                The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the\n                `tokenize` method) or a list of integers.\n\n            text_pair (`str`, `List[str]` or `List[int]`, *optional*):\n                Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using\n                the `tokenize` method) or a list of integers.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def decode(\n        self,\n        token_ids: Union[int, List[int], \"np.ndarray\", \"torch.Tensor\", \"tf.Tensor\"],\n        skip_special_tokens: bool = False,\n        clean_up_tokenization_spaces: bool = None,\n        **kwargs,\n    ) -> str:\n        \"\"\"\n        Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special\n        tokens and clean up tokenization spaces.\n\n        Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n\n        Args:\n            token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):\n                List of tokenized input ids. Can be obtained using the `__call__` method.\n            skip_special_tokens (`bool`, *optional*, defaults to `False`):\n                Whether or not to remove special tokens in the decoding.\n            clean_up_tokenization_spaces (`bool`, *optional*):\n                Whether or not to clean up the tokenization spaces. If `None`, will default to\n                `self.clean_up_tokenization_spaces`.\n            kwargs (additional keyword arguments, *optional*):\n                Will be passed to the underlying model specific decode method.\n\n        Returns:\n            `str`: The decoded sentence.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def convert_ids_to_tokens(self,\n                              ids: Union[int, List[int]],\n                              skip_special_tokens: bool = False) -> Union[str, List[str]]:\n        \"\"\"\n        Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and\n        added tokens.\n\n        Args:\n            ids (`int` or `List[int]`):\n                The token id (or token ids) to convert to tokens.\n            skip_special_tokens (`bool`, *optional*, defaults to `False`):\n                Whether or not to remove special tokens in the decoding.\n\n        Returns:\n            `str` or `List[str]`: The decoded token(s).\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def get_added_vocab(self) -> Dict[str, int]:\n        \"\"\"\n        Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from\n        the fast call because for now we always add the tokens even if they are already in the vocabulary. This is\n        something we should change.\n\n        Returns:\n            `Dict[str, int]`: The added tokens.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def convert_tokens_to_string(self, tokens: List[str]) -> str:\n        \"\"\"\n        Converts a sequence of tokens in a single string. The most simple way to do it is `\" \".join(tokens)` but we\n        often want to remove sub-word tokenization artifacts at the same time.\n\n        Args:\n            tokens (`List[str]`): The token to join in a string.\n\n        Returns:\n            `str`: The joined tokens.\n        \"\"\"\n        pass\n\n    @property\n    def is_fast(self):\n        return False\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom importlib.metadata import version, PackageNotFoundError\n\n\ndef get_version(pkg):\n    try:\n        return version(pkg)\n    except PackageNotFoundError:\n        return None\n\n\npackage_name = 'vllm'\npackage_version = get_version(package_name)\n\nif package_version <= '0.6.3':\n    vllm_mode = 'customized'\n    from .vllm_rollout import vLLMRollout\n    from .fire_vllm_rollout import FIREvLLMRollout\nelse:\n    vllm_mode = 'spmd'\n    from .vllm_rollout_spmd import vLLMRollout\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/fire_vllm_rollout.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe vllm_rollout that can be applied in different backend\nWhen working with FSDP:\n- Use DTensor weight loader (recommended) or HF weight loader\n- Utilize state_dict from the FSDP to synchronize the weights among tp ranks in vLLM\nWhen working with Megatron:\n- Use Megatron weight loader\n- During training, only the current pp stage holds the parameters\n- Before inference, broadcast the parameters of the current pp rank to all other pp ranks (all pp ranks holds all the parameters)\n- Bind the parameters to the inference engine\n- Do inference in tp. pp is treated as additional dp\n- After inference, all the parameters that doesn't belong to this pp rank is freed.\n\"\"\"\nfrom typing import List\nfrom contextlib import contextmanager\nfrom omegaconf import DictConfig\nimport torch\nimport torch.distributed\nfrom tensordict import TensorDict\nfrom torch import nn\n\nfrom verl import DataProto\nfrom verl.utils.torch_functional import get_eos_mask, pad_sequence_to_length\nfrom verl.workers.rollout.base import BaseRollout\nfrom verl.workers.rollout.vllm_rollout.vllm_rollout import vLLMRollout\nfrom verl.third_party.vllm import LLM, vllm_version\nfrom verl.third_party.vllm import parallel_state as vllm_ps\nfrom vllm import SamplingParams\n\n# TODO\n# 1. support pp in vllm\n# 2. passing tokenizer is not necessary? no encoding/decoding is happending here\n# 3. simplify init logics\n\n\n# NOTE(sgm): add for verl. We can optimize it by making the dataloader yield List[int] without padding.\ndef _pre_process_inputs(pad_token_id, prompt_token_ids: torch.Tensor) -> List[int]:\n    # remove the left padding in the prompt token_id\n    # pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n    non_pad_index = torch.nonzero(prompt_token_ids != pad_token_id, as_tuple=False)[0][0]\n    token_ids = prompt_token_ids[non_pad_index:].tolist()\n    return token_ids\n\n\nclass FIREvLLMRollout(vLLMRollout):\n\n    def __init__(self, actor_module: nn.Module, config: DictConfig, tokenizer, model_hf_config, **kwargs):\n        \"\"\"A vLLM rollout. It requires the module is supported by the vllm.\n\n        Args:\n            module: module here follows huggingface APIs\n            config: DictConfig\n            tokenizer: the task/model tokenizer\n            model_hf_config: the huggingface config to initiallize the generating model in vllm\n            **kwargs: train_tp, for Megatron Backend to initialize hybrid engine (zero redundancy) process group\n        \"\"\"\n        super().__init__(actor_module, config, tokenizer, model_hf_config, **kwargs)\n\n        self.use_fire_sampling = config.get('use_fire_sampling', False)\n        if self.use_fire_sampling:\n            kwargs_0 = kwargs.copy()\n            kwargs_0['temperature'] = 30\n            kwargs_0['max_tokens'] = 1\n            if 'top_k' not in kwargs_0 or kwargs_0['top_k'] <= 0:\n                kwargs_0['top_k'] = 16\n            kwargs['max_tokens'] -= 1\n            self.sampling_params_0 = SamplingParams(**kwargs_0)\n\n    @contextmanager\n    def update_sampling_params(self, **kwargs):\n        # update sampling params\n        old_sampling_params_args = {}\n        if kwargs:\n            for key, value in kwargs.items():\n                if hasattr(self.sampling_params, key):\n                    old_value = getattr(self.sampling_params, key)\n                    old_sampling_params_args[key] = old_value\n                    setattr(self.sampling_params, key, value)\n        if self.use_fire_sampling:\n            old_sampling_params_args_0 = {}\n            if kwargs:\n                for key, value in kwargs.items():\n                    if hasattr(self.sampling_params_0, key):\n                        old_value = getattr(self.sampling_params_0, key)\n                        old_sampling_params_args_0[key] = old_value\n                        setattr(self.sampling_params_0, key, value)\n        yield\n        # roll back to previous sampling params\n        # if len(old_sampling_params_args):\n        for key, value in old_sampling_params_args.items():\n            setattr(self.sampling_params, key, value)\n        if self.use_fire_sampling:\n            for key, value in old_sampling_params_args_0.items():\n                setattr(self.sampling_params_0, key, value)\n\n    @torch.no_grad()\n    def generate_sequences(self, prompts: DataProto, **kwargs) -> DataProto:\n        # rebuild vllm cache engine\n        if self.config.free_cache_engine:\n            self.inference_engine.init_cache_engine()\n\n        idx = prompts.batch['input_ids']  # (bs, prompt_length)\n        # left-padded attention_mask\n        attention_mask = prompts.batch['attention_mask']\n        position_ids = prompts.batch['position_ids']\n\n        # used to construct attention_mask\n        eos_token_id = prompts.meta_info['eos_token_id']\n\n        batch_size = idx.size(0)\n\n        idx_list = []\n        # parse idx from torch.Tensor to List[List[str]]\n        for i in range(batch_size):\n            idx_list.append(_pre_process_inputs(self.pad_token_id, idx[i]))\n\n        do_sample = prompts.meta_info.get('do_sample', True)\n        if not do_sample:\n            kwargs = {\n                'best_of': 1,\n                'top_p': 1.0,\n                'top_k': -1,\n                'min_p': 0.0,\n                'temperature': 0,\n                'n': 1  # if greedy, only 1 response\n            }\n\n        if not self.use_fire_sampling:\n            # users can customize different sampling_params at different run\n            with self.update_sampling_params(**kwargs):\n                output = self.inference_engine.generate(\n                    prompts=None,  # because we have already convert it to prompt token id\n                    sampling_params=self.sampling_params,\n                    prompt_token_ids=idx_list,\n                    use_tqdm=False)\n\n            response = output[0].to(idx.device)  # (bs, response_length)\n            log_probs = output[1].to(idx.device)  # (bs, response_length)\n        else:\n            with self.update_sampling_params(**kwargs):\n                output_0 = self.inference_engine.generate(\n                    prompts=None,  # because we have already convert it to prompt token id\n                    sampling_params=self.sampling_params_0,\n                    prompt_token_ids=idx_list,\n                    use_tqdm=False)\n                new_idx_list = []\n                for i in range(batch_size):\n                    new_idx_list.append(idx_list[i] + output_0[0][i].tolist())\n                output = self.inference_engine.generate(\n                    prompts=None,  # because we have already convert it to prompt token id\n                    sampling_params=self.sampling_params,\n                    prompt_token_ids=new_idx_list,\n                    use_tqdm=False)\n\n            response = torch.cat([output_0[0], output[0]], dim=1).to(idx.device)  # (bs, response_length)\n            log_probs = torch.cat([output_0[1], output[1]], dim=1).to(idx.device)  # (bs, response_length)\n\n        if response.shape[1] < self.config.response_length:\n            response = pad_sequence_to_length(response, self.config.response_length, self.pad_token_id)\n            log_probs = pad_sequence_to_length(log_probs, self.config.response_length, self.pad_token_id)\n\n        if self.config.n > 1 and do_sample:\n            idx = idx.repeat_interleave(self.config.n, dim=0)\n            attention_mask = attention_mask.repeat_interleave(self.config.n, dim=0)\n            position_ids = position_ids.repeat_interleave(self.config.n, dim=0)\n            batch_size = batch_size * self.config.n\n        seq = torch.cat([idx, response], dim=-1)\n\n        response_length = response.size(1)\n        delta_position_id = torch.arange(1, response_length + 1, device=position_ids.device)\n        delta_position_id = delta_position_id.unsqueeze(0).repeat(batch_size, 1)\n\n        # TODO(sgm): fix position_ids on right_pad\n        # prompt: left pad + response: right pad\n        # attention_mask: [0,0,0,0,1,1,1,1, | 1,1,1,0,0,0,0,0]\n        # position_ids:   [0,0,0,0,0,1,2,3, | 4,5,6,7,8,9,10,11]\n        response_position_ids = position_ids[:, -1:] + delta_position_id\n        position_ids = torch.cat([position_ids, response_position_ids], dim=-1)\n        response_attention_mask = get_eos_mask(response_id=response, eos_token=eos_token_id, dtype=attention_mask.dtype)\n        attention_mask = torch.cat((attention_mask, response_attention_mask), dim=-1)\n\n        # all the tp ranks should contain the same data here. data in all ranks are valid\n        batch = TensorDict(\n            {\n                'prompts': idx,\n                'responses': response,\n                'input_ids': seq,  # here input_ids become the whole sentences\n                # 'old_log_probs': log_probs, # we will recompute old log prob with actor\n                'attention_mask': attention_mask,\n                'position_ids': position_ids\n            },\n            batch_size=batch_size)\n\n        # free vllm cache engine\n        if self.config.free_cache_engine:\n            self.inference_engine.free_cache_engine()\n\n        return DataProto(batch=batch)\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/code/code_interpreter.py",
    "content": "import base64\nimport io\nimport json\nimport logging\nimport os\nimport queue\nimport re\nimport subprocess\nimport sys\nimport time\nimport traceback\nimport uuid\n\nimport matplotlib\nimport PIL.Image\nfrom jupyter_client import BlockingKernelClient\nfrom utils.code_utils import extract_code\n\nWORK_DIR = os.getenv('CODE_INTERPRETER_WORK_DIR', '/tmp/workspace')\n\nLAUNCH_KERNEL_PY = \"\"\"\nfrom ipykernel import kernelapp as app\napp.launch_new_instance()\n\"\"\"\n\n_KERNEL_CLIENTS = {}\n\n\n# Run this fix before jupyter starts if matplotlib cannot render CJK fonts.\n# And we need to additionally run the following lines in the jupyter notebook.\n#   ```python\n#   import matplotlib.pyplot as plt\n#   plt.rcParams['font.sans-serif'] = ['SimHei']\n#   plt.rcParams['axes.unicode_minus'] = False\n#   ````\ndef fix_matplotlib_cjk_font_issue():\n    local_ttf = os.path.join(os.path.abspath(os.path.join(matplotlib.matplotlib_fname(), os.path.pardir)), 'fonts',\n                             'ttf', 'simhei.ttf')\n    if not os.path.exists(local_ttf):\n        logging.warning(\n            f'Missing font file `{local_ttf}` for matplotlib. It may cause some error when using matplotlib.')\n\n\ndef start_kernel(pid):\n    fix_matplotlib_cjk_font_issue()\n\n    connection_file = os.path.join(WORK_DIR, f'kernel_connection_file_{pid}.json')\n    launch_kernel_script = os.path.join(WORK_DIR, f'launch_kernel_{pid}.py')\n    for f in [connection_file, launch_kernel_script]:\n        if os.path.exists(f):\n            logging.warning(f'{f} already exists')\n            os.remove(f)\n\n    os.makedirs(WORK_DIR, exist_ok=True)\n\n    with open(launch_kernel_script, 'w') as fout:\n        fout.write(LAUNCH_KERNEL_PY)\n\n    kernel_process = subprocess.Popen([\n        sys.executable,\n        launch_kernel_script,\n        '--IPKernelApp.connection_file',\n        connection_file,\n        '--matplotlib=inline',\n        '--quiet',\n    ],\n                                      cwd=WORK_DIR)\n    logging.info(f\"INFO: kernel process's PID = {kernel_process.pid}\")\n\n    # Wait for kernel connection file to be written\n    while True:\n        if not os.path.isfile(connection_file):\n            time.sleep(0.1)\n        else:\n            # Keep looping if JSON parsing fails, file may be partially written\n            try:\n                with open(connection_file, 'r') as fp:\n                    json.load(fp)\n                break\n            except json.JSONDecodeError:\n                pass\n\n    # Client\n    kc = BlockingKernelClient(connection_file=connection_file)\n    kc.load_connection_file()\n    kc.start_channels()\n    kc.wait_for_ready()\n    return kc\n\n\ndef escape_ansi(line):\n    ansi_escape = re.compile(r'(?:\\x1B[@-_]|[\\x80-\\x9F])[0-?]*[ -/]*[@-~]')\n    return ansi_escape.sub('', line)\n\n\ndef publish_image_to_local(image_base64: str):\n    image_file = str(uuid.uuid4()) + '.png'\n    local_image_file = os.path.join(WORK_DIR, image_file)\n\n    png_bytes = base64.b64decode(image_base64)\n    assert isinstance(png_bytes, bytes)\n    bytes_io = io.BytesIO(png_bytes)\n    PIL.Image.open(bytes_io).save(local_image_file, 'png')\n\n    return local_image_file\n\n\nSTART_CODE = \"\"\"\nimport signal\ndef _m6_code_interpreter_timeout_handler(signum, frame):\n    raise TimeoutError(\"M6_CODE_INTERPRETER_TIMEOUT\")\nsignal.signal(signal.SIGALRM, _m6_code_interpreter_timeout_handler)\n\ndef input(*args, **kwargs):\n    raise NotImplementedError('Python input() function is disabled.')\n\nimport os\nif 'upload_file' not in os.getcwd():\n    os.chdir(\"./upload_file/\")\n\nimport math\nimport re\nimport json\n\nimport seaborn as sns\nsns.set_theme()\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\nimport numpy as np\nimport pandas as pd\n\nfrom sympy import Eq, symbols, solve\n\"\"\"\n\n\ndef code_interpreter(action_input_list: list, timeout=30, clear=False):\n    code = ''\n    for action_input in action_input_list:\n        code += (extract_code(action_input) + '\\n')\n    fixed_code = []\n    for line in code.split('\\n'):\n        fixed_code.append(line)\n        if line.startswith('sns.set_theme('):\n            fixed_code.append('plt.rcParams[\"font.sans-serif\"] = [\"SimHei\"]')\n            fixed_code.append('plt.rcParams[\"axes.unicode_minus\"] = False')\n    fixed_code = '\\n'.join(fixed_code)\n    if 'def solution()' in fixed_code:\n        fixed_code += '\\nsolution()'\n\n    return _code_interpreter(fixed_code, timeout, clear)\n\n\ndef _code_interpreter(code: str, timeout, clear=False):\n    if not code.strip():\n        return ''\n    if timeout:\n        code = f'signal.alarm({timeout})\\n{code}'\n    if clear:\n        code = \"get_ipython().run_line_magic('reset', '-f')\\n\" + START_CODE + code\n\n    pid = os.getpid()\n    if pid not in _KERNEL_CLIENTS:\n        _KERNEL_CLIENTS[pid] = start_kernel(pid)\n        _code_interpreter(START_CODE, timeout=None)\n    kc = _KERNEL_CLIENTS[pid]\n    kc.wait_for_ready()\n    kc.execute(code)\n    result = ''\n    image_idx = 0\n    while True:\n        text = ''\n        image = ''\n        finished = False\n        msg_type = 'error'\n        try:\n            msg = kc.get_iopub_msg()\n            msg_type = msg['msg_type']\n            if msg_type == 'status':\n                if msg['content'].get('execution_state') == 'idle':\n                    finished = True\n            elif msg_type == 'execute_result':\n                text = msg['content']['data'].get('text/plain', '')\n                if 'image/png' in msg['content']['data']:\n                    image_b64 = msg['content']['data']['image/png']\n                    image_url = publish_image_to_local(image_b64)\n                    image_idx += 1\n                    image = '![fig-%03d](%s)' % (image_idx, image_url)\n            elif msg_type == 'display_data':\n                if 'image/png' in msg['content']['data']:\n                    image_b64 = msg['content']['data']['image/png']\n                    image_url = publish_image_to_local(image_b64)\n                    image_idx += 1\n                    image = '![fig-%03d](%s)' % (image_idx, image_url)\n                else:\n                    text = msg['content']['data'].get('text/plain', '')\n            elif msg_type == 'stream':\n                msg_type = msg['content']['name']  # stdout, stderr\n                text = msg['content']['text']\n            elif msg_type == 'error':\n                text = escape_ansi('\\n'.join(msg['content']['traceback']))\n                if 'M6_CODE_INTERPRETER_TIMEOUT' in text:\n                    text = f'Timeout. No response after {timeout} seconds.'\n        except queue.Empty:\n            text = f'Timeout. No response after {timeout} seconds.'\n            finished = True\n        except Exception:\n            text = 'The code interpreter encountered an unexpected error.'\n            logging.warning(''.join(traceback.format_exception(*sys.exc_info())))\n            finished = True\n        if text:\n            result += f'\\n\\n{msg_type}:\\n\\n```\\n{text}\\n```'\n        if image:\n            result += f'\\n\\n{image}'\n        if finished:\n            break\n    result = result.lstrip('\\n')\n    if timeout:\n        _code_interpreter('signal.alarm(0)', timeout=None)\n    return result\n\n\ndef get_multiline_input(hint):\n    print(hint)\n    print('// Press ENTER to make a new line. Press CTRL-D to end input.')\n    lines = []\n    while True:\n        try:\n            line = input()\n        except EOFError:  # CTRL-D\n            break\n        lines.append(line)\n    print('// Input received.')\n    if lines:\n        return '\\n'.join(lines)\n    else:\n        return ''\n\n\nif __name__ == '__main__':\n    while True:\n        print(code_interpreter([get_multiline_input('Enter python code:')]))"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/code/utils/code_utils.py",
    "content": "import os\nimport re\n\nimport json5\n\n\ndef replace_upload_fname(text, upload_fname_list):\n    for full_input_fname in upload_fname_list:\n        if full_input_fname not in text and os.path.basename(full_input_fname) in text:\n            text = text.replace(os.path.basename(full_input_fname), full_input_fname)\n    return text\n\n\ndef extract_code(text):\n    # Match triple backtick blocks first\n    triple_match = re.search(r'```[^\\n]*\\n(.+?)```', text, re.DOTALL)\n    # Match single backtick blocks second\n    single_match = re.search(r'`([^`]*)`', text, re.DOTALL)\n    if triple_match:\n        text = triple_match.group(1)\n    elif single_match:\n        text = single_match.group(1)\n    else:\n        try:\n            text = json5.loads(text)['code']\n        except Exception:\n            pass\n    # If no code blocks found, return original text\n    return text"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/llm/schema.py",
    "content": "from typing import List, Literal, Optional, Tuple, Union\n\nfrom pydantic import BaseModel, field_validator, model_validator\n\nDEFAULT_SYSTEM_MESSAGE = 'You are a helpful assistant.'\n\nROLE = 'role'\nCONTENT = 'content'\nNAME = 'name'\n\nSYSTEM = 'system'\nUSER = 'user'\nASSISTANT = 'assistant'\nFUNCTION = 'function'\n\nFILE = 'file'\nIMAGE = 'image'\nAUDIO = 'audio'\nVIDEO = 'video'\n\n\nclass BaseModelCompatibleDict(BaseModel):\n\n    def __getitem__(self, item):\n        return getattr(self, item)\n\n    def __setitem__(self, key, value):\n        setattr(self, key, value)\n\n    def model_dump(self, **kwargs):\n        if 'exclude_none' not in kwargs:\n            kwargs['exclude_none'] = True\n        return super().model_dump(**kwargs)\n\n    def model_dump_json(self, **kwargs):\n        if 'exclude_none' not in kwargs:\n            kwargs['exclude_none'] = True\n        return super().model_dump_json(**kwargs)\n\n    def get(self, key, default=None):\n        try:\n            value = getattr(self, key)\n            if value:\n                return value\n            else:\n                return default\n        except AttributeError:\n            return default\n\n    def __str__(self):\n        return f'{self.model_dump()}'\n\n\nclass FunctionCall(BaseModelCompatibleDict):\n    name: str\n    arguments: str\n\n    def __init__(self, name: str, arguments: str):\n        super().__init__(name=name, arguments=arguments)\n\n    def __repr__(self):\n        return f'FunctionCall({self.model_dump()})'\n\n\nclass ContentItem(BaseModelCompatibleDict):\n    text: Optional[str] = None\n    image: Optional[str] = None\n    file: Optional[str] = None\n    audio: Optional[str] = None\n    video: Optional[Union[str, list]] = None\n\n    def __init__(self,\n                 text: Optional[str] = None,\n                 image: Optional[str] = None,\n                 file: Optional[str] = None,\n                 audio: Optional[str] = None,\n                 video: Optional[Union[str, list]] = None):\n        super().__init__(text=text, image=image, file=file, audio=audio, video=video)\n\n    @model_validator(mode='after')\n    def check_exclusivity(self):\n        provided_fields = 0\n        if self.text is not None:\n            provided_fields += 1\n        if self.image:\n            provided_fields += 1\n        if self.file:\n            provided_fields += 1\n        if self.audio:\n            provided_fields += 1\n        if self.video:\n            provided_fields += 1\n\n        if provided_fields != 1:\n            raise ValueError(\"Exactly one of 'text', 'image', 'file', 'audio', or 'video' must be provided.\")\n        return self\n\n    def __repr__(self):\n        return f'ContentItem({self.model_dump()})'\n\n    def get_type_and_value(self) -> Tuple[Literal['text', 'image', 'file', 'audio', 'video'], str]:\n        (t, v), = self.model_dump().items()\n        assert t in ('text', 'image', 'file', 'audio', 'video')\n        return t, v\n\n    @property\n    def type(self) -> Literal['text', 'image', 'file', 'audio', 'video']:\n        t, v = self.get_type_and_value()\n        return t\n\n    @property\n    def value(self) -> str:\n        t, v = self.get_type_and_value()\n        return v\n\n\nclass Message(BaseModelCompatibleDict):\n    role: str\n    content: Union[str, List[ContentItem]]\n    name: Optional[str] = None\n    function_call: Optional[FunctionCall] = None\n    extra: Optional[dict] = None\n\n    def __init__(self,\n                 role: str,\n                 content: Optional[Union[str, List[ContentItem]]],\n                 name: Optional[str] = None,\n                 function_call: Optional[FunctionCall] = None,\n                 extra: Optional[dict] = None,\n                 **kwargs):\n        if content is None:\n            content = ''\n        super().__init__(role=role, content=content, name=name, function_call=function_call, extra=extra)\n\n    def __repr__(self):\n        return f'Message({self.model_dump()})'\n\n    @field_validator('role')\n    def role_checker(cls, value: str) -> str:\n        if value not in [USER, ASSISTANT, SYSTEM, FUNCTION]:\n            raise ValueError(f'{value} must be one of {\",\".join([USER, ASSISTANT, SYSTEM, FUNCTION])}')\n        return value\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/log.py",
    "content": "import logging\nimport os\n\n\ndef setup_logger(level=None):\n    if level is None:\n        if os.getenv('QWEN_AGENT_DEBUG', '0').strip().lower() in ('1', 'true'):\n            level = logging.DEBUG\n        else:\n            level = logging.INFO\n\n    handler = logging.StreamHandler()\n    # Do not run handler.setLevel(level) so that users can change the level via logger.setLevel later\n    formatter = logging.Formatter('%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s')\n    handler.setFormatter(formatter)\n\n    _logger = logging.getLogger('qwen_agent_logger')\n    _logger.setLevel(level)\n    _logger.addHandler(handler)\n    return _logger\n\n\nlogger = setup_logger()\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/settings.py",
    "content": "import ast\nimport os\nfrom typing import List, Literal\n\n# Settings for LLMs\nDEFAULT_MAX_INPUT_TOKENS: int = int(os.getenv(\n    'QWEN_AGENT_DEFAULT_MAX_INPUT_TOKENS', 30000))  # The LLM will truncate the input messages if they exceed this limit\n\n# Settings for agents\nMAX_LLM_CALL_PER_RUN: int = int(os.getenv('QWEN_AGENT_MAX_LLM_CALL_PER_RUN', 8))\n\n# Settings for tools\nDEFAULT_WORKSPACE: str = os.getenv('QWEN_AGENT_DEFAULT_WORKSPACE', 'workspace')\n\n# Settings for RAG\nDEFAULT_MAX_REF_TOKEN: int = int(os.getenv('QWEN_AGENT_DEFAULT_MAX_REF_TOKEN',\n                                           20000))  # The window size reserved for RAG materials\nDEFAULT_PARSER_PAGE_SIZE: int = int(os.getenv('QWEN_AGENT_DEFAULT_PARSER_PAGE_SIZE',\n                                              500))  # Max tokens per chunk when doing RAG\nDEFAULT_RAG_KEYGEN_STRATEGY: Literal['None', 'GenKeyword', 'SplitQueryThenGenKeyword', 'GenKeywordWithKnowledge',\n                                     'SplitQueryThenGenKeywordWithKnowledge'] = os.getenv(\n                                         'QWEN_AGENT_DEFAULT_RAG_KEYGEN_STRATEGY', 'GenKeyword')\nDEFAULT_RAG_SEARCHERS: List[str] = ast.literal_eval(\n    os.getenv('QWEN_AGENT_DEFAULT_RAG_SEARCHERS',\n              \"['keyword_search', 'front_page_search']\"))  # Sub-searchers for hybrid retrieval\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/tools/base.py",
    "content": "import json\nimport os\nfrom abc import ABC, abstractmethod\nfrom typing import Dict, List, Optional, Union\n\nfrom qwen_agent.llm.schema import ContentItem\nfrom qwen_agent.settings import DEFAULT_WORKSPACE\nfrom qwen_agent.utils.utils import has_chinese_chars, json_loads, logger, print_traceback, save_url_to_local_work_dir\n\nTOOL_REGISTRY = {}\n\n\nclass ToolServiceError(Exception):\n\n    def __init__(self,\n                 exception: Optional[Exception] = None,\n                 code: Optional[str] = None,\n                 message: Optional[str] = None,\n                 extra: Optional[dict] = None):\n        if exception is not None:\n            super().__init__(exception)\n        else:\n            super().__init__(f'\\nError code: {code}. Error message: {message}')\n        self.exception = exception\n        self.code = code\n        self.message = message\n        self.extra = extra\n\n\ndef register_tool(name, allow_overwrite=False):\n\n    def decorator(cls):\n        if name in TOOL_REGISTRY:\n            if allow_overwrite:\n                logger.warning(f'Tool `{name}` already exists! Overwriting with class {cls}.')\n            else:\n                raise ValueError(f'Tool `{name}` already exists! Please ensure that the tool name is unique.')\n        if cls.name and (cls.name != name):\n            raise ValueError(f'{cls.__name__}.name=\"{cls.name}\" conflicts with @register_tool(name=\"{name}\").')\n        cls.name = name\n        TOOL_REGISTRY[name] = cls\n\n        return cls\n\n    return decorator\n\n\ndef is_tool_schema(obj: dict) -> bool:\n    \"\"\"\n    Check if obj is a valid JSON schema describing a tool compatible with OpenAI's tool calling.\n    Example valid schema:\n    {\n      \"name\": \"get_current_weather\",\n      \"description\": \"Get the current weather in a given location\",\n      \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"location\": {\n            \"type\": \"string\",\n            \"description\": \"The city and state, e.g. San Francisco, CA\"\n          },\n          \"unit\": {\n            \"type\": \"string\",\n            \"enum\": [\"celsius\", \"fahrenheit\"]\n          }\n        },\n        \"required\": [\"location\"]\n      }\n    }\n    \"\"\"\n    import jsonschema\n    try:\n        assert set(obj.keys()) == {'name', 'description', 'parameters'}\n        assert isinstance(obj['name'], str)\n        assert obj['name'].strip()\n        assert isinstance(obj['description'], str)\n        assert isinstance(obj['parameters'], dict)\n\n        assert set(obj['parameters'].keys()) == {'type', 'properties', 'required'}\n        assert obj['parameters']['type'] == 'object'\n        assert isinstance(obj['parameters']['properties'], dict)\n        assert isinstance(obj['parameters']['required'], list)\n        assert set(obj['parameters']['required']).issubset(set(obj['parameters']['properties'].keys()))\n    except AssertionError:\n        return False\n    try:\n        jsonschema.validate(instance={}, schema=obj['parameters'])\n    except jsonschema.exceptions.SchemaError:\n        return False\n    except jsonschema.exceptions.ValidationError:\n        pass\n    return True\n\n\nclass BaseTool(ABC):\n    name: str = ''\n    description: str = ''\n    parameters: Union[List[dict], dict] = []\n\n    def __init__(self, cfg: Optional[dict] = None):\n        self.cfg = cfg or {}\n        if not self.name:\n            raise ValueError(\n                f'You must set {self.__class__.__name__}.name, either by @register_tool(name=...) or explicitly setting {self.__class__.__name__}.name'\n            )\n        if isinstance(self.parameters, dict):\n            if not is_tool_schema({'name': self.name, 'description': self.description, 'parameters': self.parameters}):\n                raise ValueError(\n                    'The parameters, when provided as a dict, must confirm to a valid openai-compatible JSON schema.')\n\n    @abstractmethod\n    def call(self, params: Union[str, dict], **kwargs) -> Union[str, list, dict, List[ContentItem]]:\n        \"\"\"The interface for calling tools.\n\n        Each tool needs to implement this function, which is the workflow of the tool.\n\n        Args:\n            params: The parameters of func_call.\n            kwargs: Additional parameters for calling tools.\n\n        Returns:\n            The result returned by the tool, implemented in the subclass.\n        \"\"\"\n        raise NotImplementedError\n\n    def _verify_json_format_args(self, params: Union[str, dict], strict_json: bool = False) -> dict:\n        \"\"\"Verify the parameters of the function call\"\"\"\n        if isinstance(params, str):\n            try:\n                if strict_json:\n                    params_json: dict = json.loads(params)\n                else:\n                    params_json: dict = json_loads(params)\n            except json.decoder.JSONDecodeError:\n                raise ValueError('Parameters must be formatted as a valid JSON!')\n        else:\n            params_json: dict = params\n        if isinstance(self.parameters, list):\n            for param in self.parameters:\n                if 'required' in param and param['required']:\n                    if param['name'] not in params_json:\n                        raise ValueError('Parameters %s is required!' % param['name'])\n        elif isinstance(self.parameters, dict):\n            import jsonschema\n            jsonschema.validate(instance=params_json, schema=self.parameters)\n        else:\n            raise ValueError\n        return params_json\n\n    @property\n    def function(self) -> dict:  # Bad naming. It should be `function_info`.\n        return {\n            'name_for_human': self.name_for_human,\n            'name': self.name,\n            'description': self.description,\n            'parameters': self.parameters,\n            'args_format': self.args_format\n        }\n\n    @property\n    def name_for_human(self) -> str:\n        return self.cfg.get('name_for_human', self.name)\n\n    @property\n    def args_format(self) -> str:\n        fmt = self.cfg.get('args_format')\n        if fmt is None:\n            if has_chinese_chars([self.name_for_human, self.name, self.description, self.parameters]):\n                fmt = '此工具的输入应为JSON对象。'\n            else:\n                fmt = 'Format the arguments as a JSON object.'\n        return fmt\n\n    @property\n    def file_access(self) -> bool:\n        return False\n\n\nclass BaseToolWithFileAccess(BaseTool, ABC):\n\n    def __init__(self, cfg: Optional[Dict] = None):\n        super().__init__(cfg)\n        assert self.name\n        default_work_dir = os.path.join(DEFAULT_WORKSPACE, 'tools', self.name)\n        self.work_dir: str = self.cfg.get('work_dir', default_work_dir)\n\n    @property\n    def file_access(self) -> bool:\n        return True\n\n    def call(self, params: Union[str, dict], files: List[str] = None, **kwargs) -> str:\n        # Copy remote files to the working directory:\n        if files:\n            os.makedirs(self.work_dir, exist_ok=True)\n            for file in files:\n                try:\n                    save_url_to_local_work_dir(file, self.work_dir)\n                except Exception:\n                    print_traceback()\n\n        # Then do something with the files:\n        # ...\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/tools/code_interpreter.py",
    "content": "import asyncio\nimport atexit\nimport base64\nimport glob\nimport io\nimport json\nimport os\nimport queue\nimport re\nimport shutil\nimport signal\nimport stat\nimport subprocess\nimport sys\nimport time\nimport uuid\nimport threading\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Union\n\nimport json5\n\nfrom qwen_agent.log import logger\nfrom qwen_agent.tools.base import BaseToolWithFileAccess, register_tool\nfrom qwen_agent.utils.utils import append_signal_handler, extract_code, has_chinese_chars, print_traceback\n\nLAUNCH_KERNEL_PY = \"\"\"\nfrom ipykernel import kernelapp as app\napp.launch_new_instance()\n\"\"\"\n\nINIT_CODE_FILE = str(Path(__file__).absolute().parent / 'resource' / 'code_interpreter_init_kernel.py')\nALIB_FONT_FILE = str(Path(__file__).absolute().parent / 'resource' / 'AlibabaPuHuiTi-3-45-Light.ttf')\n\n_KERNEL_CLIENTS: dict = {}\n_MISC_SUBPROCESSES: Dict[str, subprocess.Popen] = {}\n\n\ndef _kill_kernels_and_subprocesses(_sig_num=None, _frame=None):\n    for v in _KERNEL_CLIENTS.values():\n        v.shutdown()\n    for k in list(_KERNEL_CLIENTS.keys()):\n        del _KERNEL_CLIENTS[k]\n\n    for v in _MISC_SUBPROCESSES.values():\n        v.terminate()\n    for k in list(_MISC_SUBPROCESSES.keys()):\n        del _MISC_SUBPROCESSES[k]\n\n\n# Make sure all subprocesses are terminated even if killed abnormally:\n# If not running in the main thread, (for example run in streamlit)\n# register a signal would cause a RuntimeError\nif threading.current_thread() is threading.main_thread():\n    atexit.register(_kill_kernels_and_subprocesses)\n    append_signal_handler(signal.SIGTERM, _kill_kernels_and_subprocesses)\n    append_signal_handler(signal.SIGINT, _kill_kernels_and_subprocesses)\n\n\n@register_tool('code_interpreter')\nclass CodeInterpreter(BaseToolWithFileAccess):\n    description = 'Python代码沙盒，可用于执行Python代码。'\n    parameters = [{'name': 'code', 'type': 'string', 'description': '待执行的代码', 'required': True}]\n\n    def __init__(self, cfg: Optional[Dict] = None):\n        super().__init__(cfg)\n        self.work_dir: str = os.getenv('M6_CODE_INTERPRETER_WORK_DIR', self.work_dir)\n        self.work_dir: str = self.cfg.get('work_dir', self.work_dir)\n        self.instance_id: str = str(uuid.uuid4())\n        _check_deps_for_code_interpreter()\n\n    @property\n    def args_format(self) -> str:\n        fmt = self.cfg.get('args_format')\n        if fmt is None:\n            if has_chinese_chars([self.name_for_human, self.name, self.description, self.parameters]):\n                fmt = '此工具的输入应为Markdown代码块。'\n            else:\n                fmt = 'Enclose the code within triple backticks (`) at the beginning and end of the code.'\n        return fmt\n\n    def call(self, params: Union[str, dict], files: List[str] = None, timeout: Optional[int] = 1, **kwargs) -> str:\n        super().call(params=params, files=files)  # copy remote files to work_dir\n\n        try:\n            params = json5.loads(params)\n            code = params['code']\n        except Exception:\n            code = extract_code(params)\n\n        if not code.strip():\n            return ''\n\n        kernel_id: str = f'{self.instance_id}_{os.getpid()}'\n        if kernel_id in _KERNEL_CLIENTS:\n            kc = _KERNEL_CLIENTS[kernel_id]\n        else:\n            _fix_matplotlib_cjk_font_issue()\n            self._fix_secure_write_for_code_interpreter()\n            kc, subproc = self._start_kernel(kernel_id)\n            with open(INIT_CODE_FILE) as fin:\n                start_code = fin.read()\n                start_code = start_code.replace('{{M6_FONT_PATH}}', repr(ALIB_FONT_FILE)[1:-1])\n                start_code += '\\n%xmode Minimal'\n            self._execute_code(kc, start_code)\n            # logger.info(self._execute_code(kc, start_code))\n            _KERNEL_CLIENTS[kernel_id] = kc\n            _MISC_SUBPROCESSES[kernel_id] = subproc\n\n        if timeout:\n            code = f'_M6CountdownTimer.start({timeout})\\n{code}'\n\n        fixed_code = []\n        for line in code.split('\\n'):\n            fixed_code.append(line)\n            if line.startswith('sns.set_theme('):\n                fixed_code.append('plt.rcParams[\"font.family\"] = _m6_font_prop.get_name()')\n        fixed_code = '\\n'.join(fixed_code)\n        fixed_code += '\\n\\n'  # Prevent code not executing in notebook due to no line breaks at the end\n        result = self._execute_code(kc, fixed_code)\n\n        if timeout:\n            self._execute_code(kc, '_M6CountdownTimer.cancel()')\n\n        return result if result.strip() else 'Finished execution.'\n\n    def __del__(self):\n        # Recycle the jupyter subprocess:\n        k: str = f'{self.instance_id}_{os.getpid()}'\n        if k in _KERNEL_CLIENTS:\n            _KERNEL_CLIENTS[k].shutdown()\n            del _KERNEL_CLIENTS[k]\n        if k in _MISC_SUBPROCESSES:\n            _MISC_SUBPROCESSES[k].terminate()\n            del _MISC_SUBPROCESSES[k]\n\n    def _fix_secure_write_for_code_interpreter(self):\n        if 'linux' in sys.platform.lower():\n            os.makedirs(self.work_dir, exist_ok=True)\n            fname = os.path.join(self.work_dir, f'test_file_permission_{os.getpid()}.txt')\n            if os.path.exists(fname):\n                os.remove(fname)\n            with os.fdopen(os.open(fname, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o0600), 'w') as f:\n                f.write('test')\n            file_mode = stat.S_IMODE(os.stat(fname).st_mode) & 0o6677\n            if file_mode != 0o0600:\n                os.environ['JUPYTER_ALLOW_INSECURE_WRITES'] = '1'\n            if os.path.exists(fname):\n                os.remove(fname)\n\n    def _start_kernel(self, kernel_id: str):\n        connection_file = os.path.join(self.work_dir, f'kernel_connection_file_{kernel_id}.json')\n        launch_kernel_script = os.path.join(self.work_dir, f'launch_kernel_{kernel_id}.py')\n        for f in [connection_file, launch_kernel_script]:\n            if os.path.exists(f):\n                logger.info(f'WARNING: {f} already exists')\n                os.remove(f)\n\n        os.makedirs(self.work_dir, exist_ok=True)\n        with open(launch_kernel_script, 'w') as fout:\n            fout.write(LAUNCH_KERNEL_PY)\n\n        kernel_process = subprocess.Popen(\n            [\n                sys.executable,\n                os.path.abspath(launch_kernel_script),\n                '--IPKernelApp.connection_file',\n                os.path.abspath(connection_file),\n                '--matplotlib=inline',\n                '--quiet',\n            ],\n            cwd=os.path.abspath(self.work_dir),\n        )\n        logger.info(f\"INFO: kernel process's PID = {kernel_process.pid}\")\n\n        # Wait for kernel connection file to be written\n        while True:\n            if not os.path.isfile(connection_file):\n                time.sleep(0.1)\n            else:\n                # Keep looping if JSON parsing fails, file may be partially written\n                try:\n                    with open(connection_file, 'r') as fp:\n                        json.load(fp)\n                    break\n                except json.JSONDecodeError:\n                    pass\n\n        # Client\n        from jupyter_client import BlockingKernelClient\n\n        kc = BlockingKernelClient(connection_file=connection_file)\n        asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())\n        kc.load_connection_file()\n        kc.start_channels()\n        kc.wait_for_ready()\n        return kc, kernel_process\n\n    def _execute_code(self, kc, code: str) -> str:\n        kc.wait_for_ready()\n        kc.execute(code)\n        result = ''\n        image_idx = 0\n        while True:\n            text = ''\n            image = ''\n            finished = False\n            msg_type = 'error'\n            try:\n                msg = kc.get_iopub_msg()\n                msg_type = msg['msg_type']\n                if msg_type == 'status':\n                    if msg['content'].get('execution_state') == 'idle':\n                        finished = True\n                elif msg_type == 'execute_result':\n                    text = msg['content']['data'].get('text/plain', '')\n                    if 'image/png' in msg['content']['data']:\n                        image_b64 = msg['content']['data']['image/png']\n                        image_url = self._serve_image(image_b64)\n                        image_idx += 1\n                        image = '![fig-%03d](%s)' % (image_idx, image_url)\n                elif msg_type == 'display_data':\n                    if 'image/png' in msg['content']['data']:\n                        image_b64 = msg['content']['data']['image/png']\n                        image_url = self._serve_image(image_b64)\n                        image_idx += 1\n                        image = '![fig-%03d](%s)' % (image_idx, image_url)\n                    else:\n                        text = msg['content']['data'].get('text/plain', '')\n                elif msg_type == 'stream':\n                    msg_type = msg['content']['name']  # stdout, stderr\n                    text = msg['content']['text']\n                elif msg_type == 'error':\n                    text = _escape_ansi('\\n'.join(msg['content']['traceback']))\n                    if 'M6_CODE_INTERPRETER_TIMEOUT' in text:\n                        text = 'Timeout: Code execution exceeded the time limit.'\n            except queue.Empty:\n                text = 'Timeout: Code execution exceeded the time limit.'\n                finished = True\n            except Exception:\n                text = 'The code interpreter encountered an unexpected error.'\n                print_traceback()\n                finished = True\n            if text:\n                result += f'\\n\\n{msg_type}:\\n\\n```\\n{text}\\n```'\n            if image:\n                result += f'\\n\\n{image}'\n            if finished:\n                break\n        result = result.lstrip('\\n')\n        return result\n\n    def _serve_image(self, image_base64: str) -> str:\n        import PIL.Image\n\n        image_file = f'{uuid.uuid4()}.png'\n        local_image_file = os.path.join(self.work_dir, image_file)\n\n        png_bytes = base64.b64decode(image_base64)\n        assert isinstance(png_bytes, bytes)\n        bytes_io = io.BytesIO(png_bytes)\n        PIL.Image.open(bytes_io).save(local_image_file, 'png')\n\n        image_server_url = os.getenv('M6_CODE_INTERPRETER_STATIC_URL', '')\n        if image_server_url:\n            return f'{image_server_url}/{image_file}'\n        return local_image_file\n\n\ndef _check_deps_for_code_interpreter():\n    try:\n        import matplotlib  # noqa\n        import matplotlib.pyplot as plt  # noqa\n        import numpy as np  # noqa\n        import pandas as pd  # noqa\n        import PIL.Image  # noqa\n        import seaborn as sns  # noqa\n        from jupyter_client import BlockingKernelClient  # noqa\n        from sympy import Eq, solve, symbols  # noqa\n    except ImportError as e:\n        raise ImportError(\n            'The dependencies for Code Interpreter support are not installed. '\n            'Please install the required dependencies by running: pip install \"qwen-agent[code_interpreter]\"') from e\n\n\ndef _fix_matplotlib_cjk_font_issue():\n    import matplotlib\n\n    ttf_name = os.path.basename(ALIB_FONT_FILE)\n    local_ttf = os.path.join(os.path.abspath(os.path.join(matplotlib.matplotlib_fname(), os.path.pardir)), 'fonts',\n                             'ttf', ttf_name)\n    if not os.path.exists(local_ttf):\n        try:\n            shutil.copy(ALIB_FONT_FILE, local_ttf)\n            font_list_cache = os.path.join(matplotlib.get_cachedir(), 'fontlist-*.json')\n            for cache_file in glob.glob(font_list_cache):\n                with open(cache_file) as fin:\n                    cache_content = fin.read()\n                if ttf_name not in cache_content:\n                    os.remove(cache_file)\n        except Exception:\n            print_traceback()\n\n\ndef _escape_ansi(line: str) -> str:\n    ansi_escape = re.compile(r'(?:\\x1B[@-_]|[\\x80-\\x9F])[0-?]*[ -/]*[@-~]')\n    return ansi_escape.sub('', line)\n\n\n#\n# The _BasePolicy and AnyThreadEventLoopPolicy below are borrowed from Tornado.\n# Ref: https://www.tornadoweb.org/en/stable/_modules/tornado/platform/asyncio.html#AnyThreadEventLoopPolicy\n#\n\nif sys.platform == 'win32' and hasattr(asyncio, 'WindowsSelectorEventLoopPolicy'):\n    _BasePolicy = asyncio.WindowsSelectorEventLoopPolicy  # type: ignore\nelse:\n    _BasePolicy = asyncio.DefaultEventLoopPolicy\n\n\nclass AnyThreadEventLoopPolicy(_BasePolicy):  # type: ignore\n    \"\"\"Event loop policy that allows loop creation on any thread.\n\n    The default `asyncio` event loop policy only automatically creates\n    event loops in the main threads. Other threads must create event\n    loops explicitly or `asyncio.get_event_loop` (and therefore\n    `.IOLoop.current`) will fail. Installing this policy allows event\n    loops to be created automatically on any thread.\n\n    Usage::\n        asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())\n    \"\"\"\n\n    def get_event_loop(self) -> asyncio.AbstractEventLoop:\n        try:\n            return super().get_event_loop()\n        except RuntimeError:\n            # \"There is no current event loop in thread %r\"\n            loop = self.new_event_loop()\n            self.set_event_loop(loop)\n            return loop"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/tools/python_executor.py",
    "content": "import copy\nimport datetime\nimport io\nimport os\nimport pickle\nimport traceback\nfrom concurrent.futures import TimeoutError\nfrom contextlib import redirect_stdout\nfrom functools import partial\nfrom typing import Any, Dict, List, Optional, Union\nfrom multiprocessing import Pool, cpu_count\n\nimport json5\nimport regex\nfrom tqdm import tqdm\n\nfrom qwen_agent.tools.base import BaseTool\nfrom qwen_agent.utils.utils import extract_code\n\n\nclass GenericRuntime:\n    GLOBAL_DICT = {}\n    LOCAL_DICT = None\n    HEADERS = []\n\n    def __init__(self):\n        self._global_vars = copy.copy(self.GLOBAL_DICT)\n        self._local_vars = copy.copy(self.LOCAL_DICT) if self.LOCAL_DICT else None\n\n        for c in self.HEADERS:\n            self.exec_code(c)\n\n    def exec_code(self, code_piece: str) -> None:\n        if regex.search(r'(\\s|^)?input\\(', code_piece) or regex.search(r'(\\s|^)?os.system\\(', code_piece):\n            raise RuntimeError()\n        exec(code_piece, self._global_vars)\n\n    def eval_code(self, expr: str) -> Any:\n        return eval(expr, self._global_vars)\n\n    def inject(self, var_dict: Dict[str, Any]) -> None:\n        for k, v in var_dict.items():\n            self._global_vars[k] = v\n\n    @property\n    def answer(self):\n        return self._global_vars['answer']\n\n\nclass DateRuntime(GenericRuntime):\n    import dateutil.relativedelta\n    GLOBAL_DICT = {\n        'datetime': datetime.datetime,\n        'timedelta': dateutil.relativedelta.relativedelta,\n        'relativedelta': dateutil.relativedelta.relativedelta\n    }\n\n\nclass CustomDict(dict):\n\n    def __iter__(self):\n        return list(super().__iter__()).__iter__()\n\n\nclass ColorObjectRuntime(GenericRuntime):\n    GLOBAL_DICT = {'dict': CustomDict}\n\n\ndef _check_deps_for_python_executor():\n    try:\n        import dateutil.relativedelta  # noqa\n        import multiprocess  # noqa\n        from multiprocess import Pool  # noqa\n        from pebble import ProcessPool  # noqa\n        from timeout_decorator import timeout  # noqa\n    except ImportError as e:\n        raise ImportError(\n            'The dependencies for Python Executor support are not installed. '\n            'Please install the required dependencies by running: pip install \"qwen-agent[python_executor]\"') from e\n\n\n# @register_tool('python_executor')  # Do not register this tool by default because it is dangerous.\nclass PythonExecutor(BaseTool):\n    name = 'python_executor'\n    description = 'For executing python code. Not sandboxed. Do not use it for production purposes.'\n    parameters = [{'name': 'code', 'type': 'string', 'description': '待执行的代码', 'required': True}]\n\n    def __init__(self, cfg: Optional[Dict] = None):\n        _check_deps_for_python_executor()\n        import multiprocess\n        from multiprocess import Pool\n        super().__init__(cfg)\n\n        runtime: Optional[Any] = self.cfg.get('runtime', None)\n        get_answer_symbol: Optional[str] = self.cfg.get('get_answer_symbol', None)\n        get_answer_expr: Optional[str] = self.cfg.get('get_answer_expr', None)\n        get_answer_from_stdout: bool = self.cfg.get('get_answer_from_stdout', True)\n        timeout_length: int = self.cfg.get('timeout_length', 20)\n\n        self.runtime = runtime if runtime else GenericRuntime()\n        self.answer_symbol = get_answer_symbol\n        self.answer_expr = get_answer_expr\n        self.get_answer_from_stdout = get_answer_from_stdout\n        self.pool = Pool(multiprocess.cpu_count())\n        self.timeout_length = timeout_length\n\n    def call(self, params: Union[str, dict], **kwargs) -> list:\n        try:\n            params = json5.loads(params)\n            code = params['code']\n        except Exception:\n            code = extract_code(params)\n\n        if not code.strip():\n            return ['', '']\n\n        predictions = self.apply(code)\n        return predictions\n\n    def apply(self, code: str) -> list:\n        return self.batch_apply([code])[0]\n\n    def process_generation_to_code(self, gens: str):\n        return [g.split('\\n') for g in gens]\n\n    @staticmethod\n    def execute(\n        code,\n        get_answer_from_stdout=None,\n        runtime=None,\n        answer_symbol=None,\n        answer_expr=None,\n        timeout_length=20,\n    ):\n        from timeout_decorator import timeout\n        try:\n            if get_answer_from_stdout:\n                program_io = io.StringIO()\n                with redirect_stdout(program_io):\n                    timeout(timeout_length)(runtime.exec_code)('\\n'.join(code))\n                program_io.seek(0)\n                result = program_io.read()\n            elif answer_symbol:\n                timeout(timeout_length)(runtime.exec_code)('\\n'.join(code))\n                result = runtime._global_vars[answer_symbol]\n            elif answer_expr:\n                timeout(timeout_length)(runtime.exec_code)('\\n'.join(code))\n                result = timeout(timeout_length)(runtime.eval_code)(answer_expr)\n            else:\n                timeout(timeout_length)(runtime.exec_code)('\\n'.join(code[:-1]))\n                result = timeout(timeout_length)(runtime.eval_code)(code[-1])\n            report = 'Done'\n            str(result)\n            pickle.dumps(result)  # serialization check\n        except Exception:\n            result = ''\n            report = traceback.format_exc().split('\\n')[-2]\n        return result, report\n\n    @staticmethod\n    def truncate(s, max_length=256):\n        half = max_length // 2\n        if len(s) > max_length:\n            s = s[:half] + '...' + s[-half:]\n        return s\n\n    def batch_apply(self, batch_code: List[str]) -> list:\n        from pebble import ProcessPool\n        all_code_snippets = self.process_generation_to_code(batch_code)\n\n        timeout_cnt = 0\n        all_exec_results = []\n        with ProcessPool(max_workers=min(len(all_code_snippets), os.cpu_count())) as pool:\n            executor = partial(\n                self.execute,\n                get_answer_from_stdout=self.get_answer_from_stdout,\n                runtime=self.runtime,\n                answer_symbol=self.answer_symbol,\n                answer_expr=self.answer_expr,\n                timeout_length=self.timeout_length,  # this timeout not work\n            )\n            future = pool.map(executor, all_code_snippets, timeout=self.timeout_length)\n            iterator = future.result()\n\n            if len(all_code_snippets) > 100:\n                progress_bar = tqdm(total=len(all_code_snippets), desc='Execute')\n            else:\n                progress_bar = None\n\n            while True:\n                try:\n                    result = next(iterator)\n                    all_exec_results.append(result)\n                except StopIteration:\n                    break\n                except TimeoutError as error:\n                    print(error)\n                    all_exec_results.append(('', 'Timeout Error'))\n                    timeout_cnt += 1\n                except Exception as error:\n                    print(error)\n                    exit()\n                if progress_bar is not None:\n                    progress_bar.update(1)\n\n            if progress_bar is not None:\n                progress_bar.close()\n\n        batch_results = []\n        for code, (res, report) in zip(all_code_snippets, all_exec_results):\n            # post processing\n            res, report = str(res).strip(), str(report).strip()\n            res, report = self.truncate(res), self.truncate(report)\n            batch_results.append((res, report))\n        return batch_results\n\n\n\ndef _test():\n    batch_code = [\"\"\"import math\nprint(math.pi*4)\"\"\"]\n\n    executor = PythonExecutor()\n    predictions = executor.apply(batch_code[0])\n    print(predictions)\n\n\nif __name__ == '__main__':\n    _test()\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/qwen_agent/utils/utils.py",
    "content": "import base64\nimport copy\nimport hashlib\nimport json\nimport os\nimport re\nimport shutil\nimport signal\nimport socket\nimport sys\nimport time\nimport traceback\nimport urllib.parse\nfrom io import BytesIO\nfrom typing import Any, List, Literal, Optional, Tuple, Union\n\nimport json5\nimport requests\nfrom pydantic import BaseModel\n\nfrom qwen_agent.llm.schema import ASSISTANT, DEFAULT_SYSTEM_MESSAGE, FUNCTION, SYSTEM, USER, ContentItem, Message\nfrom qwen_agent.log import logger\n\n\ndef append_signal_handler(sig, handler):\n    \"\"\"\n    Installs a new signal handler while preserving any existing handler.\n    If an existing handler is present, it will be called _after_ the new handler.\n    \"\"\"\n\n    old_handler = signal.getsignal(sig)\n    if not callable(old_handler):\n        old_handler = None\n        if sig == signal.SIGINT:\n\n            def old_handler(*args, **kwargs):\n                raise KeyboardInterrupt\n        elif sig == signal.SIGTERM:\n\n            def old_handler(*args, **kwargs):\n                raise SystemExit\n\n    def new_handler(*args, **kwargs):\n        handler(*args, **kwargs)\n        if old_handler is not None:\n            old_handler(*args, **kwargs)\n\n    signal.signal(sig, new_handler)\n\n\ndef get_local_ip() -> str:\n    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    try:\n        # doesn't even have to be reachable\n        s.connect(('10.255.255.255', 1))\n        ip = s.getsockname()[0]\n    except Exception:\n        ip = '127.0.0.1'\n    finally:\n        s.close()\n    return ip\n\n\ndef hash_sha256(text: str) -> str:\n    hash_object = hashlib.sha256(text.encode())\n    key = hash_object.hexdigest()\n    return key\n\n\ndef print_traceback(is_error: bool = True):\n    tb = ''.join(traceback.format_exception(*sys.exc_info(), limit=3))\n    if is_error:\n        logger.error(tb)\n    else:\n        logger.warning(tb)\n\n\nCHINESE_CHAR_RE = re.compile(r'[\\u4e00-\\u9fff]')\n\n\ndef has_chinese_chars(data: Any) -> bool:\n    text = f'{data}'\n    return bool(CHINESE_CHAR_RE.search(text))\n\n\ndef has_chinese_messages(messages: List[Union[Message, dict]], check_roles: Tuple[str] = (SYSTEM, USER)) -> bool:\n    for m in messages:\n        if m['role'] in check_roles:\n            if has_chinese_chars(m['content']):\n                return True\n    return False\n\n\ndef get_basename_from_url(path_or_url: str) -> str:\n    if re.match(r'^[A-Za-z]:\\\\', path_or_url):\n        # \"C:\\\\a\\\\b\\\\c\" -> \"C:/a/b/c\"\n        path_or_url = path_or_url.replace('\\\\', '/')\n\n    # \"/mnt/a/b/c\" -> \"c\"\n    # \"https://github.com/here?k=v\" -> \"here\"\n    # \"https://github.com/\" -> \"\"\n    basename = urllib.parse.urlparse(path_or_url).path\n    basename = os.path.basename(basename)\n    basename = urllib.parse.unquote(basename)\n    basename = basename.strip()\n\n    # \"https://github.com/\" -> \"\" -> \"github.com\"\n    if not basename:\n        basename = [x.strip() for x in path_or_url.split('/') if x.strip()][-1]\n\n    return basename\n\n\ndef is_http_url(path_or_url: str) -> bool:\n    if path_or_url.startswith('https://') or path_or_url.startswith('http://'):\n        return True\n    return False\n\n\ndef is_image(path_or_url: str) -> bool:\n    filename = get_basename_from_url(path_or_url).lower()\n    for ext in ['jpg', 'jpeg', 'png', 'webp']:\n        if filename.endswith(ext):\n            return True\n    return False\n\n\ndef sanitize_chrome_file_path(file_path: str) -> str:\n    if os.path.exists(file_path):\n        return file_path\n\n    # Dealing with \"file:///...\":\n    new_path = urllib.parse.urlparse(file_path)\n    new_path = urllib.parse.unquote(new_path.path)\n    new_path = sanitize_windows_file_path(new_path)\n    if os.path.exists(new_path):\n        return new_path\n\n    return sanitize_windows_file_path(file_path)\n\n\ndef sanitize_windows_file_path(file_path: str) -> str:\n    # For Linux and macOS.\n    if os.path.exists(file_path):\n        return file_path\n\n    # For native Windows, drop the leading '/' in '/C:/'\n    win_path = file_path\n    if win_path.startswith('/'):\n        win_path = win_path[1:]\n    if os.path.exists(win_path):\n        return win_path\n\n    # For Windows + WSL.\n    if re.match(r'^[A-Za-z]:/', win_path):\n        wsl_path = f'/mnt/{win_path[0].lower()}/{win_path[3:]}'\n        if os.path.exists(wsl_path):\n            return wsl_path\n\n    # For native Windows, replace / with \\.\n    win_path = win_path.replace('/', '\\\\')\n    if os.path.exists(win_path):\n        return win_path\n\n    return file_path\n\n\ndef save_url_to_local_work_dir(url: str, save_dir: str, save_filename: str = '') -> str:\n    if not save_filename:\n        save_filename = get_basename_from_url(url)\n    new_path = os.path.join(save_dir, save_filename)\n    if os.path.exists(new_path):\n        os.remove(new_path)\n    logger.info(f'Downloading {url} to {new_path}...')\n    start_time = time.time()\n    if not is_http_url(url):\n        url = sanitize_chrome_file_path(url)\n        shutil.copy(url, new_path)\n    else:\n        headers = {\n            'User-Agent':\n                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'\n        }\n        response = requests.get(url, headers=headers)\n        if response.status_code == 200:\n            with open(new_path, 'wb') as file:\n                file.write(response.content)\n        else:\n            raise ValueError('Can not download this file. Please check your network or the file link.')\n    end_time = time.time()\n    logger.info(f'Finished downloading {url} to {new_path}. Time spent: {end_time - start_time} seconds.')\n    return new_path\n\n\ndef save_text_to_file(path: str, text: str) -> None:\n    with open(path, 'w', encoding='utf-8') as fp:\n        fp.write(text)\n\n\ndef read_text_from_file(path: str) -> str:\n    try:\n        with open(path, 'r', encoding='utf-8') as file:\n            file_content = file.read()\n    except UnicodeDecodeError:\n        print_traceback(is_error=False)\n        from charset_normalizer import from_path\n        results = from_path(path)\n        file_content = str(results.best())\n    return file_content\n\n\ndef contains_html_tags(text: str) -> bool:\n    pattern = r'<(p|span|div|li|html|script)[^>]*?'\n    return bool(re.search(pattern, text))\n\n\ndef get_content_type_by_head_request(path: str) -> str:\n    try:\n        response = requests.head(path, timeout=5)\n        content_type = response.headers.get('Content-Type', '')\n        return content_type\n    except requests.RequestException:\n        return 'unk'\n\n\ndef get_file_type(path: str) -> Literal['pdf', 'docx', 'pptx', 'txt', 'html', 'csv', 'tsv', 'xlsx', 'xls', 'unk']:\n    f_type = get_basename_from_url(path).split('.')[-1].lower()\n    if f_type in ['pdf', 'docx', 'pptx', 'csv', 'tsv', 'xlsx', 'xls']:\n        # Specially supported file types\n        return f_type\n\n    if is_http_url(path):\n        # The HTTP header information for the response is obtained by making a HEAD request to the target URL,\n        # where the Content-type field usually indicates the Type of Content to be returned\n        content_type = get_content_type_by_head_request(path)\n        if 'application/pdf' in content_type:\n            return 'pdf'\n        elif 'application/msword' in content_type:\n            return 'docx'\n\n        # Assuming that the URL is HTML by default,\n        # because the file downloaded by the request may contain html tags\n        return 'html'\n    else:\n        # Determine by reading local HTML file\n        try:\n            content = read_text_from_file(path)\n        except Exception:\n            print_traceback()\n            return 'unk'\n\n        if contains_html_tags(content):\n            return 'html'\n        else:\n            return 'txt'\n\n\ndef extract_urls(text: str) -> List[str]:\n    pattern = re.compile(r'https?://\\S+')\n    urls = re.findall(pattern, text)\n    return urls\n\n\ndef extract_markdown_urls(md_text: str) -> List[str]:\n    pattern = r'!?\\[[^\\]]*\\]\\(([^\\)]+)\\)'\n    urls = re.findall(pattern, md_text)\n    return urls\n\n\ndef extract_code(text: str) -> str:\n    # Match triple backtick blocks first\n    triple_match = re.search(r'```[^\\n]*\\n(.+?)```', text, re.DOTALL)\n    if triple_match:\n        text = triple_match.group(1)\n    else:\n        try:\n            text = json5.loads(text)['code']\n        except Exception:\n            print_traceback(is_error=False)\n    # If no code blocks found, return original text\n    return text\n\n\ndef json_loads(text: str) -> dict:\n    text = text.strip('\\n')\n    if text.startswith('```') and text.endswith('\\n```'):\n        text = '\\n'.join(text.split('\\n')[1:-1])\n    try:\n        return json.loads(text)\n    except json.decoder.JSONDecodeError as json_err:\n        try:\n            return json5.loads(text)\n        except ValueError:\n            raise json_err\n\n\nclass PydanticJSONEncoder(json.JSONEncoder):\n\n    def default(self, obj):\n        if isinstance(obj, BaseModel):\n            return obj.model_dump()\n        return super().default(obj)\n\n\ndef json_dumps_pretty(obj: dict, ensure_ascii=False, indent=2, **kwargs) -> str:\n    return json.dumps(obj, ensure_ascii=ensure_ascii, indent=indent, cls=PydanticJSONEncoder, **kwargs)\n\n\ndef json_dumps_compact(obj: dict, ensure_ascii=False, indent=None, **kwargs) -> str:\n    return json.dumps(obj, ensure_ascii=ensure_ascii, indent=indent, cls=PydanticJSONEncoder, **kwargs)\n\n\ndef format_as_multimodal_message(\n    msg: Message,\n    add_upload_info: bool,\n    add_multimodel_upload_info: bool,\n    lang: Literal['auto', 'en', 'zh'] = 'auto',\n) -> Message:\n    assert msg.role in (USER, ASSISTANT, SYSTEM, FUNCTION)\n    content: List[ContentItem] = []\n    if isinstance(msg.content, str):  # if text content\n        if msg.content:\n            content = [ContentItem(text=msg.content)]\n    elif isinstance(msg.content, list):  # if multimodal content\n        files = []\n        for item in msg.content:\n            k, v = item.get_type_and_value()\n            if k in ('text', 'image', 'audio', 'video'):\n                content.append(item)\n            if k == 'file':\n                # Move 'file' out of 'content' since it's not natively supported by models\n                files.append(v)\n            if add_multimodel_upload_info and k == 'image':\n                # Indicate the image name\n                # Not considering audio and video for now\n                files.append(v)\n        if add_upload_info and files and (msg.role in (SYSTEM, USER)):\n            if lang == 'auto':\n                has_zh = has_chinese_chars(msg)\n            else:\n                has_zh = (lang == 'zh')\n            upload = []\n            for f in [get_basename_from_url(f) for f in files]:\n                if is_image(f):\n                    if has_zh:\n                        upload.append(f'![图片]({f})')\n                    else:\n                        upload.append(f'![image]({f})')\n                else:\n                    if has_zh:\n                        upload.append(f'[文件]({f})')\n                    else:\n                        upload.append(f'[file]({f})')\n            upload = ' '.join(upload)\n            if has_zh:\n                upload = f'（上传了 {upload}）\\n\\n'\n            else:\n                upload = f'(Uploaded {upload})\\n\\n'\n\n            # Check and avoid adding duplicate upload info\n            upload_info_already_added = False\n            for item in content:\n                if item.text and (upload in item.text):\n                    upload_info_already_added = True\n\n            if not upload_info_already_added:\n                content = [ContentItem(text=upload)] + content\n    else:\n        raise TypeError\n    msg = Message(role=msg.role,\n                  content=content,\n                  name=msg.name if msg.role == FUNCTION else None,\n                  function_call=msg.function_call,\n                  extra=msg.extra)\n    return msg\n\n\ndef format_as_text_message(\n    msg: Message,\n    add_upload_info: bool,\n    lang: Literal['auto', 'en', 'zh'] = 'auto',\n) -> Message:\n    msg = format_as_multimodal_message(msg,\n                                       add_upload_info=add_upload_info,\n                                       add_multimodel_upload_info=add_upload_info,\n                                       lang=lang)\n    text = ''\n    for item in msg.content:\n        if item.type == 'text':\n            text += item.value\n    msg.content = text\n    return msg\n\n\ndef extract_text_from_message(\n    msg: Message,\n    add_upload_info: bool,\n    lang: Literal['auto', 'en', 'zh'] = 'auto',\n) -> str:\n    if isinstance(msg.content, list):\n        text = format_as_text_message(msg, add_upload_info=add_upload_info, lang=lang).content\n    elif isinstance(msg.content, str):\n        text = msg.content\n    else:\n        raise TypeError(f'List of str or str expected, but received {type(msg.content).__name__}.')\n    return text.strip()\n\n\ndef extract_files_from_messages(messages: List[Message], include_images: bool) -> List[str]:\n    files = []\n    for msg in messages:\n        if isinstance(msg.content, list):\n            for item in msg.content:\n                if item.file and item.file not in files:\n                    files.append(item.file)\n                if include_images and item.image and item.image not in files:\n                    files.append(item.image)\n    return files\n\n\ndef merge_generate_cfgs(base_generate_cfg: Optional[dict], new_generate_cfg: Optional[dict]) -> dict:\n    generate_cfg: dict = copy.deepcopy(base_generate_cfg or {})\n    if new_generate_cfg:\n        for k, v in new_generate_cfg.items():\n            if k == 'stop':\n                stop = generate_cfg.get('stop', [])\n                stop = stop + [s for s in v if s not in stop]\n                generate_cfg['stop'] = stop\n            else:\n                generate_cfg[k] = v\n    return generate_cfg\n\n\ndef build_text_completion_prompt(\n    messages: List[Message],\n    allow_special: bool = False,\n    default_system: str = DEFAULT_SYSTEM_MESSAGE,\n) -> str:\n    im_start = '<|im_start|>'\n    im_end = '<|im_end|>'\n\n    if messages[0].role == SYSTEM:\n        sys = messages[0].content\n        assert isinstance(sys, str)\n        prompt = f'{im_start}{SYSTEM}\\n{sys}{im_end}'\n        messages = messages[1:]\n    else:\n        prompt = f'{im_start}{SYSTEM}\\n{default_system}{im_end}'\n\n    # Make sure we are completing the chat in the tone of the assistant\n    if messages[-1].role != ASSISTANT:\n        messages = messages + [Message(ASSISTANT, '')]\n\n    for msg in messages:\n        assert isinstance(msg.content, str)\n        content = msg.content\n        if allow_special:\n            assert msg.role in (USER, ASSISTANT, SYSTEM, FUNCTION)\n            if msg.function_call:\n                assert msg.role == ASSISTANT\n                tool_call = msg.function_call.arguments\n                try:\n                    tool_call = {'name': msg.function_call.name, 'arguments': json.loads(tool_call)}\n                    tool_call = json.dumps(tool_call, ensure_ascii=False, indent=2)\n                except json.decoder.JSONDecodeError:\n                    tool_call = '{\"name\": \"' + msg.function_call.name + '\", \"arguments\": ' + tool_call + '}'\n                if content:\n                    content += '\\n'\n                content += f'<tool_call>\\n{tool_call}\\n</tool_call>'\n        else:\n            assert msg.role in (USER, ASSISTANT)\n            assert msg.function_call is None\n        prompt += f'\\n{im_start}{msg.role}\\n{content}{im_end}'\n\n    assert prompt.endswith(im_end)\n    prompt = prompt[:-len(im_end)]\n    return prompt\n\n\ndef encode_image_as_base64(path: str, max_short_side_length: int = -1) -> str:\n    from PIL import Image\n    image = Image.open(path)\n\n    if (max_short_side_length > 0) and (min(image.size) > max_short_side_length):\n        ori_size = image.size\n        image = resize_image(image, short_side_length=max_short_side_length)\n        logger.debug(f'Image \"{path}\" resized from {ori_size} to {image.size}.')\n\n    image = image.convert(mode='RGB')\n    buffered = BytesIO()\n    image.save(buffered, format='JPEG')\n    return 'data:image/jpeg;base64,' + base64.b64encode(buffered.getvalue()).decode('utf-8')\n\n\ndef load_image_from_base64(image_base64: Union[bytes, str]):\n    from PIL import Image\n    image = Image.open(BytesIO(base64.b64decode(image_base64)))\n    image.load()\n    return image\n\n\ndef resize_image(img, short_side_length: int = 1080):\n    from PIL import Image\n    assert isinstance(img, Image.Image)\n\n    width, height = img.size\n\n    if width <= height:\n        new_width = short_side_length\n        new_height = int((short_side_length / width) * height)\n    else:\n        new_height = short_side_length\n        new_width = int((short_side_length / height) * width)\n\n    resized_img = img.resize((new_width, new_height), resample=Image.Resampling.BILINEAR)\n    return resized_img\n\n\ndef get_last_usr_msg_idx(messages: List[Union[dict, Message]]) -> int:\n    i = len(messages) - 1\n    while (i >= 0) and (messages[i]['role'] != 'user'):\n        i -= 1\n    assert i >= 0, messages\n    assert messages[i]['role'] == 'user'\n    return i\n"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/vllm_rollout.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe vllm_rollout that can be applied in different backend\nWhen working with FSDP:\n- Use DTensor weight loader (recommended) or HF weight loader\n- Utilize state_dict from the FSDP to synchronize the weights among tp ranks in vLLM\nWhen working with Megatron:\n- Use Megatron weight loader\n- During training, only the current pp stage holds the parameters\n- Before inference, broadcast the parameters of the current pp rank to all other pp ranks (all pp ranks holds all the parameters)\n- Bind the parameters to the inference engine\n- Do inference in tp. pp is treated as additional dp\n- After inference, all the parameters that doesn't belong to this pp rank is freed.\n\"\"\"\nfrom typing import List\nfrom contextlib import contextmanager\nfrom omegaconf import DictConfig\nimport torch\nimport torch.distributed\nfrom tensordict import TensorDict\nfrom torch import nn\n\nfrom verl import DataProto\nfrom verl.utils.torch_functional import get_eos_mask, pad_sequence_to_length\nfrom verl.workers.rollout.base import BaseRollout\nfrom verl.third_party.vllm import LLM, vllm_version\nfrom verl.third_party.vllm import parallel_state as vllm_ps\nfrom vllm import SamplingParams\n\n# TODO\n# 1. support pp in vllm\n# 2. passing tokenizer is not necessary? no encoding/decoding is happending here\n# 3. simplify init logics\n\n\n# NOTE(sgm): add for verl. We can optimize it by making the dataloader yield List[int] without padding.\ndef _pre_process_inputs(pad_token_id, prompt_token_ids: torch.Tensor) -> List[int]:\n    # remove the left padding in the prompt token_id\n    # pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n    non_pad_index = torch.nonzero(prompt_token_ids != pad_token_id, as_tuple=False)[0][0]\n    token_ids = prompt_token_ids[non_pad_index:].tolist()\n    return token_ids\n\n\nclass vLLMRollout(BaseRollout):\n\n    def __init__(self, actor_module: nn.Module, config: DictConfig, tokenizer, model_hf_config, **kwargs):\n        \"\"\"A vLLM rollout. It requires the module is supported by the vllm.\n\n        Args:\n            module: module here follows huggingface APIs\n            config: DictConfig\n            tokenizer: the task/model tokenizer\n            model_hf_config: the huggingface config to initiallize the generating model in vllm\n            **kwargs: train_tp, for Megatron Backend to initialize hybrid engine (zero redundancy) process group\n        \"\"\"\n        super().__init__()\n        self.config = config\n        assert not (not config.enforce_eager and config.free_cache_engine), \\\n            \"disable CUDA graph (enforce_eager = False) if free cache engine\"\n\n        tensor_parallel_size = self.config.get('tensor_model_parallel_size', 1)\n        assert tensor_parallel_size <= torch.distributed.get_world_size(), \\\n            \"tensor parallel size should be less than or equal to the world size\"\n        max_num_batched_tokens = int(self.config.get('max_num_batched_tokens', 8192))\n\n        if kwargs.get('train_tp', None) is not None:\n            # deployed with megatron\n            import os\n            os.environ['CUDA_TIMER_STREAM_KAFKA_ENABLE'] = '0'\n            os.environ['MEGATRON_IMPORT_TIMERS'] = '0'\n            train_tp = kwargs.get('train_tp', None)\n            num_tp_per_train_tp = train_tp // tensor_parallel_size\n            if vllm_version in ('0.4.2', '0.5.4', '0.6.3'):\n                vllm_ps.initialize_parallel_state(tensor_model_parallel_size=tensor_parallel_size,\n                                                  num_tp_per_train_tp=num_tp_per_train_tp)\n\n        assert model_hf_config.max_position_embeddings >= config.prompt_length + config.response_length, \\\n            \"model context length should be greater than total sequence length\"\n\n        max_model_len = self.config.max_model_len if self.config.max_model_len \\\n                        else config.prompt_length + config.response_length\n        max_model_len = int(max_model_len)\n\n        if max_num_batched_tokens < max_model_len and self.config.enable_chunked_prefill:\n            raise ValueError('Enable chunked prefill, max_num_batched_tokens is smaller than max_model_len, \\\n                             please increase max_num_batched_tokens or disable chunked prefill')\n\n        self.inference_engine = LLM(\n            actor_module,\n            tokenizer=tokenizer,\n            model_hf_config=model_hf_config,\n            tensor_parallel_size=tensor_parallel_size,\n            dtype=config.dtype,\n            enforce_eager=config.enforce_eager,\n            gpu_memory_utilization=config.gpu_memory_utilization,\n            skip_tokenizer_init=False,\n            max_model_len=max_model_len,\n            load_format=config.load_format,\n            disable_log_stats=config.disable_log_stats,\n            max_num_batched_tokens=max_num_batched_tokens,\n            enable_chunked_prefill=config.enable_chunked_prefill,\n        )\n\n        # Offload vllm model to reduce peak memory usage\n        self.inference_engine.offload_model_weights()\n\n        kwargs = dict(\n            n=1,\n            logprobs=1,  # can be set to 0 and let actor to recompute\n            max_tokens=config.response_length,\n        )\n\n        # we may detokenize the result all together later\n        if vllm_version in ('0.4.2', '0.5.4', '0.6.3'):\n            kwargs['detokenize'] = False\n\n        # supporting adding any sampling params from the config file\n        for k in config.keys():\n            if hasattr(SamplingParams(), str(k)):\n                kwargs[k] = config.get(k)\n\n        print(f\"kwargs: {kwargs}\")\n        self.sampling_params = SamplingParams(**kwargs)\n\n        self.pad_token_id = tokenizer.pad_token_id\n\n    @contextmanager\n    def update_sampling_params(self, **kwargs):\n        # update sampling params\n        old_sampling_params_args = {}\n        if kwargs:\n            for key, value in kwargs.items():\n                if hasattr(self.sampling_params, key):\n                    old_value = getattr(self.sampling_params, key)\n                    old_sampling_params_args[key] = old_value\n                    setattr(self.sampling_params, key, value)\n        yield\n        # roll back to previous sampling params\n        # if len(old_sampling_params_args):\n        for key, value in old_sampling_params_args.items():\n            setattr(self.sampling_params, key, value)\n\n    @torch.no_grad()\n    def generate_sequences(self, prompts: DataProto, **kwargs) -> DataProto:\n        # rebuild vllm cache engine\n        if self.config.free_cache_engine:\n            self.inference_engine.init_cache_engine()\n\n        idx = prompts.batch['input_ids']  # (bs, prompt_length)\n        # left-padded attention_mask\n        attention_mask = prompts.batch['attention_mask']\n        position_ids = prompts.batch['position_ids']\n\n        # used to construct attention_mask\n        eos_token_id = prompts.meta_info['eos_token_id']\n\n        batch_size = idx.size(0)\n\n        idx_list = []\n        # parse idx from torch.Tensor to List[List[str]]\n        for i in range(batch_size):\n            idx_list.append(_pre_process_inputs(self.pad_token_id, idx[i]))\n\n        do_sample = prompts.meta_info.get('do_sample', True)\n        if not do_sample:\n            kwargs = {\n                'best_of': 1,\n                'top_p': 1.0,\n                'top_k': -1,\n                'min_p': 0.0,\n                'temperature': 0,\n                'n': 1  # if greedy, only 1 response\n            }\n\n        # users can customize different sampling_params at different run\n        with self.update_sampling_params(**kwargs):\n            output = self.inference_engine.generate(\n                prompts=None,  # because we have already convert it to prompt token id\n                sampling_params=self.sampling_params,\n                prompt_token_ids=idx_list,\n                use_tqdm=False)\n\n        # TODO(sgm): disable logprob when recompute_log_prob is enable\n        # if n = 1: (bs, response_length) ; if n > 1: (bs * n, response_length)\n        response = output[0].to(idx.device)\n        log_probs = output[1].to(idx.device)\n\n        if response.shape[1] < self.config.response_length:\n            response = pad_sequence_to_length(response, self.config.response_length, self.pad_token_id)\n            log_probs = pad_sequence_to_length(log_probs, self.config.response_length, self.pad_token_id)\n\n        if self.config.n > 1 and do_sample:\n            idx = idx.repeat_interleave(self.config.n, dim=0)\n            attention_mask = attention_mask.repeat_interleave(self.config.n, dim=0)\n            position_ids = position_ids.repeat_interleave(self.config.n, dim=0)\n            batch_size = batch_size * self.config.n\n        seq = torch.cat([idx, response], dim=-1)\n\n        response_length = response.size(1)\n        delta_position_id = torch.arange(1, response_length + 1, device=position_ids.device)\n        delta_position_id = delta_position_id.unsqueeze(0).repeat(batch_size, 1)\n\n        # TODO(sgm): fix position_ids on right_pad\n        # prompt: left pad + response: right pad\n        # attention_mask: [0,0,0,0,1,1,1,1, | 1,1,1,0,0,0,0,0]\n        # position_ids:   [0,0,0,0,0,1,2,3, | 4,5,6,7,8,9,10,11]\n        response_position_ids = position_ids[:, -1:] + delta_position_id\n        position_ids = torch.cat([position_ids, response_position_ids], dim=-1)\n        response_attention_mask = get_eos_mask(response_id=response, eos_token=eos_token_id, dtype=attention_mask.dtype)\n        attention_mask = torch.cat((attention_mask, response_attention_mask), dim=-1)\n\n        # all the tp ranks should contain the same data here. data in all ranks are valid\n        batch = TensorDict(\n            {\n                'prompts': idx,\n                'responses': response,\n                'input_ids': seq,  # here input_ids become the whole sentences\n                # 'old_log_probs': log_probs, # we will recompute old log prob with actor\n                'attention_mask': attention_mask,\n                'position_ids': position_ids\n            },\n            batch_size=batch_size)\n\n        # free vllm cache engine\n        if self.config.free_cache_engine:\n            self.inference_engine.free_cache_engine()\n\n        return DataProto(batch=batch)"
  },
  {
    "path": "verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe vllm_rollout that can be applied in different backend\nWhen working with FSDP:\n- Use DTensor weight loader (recommended) or HF weight loader\n- Utilize state_dict from the FSDP to synchronize the weights among tp ranks in vLLM\nWhen working with Megatron:\n- Use Megatron weight loader\n- During training, only the current pp stage holds the parameters\n- Before inference, broadcast the parameters of the current pp rank to all other pp ranks (all pp ranks holds all the parameters)\n- Bind the parameters to the inference engine\n- Do inference in tp. pp is treated as additional dp\n- After inference, all the parameters that doesn't belong to this pp rank is freed.\n\"\"\"\nimport numpy as np\nfrom typing import List\nfrom contextlib import contextmanager\nfrom omegaconf import DictConfig\nimport os\nimport torch\nimport torch.distributed\nfrom tensordict import TensorDict\nimport requests\nfrom multiprocessing import Pool\nfrom functools import partial\nfrom torch import nn\nfrom typing import Any, Union\nfrom verl import DataProto\nfrom verl.utils.torch_functional import get_eos_mask, pad_2d_list_to_length\nfrom verl.workers.rollout.base import BaseRollout\nfrom vllm.distributed import parallel_state as vllm_ps\nfrom vllm import LLM, SamplingParams\nfrom verl.third_party.vllm import vllm_version\nfrom qwen_agent.tools.python_executor import PythonExecutor\nfrom qwen_agent.tools.code_interpreter import CodeInterpreter\nfrom qwen_agent.utils.utils import print_traceback\nfrom typing import Tuple\nimport json5\nimport pdb\nimport json\nimport copy\nfrom concurrent.futures import ThreadPoolExecutor, as_completed, TimeoutError\n# TODO\n# 1. support pp in vllm\n# 2. passing tokenizer is not necessary? no encoding/decoding is happending here\n# 3. simplify init logics\n\n\n# NOTE(sgm): add for verl. We can optimize it by making the dataloader yield List[int] without padding.\ndef _pre_process_inputs(pad_token_id, prompt_token_ids: torch.Tensor) -> List[int]:\n    # remove the left padding in the prompt token_id\n    # pad_token_id = self.llm_engine.tokenizer.pad_token_id if self.llm_engine.tokenizer.pad_token_id is not None else self.llm_engine.tokenizer.eos_token_id\n    non_pad_index = torch.nonzero(prompt_token_ids != pad_token_id, as_tuple=False)[0][0]\n    token_ids = prompt_token_ids[non_pad_index:].tolist()\n    return token_ids\n\n\ndef _repeat_interleave(value: Union[torch.Tensor, np.ndarray], repeats: int) -> Union[torch.Tensor, List[Any]]:\n    if isinstance(value, torch.Tensor):\n        return value.repeat_interleave(repeats, dim=0)\n    else:\n        return np.repeat(value, repeats, axis=0)\n\n\nOBS_START = '```output'\nOBS_END = '\\n```\\n'\ndef extract_program(result: str, last_only=True):\n    \"\"\"\n    extract the program after \"```python\", and before \"```\"\n    \"\"\"\n    program = ''\n    start = False\n    for line in result.split('\\n'):\n        if line.startswith('```python') or line.endswith('```python'):\n            if last_only:\n                program = ''  # only extract the last program\n            else:\n                program += '\\n# ========\\n'\n            start = True\n        elif line.startswith('```'):\n            start = False\n        elif start:\n            program += line + '\\n'\n    if start:\n        # the code is incomplete\n        program = ''\n    return program\n\ndef _detect_tool(text: str) -> Tuple[bool, str, str, str]:\n    program = extract_program(text)\n    if program:\n        program = json.dumps({'code': program}, ensure_ascii=False)\n    return (program != ''), PythonExecutor.name, program, text\n\ndef send_request(json_data):\n    try:\n        url = 'sandbox_url'\n        response = requests.post(url, json=json_data, timeout=10)\n        return response.json()  # 返回响应的 JSON 数据\n    except:\n        print(\"sanbox timeout\")\n        return {\"error\": \"unknown\"}\n\n\nclass vLLMRollout(BaseRollout):\n\n    def __init__(self, model_path: str, config: DictConfig, tokenizer, model_hf_config, **kwargs):\n        \"\"\"A vLLM rollout. It requires the module is supported by the vllm.\n\n        Args:\n            module: module here follows huggingface APIs\n            config: DictConfig\n            tokenizer: the task/model tokenizer\n            model_hf_config: the huggingface config to initiallize the generating model in vllm\n            **kwargs: train_tp, for Megatron Backend to initialize hybrid engine (zero redundancy) process group\n        \"\"\"\n        super().__init__()\n        self.config = config\n        assert not (not config.enforce_eager and config.free_cache_engine), \\\n            \"disable CUDA graph (enforce_eager = False) if free cache engine\"\n\n        tensor_parallel_size = self.config.get('tensor_model_parallel_size', 1)\n        assert tensor_parallel_size <= torch.distributed.get_world_size(), \\\n            \"tensor parallel size should be less than or equal to the world size\"\n        max_num_batched_tokens = self.config.get('max_num_batched_tokens', 8192)\n\n        if kwargs.get('train_tp', None) is not None:\n            # deployed with megatron\n            import os\n            os.environ['CUDA_TIMER_STREAM_KAFKA_ENABLE'] = '0'\n            os.environ['MEGATRON_IMPORT_TIMERS'] = '0'\n            train_tp = kwargs.get('train_tp', None)\n            num_tp_per_train_tp = train_tp // tensor_parallel_size\n            vllm_ps.initialize_parallel_state(tensor_model_parallel_size=tensor_parallel_size,\n                                              num_tp_per_train_tp=num_tp_per_train_tp)\n\n        assert model_hf_config.max_position_embeddings >= config.prompt_length + config.response_length, \\\n            \"model context length should be greater than total sequence length\"\n\n        self.inference_engine = LLM(\n            model=model_path,\n            enable_sleep_mode=True,\n            tensor_parallel_size=tensor_parallel_size,\n            distributed_executor_backend=\"external_launcher\",\n            dtype=config.dtype,\n            enforce_eager=config.enforce_eager,\n            gpu_memory_utilization=config.gpu_memory_utilization,\n            disable_custom_all_reduce=True,\n            skip_tokenizer_init=False,\n            max_model_len=config.prompt_length + config.response_length,\n            disable_log_stats=config.disable_log_stats,\n            max_num_batched_tokens=max_num_batched_tokens,\n            enable_chunked_prefill=config.enable_chunked_prefill,\n            enable_prefix_caching=True,\n        )\n\n        # Offload vllm model to reduce peak memory usage\n        self.inference_engine.sleep(level=1)\n\n        kwargs = dict(\n            n=1,\n            logprobs=0,  # can be set to 0 and let actor to recompute\n            max_tokens=config.response_length,\n        )\n\n        # # we may detokenize the result all together later\n        if vllm_version != '0.3.1':\n            kwargs['detokenize'] = False\n\n        # supporting adding any sampling params from the config file\n        for k in config.keys():\n            if hasattr(SamplingParams(), str(k)):\n                kwargs[k] = config.get(k)\n\n        print(f\"kwargs: {kwargs}\")\n        self.sampling_params = SamplingParams(**kwargs)\n        \n        self.pad_token_id = tokenizer.pad_token_id\n        self.tokenizer = tokenizer\n        self.executor=PythonExecutor()\n        # self.code_interpreter=CodeInterpreter()\n    \n    def _get_prompts_and_indices(self, samples_info):\n        prompts, indices=[], []\n        for index, info in enumerate(samples_info):\n            if not info['stop']:\n                prompts.append(info['sequence'])\n                indices.append(info['index'])\n        return prompts, indices\n\n    # def code_interpreter_batch_call(self, tool_inputs):\n    #     with Pool(processes=min(len(tool_inputs),os.cpu_count(), 32)) as pool:\n    #         results = pool.map(self.code_interpreter.call, tool_inputs)\n    #     def postproc(result):\n    #         report=result.split(\"```\")[0].strip()\n    #         output=result.split(\"```\")[-1].split(\"```\")[-1].strip()\n    #         if report==\"stdout:\": report=\"Done\"\n    #         return (output, report)\n    #     results=[postproc(result) for result in results]\n    #     return results\n\n    def code_interpreter_batch_call(self, tool_inputs, timeout=20):\n        tool_inputs=[{'code': tool_input,'language': 'python'} for tool_input in tool_inputs]\n        results = [None] * len(tool_inputs) \n        with ThreadPoolExecutor(max_workers=max(min(len(tool_inputs), os.cpu_count(), 64), 1)) as executor:\n            future_to_index = {executor.submit(send_request, input): i for i, input in enumerate(tool_inputs)}\n            for future in as_completed(future_to_index):\n                index = future_to_index[future]\n                try:\n                    result = future.result(timeout=timeout)\n                    results[index] = result\n                except:\n                    results[index] = {\"run_result\": {\"stdout\": \"Error\", \"stderr\": \"TimeoutError\"}}\n        \n        def postproc(output):\n            try:\n                if str(output['run_result']['return_code'])=='0' or len(str(output['run_result']['stdout'])) != 0:\n                    return output['run_result']['stdout'], \"Done\"\n                else:\n                    return output['run_result']['stdout'], output['run_result']['stderr'].strip()\n            except Exception:\n                return \"Error\", \"UnknownError\"\n        results=[postproc(result) for result in results]\n        return results\n\n    def _tokenize_and_find_mask_token_indices(self, sample_info):\n        response=sample_info['response']\n        mask_str_ranges=sample_info['mask_info']\n\n        encoding=self.tokenizer(response, add_special_tokens=False, return_offsets_mapping=True)\n        \n        response_token_ids=encoding['input_ids']\n\n        offset_mapping_tensor=torch.tensor(encoding['offset_mapping'], dtype=torch.long)\n        token_starts = offset_mapping_tensor[:,0]\n        token_ends = offset_mapping_tensor[:,1]\n\n        mask_tensor=torch.ones(len(response_token_ids))\n        for mask_str_range in mask_str_ranges:\n            start_index, end_index=mask_str_range[0], mask_str_range[1]\n            mask = (token_starts < end_index) & (token_ends > start_index) & (token_starts >= start_index)\n            mask_tensor[mask]=0 \n\n        return response_token_ids, mask_tensor\n\n\n    def _tir_generate(self, prompts=None, sampling_params=None, prompt_token_ids=None, use_tqdm=False):\n        sampling_params=copy.deepcopy(sampling_params)\n        # prompts=self.tokenizer.batch_decode(prompt_token_ids, skip_special_tokens=True)\n        prompts=[self.tokenizer.decode(prompt['prompt_token_ids'], skip_special_tokens=False) for prompt in prompts]\n        prompts=[prompt for prompt in prompts for _ in range(sampling_params.n) ]\n        sampling_params.n=1\n        sampling_params.detokenize=True\n        sampling_params.stop=[\"```output\"]\n        samples_info=[{\"prompt\": prompt, \"sequence\": prompt, \"response\": \"\", \"stop\": False, \"finish_reason\": None,\"index\": index, \"mask_info\": [], \"execution_pass\": 0} for index, prompt in enumerate(prompts)]\n        program2output=[]\n        num_llm_calls_available=copy.deepcopy(self.config.num_llm_calls_available)\n        while num_llm_calls_available >= 0:\n            if num_llm_calls_available==0: sampling_params.stop=None\n            num_llm_calls_available-=1\n            # llm generate response, stop at eos token or ```output\n            input_prompts, indices=self._get_prompts_and_indices(samples_info)\n            input_prompts = [{\n                'prompt_token_ids': self.tokenizer.encode(x, add_special_tokens=False)[:self.config.prompt_length+self.config.response_length]} for x in input_prompts]\n            outputs = self.inference_engine.generate(prompts=input_prompts, sampling_params=sampling_params, use_tqdm=use_tqdm)\n            sorted_outputs = sorted(outputs, key=lambda output: int(output.request_id))\n            responses=[x.outputs[0].text for x in sorted_outputs]\n            finish_reason=[x.outputs[0].finish_reason for x in sorted_outputs]\n            stop_reason=[x.outputs[0].stop_reason for x in sorted_outputs]\n            if num_llm_calls_available==-1:\n                for i ,index in enumerate(indices):\n                    samples_info[index]['response']+=responses[i]\n                    samples_info[index]['sequence']+=responses[i]\n                    samples_info[index]['stop']=True\n                    samples_info[index]['finish_reason']=finish_reason[i]\n                break\n\n            def _python_execution(finish_reason, stop_reason):\n                if finish_reason=='stop' and stop_reason==None: return False\n                if finish_reason=='stop' and stop_reason=='```output': return True\n                if finish_reason=='length': False\n                return False\n            is_execution=[_python_execution(finish_reason[i], stop_reason[i]) for i in range(len(finish_reason))]\n            # check if all samples are finished\n            if all([not x for x in is_execution]): break\n\n            # prepare for python execution\n            tool_infos=[ _detect_tool(response) for response in responses]\n            tool_indices=[]\n            tool_inputs=[]\n            for i, tool_info in enumerate(tool_infos):\n                if tool_info[0] and is_execution[i]:\n                    tool_indices.append(i)\n                    tool_inputs.append(tool_info[2])\n            \n            def postproc_observation(observation):\n                execution_pass=0\n                try:\n                    observation_list=observation\n                    if observation_list[-1] == 'Done':\n                        observation = observation_list[0]\n                        execution_pass=1\n                    else:\n                        observation = observation_list[-1]\n                except Exception:\n                    observation=\"Error\"\n                if \"Error\" in observation: observation=observation.strip().split(\"\\n\")[-1]\n                if len(observation.strip())==0: observation=\"timeout_decorator.timeout_decorator.TimeoutError: 'Timed Out'\"\n                observation = observation.strip()\n                if len(observation)>=256:\n                    observation = observation[:128]+\"...\"+observation[-128:]\n                observation = f'{OBS_START}\\n{observation}{OBS_END}'\n                return observation, execution_pass\n\n            # execute python code\n\n            # observations=self.executor.batch_apply([json5.loads(x)['code'] for x in tool_inputs])\n            observations=self.code_interpreter_batch_call([json5.loads(x)['code'] for x in tool_inputs])\n            \n            # construction responses from observations\n            responses=[response+\"\\n\" if not response.endswith('\\n') else response for response in responses]\n            responses_w_res=copy.deepcopy(responses)\n            execution_passes=[0 for _ in range(len(responses))]\n            for i, index in enumerate(tool_indices):\n                processed_observation=postproc_observation(observations[i])\n                responses_w_res[index]+=processed_observation[0]\n                execution_passes[index]=processed_observation[1]\n            \n            # program2output.append([{\"code\": tool_input, \"answer\": postproc_observation(observations[idx])} for idx, tool_input in enumerate(tool_inputs)])\n            # update samples_info\n            for i ,index in enumerate(indices):\n                mask=[ len(responses[i]) + len('```output'), len(responses_w_res[i]) ]\n                samples_info[index]['mask_info'].append(mask)\n                samples_info[index]['response']+=responses_w_res[i]\n                samples_info[index]['sequence']+=responses_w_res[i]\n                samples_info[index]['stop']=not is_execution[i]\n                samples_info[index]['finish_reason']=finish_reason[i]\n                samples_info[index]['execution_pass']=execution_passes[i]\n        \n        for i, line in enumerate(samples_info):\n            if samples_info[i]['finish_reason']!='length': samples_info[i]['response']+=self.tokenizer.eos_token\n        \n        responses_ids=[]\n        tool_output_masks=[]\n        execution_passes=[]\n        for idx, sample_info in enumerate(samples_info):\n            response_id, tool_output_mask = self._tokenize_and_find_mask_token_indices(sample_info)\n            responses_ids.append(response_id[:self.config.response_length])\n            tool_output_masks.append(tool_output_mask[:self.config.response_length])\n            execution_passes.append(sample_info['execution_pass'])\n            # save id and mask to check correctness\n        #     samples_info[idx]['responses_id']=response_id[:self.config.response_length]\n        #     samples_info[idx]['tool_output_mask']=tool_output_mask[:self.config.response_length].tolist()\n        \n\n        # with open(\"/mnt/bn/seedllm3-lixuefeng-2/code/o1/verl-tir/sample_infos.json\", 'w', encoding='utf-8') as f:\n        #     json.dump(samples_info, f, ensure_ascii=False, indent=2)\n        return responses_ids, tool_output_masks, torch.tensor(execution_passes, dtype=torch.long)\n\n    @contextmanager\n    def update_sampling_params(self, **kwargs):\n        # update sampling params\n        old_sampling_params_args = {}\n        if kwargs:\n            for key, value in kwargs.items():\n                if hasattr(self.sampling_params, key):\n                    old_value = getattr(self.sampling_params, key)\n                    old_sampling_params_args[key] = old_value\n                    setattr(self.sampling_params, key, value)\n        yield\n        # roll back to previous sampling params\n        # if len(old_sampling_params_args):\n        for key, value in old_sampling_params_args.items():\n            setattr(self.sampling_params, key, value)\n\n    @torch.no_grad()\n    def generate_sequences(self, prompts: DataProto, **kwargs) -> DataProto:\n        # rebuild vllm cache engine\n        if vllm_version in ('0.3.1', '0.4.2', '0.5.4', '0.6.3') and self.config.free_cache_engine:\n            self.inference_engine.init_cache_engine()\n\n        idx = prompts.batch['input_ids']  # (bs, prompt_length)\n        # left-padded attention_mask\n        attention_mask = prompts.batch['attention_mask']\n        position_ids = prompts.batch['position_ids']\n\n        # used to construct attention_mask\n        eos_token_id = prompts.meta_info['eos_token_id']\n\n        batch_size = idx.size(0)\n\n        non_tensor_batch = prompts.non_tensor_batch\n        if 'raw_prompt_ids' not in non_tensor_batch:\n            non_tensor_batch['raw_prompt_ids'] = np.array(\n                [_pre_process_inputs(self.pad_token_id, idx[i]) for i in range(batch_size)], dtype=object)\n\n        if batch_size != len(non_tensor_batch['raw_prompt_ids']):\n            raise RuntimeError('vllm sharding manager is not work properly.')\n\n        if 'multi_modal_data' in non_tensor_batch:\n            vllm_inputs = []\n            for raw_prompt_ids, multi_modal_data in zip(non_tensor_batch.pop('raw_prompt_ids'),\n                                                        non_tensor_batch.pop('multi_modal_data')):\n                vllm_inputs.append({'prompt_token_ids': raw_prompt_ids, 'multi_modal_data': multi_modal_data})\n        else:\n            vllm_inputs = [{\n                'prompt_token_ids': raw_prompt_ids\n            } for raw_prompt_ids in non_tensor_batch.pop('raw_prompt_ids')]\n\n        do_sample = prompts.meta_info.get('do_sample', True)\n        if not do_sample:\n            kwargs = {\n                'best_of': 1,\n                'top_p': 1.0,\n                'top_k': -1,\n                'min_p': 0.0,\n                'temperature': 0,\n                'n': 1  # if greedy, only 1 response\n            }\n\n        # users can customize different sampling_params at different run\n        with self.update_sampling_params(**kwargs):\n            response, tool_output_masks, execution_passes = self._tir_generate(\n                prompts=vllm_inputs,  # because we have already convert it to prompt token id\n                sampling_params=self.sampling_params,\n                use_tqdm=False)\n\n        # TODO(sgm): disable logprob when recompute_log_prob is enable\n        # if n = 1: (bs, response_length) ; if n > 1: (bs * n, response_length)\n\n        # response = []\n        # for output in outputs:\n            # for sample_id in range(len(output.outputs)):\n                # response.append(output.outputs[sample_id].token_ids)\n        response = pad_2d_list_to_length(response, self.pad_token_id,\n                                         max_length=self.config.response_length).to(idx.device)\n        tool_output_masks = pad_2d_list_to_length(tool_output_masks, 1,\n                                         max_length=self.config.response_length).to(idx.device).int()\n        execution_passes = execution_passes.to(idx.device).int()\n        if self.config.n > 1 and do_sample:\n            idx = _repeat_interleave(idx, self.config.n)\n            attention_mask = _repeat_interleave(attention_mask, self.config.n)\n            position_ids = _repeat_interleave(position_ids, self.config.n)\n            batch_size = batch_size * self.config.n\n            if 'multi_modal_inputs' in non_tensor_batch.keys():\n                non_tensor_batch['multi_modal_inputs'] = _repeat_interleave(non_tensor_batch['multi_modal_inputs'],\n                                                                            self.config.n)\n\n        seq = torch.cat([idx, response], dim=-1)\n\n        response_length = response.size(1)\n        delta_position_id = torch.arange(1, response_length + 1, device=position_ids.device)\n        delta_position_id = delta_position_id.unsqueeze(0).expand(batch_size, -1)\n        if position_ids.dim() == 3:  # qwen2vl mrope\n            delta_position_id = delta_position_id.view(batch_size, 1, -1).expand(batch_size, 3, -1)\n\n        # TODO(sgm): fix position_ids on right_pad\n        # prompt: left pad + response: right pad\n        # attention_mask: [0,0,0,0,1,1,1,1, | 1,1,1,0,0,0,0,0]\n        # position_ids:   [0,0,0,0,0,1,2,3, | 4,5,6,7,8,9,10,11]\n        response_position_ids = position_ids[:, -1:] + delta_position_id\n        position_ids = torch.cat([position_ids, response_position_ids], dim=-1)\n        response_attention_mask = get_eos_mask(response_id=response, eos_token=eos_token_id, dtype=attention_mask.dtype)\n        # response_attention_mask = response_attention_mask & tool_output_masks\n        attention_mask = torch.cat((attention_mask, response_attention_mask), dim=-1)\n\n        # all the tp ranks should contain the same data here. data in all ranks are valid\n        batch = TensorDict(\n            {\n                'prompts': idx,\n                'responses': response,\n                'input_ids': seq,  # here input_ids become the whole sentences\n                # 'old_log_probs': log_probs, # we will recompute old log prob with actor\n                'attention_mask': attention_mask,\n                'tool_output_masks': tool_output_masks,\n                'position_ids': position_ids,\n                'execution_passes': execution_passes,            \n            },\n            batch_size=batch_size)\n\n        # free vllm cache engine\n        if vllm_version in ('0.3.1', '0.4.2', '0.5.4', '0.6.3') and self.config.free_cache_engine:\n            self.inference_engine.free_cache_engine()\n\n        return DataProto(batch=batch, non_tensor_batch=non_tensor_batch)\n"
  },
  {
    "path": "verl/workers/sharding_manager/__init__.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom verl.utils.import_utils import is_vllm_available, is_megatron_core_available\n\nfrom .base import BaseShardingManager\nfrom .fsdp_ulysses import FSDPUlyssesShardingManager\n\nAllGatherPPModel = None\n\nif is_megatron_core_available() and is_vllm_available():\n    from .megatron_vllm import AllGatherPPModel, MegatronVLLMShardingManager\nelif AllGatherPPModel is not None:\n    pass\nelse:\n    AllGatherPPModel = None\n    MegatronVLLMShardingManager = None\n\nif is_vllm_available():\n    from .fsdp_vllm import FSDPVLLMShardingManager\nelse:\n    FSDPVLLMShardingManager = None\n"
  },
  {
    "path": "verl/workers/sharding_manager/base.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nSharding manager to implement HybridEngine\n\"\"\"\n\nfrom verl import DataProto\n\n\nclass BaseShardingManager:\n\n    def __enter__(self):\n        pass\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        pass\n\n    def preprocess_data(self, data: DataProto) -> DataProto:\n        return data\n\n    def postprocess_data(self, data: DataProto) -> DataProto:\n        return data\n"
  },
  {
    "path": "verl/workers/sharding_manager/fsdp_ulysses.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nContains a resharding manager that binds weights from FSDP zero3 to XPerfGPT\n\"\"\"\nfrom .base import BaseShardingManager\n\nfrom torch.distributed.device_mesh import DeviceMesh\n\nfrom verl.utils.torch_functional import allgather_dict_tensors\nfrom verl.utils.ulysses import set_ulysses_sequence_parallel_group, get_ulysses_sequence_parallel_group\nimport numpy as np\n\nimport torch\nimport torch.distributed\n\nfrom verl import DataProto\n\n\nclass FSDPUlyssesShardingManager(BaseShardingManager):\n    \"\"\"\n    Sharding manager to support data resharding when using FSDP + Ulysses\n    \"\"\"\n\n    def __init__(self, device_mesh: DeviceMesh):\n        super().__init__()\n        self.device_mesh = device_mesh\n        self.seed_offset = 12345\n\n    def __enter__(self):\n        if self.device_mesh is not None:\n            # We have a global SP group\n            # so we have to change to use model-specific sp group\n            self.prev_sp_group = get_ulysses_sequence_parallel_group()\n            set_ulysses_sequence_parallel_group(self.device_mesh['sp'].get_group())\n            # TODO: check how to set seed for each model\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        # restore random states\n        if self.device_mesh is not None:\n            # revert to previous sp group\n            set_ulysses_sequence_parallel_group(self.prev_sp_group)\n            # TODO: check how to set seed for each model\n\n    def preprocess_data(self, data: DataProto) -> DataProto:\n        \"\"\"\n        AllGather data from sp region\n        This is because the data is first sharded along the FSDP dimension as we utilize the DP_COMPUTE\n        In Ulysses, we need to make sure the same data is used across a SP group\n        \"\"\"\n        if self.device_mesh is not None:\n            sp_size = self.device_mesh['sp'].size()\n            group = self.device_mesh['sp'].get_group()\n\n            prev_device = data.batch.device\n            data.batch = data.batch.cuda(device=torch.cuda.current_device())\n            data.batch = allgather_dict_tensors(data.batch.contiguous(), size=sp_size, group=group, dim=0)\n            data.batch = data.batch.to(prev_device)\n            # all gather non_tensor_batch\n            all_non_tensor_batch = [None for _ in range(sp_size)]\n            torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=group)\n            data.non_tensor_batch = {\n                k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch\n            }\n        return data\n\n    def postprocess_data(self, data: DataProto) -> DataProto:\n        \"\"\"\n        Split the data to follow FSDP partition\n        \"\"\"\n        if self.device_mesh is not None:\n            sp_size = self.device_mesh['sp'].size()\n            sp_rank = self.device_mesh['sp'].get_local_rank()\n            data = data.chunk(chunks=sp_size)[sp_rank]\n        return data"
  },
  {
    "path": "verl/workers/sharding_manager/fsdp_vllm.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport logging\nimport torch\nimport numpy as np\nfrom torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP\nfrom torch.distributed.fsdp.api import ShardingStrategy, ShardedStateDictConfig, StateDictType, FullStateDictConfig\nfrom torch.distributed.device_mesh import DeviceMesh\n\nfrom verl.third_party.vllm import LLM\nfrom verl.third_party.vllm import parallel_state as vllm_ps\nfrom verl import DataProto\nfrom verl.utils.torch_functional import (broadcast_dict_tensor, allgather_dict_tensors)\nfrom verl.utils.debug import log_gpu_memory_usage\nfrom verl.third_party.vllm import vllm_version\n\nfrom .base import BaseShardingManager\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv('VERL_PPO_LOGGING_LEVEL', 'WARN'))\n\n\nclass FSDPVLLMShardingManager(BaseShardingManager):\n\n    def __init__(self,\n                 module: FSDP,\n                 inference_engine: LLM,\n                 model_config,\n                 full_params: bool = False,\n                 device_mesh: DeviceMesh = None):\n        self.module = module\n        self.inference_engine = inference_engine\n        self.model_config = model_config\n        self.device_mesh = device_mesh\n\n        # Full params\n        self.full_params = full_params\n        if full_params:\n            FSDP.set_state_dict_type(self.module,\n                                     state_dict_type=StateDictType.FULL_STATE_DICT,\n                                     state_dict_config=FullStateDictConfig())\n        else:\n            FSDP.set_state_dict_type(self.module,\n                                     state_dict_type=StateDictType.SHARDED_STATE_DICT,\n                                     state_dict_config=ShardedStateDictConfig())\n\n        # Note that torch_random_states may be different on each dp rank\n        self.torch_random_states = torch.cuda.get_rng_state()\n        # get a random rng states\n        if self.device_mesh is not None:\n            gen_dp_rank = self.device_mesh['dp'].get_local_rank()\n            torch.cuda.manual_seed(gen_dp_rank + 1000)  # make sure all tp ranks have the same random states\n            self.gen_random_states = torch.cuda.get_rng_state()\n            torch.cuda.set_rng_state(self.torch_random_states)\n        else:\n            self.gen_random_states = None\n\n    def __enter__(self):\n        log_gpu_memory_usage('Before state_dict() in sharding manager memory', logger=logger)\n        params = self.module.state_dict()\n        log_gpu_memory_usage('After state_dict() in sharding manager memory', logger=logger)\n        # Copy, not share memory\n        load_format = 'hf' if self.full_params else 'dtensor'\n        if vllm_version in ('0.4.2', '0.5.4', '0.6.3'):\n            self.inference_engine.sync_model_weights(params, load_format=load_format)\n        else:\n            self.inference_engine.wake_up()\n            # TODO(ZSL): deal with 'hf' format\n            if load_format == 'dtensor':\n                from verl.third_party.vllm import load_dtensor_weights\n                load_dtensor_weights(\n                    params, self.inference_engine.llm_engine.model_executor.driver_worker.worker.model_runner.model)\n            else:\n                raise NotImplementedError(f'load_format {load_format} not implemented')\n        log_gpu_memory_usage('After sync model weights in sharding manager', logger=logger)\n\n        del params\n        torch.cuda.empty_cache()\n        log_gpu_memory_usage('After del state_dict and empty_cache in sharding manager', logger=logger)\n\n        # TODO: offload FSDP model weights\n        # self.module.cpu()\n        # torch.cuda.empty_cache()\n        # if torch.distributed.get_rank() == 0:\n        # print(f'after model to cpu in sharding manager memory allocated: {torch.cuda.memory_allocated() / 1e9}GB, reserved: {torch.cuda.memory_reserved() / 1e9}GB')\n\n        # important: need to manually set the random states of each tp to be identical.\n        if self.device_mesh is not None:\n            self.torch_random_states = torch.cuda.get_rng_state()\n            torch.cuda.set_rng_state(self.gen_random_states)\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        log_gpu_memory_usage('Before vllm offload in sharding manager', logger=logger)\n        # TODO(ZSL): check this\n        if vllm_version in ('0.4.2', '0.5.4', '0.6.3'):\n            self.inference_engine.offload_model_weights()\n        else:\n            self.inference_engine.sleep(level=1)\n        log_gpu_memory_usage('After vllm offload in sharding manager', logger=logger)\n\n        # self.module.to('cuda')\n        # if torch.distributed.get_rank() == 0:\n        #     print(f'after actor module to cuda in sharding manager memory allocated: {torch.cuda.memory_allocated() / 1e9}GB, reserved: {torch.cuda.memory_reserved() / 1e9}GB')\n\n        self.module.train()\n\n        # add empty cache after each compute\n        torch.cuda.empty_cache()\n\n        # restore random states\n        if self.device_mesh is not None:\n            self.gen_random_states = torch.cuda.get_rng_state()\n            torch.cuda.set_rng_state(self.torch_random_states)\n\n    def preprocess_data(self, data: DataProto) -> DataProto:\n        # TODO: Current impl doesn't consider FSDP with torch micro-dp\n        tp_size = vllm_ps.get_tensor_model_parallel_world_size()\n        if vllm_version in ('0.3.1', '0.4.2', '0.5.4', '0.6.3'):\n            group = vllm_ps.get_tensor_model_parallel_group()\n        else:\n            group = vllm_ps.get_tensor_model_parallel_group().device_group\n\n        prev_device = data.batch.device\n        data.batch = data.batch.cuda(device=torch.cuda.current_device())\n        data.batch = allgather_dict_tensors(data.batch.contiguous(), size=tp_size, group=group, dim=0)\n        data.batch = data.batch.to(prev_device)\n        # all gather non_tensor_batch\n        all_non_tensor_batch = [None for _ in range(tp_size)]\n        torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=group)\n        data.non_tensor_batch = {k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch}\n        return data\n\n    def postprocess_data(self, data: DataProto) -> DataProto:\n        # TODO: Current impl doesn't consider FSDP with torch micro-dp\n        local_world_size = vllm_ps.get_tensor_model_parallel_world_size()\n        src_rank = (torch.distributed.get_rank() // local_world_size) * local_world_size\n        if vllm_version in ('0.3.1', '0.4.2', '0.5.4', '0.6.3'):\n            broadcast_dict_tensor(data.batch, src=src_rank, group=vllm_ps.get_tensor_model_parallel_group())\n        else:\n            broadcast_dict_tensor(data.batch,\n                                  src=src_rank,\n                                  group=vllm_ps.get_tensor_model_parallel_group().device_group)\n        dp_rank = torch.distributed.get_rank()\n        dp_size = torch.distributed.get_world_size()  # not consider torch micro-dp\n        tp_size = vllm_ps.get_tensor_model_parallel_world_size()\n        if tp_size > 1:\n            # TODO: shall we build a micro_dp group for vllm when integrating with vLLM?\n            local_prompts = data.chunk(chunks=tp_size)\n            data = local_prompts[dp_rank % tp_size]\n        return data\n"
  },
  {
    "path": "verl/workers/sharding_manager/megatron_vllm.py",
    "content": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThis file contains a Megatron style Hybrid Engine that shares the weights of the actor with the inference engine.\n\"\"\"\n\nimport importlib\nfrom packaging.version import Version\nimport torch\nimport torch.distributed as dist\n\nfrom torch import nn\n\nfrom megatron.core import parallel_state as mpu\nfrom megatron.core import DistributedDataParallel as LocalDDP\nfrom megatron.core.transformer.module import Float16Module\nfrom torch.nn.parallel.distributed import DistributedDataParallel as torchDDP\nfrom verl.utils.megatron_utils import get_model, unwrap_model\nfrom verl.utils.memory_buffer import (\n    build_memory_buffer,\n    build_memory_reference_from_module,\n    get_weight_buffer_meta_from_module,\n)\n\n\nclass AllGatherPPModel:\n\n    def __init__(self, model_provider) -> None:\n\n        self._pp_group = mpu.get_pipeline_model_parallel_group()\n        self._pp_rank = mpu.get_pipeline_model_parallel_rank()\n        self._pp_size = mpu.get_pipeline_model_parallel_world_size()\n        self._vpp_size = mpu.get_virtual_pipeline_model_parallel_world_size()\n        self._model_chunk_size = self._vpp_size or 1\n\n        # each one holds a list of model_chunks in this pp stage\n        self._pp_models = [None] * self.pp_size\n\n        rank_list = list(range(self.pp_size))\n        # make current rank the last one to initialize\n        rank_list[self.pp_rank], rank_list[-1] = rank_list[-1], rank_list[self.pp_rank]\n        self._this_rank_models = None\n\n        # store the parameter of each pp stage\n        self.memory_buffers = [None] * self.pp_size\n        for cur_pp_rank in rank_list:\n            print(\n                f'create pp model', f'torch allocated {torch.cuda.memory_allocated() / 1e9:.4f} GB, '\n                f'reserved {torch.cuda.memory_reserved() / 1e9:.4f} GB')\n            # since the last initialized rank is the current pp rank, after init, the pp rank is still correct\n            mpu.set_pipeline_model_parallel_rank(cur_pp_rank)\n            if cur_pp_rank != self.pp_rank:\n                models = get_model(model_provider, wrap_with_ddp=False)\n                models = nn.ModuleList(models)\n                assert len(models) == self._model_chunk_size, f\"{len(models)} != {self._model_chunk_size}\"\n                self.pp_models[cur_pp_rank] = models\n            else:\n                # for regular model, we wrapped it with DDP\n                models = get_model(model_provider)\n                assert len(models) == self._model_chunk_size, f\"{len(models)} != {self._model_chunk_size}\"\n                self._this_rank_models = nn.ModuleList(models)\n                self.pp_models[cur_pp_rank] = nn.ModuleList(unwrap_model(models, (torchDDP, LocalDDP)))\n\n            self._build_param_buffer(cur_pp_rank)\n            self._build_param_references(cur_pp_rank, maintain_weight=cur_pp_rank == self.pp_rank)\n\n            # TODO: after binding to the memory buffer, we can load the checkpoint here\n            if cur_pp_rank != self.pp_rank:\n                for model in self.pp_models[cur_pp_rank]:\n                    model.eval()\n                self._offload_params_to_cpu(cur_pp_rank)\n\n    def _build_param_buffer(self, pp_rank):\n        \"\"\"Build the parameter buffer in each pp rank\"\"\"\n        if pp_rank == self._pp_rank:\n            from verl.utils.memory_buffer import MemoryBuffer\n            # The code here is very hard-coded, based on the following assumptions:\n            # 1. `len(_this_rank_models) == 1`\n            # 2. `_this_rank_models[0]` is a instance of `DistributedDataParallel` and `use_distributed_optimizer=True`\n            # 3. Only bfloat16 data type is used in parameters\n            source = self._this_rank_models[0].buffers[0].param_data\n            self.memory_buffers[pp_rank] = {\n                torch.bfloat16: MemoryBuffer(source.numel(), source.numel(), torch.bfloat16, source)\n            }\n        else:\n            model = self.pp_models[pp_rank]\n            weight_buffer_meta = get_weight_buffer_meta_from_module(model)\n            self.memory_buffers[pp_rank] = build_memory_buffer(weight_buffer_meta)\n\n    def _build_param_references(self, pp_rank, maintain_weight=False):\n        if pp_rank == self._pp_rank:\n            return\n        model = self.pp_models[pp_rank]\n        build_memory_reference_from_module(model, self.memory_buffers[pp_rank], maintain_weight=maintain_weight)\n\n    def _load_params_to_cuda(self, pp_rank, to_empty=False):\n        assert pp_rank != self.pp_rank, f\"unexpected to load current pp rank [{pp_rank}] back to cuda\"\n        for buffer in self.memory_buffers[pp_rank].values():\n            if not to_empty:\n                buffer.data = buffer.data.to(torch.cuda.current_device(), non_blocking=True)\n            else:\n                buffer.data = torch.empty_like(buffer.data, device='cuda')\n        # rebuild reference after loading to CUDA\n        self._build_param_references(pp_rank)\n\n    def _offload_params_to_cpu(self, pp_rank, to_empty=False):\n        assert pp_rank != self.pp_rank, f\"unexpected to offload current pp rank [{pp_rank}] to cpu\"\n        for buffer in self.memory_buffers[pp_rank].values():\n            if not to_empty:\n                # offload the whole memory buffer to CPU\n                buffer.data = buffer.data.to('cpu', non_blocking=True)\n            else:\n                buffer.data = torch.empty_like(buffer.data, device='cpu')\n        self._build_param_references(pp_rank)\n\n    def load_params_to_cuda(self, to_empty=False):\n        \"\"\"load all model params to cuda\"\"\"\n        for cur_pp_rank in range(self.pp_size):\n            if cur_pp_rank != self.pp_rank:\n                self._load_params_to_cuda(cur_pp_rank, to_empty=to_empty)\n\n    def allgather_params(self):\n        \"\"\"allgather params of all pp ranks. Return a list of handles\"\"\"\n        for cur_pp_rank in range(self.pp_size):\n            global_src = dist.get_global_rank(group=self.pp_group, group_rank=cur_pp_rank)\n\n            # NOTE(sgm): the async op may cause memory leakage of the memory_buffer/pp_models\n\n            for _, param in sorted(self.pp_models[cur_pp_rank].named_parameters()):\n                dist.broadcast(tensor=param.data, src=global_src, group=self.pp_group, async_op=False)\n\n    def forward(self, *inputs, **kwargs):\n        try:\n            prev_output = None\n            for cur_chunk_rank in range(self._model_chunk_size):\n                if self._vpp_size:\n                    mpu.set_virtual_pipeline_model_parallel_rank(cur_chunk_rank)\n\n                for cur_pp_rank in range(self.pp_size):\n                    mpu.set_pipeline_model_parallel_rank(cur_pp_rank)\n                    self.pp_models[cur_pp_rank][cur_chunk_rank].set_input_tensor(prev_output)\n                    ret = self.pp_models[cur_pp_rank][cur_chunk_rank](*inputs, **kwargs)\n                    self.pp_models[cur_pp_rank][cur_chunk_rank].set_input_tensor(None)\n                    prev_output = ret\n        finally:\n            if self._vpp_size:\n                mpu.set_virtual_pipeline_model_parallel_rank(0)\n            mpu.set_pipeline_model_parallel_rank(self.pp_rank)\n        return ret\n\n    def __call__(self, *inputs, **kwargs):\n        return self.forward(*inputs, **kwargs)\n\n    def eval(self):\n        for model in self.pp_models[self.pp_rank]:\n            model.eval()\n\n    def train(self):\n        for model in self.pp_models[self.pp_rank]:\n            model.train()\n\n    def offload_params_to_cpu(self, to_empty=False):\n        \"\"\"offload params of models that are not of current pp rank to cpu\"\"\"\n        for cur_pp_rank in range(self.pp_size):\n            if cur_pp_rank != self.pp_rank:\n                self._offload_params_to_cpu(cur_pp_rank, to_empty=to_empty)\n\n    def get_all_params(self):\n        \"\"\"Get all the parameters of the models in all pp ranks\n\n        Returns:\n            params: List[List[Dict[str, Tensor]]]: a list of parameters in all pp, where each is a list of dict\n                tensors of each model chunk\n\n        \"\"\"\n        params = []\n        for pp_rank in range(self.pp_size):\n            params.append([])\n            for model_chunk_idx in range(len(self.pp_models[pp_rank])):\n                params[pp_rank].append({})\n                pp_model = self.pp_models[pp_rank][model_chunk_idx]\n                pp_model = unwrap_model(pp_model, ((torchDDP, LocalDDP, Float16Module)))  # not use Float16Module\n                for name, param in pp_model.named_parameters():\n                    # NOTE(gh) workaround: should not get lora params for inference\n                    if 'lora' in name:\n                        continue\n                    params[pp_rank][model_chunk_idx][name] = param\n\n        return params\n\n    def update_this_rank_models(self, new_models):\n        self._this_rank_models = new_models\n        self._pp_models[self.pp_rank] = unwrap_model(new_models, (torchDDP, LocalDDP))\n\n    @property\n    def this_rank_models(self):\n        return self._this_rank_models\n\n    @property\n    def pp_size(self):\n        return self._pp_size\n\n    @property\n    def pp_rank(self):\n        return self._pp_rank\n\n    @property\n    def pp_group(self):\n        return self._pp_group\n\n    @property\n    def pp_models(self):\n        return self._pp_models\n\n\n\"\"\"\nMegatron Hybrid Engine:\n- During training, only the current pp stage holds the parameters\n- Before inference, broadcast the parameters of the current pp rank to all other pp ranks (all pp ranks holds all the parameters)\n- Bind the parameters to the inference engine\n- Do inference in tp. pp is treated as additional dp\n- After inference, all the parameters that doesn't belong to this pp rank is freed.\n\"\"\"\n\nfrom .base import BaseShardingManager\n\nimport torch\nfrom torch import nn\nimport torch.distributed\nfrom torch.distributed import new_group\n\nfrom verl import DataProto\nfrom verl.utils.torch_functional import (broadcast_dict_tensor, allgather_dict_tensors)\nimport verl.utils.megatron.tensor_parallel as tp_utils\nfrom verl.third_party.vllm import parallel_state as vllm_ps\nfrom verl.third_party.vllm import LLM\nfrom verl.utils.model import normalize_pp_vpp_params\n# Micro Data parallel group. Micro data parallel group is additional dp group that origins from splitting training tp\n# into infer_tp and micro_tp. By default, we use order micro_dp - tp\n_MICRO_DATA_PARALLEL_GROUP = None\n\n\nclass MegatronVLLMShardingManager(BaseShardingManager):\n\n    def __init__(self, module: AllGatherPPModel, inference_engine: LLM, model_config, layer_name_mapping):\n        self.module = module\n        self.inference_engine = inference_engine\n        self.model_config = model_config\n        self.layer_name_mapping = layer_name_mapping\n\n        # initialize micro_dp group for vllm inference\n        global _MICRO_DATA_PARALLEL_GROUP\n        world_size = torch.distributed.get_world_size()\n        rank = torch.distributed.get_rank()\n        train_tensor_parallel_size = mpu.get_tensor_model_parallel_world_size()\n        infer_tensor_parallel_size = vllm_ps.get_tensor_model_parallel_world_size()\n\n        # TODO(sgm): this may not be true for FSDP -> vLLM\n        assert infer_tensor_parallel_size <= train_tensor_parallel_size, \\\n            'Not implemented for infer_tp > train_tp'\n        assert train_tensor_parallel_size % infer_tensor_parallel_size == 0\n\n        micro_dp_size = train_tensor_parallel_size // infer_tensor_parallel_size\n        num_micro_dp_groups = world_size // micro_dp_size\n        assert _MICRO_DATA_PARALLEL_GROUP is None, (\"micro data parallel group is already initialized\")\n        for i in range(num_micro_dp_groups):\n            ranks = range(i * micro_dp_size, (i + 1) * micro_dp_size)\n            group = new_group(ranks=ranks)\n            if rank in ranks:\n                _MICRO_DATA_PARALLEL_GROUP = group\n\n    def default_tp_concat_fn(self, name, param, infer_params, model_config):\n        \"\"\"\n        name: name of the parameter\n        param: training parameters\n        infer_params (List[torch.Tensor]): a list of parameters all-gathered from micro_dp_group\n        model_config: huggingface model_config\n        TODO(zhangchi.usc1992): currently, the implementation is adhoc. We can move this function to the model\n        definition so that it is model-agnostic. If the model doesn't implement this function, \n        we can throw an error to force user disable TP HybridEngine.\n        \"\"\"\n\n        if self.layer_name_mapping.get(\"qkv_layer_name\") in name:\n            # if the tensor is qkv, for each param on tp, split into q, k, v\n            # concat q, k, v separately.\n            q_lst = []\n            k_lst = []\n            v_lst = []\n            assert model_config.num_attention_heads % model_config.num_key_value_heads == 0\n            num_q_per_kv = model_config.num_attention_heads // model_config.num_key_value_heads\n            assert infer_params[0].shape[0] % (num_q_per_kv + 2) == 0\n            kv_size_per_tp = infer_params[0].shape[0] // (num_q_per_kv + 2)\n            split_size = [kv_size_per_tp * num_q_per_kv, kv_size_per_tp, kv_size_per_tp]\n            for infer_param in infer_params:\n                q, k, v = infer_param.split(split_size)\n                q_lst.append(q)\n                k_lst.append(k)\n                v_lst.append(v)\n            q = torch.cat(q_lst, dim=0)\n            k = torch.cat(k_lst, dim=0)\n            v = torch.cat(v_lst, dim=0)\n\n            infer_params = torch.cat((q, k, v), dim=0)\n\n        elif self.layer_name_mapping.get(\"gate_proj_layer_name\") in name:\n            # if the tensor is gate and proj\n            gate_lst = []\n            up_lst = []\n            for infer_param in infer_params:\n                gate, up = infer_param.chunk(2)\n                gate_lst.append(gate)\n                up_lst.append(up)\n            gate = torch.cat(gate_lst, dim=0)\n            up = torch.cat(up_lst, dim=0)\n            infer_params = torch.cat((gate, up), dim=0)\n\n        else:\n            # concat tensor\n            infer_params = torch.cat(infer_params, dim=tp_utils.get_tensor_parallel_partition_dim(param))\n\n        return infer_params\n\n    def _post_process_params(self, params):\n        \"\"\"\n        For each param, if it is a tp-splited param, we all-gather from micro_dp group.\n        \"\"\"\n        # here the params are in train tp format. we iterate params and all-gather\n        # TODO(zhangchi.usc1992) We can consider copy non-tp weight to another infer buffer.\n        # In this way, all the params in the original memory_buffers and can be offload.\n        micro_dp_size = get_micro_data_parallel_world_size()\n        micro_dp_group = get_micro_data_parallel_group()\n\n        if micro_dp_size <= 1:\n            return\n\n        origin_params = {}\n        for name in params.keys():\n            param = params[name]\n            if tp_utils.is_tensor_parallel_param(param):\n                # allocate a new tensor with proper size\n                infer_params = [torch.empty_like(param) for _ in range(micro_dp_size)]\n                torch.distributed.all_gather(infer_params, param, group=micro_dp_group)\n                infer_params = self.default_tp_concat_fn(name, param, infer_params, self.model_config)\n                # replace with original param\n                params[name] = infer_params\n            origin_params[name] = param\n\n        return origin_params\n\n    def __enter__(self):\n        # create a new cuda space for parameters not in this pp rank\n        self.module.load_params_to_cuda()\n        # broadcast the parameters from pp rank to other ranks\n        self.module.allgather_params()\n        # obtain name to parameters in pp/vpp\n        params = self.module.get_all_params()\n\n        # bind the params to inference engine\n        self.params = normalize_pp_vpp_params(params=params,\n                                              num_hidden_layers=self.model_config.num_hidden_layers,\n                                              layer_name='layers')\n        self.origin_params = self._post_process_params(self.params)\n        self.inference_engine.sync_model_weights(self.params, load_format='megatron')\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        # offload parameters doesn't belong to this pp rank\n        self.module.offload_params_to_cpu()\n\n        # FIXME(sgm): the best practice is to delete the cuda tensor\n        # rebind the model weights, can be any cpu tensor\n        if get_micro_data_parallel_world_size() > 1:\n            for name in self.params.keys():\n                self.params[name] = self.origin_params[name]\n\n        # self.inference_engine.sync_model_weights(params)\n        self.inference_engine.offload_model_weights()\n\n        self.module.train()\n\n        # add empty cache after each compute\n        torch.cuda.empty_cache()\n\n    def preprocess_data(self, data: DataProto) -> DataProto:\n        # prompts are identical for each training tp. We select for each inference tp\n        micro_dp_size = get_micro_data_parallel_world_size()\n        micro_dp_rank = get_micro_data_parallel_rank()\n\n        # broadcast from tp=0 to other tp ranks\n        broadcast_dict_tensor(data.batch,\n                              src=mpu.get_tensor_model_parallel_src_rank(),\n                              group=mpu.get_tensor_model_parallel_group())\n\n        if micro_dp_size > 1:\n            local_prompts = data.chunk(chunks=micro_dp_size)\n            data = local_prompts[micro_dp_rank]\n\n        return data\n\n    def postprocess_data(self, data: DataProto) -> DataProto:\n        meta_info = data.meta_info\n        # all gather batch among micro-dp groups\n        micro_dp_size = get_micro_data_parallel_world_size()\n        if micro_dp_size > 1:\n            data.batch = allgather_dict_tensors(data.batch.contiguous(),\n                                                size=get_micro_data_parallel_world_size(),\n                                                group=get_micro_data_parallel_group(),\n                                                dim=0)\n\n        # all gather batch among pp group\n        if meta_info.get('allgather_pp_output', True):\n            data.batch = allgather_dict_tensors(data.batch.contiguous(),\n                                                size=mpu.get_pipeline_model_parallel_world_size(),\n                                                group=mpu.get_pipeline_model_parallel_group(),\n                                                dim=0)\n        return data\n\n\n\"\"\"\nMicro Data parallel group\n\"\"\"\n\n\ndef get_micro_data_parallel_group():\n    assert _MICRO_DATA_PARALLEL_GROUP is not None\n    return _MICRO_DATA_PARALLEL_GROUP\n\n\ndef get_micro_data_parallel_world_size():\n    return torch.distributed.get_world_size(group=get_micro_data_parallel_group())\n\n\ndef get_micro_data_parallel_rank():\n    return torch.distributed.get_rank(group=get_micro_data_parallel_group())\n"
  }
]